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