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