4936ccb417d1791ce39d180d2f22f25e0c3fe994
[oota-llvm.git] / include / llvm / IR / IRBuilder.h
1 //===---- llvm/IRBuilder.h - Builder for LLVM Instructions ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the IRBuilder class, which is used as a convenient way
11 // to create LLVM instructions with a consistent and simplified interface.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_IR_IRBUILDER_H
16 #define LLVM_IR_IRBUILDER_H
17
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/ConstantFolder.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/CBindingWrapping.h"
32
33 namespace llvm {
34 class MDNode;
35
36 /// \brief This provides the default implementation of the IRBuilder
37 /// 'InsertHelper' method that is called whenever an instruction is created by
38 /// IRBuilder and needs to be inserted.
39 ///
40 /// By default, this inserts the instruction at the insertion point.
41 template <bool preserveNames = true>
42 class IRBuilderDefaultInserter {
43 protected:
44   void InsertHelper(Instruction *I, const Twine &Name,
45                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
46     if (BB) BB->getInstList().insert(InsertPt, I);
47     if (preserveNames)
48       I->setName(Name);
49   }
50 };
51
52 /// \brief Common base class shared among various IRBuilders.
53 class IRBuilderBase {
54   DebugLoc CurDbgLocation;
55
56 protected:
57   BasicBlock *BB;
58   BasicBlock::iterator InsertPt;
59   LLVMContext &Context;
60
61   MDNode *DefaultFPMathTag;
62   FastMathFlags FMF;
63
64 public:
65   IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
66     : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
67     ClearInsertionPoint();
68   }
69
70   //===--------------------------------------------------------------------===//
71   // Builder configuration methods
72   //===--------------------------------------------------------------------===//
73
74   /// \brief Clear the insertion point: created instructions will not be
75   /// inserted into a block.
76   void ClearInsertionPoint() {
77     BB = nullptr;
78     InsertPt.reset(nullptr);
79   }
80
81   BasicBlock *GetInsertBlock() const { return BB; }
82   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
83   LLVMContext &getContext() const { return Context; }
84
85   /// \brief This specifies that created instructions should be appended to the
86   /// end of the specified block.
87   void SetInsertPoint(BasicBlock *TheBB) {
88     BB = TheBB;
89     InsertPt = BB->end();
90   }
91
92   /// \brief This specifies that created instructions should be inserted before
93   /// the specified instruction.
94   void SetInsertPoint(Instruction *I) {
95     BB = I->getParent();
96     InsertPt = I->getIterator();
97     assert(InsertPt != BB->end() && "Can't read debug loc from end()");
98     SetCurrentDebugLocation(I->getDebugLoc());
99   }
100
101   /// \brief This specifies that created instructions should be inserted at the
102   /// specified point.
103   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
104     BB = TheBB;
105     InsertPt = IP;
106     if (IP != TheBB->end())
107       SetCurrentDebugLocation(IP->getDebugLoc());
108   }
109
110   /// \brief Set location information used by debugging information.
111   void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
112
113   /// \brief Get location information used by debugging information.
114   const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
115
116   /// \brief If this builder has a current debug location, set it on the
117   /// specified instruction.
118   void SetInstDebugLocation(Instruction *I) const {
119     if (CurDbgLocation)
120       I->setDebugLoc(CurDbgLocation);
121   }
122
123   /// \brief Get the return type of the current function that we're emitting
124   /// into.
125   Type *getCurrentFunctionReturnType() const;
126
127   /// InsertPoint - A saved insertion point.
128   class InsertPoint {
129     BasicBlock *Block;
130     BasicBlock::iterator Point;
131
132   public:
133     /// \brief Creates a new insertion point which doesn't point to anything.
134     InsertPoint() : Block(nullptr) {}
135
136     /// \brief Creates a new insertion point at the given location.
137     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
138       : Block(InsertBlock), Point(InsertPoint) {}
139
140     /// \brief Returns true if this insert point is set.
141     bool isSet() const { return (Block != nullptr); }
142
143     llvm::BasicBlock *getBlock() const { return Block; }
144     llvm::BasicBlock::iterator getPoint() const { return Point; }
145   };
146
147   /// \brief Returns the current insert point.
148   InsertPoint saveIP() const {
149     return InsertPoint(GetInsertBlock(), GetInsertPoint());
150   }
151
152   /// \brief Returns the current insert point, clearing it in the process.
153   InsertPoint saveAndClearIP() {
154     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
155     ClearInsertionPoint();
156     return IP;
157   }
158
159   /// \brief Sets the current insert point to a previously-saved location.
160   void restoreIP(InsertPoint IP) {
161     if (IP.isSet())
162       SetInsertPoint(IP.getBlock(), IP.getPoint());
163     else
164       ClearInsertionPoint();
165   }
166
167   /// \brief Get the floating point math metadata being used.
168   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
169
170   /// \brief Get the flags to be applied to created floating point ops
171   FastMathFlags getFastMathFlags() const { return FMF; }
172
173   /// \brief Clear the fast-math flags.
174   void clearFastMathFlags() { FMF.clear(); }
175
176   /// \brief Set the floating point math metadata to be used.
177   void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
178
179   /// \brief Set the fast-math flags to be used with generated fp-math operators
180   void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
181
182   //===--------------------------------------------------------------------===//
183   // RAII helpers.
184   //===--------------------------------------------------------------------===//
185
186   // \brief RAII object that stores the current insertion point and restores it
187   // when the object is destroyed. This includes the debug location.
188   class InsertPointGuard {
189     IRBuilderBase &Builder;
190     AssertingVH<BasicBlock> Block;
191     BasicBlock::iterator Point;
192     DebugLoc DbgLoc;
193
194     InsertPointGuard(const InsertPointGuard &) = delete;
195     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
196
197   public:
198     InsertPointGuard(IRBuilderBase &B)
199         : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
200           DbgLoc(B.getCurrentDebugLocation()) {}
201
202     ~InsertPointGuard() {
203       Builder.restoreIP(InsertPoint(Block, Point));
204       Builder.SetCurrentDebugLocation(DbgLoc);
205     }
206   };
207
208   // \brief RAII object that stores the current fast math settings and restores
209   // them when the object is destroyed.
210   class FastMathFlagGuard {
211     IRBuilderBase &Builder;
212     FastMathFlags FMF;
213     MDNode *FPMathTag;
214
215     FastMathFlagGuard(const FastMathFlagGuard &) = delete;
216     FastMathFlagGuard &operator=(
217         const FastMathFlagGuard &) = delete;
218
219   public:
220     FastMathFlagGuard(IRBuilderBase &B)
221         : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
222
223     ~FastMathFlagGuard() {
224       Builder.FMF = FMF;
225       Builder.DefaultFPMathTag = FPMathTag;
226     }
227   };
228
229   //===--------------------------------------------------------------------===//
230   // Miscellaneous creation methods.
231   //===--------------------------------------------------------------------===//
232
233   /// \brief Make a new global variable with initializer type i8*
234   ///
235   /// Make a new global variable with an initializer that has array of i8 type
236   /// filled in with the null terminated string value specified.  The new global
237   /// variable will be marked mergable with any others of the same contents.  If
238   /// Name is specified, it is the name of the global variable created.
239   GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
240                                      unsigned AddressSpace = 0);
241
242   /// \brief Get a constant value representing either true or false.
243   ConstantInt *getInt1(bool V) {
244     return ConstantInt::get(getInt1Ty(), V);
245   }
246
247   /// \brief Get the constant value for i1 true.
248   ConstantInt *getTrue() {
249     return ConstantInt::getTrue(Context);
250   }
251
252   /// \brief Get the constant value for i1 false.
253   ConstantInt *getFalse() {
254     return ConstantInt::getFalse(Context);
255   }
256
257   /// \brief Get a constant 8-bit value.
258   ConstantInt *getInt8(uint8_t C) {
259     return ConstantInt::get(getInt8Ty(), C);
260   }
261
262   /// \brief Get a constant 16-bit value.
263   ConstantInt *getInt16(uint16_t C) {
264     return ConstantInt::get(getInt16Ty(), C);
265   }
266
267   /// \brief Get a constant 32-bit value.
268   ConstantInt *getInt32(uint32_t C) {
269     return ConstantInt::get(getInt32Ty(), C);
270   }
271
272   /// \brief Get a constant 64-bit value.
273   ConstantInt *getInt64(uint64_t C) {
274     return ConstantInt::get(getInt64Ty(), C);
275   }
276
277   /// \brief Get a constant N-bit value, zero extended or truncated from
278   /// a 64-bit value.
279   ConstantInt *getIntN(unsigned N, uint64_t C) {
280     return ConstantInt::get(getIntNTy(N), C);
281   }
282
283   /// \brief Get a constant integer value.
284   ConstantInt *getInt(const APInt &AI) {
285     return ConstantInt::get(Context, AI);
286   }
287
288   //===--------------------------------------------------------------------===//
289   // Type creation methods
290   //===--------------------------------------------------------------------===//
291
292   /// \brief Fetch the type representing a single bit
293   IntegerType *getInt1Ty() {
294     return Type::getInt1Ty(Context);
295   }
296
297   /// \brief Fetch the type representing an 8-bit integer.
298   IntegerType *getInt8Ty() {
299     return Type::getInt8Ty(Context);
300   }
301
302   /// \brief Fetch the type representing a 16-bit integer.
303   IntegerType *getInt16Ty() {
304     return Type::getInt16Ty(Context);
305   }
306
307   /// \brief Fetch the type representing a 32-bit integer.
308   IntegerType *getInt32Ty() {
309     return Type::getInt32Ty(Context);
310   }
311
312   /// \brief Fetch the type representing a 64-bit integer.
313   IntegerType *getInt64Ty() {
314     return Type::getInt64Ty(Context);
315   }
316
317   /// \brief Fetch the type representing a 128-bit integer.
318   IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
319
320   /// \brief Fetch the type representing an N-bit integer.
321   IntegerType *getIntNTy(unsigned N) {
322     return Type::getIntNTy(Context, N);
323   }
324
325   /// \brief Fetch the type representing a 16-bit floating point value.
326   Type *getHalfTy() {
327     return Type::getHalfTy(Context);
328   }
329
330   /// \brief Fetch the type representing a 32-bit floating point value.
331   Type *getFloatTy() {
332     return Type::getFloatTy(Context);
333   }
334
335   /// \brief Fetch the type representing a 64-bit floating point value.
336   Type *getDoubleTy() {
337     return Type::getDoubleTy(Context);
338   }
339
340   /// \brief Fetch the type representing void.
341   Type *getVoidTy() {
342     return Type::getVoidTy(Context);
343   }
344
345   /// \brief Fetch the type representing a pointer to an 8-bit integer value.
346   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
347     return Type::getInt8PtrTy(Context, AddrSpace);
348   }
349
350   /// \brief Fetch the type representing a pointer to an integer value.
351   IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
352     return DL.getIntPtrType(Context, AddrSpace);
353   }
354
355   //===--------------------------------------------------------------------===//
356   // Intrinsic creation methods
357   //===--------------------------------------------------------------------===//
358
359   /// \brief Create and insert a memset to the specified pointer and the
360   /// specified value.
361   ///
362   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
363   /// specified, it will be added to the instruction. Likewise with alias.scope
364   /// and noalias tags.
365   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size,
366                          unsigned DstAlign,
367                          bool isVolatile = false, MDNode *TBAATag = nullptr,
368                          MDNode *ScopeTag = nullptr,
369                          MDNode *NoAliasTag = nullptr) {
370     return CreateMemSet(Ptr, Val, getInt64(Size), DstAlign, isVolatile,
371                         TBAATag, ScopeTag, NoAliasTag);
372   }
373
374   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned DstAlign,
375                          bool isVolatile = false, MDNode *TBAATag = nullptr,
376                          MDNode *ScopeTag = nullptr,
377                          MDNode *NoAliasTag = nullptr);
378
379   /// Create and insert a memcpy between the specified pointers.
380   ///
381   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
382   /// specified, it will be added to the instruction. Likewise with alias.scope
383   /// and noalias tags.
384   ///
385   /// Note!  This is very temporary.  It is only intended to catch calls to
386   /// CreateMemCpy in out of tree code which would otherwise silently pass the
387   /// volatile flag to source alignment.
388   class IntegerAlignment {
389   private:
390     uint64_t Align;
391
392     IntegerAlignment() = delete;
393     IntegerAlignment(bool) = delete;
394   public:
395     IntegerAlignment(int Align) : Align(Align) { }
396     IntegerAlignment(long long Align) : Align(Align) { }
397     IntegerAlignment(unsigned Align) : Align(Align) { }
398     IntegerAlignment(uint64_t Align) : Align(Align) { }
399
400     operator unsigned() { return Align; }
401   };
402   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size,
403                          unsigned DstAlign, IntegerAlignment SrcAlign,
404                          bool isVolatile = false, MDNode *TBAATag = nullptr,
405                          MDNode *TBAAStructTag = nullptr,
406                          MDNode *ScopeTag = nullptr,
407                          MDNode *NoAliasTag = nullptr) {
408     return CreateMemCpy(Dst, Src, getInt64(Size), DstAlign, SrcAlign,
409                         isVolatile, TBAATag,
410                         TBAAStructTag, ScopeTag, NoAliasTag);
411   }
412
413   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size,
414                          unsigned DstAlign, IntegerAlignment SrcAlign,
415                          bool isVolatile = false, MDNode *TBAATag = nullptr,
416                          MDNode *TBAAStructTag = nullptr,
417                          MDNode *ScopeTag = nullptr,
418                          MDNode *NoAliasTag = nullptr);
419
420   /// \brief Create and insert a memmove between the specified
421   /// pointers.
422   ///
423   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
424   /// specified, it will be added to the instruction. Likewise with alias.scope
425   /// and noalias tags.
426   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size,
427                           unsigned DstAlign, IntegerAlignment SrcAlign,
428                           bool isVolatile = false, MDNode *TBAATag = nullptr,
429                           MDNode *ScopeTag = nullptr,
430                           MDNode *NoAliasTag = nullptr) {
431     return CreateMemMove(Dst, Src, getInt64(Size), DstAlign, SrcAlign,
432                          isVolatile,
433                          TBAATag, ScopeTag, NoAliasTag);
434   }
435
436   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size,
437                           unsigned DstAlign, IntegerAlignment SrcAlign,
438                           bool isVolatile = false, MDNode *TBAATag = nullptr,
439                           MDNode *ScopeTag = nullptr,
440                           MDNode *NoAliasTag = nullptr);
441
442   /// \brief Create a lifetime.start intrinsic.
443   ///
444   /// If the pointer isn't i8* it will be converted.
445   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
446
447   /// \brief Create a lifetime.end intrinsic.
448   ///
449   /// If the pointer isn't i8* it will be converted.
450   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
451
452   /// \brief Create a call to Masked Load intrinsic
453   CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
454                              Value *PassThru = nullptr, const Twine &Name = "");
455
456   /// \brief Create a call to Masked Store intrinsic
457   CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
458                               Value *Mask);
459
460   /// \brief Create an assume intrinsic call that allows the optimizer to
461   /// assume that the provided condition will be true.
462   CallInst *CreateAssumption(Value *Cond);
463
464   /// \brief Create a call to the experimental.gc.statepoint intrinsic to
465   /// start a new statepoint sequence.
466   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
467                                    Value *ActualCallee,
468                                    ArrayRef<Value *> CallArgs,
469                                    ArrayRef<Value *> DeoptArgs,
470                                    ArrayRef<Value *> GCArgs,
471                                    const Twine &Name = "");
472
473   /// \brief Create a call to the experimental.gc.statepoint intrinsic to
474   /// start a new statepoint sequence.
475   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
476                                    Value *ActualCallee, uint32_t Flags,
477                                    ArrayRef<Use> CallArgs,
478                                    ArrayRef<Use> TransitionArgs,
479                                    ArrayRef<Use> DeoptArgs,
480                                    ArrayRef<Value *> GCArgs,
481                                    const Twine &Name = "");
482
483   // \brief Conveninence function for the common case when CallArgs are filled
484   // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
485   // .get()'ed to get the Value pointer.
486   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
487                                    Value *ActualCallee, ArrayRef<Use> CallArgs,
488                                    ArrayRef<Value *> DeoptArgs,
489                                    ArrayRef<Value *> GCArgs,
490                                    const Twine &Name = "");
491
492   /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
493   /// start a new statepoint sequence.
494   InvokeInst *
495   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
496                            Value *ActualInvokee, BasicBlock *NormalDest,
497                            BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
498                            ArrayRef<Value *> DeoptArgs,
499                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
500
501   /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
502   /// start a new statepoint sequence.
503   InvokeInst *CreateGCStatepointInvoke(
504       uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
505       BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
506       ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
507       ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
508       const Twine &Name = "");
509
510   // Conveninence function for the common case when CallArgs are filled in using
511   // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
512   // get the Value *.
513   InvokeInst *
514   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
515                            Value *ActualInvokee, BasicBlock *NormalDest,
516                            BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
517                            ArrayRef<Value *> DeoptArgs,
518                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
519
520   /// \brief Create a call to the experimental.gc.result intrinsic to extract
521   /// the result from a call wrapped in a statepoint.
522   CallInst *CreateGCResult(Instruction *Statepoint,
523                            Type *ResultType,
524                            const Twine &Name = "");
525
526   /// \brief Create a call to the experimental.gc.relocate intrinsics to
527   /// project the relocated value of one pointer from the statepoint.
528   CallInst *CreateGCRelocate(Instruction *Statepoint,
529                              int BaseOffset,
530                              int DerivedOffset,
531                              Type *ResultType,
532                              const Twine &Name = "");
533
534 private:
535   /// \brief Create a call to a masked intrinsic with given Id.
536   /// Masked intrinsic has only one overloaded type - data type.
537   CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
538                                   Type *DataTy, const Twine &Name = "");
539
540   Value *getCastedInt8PtrValue(Value *Ptr);
541 };
542
543 /// \brief This provides a uniform API for creating instructions and inserting
544 /// them into a basic block: either at the end of a BasicBlock, or at a specific
545 /// iterator location in a block.
546 ///
547 /// Note that the builder does not expose the full generality of LLVM
548 /// instructions.  For access to extra instruction properties, use the mutators
549 /// (e.g. setVolatile) on the instructions after they have been
550 /// created. Convenience state exists to specify fast-math flags and fp-math
551 /// tags.
552 ///
553 /// The first template argument handles whether or not to preserve names in the
554 /// final instruction output. This defaults to on.  The second template argument
555 /// specifies a class to use for creating constants.  This defaults to creating
556 /// minimally folded constants.  The third template argument allows clients to
557 /// specify custom insertion hooks that are called on every newly created
558 /// insertion.
559 template<bool preserveNames = true, typename T = ConstantFolder,
560          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
561 class IRBuilder : public IRBuilderBase, public Inserter {
562   T Folder;
563
564 public:
565   IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
566             MDNode *FPMathTag = nullptr)
567       : IRBuilderBase(C, FPMathTag), Inserter(std::move(I)), Folder(F) {}
568
569   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
570     : IRBuilderBase(C, FPMathTag), Folder() {
571   }
572
573   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
574     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
575     SetInsertPoint(TheBB);
576   }
577
578   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
579     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
580     SetInsertPoint(TheBB);
581   }
582
583   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
584     : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
585     SetInsertPoint(IP);
586   }
587
588   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
589             MDNode *FPMathTag = nullptr)
590     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
591     SetInsertPoint(TheBB, IP);
592   }
593
594   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
595             MDNode *FPMathTag = nullptr)
596     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
597     SetInsertPoint(TheBB, IP);
598   }
599
600   /// \brief Get the constant folder being used.
601   const T &getFolder() { return Folder; }
602
603   /// \brief Return true if this builder is configured to actually add the
604   /// requested names to IR created through it.
605   bool isNamePreserving() const { return preserveNames; }
606
607   /// \brief Insert and return the specified instruction.
608   template<typename InstTy>
609   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
610     this->InsertHelper(I, Name, BB, InsertPt);
611     this->SetInstDebugLocation(I);
612     return I;
613   }
614
615   /// \brief No-op overload to handle constants.
616   Constant *Insert(Constant *C, const Twine& = "") const {
617     return C;
618   }
619
620   //===--------------------------------------------------------------------===//
621   // Instruction creation methods: Terminators
622   //===--------------------------------------------------------------------===//
623
624 private:
625   /// \brief Helper to add branch weight and unpredictable metadata onto an
626   /// instruction.
627   /// \returns The annotated instruction.
628   template <typename InstTy>
629   InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
630     if (Weights)
631       I->setMetadata(LLVMContext::MD_prof, Weights);
632     if (Unpredictable)
633       I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
634     return I;
635   }
636
637 public:
638   /// \brief Create a 'ret void' instruction.
639   ReturnInst *CreateRetVoid() {
640     return Insert(ReturnInst::Create(Context));
641   }
642
643   /// \brief Create a 'ret <val>' instruction.
644   ReturnInst *CreateRet(Value *V) {
645     return Insert(ReturnInst::Create(Context, V));
646   }
647
648   /// \brief Create a sequence of N insertvalue instructions,
649   /// with one Value from the retVals array each, that build a aggregate
650   /// return value one value at a time, and a ret instruction to return
651   /// the resulting aggregate value.
652   ///
653   /// This is a convenience function for code that uses aggregate return values
654   /// as a vehicle for having multiple return values.
655   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
656     Value *V = UndefValue::get(getCurrentFunctionReturnType());
657     for (unsigned i = 0; i != N; ++i)
658       V = CreateInsertValue(V, retVals[i], i, "mrv");
659     return Insert(ReturnInst::Create(Context, V));
660   }
661
662   /// \brief Create an unconditional 'br label X' instruction.
663   BranchInst *CreateBr(BasicBlock *Dest) {
664     return Insert(BranchInst::Create(Dest));
665   }
666
667   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
668   /// instruction.
669   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
670                            MDNode *BranchWeights = nullptr,
671                            MDNode *Unpredictable = nullptr) {
672     return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
673                                     BranchWeights, Unpredictable));
674   }
675
676   /// \brief Create a switch instruction with the specified value, default dest,
677   /// and with a hint for the number of cases that will be added (for efficient
678   /// allocation).
679   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
680                            MDNode *BranchWeights = nullptr,
681                            MDNode *Unpredictable = nullptr) {
682     return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
683                                     BranchWeights, Unpredictable));
684   }
685
686   /// \brief Create an indirect branch instruction with the specified address
687   /// operand, with an optional hint for the number of destinations that will be
688   /// added (for efficient allocation).
689   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
690     return Insert(IndirectBrInst::Create(Addr, NumDests));
691   }
692
693   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
694                            BasicBlock *UnwindDest, const Twine &Name = "") {
695     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
696                   Name);
697   }
698   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
699                            BasicBlock *UnwindDest, Value *Arg1,
700                            const Twine &Name = "") {
701     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
702                   Name);
703   }
704   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
705                             BasicBlock *UnwindDest, Value *Arg1,
706                             Value *Arg2, Value *Arg3,
707                             const Twine &Name = "") {
708     Value *Args[] = { Arg1, Arg2, Arg3 };
709     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
710                   Name);
711   }
712   /// \brief Create an invoke instruction.
713   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
714                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
715                            const Twine &Name = "") {
716     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
717                   Name);
718   }
719
720   ResumeInst *CreateResume(Value *Exn) {
721     return Insert(ResumeInst::Create(Exn));
722   }
723
724   CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
725                                       BasicBlock *UnwindBB = nullptr) {
726     return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
727   }
728
729   CleanupEndPadInst *CreateCleanupEndPad(CleanupPadInst *CleanupPad,
730                                          BasicBlock *UnwindBB = nullptr) {
731     return Insert(CleanupEndPadInst::Create(CleanupPad, UnwindBB));
732   }
733
734   CatchPadInst *CreateCatchPad(BasicBlock *NormalDest, BasicBlock *UnwindDest,
735                                ArrayRef<Value *> Args, const Twine &Name = "") {
736     return Insert(CatchPadInst::Create(NormalDest, UnwindDest, Args), Name);
737   }
738
739   CatchEndPadInst *CreateCatchEndPad(BasicBlock *UnwindBB = nullptr) {
740     return Insert(CatchEndPadInst::Create(Context, UnwindBB));
741   }
742
743   TerminatePadInst *CreateTerminatePad(BasicBlock *UnwindBB = nullptr,
744                                        ArrayRef<Value *> Args = {},
745                                        const Twine &Name = "") {
746     return Insert(TerminatePadInst::Create(Context, UnwindBB, Args), Name);
747   }
748
749   CleanupPadInst *CreateCleanupPad(ArrayRef<Value *> Args,
750                                    const Twine &Name = "") {
751     return Insert(CleanupPadInst::Create(Context, Args), Name);
752   }
753
754   CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
755     return Insert(CatchReturnInst::Create(CatchPad, BB));
756   }
757
758   UnreachableInst *CreateUnreachable() {
759     return Insert(new UnreachableInst(Context));
760   }
761
762   //===--------------------------------------------------------------------===//
763   // Instruction creation methods: Binary Operators
764   //===--------------------------------------------------------------------===//
765 private:
766   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
767                                           Value *LHS, Value *RHS,
768                                           const Twine &Name,
769                                           bool HasNUW, bool HasNSW) {
770     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
771     if (HasNUW) BO->setHasNoUnsignedWrap();
772     if (HasNSW) BO->setHasNoSignedWrap();
773     return BO;
774   }
775
776   Instruction *AddFPMathAttributes(Instruction *I,
777                                    MDNode *FPMathTag,
778                                    FastMathFlags FMF) const {
779     if (!FPMathTag)
780       FPMathTag = DefaultFPMathTag;
781     if (FPMathTag)
782       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
783     I->setFastMathFlags(FMF);
784     return I;
785   }
786
787 public:
788   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
789                    bool HasNUW = false, bool HasNSW = false) {
790     if (Constant *LC = dyn_cast<Constant>(LHS))
791       if (Constant *RC = dyn_cast<Constant>(RHS))
792         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
793     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
794                                    HasNUW, HasNSW);
795   }
796   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
797     return CreateAdd(LHS, RHS, Name, false, true);
798   }
799   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
800     return CreateAdd(LHS, RHS, Name, true, false);
801   }
802   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
803                     MDNode *FPMathTag = nullptr) {
804     if (Constant *LC = dyn_cast<Constant>(LHS))
805       if (Constant *RC = dyn_cast<Constant>(RHS))
806         return Insert(Folder.CreateFAdd(LC, RC), Name);
807     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
808                                       FPMathTag, FMF), Name);
809   }
810   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
811                    bool HasNUW = false, bool HasNSW = false) {
812     if (Constant *LC = dyn_cast<Constant>(LHS))
813       if (Constant *RC = dyn_cast<Constant>(RHS))
814         return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
815     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
816                                    HasNUW, HasNSW);
817   }
818   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
819     return CreateSub(LHS, RHS, Name, false, true);
820   }
821   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
822     return CreateSub(LHS, RHS, Name, true, false);
823   }
824   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
825                     MDNode *FPMathTag = nullptr) {
826     if (Constant *LC = dyn_cast<Constant>(LHS))
827       if (Constant *RC = dyn_cast<Constant>(RHS))
828         return Insert(Folder.CreateFSub(LC, RC), Name);
829     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
830                                       FPMathTag, FMF), Name);
831   }
832   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
833                    bool HasNUW = false, bool HasNSW = false) {
834     if (Constant *LC = dyn_cast<Constant>(LHS))
835       if (Constant *RC = dyn_cast<Constant>(RHS))
836         return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
837     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
838                                    HasNUW, HasNSW);
839   }
840   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
841     return CreateMul(LHS, RHS, Name, false, true);
842   }
843   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
844     return CreateMul(LHS, RHS, Name, true, false);
845   }
846   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
847                     MDNode *FPMathTag = nullptr) {
848     if (Constant *LC = dyn_cast<Constant>(LHS))
849       if (Constant *RC = dyn_cast<Constant>(RHS))
850         return Insert(Folder.CreateFMul(LC, RC), Name);
851     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
852                                       FPMathTag, FMF), Name);
853   }
854   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
855                     bool isExact = false) {
856     if (Constant *LC = dyn_cast<Constant>(LHS))
857       if (Constant *RC = dyn_cast<Constant>(RHS))
858         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
859     if (!isExact)
860       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
861     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
862   }
863   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
864     return CreateUDiv(LHS, RHS, Name, true);
865   }
866   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
867                     bool isExact = false) {
868     if (Constant *LC = dyn_cast<Constant>(LHS))
869       if (Constant *RC = dyn_cast<Constant>(RHS))
870         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
871     if (!isExact)
872       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
873     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
874   }
875   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
876     return CreateSDiv(LHS, RHS, Name, true);
877   }
878   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
879                     MDNode *FPMathTag = nullptr) {
880     if (Constant *LC = dyn_cast<Constant>(LHS))
881       if (Constant *RC = dyn_cast<Constant>(RHS))
882         return Insert(Folder.CreateFDiv(LC, RC), Name);
883     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
884                                       FPMathTag, FMF), Name);
885   }
886   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
887     if (Constant *LC = dyn_cast<Constant>(LHS))
888       if (Constant *RC = dyn_cast<Constant>(RHS))
889         return Insert(Folder.CreateURem(LC, RC), Name);
890     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
891   }
892   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
893     if (Constant *LC = dyn_cast<Constant>(LHS))
894       if (Constant *RC = dyn_cast<Constant>(RHS))
895         return Insert(Folder.CreateSRem(LC, RC), Name);
896     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
897   }
898   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
899                     MDNode *FPMathTag = nullptr) {
900     if (Constant *LC = dyn_cast<Constant>(LHS))
901       if (Constant *RC = dyn_cast<Constant>(RHS))
902         return Insert(Folder.CreateFRem(LC, RC), Name);
903     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
904                                       FPMathTag, FMF), Name);
905   }
906
907   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
908                    bool HasNUW = false, bool HasNSW = false) {
909     if (Constant *LC = dyn_cast<Constant>(LHS))
910       if (Constant *RC = dyn_cast<Constant>(RHS))
911         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
912     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
913                                    HasNUW, HasNSW);
914   }
915   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
916                    bool HasNUW = false, bool HasNSW = false) {
917     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
918                      HasNUW, HasNSW);
919   }
920   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
921                    bool HasNUW = false, bool HasNSW = false) {
922     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
923                      HasNUW, HasNSW);
924   }
925
926   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
927                     bool isExact = false) {
928     if (Constant *LC = dyn_cast<Constant>(LHS))
929       if (Constant *RC = dyn_cast<Constant>(RHS))
930         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
931     if (!isExact)
932       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
933     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
934   }
935   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
936                     bool isExact = false) {
937     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
938   }
939   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
940                     bool isExact = false) {
941     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
942   }
943
944   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
945                     bool isExact = false) {
946     if (Constant *LC = dyn_cast<Constant>(LHS))
947       if (Constant *RC = dyn_cast<Constant>(RHS))
948         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
949     if (!isExact)
950       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
951     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
952   }
953   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
954                     bool isExact = false) {
955     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
956   }
957   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
958                     bool isExact = false) {
959     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
960   }
961
962   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
963     if (Constant *RC = dyn_cast<Constant>(RHS)) {
964       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
965         return LHS;  // LHS & -1 -> LHS
966       if (Constant *LC = dyn_cast<Constant>(LHS))
967         return Insert(Folder.CreateAnd(LC, RC), Name);
968     }
969     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
970   }
971   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
972     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
973   }
974   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
975     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
976   }
977
978   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
979     if (Constant *RC = dyn_cast<Constant>(RHS)) {
980       if (RC->isNullValue())
981         return LHS;  // LHS | 0 -> LHS
982       if (Constant *LC = dyn_cast<Constant>(LHS))
983         return Insert(Folder.CreateOr(LC, RC), Name);
984     }
985     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
986   }
987   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
988     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
989   }
990   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
991     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
992   }
993
994   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
995     if (Constant *LC = dyn_cast<Constant>(LHS))
996       if (Constant *RC = dyn_cast<Constant>(RHS))
997         return Insert(Folder.CreateXor(LC, RC), Name);
998     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
999   }
1000   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1001     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1002   }
1003   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1004     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1005   }
1006
1007   Value *CreateBinOp(Instruction::BinaryOps Opc,
1008                      Value *LHS, Value *RHS, const Twine &Name = "",
1009                      MDNode *FPMathTag = nullptr) {
1010     if (Constant *LC = dyn_cast<Constant>(LHS))
1011       if (Constant *RC = dyn_cast<Constant>(RHS))
1012         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
1013     llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
1014     if (isa<FPMathOperator>(BinOp))
1015       BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
1016     return Insert(BinOp, Name);
1017   }
1018
1019   Value *CreateNeg(Value *V, const Twine &Name = "",
1020                    bool HasNUW = false, bool HasNSW = false) {
1021     if (Constant *VC = dyn_cast<Constant>(V))
1022       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
1023     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
1024     if (HasNUW) BO->setHasNoUnsignedWrap();
1025     if (HasNSW) BO->setHasNoSignedWrap();
1026     return BO;
1027   }
1028   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1029     return CreateNeg(V, Name, false, true);
1030   }
1031   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1032     return CreateNeg(V, Name, true, false);
1033   }
1034   Value *CreateFNeg(Value *V, const Twine &Name = "",
1035                     MDNode *FPMathTag = nullptr) {
1036     if (Constant *VC = dyn_cast<Constant>(V))
1037       return Insert(Folder.CreateFNeg(VC), Name);
1038     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
1039                                       FPMathTag, FMF), Name);
1040   }
1041   Value *CreateNot(Value *V, const Twine &Name = "") {
1042     if (Constant *VC = dyn_cast<Constant>(V))
1043       return Insert(Folder.CreateNot(VC), Name);
1044     return Insert(BinaryOperator::CreateNot(V), Name);
1045   }
1046
1047   //===--------------------------------------------------------------------===//
1048   // Instruction creation methods: Memory Instructions
1049   //===--------------------------------------------------------------------===//
1050
1051   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1052                            const Twine &Name = "") {
1053     return Insert(new AllocaInst(Ty, ArraySize), Name);
1054   }
1055   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
1056   // converting the string to 'bool' for the isVolatile parameter.
1057   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1058     return Insert(new LoadInst(Ptr), Name);
1059   }
1060   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1061     return Insert(new LoadInst(Ptr), Name);
1062   }
1063   LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1064     return Insert(new LoadInst(Ty, Ptr), Name);
1065   }
1066   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1067     return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1068   }
1069   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1070     return Insert(new StoreInst(Val, Ptr, isVolatile));
1071   }
1072   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1073   // correctly, instead of converting the string to 'bool' for the isVolatile
1074   // parameter.
1075   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1076     LoadInst *LI = CreateLoad(Ptr, Name);
1077     LI->setAlignment(Align);
1078     return LI;
1079   }
1080   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1081                               const Twine &Name = "") {
1082     LoadInst *LI = CreateLoad(Ptr, Name);
1083     LI->setAlignment(Align);
1084     return LI;
1085   }
1086   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1087                               const Twine &Name = "") {
1088     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1089     LI->setAlignment(Align);
1090     return LI;
1091   }
1092   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1093                                 bool isVolatile = false) {
1094     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1095     SI->setAlignment(Align);
1096     return SI;
1097   }
1098   FenceInst *CreateFence(AtomicOrdering Ordering,
1099                          SynchronizationScope SynchScope = CrossThread,
1100                          const Twine &Name = "") {
1101     return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1102   }
1103   AtomicCmpXchgInst *
1104   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1105                       AtomicOrdering SuccessOrdering,
1106                       AtomicOrdering FailureOrdering,
1107                       SynchronizationScope SynchScope = CrossThread) {
1108     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1109                                         FailureOrdering, SynchScope));
1110   }
1111   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1112                                  AtomicOrdering Ordering,
1113                                SynchronizationScope SynchScope = CrossThread) {
1114     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1115   }
1116   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1117                    const Twine &Name = "") {
1118     return CreateGEP(nullptr, Ptr, IdxList, Name);
1119   }
1120   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1121                    const Twine &Name = "") {
1122     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1123       // Every index must be constant.
1124       size_t i, e;
1125       for (i = 0, e = IdxList.size(); i != e; ++i)
1126         if (!isa<Constant>(IdxList[i]))
1127           break;
1128       if (i == e)
1129         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1130     }
1131     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1132   }
1133   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1134                            const Twine &Name = "") {
1135     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1136   }
1137   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1138                            const Twine &Name = "") {
1139     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1140       // Every index must be constant.
1141       size_t i, e;
1142       for (i = 0, e = IdxList.size(); i != e; ++i)
1143         if (!isa<Constant>(IdxList[i]))
1144           break;
1145       if (i == e)
1146         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1147                       Name);
1148     }
1149     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1150   }
1151   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1152     return CreateGEP(nullptr, Ptr, Idx, Name);
1153   }
1154   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1155     if (Constant *PC = dyn_cast<Constant>(Ptr))
1156       if (Constant *IC = dyn_cast<Constant>(Idx))
1157         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1158     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1159   }
1160   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1161                            const Twine &Name = "") {
1162     if (Constant *PC = dyn_cast<Constant>(Ptr))
1163       if (Constant *IC = dyn_cast<Constant>(Idx))
1164         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1165     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1166   }
1167   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1168     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1169   }
1170   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1171                             const Twine &Name = "") {
1172     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1173
1174     if (Constant *PC = dyn_cast<Constant>(Ptr))
1175       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1176
1177     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1178   }
1179   Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1180                                     const Twine &Name = "") {
1181     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1182
1183     if (Constant *PC = dyn_cast<Constant>(Ptr))
1184       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1185
1186     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1187   }
1188   Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1189                             const Twine &Name = "") {
1190     Value *Idxs[] = {
1191       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1192       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1193     };
1194
1195     if (Constant *PC = dyn_cast<Constant>(Ptr))
1196       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1197
1198     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1199   }
1200   Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1201                                     unsigned Idx1, const Twine &Name = "") {
1202     Value *Idxs[] = {
1203       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1204       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1205     };
1206
1207     if (Constant *PC = dyn_cast<Constant>(Ptr))
1208       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1209
1210     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1211   }
1212   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1213     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1214
1215     if (Constant *PC = dyn_cast<Constant>(Ptr))
1216       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1217
1218     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1219   }
1220   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1221                                     const Twine &Name = "") {
1222     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1223
1224     if (Constant *PC = dyn_cast<Constant>(Ptr))
1225       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1226
1227     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1228   }
1229   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1230                     const Twine &Name = "") {
1231     Value *Idxs[] = {
1232       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1233       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1234     };
1235
1236     if (Constant *PC = dyn_cast<Constant>(Ptr))
1237       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1238
1239     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1240   }
1241   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1242                                     const Twine &Name = "") {
1243     Value *Idxs[] = {
1244       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1245       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1246     };
1247
1248     if (Constant *PC = dyn_cast<Constant>(Ptr))
1249       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1250                     Name);
1251
1252     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1253   }
1254   Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1255                          const Twine &Name = "") {
1256     return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1257   }
1258
1259   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1260   /// instead of a pointer to array of i8.
1261   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1262                                unsigned AddressSpace = 0) {
1263     GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace);
1264     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1265     Value *Args[] = { zero, zero };
1266     return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1267   }
1268
1269   //===--------------------------------------------------------------------===//
1270   // Instruction creation methods: Cast/Conversion Operators
1271   //===--------------------------------------------------------------------===//
1272
1273   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1274     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1275   }
1276   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1277     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1278   }
1279   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1280     return CreateCast(Instruction::SExt, V, DestTy, Name);
1281   }
1282   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1283   /// the value untouched if the type of V is already DestTy.
1284   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1285                            const Twine &Name = "") {
1286     assert(V->getType()->isIntOrIntVectorTy() &&
1287            DestTy->isIntOrIntVectorTy() &&
1288            "Can only zero extend/truncate integers!");
1289     Type *VTy = V->getType();
1290     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1291       return CreateZExt(V, DestTy, Name);
1292     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1293       return CreateTrunc(V, DestTy, Name);
1294     return V;
1295   }
1296   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1297   /// the value untouched if the type of V is already DestTy.
1298   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1299                            const Twine &Name = "") {
1300     assert(V->getType()->isIntOrIntVectorTy() &&
1301            DestTy->isIntOrIntVectorTy() &&
1302            "Can only sign extend/truncate integers!");
1303     Type *VTy = V->getType();
1304     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1305       return CreateSExt(V, DestTy, Name);
1306     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1307       return CreateTrunc(V, DestTy, Name);
1308     return V;
1309   }
1310   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1311     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1312   }
1313   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1314     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1315   }
1316   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1317     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1318   }
1319   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1320     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1321   }
1322   Value *CreateFPTrunc(Value *V, Type *DestTy,
1323                        const Twine &Name = "") {
1324     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1325   }
1326   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1327     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1328   }
1329   Value *CreatePtrToInt(Value *V, Type *DestTy,
1330                         const Twine &Name = "") {
1331     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1332   }
1333   Value *CreateIntToPtr(Value *V, Type *DestTy,
1334                         const Twine &Name = "") {
1335     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1336   }
1337   Value *CreateBitCast(Value *V, Type *DestTy,
1338                        const Twine &Name = "") {
1339     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1340   }
1341   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1342                              const Twine &Name = "") {
1343     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1344   }
1345   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1346                              const Twine &Name = "") {
1347     if (V->getType() == DestTy)
1348       return V;
1349     if (Constant *VC = dyn_cast<Constant>(V))
1350       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1351     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1352   }
1353   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1354                              const Twine &Name = "") {
1355     if (V->getType() == DestTy)
1356       return V;
1357     if (Constant *VC = dyn_cast<Constant>(V))
1358       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1359     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1360   }
1361   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1362                               const Twine &Name = "") {
1363     if (V->getType() == DestTy)
1364       return V;
1365     if (Constant *VC = dyn_cast<Constant>(V))
1366       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1367     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1368   }
1369   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1370                     const Twine &Name = "") {
1371     if (V->getType() == DestTy)
1372       return V;
1373     if (Constant *VC = dyn_cast<Constant>(V))
1374       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1375     return Insert(CastInst::Create(Op, V, DestTy), Name);
1376   }
1377   Value *CreatePointerCast(Value *V, Type *DestTy,
1378                            const Twine &Name = "") {
1379     if (V->getType() == DestTy)
1380       return V;
1381     if (Constant *VC = dyn_cast<Constant>(V))
1382       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1383     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1384   }
1385
1386   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1387                                              const Twine &Name = "") {
1388     if (V->getType() == DestTy)
1389       return V;
1390
1391     if (Constant *VC = dyn_cast<Constant>(V)) {
1392       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1393                     Name);
1394     }
1395
1396     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1397                   Name);
1398   }
1399
1400   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1401                        const Twine &Name = "") {
1402     if (V->getType() == DestTy)
1403       return V;
1404     if (Constant *VC = dyn_cast<Constant>(V))
1405       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1406     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1407   }
1408
1409   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1410                                 const Twine &Name = "") {
1411     if (V->getType() == DestTy)
1412       return V;
1413     if (V->getType()->getScalarType()->isPointerTy() &&
1414         DestTy->getScalarType()->isIntegerTy())
1415       return CreatePtrToInt(V, DestTy, Name);
1416     if (V->getType()->getScalarType()->isIntegerTy() &&
1417         DestTy->getScalarType()->isPointerTy())
1418       return CreateIntToPtr(V, DestTy, Name);
1419
1420     return CreateBitCast(V, DestTy, Name);
1421   }
1422
1423 private:
1424   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1425   // compile time error, instead of converting the string to bool for the
1426   // isSigned parameter.
1427   Value *CreateIntCast(Value *, Type *, const char *) = delete;
1428
1429 public:
1430   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1431     if (V->getType() == DestTy)
1432       return V;
1433     if (Constant *VC = dyn_cast<Constant>(V))
1434       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1435     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1436   }
1437
1438   //===--------------------------------------------------------------------===//
1439   // Instruction creation methods: Compare Instructions
1440   //===--------------------------------------------------------------------===//
1441
1442   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1443     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1444   }
1445   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1446     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1447   }
1448   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1449     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1450   }
1451   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1452     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1453   }
1454   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1455     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1456   }
1457   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1458     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1459   }
1460   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1461     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1462   }
1463   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1464     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1465   }
1466   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1467     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1468   }
1469   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1470     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1471   }
1472
1473   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1474                        MDNode *FPMathTag = nullptr) {
1475     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1476   }
1477   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1478                        MDNode *FPMathTag = nullptr) {
1479     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1480   }
1481   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1482                        MDNode *FPMathTag = nullptr) {
1483     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1484   }
1485   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1486                        MDNode *FPMathTag = nullptr) {
1487     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1488   }
1489   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1490                        MDNode *FPMathTag = nullptr) {
1491     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1492   }
1493   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1494                        MDNode *FPMathTag = nullptr) {
1495     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1496   }
1497   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1498                        MDNode *FPMathTag = nullptr) {
1499     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1500   }
1501   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1502                        MDNode *FPMathTag = nullptr) {
1503     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1504   }
1505   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1506                        MDNode *FPMathTag = nullptr) {
1507     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1508   }
1509   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1510                        MDNode *FPMathTag = nullptr) {
1511     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1512   }
1513   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1514                        MDNode *FPMathTag = nullptr) {
1515     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1516   }
1517   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1518                        MDNode *FPMathTag = nullptr) {
1519     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1520   }
1521   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1522                        MDNode *FPMathTag = nullptr) {
1523     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1524   }
1525   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1526                        MDNode *FPMathTag = nullptr) {
1527     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1528   }
1529
1530   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1531                     const Twine &Name = "") {
1532     if (Constant *LC = dyn_cast<Constant>(LHS))
1533       if (Constant *RC = dyn_cast<Constant>(RHS))
1534         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1535     return Insert(new ICmpInst(P, LHS, RHS), Name);
1536   }
1537   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1538                     const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1539     if (Constant *LC = dyn_cast<Constant>(LHS))
1540       if (Constant *RC = dyn_cast<Constant>(RHS))
1541         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1542     return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS),
1543                                       FPMathTag, FMF), Name);
1544   }
1545
1546   //===--------------------------------------------------------------------===//
1547   // Instruction creation methods: Other Instructions
1548   //===--------------------------------------------------------------------===//
1549
1550   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1551                      const Twine &Name = "") {
1552     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1553   }
1554
1555   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1556                        const Twine &Name = "") {
1557     return Insert(CallInst::Create(Callee, Args), Name);
1558   }
1559
1560   CallInst *CreateCall(llvm::FunctionType *FTy, Value *Callee,
1561                        ArrayRef<Value *> Args, const Twine &Name = "") {
1562     return Insert(CallInst::Create(FTy, Callee, Args), Name);
1563   }
1564
1565   CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1566                        const Twine &Name = "") {
1567     return CreateCall(Callee->getFunctionType(), Callee, Args, Name);
1568   }
1569
1570   Value *CreateSelect(Value *C, Value *True, Value *False,
1571                       const Twine &Name = "") {
1572     if (Constant *CC = dyn_cast<Constant>(C))
1573       if (Constant *TC = dyn_cast<Constant>(True))
1574         if (Constant *FC = dyn_cast<Constant>(False))
1575           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1576     return Insert(SelectInst::Create(C, True, False), Name);
1577   }
1578
1579   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1580     return Insert(new VAArgInst(List, Ty), Name);
1581   }
1582
1583   Value *CreateExtractElement(Value *Vec, Value *Idx,
1584                               const Twine &Name = "") {
1585     if (Constant *VC = dyn_cast<Constant>(Vec))
1586       if (Constant *IC = dyn_cast<Constant>(Idx))
1587         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1588     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1589   }
1590
1591   Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1592                               const Twine &Name = "") {
1593     return CreateExtractElement(Vec, getInt64(Idx), Name);
1594   }
1595
1596   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1597                              const Twine &Name = "") {
1598     if (Constant *VC = dyn_cast<Constant>(Vec))
1599       if (Constant *NC = dyn_cast<Constant>(NewElt))
1600         if (Constant *IC = dyn_cast<Constant>(Idx))
1601           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1602     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1603   }
1604
1605   Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1606                              const Twine &Name = "") {
1607     return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1608   }
1609
1610   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1611                              const Twine &Name = "") {
1612     if (Constant *V1C = dyn_cast<Constant>(V1))
1613       if (Constant *V2C = dyn_cast<Constant>(V2))
1614         if (Constant *MC = dyn_cast<Constant>(Mask))
1615           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1616     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1617   }
1618
1619   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1620                              const Twine &Name = "") {
1621     size_t MaskSize = IntMask.size();
1622     SmallVector<Constant*, 8> MaskVec(MaskSize);
1623     for (size_t i = 0; i != MaskSize; ++i)
1624       MaskVec[i] = getInt32(IntMask[i]);
1625     Value *Mask = ConstantVector::get(MaskVec);
1626     return CreateShuffleVector(V1, V2, Mask, Name);
1627   }
1628
1629   Value *CreateExtractValue(Value *Agg,
1630                             ArrayRef<unsigned> Idxs,
1631                             const Twine &Name = "") {
1632     if (Constant *AggC = dyn_cast<Constant>(Agg))
1633       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1634     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1635   }
1636
1637   Value *CreateInsertValue(Value *Agg, Value *Val,
1638                            ArrayRef<unsigned> Idxs,
1639                            const Twine &Name = "") {
1640     if (Constant *AggC = dyn_cast<Constant>(Agg))
1641       if (Constant *ValC = dyn_cast<Constant>(Val))
1642         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1643     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1644   }
1645
1646   LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1647                                    const Twine &Name = "") {
1648     return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1649   }
1650
1651   //===--------------------------------------------------------------------===//
1652   // Utility creation methods
1653   //===--------------------------------------------------------------------===//
1654
1655   /// \brief Return an i1 value testing if \p Arg is null.
1656   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1657     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1658                         Name);
1659   }
1660
1661   /// \brief Return an i1 value testing if \p Arg is not null.
1662   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1663     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1664                         Name);
1665   }
1666
1667   /// \brief Return the i64 difference between two pointer values, dividing out
1668   /// the size of the pointed-to objects.
1669   ///
1670   /// This is intended to implement C-style pointer subtraction. As such, the
1671   /// pointers must be appropriately aligned for their element types and
1672   /// pointing into the same object.
1673   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1674     assert(LHS->getType() == RHS->getType() &&
1675            "Pointer subtraction operand types must match!");
1676     PointerType *ArgType = cast<PointerType>(LHS->getType());
1677     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1678     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1679     Value *Difference = CreateSub(LHS_int, RHS_int);
1680     return CreateExactSDiv(Difference,
1681                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1682                            Name);
1683   }
1684
1685   /// \brief Create an invariant.group.barrier intrinsic call, that stops
1686   /// optimizer to propagate equality using invariant.group metadata.
1687   /// If Ptr type is different from i8*, it's casted to i8* before call
1688   /// and casted back to Ptr type after call.
1689   Value *CreateInvariantGroupBarrier(Value *Ptr) {
1690     Module *M = BB->getParent()->getParent();
1691     Function *FnInvariantGroupBarrier = Intrinsic::getDeclaration(M,
1692             Intrinsic::invariant_group_barrier);
1693
1694     Type *ArgumentAndReturnType = FnInvariantGroupBarrier->getReturnType();
1695     assert(ArgumentAndReturnType ==
1696         FnInvariantGroupBarrier->getFunctionType()->getParamType(0) &&
1697         "InvariantGroupBarrier should take and return the same type");
1698     Type *PtrType = Ptr->getType();
1699
1700     bool PtrTypeConversionNeeded = PtrType != ArgumentAndReturnType;
1701     if (PtrTypeConversionNeeded)
1702       Ptr = CreateBitCast(Ptr, ArgumentAndReturnType);
1703
1704     CallInst *Fn = CreateCall(FnInvariantGroupBarrier, {Ptr});
1705
1706     if (PtrTypeConversionNeeded)
1707       return CreateBitCast(Fn, PtrType);
1708     return Fn;
1709   }
1710
1711   /// \brief Return a vector value that contains \arg V broadcasted to \p
1712   /// NumElts elements.
1713   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1714     assert(NumElts > 0 && "Cannot splat to an empty vector!");
1715
1716     // First insert it into an undef vector so we can shuffle it.
1717     Type *I32Ty = getInt32Ty();
1718     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1719     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1720                             Name + ".splatinsert");
1721
1722     // Shuffle the value across the desired number of elements.
1723     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1724     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1725   }
1726
1727   /// \brief Return a value that has been extracted from a larger integer type.
1728   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1729                               IntegerType *ExtractedTy, uint64_t Offset,
1730                               const Twine &Name) {
1731     IntegerType *IntTy = cast<IntegerType>(From->getType());
1732     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1733                DL.getTypeStoreSize(IntTy) &&
1734            "Element extends past full value");
1735     uint64_t ShAmt = 8 * Offset;
1736     Value *V = From;
1737     if (DL.isBigEndian())
1738       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1739                    DL.getTypeStoreSize(ExtractedTy) - Offset);
1740     if (ShAmt) {
1741       V = CreateLShr(V, ShAmt, Name + ".shift");
1742     }
1743     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1744            "Cannot extract to a larger integer!");
1745     if (ExtractedTy != IntTy) {
1746       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1747     }
1748     return V;
1749   }
1750
1751   /// \brief Create an assume intrinsic call that represents an alignment
1752   /// assumption on the provided pointer.
1753   ///
1754   /// An optional offset can be provided, and if it is provided, the offset
1755   /// must be subtracted from the provided pointer to get the pointer with the
1756   /// specified alignment.
1757   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1758                                       unsigned Alignment,
1759                                       Value *OffsetValue = nullptr) {
1760     assert(isa<PointerType>(PtrValue->getType()) &&
1761            "trying to create an alignment assumption on a non-pointer?");
1762
1763     PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1764     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1765     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1766
1767     Value *Mask = ConstantInt::get(IntPtrTy,
1768       Alignment > 0 ? Alignment - 1 : 0);
1769     if (OffsetValue) {
1770       bool IsOffsetZero = false;
1771       if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1772         IsOffsetZero = CI->isZero();
1773
1774       if (!IsOffsetZero) {
1775         if (OffsetValue->getType() != IntPtrTy)
1776           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1777                                       "offsetcast");
1778         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1779       }
1780     }
1781
1782     Value *Zero = ConstantInt::get(IntPtrTy, 0);
1783     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1784     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1785
1786     return CreateAssumption(InvCond);
1787   }
1788 };
1789
1790 // Create wrappers for C Binding types (see CBindingWrapping.h).
1791 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1792
1793 } // end namespace llvm
1794
1795 #endif // LLVM_IR_IRBUILDER_H