OSDN Git Service

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