05c3c569aa1a7a4fbde2da64d343c4fe313ec819
[oota-llvm.git] / include / llvm / Support / IRBuilder.h
1 //===---- llvm/Support/IRBuilder.h - Builder for LLVM Instrs ----*- 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_SUPPORT_IRBUILDER_H
16 #define LLVM_SUPPORT_IRBUILDER_H
17
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Function.h"
23 #include "llvm/Metadata.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/ConstantFolder.h"
27
28 namespace llvm {
29
30 /// IRBuilderDefaultInserter - This provides the default implementation of the
31 /// IRBuilder 'InsertHelper' method that is called whenever an instruction is
32 /// created by IRBuilder and needs to be inserted.  By default, this inserts the
33 /// instruction at the insertion point.
34 template <bool preserveNames = true>
35 class IRBuilderDefaultInserter {
36 protected:
37   void InsertHelper(Instruction *I, const Twine &Name,
38                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
39     if (BB) BB->getInstList().insert(InsertPt, I);
40     if (preserveNames)
41       I->setName(Name);
42   }
43 };
44   
45   
46 /// IRBuilder - This provides a uniform API for creating instructions and
47 /// inserting them into a basic block: either at the end of a BasicBlock, or
48 /// at a specific iterator location in a block.
49 ///
50 /// Note that the builder does not expose the full generality of LLVM
51 /// instructions.  For access to extra instruction properties, use the mutators
52 /// (e.g. setVolatile) on the instructions after they have been created.
53 /// The first template argument handles whether or not to preserve names in the
54 /// final instruction output. This defaults to on.  The second template argument
55 /// specifies a class to use for creating constants.  This defaults to creating
56 /// minimally folded constants.  The fourth template argument allows clients to
57 /// specify custom insertion hooks that are called on every newly created
58 /// insertion.
59 template<bool preserveNames = true, typename T = ConstantFolder,
60          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
61 class IRBuilder : public Inserter {
62   BasicBlock *BB;
63   BasicBlock::iterator InsertPt;
64   unsigned MDKind;
65   MDNode *CurDbgLocation;
66   LLVMContext &Context;
67   T Folder;
68 public:
69   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter())
70     : Inserter(I), MDKind(0), CurDbgLocation(0), Context(C), Folder(F) {
71     ClearInsertionPoint(); 
72   }
73   
74   explicit IRBuilder(LLVMContext &C) 
75     : MDKind(0), CurDbgLocation(0), Context(C), Folder(C) {
76     ClearInsertionPoint();
77   }
78   
79   explicit IRBuilder(BasicBlock *TheBB, const T &F)
80     : MDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(F) {
81     SetInsertPoint(TheBB);
82   }
83   
84   explicit IRBuilder(BasicBlock *TheBB)
85     : MDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), 
86       Folder(Context) {
87     SetInsertPoint(TheBB);
88   }
89   
90   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F)
91     : MDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), Folder(F) {
92     SetInsertPoint(TheBB, IP);
93   }
94   
95   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP)
96     : MDKind(0), CurDbgLocation(0), Context(TheBB->getContext()), 
97       Folder(Context) {
98     SetInsertPoint(TheBB, IP);
99   }
100
101   /// getFolder - Get the constant folder being used.
102   const T &getFolder() { return Folder; }
103
104   /// isNamePreserving - Return true if this builder is configured to actually
105   /// add the requested names to IR created through it.
106   bool isNamePreserving() const { return preserveNames; }
107   
108   //===--------------------------------------------------------------------===//
109   // Builder configuration methods
110   //===--------------------------------------------------------------------===//
111
112   /// ClearInsertionPoint - Clear the insertion point: created instructions will
113   /// not be inserted into a block.
114   void ClearInsertionPoint() {
115     BB = 0;
116   }
117
118   BasicBlock *GetInsertBlock() const { return BB; }
119
120   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
121
122   /// SetInsertPoint - This specifies that created instructions should be
123   /// appended to the end of the specified block.
124   void SetInsertPoint(BasicBlock *TheBB) {
125     BB = TheBB;
126     InsertPt = BB->end();
127   }
128
129   /// SetInsertPoint - This specifies that created instructions should be
130   /// inserted at the specified point.
131   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
132     BB = TheBB;
133     InsertPt = IP;
134   }
135
136   /// SetCurrentDebugLocation - Set location information used by debugging
137   /// information.
138   void SetCurrentDebugLocation(MDNode *L) {
139     if (MDKind == 0) 
140       MDKind = Context.getMetadata().getMDKind("dbg");
141     if (MDKind == 0)
142       MDKind = Context.getMetadata().registerMDKind("dbg");
143     CurDbgLocation = L;
144   }
145
146   MDNode *getCurrentDebugLocation() const { return CurDbgLocation; }
147
148   /// SetDebugLocation -  Set location information for the given instruction.
149   void SetDebugLocation(Instruction *I) {
150     if (CurDbgLocation)
151       Context.getMetadata().addMD(MDKind, CurDbgLocation, I);
152   }
153
154   /// SetDebugLocation -  Set location information for the given instruction.
155   void SetDebugLocation(Instruction *I, MDNode *Loc) {
156     if (MDKind == 0) 
157       MDKind = Context.getMetadata().getMDKind("dbg");
158     if (MDKind == 0)
159       MDKind = Context.getMetadata().registerMDKind("dbg");
160     Context.getMetadata().addMD(MDKind, Loc, I);
161   }
162
163   /// Insert - Insert and return the specified instruction.
164   template<typename InstTy>
165   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
166     this->InsertHelper(I, Name, BB, InsertPt);
167     if (CurDbgLocation)
168       Context.getMetadata().addMD(MDKind, CurDbgLocation, I);
169     return I;
170   }
171
172   //===--------------------------------------------------------------------===//
173   // Type creation methods
174   //===--------------------------------------------------------------------===//
175
176   /// getInt1Ty - Fetch the type representing a single bit
177   const Type *getInt1Ty() {
178     return Type::getInt1Ty(Context);
179   }
180   
181   /// getInt8Ty - Fetch the type representing an 8-bit integer.
182   const Type *getInt8Ty() {
183     return Type::getInt8Ty(Context);
184   }
185   
186   /// getInt16Ty - Fetch the type representing a 16-bit integer.
187   const Type *getInt16Ty() {
188     return Type::getInt16Ty(Context);
189   }
190   
191   /// getInt32Ty - Fetch the type resepresenting a 32-bit integer.
192   const Type *getInt32Ty() {
193     return Type::getInt32Ty(Context);
194   }
195   
196   /// getInt64Ty - Fetch the type representing a 64-bit integer.
197   const Type *getInt64Ty() {
198     return Type::getInt64Ty(Context);
199   }
200
201   /// getFloatTy - Fetch the type representing a 32-bit floating point value.
202   const Type *getFloatTy() {
203     return Type::getFloatTy(Context);
204   }
205   
206   /// getDoubleTy - Fetch the type representing a 64-bit floating point value.
207   const Type *getDoubleTy() {
208     return Type::getDoubleTy(Context);
209   }
210   
211   /// getVoidTy - Fetch the type representing void.
212   const Type *getVoidTy() {
213     return Type::getVoidTy(Context);
214   }
215
216   //===--------------------------------------------------------------------===//
217   // Instruction creation methods: Terminators
218   //===--------------------------------------------------------------------===//
219
220   /// CreateRetVoid - Create a 'ret void' instruction.
221   ReturnInst *CreateRetVoid() {
222     return Insert(ReturnInst::Create(Context));
223   }
224
225   /// @verbatim
226   /// CreateRet - Create a 'ret <val>' instruction.
227   /// @endverbatim
228   ReturnInst *CreateRet(Value *V) {
229     return Insert(ReturnInst::Create(Context, V));
230   }
231
232   /// CreateAggregateRet - Create a sequence of N insertvalue instructions,
233   /// with one Value from the retVals array each, that build a aggregate
234   /// return value one value at a time, and a ret instruction to return
235   /// the resulting aggregate value. This is a convenience function for
236   /// code that uses aggregate return values as a vehicle for having
237   /// multiple return values.
238   ///
239   ReturnInst *CreateAggregateRet(Value * const* retVals, unsigned N) {
240     const Type *RetType = BB->getParent()->getReturnType();
241     Value *V = UndefValue::get(RetType);
242     for (unsigned i = 0; i != N; ++i)
243       V = CreateInsertValue(V, retVals[i], i, "mrv");
244     return Insert(ReturnInst::Create(Context, V));
245   }
246
247   /// CreateBr - Create an unconditional 'br label X' instruction.
248   BranchInst *CreateBr(BasicBlock *Dest) {
249     return Insert(BranchInst::Create(Dest));
250   }
251
252   /// CreateCondBr - Create a conditional 'br Cond, TrueDest, FalseDest'
253   /// instruction.
254   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False) {
255     return Insert(BranchInst::Create(True, False, Cond));
256   }
257
258   /// CreateSwitch - Create a switch instruction with the specified value,
259   /// default dest, and with a hint for the number of cases that will be added
260   /// (for efficient allocation).
261   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10) {
262     return Insert(SwitchInst::Create(V, Dest, NumCases));
263   }
264
265   /// CreateIndirectBr - Create an indirect branch instruction with the
266   /// specified address operand, with an optional hint for the number of
267   /// destinations that will be added (for efficient allocation).
268   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
269     return Insert(IndirectBrInst::Create(Addr, NumDests));
270   }
271
272   /// CreateInvoke - Create an invoke instruction.
273   template<typename InputIterator>
274   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
275                            BasicBlock *UnwindDest, InputIterator ArgBegin,
276                            InputIterator ArgEnd, const Twine &Name = "") {
277     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest,
278                                      ArgBegin, ArgEnd), Name);
279   }
280
281   UnwindInst *CreateUnwind() {
282     return Insert(new UnwindInst(Context));
283   }
284
285   UnreachableInst *CreateUnreachable() {
286     return Insert(new UnreachableInst(Context));
287   }
288
289   //===--------------------------------------------------------------------===//
290   // Instruction creation methods: Binary Operators
291   //===--------------------------------------------------------------------===//
292
293   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
294     if (Constant *LC = dyn_cast<Constant>(LHS))
295       if (Constant *RC = dyn_cast<Constant>(RHS))
296         return Folder.CreateAdd(LC, RC);
297     return Insert(BinaryOperator::CreateAdd(LHS, RHS), Name);
298   }
299   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
300     if (Constant *LC = dyn_cast<Constant>(LHS))
301       if (Constant *RC = dyn_cast<Constant>(RHS))
302         return Folder.CreateNSWAdd(LC, RC);
303     return Insert(BinaryOperator::CreateNSWAdd(LHS, RHS), Name);
304   }
305   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
306     if (Constant *LC = dyn_cast<Constant>(LHS))
307       if (Constant *RC = dyn_cast<Constant>(RHS))
308         return Folder.CreateFAdd(LC, RC);
309     return Insert(BinaryOperator::CreateFAdd(LHS, RHS), Name);
310   }
311   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "") {
312     if (Constant *LC = dyn_cast<Constant>(LHS))
313       if (Constant *RC = dyn_cast<Constant>(RHS))
314         return Folder.CreateSub(LC, RC);
315     return Insert(BinaryOperator::CreateSub(LHS, RHS), Name);
316   }
317   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
318     if (Constant *LC = dyn_cast<Constant>(LHS))
319       if (Constant *RC = dyn_cast<Constant>(RHS))
320         return Folder.CreateNSWSub(LC, RC);
321     return Insert(BinaryOperator::CreateNSWSub(LHS, RHS), Name);
322   }
323   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "") {
324     if (Constant *LC = dyn_cast<Constant>(LHS))
325       if (Constant *RC = dyn_cast<Constant>(RHS))
326         return Folder.CreateFSub(LC, RC);
327     return Insert(BinaryOperator::CreateFSub(LHS, RHS), Name);
328   }
329   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "") {
330     if (Constant *LC = dyn_cast<Constant>(LHS))
331       if (Constant *RC = dyn_cast<Constant>(RHS))
332         return Folder.CreateMul(LC, RC);
333     return Insert(BinaryOperator::CreateMul(LHS, RHS), Name);
334   }
335   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "") {
336     if (Constant *LC = dyn_cast<Constant>(LHS))
337       if (Constant *RC = dyn_cast<Constant>(RHS))
338         return Folder.CreateFMul(LC, RC);
339     return Insert(BinaryOperator::CreateFMul(LHS, RHS), Name);
340   }
341   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
342     if (Constant *LC = dyn_cast<Constant>(LHS))
343       if (Constant *RC = dyn_cast<Constant>(RHS))
344         return Folder.CreateUDiv(LC, RC);
345     return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
346   }
347   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
348     if (Constant *LC = dyn_cast<Constant>(LHS))
349       if (Constant *RC = dyn_cast<Constant>(RHS))
350         return Folder.CreateSDiv(LC, RC);
351     return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
352   }
353   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
354     if (Constant *LC = dyn_cast<Constant>(LHS))
355       if (Constant *RC = dyn_cast<Constant>(RHS))
356         return Folder.CreateExactSDiv(LC, RC);
357     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
358   }
359   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
360     if (Constant *LC = dyn_cast<Constant>(LHS))
361       if (Constant *RC = dyn_cast<Constant>(RHS))
362         return Folder.CreateFDiv(LC, RC);
363     return Insert(BinaryOperator::CreateFDiv(LHS, RHS), Name);
364   }
365   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
366     if (Constant *LC = dyn_cast<Constant>(LHS))
367       if (Constant *RC = dyn_cast<Constant>(RHS))
368         return Folder.CreateURem(LC, RC);
369     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
370   }
371   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
372     if (Constant *LC = dyn_cast<Constant>(LHS))
373       if (Constant *RC = dyn_cast<Constant>(RHS))
374         return Folder.CreateSRem(LC, RC);
375     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
376   }
377   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "") {
378     if (Constant *LC = dyn_cast<Constant>(LHS))
379       if (Constant *RC = dyn_cast<Constant>(RHS))
380         return Folder.CreateFRem(LC, RC);
381     return Insert(BinaryOperator::CreateFRem(LHS, RHS), Name);
382   }
383   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "") {
384     if (Constant *LC = dyn_cast<Constant>(LHS))
385       if (Constant *RC = dyn_cast<Constant>(RHS))
386         return Folder.CreateShl(LC, RC);
387     return Insert(BinaryOperator::CreateShl(LHS, RHS), Name);
388   }
389   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "") {
390     if (Constant *LC = dyn_cast<Constant>(LHS))
391       if (Constant *RC = dyn_cast<Constant>(RHS))
392         return Folder.CreateLShr(LC, RC);
393     return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
394   }
395   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "") {
396     if (Constant *LC = dyn_cast<Constant>(LHS))
397       if (Constant *RC = dyn_cast<Constant>(RHS))
398         return Folder.CreateAShr(LC, RC);
399     return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
400   }
401   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
402     if (Constant *RC = dyn_cast<Constant>(RHS)) {
403       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
404         return LHS;  // LHS & -1 -> LHS
405       if (Constant *LC = dyn_cast<Constant>(LHS))
406         return Folder.CreateAnd(LC, RC);
407     }
408     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
409   }
410   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
411     if (Constant *RC = dyn_cast<Constant>(RHS)) {
412       if (RC->isNullValue())
413         return LHS;  // LHS | 0 -> LHS
414       if (Constant *LC = dyn_cast<Constant>(LHS))
415         return Folder.CreateOr(LC, RC);
416     }
417     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
418   }
419   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
420     if (Constant *LC = dyn_cast<Constant>(LHS))
421       if (Constant *RC = dyn_cast<Constant>(RHS))
422         return Folder.CreateXor(LC, RC);
423     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
424   }
425
426   Value *CreateBinOp(Instruction::BinaryOps Opc,
427                      Value *LHS, Value *RHS, const Twine &Name = "") {
428     if (Constant *LC = dyn_cast<Constant>(LHS))
429       if (Constant *RC = dyn_cast<Constant>(RHS))
430         return Folder.CreateBinOp(Opc, LC, RC);
431     return Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
432   }
433
434   Value *CreateNeg(Value *V, const Twine &Name = "") {
435     if (Constant *VC = dyn_cast<Constant>(V))
436       return Folder.CreateNeg(VC);
437     return Insert(BinaryOperator::CreateNeg(V), Name);
438   }
439   Value *CreateFNeg(Value *V, const Twine &Name = "") {
440     if (Constant *VC = dyn_cast<Constant>(V))
441       return Folder.CreateFNeg(VC);
442     return Insert(BinaryOperator::CreateFNeg(V), Name);
443   }
444   Value *CreateNot(Value *V, const Twine &Name = "") {
445     if (Constant *VC = dyn_cast<Constant>(V))
446       return Folder.CreateNot(VC);
447     return Insert(BinaryOperator::CreateNot(V), Name);
448   }
449
450   //===--------------------------------------------------------------------===//
451   // Instruction creation methods: Memory Instructions
452   //===--------------------------------------------------------------------===//
453
454   AllocaInst *CreateAlloca(const Type *Ty, Value *ArraySize = 0,
455                            const Twine &Name = "") {
456     return Insert(new AllocaInst(Ty, ArraySize), Name);
457   }
458   // Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
459   // converting the string to 'bool' for the isVolatile parameter.
460   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
461     return Insert(new LoadInst(Ptr), Name);
462   }
463   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
464     return Insert(new LoadInst(Ptr), Name);
465   }
466   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
467     return Insert(new LoadInst(Ptr, 0, isVolatile), Name);
468   }
469   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
470     return Insert(new StoreInst(Val, Ptr, isVolatile));
471   }
472   template<typename InputIterator>
473   Value *CreateGEP(Value *Ptr, InputIterator IdxBegin, InputIterator IdxEnd,
474                    const Twine &Name = "") {
475     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
476       // Every index must be constant.
477       InputIterator i;
478       for (i = IdxBegin; i < IdxEnd; ++i)
479         if (!isa<Constant>(*i))
480           break;
481       if (i == IdxEnd)
482         return Folder.CreateGetElementPtr(PC, &IdxBegin[0], IdxEnd - IdxBegin);
483     }
484     return Insert(GetElementPtrInst::Create(Ptr, IdxBegin, IdxEnd), Name);
485   }
486   template<typename InputIterator>
487   Value *CreateInBoundsGEP(Value *Ptr, InputIterator IdxBegin, InputIterator IdxEnd,
488                            const Twine &Name = "") {
489     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
490       // Every index must be constant.
491       InputIterator i;
492       for (i = IdxBegin; i < IdxEnd; ++i)
493         if (!isa<Constant>(*i))
494           break;
495       if (i == IdxEnd)
496         return Folder.CreateInBoundsGetElementPtr(PC,
497                                                   &IdxBegin[0],
498                                                   IdxEnd - IdxBegin);
499     }
500     return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxBegin, IdxEnd),
501                   Name);
502   }
503   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
504     if (Constant *PC = dyn_cast<Constant>(Ptr))
505       if (Constant *IC = dyn_cast<Constant>(Idx))
506         return Folder.CreateGetElementPtr(PC, &IC, 1);
507     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
508   }
509   Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
510     if (Constant *PC = dyn_cast<Constant>(Ptr))
511       if (Constant *IC = dyn_cast<Constant>(Idx))
512         return Folder.CreateInBoundsGetElementPtr(PC, &IC, 1);
513     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
514   }
515   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
516     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
517
518     if (Constant *PC = dyn_cast<Constant>(Ptr))
519       return Folder.CreateGetElementPtr(PC, &Idx, 1);
520
521     return Insert(GetElementPtrInst::Create(Ptr, &Idx, &Idx+1), Name);    
522   }
523   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
524                                     const Twine &Name = "") {
525     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
526
527     if (Constant *PC = dyn_cast<Constant>(Ptr))
528       return Folder.CreateInBoundsGetElementPtr(PC, &Idx, 1);
529
530     return Insert(GetElementPtrInst::CreateInBounds(Ptr, &Idx, &Idx+1), Name);
531   }
532   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1, 
533                     const Twine &Name = "") {
534     Value *Idxs[] = {
535       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
536       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
537     };
538
539     if (Constant *PC = dyn_cast<Constant>(Ptr))
540       return Folder.CreateGetElementPtr(PC, Idxs, 2);
541
542     return Insert(GetElementPtrInst::Create(Ptr, Idxs, Idxs+2), Name);    
543   }
544   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
545                                     const Twine &Name = "") {
546     Value *Idxs[] = {
547       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
548       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
549     };
550
551     if (Constant *PC = dyn_cast<Constant>(Ptr))
552       return Folder.CreateInBoundsGetElementPtr(PC, Idxs, 2);
553
554     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs, Idxs+2), Name);
555   }
556   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
557     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
558
559     if (Constant *PC = dyn_cast<Constant>(Ptr))
560       return Folder.CreateGetElementPtr(PC, &Idx, 1);
561
562     return Insert(GetElementPtrInst::Create(Ptr, &Idx, &Idx+1), Name);    
563   }
564   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
565                                     const Twine &Name = "") {
566     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
567
568     if (Constant *PC = dyn_cast<Constant>(Ptr))
569       return Folder.CreateInBoundsGetElementPtr(PC, &Idx, 1);
570
571     return Insert(GetElementPtrInst::CreateInBounds(Ptr, &Idx, &Idx+1), Name);
572   }
573   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
574                     const Twine &Name = "") {
575     Value *Idxs[] = {
576       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
577       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
578     };
579
580     if (Constant *PC = dyn_cast<Constant>(Ptr))
581       return Folder.CreateGetElementPtr(PC, Idxs, 2);
582
583     return Insert(GetElementPtrInst::Create(Ptr, Idxs, Idxs+2), Name);    
584   }
585   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
586                                     const Twine &Name = "") {
587     Value *Idxs[] = {
588       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
589       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
590     };
591
592     if (Constant *PC = dyn_cast<Constant>(Ptr))
593       return Folder.CreateInBoundsGetElementPtr(PC, Idxs, 2);
594
595     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs, Idxs+2), Name);
596   }
597   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
598     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
599   }
600   Value *CreateGlobalString(const char *Str = "", const Twine &Name = "") {
601     Constant *StrConstant = ConstantArray::get(Context, Str, true);
602     Module &M = *BB->getParent()->getParent();
603     GlobalVariable *gv = new GlobalVariable(M,
604                                             StrConstant->getType(),
605                                             true,
606                                             GlobalValue::InternalLinkage,
607                                             StrConstant,
608                                             "",
609                                             0,
610                                             false);
611     gv->setName(Name);
612     return gv;
613   }
614   Value *CreateGlobalStringPtr(const char *Str = "", const Twine &Name = "") {
615     Value *gv = CreateGlobalString(Str, Name);
616     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
617     Value *Args[] = { zero, zero };
618     return CreateInBoundsGEP(gv, Args, Args+2, Name);
619   }
620   //===--------------------------------------------------------------------===//
621   // Instruction creation methods: Cast/Conversion Operators
622   //===--------------------------------------------------------------------===//
623
624   Value *CreateTrunc(Value *V, const Type *DestTy, const Twine &Name = "") {
625     return CreateCast(Instruction::Trunc, V, DestTy, Name);
626   }
627   Value *CreateZExt(Value *V, const Type *DestTy, const Twine &Name = "") {
628     return CreateCast(Instruction::ZExt, V, DestTy, Name);
629   }
630   Value *CreateSExt(Value *V, const Type *DestTy, const Twine &Name = "") {
631     return CreateCast(Instruction::SExt, V, DestTy, Name);
632   }
633   Value *CreateFPToUI(Value *V, const Type *DestTy, const Twine &Name = ""){
634     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
635   }
636   Value *CreateFPToSI(Value *V, const Type *DestTy, const Twine &Name = ""){
637     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
638   }
639   Value *CreateUIToFP(Value *V, const Type *DestTy, const Twine &Name = ""){
640     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
641   }
642   Value *CreateSIToFP(Value *V, const Type *DestTy, const Twine &Name = ""){
643     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
644   }
645   Value *CreateFPTrunc(Value *V, const Type *DestTy,
646                        const Twine &Name = "") {
647     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
648   }
649   Value *CreateFPExt(Value *V, const Type *DestTy, const Twine &Name = "") {
650     return CreateCast(Instruction::FPExt, V, DestTy, Name);
651   }
652   Value *CreatePtrToInt(Value *V, const Type *DestTy,
653                         const Twine &Name = "") {
654     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
655   }
656   Value *CreateIntToPtr(Value *V, const Type *DestTy,
657                         const Twine &Name = "") {
658     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
659   }
660   Value *CreateBitCast(Value *V, const Type *DestTy,
661                        const Twine &Name = "") {
662     return CreateCast(Instruction::BitCast, V, DestTy, Name);
663   }
664   Value *CreateZExtOrBitCast(Value *V, const Type *DestTy,
665                              const Twine &Name = "") {
666     if (V->getType() == DestTy)
667       return V;
668     if (Constant *VC = dyn_cast<Constant>(V))
669       return Folder.CreateZExtOrBitCast(VC, DestTy);
670     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
671   }
672   Value *CreateSExtOrBitCast(Value *V, const Type *DestTy,
673                              const Twine &Name = "") {
674     if (V->getType() == DestTy)
675       return V;
676     if (Constant *VC = dyn_cast<Constant>(V))
677       return Folder.CreateSExtOrBitCast(VC, DestTy);
678     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
679   }
680   Value *CreateTruncOrBitCast(Value *V, const Type *DestTy,
681                               const Twine &Name = "") {
682     if (V->getType() == DestTy)
683       return V;
684     if (Constant *VC = dyn_cast<Constant>(V))
685       return Folder.CreateTruncOrBitCast(VC, DestTy);
686     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
687   }
688   Value *CreateCast(Instruction::CastOps Op, Value *V, const Type *DestTy,
689                     const Twine &Name = "") {
690     if (V->getType() == DestTy)
691       return V;
692     if (Constant *VC = dyn_cast<Constant>(V))
693       return Folder.CreateCast(Op, VC, DestTy);
694     return Insert(CastInst::Create(Op, V, DestTy), Name);
695   }
696   Value *CreatePointerCast(Value *V, const Type *DestTy,
697                            const Twine &Name = "") {
698     if (V->getType() == DestTy)
699       return V;
700     if (Constant *VC = dyn_cast<Constant>(V))
701       return Folder.CreatePointerCast(VC, DestTy);
702     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
703   }
704   Value *CreateIntCast(Value *V, const Type *DestTy, bool isSigned,
705                        const Twine &Name = "") {
706     if (V->getType() == DestTy)
707       return V;
708     if (Constant *VC = dyn_cast<Constant>(V))
709       return Folder.CreateIntCast(VC, DestTy, isSigned);
710     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
711   }
712   Value *CreateFPCast(Value *V, const Type *DestTy, const Twine &Name = "") {
713     if (V->getType() == DestTy)
714       return V;
715     if (Constant *VC = dyn_cast<Constant>(V))
716       return Folder.CreateFPCast(VC, DestTy);
717     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
718   }
719
720   //===--------------------------------------------------------------------===//
721   // Instruction creation methods: Compare Instructions
722   //===--------------------------------------------------------------------===//
723
724   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
725     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
726   }
727   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
728     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
729   }
730   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
731     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
732   }
733   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
734     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
735   }
736   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
737     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
738   }
739   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
740     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
741   }
742   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
743     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
744   }
745   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
746     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
747   }
748   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
749     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
750   }
751   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
752     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
753   }
754
755   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
756     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
757   }
758   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
759     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
760   }
761   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
762     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
763   }
764   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
765     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
766   }
767   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
768     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
769   }
770   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
771     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
772   }
773   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
774     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
775   }
776   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
777     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
778   }
779   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
780     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
781   }
782   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
783     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
784   }
785   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
786     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
787   }
788   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
789     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
790   }
791   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
792     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
793   }
794   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
795     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
796   }
797
798   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
799                     const Twine &Name = "") {
800     if (Constant *LC = dyn_cast<Constant>(LHS))
801       if (Constant *RC = dyn_cast<Constant>(RHS))
802         return Folder.CreateICmp(P, LC, RC);
803     return Insert(new ICmpInst(P, LHS, RHS), Name);
804   }
805   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
806                     const Twine &Name = "") {
807     if (Constant *LC = dyn_cast<Constant>(LHS))
808       if (Constant *RC = dyn_cast<Constant>(RHS))
809         return Folder.CreateFCmp(P, LC, RC);
810     return Insert(new FCmpInst(P, LHS, RHS), Name);
811   }
812
813   //===--------------------------------------------------------------------===//
814   // Instruction creation methods: Other Instructions
815   //===--------------------------------------------------------------------===//
816
817   PHINode *CreatePHI(const Type *Ty, const Twine &Name = "") {
818     return Insert(PHINode::Create(Ty), Name);
819   }
820
821   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
822     return Insert(CallInst::Create(Callee), Name);
823   }
824   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
825     return Insert(CallInst::Create(Callee, Arg), Name);
826   }
827   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
828                         const Twine &Name = "") {
829     Value *Args[] = { Arg1, Arg2 };
830     return Insert(CallInst::Create(Callee, Args, Args+2), Name);
831   }
832   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
833                         const Twine &Name = "") {
834     Value *Args[] = { Arg1, Arg2, Arg3 };
835     return Insert(CallInst::Create(Callee, Args, Args+3), Name);
836   }
837   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
838                         Value *Arg4, const Twine &Name = "") {
839     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
840     return Insert(CallInst::Create(Callee, Args, Args+4), Name);
841   }
842
843   template<typename InputIterator>
844   CallInst *CreateCall(Value *Callee, InputIterator ArgBegin,
845                        InputIterator ArgEnd, const Twine &Name = "") {
846     return Insert(CallInst::Create(Callee, ArgBegin, ArgEnd), Name);
847   }
848
849   Value *CreateSelect(Value *C, Value *True, Value *False,
850                       const Twine &Name = "") {
851     if (Constant *CC = dyn_cast<Constant>(C))
852       if (Constant *TC = dyn_cast<Constant>(True))
853         if (Constant *FC = dyn_cast<Constant>(False))
854           return Folder.CreateSelect(CC, TC, FC);
855     return Insert(SelectInst::Create(C, True, False), Name);
856   }
857
858   VAArgInst *CreateVAArg(Value *List, const Type *Ty, const Twine &Name = "") {
859     return Insert(new VAArgInst(List, Ty), Name);
860   }
861
862   Value *CreateExtractElement(Value *Vec, Value *Idx,
863                               const Twine &Name = "") {
864     if (Constant *VC = dyn_cast<Constant>(Vec))
865       if (Constant *IC = dyn_cast<Constant>(Idx))
866         return Folder.CreateExtractElement(VC, IC);
867     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
868   }
869
870   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
871                              const Twine &Name = "") {
872     if (Constant *VC = dyn_cast<Constant>(Vec))
873       if (Constant *NC = dyn_cast<Constant>(NewElt))
874         if (Constant *IC = dyn_cast<Constant>(Idx))
875           return Folder.CreateInsertElement(VC, NC, IC);
876     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
877   }
878
879   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
880                              const Twine &Name = "") {
881     if (Constant *V1C = dyn_cast<Constant>(V1))
882       if (Constant *V2C = dyn_cast<Constant>(V2))
883         if (Constant *MC = dyn_cast<Constant>(Mask))
884           return Folder.CreateShuffleVector(V1C, V2C, MC);
885     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
886   }
887
888   Value *CreateExtractValue(Value *Agg, unsigned Idx,
889                             const Twine &Name = "") {
890     if (Constant *AggC = dyn_cast<Constant>(Agg))
891       return Folder.CreateExtractValue(AggC, &Idx, 1);
892     return Insert(ExtractValueInst::Create(Agg, Idx), Name);
893   }
894
895   template<typename InputIterator>
896   Value *CreateExtractValue(Value *Agg,
897                             InputIterator IdxBegin,
898                             InputIterator IdxEnd,
899                             const Twine &Name = "") {
900     if (Constant *AggC = dyn_cast<Constant>(Agg))
901       return Folder.CreateExtractValue(AggC, IdxBegin, IdxEnd - IdxBegin);
902     return Insert(ExtractValueInst::Create(Agg, IdxBegin, IdxEnd), Name);
903   }
904
905   Value *CreateInsertValue(Value *Agg, Value *Val, unsigned Idx,
906                            const Twine &Name = "") {
907     if (Constant *AggC = dyn_cast<Constant>(Agg))
908       if (Constant *ValC = dyn_cast<Constant>(Val))
909         return Folder.CreateInsertValue(AggC, ValC, &Idx, 1);
910     return Insert(InsertValueInst::Create(Agg, Val, Idx), Name);
911   }
912
913   template<typename InputIterator>
914   Value *CreateInsertValue(Value *Agg, Value *Val,
915                            InputIterator IdxBegin,
916                            InputIterator IdxEnd,
917                            const Twine &Name = "") {
918     if (Constant *AggC = dyn_cast<Constant>(Agg))
919       if (Constant *ValC = dyn_cast<Constant>(Val))
920         return Folder.CreateInsertValue(AggC, ValC, IdxBegin, IdxEnd-IdxBegin);
921     return Insert(InsertValueInst::Create(Agg, Val, IdxBegin, IdxEnd), Name);
922   }
923
924   //===--------------------------------------------------------------------===//
925   // Utility creation methods
926   //===--------------------------------------------------------------------===//
927
928   /// CreateIsNull - Return an i1 value testing if \arg Arg is null.
929   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
930     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
931                         Name);
932   }
933
934   /// CreateIsNotNull - Return an i1 value testing if \arg Arg is not null.
935   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
936     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
937                         Name);
938   }
939
940   /// CreatePtrDiff - Return the i64 difference between two pointer values,
941   /// dividing out the size of the pointed-to objects.  This is intended to
942   /// implement C-style pointer subtraction. As such, the pointers must be
943   /// appropriately aligned for their element types and pointing into the
944   /// same object.
945   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
946     assert(LHS->getType() == RHS->getType() &&
947            "Pointer subtraction operand types must match!");
948     const PointerType *ArgType = cast<PointerType>(LHS->getType());
949     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
950     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
951     Value *Difference = CreateSub(LHS_int, RHS_int);
952     return CreateExactSDiv(Difference,
953                            ConstantExpr::getSizeOf(ArgType->getElementType()),
954                            Name);
955   }
956 };
957
958 }
959
960 #endif