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