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