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