LLVM API Documentation

IRBuilder.h
Go to the documentation of this file.
00001 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the IRBuilder class, which is used as a convenient way
00011 // to create LLVM instructions with a consistent and simplified interface.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_IR_IRBUILDER_H
00016 #define LLVM_IR_IRBUILDER_H
00017 
00018 #include "llvm/ADT/ArrayRef.h"
00019 #include "llvm/ADT/StringRef.h"
00020 #include "llvm/ADT/Twine.h"
00021 #include "llvm/IR/BasicBlock.h"
00022 #include "llvm/IR/ConstantFolder.h"
00023 #include "llvm/IR/DataLayout.h"
00024 #include "llvm/IR/Instructions.h"
00025 #include "llvm/IR/LLVMContext.h"
00026 #include "llvm/IR/Operator.h"
00027 #include "llvm/IR/ValueHandle.h"
00028 #include "llvm/Support/CBindingWrapping.h"
00029 
00030 namespace llvm {
00031   class MDNode;
00032 
00033 /// \brief This provides the default implementation of the IRBuilder
00034 /// 'InsertHelper' method that is called whenever an instruction is created by
00035 /// IRBuilder and needs to be inserted.
00036 ///
00037 /// By default, this inserts the instruction at the insertion point.
00038 template <bool preserveNames = true>
00039 class IRBuilderDefaultInserter {
00040 protected:
00041   void InsertHelper(Instruction *I, const Twine &Name,
00042                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
00043     if (BB) BB->getInstList().insert(InsertPt, I);
00044     if (preserveNames)
00045       I->setName(Name);
00046   }
00047 };
00048 
00049 /// \brief Common base class shared among various IRBuilders.
00050 class IRBuilderBase {
00051   DebugLoc CurDbgLocation;
00052 protected:
00053   BasicBlock *BB;
00054   BasicBlock::iterator InsertPt;
00055   LLVMContext &Context;
00056 
00057   MDNode *DefaultFPMathTag;
00058   FastMathFlags FMF;
00059 public:
00060 
00061   IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
00062     : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
00063     ClearInsertionPoint();
00064   }
00065 
00066   //===--------------------------------------------------------------------===//
00067   // Builder configuration methods
00068   //===--------------------------------------------------------------------===//
00069 
00070   /// \brief Clear the insertion point: created instructions will not be
00071   /// inserted into a block.
00072   void ClearInsertionPoint() {
00073     BB = nullptr;
00074     InsertPt = nullptr;
00075   }
00076 
00077   BasicBlock *GetInsertBlock() const { return BB; }
00078   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
00079   LLVMContext &getContext() const { return Context; }
00080 
00081   /// \brief This specifies that created instructions should be appended to the
00082   /// end of the specified block.
00083   void SetInsertPoint(BasicBlock *TheBB) {
00084     BB = TheBB;
00085     InsertPt = BB->end();
00086   }
00087 
00088   /// \brief This specifies that created instructions should be inserted before
00089   /// the specified instruction.
00090   void SetInsertPoint(Instruction *I) {
00091     BB = I->getParent();
00092     InsertPt = I;
00093     assert(I != BB->end() && "Can't read debug loc from end()");
00094     SetCurrentDebugLocation(I->getDebugLoc());
00095   }
00096 
00097   /// \brief This specifies that created instructions should be inserted at the
00098   /// specified point.
00099   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
00100     BB = TheBB;
00101     InsertPt = IP;
00102   }
00103 
00104   /// \brief Find the nearest point that dominates this use, and specify that
00105   /// created instructions should be inserted at this point.
00106   void SetInsertPoint(Use &U) {
00107     Instruction *UseInst = cast<Instruction>(U.getUser());
00108     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
00109       BasicBlock *PredBB = Phi->getIncomingBlock(U);
00110       assert(U != PredBB->getTerminator() && "critical edge not split");
00111       SetInsertPoint(PredBB, PredBB->getTerminator());
00112       return;
00113     }
00114     SetInsertPoint(UseInst);
00115   }
00116 
00117   /// \brief Set location information used by debugging information.
00118   void SetCurrentDebugLocation(const DebugLoc &L) {
00119     CurDbgLocation = L;
00120   }
00121 
00122   /// \brief Get location information used by debugging information.
00123   DebugLoc getCurrentDebugLocation() const { return CurDbgLocation; }
00124 
00125   /// \brief If this builder has a current debug location, set it on the
00126   /// specified instruction.
00127   void SetInstDebugLocation(Instruction *I) const {
00128     if (!CurDbgLocation.isUnknown())
00129       I->setDebugLoc(CurDbgLocation);
00130   }
00131 
00132   /// \brief Get the return type of the current function that we're emitting
00133   /// into.
00134   Type *getCurrentFunctionReturnType() const;
00135 
00136   /// InsertPoint - A saved insertion point.
00137   class InsertPoint {
00138     BasicBlock *Block;
00139     BasicBlock::iterator Point;
00140 
00141   public:
00142     /// \brief Creates a new insertion point which doesn't point to anything.
00143     InsertPoint() : Block(nullptr) {}
00144 
00145     /// \brief Creates a new insertion point at the given location.
00146     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
00147       : Block(InsertBlock), Point(InsertPoint) {}
00148 
00149     /// \brief Returns true if this insert point is set.
00150     bool isSet() const { return (Block != nullptr); }
00151 
00152     llvm::BasicBlock *getBlock() const { return Block; }
00153     llvm::BasicBlock::iterator getPoint() const { return Point; }
00154   };
00155 
00156   /// \brief Returns the current insert point.
00157   InsertPoint saveIP() const {
00158     return InsertPoint(GetInsertBlock(), GetInsertPoint());
00159   }
00160 
00161   /// \brief Returns the current insert point, clearing it in the process.
00162   InsertPoint saveAndClearIP() {
00163     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
00164     ClearInsertionPoint();
00165     return IP;
00166   }
00167 
00168   /// \brief Sets the current insert point to a previously-saved location.
00169   void restoreIP(InsertPoint IP) {
00170     if (IP.isSet())
00171       SetInsertPoint(IP.getBlock(), IP.getPoint());
00172     else
00173       ClearInsertionPoint();
00174   }
00175 
00176   /// \brief Get the floating point math metadata being used.
00177   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
00178 
00179   /// \brief Get the flags to be applied to created floating point ops
00180   FastMathFlags getFastMathFlags() const { return FMF; }
00181 
00182   /// \brief Clear the fast-math flags.
00183   void clearFastMathFlags() { FMF.clear(); }
00184 
00185   /// \brief Set the floating point math metadata to be used.
00186   void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
00187 
00188   /// \brief Set the fast-math flags to be used with generated fp-math operators
00189   void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
00190 
00191   //===--------------------------------------------------------------------===//
00192   // RAII helpers.
00193   //===--------------------------------------------------------------------===//
00194 
00195   // \brief RAII object that stores the current insertion point and restores it
00196   // when the object is destroyed. This includes the debug location.
00197   class InsertPointGuard {
00198     IRBuilderBase &Builder;
00199     AssertingVH<BasicBlock> Block;
00200     BasicBlock::iterator Point;
00201     DebugLoc DbgLoc;
00202 
00203     InsertPointGuard(const InsertPointGuard &) LLVM_DELETED_FUNCTION;
00204     InsertPointGuard &operator=(const InsertPointGuard &) LLVM_DELETED_FUNCTION;
00205 
00206   public:
00207     InsertPointGuard(IRBuilderBase &B)
00208         : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
00209           DbgLoc(B.getCurrentDebugLocation()) {}
00210 
00211     ~InsertPointGuard() {
00212       Builder.restoreIP(InsertPoint(Block, Point));
00213       Builder.SetCurrentDebugLocation(DbgLoc);
00214     }
00215   };
00216 
00217   // \brief RAII object that stores the current fast math settings and restores
00218   // them when the object is destroyed.
00219   class FastMathFlagGuard {
00220     IRBuilderBase &Builder;
00221     FastMathFlags FMF;
00222     MDNode *FPMathTag;
00223 
00224     FastMathFlagGuard(const FastMathFlagGuard &) LLVM_DELETED_FUNCTION;
00225     FastMathFlagGuard &operator=(
00226         const FastMathFlagGuard &) LLVM_DELETED_FUNCTION;
00227 
00228   public:
00229     FastMathFlagGuard(IRBuilderBase &B)
00230         : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
00231 
00232     ~FastMathFlagGuard() {
00233       Builder.FMF = FMF;
00234       Builder.DefaultFPMathTag = FPMathTag;
00235     }
00236   };
00237 
00238   //===--------------------------------------------------------------------===//
00239   // Miscellaneous creation methods.
00240   //===--------------------------------------------------------------------===//
00241 
00242   /// \brief Make a new global variable with initializer type i8*
00243   ///
00244   /// Make a new global variable with an initializer that has array of i8 type
00245   /// filled in with the null terminated string value specified.  The new global
00246   /// variable will be marked mergable with any others of the same contents.  If
00247   /// Name is specified, it is the name of the global variable created.
00248   Value *CreateGlobalString(StringRef Str, const Twine &Name = "");
00249 
00250   /// \brief Get a constant value representing either true or false.
00251   ConstantInt *getInt1(bool V) {
00252     return ConstantInt::get(getInt1Ty(), V);
00253   }
00254 
00255   /// \brief Get the constant value for i1 true.
00256   ConstantInt *getTrue() {
00257     return ConstantInt::getTrue(Context);
00258   }
00259 
00260   /// \brief Get the constant value for i1 false.
00261   ConstantInt *getFalse() {
00262     return ConstantInt::getFalse(Context);
00263   }
00264 
00265   /// \brief Get a constant 8-bit value.
00266   ConstantInt *getInt8(uint8_t C) {
00267     return ConstantInt::get(getInt8Ty(), C);
00268   }
00269 
00270   /// \brief Get a constant 16-bit value.
00271   ConstantInt *getInt16(uint16_t C) {
00272     return ConstantInt::get(getInt16Ty(), C);
00273   }
00274 
00275   /// \brief Get a constant 32-bit value.
00276   ConstantInt *getInt32(uint32_t C) {
00277     return ConstantInt::get(getInt32Ty(), C);
00278   }
00279 
00280   /// \brief Get a constant 64-bit value.
00281   ConstantInt *getInt64(uint64_t C) {
00282     return ConstantInt::get(getInt64Ty(), C);
00283   }
00284 
00285   /// \brief Get a constant N-bit value, zero extended or truncated from
00286   /// a 64-bit value.
00287   ConstantInt *getIntN(unsigned N, uint64_t C) {
00288     return ConstantInt::get(getIntNTy(N), C);
00289   }
00290 
00291   /// \brief Get a constant integer value.
00292   ConstantInt *getInt(const APInt &AI) {
00293     return ConstantInt::get(Context, AI);
00294   }
00295 
00296   //===--------------------------------------------------------------------===//
00297   // Type creation methods
00298   //===--------------------------------------------------------------------===//
00299 
00300   /// \brief Fetch the type representing a single bit
00301   IntegerType *getInt1Ty() {
00302     return Type::getInt1Ty(Context);
00303   }
00304 
00305   /// \brief Fetch the type representing an 8-bit integer.
00306   IntegerType *getInt8Ty() {
00307     return Type::getInt8Ty(Context);
00308   }
00309 
00310   /// \brief Fetch the type representing a 16-bit integer.
00311   IntegerType *getInt16Ty() {
00312     return Type::getInt16Ty(Context);
00313   }
00314 
00315   /// \brief Fetch the type representing a 32-bit integer.
00316   IntegerType *getInt32Ty() {
00317     return Type::getInt32Ty(Context);
00318   }
00319 
00320   /// \brief Fetch the type representing a 64-bit integer.
00321   IntegerType *getInt64Ty() {
00322     return Type::getInt64Ty(Context);
00323   }
00324 
00325   /// \brief Fetch the type representing an N-bit integer.
00326   IntegerType *getIntNTy(unsigned N) {
00327     return Type::getIntNTy(Context, N);
00328   }
00329 
00330   /// \brief Fetch the type representing a 16-bit floating point value.
00331   Type *getHalfTy() {
00332     return Type::getHalfTy(Context);
00333   }
00334 
00335   /// \brief Fetch the type representing a 32-bit floating point value.
00336   Type *getFloatTy() {
00337     return Type::getFloatTy(Context);
00338   }
00339 
00340   /// \brief Fetch the type representing a 64-bit floating point value.
00341   Type *getDoubleTy() {
00342     return Type::getDoubleTy(Context);
00343   }
00344 
00345   /// \brief Fetch the type representing void.
00346   Type *getVoidTy() {
00347     return Type::getVoidTy(Context);
00348   }
00349 
00350   /// \brief Fetch the type representing a pointer to an 8-bit integer value.
00351   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
00352     return Type::getInt8PtrTy(Context, AddrSpace);
00353   }
00354 
00355   /// \brief Fetch the type representing a pointer to an integer value.
00356   IntegerType* getIntPtrTy(const DataLayout *DL, unsigned AddrSpace = 0) {
00357     return DL->getIntPtrType(Context, AddrSpace);
00358   }
00359 
00360   //===--------------------------------------------------------------------===//
00361   // Intrinsic creation methods
00362   //===--------------------------------------------------------------------===//
00363 
00364   /// \brief Create and insert a memset to the specified pointer and the
00365   /// specified value.
00366   ///
00367   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
00368   /// specified, it will be added to the instruction. Likewise with alias.scope
00369   /// and noalias tags.
00370   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
00371                          bool isVolatile = false, MDNode *TBAATag = nullptr,
00372                          MDNode *ScopeTag = nullptr,
00373                          MDNode *NoAliasTag = nullptr) {
00374     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
00375                         TBAATag, ScopeTag, NoAliasTag);
00376   }
00377 
00378   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
00379                          bool isVolatile = false, MDNode *TBAATag = nullptr,
00380                          MDNode *ScopeTag = nullptr,
00381                          MDNode *NoAliasTag = nullptr);
00382 
00383   /// \brief Create and insert a memcpy between the specified pointers.
00384   ///
00385   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
00386   /// specified, it will be added to the instruction. Likewise with alias.scope
00387   /// and noalias tags.
00388   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
00389                          bool isVolatile = false, MDNode *TBAATag = nullptr,
00390                          MDNode *TBAAStructTag = nullptr,
00391                          MDNode *ScopeTag = nullptr,
00392                          MDNode *NoAliasTag = nullptr) {
00393     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
00394                         TBAAStructTag, ScopeTag, NoAliasTag);
00395   }
00396 
00397   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
00398                          bool isVolatile = false, MDNode *TBAATag = nullptr,
00399                          MDNode *TBAAStructTag = nullptr,
00400                          MDNode *ScopeTag = nullptr,
00401                          MDNode *NoAliasTag = nullptr);
00402 
00403   /// \brief Create and insert a memmove between the specified
00404   /// pointers.
00405   ///
00406   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
00407   /// specified, it will be added to the instruction. Likewise with alias.scope
00408   /// and noalias tags.
00409   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
00410                           bool isVolatile = false, MDNode *TBAATag = nullptr,
00411                           MDNode *ScopeTag = nullptr,
00412                           MDNode *NoAliasTag = nullptr) {
00413     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
00414                          TBAATag, ScopeTag, NoAliasTag);
00415   }
00416 
00417   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
00418                           bool isVolatile = false, MDNode *TBAATag = nullptr,
00419                           MDNode *ScopeTag = nullptr,
00420                           MDNode *NoAliasTag = nullptr);
00421 
00422   /// \brief Create a lifetime.start intrinsic.
00423   ///
00424   /// If the pointer isn't i8* it will be converted.
00425   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
00426 
00427   /// \brief Create a lifetime.end intrinsic.
00428   ///
00429   /// If the pointer isn't i8* it will be converted.
00430   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
00431 
00432 private:
00433   Value *getCastedInt8PtrValue(Value *Ptr);
00434 };
00435 
00436 /// \brief This provides a uniform API for creating instructions and inserting
00437 /// them into a basic block: either at the end of a BasicBlock, or at a specific
00438 /// iterator location in a block.
00439 ///
00440 /// Note that the builder does not expose the full generality of LLVM
00441 /// instructions.  For access to extra instruction properties, use the mutators
00442 /// (e.g. setVolatile) on the instructions after they have been
00443 /// created. Convenience state exists to specify fast-math flags and fp-math
00444 /// tags.
00445 ///
00446 /// The first template argument handles whether or not to preserve names in the
00447 /// final instruction output. This defaults to on.  The second template argument
00448 /// specifies a class to use for creating constants.  This defaults to creating
00449 /// minimally folded constants.  The third template argument allows clients to
00450 /// specify custom insertion hooks that are called on every newly created
00451 /// insertion.
00452 template<bool preserveNames = true, typename T = ConstantFolder,
00453          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
00454 class IRBuilder : public IRBuilderBase, public Inserter {
00455   T Folder;
00456 public:
00457   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
00458             MDNode *FPMathTag = nullptr)
00459     : IRBuilderBase(C, FPMathTag), Inserter(I), Folder(F) {
00460   }
00461 
00462   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
00463     : IRBuilderBase(C, FPMathTag), Folder() {
00464   }
00465 
00466   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
00467     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
00468     SetInsertPoint(TheBB);
00469   }
00470 
00471   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
00472     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
00473     SetInsertPoint(TheBB);
00474   }
00475 
00476   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
00477     : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
00478     SetInsertPoint(IP);
00479     SetCurrentDebugLocation(IP->getDebugLoc());
00480   }
00481 
00482   explicit IRBuilder(Use &U, MDNode *FPMathTag = nullptr)
00483     : IRBuilderBase(U->getContext(), FPMathTag), Folder() {
00484     SetInsertPoint(U);
00485     SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
00486   }
00487 
00488   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
00489             MDNode *FPMathTag = nullptr)
00490     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
00491     SetInsertPoint(TheBB, IP);
00492   }
00493 
00494   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
00495             MDNode *FPMathTag = nullptr)
00496     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
00497     SetInsertPoint(TheBB, IP);
00498   }
00499 
00500   /// \brief Get the constant folder being used.
00501   const T &getFolder() { return Folder; }
00502 
00503   /// \brief Return true if this builder is configured to actually add the
00504   /// requested names to IR created through it.
00505   bool isNamePreserving() const { return preserveNames; }
00506 
00507   /// \brief Insert and return the specified instruction.
00508   template<typename InstTy>
00509   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
00510     this->InsertHelper(I, Name, BB, InsertPt);
00511     this->SetInstDebugLocation(I);
00512     return I;
00513   }
00514 
00515   /// \brief No-op overload to handle constants.
00516   Constant *Insert(Constant *C, const Twine& = "") const {
00517     return C;
00518   }
00519 
00520   //===--------------------------------------------------------------------===//
00521   // Instruction creation methods: Terminators
00522   //===--------------------------------------------------------------------===//
00523 
00524 private:
00525   /// \brief Helper to add branch weight metadata onto an instruction.
00526   /// \returns The annotated instruction.
00527   template <typename InstTy>
00528   InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
00529     if (Weights)
00530       I->setMetadata(LLVMContext::MD_prof, Weights);
00531     return I;
00532   }
00533 
00534 public:
00535   /// \brief Create a 'ret void' instruction.
00536   ReturnInst *CreateRetVoid() {
00537     return Insert(ReturnInst::Create(Context));
00538   }
00539 
00540   /// \brief Create a 'ret <val>' instruction.
00541   ReturnInst *CreateRet(Value *V) {
00542     return Insert(ReturnInst::Create(Context, V));
00543   }
00544 
00545   /// \brief Create a sequence of N insertvalue instructions,
00546   /// with one Value from the retVals array each, that build a aggregate
00547   /// return value one value at a time, and a ret instruction to return
00548   /// the resulting aggregate value.
00549   ///
00550   /// This is a convenience function for code that uses aggregate return values
00551   /// as a vehicle for having multiple return values.
00552   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
00553     Value *V = UndefValue::get(getCurrentFunctionReturnType());
00554     for (unsigned i = 0; i != N; ++i)
00555       V = CreateInsertValue(V, retVals[i], i, "mrv");
00556     return Insert(ReturnInst::Create(Context, V));
00557   }
00558 
00559   /// \brief Create an unconditional 'br label X' instruction.
00560   BranchInst *CreateBr(BasicBlock *Dest) {
00561     return Insert(BranchInst::Create(Dest));
00562   }
00563 
00564   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
00565   /// instruction.
00566   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
00567                            MDNode *BranchWeights = nullptr) {
00568     return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
00569                                    BranchWeights));
00570   }
00571 
00572   /// \brief Create a switch instruction with the specified value, default dest,
00573   /// and with a hint for the number of cases that will be added (for efficient
00574   /// allocation).
00575   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
00576                            MDNode *BranchWeights = nullptr) {
00577     return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
00578                                    BranchWeights));
00579   }
00580 
00581   /// \brief Create an indirect branch instruction with the specified address
00582   /// operand, with an optional hint for the number of destinations that will be
00583   /// added (for efficient allocation).
00584   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
00585     return Insert(IndirectBrInst::Create(Addr, NumDests));
00586   }
00587 
00588   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
00589                            BasicBlock *UnwindDest, const Twine &Name = "") {
00590     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
00591                   Name);
00592   }
00593   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
00594                            BasicBlock *UnwindDest, Value *Arg1,
00595                            const Twine &Name = "") {
00596     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
00597                   Name);
00598   }
00599   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
00600                             BasicBlock *UnwindDest, Value *Arg1,
00601                             Value *Arg2, Value *Arg3,
00602                             const Twine &Name = "") {
00603     Value *Args[] = { Arg1, Arg2, Arg3 };
00604     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
00605                   Name);
00606   }
00607   /// \brief Create an invoke instruction.
00608   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
00609                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
00610                            const Twine &Name = "") {
00611     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
00612                   Name);
00613   }
00614 
00615   ResumeInst *CreateResume(Value *Exn) {
00616     return Insert(ResumeInst::Create(Exn));
00617   }
00618 
00619   UnreachableInst *CreateUnreachable() {
00620     return Insert(new UnreachableInst(Context));
00621   }
00622 
00623   //===--------------------------------------------------------------------===//
00624   // Instruction creation methods: Binary Operators
00625   //===--------------------------------------------------------------------===//
00626 private:
00627   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
00628                                           Value *LHS, Value *RHS,
00629                                           const Twine &Name,
00630                                           bool HasNUW, bool HasNSW) {
00631     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
00632     if (HasNUW) BO->setHasNoUnsignedWrap();
00633     if (HasNSW) BO->setHasNoSignedWrap();
00634     return BO;
00635   }
00636 
00637   Instruction *AddFPMathAttributes(Instruction *I,
00638                                    MDNode *FPMathTag,
00639                                    FastMathFlags FMF) const {
00640     if (!FPMathTag)
00641       FPMathTag = DefaultFPMathTag;
00642     if (FPMathTag)
00643       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
00644     I->setFastMathFlags(FMF);
00645     return I;
00646   }
00647 public:
00648   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
00649                    bool HasNUW = false, bool HasNSW = false) {
00650     if (Constant *LC = dyn_cast<Constant>(LHS))
00651       if (Constant *RC = dyn_cast<Constant>(RHS))
00652         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
00653     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
00654                                    HasNUW, HasNSW);
00655   }
00656   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
00657     return CreateAdd(LHS, RHS, Name, false, true);
00658   }
00659   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
00660     return CreateAdd(LHS, RHS, Name, true, false);
00661   }
00662   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
00663                     MDNode *FPMathTag = nullptr) {
00664     if (Constant *LC = dyn_cast<Constant>(LHS))
00665       if (Constant *RC = dyn_cast<Constant>(RHS))
00666         return Insert(Folder.CreateFAdd(LC, RC), Name);
00667     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
00668                                       FPMathTag, FMF), Name);
00669   }
00670   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
00671                    bool HasNUW = false, bool HasNSW = false) {
00672     if (Constant *LC = dyn_cast<Constant>(LHS))
00673       if (Constant *RC = dyn_cast<Constant>(RHS))
00674         return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
00675     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
00676                                    HasNUW, HasNSW);
00677   }
00678   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
00679     return CreateSub(LHS, RHS, Name, false, true);
00680   }
00681   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
00682     return CreateSub(LHS, RHS, Name, true, false);
00683   }
00684   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
00685                     MDNode *FPMathTag = nullptr) {
00686     if (Constant *LC = dyn_cast<Constant>(LHS))
00687       if (Constant *RC = dyn_cast<Constant>(RHS))
00688         return Insert(Folder.CreateFSub(LC, RC), Name);
00689     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
00690                                       FPMathTag, FMF), Name);
00691   }
00692   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
00693                    bool HasNUW = false, bool HasNSW = false) {
00694     if (Constant *LC = dyn_cast<Constant>(LHS))
00695       if (Constant *RC = dyn_cast<Constant>(RHS))
00696         return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
00697     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
00698                                    HasNUW, HasNSW);
00699   }
00700   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
00701     return CreateMul(LHS, RHS, Name, false, true);
00702   }
00703   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
00704     return CreateMul(LHS, RHS, Name, true, false);
00705   }
00706   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
00707                     MDNode *FPMathTag = nullptr) {
00708     if (Constant *LC = dyn_cast<Constant>(LHS))
00709       if (Constant *RC = dyn_cast<Constant>(RHS))
00710         return Insert(Folder.CreateFMul(LC, RC), Name);
00711     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
00712                                       FPMathTag, FMF), Name);
00713   }
00714   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
00715                     bool isExact = false) {
00716     if (Constant *LC = dyn_cast<Constant>(LHS))
00717       if (Constant *RC = dyn_cast<Constant>(RHS))
00718         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
00719     if (!isExact)
00720       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
00721     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
00722   }
00723   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
00724     return CreateUDiv(LHS, RHS, Name, true);
00725   }
00726   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
00727                     bool isExact = false) {
00728     if (Constant *LC = dyn_cast<Constant>(LHS))
00729       if (Constant *RC = dyn_cast<Constant>(RHS))
00730         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
00731     if (!isExact)
00732       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
00733     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
00734   }
00735   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
00736     return CreateSDiv(LHS, RHS, Name, true);
00737   }
00738   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
00739                     MDNode *FPMathTag = nullptr) {
00740     if (Constant *LC = dyn_cast<Constant>(LHS))
00741       if (Constant *RC = dyn_cast<Constant>(RHS))
00742         return Insert(Folder.CreateFDiv(LC, RC), Name);
00743     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
00744                                       FPMathTag, FMF), Name);
00745   }
00746   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
00747     if (Constant *LC = dyn_cast<Constant>(LHS))
00748       if (Constant *RC = dyn_cast<Constant>(RHS))
00749         return Insert(Folder.CreateURem(LC, RC), Name);
00750     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
00751   }
00752   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
00753     if (Constant *LC = dyn_cast<Constant>(LHS))
00754       if (Constant *RC = dyn_cast<Constant>(RHS))
00755         return Insert(Folder.CreateSRem(LC, RC), Name);
00756     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
00757   }
00758   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
00759                     MDNode *FPMathTag = nullptr) {
00760     if (Constant *LC = dyn_cast<Constant>(LHS))
00761       if (Constant *RC = dyn_cast<Constant>(RHS))
00762         return Insert(Folder.CreateFRem(LC, RC), Name);
00763     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
00764                                       FPMathTag, FMF), Name);
00765   }
00766 
00767   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
00768                    bool HasNUW = false, bool HasNSW = false) {
00769     if (Constant *LC = dyn_cast<Constant>(LHS))
00770       if (Constant *RC = dyn_cast<Constant>(RHS))
00771         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
00772     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
00773                                    HasNUW, HasNSW);
00774   }
00775   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
00776                    bool HasNUW = false, bool HasNSW = false) {
00777     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
00778                      HasNUW, HasNSW);
00779   }
00780   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
00781                    bool HasNUW = false, bool HasNSW = false) {
00782     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
00783                      HasNUW, HasNSW);
00784   }
00785 
00786   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
00787                     bool isExact = false) {
00788     if (Constant *LC = dyn_cast<Constant>(LHS))
00789       if (Constant *RC = dyn_cast<Constant>(RHS))
00790         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
00791     if (!isExact)
00792       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
00793     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
00794   }
00795   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
00796                     bool isExact = false) {
00797     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
00798   }
00799   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
00800                     bool isExact = false) {
00801     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
00802   }
00803 
00804   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
00805                     bool isExact = false) {
00806     if (Constant *LC = dyn_cast<Constant>(LHS))
00807       if (Constant *RC = dyn_cast<Constant>(RHS))
00808         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
00809     if (!isExact)
00810       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
00811     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
00812   }
00813   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
00814                     bool isExact = false) {
00815     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
00816   }
00817   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
00818                     bool isExact = false) {
00819     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
00820   }
00821 
00822   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
00823     if (Constant *RC = dyn_cast<Constant>(RHS)) {
00824       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
00825         return LHS;  // LHS & -1 -> LHS
00826       if (Constant *LC = dyn_cast<Constant>(LHS))
00827         return Insert(Folder.CreateAnd(LC, RC), Name);
00828     }
00829     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
00830   }
00831   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
00832     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00833   }
00834   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
00835     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00836   }
00837 
00838   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
00839     if (Constant *RC = dyn_cast<Constant>(RHS)) {
00840       if (RC->isNullValue())
00841         return LHS;  // LHS | 0 -> LHS
00842       if (Constant *LC = dyn_cast<Constant>(LHS))
00843         return Insert(Folder.CreateOr(LC, RC), Name);
00844     }
00845     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
00846   }
00847   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
00848     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00849   }
00850   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
00851     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00852   }
00853 
00854   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
00855     if (Constant *LC = dyn_cast<Constant>(LHS))
00856       if (Constant *RC = dyn_cast<Constant>(RHS))
00857         return Insert(Folder.CreateXor(LC, RC), Name);
00858     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
00859   }
00860   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
00861     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00862   }
00863   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
00864     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
00865   }
00866 
00867   Value *CreateBinOp(Instruction::BinaryOps Opc,
00868                      Value *LHS, Value *RHS, const Twine &Name = "",
00869                      MDNode *FPMathTag = nullptr) {
00870     if (Constant *LC = dyn_cast<Constant>(LHS))
00871       if (Constant *RC = dyn_cast<Constant>(RHS))
00872         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
00873     llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
00874     if (isa<FPMathOperator>(BinOp))
00875       BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
00876     return Insert(BinOp, Name);
00877   }
00878 
00879   Value *CreateNeg(Value *V, const Twine &Name = "",
00880                    bool HasNUW = false, bool HasNSW = false) {
00881     if (Constant *VC = dyn_cast<Constant>(V))
00882       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
00883     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
00884     if (HasNUW) BO->setHasNoUnsignedWrap();
00885     if (HasNSW) BO->setHasNoSignedWrap();
00886     return BO;
00887   }
00888   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
00889     return CreateNeg(V, Name, false, true);
00890   }
00891   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
00892     return CreateNeg(V, Name, true, false);
00893   }
00894   Value *CreateFNeg(Value *V, const Twine &Name = "",
00895                     MDNode *FPMathTag = nullptr) {
00896     if (Constant *VC = dyn_cast<Constant>(V))
00897       return Insert(Folder.CreateFNeg(VC), Name);
00898     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
00899                                       FPMathTag, FMF), Name);
00900   }
00901   Value *CreateNot(Value *V, const Twine &Name = "") {
00902     if (Constant *VC = dyn_cast<Constant>(V))
00903       return Insert(Folder.CreateNot(VC), Name);
00904     return Insert(BinaryOperator::CreateNot(V), Name);
00905   }
00906 
00907   //===--------------------------------------------------------------------===//
00908   // Instruction creation methods: Memory Instructions
00909   //===--------------------------------------------------------------------===//
00910 
00911   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
00912                            const Twine &Name = "") {
00913     return Insert(new AllocaInst(Ty, ArraySize), Name);
00914   }
00915   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
00916   // converting the string to 'bool' for the isVolatile parameter.
00917   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
00918     return Insert(new LoadInst(Ptr), Name);
00919   }
00920   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
00921     return Insert(new LoadInst(Ptr), Name);
00922   }
00923   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
00924     return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
00925   }
00926   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
00927     return Insert(new StoreInst(Val, Ptr, isVolatile));
00928   }
00929   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
00930   // correctly, instead of converting the string to 'bool' for the isVolatile
00931   // parameter.
00932   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
00933     LoadInst *LI = CreateLoad(Ptr, Name);
00934     LI->setAlignment(Align);
00935     return LI;
00936   }
00937   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
00938                               const Twine &Name = "") {
00939     LoadInst *LI = CreateLoad(Ptr, Name);
00940     LI->setAlignment(Align);
00941     return LI;
00942   }
00943   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
00944                               const Twine &Name = "") {
00945     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
00946     LI->setAlignment(Align);
00947     return LI;
00948   }
00949   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
00950                                 bool isVolatile = false) {
00951     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
00952     SI->setAlignment(Align);
00953     return SI;
00954   }
00955   FenceInst *CreateFence(AtomicOrdering Ordering,
00956                          SynchronizationScope SynchScope = CrossThread,
00957                          const Twine &Name = "") {
00958     return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
00959   }
00960   AtomicCmpXchgInst *
00961   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
00962                       AtomicOrdering SuccessOrdering,
00963                       AtomicOrdering FailureOrdering,
00964                       SynchronizationScope SynchScope = CrossThread) {
00965     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
00966                                         FailureOrdering, SynchScope));
00967   }
00968   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
00969                                  AtomicOrdering Ordering,
00970                                SynchronizationScope SynchScope = CrossThread) {
00971     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
00972   }
00973   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
00974                    const Twine &Name = "") {
00975     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
00976       // Every index must be constant.
00977       size_t i, e;
00978       for (i = 0, e = IdxList.size(); i != e; ++i)
00979         if (!isa<Constant>(IdxList[i]))
00980           break;
00981       if (i == e)
00982         return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
00983     }
00984     return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
00985   }
00986   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
00987                            const Twine &Name = "") {
00988     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
00989       // Every index must be constant.
00990       size_t i, e;
00991       for (i = 0, e = IdxList.size(); i != e; ++i)
00992         if (!isa<Constant>(IdxList[i]))
00993           break;
00994       if (i == e)
00995         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
00996     }
00997     return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
00998   }
00999   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
01000     if (Constant *PC = dyn_cast<Constant>(Ptr))
01001       if (Constant *IC = dyn_cast<Constant>(Idx))
01002         return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
01003     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
01004   }
01005   Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
01006     if (Constant *PC = dyn_cast<Constant>(Ptr))
01007       if (Constant *IC = dyn_cast<Constant>(Idx))
01008         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
01009     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
01010   }
01011   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
01012     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
01013 
01014     if (Constant *PC = dyn_cast<Constant>(Ptr))
01015       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
01016 
01017     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
01018   }
01019   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
01020                                     const Twine &Name = "") {
01021     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
01022 
01023     if (Constant *PC = dyn_cast<Constant>(Ptr))
01024       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
01025 
01026     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
01027   }
01028   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
01029                     const Twine &Name = "") {
01030     Value *Idxs[] = {
01031       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
01032       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
01033     };
01034 
01035     if (Constant *PC = dyn_cast<Constant>(Ptr))
01036       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
01037 
01038     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
01039   }
01040   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
01041                                     const Twine &Name = "") {
01042     Value *Idxs[] = {
01043       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
01044       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
01045     };
01046 
01047     if (Constant *PC = dyn_cast<Constant>(Ptr))
01048       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
01049 
01050     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
01051   }
01052   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
01053     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
01054 
01055     if (Constant *PC = dyn_cast<Constant>(Ptr))
01056       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
01057 
01058     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
01059   }
01060   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
01061                                     const Twine &Name = "") {
01062     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
01063 
01064     if (Constant *PC = dyn_cast<Constant>(Ptr))
01065       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
01066 
01067     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
01068   }
01069   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
01070                     const Twine &Name = "") {
01071     Value *Idxs[] = {
01072       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
01073       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
01074     };
01075 
01076     if (Constant *PC = dyn_cast<Constant>(Ptr))
01077       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
01078 
01079     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
01080   }
01081   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
01082                                     const Twine &Name = "") {
01083     Value *Idxs[] = {
01084       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
01085       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
01086     };
01087 
01088     if (Constant *PC = dyn_cast<Constant>(Ptr))
01089       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
01090 
01091     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
01092   }
01093   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
01094     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
01095   }
01096 
01097   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
01098   /// instead of a pointer to array of i8.
01099   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
01100     Value *gv = CreateGlobalString(Str, Name);
01101     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
01102     Value *Args[] = { zero, zero };
01103     return CreateInBoundsGEP(gv, Args, Name);
01104   }
01105 
01106   //===--------------------------------------------------------------------===//
01107   // Instruction creation methods: Cast/Conversion Operators
01108   //===--------------------------------------------------------------------===//
01109 
01110   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
01111     return CreateCast(Instruction::Trunc, V, DestTy, Name);
01112   }
01113   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
01114     return CreateCast(Instruction::ZExt, V, DestTy, Name);
01115   }
01116   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
01117     return CreateCast(Instruction::SExt, V, DestTy, Name);
01118   }
01119   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
01120   /// the value untouched if the type of V is already DestTy.
01121   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
01122                            const Twine &Name = "") {
01123     assert(V->getType()->isIntOrIntVectorTy() &&
01124            DestTy->isIntOrIntVectorTy() &&
01125            "Can only zero extend/truncate integers!");
01126     Type *VTy = V->getType();
01127     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
01128       return CreateZExt(V, DestTy, Name);
01129     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
01130       return CreateTrunc(V, DestTy, Name);
01131     return V;
01132   }
01133   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
01134   /// the value untouched if the type of V is already DestTy.
01135   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
01136                            const Twine &Name = "") {
01137     assert(V->getType()->isIntOrIntVectorTy() &&
01138            DestTy->isIntOrIntVectorTy() &&
01139            "Can only sign extend/truncate integers!");
01140     Type *VTy = V->getType();
01141     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
01142       return CreateSExt(V, DestTy, Name);
01143     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
01144       return CreateTrunc(V, DestTy, Name);
01145     return V;
01146   }
01147   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
01148     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
01149   }
01150   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
01151     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
01152   }
01153   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
01154     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
01155   }
01156   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
01157     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
01158   }
01159   Value *CreateFPTrunc(Value *V, Type *DestTy,
01160                        const Twine &Name = "") {
01161     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
01162   }
01163   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
01164     return CreateCast(Instruction::FPExt, V, DestTy, Name);
01165   }
01166   Value *CreatePtrToInt(Value *V, Type *DestTy,
01167                         const Twine &Name = "") {
01168     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
01169   }
01170   Value *CreateIntToPtr(Value *V, Type *DestTy,
01171                         const Twine &Name = "") {
01172     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
01173   }
01174   Value *CreateBitCast(Value *V, Type *DestTy,
01175                        const Twine &Name = "") {
01176     return CreateCast(Instruction::BitCast, V, DestTy, Name);
01177   }
01178   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
01179                              const Twine &Name = "") {
01180     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
01181   }
01182   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
01183                              const Twine &Name = "") {
01184     if (V->getType() == DestTy)
01185       return V;
01186     if (Constant *VC = dyn_cast<Constant>(V))
01187       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
01188     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
01189   }
01190   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
01191                              const Twine &Name = "") {
01192     if (V->getType() == DestTy)
01193       return V;
01194     if (Constant *VC = dyn_cast<Constant>(V))
01195       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
01196     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
01197   }
01198   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
01199                               const Twine &Name = "") {
01200     if (V->getType() == DestTy)
01201       return V;
01202     if (Constant *VC = dyn_cast<Constant>(V))
01203       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
01204     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
01205   }
01206   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
01207                     const Twine &Name = "") {
01208     if (V->getType() == DestTy)
01209       return V;
01210     if (Constant *VC = dyn_cast<Constant>(V))
01211       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
01212     return Insert(CastInst::Create(Op, V, DestTy), Name);
01213   }
01214   Value *CreatePointerCast(Value *V, Type *DestTy,
01215                            const Twine &Name = "") {
01216     if (V->getType() == DestTy)
01217       return V;
01218     if (Constant *VC = dyn_cast<Constant>(V))
01219       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
01220     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
01221   }
01222 
01223   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
01224                                              const Twine &Name = "") {
01225     if (V->getType() == DestTy)
01226       return V;
01227 
01228     if (Constant *VC = dyn_cast<Constant>(V)) {
01229       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
01230                     Name);
01231     }
01232 
01233     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
01234                   Name);
01235   }
01236 
01237   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
01238                        const Twine &Name = "") {
01239     if (V->getType() == DestTy)
01240       return V;
01241     if (Constant *VC = dyn_cast<Constant>(V))
01242       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
01243     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
01244   }
01245 private:
01246   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
01247   // compile time error, instead of converting the string to bool for the
01248   // isSigned parameter.
01249   Value *CreateIntCast(Value *, Type *, const char *) LLVM_DELETED_FUNCTION;
01250 public:
01251   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
01252     if (V->getType() == DestTy)
01253       return V;
01254     if (Constant *VC = dyn_cast<Constant>(V))
01255       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
01256     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
01257   }
01258 
01259   //===--------------------------------------------------------------------===//
01260   // Instruction creation methods: Compare Instructions
01261   //===--------------------------------------------------------------------===//
01262 
01263   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
01264     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
01265   }
01266   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
01267     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
01268   }
01269   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
01270     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
01271   }
01272   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
01273     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
01274   }
01275   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
01276     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
01277   }
01278   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
01279     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
01280   }
01281   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
01282     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
01283   }
01284   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
01285     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
01286   }
01287   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
01288     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
01289   }
01290   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
01291     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
01292   }
01293 
01294   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
01295     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
01296   }
01297   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
01298     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
01299   }
01300   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
01301     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
01302   }
01303   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
01304     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
01305   }
01306   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
01307     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
01308   }
01309   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
01310     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
01311   }
01312   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
01313     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
01314   }
01315   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
01316     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
01317   }
01318   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
01319     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
01320   }
01321   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
01322     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
01323   }
01324   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
01325     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
01326   }
01327   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
01328     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
01329   }
01330   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
01331     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
01332   }
01333   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
01334     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
01335   }
01336 
01337   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
01338                     const Twine &Name = "") {
01339     if (Constant *LC = dyn_cast<Constant>(LHS))
01340       if (Constant *RC = dyn_cast<Constant>(RHS))
01341         return Insert(Folder.CreateICmp(P, LC, RC), Name);
01342     return Insert(new ICmpInst(P, LHS, RHS), Name);
01343   }
01344   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
01345                     const Twine &Name = "") {
01346     if (Constant *LC = dyn_cast<Constant>(LHS))
01347       if (Constant *RC = dyn_cast<Constant>(RHS))
01348         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
01349     return Insert(new FCmpInst(P, LHS, RHS), Name);
01350   }
01351 
01352   //===--------------------------------------------------------------------===//
01353   // Instruction creation methods: Other Instructions
01354   //===--------------------------------------------------------------------===//
01355 
01356   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
01357                      const Twine &Name = "") {
01358     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
01359   }
01360 
01361   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
01362     return Insert(CallInst::Create(Callee), Name);
01363   }
01364   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
01365     return Insert(CallInst::Create(Callee, Arg), Name);
01366   }
01367   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
01368                         const Twine &Name = "") {
01369     Value *Args[] = { Arg1, Arg2 };
01370     return Insert(CallInst::Create(Callee, Args), Name);
01371   }
01372   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
01373                         const Twine &Name = "") {
01374     Value *Args[] = { Arg1, Arg2, Arg3 };
01375     return Insert(CallInst::Create(Callee, Args), Name);
01376   }
01377   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
01378                         Value *Arg4, const Twine &Name = "") {
01379     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
01380     return Insert(CallInst::Create(Callee, Args), Name);
01381   }
01382   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
01383                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
01384     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
01385     return Insert(CallInst::Create(Callee, Args), Name);
01386   }
01387 
01388   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
01389                        const Twine &Name = "") {
01390     return Insert(CallInst::Create(Callee, Args), Name);
01391   }
01392 
01393   Value *CreateSelect(Value *C, Value *True, Value *False,
01394                       const Twine &Name = "") {
01395     if (Constant *CC = dyn_cast<Constant>(C))
01396       if (Constant *TC = dyn_cast<Constant>(True))
01397         if (Constant *FC = dyn_cast<Constant>(False))
01398           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
01399     return Insert(SelectInst::Create(C, True, False), Name);
01400   }
01401 
01402   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
01403     return Insert(new VAArgInst(List, Ty), Name);
01404   }
01405 
01406   Value *CreateExtractElement(Value *Vec, Value *Idx,
01407                               const Twine &Name = "") {
01408     if (Constant *VC = dyn_cast<Constant>(Vec))
01409       if (Constant *IC = dyn_cast<Constant>(Idx))
01410         return Insert(Folder.CreateExtractElement(VC, IC), Name);
01411     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
01412   }
01413 
01414   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
01415                              const Twine &Name = "") {
01416     if (Constant *VC = dyn_cast<Constant>(Vec))
01417       if (Constant *NC = dyn_cast<Constant>(NewElt))
01418         if (Constant *IC = dyn_cast<Constant>(Idx))
01419           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
01420     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
01421   }
01422 
01423   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
01424                              const Twine &Name = "") {
01425     if (Constant *V1C = dyn_cast<Constant>(V1))
01426       if (Constant *V2C = dyn_cast<Constant>(V2))
01427         if (Constant *MC = dyn_cast<Constant>(Mask))
01428           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
01429     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
01430   }
01431 
01432   Value *CreateExtractValue(Value *Agg,
01433                             ArrayRef<unsigned> Idxs,
01434                             const Twine &Name = "") {
01435     if (Constant *AggC = dyn_cast<Constant>(Agg))
01436       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
01437     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
01438   }
01439 
01440   Value *CreateInsertValue(Value *Agg, Value *Val,
01441                            ArrayRef<unsigned> Idxs,
01442                            const Twine &Name = "") {
01443     if (Constant *AggC = dyn_cast<Constant>(Agg))
01444       if (Constant *ValC = dyn_cast<Constant>(Val))
01445         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
01446     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
01447   }
01448 
01449   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
01450                                    const Twine &Name = "") {
01451     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses), Name);
01452   }
01453 
01454   //===--------------------------------------------------------------------===//
01455   // Utility creation methods
01456   //===--------------------------------------------------------------------===//
01457 
01458   /// \brief Return an i1 value testing if \p Arg is null.
01459   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
01460     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
01461                         Name);
01462   }
01463 
01464   /// \brief Return an i1 value testing if \p Arg is not null.
01465   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
01466     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
01467                         Name);
01468   }
01469 
01470   /// \brief Return the i64 difference between two pointer values, dividing out
01471   /// the size of the pointed-to objects.
01472   ///
01473   /// This is intended to implement C-style pointer subtraction. As such, the
01474   /// pointers must be appropriately aligned for their element types and
01475   /// pointing into the same object.
01476   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
01477     assert(LHS->getType() == RHS->getType() &&
01478            "Pointer subtraction operand types must match!");
01479     PointerType *ArgType = cast<PointerType>(LHS->getType());
01480     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
01481     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
01482     Value *Difference = CreateSub(LHS_int, RHS_int);
01483     return CreateExactSDiv(Difference,
01484                            ConstantExpr::getSizeOf(ArgType->getElementType()),
01485                            Name);
01486   }
01487 
01488   /// \brief Return a vector value that contains \arg V broadcasted to \p
01489   /// NumElts elements.
01490   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
01491     assert(NumElts > 0 && "Cannot splat to an empty vector!");
01492 
01493     // First insert it into an undef vector so we can shuffle it.
01494     Type *I32Ty = getInt32Ty();
01495     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
01496     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
01497                             Name + ".splatinsert");
01498 
01499     // Shuffle the value across the desired number of elements.
01500     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
01501     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
01502   }
01503 
01504   /// \brief Return a value that has been extracted from a larger integer type.
01505   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
01506                               IntegerType *ExtractedTy, uint64_t Offset,
01507                               const Twine &Name) {
01508     IntegerType *IntTy = cast<IntegerType>(From->getType());
01509     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
01510                DL.getTypeStoreSize(IntTy) &&
01511            "Element extends past full value");
01512     uint64_t ShAmt = 8 * Offset;
01513     Value *V = From;
01514     if (DL.isBigEndian())
01515       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
01516                    DL.getTypeStoreSize(ExtractedTy) - Offset);
01517     if (ShAmt) {
01518       V = CreateLShr(V, ShAmt, Name + ".shift");
01519     }
01520     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
01521            "Cannot extract to a larger integer!");
01522     if (ExtractedTy != IntTy) {
01523       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
01524     }
01525     return V;
01526   }
01527 };
01528 
01529 // Create wrappers for C Binding types (see CBindingWrapping.h).
01530 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
01531 
01532 }
01533 
01534 #endif