Change MachineFrameInfo::StackObject::Alloca from Value* to AllocaInst*
[oota-llvm.git] / include / llvm / 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_IRBUILDER_H
16 #define LLVM_IRBUILDER_H
17
18 #include "llvm/Instructions.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/LLVMContext.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/ConstantFolder.h"
25
26 namespace llvm {
27   class MDNode;
28
29 /// IRBuilderDefaultInserter - This provides the default implementation of the
30 /// IRBuilder 'InsertHelper' method that is called whenever an instruction is
31 /// created by IRBuilder and needs to be inserted.  By default, this inserts the
32 /// instruction at the insertion point.
33 template <bool preserveNames = true>
34 class IRBuilderDefaultInserter {
35 protected:
36   void InsertHelper(Instruction *I, const Twine &Name,
37                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
38     if (BB) BB->getInstList().insert(InsertPt, I);
39     if (preserveNames)
40       I->setName(Name);
41   }
42 };
43
44 /// IRBuilderBase - Common base class shared among various IRBuilders.
45 class IRBuilderBase {
46   DebugLoc CurDbgLocation;
47 protected:
48   BasicBlock *BB;
49   BasicBlock::iterator InsertPt;
50   LLVMContext &Context;
51 public:
52
53   IRBuilderBase(LLVMContext &context)
54     : Context(context) {
55     ClearInsertionPoint();
56   }
57
58   //===--------------------------------------------------------------------===//
59   // Builder configuration methods
60   //===--------------------------------------------------------------------===//
61
62   /// ClearInsertionPoint - Clear the insertion point: created instructions will
63   /// not be inserted into a block.
64   void ClearInsertionPoint() {
65     BB = 0;
66   }
67
68   BasicBlock *GetInsertBlock() const { return BB; }
69   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
70   LLVMContext &getContext() const { return Context; }
71
72   /// SetInsertPoint - This specifies that created instructions should be
73   /// appended to the end of the specified block.
74   void SetInsertPoint(BasicBlock *TheBB) {
75     BB = TheBB;
76     InsertPt = BB->end();
77   }
78
79   /// SetInsertPoint - This specifies that created instructions should be
80   /// inserted before the specified instruction.
81   void SetInsertPoint(Instruction *I) {
82     BB = I->getParent();
83     InsertPt = I;
84     SetCurrentDebugLocation(I->getDebugLoc());
85   }
86
87   /// SetInsertPoint - This specifies that created instructions should be
88   /// inserted at the specified point.
89   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
90     BB = TheBB;
91     InsertPt = IP;
92   }
93
94   /// SetInsertPoint(Use) - Find the nearest point that dominates this use, and
95   /// specify that created instructions should be inserted at this point.
96   void SetInsertPoint(Use &U) {
97     Instruction *UseInst = cast<Instruction>(U.getUser());
98     if (PHINode *Phi = dyn_cast<PHINode>(UseInst)) {
99       BasicBlock *PredBB = Phi->getIncomingBlock(U);
100       assert(U != PredBB->getTerminator() && "critical edge not split");
101       SetInsertPoint(PredBB, PredBB->getTerminator());
102       return;
103     }
104     SetInsertPoint(UseInst);
105   }
106
107   /// SetCurrentDebugLocation - Set location information used by debugging
108   /// information.
109   void SetCurrentDebugLocation(const DebugLoc &L) {
110     CurDbgLocation = L;
111   }
112
113   /// getCurrentDebugLocation - Get location information used by debugging
114   /// information.
115   DebugLoc getCurrentDebugLocation() const { return CurDbgLocation; }
116
117   /// SetInstDebugLocation - If this builder has a current debug location, set
118   /// it on the specified instruction.
119   void SetInstDebugLocation(Instruction *I) const {
120     if (!CurDbgLocation.isUnknown())
121       I->setDebugLoc(CurDbgLocation);
122   }
123
124   /// getCurrentFunctionReturnType - Get the return type of the current function
125   /// that we're emitting into.
126   Type *getCurrentFunctionReturnType() const;
127
128   /// InsertPoint - A saved insertion point.
129   class InsertPoint {
130     BasicBlock *Block;
131     BasicBlock::iterator Point;
132
133   public:
134     /// Creates a new insertion point which doesn't point to anything.
135     InsertPoint() : Block(0) {}
136
137     /// Creates a new insertion point at the given location.
138     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
139       : Block(InsertBlock), Point(InsertPoint) {}
140
141     /// isSet - Returns true if this insert point is set.
142     bool isSet() const { return (Block != 0); }
143
144     llvm::BasicBlock *getBlock() const { return Block; }
145     llvm::BasicBlock::iterator getPoint() const { return Point; }
146   };
147
148   /// saveIP - Returns the current insert point.
149   InsertPoint saveIP() const {
150     return InsertPoint(GetInsertBlock(), GetInsertPoint());
151   }
152
153   /// saveAndClearIP - Returns the current insert point, clearing it
154   /// in the process.
155   InsertPoint saveAndClearIP() {
156     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
157     ClearInsertionPoint();
158     return IP;
159   }
160
161   /// restoreIP - Sets the current insert point to a previously-saved
162   /// location.
163   void restoreIP(InsertPoint IP) {
164     if (IP.isSet())
165       SetInsertPoint(IP.getBlock(), IP.getPoint());
166     else
167       ClearInsertionPoint();
168   }
169
170   //===--------------------------------------------------------------------===//
171   // Miscellaneous creation methods.
172   //===--------------------------------------------------------------------===//
173
174   /// CreateGlobalString - Make a new global variable with an initializer that
175   /// has array of i8 type filled in with the nul terminated string value
176   /// specified.  The new global variable will be marked mergable with any
177   /// others of the same contents.  If Name is specified, it is the name of the
178   /// global variable created.
179   Value *CreateGlobalString(StringRef Str, const Twine &Name = "");
180
181   /// getInt1 - Get a constant value representing either true or false.
182   ConstantInt *getInt1(bool V) {
183     return ConstantInt::get(getInt1Ty(), V);
184   }
185
186   /// getTrue - Get the constant value for i1 true.
187   ConstantInt *getTrue() {
188     return ConstantInt::getTrue(Context);
189   }
190
191   /// getFalse - Get the constant value for i1 false.
192   ConstantInt *getFalse() {
193     return ConstantInt::getFalse(Context);
194   }
195
196   /// getInt8 - Get a constant 8-bit value.
197   ConstantInt *getInt8(uint8_t C) {
198     return ConstantInt::get(getInt8Ty(), C);
199   }
200
201   /// getInt16 - Get a constant 16-bit value.
202   ConstantInt *getInt16(uint16_t C) {
203     return ConstantInt::get(getInt16Ty(), C);
204   }
205
206   /// getInt32 - Get a constant 32-bit value.
207   ConstantInt *getInt32(uint32_t C) {
208     return ConstantInt::get(getInt32Ty(), C);
209   }
210
211   /// getInt64 - Get a constant 64-bit value.
212   ConstantInt *getInt64(uint64_t C) {
213     return ConstantInt::get(getInt64Ty(), C);
214   }
215
216   /// getInt - Get a constant integer value.
217   ConstantInt *getInt(const APInt &AI) {
218     return ConstantInt::get(Context, AI);
219   }
220
221   //===--------------------------------------------------------------------===//
222   // Type creation methods
223   //===--------------------------------------------------------------------===//
224
225   /// getInt1Ty - Fetch the type representing a single bit
226   IntegerType *getInt1Ty() {
227     return Type::getInt1Ty(Context);
228   }
229
230   /// getInt8Ty - Fetch the type representing an 8-bit integer.
231   IntegerType *getInt8Ty() {
232     return Type::getInt8Ty(Context);
233   }
234
235   /// getInt16Ty - Fetch the type representing a 16-bit integer.
236   IntegerType *getInt16Ty() {
237     return Type::getInt16Ty(Context);
238   }
239
240   /// getInt32Ty - Fetch the type resepresenting a 32-bit integer.
241   IntegerType *getInt32Ty() {
242     return Type::getInt32Ty(Context);
243   }
244
245   /// getInt64Ty - Fetch the type representing a 64-bit integer.
246   IntegerType *getInt64Ty() {
247     return Type::getInt64Ty(Context);
248   }
249
250   /// getFloatTy - Fetch the type representing a 32-bit floating point value.
251   Type *getFloatTy() {
252     return Type::getFloatTy(Context);
253   }
254
255   /// getDoubleTy - Fetch the type representing a 64-bit floating point value.
256   Type *getDoubleTy() {
257     return Type::getDoubleTy(Context);
258   }
259
260   /// getVoidTy - Fetch the type representing void.
261   Type *getVoidTy() {
262     return Type::getVoidTy(Context);
263   }
264
265   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
266     return Type::getInt8PtrTy(Context, AddrSpace);
267   }
268
269   //===--------------------------------------------------------------------===//
270   // Intrinsic creation methods
271   //===--------------------------------------------------------------------===//
272
273   /// CreateMemSet - Create and insert a memset to the specified pointer and the
274   /// specified value.  If the pointer isn't an i8*, it will be converted.  If a
275   /// TBAA tag is specified, it will be added to the instruction.
276   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
277                          bool isVolatile = false, MDNode *TBAATag = 0) {
278     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile, TBAATag);
279   }
280
281   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
282                          bool isVolatile = false, MDNode *TBAATag = 0);
283
284   /// CreateMemCpy - Create and insert a memcpy between the specified pointers.
285   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
286   /// specified, it will be added to the instruction.
287   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
288                          bool isVolatile = false, MDNode *TBAATag = 0,
289                          MDNode *TBAAStructTag = 0) {
290     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
291                         TBAAStructTag);
292   }
293
294   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
295                          bool isVolatile = false, MDNode *TBAATag = 0,
296                          MDNode *TBAAStructTag = 0);
297
298   /// CreateMemMove - Create and insert a memmove between the specified
299   /// pointers.  If the pointers aren't i8*, they will be converted.  If a TBAA
300   /// tag is specified, it will be added to the instruction.
301   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
302                           bool isVolatile = false, MDNode *TBAATag = 0) {
303     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag);
304   }
305
306   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
307                           bool isVolatile = false, MDNode *TBAATag = 0);
308
309   /// CreateLifetimeStart - Create a lifetime.start intrinsic.  If the pointer
310   /// isn't i8* it will be converted.
311   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = 0);
312
313   /// CreateLifetimeEnd - Create a lifetime.end intrinsic.  If the pointer isn't
314   /// i8* it will be converted.
315   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = 0);
316
317 private:
318   Value *getCastedInt8PtrValue(Value *Ptr);
319 };
320
321 /// IRBuilder - This provides a uniform API for creating instructions and
322 /// inserting them into a basic block: either at the end of a BasicBlock, or
323 /// at a specific iterator location in a block.
324 ///
325 /// Note that the builder does not expose the full generality of LLVM
326 /// instructions.  For access to extra instruction properties, use the mutators
327 /// (e.g. setVolatile) on the instructions after they have been created.
328 /// The first template argument handles whether or not to preserve names in the
329 /// final instruction output. This defaults to on.  The second template argument
330 /// specifies a class to use for creating constants.  This defaults to creating
331 /// minimally folded constants.  The fourth template argument allows clients to
332 /// specify custom insertion hooks that are called on every newly created
333 /// insertion.
334 template<bool preserveNames = true, typename T = ConstantFolder,
335          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
336 class IRBuilder : public IRBuilderBase, public Inserter {
337   T Folder;
338   MDNode *DefaultFPMathTag;
339 public:
340   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
341             MDNode *FPMathTag = 0)
342     : IRBuilderBase(C), Inserter(I), Folder(F), DefaultFPMathTag(FPMathTag) {
343   }
344
345   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = 0) : IRBuilderBase(C),
346     Folder(), DefaultFPMathTag(FPMathTag) {
347   }
348
349   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = 0)
350     : IRBuilderBase(TheBB->getContext()), Folder(F),
351       DefaultFPMathTag(FPMathTag) {
352     SetInsertPoint(TheBB);
353   }
354
355   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = 0)
356     : IRBuilderBase(TheBB->getContext()), Folder(),
357       DefaultFPMathTag(FPMathTag) {
358     SetInsertPoint(TheBB);
359   }
360
361   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = 0)
362     : IRBuilderBase(IP->getContext()), Folder(), DefaultFPMathTag(FPMathTag) {
363     SetInsertPoint(IP);
364     SetCurrentDebugLocation(IP->getDebugLoc());
365   }
366
367   explicit IRBuilder(Use &U, MDNode *FPMathTag = 0)
368     : IRBuilderBase(U->getContext()), Folder(), DefaultFPMathTag(FPMathTag) {
369     SetInsertPoint(U);
370     SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
371   }
372
373   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
374             MDNode *FPMathTag = 0)
375     : IRBuilderBase(TheBB->getContext()), Folder(F),
376       DefaultFPMathTag(FPMathTag) {
377     SetInsertPoint(TheBB, IP);
378   }
379
380   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, MDNode *FPMathTag = 0)
381     : IRBuilderBase(TheBB->getContext()), Folder(),
382       DefaultFPMathTag(FPMathTag) {
383     SetInsertPoint(TheBB, IP);
384   }
385
386   /// getFolder - Get the constant folder being used.
387   const T &getFolder() { return Folder; }
388
389   /// getDefaultFPMathTag - Get the floating point math metadata being used.
390   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
391
392   /// SetDefaultFPMathTag - Set the floating point math metadata to be used.
393   void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
394
395   /// isNamePreserving - Return true if this builder is configured to actually
396   /// add the requested names to IR created through it.
397   bool isNamePreserving() const { return preserveNames; }
398
399   /// Insert - Insert and return the specified instruction.
400   template<typename InstTy>
401   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
402     this->InsertHelper(I, Name, BB, InsertPt);
403     if (!getCurrentDebugLocation().isUnknown())
404       this->SetInstDebugLocation(I);
405     return I;
406   }
407
408   /// Insert - No-op overload to handle constants.
409   Constant *Insert(Constant *C, const Twine& = "") const {
410     return C;
411   }
412
413   //===--------------------------------------------------------------------===//
414   // Instruction creation methods: Terminators
415   //===--------------------------------------------------------------------===//
416
417 private:
418   /// \brief Helper to add branch weight metadata onto an instruction.
419   /// \returns The annotated instruction.
420   template <typename InstTy>
421   InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
422     if (Weights)
423       I->setMetadata(LLVMContext::MD_prof, Weights);
424     return I;
425   }
426
427 public:
428   /// CreateRetVoid - Create a 'ret void' instruction.
429   ReturnInst *CreateRetVoid() {
430     return Insert(ReturnInst::Create(Context));
431   }
432
433   /// @verbatim
434   /// CreateRet - Create a 'ret <val>' instruction.
435   /// @endverbatim
436   ReturnInst *CreateRet(Value *V) {
437     return Insert(ReturnInst::Create(Context, V));
438   }
439
440   /// CreateAggregateRet - Create a sequence of N insertvalue instructions,
441   /// with one Value from the retVals array each, that build a aggregate
442   /// return value one value at a time, and a ret instruction to return
443   /// the resulting aggregate value. This is a convenience function for
444   /// code that uses aggregate return values as a vehicle for having
445   /// multiple return values.
446   ///
447   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
448     Value *V = UndefValue::get(getCurrentFunctionReturnType());
449     for (unsigned i = 0; i != N; ++i)
450       V = CreateInsertValue(V, retVals[i], i, "mrv");
451     return Insert(ReturnInst::Create(Context, V));
452   }
453
454   /// CreateBr - Create an unconditional 'br label X' instruction.
455   BranchInst *CreateBr(BasicBlock *Dest) {
456     return Insert(BranchInst::Create(Dest));
457   }
458
459   /// CreateCondBr - Create a conditional 'br Cond, TrueDest, FalseDest'
460   /// instruction.
461   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
462                            MDNode *BranchWeights = 0) {
463     return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
464                                    BranchWeights));
465   }
466
467   /// CreateSwitch - Create a switch instruction with the specified value,
468   /// default dest, and with a hint for the number of cases that will be added
469   /// (for efficient allocation).
470   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
471                            MDNode *BranchWeights = 0) {
472     return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
473                                    BranchWeights));
474   }
475
476   /// CreateIndirectBr - Create an indirect branch instruction with the
477   /// specified address operand, with an optional hint for the number of
478   /// destinations that will be added (for efficient allocation).
479   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
480     return Insert(IndirectBrInst::Create(Addr, NumDests));
481   }
482
483   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
484                            BasicBlock *UnwindDest, const Twine &Name = "") {
485     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest,
486                                      ArrayRef<Value *>()),
487                   Name);
488   }
489   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
490                            BasicBlock *UnwindDest, Value *Arg1,
491                            const Twine &Name = "") {
492     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
493                   Name);
494   }
495   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
496                             BasicBlock *UnwindDest, Value *Arg1,
497                             Value *Arg2, Value *Arg3,
498                             const Twine &Name = "") {
499     Value *Args[] = { Arg1, Arg2, Arg3 };
500     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
501                   Name);
502   }
503   /// CreateInvoke - Create an invoke instruction.
504   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
505                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
506                            const Twine &Name = "") {
507     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
508                   Name);
509   }
510
511   ResumeInst *CreateResume(Value *Exn) {
512     return Insert(ResumeInst::Create(Exn));
513   }
514
515   UnreachableInst *CreateUnreachable() {
516     return Insert(new UnreachableInst(Context));
517   }
518
519   //===--------------------------------------------------------------------===//
520   // Instruction creation methods: Binary Operators
521   //===--------------------------------------------------------------------===//
522 private:
523   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
524                                           Value *LHS, Value *RHS,
525                                           const Twine &Name,
526                                           bool HasNUW, bool HasNSW) {
527     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
528     if (HasNUW) BO->setHasNoUnsignedWrap();
529     if (HasNSW) BO->setHasNoSignedWrap();
530     return BO;
531   }
532
533   Instruction *AddFPMathTag(Instruction *I, MDNode *FPMathTag) const {
534     if (!FPMathTag)
535       FPMathTag = DefaultFPMathTag;
536     if (FPMathTag)
537       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
538     return I;
539   }
540 public:
541   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
542                    bool HasNUW = false, bool HasNSW = false) {
543     if (Constant *LC = dyn_cast<Constant>(LHS))
544       if (Constant *RC = dyn_cast<Constant>(RHS))
545         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
546     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
547                                    HasNUW, HasNSW);
548   }
549   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
550     return CreateAdd(LHS, RHS, Name, false, true);
551   }
552   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
553     return CreateAdd(LHS, RHS, Name, true, false);
554   }
555   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
556                     MDNode *FPMathTag = 0) {
557     if (Constant *LC = dyn_cast<Constant>(LHS))
558       if (Constant *RC = dyn_cast<Constant>(RHS))
559         return Insert(Folder.CreateFAdd(LC, RC), Name);
560     return Insert(AddFPMathTag(BinaryOperator::CreateFAdd(LHS, RHS),
561                                FPMathTag), Name);
562   }
563   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
564                    bool HasNUW = false, bool HasNSW = false) {
565     if (Constant *LC = dyn_cast<Constant>(LHS))
566       if (Constant *RC = dyn_cast<Constant>(RHS))
567         return Insert(Folder.CreateSub(LC, RC), Name);
568     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
569                                    HasNUW, HasNSW);
570   }
571   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
572     return CreateSub(LHS, RHS, Name, false, true);
573   }
574   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
575     return CreateSub(LHS, RHS, Name, true, false);
576   }
577   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
578                     MDNode *FPMathTag = 0) {
579     if (Constant *LC = dyn_cast<Constant>(LHS))
580       if (Constant *RC = dyn_cast<Constant>(RHS))
581         return Insert(Folder.CreateFSub(LC, RC), Name);
582     return Insert(AddFPMathTag(BinaryOperator::CreateFSub(LHS, RHS),
583                                FPMathTag), Name);
584   }
585   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
586                    bool HasNUW = false, bool HasNSW = false) {
587     if (Constant *LC = dyn_cast<Constant>(LHS))
588       if (Constant *RC = dyn_cast<Constant>(RHS))
589         return Insert(Folder.CreateMul(LC, RC), Name);
590     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
591                                    HasNUW, HasNSW);
592   }
593   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
594     return CreateMul(LHS, RHS, Name, false, true);
595   }
596   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
597     return CreateMul(LHS, RHS, Name, true, false);
598   }
599   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
600                     MDNode *FPMathTag = 0) {
601     if (Constant *LC = dyn_cast<Constant>(LHS))
602       if (Constant *RC = dyn_cast<Constant>(RHS))
603         return Insert(Folder.CreateFMul(LC, RC), Name);
604     return Insert(AddFPMathTag(BinaryOperator::CreateFMul(LHS, RHS),
605                                FPMathTag), Name);
606   }
607   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
608                     bool isExact = false) {
609     if (Constant *LC = dyn_cast<Constant>(LHS))
610       if (Constant *RC = dyn_cast<Constant>(RHS))
611         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
612     if (!isExact)
613       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
614     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
615   }
616   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
617     return CreateUDiv(LHS, RHS, Name, true);
618   }
619   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
620                     bool isExact = false) {
621     if (Constant *LC = dyn_cast<Constant>(LHS))
622       if (Constant *RC = dyn_cast<Constant>(RHS))
623         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
624     if (!isExact)
625       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
626     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
627   }
628   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
629     return CreateSDiv(LHS, RHS, Name, true);
630   }
631   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
632                     MDNode *FPMathTag = 0) {
633     if (Constant *LC = dyn_cast<Constant>(LHS))
634       if (Constant *RC = dyn_cast<Constant>(RHS))
635         return Insert(Folder.CreateFDiv(LC, RC), Name);
636     return Insert(AddFPMathTag(BinaryOperator::CreateFDiv(LHS, RHS),
637                                FPMathTag), Name);
638   }
639   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
640     if (Constant *LC = dyn_cast<Constant>(LHS))
641       if (Constant *RC = dyn_cast<Constant>(RHS))
642         return Insert(Folder.CreateURem(LC, RC), Name);
643     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
644   }
645   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
646     if (Constant *LC = dyn_cast<Constant>(LHS))
647       if (Constant *RC = dyn_cast<Constant>(RHS))
648         return Insert(Folder.CreateSRem(LC, RC), Name);
649     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
650   }
651   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
652                     MDNode *FPMathTag = 0) {
653     if (Constant *LC = dyn_cast<Constant>(LHS))
654       if (Constant *RC = dyn_cast<Constant>(RHS))
655         return Insert(Folder.CreateFRem(LC, RC), Name);
656     return Insert(AddFPMathTag(BinaryOperator::CreateFRem(LHS, RHS),
657                                FPMathTag), Name);
658   }
659
660   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
661                    bool HasNUW = false, bool HasNSW = false) {
662     if (Constant *LC = dyn_cast<Constant>(LHS))
663       if (Constant *RC = dyn_cast<Constant>(RHS))
664         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
665     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
666                                    HasNUW, HasNSW);
667   }
668   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
669                    bool HasNUW = false, bool HasNSW = false) {
670     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
671                      HasNUW, HasNSW);
672   }
673   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
674                    bool HasNUW = false, bool HasNSW = false) {
675     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
676                      HasNUW, HasNSW);
677   }
678
679   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
680                     bool isExact = false) {
681     if (Constant *LC = dyn_cast<Constant>(LHS))
682       if (Constant *RC = dyn_cast<Constant>(RHS))
683         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
684     if (!isExact)
685       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
686     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
687   }
688   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
689                     bool isExact = false) {
690     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
691   }
692   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
693                     bool isExact = false) {
694     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
695   }
696
697   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
698                     bool isExact = false) {
699     if (Constant *LC = dyn_cast<Constant>(LHS))
700       if (Constant *RC = dyn_cast<Constant>(RHS))
701         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
702     if (!isExact)
703       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
704     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
705   }
706   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
707                     bool isExact = false) {
708     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
709   }
710   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
711                     bool isExact = false) {
712     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
713   }
714
715   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
716     if (Constant *RC = dyn_cast<Constant>(RHS)) {
717       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
718         return LHS;  // LHS & -1 -> LHS
719       if (Constant *LC = dyn_cast<Constant>(LHS))
720         return Insert(Folder.CreateAnd(LC, RC), Name);
721     }
722     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
723   }
724   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
725     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
726   }
727   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
728     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
729   }
730
731   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
732     if (Constant *RC = dyn_cast<Constant>(RHS)) {
733       if (RC->isNullValue())
734         return LHS;  // LHS | 0 -> LHS
735       if (Constant *LC = dyn_cast<Constant>(LHS))
736         return Insert(Folder.CreateOr(LC, RC), Name);
737     }
738     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
739   }
740   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
741     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
742   }
743   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
744     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
745   }
746
747   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
748     if (Constant *LC = dyn_cast<Constant>(LHS))
749       if (Constant *RC = dyn_cast<Constant>(RHS))
750         return Insert(Folder.CreateXor(LC, RC), Name);
751     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
752   }
753   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
754     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
755   }
756   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
757     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
758   }
759
760   Value *CreateBinOp(Instruction::BinaryOps Opc,
761                      Value *LHS, Value *RHS, const Twine &Name = "") {
762     if (Constant *LC = dyn_cast<Constant>(LHS))
763       if (Constant *RC = dyn_cast<Constant>(RHS))
764         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
765     return Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
766   }
767
768   Value *CreateNeg(Value *V, const Twine &Name = "",
769                    bool HasNUW = false, bool HasNSW = false) {
770     if (Constant *VC = dyn_cast<Constant>(V))
771       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
772     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
773     if (HasNUW) BO->setHasNoUnsignedWrap();
774     if (HasNSW) BO->setHasNoSignedWrap();
775     return BO;
776   }
777   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
778     return CreateNeg(V, Name, false, true);
779   }
780   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
781     return CreateNeg(V, Name, true, false);
782   }
783   Value *CreateFNeg(Value *V, const Twine &Name = "", MDNode *FPMathTag = 0) {
784     if (Constant *VC = dyn_cast<Constant>(V))
785       return Insert(Folder.CreateFNeg(VC), Name);
786     return Insert(AddFPMathTag(BinaryOperator::CreateFNeg(V), FPMathTag), Name);
787   }
788   Value *CreateNot(Value *V, const Twine &Name = "") {
789     if (Constant *VC = dyn_cast<Constant>(V))
790       return Insert(Folder.CreateNot(VC), Name);
791     return Insert(BinaryOperator::CreateNot(V), Name);
792   }
793
794   //===--------------------------------------------------------------------===//
795   // Instruction creation methods: Memory Instructions
796   //===--------------------------------------------------------------------===//
797
798   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = 0,
799                            const Twine &Name = "") {
800     return Insert(new AllocaInst(Ty, ArraySize), Name);
801   }
802   // Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
803   // converting the string to 'bool' for the isVolatile parameter.
804   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
805     return Insert(new LoadInst(Ptr), Name);
806   }
807   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
808     return Insert(new LoadInst(Ptr), Name);
809   }
810   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
811     return Insert(new LoadInst(Ptr, 0, isVolatile), Name);
812   }
813   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
814     return Insert(new StoreInst(Val, Ptr, isVolatile));
815   }
816   // Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly,
817   // instead of converting the string to 'bool' for the isVolatile parameter.
818   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
819     LoadInst *LI = CreateLoad(Ptr, Name);
820     LI->setAlignment(Align);
821     return LI;
822   }
823   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
824                               const Twine &Name = "") {
825     LoadInst *LI = CreateLoad(Ptr, Name);
826     LI->setAlignment(Align);
827     return LI;
828   }
829   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
830                               const Twine &Name = "") {
831     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
832     LI->setAlignment(Align);
833     return LI;
834   }
835   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
836                                 bool isVolatile = false) {
837     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
838     SI->setAlignment(Align);
839     return SI;
840   }
841   FenceInst *CreateFence(AtomicOrdering Ordering,
842                          SynchronizationScope SynchScope = CrossThread) {
843     return Insert(new FenceInst(Context, Ordering, SynchScope));
844   }
845   AtomicCmpXchgInst *CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
846                                          AtomicOrdering Ordering,
847                                SynchronizationScope SynchScope = CrossThread) {
848     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope));
849   }
850   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
851                                  AtomicOrdering Ordering,
852                                SynchronizationScope SynchScope = CrossThread) {
853     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
854   }
855   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
856                    const Twine &Name = "") {
857     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
858       // Every index must be constant.
859       size_t i, e;
860       for (i = 0, e = IdxList.size(); i != e; ++i)
861         if (!isa<Constant>(IdxList[i]))
862           break;
863       if (i == e)
864         return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
865     }
866     return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
867   }
868   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
869                            const Twine &Name = "") {
870     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
871       // Every index must be constant.
872       size_t i, e;
873       for (i = 0, e = IdxList.size(); i != e; ++i)
874         if (!isa<Constant>(IdxList[i]))
875           break;
876       if (i == e)
877         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
878     }
879     return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
880   }
881   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
882     if (Constant *PC = dyn_cast<Constant>(Ptr))
883       if (Constant *IC = dyn_cast<Constant>(Idx))
884         return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
885     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
886   }
887   Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
888     if (Constant *PC = dyn_cast<Constant>(Ptr))
889       if (Constant *IC = dyn_cast<Constant>(Idx))
890         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
891     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
892   }
893   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
894     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
895
896     if (Constant *PC = dyn_cast<Constant>(Ptr))
897       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
898
899     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
900   }
901   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
902                                     const Twine &Name = "") {
903     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
904
905     if (Constant *PC = dyn_cast<Constant>(Ptr))
906       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
907
908     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
909   }
910   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
911                     const Twine &Name = "") {
912     Value *Idxs[] = {
913       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
914       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
915     };
916
917     if (Constant *PC = dyn_cast<Constant>(Ptr))
918       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
919
920     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
921   }
922   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
923                                     const Twine &Name = "") {
924     Value *Idxs[] = {
925       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
926       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
927     };
928
929     if (Constant *PC = dyn_cast<Constant>(Ptr))
930       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
931
932     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
933   }
934   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
935     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
936
937     if (Constant *PC = dyn_cast<Constant>(Ptr))
938       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
939
940     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
941   }
942   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
943                                     const Twine &Name = "") {
944     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
945
946     if (Constant *PC = dyn_cast<Constant>(Ptr))
947       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
948
949     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
950   }
951   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
952                     const Twine &Name = "") {
953     Value *Idxs[] = {
954       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
955       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
956     };
957
958     if (Constant *PC = dyn_cast<Constant>(Ptr))
959       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
960
961     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
962   }
963   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
964                                     const Twine &Name = "") {
965     Value *Idxs[] = {
966       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
967       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
968     };
969
970     if (Constant *PC = dyn_cast<Constant>(Ptr))
971       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
972
973     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
974   }
975   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
976     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
977   }
978
979   /// CreateGlobalStringPtr - Same as CreateGlobalString, but return a pointer
980   /// with "i8*" type instead of a pointer to array of i8.
981   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
982     Value *gv = CreateGlobalString(Str, Name);
983     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
984     Value *Args[] = { zero, zero };
985     return CreateInBoundsGEP(gv, Args, Name);
986   }
987
988   //===--------------------------------------------------------------------===//
989   // Instruction creation methods: Cast/Conversion Operators
990   //===--------------------------------------------------------------------===//
991
992   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
993     return CreateCast(Instruction::Trunc, V, DestTy, Name);
994   }
995   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
996     return CreateCast(Instruction::ZExt, V, DestTy, Name);
997   }
998   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
999     return CreateCast(Instruction::SExt, V, DestTy, Name);
1000   }
1001   /// CreateZExtOrTrunc - Create a ZExt or Trunc from the integer value V to
1002   /// DestTy. Return the value untouched if the type of V is already DestTy.
1003   Value *CreateZExtOrTrunc(Value *V, IntegerType *DestTy,
1004                            const Twine &Name = "") {
1005     assert(isa<IntegerType>(V->getType()) && "Can only zero extend integers!");
1006     IntegerType *IntTy = cast<IntegerType>(V->getType());
1007     if (IntTy->getBitWidth() < DestTy->getBitWidth())
1008       return CreateZExt(V, DestTy, Name);
1009     if (IntTy->getBitWidth() > DestTy->getBitWidth())
1010       return CreateTrunc(V, DestTy, Name);
1011     return V;
1012   }
1013   /// CreateSExtOrTrunc - Create a SExt or Trunc from the integer value V to
1014   /// DestTy. Return the value untouched if the type of V is already DestTy.
1015   Value *CreateSExtOrTrunc(Value *V, IntegerType *DestTy,
1016                            const Twine &Name = "") {
1017     assert(isa<IntegerType>(V->getType()) && "Can only sign extend integers!");
1018     IntegerType *IntTy = cast<IntegerType>(V->getType());
1019     if (IntTy->getBitWidth() < DestTy->getBitWidth())
1020       return CreateSExt(V, DestTy, Name);
1021     if (IntTy->getBitWidth() > DestTy->getBitWidth())
1022       return CreateTrunc(V, DestTy, Name);
1023     return V;
1024   }
1025   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1026     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1027   }
1028   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1029     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1030   }
1031   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1032     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1033   }
1034   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1035     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1036   }
1037   Value *CreateFPTrunc(Value *V, Type *DestTy,
1038                        const Twine &Name = "") {
1039     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1040   }
1041   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1042     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1043   }
1044   Value *CreatePtrToInt(Value *V, Type *DestTy,
1045                         const Twine &Name = "") {
1046     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1047   }
1048   Value *CreateIntToPtr(Value *V, Type *DestTy,
1049                         const Twine &Name = "") {
1050     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1051   }
1052   Value *CreateBitCast(Value *V, Type *DestTy,
1053                        const Twine &Name = "") {
1054     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1055   }
1056   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1057                              const Twine &Name = "") {
1058     if (V->getType() == DestTy)
1059       return V;
1060     if (Constant *VC = dyn_cast<Constant>(V))
1061       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1062     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1063   }
1064   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1065                              const Twine &Name = "") {
1066     if (V->getType() == DestTy)
1067       return V;
1068     if (Constant *VC = dyn_cast<Constant>(V))
1069       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1070     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1071   }
1072   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1073                               const Twine &Name = "") {
1074     if (V->getType() == DestTy)
1075       return V;
1076     if (Constant *VC = dyn_cast<Constant>(V))
1077       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1078     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1079   }
1080   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1081                     const Twine &Name = "") {
1082     if (V->getType() == DestTy)
1083       return V;
1084     if (Constant *VC = dyn_cast<Constant>(V))
1085       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1086     return Insert(CastInst::Create(Op, V, DestTy), Name);
1087   }
1088   Value *CreatePointerCast(Value *V, Type *DestTy,
1089                            const Twine &Name = "") {
1090     if (V->getType() == DestTy)
1091       return V;
1092     if (Constant *VC = dyn_cast<Constant>(V))
1093       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1094     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1095   }
1096   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1097                        const Twine &Name = "") {
1098     if (V->getType() == DestTy)
1099       return V;
1100     if (Constant *VC = dyn_cast<Constant>(V))
1101       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1102     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1103   }
1104 private:
1105   // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a compile time
1106   // error, instead of converting the string to bool for the isSigned parameter.
1107   Value *CreateIntCast(Value *, Type *, const char *) LLVM_DELETED_FUNCTION;
1108 public:
1109   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1110     if (V->getType() == DestTy)
1111       return V;
1112     if (Constant *VC = dyn_cast<Constant>(V))
1113       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1114     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1115   }
1116
1117   //===--------------------------------------------------------------------===//
1118   // Instruction creation methods: Compare Instructions
1119   //===--------------------------------------------------------------------===//
1120
1121   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1122     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1123   }
1124   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1125     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1126   }
1127   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1128     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1129   }
1130   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1131     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1132   }
1133   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1134     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1135   }
1136   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1137     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1138   }
1139   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1140     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1141   }
1142   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1143     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1144   }
1145   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1146     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1147   }
1148   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1149     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1150   }
1151
1152   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1153     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1154   }
1155   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1156     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1157   }
1158   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1159     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1160   }
1161   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1162     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1163   }
1164   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1165     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1166   }
1167   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1168     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1169   }
1170   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1171     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1172   }
1173   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1174     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1175   }
1176   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1177     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1178   }
1179   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1180     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1181   }
1182   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1183     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1184   }
1185   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1186     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1187   }
1188   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1189     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1190   }
1191   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1192     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1193   }
1194
1195   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1196                     const Twine &Name = "") {
1197     if (Constant *LC = dyn_cast<Constant>(LHS))
1198       if (Constant *RC = dyn_cast<Constant>(RHS))
1199         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1200     return Insert(new ICmpInst(P, LHS, RHS), Name);
1201   }
1202   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1203                     const Twine &Name = "") {
1204     if (Constant *LC = dyn_cast<Constant>(LHS))
1205       if (Constant *RC = dyn_cast<Constant>(RHS))
1206         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1207     return Insert(new FCmpInst(P, LHS, RHS), Name);
1208   }
1209
1210   //===--------------------------------------------------------------------===//
1211   // Instruction creation methods: Other Instructions
1212   //===--------------------------------------------------------------------===//
1213
1214   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1215                      const Twine &Name = "") {
1216     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1217   }
1218
1219   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1220     return Insert(CallInst::Create(Callee), Name);
1221   }
1222   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1223     return Insert(CallInst::Create(Callee, Arg), Name);
1224   }
1225   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1226                         const Twine &Name = "") {
1227     Value *Args[] = { Arg1, Arg2 };
1228     return Insert(CallInst::Create(Callee, Args), Name);
1229   }
1230   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1231                         const Twine &Name = "") {
1232     Value *Args[] = { Arg1, Arg2, Arg3 };
1233     return Insert(CallInst::Create(Callee, Args), Name);
1234   }
1235   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1236                         Value *Arg4, const Twine &Name = "") {
1237     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1238     return Insert(CallInst::Create(Callee, Args), Name);
1239   }
1240   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1241                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
1242     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1243     return Insert(CallInst::Create(Callee, Args), Name);
1244   }
1245
1246   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1247                        const Twine &Name = "") {
1248     return Insert(CallInst::Create(Callee, Args), Name);
1249   }
1250
1251   Value *CreateSelect(Value *C, Value *True, Value *False,
1252                       const Twine &Name = "") {
1253     if (Constant *CC = dyn_cast<Constant>(C))
1254       if (Constant *TC = dyn_cast<Constant>(True))
1255         if (Constant *FC = dyn_cast<Constant>(False))
1256           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1257     return Insert(SelectInst::Create(C, True, False), Name);
1258   }
1259
1260   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1261     return Insert(new VAArgInst(List, Ty), Name);
1262   }
1263
1264   Value *CreateExtractElement(Value *Vec, Value *Idx,
1265                               const Twine &Name = "") {
1266     if (Constant *VC = dyn_cast<Constant>(Vec))
1267       if (Constant *IC = dyn_cast<Constant>(Idx))
1268         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1269     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1270   }
1271
1272   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1273                              const Twine &Name = "") {
1274     if (Constant *VC = dyn_cast<Constant>(Vec))
1275       if (Constant *NC = dyn_cast<Constant>(NewElt))
1276         if (Constant *IC = dyn_cast<Constant>(Idx))
1277           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1278     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1279   }
1280
1281   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1282                              const Twine &Name = "") {
1283     if (Constant *V1C = dyn_cast<Constant>(V1))
1284       if (Constant *V2C = dyn_cast<Constant>(V2))
1285         if (Constant *MC = dyn_cast<Constant>(Mask))
1286           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1287     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1288   }
1289
1290   Value *CreateExtractValue(Value *Agg,
1291                             ArrayRef<unsigned> Idxs,
1292                             const Twine &Name = "") {
1293     if (Constant *AggC = dyn_cast<Constant>(Agg))
1294       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1295     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1296   }
1297
1298   Value *CreateInsertValue(Value *Agg, Value *Val,
1299                            ArrayRef<unsigned> Idxs,
1300                            const Twine &Name = "") {
1301     if (Constant *AggC = dyn_cast<Constant>(Agg))
1302       if (Constant *ValC = dyn_cast<Constant>(Val))
1303         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1304     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1305   }
1306
1307   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1308                                    const Twine &Name = "") {
1309     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses, Name));
1310   }
1311
1312   //===--------------------------------------------------------------------===//
1313   // Utility creation methods
1314   //===--------------------------------------------------------------------===//
1315
1316   /// CreateIsNull - Return an i1 value testing if \p Arg is null.
1317   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1318     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1319                         Name);
1320   }
1321
1322   /// CreateIsNotNull - Return an i1 value testing if \p Arg is not null.
1323   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1324     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1325                         Name);
1326   }
1327
1328   /// CreatePtrDiff - Return the i64 difference between two pointer values,
1329   /// dividing out the size of the pointed-to objects.  This is intended to
1330   /// implement C-style pointer subtraction. As such, the pointers must be
1331   /// appropriately aligned for their element types and pointing into the
1332   /// same object.
1333   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1334     assert(LHS->getType() == RHS->getType() &&
1335            "Pointer subtraction operand types must match!");
1336     PointerType *ArgType = cast<PointerType>(LHS->getType());
1337     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1338     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1339     Value *Difference = CreateSub(LHS_int, RHS_int);
1340     return CreateExactSDiv(Difference,
1341                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1342                            Name);
1343   }
1344 };
1345
1346 }
1347
1348 #endif