75ad20601f7585658a4f9f429fff0b87660b7862
[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(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(PC, IdxList), Name);
1045     }
1046     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, IdxList), Name);
1047   }
1048   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1049     return CreateGEP(nullptr, Ptr, Idx, Name);
1050   }
1051   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1052     if (Constant *PC = dyn_cast<Constant>(Ptr))
1053       if (Constant *IC = dyn_cast<Constant>(Idx))
1054         return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
1055     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1056   }
1057   Value *CreateInBoundsGEP(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.CreateInBoundsGetElementPtr(PC, IC), Name);
1061     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1062   }
1063   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1064     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1065
1066     if (Constant *PC = dyn_cast<Constant>(Ptr))
1067       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
1068
1069     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1070   }
1071   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
1072                                     const Twine &Name = "") {
1073     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1074
1075     if (Constant *PC = dyn_cast<Constant>(Ptr))
1076       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
1077
1078     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1079   }
1080   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
1081                     const Twine &Name = "") {
1082     Value *Idxs[] = {
1083       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1084       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1085     };
1086
1087     if (Constant *PC = dyn_cast<Constant>(Ptr))
1088       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
1089
1090     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1091   }
1092   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
1093                                     const Twine &Name = "") {
1094     Value *Idxs[] = {
1095       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1096       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1097     };
1098
1099     if (Constant *PC = dyn_cast<Constant>(Ptr))
1100       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
1101
1102     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1103   }
1104   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1105     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1106
1107     if (Constant *PC = dyn_cast<Constant>(Ptr))
1108       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
1109
1110     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1111   }
1112   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1113                                     const Twine &Name = "") {
1114     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1115
1116     if (Constant *PC = dyn_cast<Constant>(Ptr))
1117       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
1118
1119     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1120   }
1121   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1122                     const Twine &Name = "") {
1123     Value *Idxs[] = {
1124       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1125       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1126     };
1127
1128     if (Constant *PC = dyn_cast<Constant>(Ptr))
1129       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
1130
1131     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1132   }
1133   Value *CreateConstInBoundsGEP2_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.CreateInBoundsGetElementPtr(PC, Idxs), Name);
1142
1143     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1144   }
1145   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1146     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
1147   }
1148
1149   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1150   /// instead of a pointer to array of i8.
1151   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
1152     Value *gv = CreateGlobalString(Str, Name);
1153     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1154     Value *Args[] = { zero, zero };
1155     return CreateInBoundsGEP(gv, Args, Name);
1156   }
1157
1158   //===--------------------------------------------------------------------===//
1159   // Instruction creation methods: Cast/Conversion Operators
1160   //===--------------------------------------------------------------------===//
1161
1162   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1163     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1164   }
1165   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1166     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1167   }
1168   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1169     return CreateCast(Instruction::SExt, V, DestTy, Name);
1170   }
1171   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1172   /// the value untouched if the type of V is already DestTy.
1173   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1174                            const Twine &Name = "") {
1175     assert(V->getType()->isIntOrIntVectorTy() &&
1176            DestTy->isIntOrIntVectorTy() &&
1177            "Can only zero extend/truncate integers!");
1178     Type *VTy = V->getType();
1179     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1180       return CreateZExt(V, DestTy, Name);
1181     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1182       return CreateTrunc(V, DestTy, Name);
1183     return V;
1184   }
1185   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1186   /// the value untouched if the type of V is already DestTy.
1187   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1188                            const Twine &Name = "") {
1189     assert(V->getType()->isIntOrIntVectorTy() &&
1190            DestTy->isIntOrIntVectorTy() &&
1191            "Can only sign extend/truncate integers!");
1192     Type *VTy = V->getType();
1193     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1194       return CreateSExt(V, DestTy, Name);
1195     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1196       return CreateTrunc(V, DestTy, Name);
1197     return V;
1198   }
1199   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1200     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1201   }
1202   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1203     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1204   }
1205   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1206     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1207   }
1208   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1209     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1210   }
1211   Value *CreateFPTrunc(Value *V, Type *DestTy,
1212                        const Twine &Name = "") {
1213     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1214   }
1215   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1216     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1217   }
1218   Value *CreatePtrToInt(Value *V, Type *DestTy,
1219                         const Twine &Name = "") {
1220     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1221   }
1222   Value *CreateIntToPtr(Value *V, Type *DestTy,
1223                         const Twine &Name = "") {
1224     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1225   }
1226   Value *CreateBitCast(Value *V, Type *DestTy,
1227                        const Twine &Name = "") {
1228     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1229   }
1230   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1231                              const Twine &Name = "") {
1232     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1233   }
1234   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1235                              const Twine &Name = "") {
1236     if (V->getType() == DestTy)
1237       return V;
1238     if (Constant *VC = dyn_cast<Constant>(V))
1239       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1240     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1241   }
1242   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1243                              const Twine &Name = "") {
1244     if (V->getType() == DestTy)
1245       return V;
1246     if (Constant *VC = dyn_cast<Constant>(V))
1247       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1248     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1249   }
1250   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1251                               const Twine &Name = "") {
1252     if (V->getType() == DestTy)
1253       return V;
1254     if (Constant *VC = dyn_cast<Constant>(V))
1255       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1256     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1257   }
1258   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1259                     const Twine &Name = "") {
1260     if (V->getType() == DestTy)
1261       return V;
1262     if (Constant *VC = dyn_cast<Constant>(V))
1263       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1264     return Insert(CastInst::Create(Op, V, DestTy), Name);
1265   }
1266   Value *CreatePointerCast(Value *V, Type *DestTy,
1267                            const Twine &Name = "") {
1268     if (V->getType() == DestTy)
1269       return V;
1270     if (Constant *VC = dyn_cast<Constant>(V))
1271       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1272     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1273   }
1274
1275   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1276                                              const Twine &Name = "") {
1277     if (V->getType() == DestTy)
1278       return V;
1279
1280     if (Constant *VC = dyn_cast<Constant>(V)) {
1281       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1282                     Name);
1283     }
1284
1285     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1286                   Name);
1287   }
1288
1289   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1290                        const Twine &Name = "") {
1291     if (V->getType() == DestTy)
1292       return V;
1293     if (Constant *VC = dyn_cast<Constant>(V))
1294       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1295     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1296   }
1297
1298   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1299                                 const Twine &Name = "") {
1300     if (V->getType() == DestTy)
1301       return V;
1302     if (V->getType()->isPointerTy() && DestTy->isIntegerTy())
1303       return CreatePtrToInt(V, DestTy, Name);
1304     if (V->getType()->isIntegerTy() && DestTy->isPointerTy())
1305       return CreateIntToPtr(V, DestTy, Name);
1306
1307     return CreateBitCast(V, DestTy, Name);
1308   }
1309 private:
1310   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1311   // compile time error, instead of converting the string to bool for the
1312   // isSigned parameter.
1313   Value *CreateIntCast(Value *, Type *, const char *) = delete;
1314 public:
1315   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1316     if (V->getType() == DestTy)
1317       return V;
1318     if (Constant *VC = dyn_cast<Constant>(V))
1319       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1320     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1321   }
1322
1323   //===--------------------------------------------------------------------===//
1324   // Instruction creation methods: Compare Instructions
1325   //===--------------------------------------------------------------------===//
1326
1327   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1328     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1329   }
1330   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1331     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1332   }
1333   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1334     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1335   }
1336   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1337     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1338   }
1339   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1340     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1341   }
1342   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1343     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1344   }
1345   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1346     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1347   }
1348   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1349     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1350   }
1351   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1352     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1353   }
1354   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1355     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1356   }
1357
1358   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1359     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1360   }
1361   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1362     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1363   }
1364   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1365     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1366   }
1367   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1368     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1369   }
1370   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1371     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1372   }
1373   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1374     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1375   }
1376   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1377     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1378   }
1379   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1380     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1381   }
1382   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1383     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1384   }
1385   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1386     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1387   }
1388   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1389     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1390   }
1391   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1392     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1393   }
1394   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1395     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1396   }
1397   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1398     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1399   }
1400
1401   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1402                     const Twine &Name = "") {
1403     if (Constant *LC = dyn_cast<Constant>(LHS))
1404       if (Constant *RC = dyn_cast<Constant>(RHS))
1405         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1406     return Insert(new ICmpInst(P, LHS, RHS), Name);
1407   }
1408   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1409                     const Twine &Name = "") {
1410     if (Constant *LC = dyn_cast<Constant>(LHS))
1411       if (Constant *RC = dyn_cast<Constant>(RHS))
1412         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1413     return Insert(new FCmpInst(P, LHS, RHS), Name);
1414   }
1415
1416   //===--------------------------------------------------------------------===//
1417   // Instruction creation methods: Other Instructions
1418   //===--------------------------------------------------------------------===//
1419
1420   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1421                      const Twine &Name = "") {
1422     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1423   }
1424
1425   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1426     return Insert(CallInst::Create(Callee), Name);
1427   }
1428   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1429     return Insert(CallInst::Create(Callee, Arg), Name);
1430   }
1431   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1432                         const Twine &Name = "") {
1433     Value *Args[] = { Arg1, Arg2 };
1434     return Insert(CallInst::Create(Callee, Args), Name);
1435   }
1436   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1437                         const Twine &Name = "") {
1438     Value *Args[] = { Arg1, Arg2, Arg3 };
1439     return Insert(CallInst::Create(Callee, Args), Name);
1440   }
1441   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1442                         Value *Arg4, const Twine &Name = "") {
1443     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1444     return Insert(CallInst::Create(Callee, Args), Name);
1445   }
1446   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1447                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
1448     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1449     return Insert(CallInst::Create(Callee, Args), Name);
1450   }
1451
1452   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1453                        const Twine &Name = "") {
1454     return Insert(CallInst::Create(Callee, Args), Name);
1455   }
1456
1457   Value *CreateSelect(Value *C, Value *True, Value *False,
1458                       const Twine &Name = "") {
1459     if (Constant *CC = dyn_cast<Constant>(C))
1460       if (Constant *TC = dyn_cast<Constant>(True))
1461         if (Constant *FC = dyn_cast<Constant>(False))
1462           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1463     return Insert(SelectInst::Create(C, True, False), Name);
1464   }
1465
1466   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1467     return Insert(new VAArgInst(List, Ty), Name);
1468   }
1469
1470   Value *CreateExtractElement(Value *Vec, Value *Idx,
1471                               const Twine &Name = "") {
1472     if (Constant *VC = dyn_cast<Constant>(Vec))
1473       if (Constant *IC = dyn_cast<Constant>(Idx))
1474         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1475     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1476   }
1477
1478   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1479                              const Twine &Name = "") {
1480     if (Constant *VC = dyn_cast<Constant>(Vec))
1481       if (Constant *NC = dyn_cast<Constant>(NewElt))
1482         if (Constant *IC = dyn_cast<Constant>(Idx))
1483           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1484     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1485   }
1486
1487   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1488                              const Twine &Name = "") {
1489     if (Constant *V1C = dyn_cast<Constant>(V1))
1490       if (Constant *V2C = dyn_cast<Constant>(V2))
1491         if (Constant *MC = dyn_cast<Constant>(Mask))
1492           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1493     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1494   }
1495
1496   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1497                              const Twine &Name = "") {
1498     size_t MaskSize = IntMask.size();
1499     SmallVector<Constant*, 8> MaskVec(MaskSize);
1500     for (size_t i = 0; i != MaskSize; ++i)
1501       MaskVec[i] = getInt32(IntMask[i]);
1502     Value *Mask = ConstantVector::get(MaskVec);
1503     return CreateShuffleVector(V1, V2, Mask, Name);
1504   }
1505
1506   Value *CreateExtractValue(Value *Agg,
1507                             ArrayRef<unsigned> Idxs,
1508                             const Twine &Name = "") {
1509     if (Constant *AggC = dyn_cast<Constant>(Agg))
1510       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1511     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1512   }
1513
1514   Value *CreateInsertValue(Value *Agg, Value *Val,
1515                            ArrayRef<unsigned> Idxs,
1516                            const Twine &Name = "") {
1517     if (Constant *AggC = dyn_cast<Constant>(Agg))
1518       if (Constant *ValC = dyn_cast<Constant>(Val))
1519         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1520     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1521   }
1522
1523   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1524                                    const Twine &Name = "") {
1525     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses), Name);
1526   }
1527
1528   //===--------------------------------------------------------------------===//
1529   // Utility creation methods
1530   //===--------------------------------------------------------------------===//
1531
1532   /// \brief Return an i1 value testing if \p Arg is null.
1533   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1534     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1535                         Name);
1536   }
1537
1538   /// \brief Return an i1 value testing if \p Arg is not null.
1539   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1540     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1541                         Name);
1542   }
1543
1544   /// \brief Return the i64 difference between two pointer values, dividing out
1545   /// the size of the pointed-to objects.
1546   ///
1547   /// This is intended to implement C-style pointer subtraction. As such, the
1548   /// pointers must be appropriately aligned for their element types and
1549   /// pointing into the same object.
1550   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1551     assert(LHS->getType() == RHS->getType() &&
1552            "Pointer subtraction operand types must match!");
1553     PointerType *ArgType = cast<PointerType>(LHS->getType());
1554     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1555     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1556     Value *Difference = CreateSub(LHS_int, RHS_int);
1557     return CreateExactSDiv(Difference,
1558                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1559                            Name);
1560   }
1561
1562   /// \brief Return a vector value that contains \arg V broadcasted to \p
1563   /// NumElts elements.
1564   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1565     assert(NumElts > 0 && "Cannot splat to an empty vector!");
1566
1567     // First insert it into an undef vector so we can shuffle it.
1568     Type *I32Ty = getInt32Ty();
1569     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1570     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1571                             Name + ".splatinsert");
1572
1573     // Shuffle the value across the desired number of elements.
1574     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1575     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1576   }
1577
1578   /// \brief Return a value that has been extracted from a larger integer type.
1579   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1580                               IntegerType *ExtractedTy, uint64_t Offset,
1581                               const Twine &Name) {
1582     IntegerType *IntTy = cast<IntegerType>(From->getType());
1583     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1584                DL.getTypeStoreSize(IntTy) &&
1585            "Element extends past full value");
1586     uint64_t ShAmt = 8 * Offset;
1587     Value *V = From;
1588     if (DL.isBigEndian())
1589       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1590                    DL.getTypeStoreSize(ExtractedTy) - Offset);
1591     if (ShAmt) {
1592       V = CreateLShr(V, ShAmt, Name + ".shift");
1593     }
1594     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1595            "Cannot extract to a larger integer!");
1596     if (ExtractedTy != IntTy) {
1597       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1598     }
1599     return V;
1600   }
1601
1602   /// \brief Create an assume intrinsic call that represents an alignment
1603   /// assumption on the provided pointer.
1604   ///
1605   /// An optional offset can be provided, and if it is provided, the offset
1606   /// must be subtracted from the provided pointer to get the pointer with the
1607   /// specified alignment.
1608   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1609                                       unsigned Alignment,
1610                                       Value *OffsetValue = nullptr) {
1611     assert(isa<PointerType>(PtrValue->getType()) &&
1612            "trying to create an alignment assumption on a non-pointer?");
1613
1614     PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1615     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1616     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1617
1618     Value *Mask = ConstantInt::get(IntPtrTy,
1619       Alignment > 0 ? Alignment - 1 : 0);
1620     if (OffsetValue) {
1621       bool IsOffsetZero = false;
1622       if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1623         IsOffsetZero = CI->isZero();
1624
1625       if (!IsOffsetZero) {
1626         if (OffsetValue->getType() != IntPtrTy)
1627           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1628                                       "offsetcast");
1629         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1630       }
1631     }
1632
1633     Value *Zero = ConstantInt::get(IntPtrTy, 0);
1634     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1635     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1636
1637     return CreateAssumption(InvCond);
1638   }
1639 };
1640
1641 // Create wrappers for C Binding types (see CBindingWrapping.h).
1642 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1643
1644 }
1645
1646 #endif