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