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