1 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the IRBuilder class, which is used as a convenient way
11 // to create LLVM instructions with a consistent and simplified interface.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_IR_IRBUILDER_H
16 #define LLVM_IR_IRBUILDER_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/ConstantFolder.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/InstrTypes.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/IR/ValueHandle.h"
40 #include "llvm/Support/AtomicOrdering.h"
41 #include "llvm/Support/CBindingWrapping.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm-c/Types.h"
57 /// \brief This provides the default implementation of the IRBuilder
58 /// 'InsertHelper' method that is called whenever an instruction is created by
59 /// IRBuilder and needs to be inserted.
61 /// By default, this inserts the instruction at the insertion point.
62 class IRBuilderDefaultInserter {
64 void InsertHelper(Instruction *I, const Twine &Name,
65 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
66 if (BB) BB->getInstList().insert(InsertPt, I);
71 /// Provides an 'InsertHelper' that calls a user-provided callback after
72 /// performing the default insertion.
73 class IRBuilderCallbackInserter : IRBuilderDefaultInserter {
74 std::function<void(Instruction *)> Callback;
77 IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
78 : Callback(Callback) {}
81 void InsertHelper(Instruction *I, const Twine &Name,
82 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
83 IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
88 /// \brief Common base class shared among various IRBuilders.
90 DebugLoc CurDbgLocation;
94 BasicBlock::iterator InsertPt;
97 MDNode *DefaultFPMathTag;
100 ArrayRef<OperandBundleDef> DefaultOperandBundles;
103 IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr,
104 ArrayRef<OperandBundleDef> OpBundles = None)
105 : Context(context), DefaultFPMathTag(FPMathTag),
106 DefaultOperandBundles(OpBundles) {
107 ClearInsertionPoint();
110 //===--------------------------------------------------------------------===//
111 // Builder configuration methods
112 //===--------------------------------------------------------------------===//
114 /// \brief Clear the insertion point: created instructions will not be
115 /// inserted into a block.
116 void ClearInsertionPoint() {
118 InsertPt = BasicBlock::iterator();
121 BasicBlock *GetInsertBlock() const { return BB; }
122 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
123 LLVMContext &getContext() const { return Context; }
125 /// \brief This specifies that created instructions should be appended to the
126 /// end of the specified block.
127 void SetInsertPoint(BasicBlock *TheBB) {
129 InsertPt = BB->end();
132 /// \brief This specifies that created instructions should be inserted before
133 /// the specified instruction.
134 void SetInsertPoint(Instruction *I) {
136 InsertPt = I->getIterator();
137 assert(InsertPt != BB->end() && "Can't read debug loc from end()");
138 SetCurrentDebugLocation(I->getDebugLoc());
141 /// \brief This specifies that created instructions should be inserted at the
143 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
146 if (IP != TheBB->end())
147 SetCurrentDebugLocation(IP->getDebugLoc());
150 /// \brief Set location information used by debugging information.
151 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
153 /// \brief Get location information used by debugging information.
154 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
156 /// \brief If this builder has a current debug location, set it on the
157 /// specified instruction.
158 void SetInstDebugLocation(Instruction *I) const {
160 I->setDebugLoc(CurDbgLocation);
163 /// \brief Get the return type of the current function that we're emitting
165 Type *getCurrentFunctionReturnType() const;
167 /// InsertPoint - A saved insertion point.
169 BasicBlock *Block = nullptr;
170 BasicBlock::iterator Point;
173 /// \brief Creates a new insertion point which doesn't point to anything.
174 InsertPoint() = default;
176 /// \brief Creates a new insertion point at the given location.
177 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
178 : Block(InsertBlock), Point(InsertPoint) {}
180 /// \brief Returns true if this insert point is set.
181 bool isSet() const { return (Block != nullptr); }
183 BasicBlock *getBlock() const { return Block; }
184 BasicBlock::iterator getPoint() const { return Point; }
187 /// \brief Returns the current insert point.
188 InsertPoint saveIP() const {
189 return InsertPoint(GetInsertBlock(), GetInsertPoint());
192 /// \brief Returns the current insert point, clearing it in the process.
193 InsertPoint saveAndClearIP() {
194 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
195 ClearInsertionPoint();
199 /// \brief Sets the current insert point to a previously-saved location.
200 void restoreIP(InsertPoint IP) {
202 SetInsertPoint(IP.getBlock(), IP.getPoint());
204 ClearInsertionPoint();
207 /// \brief Get the floating point math metadata being used.
208 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
210 /// \brief Get the flags to be applied to created floating point ops
211 FastMathFlags getFastMathFlags() const { return FMF; }
213 /// \brief Clear the fast-math flags.
214 void clearFastMathFlags() { FMF.clear(); }
216 /// \brief Set the floating point math metadata to be used.
217 void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
219 /// \brief Set the fast-math flags to be used with generated fp-math operators
220 void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
222 //===--------------------------------------------------------------------===//
224 //===--------------------------------------------------------------------===//
226 // \brief RAII object that stores the current insertion point and restores it
227 // when the object is destroyed. This includes the debug location.
228 class InsertPointGuard {
229 IRBuilderBase &Builder;
230 AssertingVH<BasicBlock> Block;
231 BasicBlock::iterator Point;
235 InsertPointGuard(IRBuilderBase &B)
236 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
237 DbgLoc(B.getCurrentDebugLocation()) {}
239 InsertPointGuard(const InsertPointGuard &) = delete;
240 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
242 ~InsertPointGuard() {
243 Builder.restoreIP(InsertPoint(Block, Point));
244 Builder.SetCurrentDebugLocation(DbgLoc);
248 // \brief RAII object that stores the current fast math settings and restores
249 // them when the object is destroyed.
250 class FastMathFlagGuard {
251 IRBuilderBase &Builder;
256 FastMathFlagGuard(IRBuilderBase &B)
257 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
259 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
260 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
262 ~FastMathFlagGuard() {
264 Builder.DefaultFPMathTag = FPMathTag;
268 //===--------------------------------------------------------------------===//
269 // Miscellaneous creation methods.
270 //===--------------------------------------------------------------------===//
272 /// \brief Make a new global variable with initializer type i8*
274 /// Make a new global variable with an initializer that has array of i8 type
275 /// filled in with the null terminated string value specified. The new global
276 /// variable will be marked mergable with any others of the same contents. If
277 /// Name is specified, it is the name of the global variable created.
278 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
279 unsigned AddressSpace = 0);
281 /// \brief Get a constant value representing either true or false.
282 ConstantInt *getInt1(bool V) {
283 return ConstantInt::get(getInt1Ty(), V);
286 /// \brief Get the constant value for i1 true.
287 ConstantInt *getTrue() {
288 return ConstantInt::getTrue(Context);
291 /// \brief Get the constant value for i1 false.
292 ConstantInt *getFalse() {
293 return ConstantInt::getFalse(Context);
296 /// \brief Get a constant 8-bit value.
297 ConstantInt *getInt8(uint8_t C) {
298 return ConstantInt::get(getInt8Ty(), C);
301 /// \brief Get a constant 16-bit value.
302 ConstantInt *getInt16(uint16_t C) {
303 return ConstantInt::get(getInt16Ty(), C);
306 /// \brief Get a constant 32-bit value.
307 ConstantInt *getInt32(uint32_t C) {
308 return ConstantInt::get(getInt32Ty(), C);
311 /// \brief Get a constant 64-bit value.
312 ConstantInt *getInt64(uint64_t C) {
313 return ConstantInt::get(getInt64Ty(), C);
316 /// \brief Get a constant N-bit value, zero extended or truncated from
318 ConstantInt *getIntN(unsigned N, uint64_t C) {
319 return ConstantInt::get(getIntNTy(N), C);
322 /// \brief Get a constant integer value.
323 ConstantInt *getInt(const APInt &AI) {
324 return ConstantInt::get(Context, AI);
327 //===--------------------------------------------------------------------===//
328 // Type creation methods
329 //===--------------------------------------------------------------------===//
331 /// \brief Fetch the type representing a single bit
332 IntegerType *getInt1Ty() {
333 return Type::getInt1Ty(Context);
336 /// \brief Fetch the type representing an 8-bit integer.
337 IntegerType *getInt8Ty() {
338 return Type::getInt8Ty(Context);
341 /// \brief Fetch the type representing a 16-bit integer.
342 IntegerType *getInt16Ty() {
343 return Type::getInt16Ty(Context);
346 /// \brief Fetch the type representing a 32-bit integer.
347 IntegerType *getInt32Ty() {
348 return Type::getInt32Ty(Context);
351 /// \brief Fetch the type representing a 64-bit integer.
352 IntegerType *getInt64Ty() {
353 return Type::getInt64Ty(Context);
356 /// \brief Fetch the type representing a 128-bit integer.
357 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
359 /// \brief Fetch the type representing an N-bit integer.
360 IntegerType *getIntNTy(unsigned N) {
361 return Type::getIntNTy(Context, N);
364 /// \brief Fetch the type representing a 16-bit floating point value.
366 return Type::getHalfTy(Context);
369 /// \brief Fetch the type representing a 32-bit floating point value.
371 return Type::getFloatTy(Context);
374 /// \brief Fetch the type representing a 64-bit floating point value.
375 Type *getDoubleTy() {
376 return Type::getDoubleTy(Context);
379 /// \brief Fetch the type representing void.
381 return Type::getVoidTy(Context);
384 /// \brief Fetch the type representing a pointer to an 8-bit integer value.
385 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
386 return Type::getInt8PtrTy(Context, AddrSpace);
389 /// \brief Fetch the type representing a pointer to an integer value.
390 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
391 return DL.getIntPtrType(Context, AddrSpace);
394 //===--------------------------------------------------------------------===//
395 // Intrinsic creation methods
396 //===--------------------------------------------------------------------===//
398 /// \brief Create and insert a memset to the specified pointer and the
401 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
402 /// specified, it will be added to the instruction. Likewise with alias.scope
403 /// and noalias tags.
404 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
405 bool isVolatile = false, MDNode *TBAATag = nullptr,
406 MDNode *ScopeTag = nullptr,
407 MDNode *NoAliasTag = nullptr) {
408 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
409 TBAATag, ScopeTag, NoAliasTag);
412 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
413 bool isVolatile = false, MDNode *TBAATag = nullptr,
414 MDNode *ScopeTag = nullptr,
415 MDNode *NoAliasTag = nullptr);
417 /// \brief Create and insert a memcpy between the specified pointers.
419 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
420 /// specified, it will be added to the instruction. Likewise with alias.scope
421 /// and noalias tags.
422 CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
423 bool isVolatile = false, MDNode *TBAATag = nullptr,
424 MDNode *TBAAStructTag = nullptr,
425 MDNode *ScopeTag = nullptr,
426 MDNode *NoAliasTag = nullptr) {
427 return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
428 TBAAStructTag, ScopeTag, NoAliasTag);
431 CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
432 bool isVolatile = false, MDNode *TBAATag = nullptr,
433 MDNode *TBAAStructTag = nullptr,
434 MDNode *ScopeTag = nullptr,
435 MDNode *NoAliasTag = nullptr);
437 /// \brief Create and insert a memmove between the specified
440 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
441 /// specified, it will be added to the instruction. Likewise with alias.scope
442 /// and noalias tags.
443 CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
444 bool isVolatile = false, MDNode *TBAATag = nullptr,
445 MDNode *ScopeTag = nullptr,
446 MDNode *NoAliasTag = nullptr) {
447 return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
448 TBAATag, ScopeTag, NoAliasTag);
451 CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
452 bool isVolatile = false, MDNode *TBAATag = nullptr,
453 MDNode *ScopeTag = nullptr,
454 MDNode *NoAliasTag = nullptr);
456 /// \brief Create a lifetime.start intrinsic.
458 /// If the pointer isn't i8* it will be converted.
459 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
461 /// \brief Create a lifetime.end intrinsic.
463 /// If the pointer isn't i8* it will be converted.
464 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
466 /// Create a call to invariant.start intrinsic.
468 /// If the pointer isn't i8* it will be converted.
469 CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
471 /// \brief Create a call to Masked Load intrinsic
472 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
473 Value *PassThru = nullptr, const Twine &Name = "");
475 /// \brief Create a call to Masked Store intrinsic
476 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
479 /// \brief Create a call to Masked Gather intrinsic
480 CallInst *CreateMaskedGather(Value *Ptrs, unsigned Align,
481 Value *Mask = nullptr,
482 Value *PassThru = nullptr,
483 const Twine& Name = "");
485 /// \brief Create a call to Masked Scatter intrinsic
486 CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Align,
487 Value *Mask = nullptr);
489 /// \brief Create an assume intrinsic call that allows the optimizer to
490 /// assume that the provided condition will be true.
491 CallInst *CreateAssumption(Value *Cond);
493 /// \brief Create a call to the experimental.gc.statepoint intrinsic to
494 /// start a new statepoint sequence.
495 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
497 ArrayRef<Value *> CallArgs,
498 ArrayRef<Value *> DeoptArgs,
499 ArrayRef<Value *> GCArgs,
500 const Twine &Name = "");
502 /// \brief Create a call to the experimental.gc.statepoint intrinsic to
503 /// start a new statepoint sequence.
504 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
505 Value *ActualCallee, uint32_t Flags,
506 ArrayRef<Use> CallArgs,
507 ArrayRef<Use> TransitionArgs,
508 ArrayRef<Use> DeoptArgs,
509 ArrayRef<Value *> GCArgs,
510 const Twine &Name = "");
512 // \brief Conveninence function for the common case when CallArgs are filled
513 // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
514 // .get()'ed to get the Value pointer.
515 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
516 Value *ActualCallee, ArrayRef<Use> CallArgs,
517 ArrayRef<Value *> DeoptArgs,
518 ArrayRef<Value *> GCArgs,
519 const Twine &Name = "");
521 /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
522 /// start a new statepoint sequence.
524 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
525 Value *ActualInvokee, BasicBlock *NormalDest,
526 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
527 ArrayRef<Value *> DeoptArgs,
528 ArrayRef<Value *> GCArgs, const Twine &Name = "");
530 /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
531 /// start a new statepoint sequence.
532 InvokeInst *CreateGCStatepointInvoke(
533 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
534 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
535 ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
536 ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
537 const Twine &Name = "");
539 // Conveninence function for the common case when CallArgs are filled in using
540 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
543 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
544 Value *ActualInvokee, BasicBlock *NormalDest,
545 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
546 ArrayRef<Value *> DeoptArgs,
547 ArrayRef<Value *> GCArgs, const Twine &Name = "");
549 /// \brief Create a call to the experimental.gc.result intrinsic to extract
550 /// the result from a call wrapped in a statepoint.
551 CallInst *CreateGCResult(Instruction *Statepoint,
553 const Twine &Name = "");
555 /// \brief Create a call to the experimental.gc.relocate intrinsics to
556 /// project the relocated value of one pointer from the statepoint.
557 CallInst *CreateGCRelocate(Instruction *Statepoint,
561 const Twine &Name = "");
564 /// \brief Create a call to a masked intrinsic with given Id.
565 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
566 ArrayRef<Type *> OverloadedTypes,
567 const Twine &Name = "");
569 Value *getCastedInt8PtrValue(Value *Ptr);
572 /// \brief This provides a uniform API for creating instructions and inserting
573 /// them into a basic block: either at the end of a BasicBlock, or at a specific
574 /// iterator location in a block.
576 /// Note that the builder does not expose the full generality of LLVM
577 /// instructions. For access to extra instruction properties, use the mutators
578 /// (e.g. setVolatile) on the instructions after they have been
579 /// created. Convenience state exists to specify fast-math flags and fp-math
582 /// The first template argument specifies a class to use for creating constants.
583 /// This defaults to creating minimally folded constants. The second template
584 /// argument allows clients to specify custom insertion hooks that are called on
585 /// every newly created insertion.
586 template <typename T = ConstantFolder,
587 typename Inserter = IRBuilderDefaultInserter>
588 class IRBuilder : public IRBuilderBase, public Inserter {
592 IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
593 MDNode *FPMathTag = nullptr,
594 ArrayRef<OperandBundleDef> OpBundles = None)
595 : IRBuilderBase(C, FPMathTag, OpBundles), Inserter(std::move(I)),
598 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
599 ArrayRef<OperandBundleDef> OpBundles = None)
600 : IRBuilderBase(C, FPMathTag, OpBundles), Folder() {}
602 explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr,
603 ArrayRef<OperandBundleDef> OpBundles = None)
604 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
605 SetInsertPoint(TheBB);
608 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
609 ArrayRef<OperandBundleDef> OpBundles = None)
610 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder() {
611 SetInsertPoint(TheBB);
614 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
615 ArrayRef<OperandBundleDef> OpBundles = None)
616 : IRBuilderBase(IP->getContext(), FPMathTag, OpBundles), Folder() {
620 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T &F,
621 MDNode *FPMathTag = nullptr,
622 ArrayRef<OperandBundleDef> OpBundles = None)
623 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
624 SetInsertPoint(TheBB, IP);
627 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
628 MDNode *FPMathTag = nullptr,
629 ArrayRef<OperandBundleDef> OpBundles = None)
630 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder() {
631 SetInsertPoint(TheBB, IP);
634 /// \brief Get the constant folder being used.
635 const T &getFolder() { return Folder; }
637 /// \brief Insert and return the specified instruction.
638 template<typename InstTy>
639 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
640 this->InsertHelper(I, Name, BB, InsertPt);
641 this->SetInstDebugLocation(I);
645 /// \brief No-op overload to handle constants.
646 Constant *Insert(Constant *C, const Twine& = "") const {
650 //===--------------------------------------------------------------------===//
651 // Instruction creation methods: Terminators
652 //===--------------------------------------------------------------------===//
655 /// \brief Helper to add branch weight and unpredictable metadata onto an
657 /// \returns The annotated instruction.
658 template <typename InstTy>
659 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
661 I->setMetadata(LLVMContext::MD_prof, Weights);
663 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
668 /// \brief Create a 'ret void' instruction.
669 ReturnInst *CreateRetVoid() {
670 return Insert(ReturnInst::Create(Context));
673 /// \brief Create a 'ret <val>' instruction.
674 ReturnInst *CreateRet(Value *V) {
675 return Insert(ReturnInst::Create(Context, V));
678 /// \brief Create a sequence of N insertvalue instructions,
679 /// with one Value from the retVals array each, that build a aggregate
680 /// return value one value at a time, and a ret instruction to return
681 /// the resulting aggregate value.
683 /// This is a convenience function for code that uses aggregate return values
684 /// as a vehicle for having multiple return values.
685 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
686 Value *V = UndefValue::get(getCurrentFunctionReturnType());
687 for (unsigned i = 0; i != N; ++i)
688 V = CreateInsertValue(V, retVals[i], i, "mrv");
689 return Insert(ReturnInst::Create(Context, V));
692 /// \brief Create an unconditional 'br label X' instruction.
693 BranchInst *CreateBr(BasicBlock *Dest) {
694 return Insert(BranchInst::Create(Dest));
697 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
699 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
700 MDNode *BranchWeights = nullptr,
701 MDNode *Unpredictable = nullptr) {
702 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
703 BranchWeights, Unpredictable));
706 /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
707 /// instruction. Copy branch meta data if available.
708 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
709 Instruction *MDSrc) {
710 BranchInst *Br = BranchInst::Create(True, False, Cond);
712 unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
713 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
714 Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
719 /// \brief Create a switch instruction with the specified value, default dest,
720 /// and with a hint for the number of cases that will be added (for efficient
722 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
723 MDNode *BranchWeights = nullptr,
724 MDNode *Unpredictable = nullptr) {
725 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
726 BranchWeights, Unpredictable));
729 /// \brief Create an indirect branch instruction with the specified address
730 /// operand, with an optional hint for the number of destinations that will be
731 /// added (for efficient allocation).
732 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
733 return Insert(IndirectBrInst::Create(Addr, NumDests));
736 /// \brief Create an invoke instruction.
737 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
738 BasicBlock *UnwindDest,
739 ArrayRef<Value *> Args = None,
740 const Twine &Name = "") {
741 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
744 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
745 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
746 ArrayRef<OperandBundleDef> OpBundles,
747 const Twine &Name = "") {
748 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args,
752 ResumeInst *CreateResume(Value *Exn) {
753 return Insert(ResumeInst::Create(Exn));
756 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
757 BasicBlock *UnwindBB = nullptr) {
758 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
761 CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
762 unsigned NumHandlers,
763 const Twine &Name = "") {
764 return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
768 CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
769 const Twine &Name = "") {
770 return Insert(CatchPadInst::Create(ParentPad, Args), Name);
773 CleanupPadInst *CreateCleanupPad(Value *ParentPad,
774 ArrayRef<Value *> Args = None,
775 const Twine &Name = "") {
776 return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
779 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
780 return Insert(CatchReturnInst::Create(CatchPad, BB));
783 UnreachableInst *CreateUnreachable() {
784 return Insert(new UnreachableInst(Context));
787 //===--------------------------------------------------------------------===//
788 // Instruction creation methods: Binary Operators
789 //===--------------------------------------------------------------------===//
791 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
792 Value *LHS, Value *RHS,
794 bool HasNUW, bool HasNSW) {
795 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
796 if (HasNUW) BO->setHasNoUnsignedWrap();
797 if (HasNSW) BO->setHasNoSignedWrap();
801 Instruction *AddFPMathAttributes(Instruction *I,
803 FastMathFlags FMF) const {
805 FPMathTag = DefaultFPMathTag;
807 I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
808 I->setFastMathFlags(FMF);
813 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
814 bool HasNUW = false, bool HasNSW = false) {
815 if (Constant *LC = dyn_cast<Constant>(LHS))
816 if (Constant *RC = dyn_cast<Constant>(RHS))
817 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
818 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
821 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
822 return CreateAdd(LHS, RHS, Name, false, true);
824 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
825 return CreateAdd(LHS, RHS, Name, true, false);
827 Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
828 MDNode *FPMathTag = nullptr) {
829 if (Constant *LC = dyn_cast<Constant>(LHS))
830 if (Constant *RC = dyn_cast<Constant>(RHS))
831 return Insert(Folder.CreateFAdd(LC, RC), Name);
832 return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
833 FPMathTag, FMF), Name);
835 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
836 bool HasNUW = false, bool HasNSW = false) {
837 if (Constant *LC = dyn_cast<Constant>(LHS))
838 if (Constant *RC = dyn_cast<Constant>(RHS))
839 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
840 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
843 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
844 return CreateSub(LHS, RHS, Name, false, true);
846 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
847 return CreateSub(LHS, RHS, Name, true, false);
849 Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
850 MDNode *FPMathTag = nullptr) {
851 if (Constant *LC = dyn_cast<Constant>(LHS))
852 if (Constant *RC = dyn_cast<Constant>(RHS))
853 return Insert(Folder.CreateFSub(LC, RC), Name);
854 return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
855 FPMathTag, FMF), Name);
857 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
858 bool HasNUW = false, bool HasNSW = false) {
859 if (Constant *LC = dyn_cast<Constant>(LHS))
860 if (Constant *RC = dyn_cast<Constant>(RHS))
861 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
862 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
865 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
866 return CreateMul(LHS, RHS, Name, false, true);
868 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
869 return CreateMul(LHS, RHS, Name, true, false);
871 Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
872 MDNode *FPMathTag = nullptr) {
873 if (Constant *LC = dyn_cast<Constant>(LHS))
874 if (Constant *RC = dyn_cast<Constant>(RHS))
875 return Insert(Folder.CreateFMul(LC, RC), Name);
876 return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
877 FPMathTag, FMF), Name);
879 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
880 bool isExact = false) {
881 if (Constant *LC = dyn_cast<Constant>(LHS))
882 if (Constant *RC = dyn_cast<Constant>(RHS))
883 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
885 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
886 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
888 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
889 return CreateUDiv(LHS, RHS, Name, true);
891 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
892 bool isExact = false) {
893 if (Constant *LC = dyn_cast<Constant>(LHS))
894 if (Constant *RC = dyn_cast<Constant>(RHS))
895 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
897 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
898 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
900 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
901 return CreateSDiv(LHS, RHS, Name, true);
903 Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
904 MDNode *FPMathTag = nullptr) {
905 if (Constant *LC = dyn_cast<Constant>(LHS))
906 if (Constant *RC = dyn_cast<Constant>(RHS))
907 return Insert(Folder.CreateFDiv(LC, RC), Name);
908 return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
909 FPMathTag, FMF), Name);
911 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
912 if (Constant *LC = dyn_cast<Constant>(LHS))
913 if (Constant *RC = dyn_cast<Constant>(RHS))
914 return Insert(Folder.CreateURem(LC, RC), Name);
915 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
917 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
918 if (Constant *LC = dyn_cast<Constant>(LHS))
919 if (Constant *RC = dyn_cast<Constant>(RHS))
920 return Insert(Folder.CreateSRem(LC, RC), Name);
921 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
923 Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
924 MDNode *FPMathTag = nullptr) {
925 if (Constant *LC = dyn_cast<Constant>(LHS))
926 if (Constant *RC = dyn_cast<Constant>(RHS))
927 return Insert(Folder.CreateFRem(LC, RC), Name);
928 return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
929 FPMathTag, FMF), Name);
932 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
933 bool HasNUW = false, bool HasNSW = false) {
934 if (Constant *LC = dyn_cast<Constant>(LHS))
935 if (Constant *RC = dyn_cast<Constant>(RHS))
936 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
937 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
940 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
941 bool HasNUW = false, bool HasNSW = false) {
942 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
945 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
946 bool HasNUW = false, bool HasNSW = false) {
947 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
951 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
952 bool isExact = false) {
953 if (Constant *LC = dyn_cast<Constant>(LHS))
954 if (Constant *RC = dyn_cast<Constant>(RHS))
955 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
957 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
958 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
960 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
961 bool isExact = false) {
962 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
964 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
965 bool isExact = false) {
966 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
969 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
970 bool isExact = false) {
971 if (Constant *LC = dyn_cast<Constant>(LHS))
972 if (Constant *RC = dyn_cast<Constant>(RHS))
973 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
975 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
976 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
978 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
979 bool isExact = false) {
980 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
982 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
983 bool isExact = false) {
984 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
987 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
988 if (Constant *RC = dyn_cast<Constant>(RHS)) {
989 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
990 return LHS; // LHS & -1 -> LHS
991 if (Constant *LC = dyn_cast<Constant>(LHS))
992 return Insert(Folder.CreateAnd(LC, RC), Name);
994 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
996 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
997 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
999 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1000 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1003 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
1004 if (Constant *RC = dyn_cast<Constant>(RHS)) {
1005 if (RC->isNullValue())
1006 return LHS; // LHS | 0 -> LHS
1007 if (Constant *LC = dyn_cast<Constant>(LHS))
1008 return Insert(Folder.CreateOr(LC, RC), Name);
1010 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
1012 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1013 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1015 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1016 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1019 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
1020 if (Constant *LC = dyn_cast<Constant>(LHS))
1021 if (Constant *RC = dyn_cast<Constant>(RHS))
1022 return Insert(Folder.CreateXor(LC, RC), Name);
1023 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
1025 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1026 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1028 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1029 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1032 Value *CreateBinOp(Instruction::BinaryOps Opc,
1033 Value *LHS, Value *RHS, const Twine &Name = "",
1034 MDNode *FPMathTag = nullptr) {
1035 if (Constant *LC = dyn_cast<Constant>(LHS))
1036 if (Constant *RC = dyn_cast<Constant>(RHS))
1037 return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
1038 Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
1039 if (isa<FPMathOperator>(BinOp))
1040 BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
1041 return Insert(BinOp, Name);
1044 Value *CreateNeg(Value *V, const Twine &Name = "",
1045 bool HasNUW = false, bool HasNSW = false) {
1046 if (Constant *VC = dyn_cast<Constant>(V))
1047 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
1048 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
1049 if (HasNUW) BO->setHasNoUnsignedWrap();
1050 if (HasNSW) BO->setHasNoSignedWrap();
1053 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1054 return CreateNeg(V, Name, false, true);
1056 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1057 return CreateNeg(V, Name, true, false);
1059 Value *CreateFNeg(Value *V, const Twine &Name = "",
1060 MDNode *FPMathTag = nullptr) {
1061 if (Constant *VC = dyn_cast<Constant>(V))
1062 return Insert(Folder.CreateFNeg(VC), Name);
1063 return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
1064 FPMathTag, FMF), Name);
1066 Value *CreateNot(Value *V, const Twine &Name = "") {
1067 if (Constant *VC = dyn_cast<Constant>(V))
1068 return Insert(Folder.CreateNot(VC), Name);
1069 return Insert(BinaryOperator::CreateNot(V), Name);
1072 //===--------------------------------------------------------------------===//
1073 // Instruction creation methods: Memory Instructions
1074 //===--------------------------------------------------------------------===//
1076 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1077 const Twine &Name = "") {
1078 return Insert(new AllocaInst(Ty, ArraySize), Name);
1080 // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
1081 // converting the string to 'bool' for the isVolatile parameter.
1082 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1083 return Insert(new LoadInst(Ptr), Name);
1085 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1086 return Insert(new LoadInst(Ptr), Name);
1088 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1089 return Insert(new LoadInst(Ty, Ptr), Name);
1091 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1092 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1094 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1095 return Insert(new StoreInst(Val, Ptr, isVolatile));
1097 // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1098 // correctly, instead of converting the string to 'bool' for the isVolatile
1100 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1101 LoadInst *LI = CreateLoad(Ptr, Name);
1102 LI->setAlignment(Align);
1105 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1106 const Twine &Name = "") {
1107 LoadInst *LI = CreateLoad(Ptr, Name);
1108 LI->setAlignment(Align);
1111 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1112 const Twine &Name = "") {
1113 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1114 LI->setAlignment(Align);
1117 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1118 bool isVolatile = false) {
1119 StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1120 SI->setAlignment(Align);
1123 FenceInst *CreateFence(AtomicOrdering Ordering,
1124 SynchronizationScope SynchScope = CrossThread,
1125 const Twine &Name = "") {
1126 return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1129 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1130 AtomicOrdering SuccessOrdering,
1131 AtomicOrdering FailureOrdering,
1132 SynchronizationScope SynchScope = CrossThread) {
1133 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1134 FailureOrdering, SynchScope));
1136 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1137 AtomicOrdering Ordering,
1138 SynchronizationScope SynchScope = CrossThread) {
1139 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1141 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1142 const Twine &Name = "") {
1143 return CreateGEP(nullptr, Ptr, IdxList, Name);
1145 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1146 const Twine &Name = "") {
1147 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1148 // Every index must be constant.
1150 for (i = 0, e = IdxList.size(); i != e; ++i)
1151 if (!isa<Constant>(IdxList[i]))
1154 return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1156 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1158 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1159 const Twine &Name = "") {
1160 return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1162 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1163 const Twine &Name = "") {
1164 if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1165 // Every index must be constant.
1167 for (i = 0, e = IdxList.size(); i != e; ++i)
1168 if (!isa<Constant>(IdxList[i]))
1171 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1174 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1176 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1177 return CreateGEP(nullptr, Ptr, Idx, Name);
1179 Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1180 if (Constant *PC = dyn_cast<Constant>(Ptr))
1181 if (Constant *IC = dyn_cast<Constant>(Idx))
1182 return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1183 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1185 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1186 const Twine &Name = "") {
1187 if (Constant *PC = dyn_cast<Constant>(Ptr))
1188 if (Constant *IC = dyn_cast<Constant>(Idx))
1189 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1190 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1192 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1193 return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1195 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1196 const Twine &Name = "") {
1197 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1199 if (Constant *PC = dyn_cast<Constant>(Ptr))
1200 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1202 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1204 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1205 const Twine &Name = "") {
1206 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1208 if (Constant *PC = dyn_cast<Constant>(Ptr))
1209 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1211 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1213 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1214 const Twine &Name = "") {
1216 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1217 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1220 if (Constant *PC = dyn_cast<Constant>(Ptr))
1221 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1223 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1225 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1226 unsigned Idx1, const Twine &Name = "") {
1228 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1229 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1232 if (Constant *PC = dyn_cast<Constant>(Ptr))
1233 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1235 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1237 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1238 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1240 if (Constant *PC = dyn_cast<Constant>(Ptr))
1241 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1243 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1245 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1246 const Twine &Name = "") {
1247 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1249 if (Constant *PC = dyn_cast<Constant>(Ptr))
1250 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1252 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1254 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1255 const Twine &Name = "") {
1257 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1258 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1261 if (Constant *PC = dyn_cast<Constant>(Ptr))
1262 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1264 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1266 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1267 const Twine &Name = "") {
1269 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1270 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1273 if (Constant *PC = dyn_cast<Constant>(Ptr))
1274 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1277 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1279 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1280 const Twine &Name = "") {
1281 return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1284 /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1285 /// instead of a pointer to array of i8.
1286 Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1287 unsigned AddressSpace = 0) {
1288 GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace);
1289 Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1290 Value *Args[] = { zero, zero };
1291 return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1294 //===--------------------------------------------------------------------===//
1295 // Instruction creation methods: Cast/Conversion Operators
1296 //===--------------------------------------------------------------------===//
1298 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1299 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1301 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1302 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1304 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1305 return CreateCast(Instruction::SExt, V, DestTy, Name);
1307 /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1308 /// the value untouched if the type of V is already DestTy.
1309 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1310 const Twine &Name = "") {
1311 assert(V->getType()->isIntOrIntVectorTy() &&
1312 DestTy->isIntOrIntVectorTy() &&
1313 "Can only zero extend/truncate integers!");
1314 Type *VTy = V->getType();
1315 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1316 return CreateZExt(V, DestTy, Name);
1317 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1318 return CreateTrunc(V, DestTy, Name);
1321 /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1322 /// the value untouched if the type of V is already DestTy.
1323 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1324 const Twine &Name = "") {
1325 assert(V->getType()->isIntOrIntVectorTy() &&
1326 DestTy->isIntOrIntVectorTy() &&
1327 "Can only sign extend/truncate integers!");
1328 Type *VTy = V->getType();
1329 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1330 return CreateSExt(V, DestTy, Name);
1331 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1332 return CreateTrunc(V, DestTy, Name);
1335 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1336 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1338 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1339 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1341 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1342 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1344 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1345 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1347 Value *CreateFPTrunc(Value *V, Type *DestTy,
1348 const Twine &Name = "") {
1349 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1351 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1352 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1354 Value *CreatePtrToInt(Value *V, Type *DestTy,
1355 const Twine &Name = "") {
1356 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1358 Value *CreateIntToPtr(Value *V, Type *DestTy,
1359 const Twine &Name = "") {
1360 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1362 Value *CreateBitCast(Value *V, Type *DestTy,
1363 const Twine &Name = "") {
1364 return CreateCast(Instruction::BitCast, V, DestTy, Name);
1366 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1367 const Twine &Name = "") {
1368 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1370 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1371 const Twine &Name = "") {
1372 if (V->getType() == DestTy)
1374 if (Constant *VC = dyn_cast<Constant>(V))
1375 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1376 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1378 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1379 const Twine &Name = "") {
1380 if (V->getType() == DestTy)
1382 if (Constant *VC = dyn_cast<Constant>(V))
1383 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1384 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1386 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1387 const Twine &Name = "") {
1388 if (V->getType() == DestTy)
1390 if (Constant *VC = dyn_cast<Constant>(V))
1391 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1392 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1394 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1395 const Twine &Name = "") {
1396 if (V->getType() == DestTy)
1398 if (Constant *VC = dyn_cast<Constant>(V))
1399 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1400 return Insert(CastInst::Create(Op, V, DestTy), Name);
1402 Value *CreatePointerCast(Value *V, Type *DestTy,
1403 const Twine &Name = "") {
1404 if (V->getType() == DestTy)
1406 if (Constant *VC = dyn_cast<Constant>(V))
1407 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1408 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1411 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1412 const Twine &Name = "") {
1413 if (V->getType() == DestTy)
1416 if (Constant *VC = dyn_cast<Constant>(V)) {
1417 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1421 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1425 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1426 const Twine &Name = "") {
1427 if (V->getType() == DestTy)
1429 if (Constant *VC = dyn_cast<Constant>(V))
1430 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1431 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1434 Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1435 const Twine &Name = "") {
1436 if (V->getType() == DestTy)
1438 if (V->getType()->getScalarType()->isPointerTy() &&
1439 DestTy->getScalarType()->isIntegerTy())
1440 return CreatePtrToInt(V, DestTy, Name);
1441 if (V->getType()->getScalarType()->isIntegerTy() &&
1442 DestTy->getScalarType()->isPointerTy())
1443 return CreateIntToPtr(V, DestTy, Name);
1445 return CreateBitCast(V, DestTy, Name);
1449 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1450 if (V->getType() == DestTy)
1452 if (Constant *VC = dyn_cast<Constant>(V))
1453 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1454 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1457 // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1458 // compile time error, instead of converting the string to bool for the
1459 // isSigned parameter.
1460 Value *CreateIntCast(Value *, Type *, const char *) = delete;
1462 //===--------------------------------------------------------------------===//
1463 // Instruction creation methods: Compare Instructions
1464 //===--------------------------------------------------------------------===//
1466 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1467 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1469 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1470 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1472 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1473 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1475 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1476 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1478 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1479 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1481 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1482 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1484 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1485 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1487 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1488 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1490 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1491 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1493 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1494 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1497 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1498 MDNode *FPMathTag = nullptr) {
1499 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1501 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1502 MDNode *FPMathTag = nullptr) {
1503 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1505 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1506 MDNode *FPMathTag = nullptr) {
1507 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1509 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1510 MDNode *FPMathTag = nullptr) {
1511 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1513 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1514 MDNode *FPMathTag = nullptr) {
1515 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1517 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1518 MDNode *FPMathTag = nullptr) {
1519 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1521 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1522 MDNode *FPMathTag = nullptr) {
1523 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1525 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1526 MDNode *FPMathTag = nullptr) {
1527 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1529 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1530 MDNode *FPMathTag = nullptr) {
1531 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1533 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1534 MDNode *FPMathTag = nullptr) {
1535 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1537 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1538 MDNode *FPMathTag = nullptr) {
1539 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1541 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1542 MDNode *FPMathTag = nullptr) {
1543 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1545 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1546 MDNode *FPMathTag = nullptr) {
1547 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1549 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1550 MDNode *FPMathTag = nullptr) {
1551 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1554 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1555 const Twine &Name = "") {
1556 if (Constant *LC = dyn_cast<Constant>(LHS))
1557 if (Constant *RC = dyn_cast<Constant>(RHS))
1558 return Insert(Folder.CreateICmp(P, LC, RC), Name);
1559 return Insert(new ICmpInst(P, LHS, RHS), Name);
1561 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1562 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1563 if (Constant *LC = dyn_cast<Constant>(LHS))
1564 if (Constant *RC = dyn_cast<Constant>(RHS))
1565 return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1566 return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS),
1567 FPMathTag, FMF), Name);
1570 //===--------------------------------------------------------------------===//
1571 // Instruction creation methods: Other Instructions
1572 //===--------------------------------------------------------------------===//
1574 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1575 const Twine &Name = "") {
1576 return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1579 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1580 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1581 PointerType *PTy = cast<PointerType>(Callee->getType());
1582 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1583 return CreateCall(FTy, Callee, Args, Name, FPMathTag);
1586 CallInst *CreateCall(FunctionType *FTy, Value *Callee,
1587 ArrayRef<Value *> Args, const Twine &Name = "",
1588 MDNode *FPMathTag = nullptr) {
1589 CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
1590 if (isa<FPMathOperator>(CI))
1591 CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF));
1592 return Insert(CI, Name);
1595 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1596 ArrayRef<OperandBundleDef> OpBundles,
1597 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1598 CallInst *CI = CallInst::Create(Callee, Args, OpBundles);
1599 if (isa<FPMathOperator>(CI))
1600 CI = cast<CallInst>(AddFPMathAttributes(CI, FPMathTag, FMF));
1601 return Insert(CI, Name);
1604 CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1605 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1606 return CreateCall(Callee->getFunctionType(), Callee, Args, Name, FPMathTag);
1609 Value *CreateSelect(Value *C, Value *True, Value *False,
1610 const Twine &Name = "", Instruction *MDFrom = nullptr) {
1611 if (Constant *CC = dyn_cast<Constant>(C))
1612 if (Constant *TC = dyn_cast<Constant>(True))
1613 if (Constant *FC = dyn_cast<Constant>(False))
1614 return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1616 SelectInst *Sel = SelectInst::Create(C, True, False);
1618 MDNode *Prof = MDFrom->getMetadata(LLVMContext::MD_prof);
1619 MDNode *Unpred = MDFrom->getMetadata(LLVMContext::MD_unpredictable);
1620 Sel = addBranchMetadata(Sel, Prof, Unpred);
1622 return Insert(Sel, Name);
1625 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1626 return Insert(new VAArgInst(List, Ty), Name);
1629 Value *CreateExtractElement(Value *Vec, Value *Idx,
1630 const Twine &Name = "") {
1631 if (Constant *VC = dyn_cast<Constant>(Vec))
1632 if (Constant *IC = dyn_cast<Constant>(Idx))
1633 return Insert(Folder.CreateExtractElement(VC, IC), Name);
1634 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1637 Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1638 const Twine &Name = "") {
1639 return CreateExtractElement(Vec, getInt64(Idx), Name);
1642 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1643 const Twine &Name = "") {
1644 if (Constant *VC = dyn_cast<Constant>(Vec))
1645 if (Constant *NC = dyn_cast<Constant>(NewElt))
1646 if (Constant *IC = dyn_cast<Constant>(Idx))
1647 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1648 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1651 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1652 const Twine &Name = "") {
1653 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1656 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1657 const Twine &Name = "") {
1658 if (Constant *V1C = dyn_cast<Constant>(V1))
1659 if (Constant *V2C = dyn_cast<Constant>(V2))
1660 if (Constant *MC = dyn_cast<Constant>(Mask))
1661 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1662 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1665 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<uint32_t> IntMask,
1666 const Twine &Name = "") {
1667 Value *Mask = ConstantDataVector::get(Context, IntMask);
1668 return CreateShuffleVector(V1, V2, Mask, Name);
1671 Value *CreateExtractValue(Value *Agg,
1672 ArrayRef<unsigned> Idxs,
1673 const Twine &Name = "") {
1674 if (Constant *AggC = dyn_cast<Constant>(Agg))
1675 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1676 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1679 Value *CreateInsertValue(Value *Agg, Value *Val,
1680 ArrayRef<unsigned> Idxs,
1681 const Twine &Name = "") {
1682 if (Constant *AggC = dyn_cast<Constant>(Agg))
1683 if (Constant *ValC = dyn_cast<Constant>(Val))
1684 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1685 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1688 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1689 const Twine &Name = "") {
1690 return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1693 //===--------------------------------------------------------------------===//
1694 // Utility creation methods
1695 //===--------------------------------------------------------------------===//
1697 /// \brief Return an i1 value testing if \p Arg is null.
1698 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1699 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1703 /// \brief Return an i1 value testing if \p Arg is not null.
1704 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1705 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1709 /// \brief Return the i64 difference between two pointer values, dividing out
1710 /// the size of the pointed-to objects.
1712 /// This is intended to implement C-style pointer subtraction. As such, the
1713 /// pointers must be appropriately aligned for their element types and
1714 /// pointing into the same object.
1715 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1716 assert(LHS->getType() == RHS->getType() &&
1717 "Pointer subtraction operand types must match!");
1718 PointerType *ArgType = cast<PointerType>(LHS->getType());
1719 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1720 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1721 Value *Difference = CreateSub(LHS_int, RHS_int);
1722 return CreateExactSDiv(Difference,
1723 ConstantExpr::getSizeOf(ArgType->getElementType()),
1727 /// \brief Create an invariant.group.barrier intrinsic call, that stops
1728 /// optimizer to propagate equality using invariant.group metadata.
1729 /// If Ptr type is different from i8*, it's casted to i8* before call
1730 /// and casted back to Ptr type after call.
1731 Value *CreateInvariantGroupBarrier(Value *Ptr) {
1732 Module *M = BB->getParent()->getParent();
1733 Function *FnInvariantGroupBarrier = Intrinsic::getDeclaration(M,
1734 Intrinsic::invariant_group_barrier);
1736 Type *ArgumentAndReturnType = FnInvariantGroupBarrier->getReturnType();
1737 assert(ArgumentAndReturnType ==
1738 FnInvariantGroupBarrier->getFunctionType()->getParamType(0) &&
1739 "InvariantGroupBarrier should take and return the same type");
1740 Type *PtrType = Ptr->getType();
1742 bool PtrTypeConversionNeeded = PtrType != ArgumentAndReturnType;
1743 if (PtrTypeConversionNeeded)
1744 Ptr = CreateBitCast(Ptr, ArgumentAndReturnType);
1746 CallInst *Fn = CreateCall(FnInvariantGroupBarrier, {Ptr});
1748 if (PtrTypeConversionNeeded)
1749 return CreateBitCast(Fn, PtrType);
1753 /// \brief Return a vector value that contains \arg V broadcasted to \p
1754 /// NumElts elements.
1755 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1756 assert(NumElts > 0 && "Cannot splat to an empty vector!");
1758 // First insert it into an undef vector so we can shuffle it.
1759 Type *I32Ty = getInt32Ty();
1760 Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1761 V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1762 Name + ".splatinsert");
1764 // Shuffle the value across the desired number of elements.
1765 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1766 return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1769 /// \brief Return a value that has been extracted from a larger integer type.
1770 Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1771 IntegerType *ExtractedTy, uint64_t Offset,
1772 const Twine &Name) {
1773 IntegerType *IntTy = cast<IntegerType>(From->getType());
1774 assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1775 DL.getTypeStoreSize(IntTy) &&
1776 "Element extends past full value");
1777 uint64_t ShAmt = 8 * Offset;
1779 if (DL.isBigEndian())
1780 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1781 DL.getTypeStoreSize(ExtractedTy) - Offset);
1783 V = CreateLShr(V, ShAmt, Name + ".shift");
1785 assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1786 "Cannot extract to a larger integer!");
1787 if (ExtractedTy != IntTy) {
1788 V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1793 /// \brief Create an assume intrinsic call that represents an alignment
1794 /// assumption on the provided pointer.
1796 /// An optional offset can be provided, and if it is provided, the offset
1797 /// must be subtracted from the provided pointer to get the pointer with the
1798 /// specified alignment.
1799 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1801 Value *OffsetValue = nullptr) {
1802 assert(isa<PointerType>(PtrValue->getType()) &&
1803 "trying to create an alignment assumption on a non-pointer?");
1805 PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1806 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1807 Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1809 Value *Mask = ConstantInt::get(IntPtrTy,
1810 Alignment > 0 ? Alignment - 1 : 0);
1812 bool IsOffsetZero = false;
1813 if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1814 IsOffsetZero = CI->isZero();
1816 if (!IsOffsetZero) {
1817 if (OffsetValue->getType() != IntPtrTy)
1818 OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1820 PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1824 Value *Zero = ConstantInt::get(IntPtrTy, 0);
1825 Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1826 Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1828 return CreateAssumption(InvCond);
1832 // Create wrappers for C Binding types (see CBindingWrapping.h).
1833 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1835 } // end namespace llvm
1837 #endif // LLVM_IR_IRBUILDER_H