Home | History | Annotate | Download | only in IR
      1 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     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.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_IR_IRBUILDER_H
     16 #define LLVM_IR_IRBUILDER_H
     17 
     18 #include "llvm/ADT/ArrayRef.h"
     19 #include "llvm/ADT/StringRef.h"
     20 #include "llvm/ADT/Twine.h"
     21 #include "llvm/IR/BasicBlock.h"
     22 #include "llvm/IR/DataLayout.h"
     23 #include "llvm/IR/Instructions.h"
     24 #include "llvm/IR/LLVMContext.h"
     25 #include "llvm/IR/Operator.h"
     26 #include "llvm/Support/ConstantFolder.h"
     27 
     28 namespace llvm {
     29   class MDNode;
     30 
     31 /// \brief This provides the default implementation of the IRBuilder
     32 /// 'InsertHelper' method that is called whenever an instruction is created by
     33 /// IRBuilder and needs to be inserted.
     34 ///
     35 /// By default, this inserts the instruction at the insertion point.
     36 template <bool preserveNames = true>
     37 class IRBuilderDefaultInserter {
     38 protected:
     39   void InsertHelper(Instruction *I, const Twine &Name,
     40                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
     41     if (BB) BB->getInstList().insert(InsertPt, I);
     42     if (preserveNames)
     43       I->setName(Name);
     44   }
     45 };
     46 
     47 /// \brief Common base class shared among various IRBuilders.
     48 class IRBuilderBase {
     49   DebugLoc CurDbgLocation;
     50 protected:
     51   BasicBlock *BB;
     52   BasicBlock::iterator InsertPt;
     53   LLVMContext &Context;
     54 public:
     55 
     56   IRBuilderBase(LLVMContext &context)
     57     : Context(context) {
     58     ClearInsertionPoint();
     59   }
     60 
     61   //===--------------------------------------------------------------------===//
     62   // Builder configuration methods
     63   //===--------------------------------------------------------------------===//
     64 
     65   /// \brief Clear the insertion point: created instructions will not be
     66   /// inserted into a block.
     67   void ClearInsertionPoint() {
     68     BB = 0;
     69   }
     70 
     71   BasicBlock *GetInsertBlock() const { return BB; }
     72   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
     73   LLVMContext &getContext() const { return Context; }
     74 
     75   /// \brief This specifies that created instructions should be appended to the
     76   /// end of the specified block.
     77   void SetInsertPoint(BasicBlock *TheBB) {
     78     BB = TheBB;
     79     InsertPt = BB->end();
     80   }
     81 
     82   /// \brief This specifies that created instructions should be inserted before
     83   /// the specified instruction.
     84   void SetInsertPoint(Instruction *I) {
     85     BB = I->getParent();
     86     InsertPt = I;
     87     SetCurrentDebugLocation(I->getDebugLoc());
     88   }
     89 
     90   /// \brief This specifies that created instructions should be inserted at the
     91   /// specified point.
     92   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
     93     BB = TheBB;
     94     InsertPt = IP;
     95   }
     96 
     97   /// \brief Find the nearest point that dominates this use, and specify that
     98   /// created instructions should be inserted at this point.
     99   void SetInsertPoint(Use &U) {
    100     Instruction *UseInst = cast<Instruction>(U.getUser());
    101     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
    102       BasicBlock *PredBB = Phi->getIncomingBlock(U);
    103       assert(U != PredBB->getTerminator() && "critical edge not split");
    104       SetInsertPoint(PredBB, PredBB->getTerminator());
    105       return;
    106     }
    107     SetInsertPoint(UseInst);
    108   }
    109 
    110   /// \brief Set location information used by debugging information.
    111   void SetCurrentDebugLocation(const DebugLoc &L) {
    112     CurDbgLocation = L;
    113   }
    114 
    115   /// \brief Get location information used by debugging information.
    116   DebugLoc getCurrentDebugLocation() const { return CurDbgLocation; }
    117 
    118   /// \brief If this builder has a current debug location, set it on the
    119   /// specified instruction.
    120   void SetInstDebugLocation(Instruction *I) const {
    121     if (!CurDbgLocation.isUnknown())
    122       I->setDebugLoc(CurDbgLocation);
    123   }
    124 
    125   /// \brief Get the return type of the current function that we're emitting
    126   /// into.
    127   Type *getCurrentFunctionReturnType() const;
    128 
    129   /// InsertPoint - A saved insertion point.
    130   class InsertPoint {
    131     BasicBlock *Block;
    132     BasicBlock::iterator Point;
    133 
    134   public:
    135     /// \brief Creates a new insertion point which doesn't point to anything.
    136     InsertPoint() : Block(0) {}
    137 
    138     /// \brief Creates a new insertion point at the given location.
    139     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
    140       : Block(InsertBlock), Point(InsertPoint) {}
    141 
    142     /// \brief Returns true if this insert point is set.
    143     bool isSet() const { return (Block != 0); }
    144 
    145     llvm::BasicBlock *getBlock() const { return Block; }
    146     llvm::BasicBlock::iterator getPoint() const { return Point; }
    147   };
    148 
    149   /// \brief Returns the current insert point.
    150   InsertPoint saveIP() const {
    151     return InsertPoint(GetInsertBlock(), GetInsertPoint());
    152   }
    153 
    154   /// \brief Returns the current insert point, clearing it in the process.
    155   InsertPoint saveAndClearIP() {
    156     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
    157     ClearInsertionPoint();
    158     return IP;
    159   }
    160 
    161   /// \brief Sets the current insert point to a previously-saved location.
    162   void restoreIP(InsertPoint IP) {
    163     if (IP.isSet())
    164       SetInsertPoint(IP.getBlock(), IP.getPoint());
    165     else
    166       ClearInsertionPoint();
    167   }
    168 
    169   //===--------------------------------------------------------------------===//
    170   // Miscellaneous creation methods.
    171   //===--------------------------------------------------------------------===//
    172 
    173   /// \brief Make a new global variable with initializer type i8*
    174   ///
    175   /// Make a new global variable with an initializer that has array of i8 type
    176   /// filled in with the null terminated string value specified.  The new global
    177   /// variable will be marked mergable with any others of the same contents.  If
    178   /// Name is specified, it is the name of the global variable created.
    179   Value *CreateGlobalString(StringRef Str, const Twine &Name = "");
    180 
    181   /// \brief Get a constant value representing either true or false.
    182   ConstantInt *getInt1(bool V) {
    183     return ConstantInt::get(getInt1Ty(), V);
    184   }
    185 
    186   /// \brief Get the constant value for i1 true.
    187   ConstantInt *getTrue() {
    188     return ConstantInt::getTrue(Context);
    189   }
    190 
    191   /// \brief Get the constant value for i1 false.
    192   ConstantInt *getFalse() {
    193     return ConstantInt::getFalse(Context);
    194   }
    195 
    196   /// \brief Get a constant 8-bit value.
    197   ConstantInt *getInt8(uint8_t C) {
    198     return ConstantInt::get(getInt8Ty(), C);
    199   }
    200 
    201   /// \brief Get a constant 16-bit value.
    202   ConstantInt *getInt16(uint16_t C) {
    203     return ConstantInt::get(getInt16Ty(), C);
    204   }
    205 
    206   /// \brief Get a constant 32-bit value.
    207   ConstantInt *getInt32(uint32_t C) {
    208     return ConstantInt::get(getInt32Ty(), C);
    209   }
    210 
    211   /// \brief Get a constant 64-bit value.
    212   ConstantInt *getInt64(uint64_t C) {
    213     return ConstantInt::get(getInt64Ty(), C);
    214   }
    215 
    216   /// \brief Get a constant integer value.
    217   ConstantInt *getInt(const APInt &AI) {
    218     return ConstantInt::get(Context, AI);
    219   }
    220 
    221   //===--------------------------------------------------------------------===//
    222   // Type creation methods
    223   //===--------------------------------------------------------------------===//
    224 
    225   /// \brief Fetch the type representing a single bit
    226   IntegerType *getInt1Ty() {
    227     return Type::getInt1Ty(Context);
    228   }
    229 
    230   /// \brief Fetch the type representing an 8-bit integer.
    231   IntegerType *getInt8Ty() {
    232     return Type::getInt8Ty(Context);
    233   }
    234 
    235   /// \brief Fetch the type representing a 16-bit integer.
    236   IntegerType *getInt16Ty() {
    237     return Type::getInt16Ty(Context);
    238   }
    239 
    240   /// \brief Fetch the type representing a 32-bit integer.
    241   IntegerType *getInt32Ty() {
    242     return Type::getInt32Ty(Context);
    243   }
    244 
    245   /// \brief Fetch the type representing a 64-bit integer.
    246   IntegerType *getInt64Ty() {
    247     return Type::getInt64Ty(Context);
    248   }
    249 
    250   /// \brief Fetch the type representing a 32-bit floating point value.
    251   Type *getFloatTy() {
    252     return Type::getFloatTy(Context);
    253   }
    254 
    255   /// \brief Fetch the type representing a 64-bit floating point value.
    256   Type *getDoubleTy() {
    257     return Type::getDoubleTy(Context);
    258   }
    259 
    260   /// \brief Fetch the type representing void.
    261   Type *getVoidTy() {
    262     return Type::getVoidTy(Context);
    263   }
    264 
    265   /// \brief Fetch the type representing a pointer to an 8-bit integer value.
    266   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
    267     return Type::getInt8PtrTy(Context, AddrSpace);
    268   }
    269 
    270   /// \brief Fetch the type representing a pointer to an integer value.
    271   IntegerType* getIntPtrTy(DataLayout *DL, unsigned AddrSpace = 0) {
    272     return DL->getIntPtrType(Context, AddrSpace);
    273   }
    274 
    275   //===--------------------------------------------------------------------===//
    276   // Intrinsic creation methods
    277   //===--------------------------------------------------------------------===//
    278 
    279   /// \brief Create and insert a memset to the specified pointer and the
    280   /// specified value.
    281   ///
    282   /// If the pointer isn't an i8*, it will be converted.  If a TBAA tag is
    283   /// specified, it will be added to the instruction.
    284   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
    285                          bool isVolatile = false, MDNode *TBAATag = 0) {
    286     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile, TBAATag);
    287   }
    288 
    289   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
    290                          bool isVolatile = false, MDNode *TBAATag = 0);
    291 
    292   /// \brief Create and insert a memcpy between the specified pointers.
    293   ///
    294   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
    295   /// specified, it will be added to the instruction.
    296   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
    297                          bool isVolatile = false, MDNode *TBAATag = 0,
    298                          MDNode *TBAAStructTag = 0) {
    299     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
    300                         TBAAStructTag);
    301   }
    302 
    303   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
    304                          bool isVolatile = false, MDNode *TBAATag = 0,
    305                          MDNode *TBAAStructTag = 0);
    306 
    307   /// \brief Create and insert a memmove between the specified
    308   /// pointers.
    309   ///
    310   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
    311   /// specified, it will be added to the instruction.
    312   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
    313                           bool isVolatile = false, MDNode *TBAATag = 0) {
    314     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag);
    315   }
    316 
    317   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
    318                           bool isVolatile = false, MDNode *TBAATag = 0);
    319 
    320   /// \brief Create a lifetime.start intrinsic.
    321   ///
    322   /// If the pointer isn't i8* it will be converted.
    323   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = 0);
    324 
    325   /// \brief Create a lifetime.end intrinsic.
    326   ///
    327   /// If the pointer isn't i8* it will be converted.
    328   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = 0);
    329 
    330 private:
    331   Value *getCastedInt8PtrValue(Value *Ptr);
    332 };
    333 
    334 /// \brief This provides a uniform API for creating instructions and inserting
    335 /// them into a basic block: either at the end of a BasicBlock, or at a specific
    336 /// iterator location in a block.
    337 ///
    338 /// Note that the builder does not expose the full generality of LLVM
    339 /// instructions.  For access to extra instruction properties, use the mutators
    340 /// (e.g. setVolatile) on the instructions after they have been
    341 /// created. Convenience state exists to specify fast-math flags and fp-math
    342 /// tags.
    343 ///
    344 /// The first template argument handles whether or not to preserve names in the
    345 /// final instruction output. This defaults to on.  The second template argument
    346 /// specifies a class to use for creating constants.  This defaults to creating
    347 /// minimally folded constants.  The fourth template argument allows clients to
    348 /// specify custom insertion hooks that are called on every newly created
    349 /// insertion.
    350 template<bool preserveNames = true, typename T = ConstantFolder,
    351          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
    352 class IRBuilder : public IRBuilderBase, public Inserter {
    353   T Folder;
    354   MDNode *DefaultFPMathTag;
    355   FastMathFlags FMF;
    356 public:
    357   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
    358             MDNode *FPMathTag = 0)
    359     : IRBuilderBase(C), Inserter(I), Folder(F), DefaultFPMathTag(FPMathTag),
    360       FMF() {
    361   }
    362 
    363   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = 0)
    364     : IRBuilderBase(C), Folder(), DefaultFPMathTag(FPMathTag), FMF() {
    365   }
    366 
    367   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = 0)
    368     : IRBuilderBase(TheBB->getContext()), Folder(F),
    369       DefaultFPMathTag(FPMathTag), FMF() {
    370     SetInsertPoint(TheBB);
    371   }
    372 
    373   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = 0)
    374     : IRBuilderBase(TheBB->getContext()), Folder(),
    375       DefaultFPMathTag(FPMathTag), FMF() {
    376     SetInsertPoint(TheBB);
    377   }
    378 
    379   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = 0)
    380     : IRBuilderBase(IP->getContext()), Folder(), DefaultFPMathTag(FPMathTag),
    381       FMF() {
    382     SetInsertPoint(IP);
    383     SetCurrentDebugLocation(IP->getDebugLoc());
    384   }
    385 
    386   explicit IRBuilder(Use &U, MDNode *FPMathTag = 0)
    387     : IRBuilderBase(U->getContext()), Folder(), DefaultFPMathTag(FPMathTag),
    388       FMF() {
    389     SetInsertPoint(U);
    390     SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
    391   }
    392 
    393   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
    394             MDNode *FPMathTag = 0)
    395     : IRBuilderBase(TheBB->getContext()), Folder(F),
    396       DefaultFPMathTag(FPMathTag), FMF() {
    397     SetInsertPoint(TheBB, IP);
    398   }
    399 
    400   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, MDNode *FPMathTag = 0)
    401     : IRBuilderBase(TheBB->getContext()), Folder(),
    402       DefaultFPMathTag(FPMathTag), FMF() {
    403     SetInsertPoint(TheBB, IP);
    404   }
    405 
    406   /// \brief Get the constant folder being used.
    407   const T &getFolder() { return Folder; }
    408 
    409   /// \brief Get the floating point math metadata being used.
    410   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
    411 
    412   /// \brief Get the flags to be applied to created floating point ops
    413   FastMathFlags getFastMathFlags() const { return FMF; }
    414 
    415   /// \brief Clear the fast-math flags.
    416   void clearFastMathFlags() { FMF.clear(); }
    417 
    418   /// \brief SetDefaultFPMathTag - Set the floating point math metadata to be used.
    419   void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
    420 
    421   /// \brief Set the fast-math flags to be used with generated fp-math operators
    422   void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
    423 
    424   /// \brief Return true if this builder is configured to actually add the
    425   /// requested names to IR created through it.
    426   bool isNamePreserving() const { return preserveNames; }
    427 
    428   /// \brief Insert and return the specified instruction.
    429   template<typename InstTy>
    430   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
    431     this->InsertHelper(I, Name, BB, InsertPt);
    432     this->SetInstDebugLocation(I);
    433     return I;
    434   }
    435 
    436   /// \brief No-op overload to handle constants.
    437   Constant *Insert(Constant *C, const Twine& = "") const {
    438     return C;
    439   }
    440 
    441   //===--------------------------------------------------------------------===//
    442   // Instruction creation methods: Terminators
    443   //===--------------------------------------------------------------------===//
    444 
    445 private:
    446   /// \brief Helper to add branch weight metadata onto an instruction.
    447   /// \returns The annotated instruction.
    448   template <typename InstTy>
    449   InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
    450     if (Weights)
    451       I->setMetadata(LLVMContext::MD_prof, Weights);
    452     return I;
    453   }
    454 
    455 public:
    456   /// \brief Create a 'ret void' instruction.
    457   ReturnInst *CreateRetVoid() {
    458     return Insert(ReturnInst::Create(Context));
    459   }
    460 
    461   /// \brief Create a 'ret <val>' instruction.
    462   ReturnInst *CreateRet(Value *V) {
    463     return Insert(ReturnInst::Create(Context, V));
    464   }
    465 
    466   /// \brief Create a sequence of N insertvalue instructions,
    467   /// with one Value from the retVals array each, that build a aggregate
    468   /// return value one value at a time, and a ret instruction to return
    469   /// the resulting aggregate value.
    470   ///
    471   /// This is a convenience function for code that uses aggregate return values
    472   /// as a vehicle for having multiple return values.
    473   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
    474     Value *V = UndefValue::get(getCurrentFunctionReturnType());
    475     for (unsigned i = 0; i != N; ++i)
    476       V = CreateInsertValue(V, retVals[i], i, "mrv");
    477     return Insert(ReturnInst::Create(Context, V));
    478   }
    479 
    480   /// \brief Create an unconditional 'br label X' instruction.
    481   BranchInst *CreateBr(BasicBlock *Dest) {
    482     return Insert(BranchInst::Create(Dest));
    483   }
    484 
    485   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
    486   /// instruction.
    487   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
    488                            MDNode *BranchWeights = 0) {
    489     return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
    490                                    BranchWeights));
    491   }
    492 
    493   /// \brief Create a switch instruction with the specified value, default dest,
    494   /// and with a hint for the number of cases that will be added (for efficient
    495   /// allocation).
    496   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
    497                            MDNode *BranchWeights = 0) {
    498     return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
    499                                    BranchWeights));
    500   }
    501 
    502   /// \brief Create an indirect branch instruction with the specified address
    503   /// operand, with an optional hint for the number of destinations that will be
    504   /// added (for efficient allocation).
    505   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
    506     return Insert(IndirectBrInst::Create(Addr, NumDests));
    507   }
    508 
    509   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
    510                            BasicBlock *UnwindDest, const Twine &Name = "") {
    511     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest,
    512                                      ArrayRef<Value *>()),
    513                   Name);
    514   }
    515   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
    516                            BasicBlock *UnwindDest, Value *Arg1,
    517                            const Twine &Name = "") {
    518     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
    519                   Name);
    520   }
    521   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
    522                             BasicBlock *UnwindDest, Value *Arg1,
    523                             Value *Arg2, Value *Arg3,
    524                             const Twine &Name = "") {
    525     Value *Args[] = { Arg1, Arg2, Arg3 };
    526     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
    527                   Name);
    528   }
    529   /// \brief Create an invoke instruction.
    530   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
    531                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
    532                            const Twine &Name = "") {
    533     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
    534                   Name);
    535   }
    536 
    537   ResumeInst *CreateResume(Value *Exn) {
    538     return Insert(ResumeInst::Create(Exn));
    539   }
    540 
    541   UnreachableInst *CreateUnreachable() {
    542     return Insert(new UnreachableInst(Context));
    543   }
    544 
    545   //===--------------------------------------------------------------------===//
    546   // Instruction creation methods: Binary Operators
    547   //===--------------------------------------------------------------------===//
    548 private:
    549   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
    550                                           Value *LHS, Value *RHS,
    551                                           const Twine &Name,
    552                                           bool HasNUW, bool HasNSW) {
    553     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
    554     if (HasNUW) BO->setHasNoUnsignedWrap();
    555     if (HasNSW) BO->setHasNoSignedWrap();
    556     return BO;
    557   }
    558 
    559   Instruction *AddFPMathAttributes(Instruction *I,
    560                                    MDNode *FPMathTag,
    561                                    FastMathFlags FMF) const {
    562     if (!FPMathTag)
    563       FPMathTag = DefaultFPMathTag;
    564     if (FPMathTag)
    565       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
    566     I->setFastMathFlags(FMF);
    567     return I;
    568   }
    569 public:
    570   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
    571                    bool HasNUW = false, bool HasNSW = false) {
    572     if (Constant *LC = dyn_cast<Constant>(LHS))
    573       if (Constant *RC = dyn_cast<Constant>(RHS))
    574         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
    575     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
    576                                    HasNUW, HasNSW);
    577   }
    578   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
    579     return CreateAdd(LHS, RHS, Name, false, true);
    580   }
    581   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
    582     return CreateAdd(LHS, RHS, Name, true, false);
    583   }
    584   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
    585                     MDNode *FPMathTag = 0) {
    586     if (Constant *LC = dyn_cast<Constant>(LHS))
    587       if (Constant *RC = dyn_cast<Constant>(RHS))
    588         return Insert(Folder.CreateFAdd(LC, RC), Name);
    589     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
    590                                       FPMathTag, FMF), Name);
    591   }
    592   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
    593                    bool HasNUW = false, bool HasNSW = false) {
    594     if (Constant *LC = dyn_cast<Constant>(LHS))
    595       if (Constant *RC = dyn_cast<Constant>(RHS))
    596         return Insert(Folder.CreateSub(LC, RC), Name);
    597     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
    598                                    HasNUW, HasNSW);
    599   }
    600   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
    601     return CreateSub(LHS, RHS, Name, false, true);
    602   }
    603   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
    604     return CreateSub(LHS, RHS, Name, true, false);
    605   }
    606   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
    607                     MDNode *FPMathTag = 0) {
    608     if (Constant *LC = dyn_cast<Constant>(LHS))
    609       if (Constant *RC = dyn_cast<Constant>(RHS))
    610         return Insert(Folder.CreateFSub(LC, RC), Name);
    611     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
    612                                       FPMathTag, FMF), Name);
    613   }
    614   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
    615                    bool HasNUW = false, bool HasNSW = false) {
    616     if (Constant *LC = dyn_cast<Constant>(LHS))
    617       if (Constant *RC = dyn_cast<Constant>(RHS))
    618         return Insert(Folder.CreateMul(LC, RC), Name);
    619     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
    620                                    HasNUW, HasNSW);
    621   }
    622   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
    623     return CreateMul(LHS, RHS, Name, false, true);
    624   }
    625   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
    626     return CreateMul(LHS, RHS, Name, true, false);
    627   }
    628   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
    629                     MDNode *FPMathTag = 0) {
    630     if (Constant *LC = dyn_cast<Constant>(LHS))
    631       if (Constant *RC = dyn_cast<Constant>(RHS))
    632         return Insert(Folder.CreateFMul(LC, RC), Name);
    633     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
    634                                       FPMathTag, FMF), Name);
    635   }
    636   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
    637                     bool isExact = false) {
    638     if (Constant *LC = dyn_cast<Constant>(LHS))
    639       if (Constant *RC = dyn_cast<Constant>(RHS))
    640         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
    641     if (!isExact)
    642       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
    643     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
    644   }
    645   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
    646     return CreateUDiv(LHS, RHS, Name, true);
    647   }
    648   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
    649                     bool isExact = false) {
    650     if (Constant *LC = dyn_cast<Constant>(LHS))
    651       if (Constant *RC = dyn_cast<Constant>(RHS))
    652         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
    653     if (!isExact)
    654       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
    655     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
    656   }
    657   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
    658     return CreateSDiv(LHS, RHS, Name, true);
    659   }
    660   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
    661                     MDNode *FPMathTag = 0) {
    662     if (Constant *LC = dyn_cast<Constant>(LHS))
    663       if (Constant *RC = dyn_cast<Constant>(RHS))
    664         return Insert(Folder.CreateFDiv(LC, RC), Name);
    665     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
    666                                       FPMathTag, FMF), Name);
    667   }
    668   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
    669     if (Constant *LC = dyn_cast<Constant>(LHS))
    670       if (Constant *RC = dyn_cast<Constant>(RHS))
    671         return Insert(Folder.CreateURem(LC, RC), Name);
    672     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
    673   }
    674   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
    675     if (Constant *LC = dyn_cast<Constant>(LHS))
    676       if (Constant *RC = dyn_cast<Constant>(RHS))
    677         return Insert(Folder.CreateSRem(LC, RC), Name);
    678     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
    679   }
    680   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
    681                     MDNode *FPMathTag = 0) {
    682     if (Constant *LC = dyn_cast<Constant>(LHS))
    683       if (Constant *RC = dyn_cast<Constant>(RHS))
    684         return Insert(Folder.CreateFRem(LC, RC), Name);
    685     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
    686                                       FPMathTag, FMF), Name);
    687   }
    688 
    689   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
    690                    bool HasNUW = false, bool HasNSW = false) {
    691     if (Constant *LC = dyn_cast<Constant>(LHS))
    692       if (Constant *RC = dyn_cast<Constant>(RHS))
    693         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
    694     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
    695                                    HasNUW, HasNSW);
    696   }
    697   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
    698                    bool HasNUW = false, bool HasNSW = false) {
    699     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
    700                      HasNUW, HasNSW);
    701   }
    702   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
    703                    bool HasNUW = false, bool HasNSW = false) {
    704     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
    705                      HasNUW, HasNSW);
    706   }
    707 
    708   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
    709                     bool isExact = false) {
    710     if (Constant *LC = dyn_cast<Constant>(LHS))
    711       if (Constant *RC = dyn_cast<Constant>(RHS))
    712         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
    713     if (!isExact)
    714       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
    715     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
    716   }
    717   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
    718                     bool isExact = false) {
    719     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
    720   }
    721   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
    722                     bool isExact = false) {
    723     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
    724   }
    725 
    726   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
    727                     bool isExact = false) {
    728     if (Constant *LC = dyn_cast<Constant>(LHS))
    729       if (Constant *RC = dyn_cast<Constant>(RHS))
    730         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
    731     if (!isExact)
    732       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
    733     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
    734   }
    735   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
    736                     bool isExact = false) {
    737     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
    738   }
    739   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
    740                     bool isExact = false) {
    741     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
    742   }
    743 
    744   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
    745     if (Constant *RC = dyn_cast<Constant>(RHS)) {
    746       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
    747         return LHS;  // LHS & -1 -> LHS
    748       if (Constant *LC = dyn_cast<Constant>(LHS))
    749         return Insert(Folder.CreateAnd(LC, RC), Name);
    750     }
    751     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
    752   }
    753   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
    754     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
    755   }
    756   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
    757     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
    758   }
    759 
    760   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
    761     if (Constant *RC = dyn_cast<Constant>(RHS)) {
    762       if (RC->isNullValue())
    763         return LHS;  // LHS | 0 -> LHS
    764       if (Constant *LC = dyn_cast<Constant>(LHS))
    765         return Insert(Folder.CreateOr(LC, RC), Name);
    766     }
    767     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
    768   }
    769   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
    770     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
    771   }
    772   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
    773     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
    774   }
    775 
    776   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
    777     if (Constant *LC = dyn_cast<Constant>(LHS))
    778       if (Constant *RC = dyn_cast<Constant>(RHS))
    779         return Insert(Folder.CreateXor(LC, RC), Name);
    780     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
    781   }
    782   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
    783     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
    784   }
    785   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
    786     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
    787   }
    788 
    789   Value *CreateBinOp(Instruction::BinaryOps Opc,
    790                      Value *LHS, Value *RHS, const Twine &Name = "") {
    791     if (Constant *LC = dyn_cast<Constant>(LHS))
    792       if (Constant *RC = dyn_cast<Constant>(RHS))
    793         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
    794     return Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
    795   }
    796 
    797   Value *CreateNeg(Value *V, const Twine &Name = "",
    798                    bool HasNUW = false, bool HasNSW = false) {
    799     if (Constant *VC = dyn_cast<Constant>(V))
    800       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
    801     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
    802     if (HasNUW) BO->setHasNoUnsignedWrap();
    803     if (HasNSW) BO->setHasNoSignedWrap();
    804     return BO;
    805   }
    806   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
    807     return CreateNeg(V, Name, false, true);
    808   }
    809   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
    810     return CreateNeg(V, Name, true, false);
    811   }
    812   Value *CreateFNeg(Value *V, const Twine &Name = "", MDNode *FPMathTag = 0) {
    813     if (Constant *VC = dyn_cast<Constant>(V))
    814       return Insert(Folder.CreateFNeg(VC), Name);
    815     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
    816                                       FPMathTag, FMF), Name);
    817   }
    818   Value *CreateNot(Value *V, const Twine &Name = "") {
    819     if (Constant *VC = dyn_cast<Constant>(V))
    820       return Insert(Folder.CreateNot(VC), Name);
    821     return Insert(BinaryOperator::CreateNot(V), Name);
    822   }
    823 
    824   //===--------------------------------------------------------------------===//
    825   // Instruction creation methods: Memory Instructions
    826   //===--------------------------------------------------------------------===//
    827 
    828   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = 0,
    829                            const Twine &Name = "") {
    830     return Insert(new AllocaInst(Ty, ArraySize), Name);
    831   }
    832   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
    833   // converting the string to 'bool' for the isVolatile parameter.
    834   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
    835     return Insert(new LoadInst(Ptr), Name);
    836   }
    837   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
    838     return Insert(new LoadInst(Ptr), Name);
    839   }
    840   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
    841     return Insert(new LoadInst(Ptr, 0, isVolatile), Name);
    842   }
    843   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
    844     return Insert(new StoreInst(Val, Ptr, isVolatile));
    845   }
    846   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
    847   // correctly, instead of converting the string to 'bool' for the isVolatile
    848   // parameter.
    849   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
    850     LoadInst *LI = CreateLoad(Ptr, Name);
    851     LI->setAlignment(Align);
    852     return LI;
    853   }
    854   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
    855                               const Twine &Name = "") {
    856     LoadInst *LI = CreateLoad(Ptr, Name);
    857     LI->setAlignment(Align);
    858     return LI;
    859   }
    860   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
    861                               const Twine &Name = "") {
    862     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
    863     LI->setAlignment(Align);
    864     return LI;
    865   }
    866   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
    867                                 bool isVolatile = false) {
    868     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
    869     SI->setAlignment(Align);
    870     return SI;
    871   }
    872   FenceInst *CreateFence(AtomicOrdering Ordering,
    873                          SynchronizationScope SynchScope = CrossThread) {
    874     return Insert(new FenceInst(Context, Ordering, SynchScope));
    875   }
    876   AtomicCmpXchgInst *CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
    877                                          AtomicOrdering Ordering,
    878                                SynchronizationScope SynchScope = CrossThread) {
    879     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope));
    880   }
    881   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
    882                                  AtomicOrdering Ordering,
    883                                SynchronizationScope SynchScope = CrossThread) {
    884     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
    885   }
    886   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
    887                    const Twine &Name = "") {
    888     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
    889       // Every index must be constant.
    890       size_t i, e;
    891       for (i = 0, e = IdxList.size(); i != e; ++i)
    892         if (!isa<Constant>(IdxList[i]))
    893           break;
    894       if (i == e)
    895         return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
    896     }
    897     return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
    898   }
    899   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
    900                            const Twine &Name = "") {
    901     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
    902       // Every index must be constant.
    903       size_t i, e;
    904       for (i = 0, e = IdxList.size(); i != e; ++i)
    905         if (!isa<Constant>(IdxList[i]))
    906           break;
    907       if (i == e)
    908         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
    909     }
    910     return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
    911   }
    912   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
    913     if (Constant *PC = dyn_cast<Constant>(Ptr))
    914       if (Constant *IC = dyn_cast<Constant>(Idx))
    915         return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
    916     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
    917   }
    918   Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
    919     if (Constant *PC = dyn_cast<Constant>(Ptr))
    920       if (Constant *IC = dyn_cast<Constant>(Idx))
    921         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
    922     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
    923   }
    924   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
    925     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
    926 
    927     if (Constant *PC = dyn_cast<Constant>(Ptr))
    928       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
    929 
    930     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
    931   }
    932   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
    933                                     const Twine &Name = "") {
    934     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
    935 
    936     if (Constant *PC = dyn_cast<Constant>(Ptr))
    937       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
    938 
    939     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
    940   }
    941   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
    942                     const Twine &Name = "") {
    943     Value *Idxs[] = {
    944       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
    945       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
    946     };
    947 
    948     if (Constant *PC = dyn_cast<Constant>(Ptr))
    949       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
    950 
    951     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
    952   }
    953   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
    954                                     const Twine &Name = "") {
    955     Value *Idxs[] = {
    956       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
    957       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
    958     };
    959 
    960     if (Constant *PC = dyn_cast<Constant>(Ptr))
    961       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
    962 
    963     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
    964   }
    965   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
    966     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
    967 
    968     if (Constant *PC = dyn_cast<Constant>(Ptr))
    969       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
    970 
    971     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
    972   }
    973   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
    974                                     const Twine &Name = "") {
    975     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
    976 
    977     if (Constant *PC = dyn_cast<Constant>(Ptr))
    978       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
    979 
    980     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
    981   }
    982   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
    983                     const Twine &Name = "") {
    984     Value *Idxs[] = {
    985       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
    986       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
    987     };
    988 
    989     if (Constant *PC = dyn_cast<Constant>(Ptr))
    990       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
    991 
    992     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
    993   }
    994   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
    995                                     const Twine &Name = "") {
    996     Value *Idxs[] = {
    997       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
    998       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
    999     };
   1000 
   1001     if (Constant *PC = dyn_cast<Constant>(Ptr))
   1002       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
   1003 
   1004     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
   1005   }
   1006   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
   1007     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
   1008   }
   1009 
   1010   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
   1011   /// instead of a pointer to array of i8.
   1012   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
   1013     Value *gv = CreateGlobalString(Str, Name);
   1014     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
   1015     Value *Args[] = { zero, zero };
   1016     return CreateInBoundsGEP(gv, Args, Name);
   1017   }
   1018 
   1019   //===--------------------------------------------------------------------===//
   1020   // Instruction creation methods: Cast/Conversion Operators
   1021   //===--------------------------------------------------------------------===//
   1022 
   1023   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
   1024     return CreateCast(Instruction::Trunc, V, DestTy, Name);
   1025   }
   1026   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
   1027     return CreateCast(Instruction::ZExt, V, DestTy, Name);
   1028   }
   1029   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
   1030     return CreateCast(Instruction::SExt, V, DestTy, Name);
   1031   }
   1032   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
   1033   /// the value untouched if the type of V is already DestTy.
   1034   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
   1035                            const Twine &Name = "") {
   1036     assert(V->getType()->isIntOrIntVectorTy() &&
   1037            DestTy->isIntOrIntVectorTy() &&
   1038            "Can only zero extend/truncate integers!");
   1039     Type *VTy = V->getType();
   1040     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
   1041       return CreateZExt(V, DestTy, Name);
   1042     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
   1043       return CreateTrunc(V, DestTy, Name);
   1044     return V;
   1045   }
   1046   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
   1047   /// the value untouched if the type of V is already DestTy.
   1048   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
   1049                            const Twine &Name = "") {
   1050     assert(V->getType()->isIntOrIntVectorTy() &&
   1051            DestTy->isIntOrIntVectorTy() &&
   1052            "Can only sign extend/truncate integers!");
   1053     Type *VTy = V->getType();
   1054     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
   1055       return CreateSExt(V, DestTy, Name);
   1056     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
   1057       return CreateTrunc(V, DestTy, Name);
   1058     return V;
   1059   }
   1060   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
   1061     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
   1062   }
   1063   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
   1064     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
   1065   }
   1066   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
   1067     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
   1068   }
   1069   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
   1070     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
   1071   }
   1072   Value *CreateFPTrunc(Value *V, Type *DestTy,
   1073                        const Twine &Name = "") {
   1074     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
   1075   }
   1076   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
   1077     return CreateCast(Instruction::FPExt, V, DestTy, Name);
   1078   }
   1079   Value *CreatePtrToInt(Value *V, Type *DestTy,
   1080                         const Twine &Name = "") {
   1081     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
   1082   }
   1083   Value *CreateIntToPtr(Value *V, Type *DestTy,
   1084                         const Twine &Name = "") {
   1085     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
   1086   }
   1087   Value *CreateBitCast(Value *V, Type *DestTy,
   1088                        const Twine &Name = "") {
   1089     return CreateCast(Instruction::BitCast, V, DestTy, Name);
   1090   }
   1091   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
   1092                              const Twine &Name = "") {
   1093     if (V->getType() == DestTy)
   1094       return V;
   1095     if (Constant *VC = dyn_cast<Constant>(V))
   1096       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
   1097     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
   1098   }
   1099   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
   1100                              const Twine &Name = "") {
   1101     if (V->getType() == DestTy)
   1102       return V;
   1103     if (Constant *VC = dyn_cast<Constant>(V))
   1104       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
   1105     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
   1106   }
   1107   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
   1108                               const Twine &Name = "") {
   1109     if (V->getType() == DestTy)
   1110       return V;
   1111     if (Constant *VC = dyn_cast<Constant>(V))
   1112       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
   1113     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
   1114   }
   1115   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
   1116                     const Twine &Name = "") {
   1117     if (V->getType() == DestTy)
   1118       return V;
   1119     if (Constant *VC = dyn_cast<Constant>(V))
   1120       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
   1121     return Insert(CastInst::Create(Op, V, DestTy), Name);
   1122   }
   1123   Value *CreatePointerCast(Value *V, Type *DestTy,
   1124                            const Twine &Name = "") {
   1125     if (V->getType() == DestTy)
   1126       return V;
   1127     if (Constant *VC = dyn_cast<Constant>(V))
   1128       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
   1129     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
   1130   }
   1131   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
   1132                        const Twine &Name = "") {
   1133     if (V->getType() == DestTy)
   1134       return V;
   1135     if (Constant *VC = dyn_cast<Constant>(V))
   1136       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
   1137     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
   1138   }
   1139 private:
   1140   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
   1141   // compile time error, instead of converting the string to bool for the
   1142   // isSigned parameter.
   1143   Value *CreateIntCast(Value *, Type *, const char *) LLVM_DELETED_FUNCTION;
   1144 public:
   1145   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
   1146     if (V->getType() == DestTy)
   1147       return V;
   1148     if (Constant *VC = dyn_cast<Constant>(V))
   1149       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
   1150     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
   1151   }
   1152 
   1153   //===--------------------------------------------------------------------===//
   1154   // Instruction creation methods: Compare Instructions
   1155   //===--------------------------------------------------------------------===//
   1156 
   1157   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
   1158     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
   1159   }
   1160   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1161     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
   1162   }
   1163   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
   1164     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
   1165   }
   1166   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1167     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
   1168   }
   1169   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
   1170     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
   1171   }
   1172   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1173     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
   1174   }
   1175   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
   1176     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
   1177   }
   1178   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1179     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
   1180   }
   1181   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
   1182     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
   1183   }
   1184   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1185     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
   1186   }
   1187 
   1188   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
   1189     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
   1190   }
   1191   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
   1192     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
   1193   }
   1194   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1195     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
   1196   }
   1197   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
   1198     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
   1199   }
   1200   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1201     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
   1202   }
   1203   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1204     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
   1205   }
   1206   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
   1207     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
   1208   }
   1209   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
   1210     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
   1211   }
   1212   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
   1213     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
   1214   }
   1215   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
   1216     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
   1217   }
   1218   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1219     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
   1220   }
   1221   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
   1222     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
   1223   }
   1224   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1225     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
   1226   }
   1227   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
   1228     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
   1229   }
   1230 
   1231   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
   1232                     const Twine &Name = "") {
   1233     if (Constant *LC = dyn_cast<Constant>(LHS))
   1234       if (Constant *RC = dyn_cast<Constant>(RHS))
   1235         return Insert(Folder.CreateICmp(P, LC, RC), Name);
   1236     return Insert(new ICmpInst(P, LHS, RHS), Name);
   1237   }
   1238   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
   1239                     const Twine &Name = "") {
   1240     if (Constant *LC = dyn_cast<Constant>(LHS))
   1241       if (Constant *RC = dyn_cast<Constant>(RHS))
   1242         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
   1243     return Insert(new FCmpInst(P, LHS, RHS), Name);
   1244   }
   1245 
   1246   //===--------------------------------------------------------------------===//
   1247   // Instruction creation methods: Other Instructions
   1248   //===--------------------------------------------------------------------===//
   1249 
   1250   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
   1251                      const Twine &Name = "") {
   1252     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
   1253   }
   1254 
   1255   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
   1256     return Insert(CallInst::Create(Callee), Name);
   1257   }
   1258   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
   1259     return Insert(CallInst::Create(Callee, Arg), Name);
   1260   }
   1261   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
   1262                         const Twine &Name = "") {
   1263     Value *Args[] = { Arg1, Arg2 };
   1264     return Insert(CallInst::Create(Callee, Args), Name);
   1265   }
   1266   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
   1267                         const Twine &Name = "") {
   1268     Value *Args[] = { Arg1, Arg2, Arg3 };
   1269     return Insert(CallInst::Create(Callee, Args), Name);
   1270   }
   1271   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
   1272                         Value *Arg4, const Twine &Name = "") {
   1273     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
   1274     return Insert(CallInst::Create(Callee, Args), Name);
   1275   }
   1276   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
   1277                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
   1278     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
   1279     return Insert(CallInst::Create(Callee, Args), Name);
   1280   }
   1281 
   1282   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
   1283                        const Twine &Name = "") {
   1284     return Insert(CallInst::Create(Callee, Args), Name);
   1285   }
   1286 
   1287   Value *CreateSelect(Value *C, Value *True, Value *False,
   1288                       const Twine &Name = "") {
   1289     if (Constant *CC = dyn_cast<Constant>(C))
   1290       if (Constant *TC = dyn_cast<Constant>(True))
   1291         if (Constant *FC = dyn_cast<Constant>(False))
   1292           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
   1293     return Insert(SelectInst::Create(C, True, False), Name);
   1294   }
   1295 
   1296   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
   1297     return Insert(new VAArgInst(List, Ty), Name);
   1298   }
   1299 
   1300   Value *CreateExtractElement(Value *Vec, Value *Idx,
   1301                               const Twine &Name = "") {
   1302     if (Constant *VC = dyn_cast<Constant>(Vec))
   1303       if (Constant *IC = dyn_cast<Constant>(Idx))
   1304         return Insert(Folder.CreateExtractElement(VC, IC), Name);
   1305     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
   1306   }
   1307 
   1308   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
   1309                              const Twine &Name = "") {
   1310     if (Constant *VC = dyn_cast<Constant>(Vec))
   1311       if (Constant *NC = dyn_cast<Constant>(NewElt))
   1312         if (Constant *IC = dyn_cast<Constant>(Idx))
   1313           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
   1314     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
   1315   }
   1316 
   1317   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
   1318                              const Twine &Name = "") {
   1319     if (Constant *V1C = dyn_cast<Constant>(V1))
   1320       if (Constant *V2C = dyn_cast<Constant>(V2))
   1321         if (Constant *MC = dyn_cast<Constant>(Mask))
   1322           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
   1323     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
   1324   }
   1325 
   1326   Value *CreateExtractValue(Value *Agg,
   1327                             ArrayRef<unsigned> Idxs,
   1328                             const Twine &Name = "") {
   1329     if (Constant *AggC = dyn_cast<Constant>(Agg))
   1330       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
   1331     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
   1332   }
   1333 
   1334   Value *CreateInsertValue(Value *Agg, Value *Val,
   1335                            ArrayRef<unsigned> Idxs,
   1336                            const Twine &Name = "") {
   1337     if (Constant *AggC = dyn_cast<Constant>(Agg))
   1338       if (Constant *ValC = dyn_cast<Constant>(Val))
   1339         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
   1340     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
   1341   }
   1342 
   1343   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
   1344                                    const Twine &Name = "") {
   1345     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses), Name);
   1346   }
   1347 
   1348   //===--------------------------------------------------------------------===//
   1349   // Utility creation methods
   1350   //===--------------------------------------------------------------------===//
   1351 
   1352   /// \brief Return an i1 value testing if \p Arg is null.
   1353   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
   1354     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
   1355                         Name);
   1356   }
   1357 
   1358   /// \brief Return an i1 value testing if \p Arg is not null.
   1359   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
   1360     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
   1361                         Name);
   1362   }
   1363 
   1364   /// \brief Return the i64 difference between two pointer values, dividing out
   1365   /// the size of the pointed-to objects.
   1366   ///
   1367   /// This is intended to implement C-style pointer subtraction. As such, the
   1368   /// pointers must be appropriately aligned for their element types and
   1369   /// pointing into the same object.
   1370   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
   1371     assert(LHS->getType() == RHS->getType() &&
   1372            "Pointer subtraction operand types must match!");
   1373     PointerType *ArgType = cast<PointerType>(LHS->getType());
   1374     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
   1375     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
   1376     Value *Difference = CreateSub(LHS_int, RHS_int);
   1377     return CreateExactSDiv(Difference,
   1378                            ConstantExpr::getSizeOf(ArgType->getElementType()),
   1379                            Name);
   1380   }
   1381 
   1382   /// \brief Return a vector value that contains \arg V broadcasted to \p
   1383   /// NumElts elements.
   1384   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
   1385     assert(NumElts > 0 && "Cannot splat to an empty vector!");
   1386 
   1387     // First insert it into an undef vector so we can shuffle it.
   1388     Type *I32Ty = getInt32Ty();
   1389     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
   1390     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
   1391                             Name + ".splatinsert");
   1392 
   1393     // Shuffle the value across the desired number of elements.
   1394     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
   1395     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
   1396   }
   1397 };
   1398 
   1399 }
   1400 
   1401 #endif
   1402