[opaque pointer type] More GEP IRBuilder API migrations
[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 an N-bit integer.
325   IntegerType *getIntNTy(unsigned N) {
326     return Type::getIntNTy(Context, N);
327   }
328
329   /// \brief Fetch the type representing a 16-bit floating point value.
330   Type *getHalfTy() {
331     return Type::getHalfTy(Context);
332   }
333
334   /// \brief Fetch the type representing a 32-bit floating point value.
335   Type *getFloatTy() {
336     return Type::getFloatTy(Context);
337   }
338
339   /// \brief Fetch the type representing a 64-bit floating point value.
340   Type *getDoubleTy() {
341     return Type::getDoubleTy(Context);
342   }
343
344   /// \brief Fetch the type representing void.
345   Type *getVoidTy() {
346     return Type::getVoidTy(Context);
347   }
348
349   /// \brief Fetch the type representing a pointer to an 8-bit integer value.
350   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
351     return Type::getInt8PtrTy(Context, AddrSpace);
352   }
353
354   /// \brief Fetch the type representing a pointer to an integer value.
355   IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
356     return DL.getIntPtrType(Context, AddrSpace);
357   }
358
359   //===--------------------------------------------------------------------===//
360   // Intrinsic creation methods
361   //===--------------------------------------------------------------------===//
362
363   /// \brief Create and insert a memset to the specified pointer and the
364   /// specified value.
365   ///
366   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
367   /// specified, it will be added to the instruction. Likewise with alias.scope
368   /// and noalias tags.
369   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
370                          bool isVolatile = false, MDNode *TBAATag = nullptr,
371                          MDNode *ScopeTag = nullptr,
372                          MDNode *NoAliasTag = nullptr) {
373     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
374                         TBAATag, ScopeTag, NoAliasTag);
375   }
376
377   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
378                          bool isVolatile = false, MDNode *TBAATag = nullptr,
379                          MDNode *ScopeTag = nullptr,
380                          MDNode *NoAliasTag = nullptr);
381
382   /// \brief Create and insert a memcpy between the specified pointers.
383   ///
384   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
385   /// specified, it will be added to the instruction. Likewise with alias.scope
386   /// and noalias tags.
387   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
388                          bool isVolatile = false, MDNode *TBAATag = nullptr,
389                          MDNode *TBAAStructTag = nullptr,
390                          MDNode *ScopeTag = nullptr,
391                          MDNode *NoAliasTag = nullptr) {
392     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
393                         TBAAStructTag, ScopeTag, NoAliasTag);
394   }
395
396   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
397                          bool isVolatile = false, MDNode *TBAATag = nullptr,
398                          MDNode *TBAAStructTag = nullptr,
399                          MDNode *ScopeTag = nullptr,
400                          MDNode *NoAliasTag = nullptr);
401
402   /// \brief Create and insert a memmove between the specified
403   /// pointers.
404   ///
405   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
406   /// specified, it will be added to the instruction. Likewise with alias.scope
407   /// and noalias tags.
408   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
409                           bool isVolatile = false, MDNode *TBAATag = nullptr,
410                           MDNode *ScopeTag = nullptr,
411                           MDNode *NoAliasTag = nullptr) {
412     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
413                          TBAATag, ScopeTag, NoAliasTag);
414   }
415
416   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
417                           bool isVolatile = false, MDNode *TBAATag = nullptr,
418                           MDNode *ScopeTag = nullptr,
419                           MDNode *NoAliasTag = nullptr);
420
421   /// \brief Create a lifetime.start intrinsic.
422   ///
423   /// If the pointer isn't i8* it will be converted.
424   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
425
426   /// \brief Create a lifetime.end intrinsic.
427   ///
428   /// If the pointer isn't i8* it will be converted.
429   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
430
431   /// \brief Create a call to Masked Load intrinsic
432   CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
433                              Value *PassThru = 0, const Twine &Name = "");
434
435   /// \brief Create a call to Masked Store intrinsic
436   CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
437                               Value *Mask);
438
439   /// \brief Create an assume intrinsic call that allows the optimizer to
440   /// assume that the provided condition will be true.
441   CallInst *CreateAssumption(Value *Cond);
442
443   /// \brief Create a call to the experimental.gc.statepoint intrinsic to
444   /// start a new statepoint sequence.
445   CallInst *CreateGCStatepoint(Value *ActualCallee,
446                                ArrayRef<Value *> CallArgs,
447                                ArrayRef<Value *> DeoptArgs,
448                                ArrayRef<Value *> GCArgs,
449                                const Twine &Name = "");
450
451   // Conveninence function for the common case when CallArgs are filled in using
452   // makeArrayRef(CS.arg_begin(), .arg_end()); Use needs to be .get()'ed to get
453   // the Value *.
454   CallInst *CreateGCStatepoint(Value *ActualCallee, ArrayRef<Use> CallArgs,
455                                ArrayRef<Value *> DeoptArgs,
456                                ArrayRef<Value *> GCArgs,
457                                const Twine &Name = "");
458
459   /// \brief Create a call to the experimental.gc.result intrinsic to extract
460   /// the result from a call wrapped in a statepoint.
461   CallInst *CreateGCResult(Instruction *Statepoint,
462                            Type *ResultType,
463                            const Twine &Name = "");
464
465   /// \brief Create a call to the experimental.gc.relocate intrinsics to
466   /// project the relocated value of one pointer from the statepoint.
467   CallInst *CreateGCRelocate(Instruction *Statepoint,
468                              int BaseOffset,
469                              int DerivedOffset,
470                              Type *ResultType,
471                              const Twine &Name = "");
472
473 private:
474   /// \brief Create a call to a masked intrinsic with given Id.
475   /// Masked intrinsic has only one overloaded type - data type.
476   CallInst *CreateMaskedIntrinsic(unsigned Id, ArrayRef<Value *> Ops,
477                                   Type *DataTy, const Twine &Name = "");
478
479   Value *getCastedInt8PtrValue(Value *Ptr);
480 };
481
482 /// \brief This provides a uniform API for creating instructions and inserting
483 /// them into a basic block: either at the end of a BasicBlock, or at a specific
484 /// iterator location in a block.
485 ///
486 /// Note that the builder does not expose the full generality of LLVM
487 /// instructions.  For access to extra instruction properties, use the mutators
488 /// (e.g. setVolatile) on the instructions after they have been
489 /// created. Convenience state exists to specify fast-math flags and fp-math
490 /// tags.
491 ///
492 /// The first template argument handles whether or not to preserve names in the
493 /// final instruction output. This defaults to on.  The second template argument
494 /// specifies a class to use for creating constants.  This defaults to creating
495 /// minimally folded constants.  The third template argument allows clients to
496 /// specify custom insertion hooks that are called on every newly created
497 /// insertion.
498 template<bool preserveNames = true, typename T = ConstantFolder,
499          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
500 class IRBuilder : public IRBuilderBase, public Inserter {
501   T Folder;
502 public:
503   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
504             MDNode *FPMathTag = nullptr)
505     : IRBuilderBase(C, FPMathTag), Inserter(I), Folder(F) {
506   }
507
508   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
509     : IRBuilderBase(C, FPMathTag), Folder() {
510   }
511
512   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
513     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
514     SetInsertPoint(TheBB);
515   }
516
517   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
518     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
519     SetInsertPoint(TheBB);
520   }
521
522   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
523     : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
524     SetInsertPoint(IP);
525     SetCurrentDebugLocation(IP->getDebugLoc());
526   }
527
528   explicit IRBuilder(Use &U, MDNode *FPMathTag = nullptr)
529     : IRBuilderBase(U->getContext(), FPMathTag), Folder() {
530     SetInsertPoint(U);
531     SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
532   }
533
534   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
535             MDNode *FPMathTag = nullptr)
536     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
537     SetInsertPoint(TheBB, IP);
538   }
539
540   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
541             MDNode *FPMathTag = nullptr)
542     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
543     SetInsertPoint(TheBB, IP);
544   }
545
546   /// \brief Get the constant folder being used.
547   const T &getFolder() { return Folder; }
548
549   /// \brief Return true if this builder is configured to actually add the
550   /// requested names to IR created through it.
551   bool isNamePreserving() const { return preserveNames; }
552
553   /// \brief Insert and return the specified instruction.
554   template<typename InstTy>
555   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
556     this->InsertHelper(I, Name, BB, InsertPt);
557     this->SetInstDebugLocation(I);
558     return I;
559   }
560
561   /// \brief No-op overload to handle constants.
562   Constant *Insert(Constant *C, const Twine& = "") const {
563     return C;
564   }
565
566   //===--------------------------------------------------------------------===//
567   // Instruction creation methods: Terminators
568   //===--------------------------------------------------------------------===//
569
570 private:
571   /// \brief Helper to add branch weight metadata onto an instruction.
572   /// \returns The annotated instruction.
573   template <typename InstTy>
574   InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
575     if (Weights)
576       I->setMetadata(LLVMContext::MD_prof, Weights);
577     return I;
578   }
579
580 public:
581   /// \brief Create a 'ret void' instruction.
582   ReturnInst *CreateRetVoid() {
583     return Insert(ReturnInst::Create(Context));
584   }
585
586   /// \brief Create a 'ret <val>' instruction.
587   ReturnInst *CreateRet(Value *V) {
588     return Insert(ReturnInst::Create(Context, V));
589   }
590
591   /// \brief Create a sequence of N insertvalue instructions,
592   /// with one Value from the retVals array each, that build a aggregate
593   /// return value one value at a time, and a ret instruction to return
594   /// the resulting aggregate value.
595   ///
596   /// This is a convenience function for code that uses aggregate return values
597   /// as a vehicle for having multiple return values.
598   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
599     Value *V = UndefValue::get(getCurrentFunctionReturnType());
600     for (unsigned i = 0; i != N; ++i)
601       V = CreateInsertValue(V, retVals[i], i, "mrv");
602     return Insert(ReturnInst::Create(Context, V));
603   }
604
605   /// \brief Create an unconditional 'br label X' instruction.
606   BranchInst *CreateBr(BasicBlock *Dest) {
607     return Insert(BranchInst::Create(Dest));
608   }
609
610   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
611   /// instruction.
612   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
613                            MDNode *BranchWeights = nullptr) {
614     return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
615                                    BranchWeights));
616   }
617
618   /// \brief Create a switch instruction with the specified value, default dest,
619   /// and with a hint for the number of cases that will be added (for efficient
620   /// allocation).
621   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
622                            MDNode *BranchWeights = nullptr) {
623     return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
624                                    BranchWeights));
625   }
626
627   /// \brief Create an indirect branch instruction with the specified address
628   /// operand, with an optional hint for the number of destinations that will be
629   /// added (for efficient allocation).
630   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
631     return Insert(IndirectBrInst::Create(Addr, NumDests));
632   }
633
634   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
635                            BasicBlock *UnwindDest, const Twine &Name = "") {
636     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
637                   Name);
638   }
639   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
640                            BasicBlock *UnwindDest, Value *Arg1,
641                            const Twine &Name = "") {
642     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
643                   Name);
644   }
645   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
646                             BasicBlock *UnwindDest, Value *Arg1,
647                             Value *Arg2, Value *Arg3,
648                             const Twine &Name = "") {
649     Value *Args[] = { Arg1, Arg2, Arg3 };
650     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
651                   Name);
652   }
653   /// \brief Create an invoke instruction.
654   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
655                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
656                            const Twine &Name = "") {
657     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
658                   Name);
659   }
660
661   ResumeInst *CreateResume(Value *Exn) {
662     return Insert(ResumeInst::Create(Exn));
663   }
664
665   UnreachableInst *CreateUnreachable() {
666     return Insert(new UnreachableInst(Context));
667   }
668
669   //===--------------------------------------------------------------------===//
670   // Instruction creation methods: Binary Operators
671   //===--------------------------------------------------------------------===//
672 private:
673   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
674                                           Value *LHS, Value *RHS,
675                                           const Twine &Name,
676                                           bool HasNUW, bool HasNSW) {
677     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
678     if (HasNUW) BO->setHasNoUnsignedWrap();
679     if (HasNSW) BO->setHasNoSignedWrap();
680     return BO;
681   }
682
683   Instruction *AddFPMathAttributes(Instruction *I,
684                                    MDNode *FPMathTag,
685                                    FastMathFlags FMF) const {
686     if (!FPMathTag)
687       FPMathTag = DefaultFPMathTag;
688     if (FPMathTag)
689       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
690     I->setFastMathFlags(FMF);
691     return I;
692   }
693 public:
694   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
695                    bool HasNUW = false, bool HasNSW = false) {
696     if (Constant *LC = dyn_cast<Constant>(LHS))
697       if (Constant *RC = dyn_cast<Constant>(RHS))
698         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
699     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
700                                    HasNUW, HasNSW);
701   }
702   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
703     return CreateAdd(LHS, RHS, Name, false, true);
704   }
705   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
706     return CreateAdd(LHS, RHS, Name, true, false);
707   }
708   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
709                     MDNode *FPMathTag = nullptr) {
710     if (Constant *LC = dyn_cast<Constant>(LHS))
711       if (Constant *RC = dyn_cast<Constant>(RHS))
712         return Insert(Folder.CreateFAdd(LC, RC), Name);
713     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
714                                       FPMathTag, FMF), Name);
715   }
716   Value *CreateSub(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.CreateSub(LC, RC, HasNUW, HasNSW), Name);
721     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
722                                    HasNUW, HasNSW);
723   }
724   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
725     return CreateSub(LHS, RHS, Name, false, true);
726   }
727   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
728     return CreateSub(LHS, RHS, Name, true, false);
729   }
730   Value *CreateFSub(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.CreateFSub(LC, RC), Name);
735     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
736                                       FPMathTag, FMF), Name);
737   }
738   Value *CreateMul(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.CreateMul(LC, RC, HasNUW, HasNSW), Name);
743     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
744                                    HasNUW, HasNSW);
745   }
746   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
747     return CreateMul(LHS, RHS, Name, false, true);
748   }
749   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
750     return CreateMul(LHS, RHS, Name, true, false);
751   }
752   Value *CreateFMul(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.CreateFMul(LC, RC), Name);
757     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
758                                       FPMathTag, FMF), Name);
759   }
760   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
761                     bool isExact = false) {
762     if (Constant *LC = dyn_cast<Constant>(LHS))
763       if (Constant *RC = dyn_cast<Constant>(RHS))
764         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
765     if (!isExact)
766       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
767     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
768   }
769   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
770     return CreateUDiv(LHS, RHS, Name, true);
771   }
772   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
773                     bool isExact = false) {
774     if (Constant *LC = dyn_cast<Constant>(LHS))
775       if (Constant *RC = dyn_cast<Constant>(RHS))
776         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
777     if (!isExact)
778       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
779     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
780   }
781   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
782     return CreateSDiv(LHS, RHS, Name, true);
783   }
784   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
785                     MDNode *FPMathTag = nullptr) {
786     if (Constant *LC = dyn_cast<Constant>(LHS))
787       if (Constant *RC = dyn_cast<Constant>(RHS))
788         return Insert(Folder.CreateFDiv(LC, RC), Name);
789     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
790                                       FPMathTag, FMF), Name);
791   }
792   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
793     if (Constant *LC = dyn_cast<Constant>(LHS))
794       if (Constant *RC = dyn_cast<Constant>(RHS))
795         return Insert(Folder.CreateURem(LC, RC), Name);
796     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
797   }
798   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
799     if (Constant *LC = dyn_cast<Constant>(LHS))
800       if (Constant *RC = dyn_cast<Constant>(RHS))
801         return Insert(Folder.CreateSRem(LC, RC), Name);
802     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
803   }
804   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
805                     MDNode *FPMathTag = nullptr) {
806     if (Constant *LC = dyn_cast<Constant>(LHS))
807       if (Constant *RC = dyn_cast<Constant>(RHS))
808         return Insert(Folder.CreateFRem(LC, RC), Name);
809     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
810                                       FPMathTag, FMF), Name);
811   }
812
813   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
814                    bool HasNUW = false, bool HasNSW = false) {
815     if (Constant *LC = dyn_cast<Constant>(LHS))
816       if (Constant *RC = dyn_cast<Constant>(RHS))
817         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
818     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
819                                    HasNUW, HasNSW);
820   }
821   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
822                    bool HasNUW = false, bool HasNSW = false) {
823     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
824                      HasNUW, HasNSW);
825   }
826   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
827                    bool HasNUW = false, bool HasNSW = false) {
828     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
829                      HasNUW, HasNSW);
830   }
831
832   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
833                     bool isExact = false) {
834     if (Constant *LC = dyn_cast<Constant>(LHS))
835       if (Constant *RC = dyn_cast<Constant>(RHS))
836         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
837     if (!isExact)
838       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
839     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
840   }
841   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
842                     bool isExact = false) {
843     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
844   }
845   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
846                     bool isExact = false) {
847     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
848   }
849
850   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
851                     bool isExact = false) {
852     if (Constant *LC = dyn_cast<Constant>(LHS))
853       if (Constant *RC = dyn_cast<Constant>(RHS))
854         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
855     if (!isExact)
856       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
857     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
858   }
859   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
860                     bool isExact = false) {
861     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
862   }
863   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
864                     bool isExact = false) {
865     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
866   }
867
868   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
869     if (Constant *RC = dyn_cast<Constant>(RHS)) {
870       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
871         return LHS;  // LHS & -1 -> LHS
872       if (Constant *LC = dyn_cast<Constant>(LHS))
873         return Insert(Folder.CreateAnd(LC, RC), Name);
874     }
875     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
876   }
877   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
878     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
879   }
880   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
881     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
882   }
883
884   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
885     if (Constant *RC = dyn_cast<Constant>(RHS)) {
886       if (RC->isNullValue())
887         return LHS;  // LHS | 0 -> LHS
888       if (Constant *LC = dyn_cast<Constant>(LHS))
889         return Insert(Folder.CreateOr(LC, RC), Name);
890     }
891     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
892   }
893   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
894     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
895   }
896   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
897     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
898   }
899
900   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
901     if (Constant *LC = dyn_cast<Constant>(LHS))
902       if (Constant *RC = dyn_cast<Constant>(RHS))
903         return Insert(Folder.CreateXor(LC, RC), Name);
904     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
905   }
906   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
907     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
908   }
909   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
910     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
911   }
912
913   Value *CreateBinOp(Instruction::BinaryOps Opc,
914                      Value *LHS, Value *RHS, const Twine &Name = "",
915                      MDNode *FPMathTag = nullptr) {
916     if (Constant *LC = dyn_cast<Constant>(LHS))
917       if (Constant *RC = dyn_cast<Constant>(RHS))
918         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
919     llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
920     if (isa<FPMathOperator>(BinOp))
921       BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
922     return Insert(BinOp, Name);
923   }
924
925   Value *CreateNeg(Value *V, const Twine &Name = "",
926                    bool HasNUW = false, bool HasNSW = false) {
927     if (Constant *VC = dyn_cast<Constant>(V))
928       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
929     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
930     if (HasNUW) BO->setHasNoUnsignedWrap();
931     if (HasNSW) BO->setHasNoSignedWrap();
932     return BO;
933   }
934   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
935     return CreateNeg(V, Name, false, true);
936   }
937   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
938     return CreateNeg(V, Name, true, false);
939   }
940   Value *CreateFNeg(Value *V, const Twine &Name = "",
941                     MDNode *FPMathTag = nullptr) {
942     if (Constant *VC = dyn_cast<Constant>(V))
943       return Insert(Folder.CreateFNeg(VC), Name);
944     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
945                                       FPMathTag, FMF), Name);
946   }
947   Value *CreateNot(Value *V, const Twine &Name = "") {
948     if (Constant *VC = dyn_cast<Constant>(V))
949       return Insert(Folder.CreateNot(VC), Name);
950     return Insert(BinaryOperator::CreateNot(V), Name);
951   }
952
953   //===--------------------------------------------------------------------===//
954   // Instruction creation methods: Memory Instructions
955   //===--------------------------------------------------------------------===//
956
957   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
958                            const Twine &Name = "") {
959     return Insert(new AllocaInst(Ty, ArraySize), Name);
960   }
961   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
962   // converting the string to 'bool' for the isVolatile parameter.
963   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
964     return Insert(new LoadInst(Ptr), Name);
965   }
966   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
967     return Insert(new LoadInst(Ptr), Name);
968   }
969   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
970     return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
971   }
972   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
973     return Insert(new StoreInst(Val, Ptr, isVolatile));
974   }
975   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
976   // correctly, instead of converting the string to 'bool' for the isVolatile
977   // parameter.
978   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
979     LoadInst *LI = CreateLoad(Ptr, Name);
980     LI->setAlignment(Align);
981     return LI;
982   }
983   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
984                               const Twine &Name = "") {
985     LoadInst *LI = CreateLoad(Ptr, Name);
986     LI->setAlignment(Align);
987     return LI;
988   }
989   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
990                               const Twine &Name = "") {
991     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
992     LI->setAlignment(Align);
993     return LI;
994   }
995   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
996                                 bool isVolatile = false) {
997     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
998     SI->setAlignment(Align);
999     return SI;
1000   }
1001   FenceInst *CreateFence(AtomicOrdering Ordering,
1002                          SynchronizationScope SynchScope = CrossThread,
1003                          const Twine &Name = "") {
1004     return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1005   }
1006   AtomicCmpXchgInst *
1007   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1008                       AtomicOrdering SuccessOrdering,
1009                       AtomicOrdering FailureOrdering,
1010                       SynchronizationScope SynchScope = CrossThread) {
1011     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1012                                         FailureOrdering, SynchScope));
1013   }
1014   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1015                                  AtomicOrdering Ordering,
1016                                SynchronizationScope SynchScope = CrossThread) {
1017     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1018   }
1019   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1020                    const Twine &Name = "") {
1021     return CreateGEP(nullptr, Ptr, IdxList, Name);
1022   }
1023   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1024                    const Twine &Name = "") {
1025     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1026       // Every index must be constant.
1027       size_t i, e;
1028       for (i = 0, e = IdxList.size(); i != e; ++i)
1029         if (!isa<Constant>(IdxList[i]))
1030           break;
1031       if (i == e)
1032         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1033     }
1034     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1035   }
1036   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1037                            const Twine &Name = "") {
1038     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1039   }
1040   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1041                            const Twine &Name = "") {
1042     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1043       // Every index must be constant.
1044       size_t i, e;
1045       for (i = 0, e = IdxList.size(); i != e; ++i)
1046         if (!isa<Constant>(IdxList[i]))
1047           break;
1048       if (i == e)
1049         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1050                       Name);
1051     }
1052     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1053   }
1054   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1055     return CreateGEP(nullptr, Ptr, Idx, Name);
1056   }
1057   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1058     if (Constant *PC = dyn_cast<Constant>(Ptr))
1059       if (Constant *IC = dyn_cast<Constant>(Idx))
1060         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1061     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1062   }
1063   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1064                            const Twine &Name = "") {
1065     if (Constant *PC = dyn_cast<Constant>(Ptr))
1066       if (Constant *IC = dyn_cast<Constant>(Idx))
1067         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1068     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1069   }
1070   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1071     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1072   }
1073   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1074                             const Twine &Name = "") {
1075     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1076
1077     if (Constant *PC = dyn_cast<Constant>(Ptr))
1078       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1079
1080     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1081   }
1082   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
1083                                     const Twine &Name = "") {
1084     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1085
1086     if (Constant *PC = dyn_cast<Constant>(Ptr))
1087       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1088
1089     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1090   }
1091   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
1092                     const Twine &Name = "") {
1093     Value *Idxs[] = {
1094       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1095       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1096     };
1097
1098     if (Constant *PC = dyn_cast<Constant>(Ptr))
1099       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1100
1101     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1102   }
1103   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
1104                                     const Twine &Name = "") {
1105     Value *Idxs[] = {
1106       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1107       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1108     };
1109
1110     if (Constant *PC = dyn_cast<Constant>(Ptr))
1111       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1112                     Name);
1113
1114     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1115   }
1116   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1117     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1118
1119     if (Constant *PC = dyn_cast<Constant>(Ptr))
1120       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1121
1122     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1123   }
1124   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1125                                     const Twine &Name = "") {
1126     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1127
1128     if (Constant *PC = dyn_cast<Constant>(Ptr))
1129       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1130
1131     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1132   }
1133   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1134                     const Twine &Name = "") {
1135     Value *Idxs[] = {
1136       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1137       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1138     };
1139
1140     if (Constant *PC = dyn_cast<Constant>(Ptr))
1141       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1142
1143     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1144   }
1145   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1146                                     const Twine &Name = "") {
1147     Value *Idxs[] = {
1148       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1149       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1150     };
1151
1152     if (Constant *PC = dyn_cast<Constant>(Ptr))
1153       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1154                     Name);
1155
1156     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1157   }
1158   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1159     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
1160   }
1161
1162   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1163   /// instead of a pointer to array of i8.
1164   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
1165     GlobalVariable *gv = CreateGlobalString(Str, Name);
1166     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1167     Value *Args[] = { zero, zero };
1168     return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1169   }
1170
1171   //===--------------------------------------------------------------------===//
1172   // Instruction creation methods: Cast/Conversion Operators
1173   //===--------------------------------------------------------------------===//
1174
1175   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1176     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1177   }
1178   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1179     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1180   }
1181   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1182     return CreateCast(Instruction::SExt, V, DestTy, Name);
1183   }
1184   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1185   /// the value untouched if the type of V is already DestTy.
1186   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1187                            const Twine &Name = "") {
1188     assert(V->getType()->isIntOrIntVectorTy() &&
1189            DestTy->isIntOrIntVectorTy() &&
1190            "Can only zero extend/truncate integers!");
1191     Type *VTy = V->getType();
1192     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1193       return CreateZExt(V, DestTy, Name);
1194     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1195       return CreateTrunc(V, DestTy, Name);
1196     return V;
1197   }
1198   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1199   /// the value untouched if the type of V is already DestTy.
1200   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1201                            const Twine &Name = "") {
1202     assert(V->getType()->isIntOrIntVectorTy() &&
1203            DestTy->isIntOrIntVectorTy() &&
1204            "Can only sign extend/truncate integers!");
1205     Type *VTy = V->getType();
1206     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1207       return CreateSExt(V, DestTy, Name);
1208     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1209       return CreateTrunc(V, DestTy, Name);
1210     return V;
1211   }
1212   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1213     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1214   }
1215   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1216     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1217   }
1218   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1219     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1220   }
1221   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1222     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1223   }
1224   Value *CreateFPTrunc(Value *V, Type *DestTy,
1225                        const Twine &Name = "") {
1226     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1227   }
1228   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1229     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1230   }
1231   Value *CreatePtrToInt(Value *V, Type *DestTy,
1232                         const Twine &Name = "") {
1233     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1234   }
1235   Value *CreateIntToPtr(Value *V, Type *DestTy,
1236                         const Twine &Name = "") {
1237     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1238   }
1239   Value *CreateBitCast(Value *V, Type *DestTy,
1240                        const Twine &Name = "") {
1241     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1242   }
1243   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1244                              const Twine &Name = "") {
1245     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1246   }
1247   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1248                              const Twine &Name = "") {
1249     if (V->getType() == DestTy)
1250       return V;
1251     if (Constant *VC = dyn_cast<Constant>(V))
1252       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1253     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1254   }
1255   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1256                              const Twine &Name = "") {
1257     if (V->getType() == DestTy)
1258       return V;
1259     if (Constant *VC = dyn_cast<Constant>(V))
1260       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1261     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1262   }
1263   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1264                               const Twine &Name = "") {
1265     if (V->getType() == DestTy)
1266       return V;
1267     if (Constant *VC = dyn_cast<Constant>(V))
1268       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1269     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1270   }
1271   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1272                     const Twine &Name = "") {
1273     if (V->getType() == DestTy)
1274       return V;
1275     if (Constant *VC = dyn_cast<Constant>(V))
1276       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1277     return Insert(CastInst::Create(Op, V, DestTy), Name);
1278   }
1279   Value *CreatePointerCast(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.CreatePointerCast(VC, DestTy), Name);
1285     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1286   }
1287
1288   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1289                                              const Twine &Name = "") {
1290     if (V->getType() == DestTy)
1291       return V;
1292
1293     if (Constant *VC = dyn_cast<Constant>(V)) {
1294       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1295                     Name);
1296     }
1297
1298     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1299                   Name);
1300   }
1301
1302   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1303                        const Twine &Name = "") {
1304     if (V->getType() == DestTy)
1305       return V;
1306     if (Constant *VC = dyn_cast<Constant>(V))
1307       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1308     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1309   }
1310
1311   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1312                                 const Twine &Name = "") {
1313     if (V->getType() == DestTy)
1314       return V;
1315     if (V->getType()->isPointerTy() && DestTy->isIntegerTy())
1316       return CreatePtrToInt(V, DestTy, Name);
1317     if (V->getType()->isIntegerTy() && DestTy->isPointerTy())
1318       return CreateIntToPtr(V, DestTy, Name);
1319
1320     return CreateBitCast(V, DestTy, Name);
1321   }
1322 private:
1323   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1324   // compile time error, instead of converting the string to bool for the
1325   // isSigned parameter.
1326   Value *CreateIntCast(Value *, Type *, const char *) = delete;
1327 public:
1328   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1329     if (V->getType() == DestTy)
1330       return V;
1331     if (Constant *VC = dyn_cast<Constant>(V))
1332       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1333     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1334   }
1335
1336   //===--------------------------------------------------------------------===//
1337   // Instruction creation methods: Compare Instructions
1338   //===--------------------------------------------------------------------===//
1339
1340   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1341     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1342   }
1343   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1344     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1345   }
1346   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1347     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1348   }
1349   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1350     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1351   }
1352   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1353     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1354   }
1355   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1356     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1357   }
1358   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1359     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1360   }
1361   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1362     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1363   }
1364   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1365     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1366   }
1367   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1368     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1369   }
1370
1371   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1372     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1373   }
1374   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1375     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1376   }
1377   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1378     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1379   }
1380   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1381     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1382   }
1383   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1384     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1385   }
1386   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1387     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1388   }
1389   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1390     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1391   }
1392   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1393     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1394   }
1395   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1396     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1397   }
1398   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1399     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1400   }
1401   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1402     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1403   }
1404   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1405     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1406   }
1407   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1408     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1409   }
1410   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1411     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1412   }
1413
1414   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1415                     const Twine &Name = "") {
1416     if (Constant *LC = dyn_cast<Constant>(LHS))
1417       if (Constant *RC = dyn_cast<Constant>(RHS))
1418         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1419     return Insert(new ICmpInst(P, LHS, RHS), Name);
1420   }
1421   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1422                     const Twine &Name = "") {
1423     if (Constant *LC = dyn_cast<Constant>(LHS))
1424       if (Constant *RC = dyn_cast<Constant>(RHS))
1425         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1426     return Insert(new FCmpInst(P, LHS, RHS), Name);
1427   }
1428
1429   //===--------------------------------------------------------------------===//
1430   // Instruction creation methods: Other Instructions
1431   //===--------------------------------------------------------------------===//
1432
1433   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1434                      const Twine &Name = "") {
1435     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1436   }
1437
1438   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1439     return Insert(CallInst::Create(Callee), Name);
1440   }
1441   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1442     return Insert(CallInst::Create(Callee, Arg), Name);
1443   }
1444   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1445                         const Twine &Name = "") {
1446     Value *Args[] = { Arg1, Arg2 };
1447     return Insert(CallInst::Create(Callee, Args), Name);
1448   }
1449   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1450                         const Twine &Name = "") {
1451     Value *Args[] = { Arg1, Arg2, Arg3 };
1452     return Insert(CallInst::Create(Callee, Args), Name);
1453   }
1454   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1455                         Value *Arg4, const Twine &Name = "") {
1456     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1457     return Insert(CallInst::Create(Callee, Args), Name);
1458   }
1459   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1460                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
1461     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1462     return Insert(CallInst::Create(Callee, Args), Name);
1463   }
1464
1465   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1466                        const Twine &Name = "") {
1467     return Insert(CallInst::Create(Callee, Args), Name);
1468   }
1469
1470   Value *CreateSelect(Value *C, Value *True, Value *False,
1471                       const Twine &Name = "") {
1472     if (Constant *CC = dyn_cast<Constant>(C))
1473       if (Constant *TC = dyn_cast<Constant>(True))
1474         if (Constant *FC = dyn_cast<Constant>(False))
1475           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1476     return Insert(SelectInst::Create(C, True, False), Name);
1477   }
1478
1479   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1480     return Insert(new VAArgInst(List, Ty), Name);
1481   }
1482
1483   Value *CreateExtractElement(Value *Vec, Value *Idx,
1484                               const Twine &Name = "") {
1485     if (Constant *VC = dyn_cast<Constant>(Vec))
1486       if (Constant *IC = dyn_cast<Constant>(Idx))
1487         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1488     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1489   }
1490
1491   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1492                              const Twine &Name = "") {
1493     if (Constant *VC = dyn_cast<Constant>(Vec))
1494       if (Constant *NC = dyn_cast<Constant>(NewElt))
1495         if (Constant *IC = dyn_cast<Constant>(Idx))
1496           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1497     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1498   }
1499
1500   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1501                              const Twine &Name = "") {
1502     if (Constant *V1C = dyn_cast<Constant>(V1))
1503       if (Constant *V2C = dyn_cast<Constant>(V2))
1504         if (Constant *MC = dyn_cast<Constant>(Mask))
1505           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1506     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1507   }
1508
1509   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1510                              const Twine &Name = "") {
1511     size_t MaskSize = IntMask.size();
1512     SmallVector<Constant*, 8> MaskVec(MaskSize);
1513     for (size_t i = 0; i != MaskSize; ++i)
1514       MaskVec[i] = getInt32(IntMask[i]);
1515     Value *Mask = ConstantVector::get(MaskVec);
1516     return CreateShuffleVector(V1, V2, Mask, Name);
1517   }
1518
1519   Value *CreateExtractValue(Value *Agg,
1520                             ArrayRef<unsigned> Idxs,
1521                             const Twine &Name = "") {
1522     if (Constant *AggC = dyn_cast<Constant>(Agg))
1523       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1524     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1525   }
1526
1527   Value *CreateInsertValue(Value *Agg, Value *Val,
1528                            ArrayRef<unsigned> Idxs,
1529                            const Twine &Name = "") {
1530     if (Constant *AggC = dyn_cast<Constant>(Agg))
1531       if (Constant *ValC = dyn_cast<Constant>(Val))
1532         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1533     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1534   }
1535
1536   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1537                                    const Twine &Name = "") {
1538     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses), Name);
1539   }
1540
1541   //===--------------------------------------------------------------------===//
1542   // Utility creation methods
1543   //===--------------------------------------------------------------------===//
1544
1545   /// \brief Return an i1 value testing if \p Arg is null.
1546   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1547     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1548                         Name);
1549   }
1550
1551   /// \brief Return an i1 value testing if \p Arg is not null.
1552   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1553     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1554                         Name);
1555   }
1556
1557   /// \brief Return the i64 difference between two pointer values, dividing out
1558   /// the size of the pointed-to objects.
1559   ///
1560   /// This is intended to implement C-style pointer subtraction. As such, the
1561   /// pointers must be appropriately aligned for their element types and
1562   /// pointing into the same object.
1563   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1564     assert(LHS->getType() == RHS->getType() &&
1565            "Pointer subtraction operand types must match!");
1566     PointerType *ArgType = cast<PointerType>(LHS->getType());
1567     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1568     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1569     Value *Difference = CreateSub(LHS_int, RHS_int);
1570     return CreateExactSDiv(Difference,
1571                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1572                            Name);
1573   }
1574
1575   /// \brief Return a vector value that contains \arg V broadcasted to \p
1576   /// NumElts elements.
1577   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1578     assert(NumElts > 0 && "Cannot splat to an empty vector!");
1579
1580     // First insert it into an undef vector so we can shuffle it.
1581     Type *I32Ty = getInt32Ty();
1582     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1583     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1584                             Name + ".splatinsert");
1585
1586     // Shuffle the value across the desired number of elements.
1587     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1588     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1589   }
1590
1591   /// \brief Return a value that has been extracted from a larger integer type.
1592   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1593                               IntegerType *ExtractedTy, uint64_t Offset,
1594                               const Twine &Name) {
1595     IntegerType *IntTy = cast<IntegerType>(From->getType());
1596     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1597                DL.getTypeStoreSize(IntTy) &&
1598            "Element extends past full value");
1599     uint64_t ShAmt = 8 * Offset;
1600     Value *V = From;
1601     if (DL.isBigEndian())
1602       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1603                    DL.getTypeStoreSize(ExtractedTy) - Offset);
1604     if (ShAmt) {
1605       V = CreateLShr(V, ShAmt, Name + ".shift");
1606     }
1607     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1608            "Cannot extract to a larger integer!");
1609     if (ExtractedTy != IntTy) {
1610       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1611     }
1612     return V;
1613   }
1614
1615   /// \brief Create an assume intrinsic call that represents an alignment
1616   /// assumption on the provided pointer.
1617   ///
1618   /// An optional offset can be provided, and if it is provided, the offset
1619   /// must be subtracted from the provided pointer to get the pointer with the
1620   /// specified alignment.
1621   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1622                                       unsigned Alignment,
1623                                       Value *OffsetValue = nullptr) {
1624     assert(isa<PointerType>(PtrValue->getType()) &&
1625            "trying to create an alignment assumption on a non-pointer?");
1626
1627     PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1628     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1629     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1630
1631     Value *Mask = ConstantInt::get(IntPtrTy,
1632       Alignment > 0 ? Alignment - 1 : 0);
1633     if (OffsetValue) {
1634       bool IsOffsetZero = false;
1635       if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1636         IsOffsetZero = CI->isZero();
1637
1638       if (!IsOffsetZero) {
1639         if (OffsetValue->getType() != IntPtrTy)
1640           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1641                                       "offsetcast");
1642         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1643       }
1644     }
1645
1646     Value *Zero = ConstantInt::get(IntPtrTy, 0);
1647     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1648     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1649
1650     return CreateAssumption(InvCond);
1651   }
1652 };
1653
1654 // Create wrappers for C Binding types (see CBindingWrapping.h).
1655 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1656
1657 }
1658
1659 #endif