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