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