[llvm] 9550cd7 - [IR] Remove IRBuilder AddMetadataToInst (#202280)

via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 23 01:03:00 PDT 2026


Author: Alexis Engelke
Date: 2026-06-23T10:02:55+02:00
New Revision: 9550cd76cadea9f25a5c0bf3ee06e9f7ce5631ed

URL: https://github.com/llvm/llvm-project/commit/9550cd76cadea9f25a5c0bf3ee06e9f7ce5631ed
DIFF: https://github.com/llvm/llvm-project/commit/9550cd76cadea9f25a5c0bf3ee06e9f7ce5631ed.diff

LOG: [IR] Remove IRBuilder AddMetadataToInst (#202280)

This avoids an extra check for metadata on every instruction insertion,
makes constructing an IRBuilder cheaper, and therefore slightly improves
performance.

As the C API doesn't expose CollectMetadataToCopy or any other way to
add additional metadata to the IRBuilder, make LLVMAddMetadataToInst an
alias for LLVMSetInstDebugLocation and undeprecate the latter.

Added: 
    

Modified: 
    llvm/include/llvm-c/Core.h
    llvm/include/llvm/IR/IRBuilder.h
    llvm/lib/CodeGen/AtomicExpandPass.cpp
    llvm/lib/IR/Core.cpp
    llvm/lib/Target/X86/X86ISelLowering.cpp
    llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
    llvm/lib/Transforms/Utils/SimplifyCFG.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm-c/Core.h b/llvm/include/llvm-c/Core.h
index 86f636c636783..f3b98a31c5bd7 100644
--- a/llvm/include/llvm-c/Core.h
+++ b/llvm/include/llvm-c/Core.h
@@ -4643,18 +4643,17 @@ LLVM_C_ABI void LLVMSetCurrentDebugLocation2(LLVMBuilderRef Builder,
  * current debug location for the given builder.  If the builder has no current
  * debug location, this function is a no-op.
  *
- * @deprecated LLVMSetInstDebugLocation is deprecated in favor of the more general
- *             LLVMAddMetadataToInst.
- *
  * @see llvm::IRBuilder::SetInstDebugLocation()
  */
 LLVM_C_ABI void LLVMSetInstDebugLocation(LLVMBuilderRef Builder,
                                          LLVMValueRef Inst);
 
 /**
- * Adds the metadata registered with the given builder to the given instruction.
+ * Same as LLVMSetInstDebugLocation.
+ *
+ * @deprecated Use the identical LLVMSetInstDebugLocation.
  *
- * @see llvm::IRBuilder::AddMetadataToInst()
+ * @see llvm::IRBuilder::SetInstDebugLocation()
  */
 LLVM_C_ABI void LLVMAddMetadataToInst(LLVMBuilderRef Builder,
                                       LLVMValueRef Inst);

diff  --git a/llvm/include/llvm/IR/IRBuilder.h b/llvm/include/llvm/IR/IRBuilder.h
index 400c3723e5d1c..692990f93c6fb 100644
--- a/llvm/include/llvm/IR/IRBuilder.h
+++ b/llvm/include/llvm/IR/IRBuilder.h
@@ -112,36 +112,10 @@ class FMFSource {
 
 /// Common base class shared among various IRBuilders.
 class IRBuilderBase {
-  /// Pairs of (metadata kind, MDNode *) that should be added to all newly
-  /// created instructions, excluding !dbg metadata, which is stored in the
-  /// StoredDL field.
-  SmallVector<std::pair<unsigned, MDNode *>, 2> MetadataToCopy;
   /// The DebugLoc that will be applied to instructions inserted by this
   /// builder.
   DebugLoc StoredDL;
 
-  /// Add or update the an entry (Kind, MD) to MetadataToCopy, if \p MD is not
-  /// null. If \p MD is null, remove the entry with \p Kind.
-  void AddOrRemoveMetadataToCopy(unsigned Kind, MDNode *MD) {
-    assert(Kind != LLVMContext::MD_dbg &&
-           "MD_dbg metadata must be stored in StoredDL");
-
-    if (!MD) {
-      erase_if(MetadataToCopy, [Kind](const std::pair<unsigned, MDNode *> &KV) {
-        return KV.first == Kind;
-      });
-      return;
-    }
-
-    for (auto &KV : MetadataToCopy)
-      if (KV.first == Kind) {
-        KV.second = MD;
-        return;
-      }
-
-    MetadataToCopy.emplace_back(Kind, MD);
-  }
-
 protected:
   BasicBlock *BB;
   BasicBlock::iterator InsertPt;
@@ -171,7 +145,7 @@ class IRBuilderBase {
   template<typename InstTy>
   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
     Inserter.InsertHelper(I, Name, InsertPt);
-    AddMetadataToInst(I);
+    SetInstDebugLocation(I);
     return I;
   }
 
@@ -257,25 +231,6 @@ class IRBuilderBase {
     StoredDL = std::move(L);
   }
 
-  /// Set nosanitize metadata.
-  void SetNoSanitizeMetadata() {
-    AddOrRemoveMetadataToCopy(llvm::LLVMContext::MD_nosanitize,
-                              llvm::MDNode::get(getContext(), {}));
-  }
-
-  /// Collect metadata with IDs \p MetadataKinds from \p Src which should be
-  /// added to all created instructions. Entries present in MedataDataToCopy but
-  /// not on \p Src will be dropped from MetadataToCopy.
-  void CollectMetadataToCopy(Instruction *Src,
-                             ArrayRef<unsigned> MetadataKinds) {
-    for (unsigned K : MetadataKinds) {
-      if (K == LLVMContext::MD_dbg)
-        SetCurrentDebugLocation(Src->getDebugLoc());
-      else
-        AddOrRemoveMetadataToCopy(K, Src->getMetadata(K));
-    }
-  }
-
   /// Get location information used by debugging information.
   LLVM_ABI DebugLoc getCurrentDebugLocation() const;
 
@@ -283,13 +238,6 @@ class IRBuilderBase {
   /// specified instruction.
   LLVM_ABI void SetInstDebugLocation(Instruction *I) const;
 
-  /// Add all entries in MetadataToCopy to \p I.
-  void AddMetadataToInst(Instruction *I) const {
-    for (const auto &KV : MetadataToCopy)
-      I->setMetadata(KV.first, KV.second);
-    SetInstDebugLocation(I);
-  }
-
   /// Get the return type of the current function that we're emitting
   /// into.
   LLVM_ABI Type *getCurrentFunctionReturnType() const;

diff  --git a/llvm/lib/CodeGen/AtomicExpandPass.cpp b/llvm/lib/CodeGen/AtomicExpandPass.cpp
index db048e0c5ab5c..059c0d5cb7b8b 100644
--- a/llvm/lib/CodeGen/AtomicExpandPass.cpp
+++ b/llvm/lib/CodeGen/AtomicExpandPass.cpp
@@ -174,24 +174,26 @@ class AtomicExpandLegacy : public FunctionPass {
 struct ReplacementIRBuilder
     : IRBuilder<InstSimplifyFolder, IRBuilderCallbackInserter> {
   MDNode *MMRAMD = nullptr;
+  MDNode *PCSectionsMD = nullptr;
 
   // Preserves the DebugLoc from I, and preserves still valid metadata.
   // Enable StrictFP builder mode when appropriate.
   explicit ReplacementIRBuilder(Instruction *I, const DataLayout &DL)
-      : IRBuilder(I->getContext(), InstSimplifyFolder(DL),
-                  IRBuilderCallbackInserter(
-                      [this](Instruction *I) { addMMRAMD(I); })) {
+      : IRBuilder(
+            I->getContext(), InstSimplifyFolder(DL),
+            IRBuilderCallbackInserter([this](Instruction *I) { addMD(I); })) {
     SetInsertPoint(I);
-    this->CollectMetadataToCopy(I, {LLVMContext::MD_pcsections});
     if (BB->getParent()->getAttributes().hasFnAttr(Attribute::StrictFP))
       this->setIsFPConstrained(true);
 
     MMRAMD = I->getMetadata(LLVMContext::MD_mmra);
+    PCSectionsMD = I->getMetadata(LLVMContext::MD_pcsections);
   }
 
-  void addMMRAMD(Instruction *I) {
+  void addMD(Instruction *I) {
     if (canInstructionHaveMMRAs(*I))
       I->setMetadata(LLVMContext::MD_mmra, MMRAMD);
+    I->setMetadata(LLVMContext::MD_pcsections, PCSectionsMD);
   }
 };
 

diff  --git a/llvm/lib/IR/Core.cpp b/llvm/lib/IR/Core.cpp
index e64341aa0d1d7..6c6c3b5c84ede 100644
--- a/llvm/lib/IR/Core.cpp
+++ b/llvm/lib/IR/Core.cpp
@@ -3508,7 +3508,7 @@ void LLVMSetInstDebugLocation(LLVMBuilderRef Builder, LLVMValueRef Inst) {
 }
 
 void LLVMAddMetadataToInst(LLVMBuilderRef Builder, LLVMValueRef Inst) {
-  unwrap(Builder)->AddMetadataToInst(unwrap<Instruction>(Inst));
+  unwrap(Builder)->SetInstDebugLocation(unwrap<Instruction>(Inst));
 }
 
 void LLVMBuilderSetDefaultFPMathTag(LLVMBuilderRef Builder,

diff  --git a/llvm/lib/Target/X86/X86ISelLowering.cpp b/llvm/lib/Target/X86/X86ISelLowering.cpp
index 7e9e82ae49f9e..291124bb485cb 100644
--- a/llvm/lib/Target/X86/X86ISelLowering.cpp
+++ b/llvm/lib/Target/X86/X86ISelLowering.cpp
@@ -32803,8 +32803,12 @@ X86TargetLowering::shouldExpandLogicAtomicRMWInIR(
 }
 
 void X86TargetLowering::emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const {
-  IRBuilder<> Builder(AI);
-  Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
+  LLVMContext &Ctx = AI->getContext();
+  IRBuilder<ConstantFolder, IRBuilderCallbackInserter> Builder(
+      Ctx, ConstantFolder{}, IRBuilderCallbackInserter([&AI](Instruction *I) {
+        I->copyMetadata(*AI, LLVMContext::MD_pcsections);
+      }));
+  Builder.SetInsertPoint(AI);
   Intrinsic::ID IID_C = Intrinsic::not_intrinsic;
   Intrinsic::ID IID_I = Intrinsic::not_intrinsic;
   switch (AI->getOperation()) {
@@ -32824,7 +32828,6 @@ void X86TargetLowering::emitBitTestAtomicRMWIntrinsic(AtomicRMWInst *AI) const {
     break;
   }
   Instruction *I = AI->user_back();
-  LLVMContext &Ctx = AI->getContext();
   Value *Addr = Builder.CreatePointerCast(AI->getPointerOperand(),
                                           PointerType::getUnqual(Ctx));
   Value *Result = nullptr;
@@ -33047,10 +33050,13 @@ static bool shouldExpandCmpArithRMWInIR(const AtomicRMWInst *AI) {
 
 void X86TargetLowering::emitCmpArithAtomicRMWIntrinsic(
     AtomicRMWInst *AI) const {
-  IRBuilder<> Builder(AI);
-  Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
-  Instruction *TempI = nullptr;
   LLVMContext &Ctx = AI->getContext();
+  IRBuilder<ConstantFolder, IRBuilderCallbackInserter> Builder(
+      Ctx, ConstantFolder{}, IRBuilderCallbackInserter([&AI](Instruction *I) {
+        I->copyMetadata(*AI, LLVMContext::MD_pcsections);
+      }));
+  Builder.SetInsertPoint(AI);
+  Instruction *TempI = nullptr;
   ICmpInst *ICI = dyn_cast<ICmpInst>(AI->user_back());
   if (!ICI) {
     TempI = AI->user_back();
@@ -33159,8 +33165,12 @@ X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
         AI->use_empty())
       return nullptr;
 
-  IRBuilder<> Builder(AI);
-  Builder.CollectMetadataToCopy(AI, {LLVMContext::MD_pcsections});
+  IRBuilder<ConstantFolder, IRBuilderCallbackInserter> Builder(
+      AI->getContext(), ConstantFolder{},
+      IRBuilderCallbackInserter([&AI](Instruction *I) {
+        I->copyMetadata(*AI, LLVMContext::MD_pcsections);
+      }));
+  Builder.SetInsertPoint(AI);
   auto SSID = AI->getSyncScopeID();
   // We must restrict the ordering to avoid generating loads with Release or
   // ReleaseAcquire orderings.

diff  --git a/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp b/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
index 0506a9b44589b..58bc18b379048 100644
--- a/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
+++ b/llvm/lib/Transforms/Instrumentation/BoundsChecking.cpp
@@ -41,14 +41,23 @@ STATISTIC(ChecksAdded, "Bounds checks added");
 STATISTIC(ChecksSkipped, "Bounds checks skipped");
 STATISTIC(ChecksUnable, "Bounds checks unable to add");
 
-class BuilderTy : public IRBuilder<TargetFolder> {
+class NoSanitizeInserter final : public IRBuilderDefaultInserter {
+  mutable MDNode *NoSanitizeMD = nullptr;
+
 public:
-  BuilderTy(BasicBlock *TheBB, BasicBlock::iterator IP, TargetFolder Folder)
-      : IRBuilder<TargetFolder>(TheBB, IP, Folder) {
-    SetNoSanitizeMetadata();
+  NoSanitizeInserter() = default;
+
+  void InsertHelper(Instruction *I, const Twine &Name,
+                    BasicBlock::iterator InsertPt) const override {
+    IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
+    if (!NoSanitizeMD)
+      NoSanitizeMD = MDNode::get(I->getContext(), {});
+    I->setMetadata(LLVMContext::MD_nosanitize, NoSanitizeMD);
   }
 };
 
+using BuilderTy = IRBuilder<TargetFolder, NoSanitizeInserter>;
+
 /// Gets the conditions under which memory accessing instructions will overflow.
 ///
 /// \p Ptr is the pointer that will be read/written, and \p InstVal is either

diff  --git a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
index b1478b7d10b8f..1e9c66c5a660c 100644
--- a/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
+++ b/llvm/lib/Transforms/Utils/SimplifyCFG.cpp
@@ -4024,12 +4024,15 @@ static bool performBranchToCommonDestFolding(CondBrInst *BI, CondBrInst *PBI,
 
   LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
 
-  IRBuilder<> Builder(PBI);
-  // The builder is used to create instructions to eliminate the branch in BB.
-  // If BB's terminator has !annotation metadata, add it to the new
-  // instructions.
-  Builder.CollectMetadataToCopy(BB->getTerminator(),
-                                {LLVMContext::MD_annotation});
+  IRBuilder<ConstantFolder, IRBuilderCallbackInserter> Builder(
+      BB->getContext(), ConstantFolder{},
+      IRBuilderCallbackInserter([&BB](Instruction *I) {
+        // The builder is used to create instructions to eliminate the branch in
+        // BB. If BB's terminator has !annotation metadata, add it to the new
+        // instructions.
+        I->copyMetadata(*BB->getTerminator(), LLVMContext::MD_annotation);
+      }));
+  Builder.SetInsertPoint(PBI);
 
   // If we need to invert the condition in the pred block to match, do so now.
   if (InvertPredCond) {


        


More information about the llvm-commits mailing list