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