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