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