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