Move llvm/Support/IRBuilder.h -> llvm/IRBuilder.h
[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     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag);
290   }
291
292   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
293                          bool isVolatile = false, MDNode *TBAATag = 0);
294
295   /// CreateMemMove - Create and insert a memmove between the specified
296   /// pointers.  If the pointers aren't i8*, they will be converted.  If a TBAA
297   /// tag is specified, it will be added to the instruction.
298   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
299                           bool isVolatile = false, MDNode *TBAATag = 0) {
300     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag);
301   }
302
303   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
304                           bool isVolatile = false, MDNode *TBAATag = 0);
305
306   /// CreateLifetimeStart - Create a lifetime.start intrinsic.  If the pointer
307   /// isn't i8* it will be converted.
308   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = 0);
309
310   /// CreateLifetimeEnd - Create a lifetime.end intrinsic.  If the pointer isn't
311   /// i8* it will be converted.
312   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = 0);
313
314 private:
315   Value *getCastedInt8PtrValue(Value *Ptr);
316 };
317
318 /// IRBuilder - This provides a uniform API for creating instructions and
319 /// inserting them into a basic block: either at the end of a BasicBlock, or
320 /// at a specific iterator location in a block.
321 ///
322 /// Note that the builder does not expose the full generality of LLVM
323 /// instructions.  For access to extra instruction properties, use the mutators
324 /// (e.g. setVolatile) on the instructions after they have been created.
325 /// The first template argument handles whether or not to preserve names in the
326 /// final instruction output. This defaults to on.  The second template argument
327 /// specifies a class to use for creating constants.  This defaults to creating
328 /// minimally folded constants.  The fourth template argument allows clients to
329 /// specify custom insertion hooks that are called on every newly created
330 /// insertion.
331 template<bool preserveNames = true, typename T = ConstantFolder,
332          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
333 class IRBuilder : public IRBuilderBase, public Inserter {
334   T Folder;
335   MDNode *DefaultFPMathTag;
336 public:
337   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
338             MDNode *FPMathTag = 0)
339     : IRBuilderBase(C), Inserter(I), Folder(F), DefaultFPMathTag(FPMathTag) {
340   }
341
342   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = 0) : IRBuilderBase(C),
343     Folder(), DefaultFPMathTag(FPMathTag) {
344   }
345
346   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = 0)
347     : IRBuilderBase(TheBB->getContext()), Folder(F),
348       DefaultFPMathTag(FPMathTag) {
349     SetInsertPoint(TheBB);
350   }
351
352   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = 0)
353     : IRBuilderBase(TheBB->getContext()), Folder(),
354       DefaultFPMathTag(FPMathTag) {
355     SetInsertPoint(TheBB);
356   }
357
358   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = 0)
359     : IRBuilderBase(IP->getContext()), Folder(), DefaultFPMathTag(FPMathTag) {
360     SetInsertPoint(IP);
361     SetCurrentDebugLocation(IP->getDebugLoc());
362   }
363
364   explicit IRBuilder(Use &U, MDNode *FPMathTag = 0)
365     : IRBuilderBase(U->getContext()), Folder(), DefaultFPMathTag(FPMathTag) {
366     SetInsertPoint(U);
367     SetCurrentDebugLocation(cast<Instruction>(U.getUser())->getDebugLoc());
368   }
369
370   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
371             MDNode *FPMathTag = 0)
372     : IRBuilderBase(TheBB->getContext()), Folder(F),
373       DefaultFPMathTag(FPMathTag) {
374     SetInsertPoint(TheBB, IP);
375   }
376
377   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, MDNode *FPMathTag = 0)
378     : IRBuilderBase(TheBB->getContext()), Folder(),
379       DefaultFPMathTag(FPMathTag) {
380     SetInsertPoint(TheBB, IP);
381   }
382
383   /// getFolder - Get the constant folder being used.
384   const T &getFolder() { return Folder; }
385
386   /// getDefaultFPMathTag - Get the floating point math metadata being used.
387   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
388
389   /// SetDefaultFPMathTag - Set the floating point math metadata to be used.
390   void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
391
392   /// isNamePreserving - Return true if this builder is configured to actually
393   /// add the requested names to IR created through it.
394   bool isNamePreserving() const { return preserveNames; }
395
396   /// Insert - Insert and return the specified instruction.
397   template<typename InstTy>
398   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
399     this->InsertHelper(I, Name, BB, InsertPt);
400     if (!getCurrentDebugLocation().isUnknown())
401       this->SetInstDebugLocation(I);
402     return I;
403   }
404
405   /// Insert - No-op overload to handle constants.
406   Constant *Insert(Constant *C, const Twine& = "") const {
407     return C;
408   }
409
410   //===--------------------------------------------------------------------===//
411   // Instruction creation methods: Terminators
412   //===--------------------------------------------------------------------===//
413
414   /// CreateRetVoid - Create a 'ret void' instruction.
415   ReturnInst *CreateRetVoid() {
416     return Insert(ReturnInst::Create(Context));
417   }
418
419   /// @verbatim
420   /// CreateRet - Create a 'ret <val>' instruction.
421   /// @endverbatim
422   ReturnInst *CreateRet(Value *V) {
423     return Insert(ReturnInst::Create(Context, V));
424   }
425
426   /// CreateAggregateRet - Create a sequence of N insertvalue instructions,
427   /// with one Value from the retVals array each, that build a aggregate
428   /// return value one value at a time, and a ret instruction to return
429   /// the resulting aggregate value. This is a convenience function for
430   /// code that uses aggregate return values as a vehicle for having
431   /// multiple return values.
432   ///
433   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
434     Value *V = UndefValue::get(getCurrentFunctionReturnType());
435     for (unsigned i = 0; i != N; ++i)
436       V = CreateInsertValue(V, retVals[i], i, "mrv");
437     return Insert(ReturnInst::Create(Context, V));
438   }
439
440   /// CreateBr - Create an unconditional 'br label X' instruction.
441   BranchInst *CreateBr(BasicBlock *Dest) {
442     return Insert(BranchInst::Create(Dest));
443   }
444
445   /// CreateCondBr - Create a conditional 'br Cond, TrueDest, FalseDest'
446   /// instruction.
447   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False) {
448     return Insert(BranchInst::Create(True, False, Cond));
449   }
450
451   /// CreateSwitch - Create a switch instruction with the specified value,
452   /// default dest, and with a hint for the number of cases that will be added
453   /// (for efficient allocation).
454   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10) {
455     return Insert(SwitchInst::Create(V, Dest, NumCases));
456   }
457
458   /// CreateIndirectBr - Create an indirect branch instruction with the
459   /// specified address operand, with an optional hint for the number of
460   /// destinations that will be added (for efficient allocation).
461   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
462     return Insert(IndirectBrInst::Create(Addr, NumDests));
463   }
464
465   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
466                            BasicBlock *UnwindDest, const Twine &Name = "") {
467     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest,
468                                      ArrayRef<Value *>()),
469                   Name);
470   }
471   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
472                            BasicBlock *UnwindDest, Value *Arg1,
473                            const Twine &Name = "") {
474     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
475                   Name);
476   }
477   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
478                             BasicBlock *UnwindDest, Value *Arg1,
479                             Value *Arg2, Value *Arg3,
480                             const Twine &Name = "") {
481     Value *Args[] = { Arg1, Arg2, Arg3 };
482     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
483                   Name);
484   }
485   /// CreateInvoke - Create an invoke instruction.
486   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
487                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
488                            const Twine &Name = "") {
489     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
490                   Name);
491   }
492
493   ResumeInst *CreateResume(Value *Exn) {
494     return Insert(ResumeInst::Create(Exn));
495   }
496
497   UnreachableInst *CreateUnreachable() {
498     return Insert(new UnreachableInst(Context));
499   }
500
501   //===--------------------------------------------------------------------===//
502   // Instruction creation methods: Binary Operators
503   //===--------------------------------------------------------------------===//
504 private:
505   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
506                                           Value *LHS, Value *RHS,
507                                           const Twine &Name,
508                                           bool HasNUW, bool HasNSW) {
509     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
510     if (HasNUW) BO->setHasNoUnsignedWrap();
511     if (HasNSW) BO->setHasNoSignedWrap();
512     return BO;
513   }
514
515   Instruction *AddFPMathTag(Instruction *I, MDNode *FPMathTag) const {
516     if (!FPMathTag)
517       FPMathTag = DefaultFPMathTag;
518     if (FPMathTag)
519       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
520     return I;
521   }
522 public:
523   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
524                    bool HasNUW = false, bool HasNSW = false) {
525     if (Constant *LC = dyn_cast<Constant>(LHS))
526       if (Constant *RC = dyn_cast<Constant>(RHS))
527         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
528     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
529                                    HasNUW, HasNSW);
530   }
531   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
532     return CreateAdd(LHS, RHS, Name, false, true);
533   }
534   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
535     return CreateAdd(LHS, RHS, Name, true, false);
536   }
537   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
538                     MDNode *FPMathTag = 0) {
539     if (Constant *LC = dyn_cast<Constant>(LHS))
540       if (Constant *RC = dyn_cast<Constant>(RHS))
541         return Insert(Folder.CreateFAdd(LC, RC), Name);
542     return Insert(AddFPMathTag(BinaryOperator::CreateFAdd(LHS, RHS),
543                                FPMathTag), Name);
544   }
545   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
546                    bool HasNUW = false, bool HasNSW = false) {
547     if (Constant *LC = dyn_cast<Constant>(LHS))
548       if (Constant *RC = dyn_cast<Constant>(RHS))
549         return Insert(Folder.CreateSub(LC, RC), Name);
550     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
551                                    HasNUW, HasNSW);
552   }
553   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
554     return CreateSub(LHS, RHS, Name, false, true);
555   }
556   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
557     return CreateSub(LHS, RHS, Name, true, false);
558   }
559   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
560                     MDNode *FPMathTag = 0) {
561     if (Constant *LC = dyn_cast<Constant>(LHS))
562       if (Constant *RC = dyn_cast<Constant>(RHS))
563         return Insert(Folder.CreateFSub(LC, RC), Name);
564     return Insert(AddFPMathTag(BinaryOperator::CreateFSub(LHS, RHS),
565                                FPMathTag), Name);
566   }
567   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
568                    bool HasNUW = false, bool HasNSW = false) {
569     if (Constant *LC = dyn_cast<Constant>(LHS))
570       if (Constant *RC = dyn_cast<Constant>(RHS))
571         return Insert(Folder.CreateMul(LC, RC), Name);
572     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
573                                    HasNUW, HasNSW);
574   }
575   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
576     return CreateMul(LHS, RHS, Name, false, true);
577   }
578   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
579     return CreateMul(LHS, RHS, Name, true, false);
580   }
581   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
582                     MDNode *FPMathTag = 0) {
583     if (Constant *LC = dyn_cast<Constant>(LHS))
584       if (Constant *RC = dyn_cast<Constant>(RHS))
585         return Insert(Folder.CreateFMul(LC, RC), Name);
586     return Insert(AddFPMathTag(BinaryOperator::CreateFMul(LHS, RHS),
587                                FPMathTag), Name);
588   }
589   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
590                     bool isExact = false) {
591     if (Constant *LC = dyn_cast<Constant>(LHS))
592       if (Constant *RC = dyn_cast<Constant>(RHS))
593         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
594     if (!isExact)
595       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
596     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
597   }
598   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
599     return CreateUDiv(LHS, RHS, Name, true);
600   }
601   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
602                     bool isExact = false) {
603     if (Constant *LC = dyn_cast<Constant>(LHS))
604       if (Constant *RC = dyn_cast<Constant>(RHS))
605         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
606     if (!isExact)
607       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
608     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
609   }
610   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
611     return CreateSDiv(LHS, RHS, Name, true);
612   }
613   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
614                     MDNode *FPMathTag = 0) {
615     if (Constant *LC = dyn_cast<Constant>(LHS))
616       if (Constant *RC = dyn_cast<Constant>(RHS))
617         return Insert(Folder.CreateFDiv(LC, RC), Name);
618     return Insert(AddFPMathTag(BinaryOperator::CreateFDiv(LHS, RHS),
619                                FPMathTag), Name);
620   }
621   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
622     if (Constant *LC = dyn_cast<Constant>(LHS))
623       if (Constant *RC = dyn_cast<Constant>(RHS))
624         return Insert(Folder.CreateURem(LC, RC), Name);
625     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
626   }
627   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
628     if (Constant *LC = dyn_cast<Constant>(LHS))
629       if (Constant *RC = dyn_cast<Constant>(RHS))
630         return Insert(Folder.CreateSRem(LC, RC), Name);
631     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
632   }
633   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
634                     MDNode *FPMathTag = 0) {
635     if (Constant *LC = dyn_cast<Constant>(LHS))
636       if (Constant *RC = dyn_cast<Constant>(RHS))
637         return Insert(Folder.CreateFRem(LC, RC), Name);
638     return Insert(AddFPMathTag(BinaryOperator::CreateFRem(LHS, RHS),
639                                FPMathTag), Name);
640   }
641
642   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
643                    bool HasNUW = false, bool HasNSW = false) {
644     if (Constant *LC = dyn_cast<Constant>(LHS))
645       if (Constant *RC = dyn_cast<Constant>(RHS))
646         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
647     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
648                                    HasNUW, HasNSW);
649   }
650   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
651                    bool HasNUW = false, bool HasNSW = false) {
652     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
653                      HasNUW, HasNSW);
654   }
655   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
656                    bool HasNUW = false, bool HasNSW = false) {
657     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
658                      HasNUW, HasNSW);
659   }
660
661   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
662                     bool isExact = false) {
663     if (Constant *LC = dyn_cast<Constant>(LHS))
664       if (Constant *RC = dyn_cast<Constant>(RHS))
665         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
666     if (!isExact)
667       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
668     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
669   }
670   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
671                     bool isExact = false) {
672     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
673   }
674   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
675                     bool isExact = false) {
676     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
677   }
678
679   Value *CreateAShr(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.CreateAShr(LC, RC, isExact), Name);
684     if (!isExact)
685       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
686     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
687   }
688   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
689                     bool isExact = false) {
690     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
691   }
692   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
693                     bool isExact = false) {
694     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
695   }
696
697   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
698     if (Constant *RC = dyn_cast<Constant>(RHS)) {
699       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
700         return LHS;  // LHS & -1 -> LHS
701       if (Constant *LC = dyn_cast<Constant>(LHS))
702         return Insert(Folder.CreateAnd(LC, RC), Name);
703     }
704     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
705   }
706   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
707     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
708   }
709   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
710     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
711   }
712
713   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
714     if (Constant *RC = dyn_cast<Constant>(RHS)) {
715       if (RC->isNullValue())
716         return LHS;  // LHS | 0 -> LHS
717       if (Constant *LC = dyn_cast<Constant>(LHS))
718         return Insert(Folder.CreateOr(LC, RC), Name);
719     }
720     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
721   }
722   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
723     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
724   }
725   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
726     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
727   }
728
729   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
730     if (Constant *LC = dyn_cast<Constant>(LHS))
731       if (Constant *RC = dyn_cast<Constant>(RHS))
732         return Insert(Folder.CreateXor(LC, RC), Name);
733     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
734   }
735   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
736     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
737   }
738   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
739     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
740   }
741
742   Value *CreateBinOp(Instruction::BinaryOps Opc,
743                      Value *LHS, Value *RHS, const Twine &Name = "") {
744     if (Constant *LC = dyn_cast<Constant>(LHS))
745       if (Constant *RC = dyn_cast<Constant>(RHS))
746         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
747     return Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
748   }
749
750   Value *CreateNeg(Value *V, const Twine &Name = "",
751                    bool HasNUW = false, bool HasNSW = false) {
752     if (Constant *VC = dyn_cast<Constant>(V))
753       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
754     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
755     if (HasNUW) BO->setHasNoUnsignedWrap();
756     if (HasNSW) BO->setHasNoSignedWrap();
757     return BO;
758   }
759   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
760     return CreateNeg(V, Name, false, true);
761   }
762   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
763     return CreateNeg(V, Name, true, false);
764   }
765   Value *CreateFNeg(Value *V, const Twine &Name = "", MDNode *FPMathTag = 0) {
766     if (Constant *VC = dyn_cast<Constant>(V))
767       return Insert(Folder.CreateFNeg(VC), Name);
768     return Insert(AddFPMathTag(BinaryOperator::CreateFNeg(V), FPMathTag), Name);
769   }
770   Value *CreateNot(Value *V, const Twine &Name = "") {
771     if (Constant *VC = dyn_cast<Constant>(V))
772       return Insert(Folder.CreateNot(VC), Name);
773     return Insert(BinaryOperator::CreateNot(V), Name);
774   }
775
776   //===--------------------------------------------------------------------===//
777   // Instruction creation methods: Memory Instructions
778   //===--------------------------------------------------------------------===//
779
780   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = 0,
781                            const Twine &Name = "") {
782     return Insert(new AllocaInst(Ty, ArraySize), Name);
783   }
784   // Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
785   // converting the string to 'bool' for the isVolatile parameter.
786   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
787     return Insert(new LoadInst(Ptr), Name);
788   }
789   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
790     return Insert(new LoadInst(Ptr), Name);
791   }
792   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
793     return Insert(new LoadInst(Ptr, 0, isVolatile), Name);
794   }
795   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
796     return Insert(new StoreInst(Val, Ptr, isVolatile));
797   }
798   FenceInst *CreateFence(AtomicOrdering Ordering,
799                          SynchronizationScope SynchScope = CrossThread) {
800     return Insert(new FenceInst(Context, Ordering, SynchScope));
801   }
802   AtomicCmpXchgInst *CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
803                                          AtomicOrdering Ordering,
804                                SynchronizationScope SynchScope = CrossThread) {
805     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope));
806   }
807   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
808                                  AtomicOrdering Ordering,
809                                SynchronizationScope SynchScope = CrossThread) {
810     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
811   }
812   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
813                    const Twine &Name = "") {
814     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
815       // Every index must be constant.
816       size_t i, e;
817       for (i = 0, e = IdxList.size(); i != e; ++i)
818         if (!isa<Constant>(IdxList[i]))
819           break;
820       if (i == e)
821         return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
822     }
823     return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
824   }
825   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
826                            const Twine &Name = "") {
827     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
828       // Every index must be constant.
829       size_t i, e;
830       for (i = 0, e = IdxList.size(); i != e; ++i)
831         if (!isa<Constant>(IdxList[i]))
832           break;
833       if (i == e)
834         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
835     }
836     return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
837   }
838   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
839     if (Constant *PC = dyn_cast<Constant>(Ptr))
840       if (Constant *IC = dyn_cast<Constant>(Idx))
841         return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
842     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
843   }
844   Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
845     if (Constant *PC = dyn_cast<Constant>(Ptr))
846       if (Constant *IC = dyn_cast<Constant>(Idx))
847         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
848     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
849   }
850   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
851     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
852
853     if (Constant *PC = dyn_cast<Constant>(Ptr))
854       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
855
856     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
857   }
858   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
859                                     const Twine &Name = "") {
860     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
861
862     if (Constant *PC = dyn_cast<Constant>(Ptr))
863       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
864
865     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
866   }
867   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
868                     const Twine &Name = "") {
869     Value *Idxs[] = {
870       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
871       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
872     };
873
874     if (Constant *PC = dyn_cast<Constant>(Ptr))
875       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
876
877     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
878   }
879   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
880                                     const Twine &Name = "") {
881     Value *Idxs[] = {
882       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
883       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
884     };
885
886     if (Constant *PC = dyn_cast<Constant>(Ptr))
887       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
888
889     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
890   }
891   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
892     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
893
894     if (Constant *PC = dyn_cast<Constant>(Ptr))
895       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
896
897     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
898   }
899   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
900                                     const Twine &Name = "") {
901     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
902
903     if (Constant *PC = dyn_cast<Constant>(Ptr))
904       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
905
906     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
907   }
908   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
909                     const Twine &Name = "") {
910     Value *Idxs[] = {
911       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
912       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
913     };
914
915     if (Constant *PC = dyn_cast<Constant>(Ptr))
916       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
917
918     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
919   }
920   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
921                                     const Twine &Name = "") {
922     Value *Idxs[] = {
923       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
924       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
925     };
926
927     if (Constant *PC = dyn_cast<Constant>(Ptr))
928       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
929
930     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
931   }
932   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
933     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
934   }
935
936   /// CreateGlobalStringPtr - Same as CreateGlobalString, but return a pointer
937   /// with "i8*" type instead of a pointer to array of i8.
938   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
939     Value *gv = CreateGlobalString(Str, Name);
940     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
941     Value *Args[] = { zero, zero };
942     return CreateInBoundsGEP(gv, Args, Name);
943   }
944
945   //===--------------------------------------------------------------------===//
946   // Instruction creation methods: Cast/Conversion Operators
947   //===--------------------------------------------------------------------===//
948
949   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
950     return CreateCast(Instruction::Trunc, V, DestTy, Name);
951   }
952   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
953     return CreateCast(Instruction::ZExt, V, DestTy, Name);
954   }
955   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
956     return CreateCast(Instruction::SExt, V, DestTy, Name);
957   }
958   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
959     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
960   }
961   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
962     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
963   }
964   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
965     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
966   }
967   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
968     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
969   }
970   Value *CreateFPTrunc(Value *V, Type *DestTy,
971                        const Twine &Name = "") {
972     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
973   }
974   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
975     return CreateCast(Instruction::FPExt, V, DestTy, Name);
976   }
977   Value *CreatePtrToInt(Value *V, Type *DestTy,
978                         const Twine &Name = "") {
979     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
980   }
981   Value *CreateIntToPtr(Value *V, Type *DestTy,
982                         const Twine &Name = "") {
983     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
984   }
985   Value *CreateBitCast(Value *V, Type *DestTy,
986                        const Twine &Name = "") {
987     return CreateCast(Instruction::BitCast, V, DestTy, Name);
988   }
989   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
990                              const Twine &Name = "") {
991     if (V->getType() == DestTy)
992       return V;
993     if (Constant *VC = dyn_cast<Constant>(V))
994       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
995     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
996   }
997   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
998                              const Twine &Name = "") {
999     if (V->getType() == DestTy)
1000       return V;
1001     if (Constant *VC = dyn_cast<Constant>(V))
1002       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1003     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1004   }
1005   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1006                               const Twine &Name = "") {
1007     if (V->getType() == DestTy)
1008       return V;
1009     if (Constant *VC = dyn_cast<Constant>(V))
1010       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1011     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1012   }
1013   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1014                     const Twine &Name = "") {
1015     if (V->getType() == DestTy)
1016       return V;
1017     if (Constant *VC = dyn_cast<Constant>(V))
1018       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1019     return Insert(CastInst::Create(Op, V, DestTy), Name);
1020   }
1021   Value *CreatePointerCast(Value *V, Type *DestTy,
1022                            const Twine &Name = "") {
1023     if (V->getType() == DestTy)
1024       return V;
1025     if (Constant *VC = dyn_cast<Constant>(V))
1026       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1027     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1028   }
1029   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1030                        const Twine &Name = "") {
1031     if (V->getType() == DestTy)
1032       return V;
1033     if (Constant *VC = dyn_cast<Constant>(V))
1034       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1035     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1036   }
1037 private:
1038   // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a compile time
1039   // error, instead of converting the string to bool for the isSigned parameter.
1040   Value *CreateIntCast(Value *, Type *, const char *); // DO NOT IMPLEMENT
1041 public:
1042   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1043     if (V->getType() == DestTy)
1044       return V;
1045     if (Constant *VC = dyn_cast<Constant>(V))
1046       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1047     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1048   }
1049
1050   //===--------------------------------------------------------------------===//
1051   // Instruction creation methods: Compare Instructions
1052   //===--------------------------------------------------------------------===//
1053
1054   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1055     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1056   }
1057   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1058     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1059   }
1060   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1061     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1062   }
1063   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1064     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1065   }
1066   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1067     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1068   }
1069   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1070     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1071   }
1072   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1073     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1074   }
1075   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1076     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1077   }
1078   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1079     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1080   }
1081   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1082     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1083   }
1084
1085   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1086     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1087   }
1088   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1089     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1090   }
1091   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1092     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1093   }
1094   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1095     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1096   }
1097   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1098     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1099   }
1100   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1101     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1102   }
1103   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1104     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1105   }
1106   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1107     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1108   }
1109   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1110     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1111   }
1112   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1113     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1114   }
1115   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1116     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1117   }
1118   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1119     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1120   }
1121   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1122     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1123   }
1124   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1125     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1126   }
1127
1128   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1129                     const Twine &Name = "") {
1130     if (Constant *LC = dyn_cast<Constant>(LHS))
1131       if (Constant *RC = dyn_cast<Constant>(RHS))
1132         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1133     return Insert(new ICmpInst(P, LHS, RHS), Name);
1134   }
1135   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1136                     const Twine &Name = "") {
1137     if (Constant *LC = dyn_cast<Constant>(LHS))
1138       if (Constant *RC = dyn_cast<Constant>(RHS))
1139         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1140     return Insert(new FCmpInst(P, LHS, RHS), Name);
1141   }
1142
1143   //===--------------------------------------------------------------------===//
1144   // Instruction creation methods: Other Instructions
1145   //===--------------------------------------------------------------------===//
1146
1147   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1148                      const Twine &Name = "") {
1149     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1150   }
1151
1152   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1153     return Insert(CallInst::Create(Callee), Name);
1154   }
1155   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1156     return Insert(CallInst::Create(Callee, Arg), Name);
1157   }
1158   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1159                         const Twine &Name = "") {
1160     Value *Args[] = { Arg1, Arg2 };
1161     return Insert(CallInst::Create(Callee, Args), Name);
1162   }
1163   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1164                         const Twine &Name = "") {
1165     Value *Args[] = { Arg1, Arg2, Arg3 };
1166     return Insert(CallInst::Create(Callee, Args), Name);
1167   }
1168   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1169                         Value *Arg4, const Twine &Name = "") {
1170     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1171     return Insert(CallInst::Create(Callee, Args), Name);
1172   }
1173   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1174                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
1175     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1176     return Insert(CallInst::Create(Callee, Args), Name);
1177   }
1178
1179   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1180                        const Twine &Name = "") {
1181     return Insert(CallInst::Create(Callee, Args), Name);
1182   }
1183
1184   Value *CreateSelect(Value *C, Value *True, Value *False,
1185                       const Twine &Name = "") {
1186     if (Constant *CC = dyn_cast<Constant>(C))
1187       if (Constant *TC = dyn_cast<Constant>(True))
1188         if (Constant *FC = dyn_cast<Constant>(False))
1189           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1190     return Insert(SelectInst::Create(C, True, False), Name);
1191   }
1192
1193   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1194     return Insert(new VAArgInst(List, Ty), Name);
1195   }
1196
1197   Value *CreateExtractElement(Value *Vec, Value *Idx,
1198                               const Twine &Name = "") {
1199     if (Constant *VC = dyn_cast<Constant>(Vec))
1200       if (Constant *IC = dyn_cast<Constant>(Idx))
1201         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1202     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1203   }
1204
1205   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1206                              const Twine &Name = "") {
1207     if (Constant *VC = dyn_cast<Constant>(Vec))
1208       if (Constant *NC = dyn_cast<Constant>(NewElt))
1209         if (Constant *IC = dyn_cast<Constant>(Idx))
1210           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1211     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1212   }
1213
1214   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1215                              const Twine &Name = "") {
1216     if (Constant *V1C = dyn_cast<Constant>(V1))
1217       if (Constant *V2C = dyn_cast<Constant>(V2))
1218         if (Constant *MC = dyn_cast<Constant>(Mask))
1219           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1220     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1221   }
1222
1223   Value *CreateExtractValue(Value *Agg,
1224                             ArrayRef<unsigned> Idxs,
1225                             const Twine &Name = "") {
1226     if (Constant *AggC = dyn_cast<Constant>(Agg))
1227       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1228     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1229   }
1230
1231   Value *CreateInsertValue(Value *Agg, Value *Val,
1232                            ArrayRef<unsigned> Idxs,
1233                            const Twine &Name = "") {
1234     if (Constant *AggC = dyn_cast<Constant>(Agg))
1235       if (Constant *ValC = dyn_cast<Constant>(Val))
1236         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1237     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1238   }
1239
1240   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1241                                    const Twine &Name = "") {
1242     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses, Name));
1243   }
1244
1245   //===--------------------------------------------------------------------===//
1246   // Utility creation methods
1247   //===--------------------------------------------------------------------===//
1248
1249   /// CreateIsNull - Return an i1 value testing if \arg Arg is null.
1250   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1251     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1252                         Name);
1253   }
1254
1255   /// CreateIsNotNull - Return an i1 value testing if \arg Arg is not null.
1256   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1257     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1258                         Name);
1259   }
1260
1261   /// CreatePtrDiff - Return the i64 difference between two pointer values,
1262   /// dividing out the size of the pointed-to objects.  This is intended to
1263   /// implement C-style pointer subtraction. As such, the pointers must be
1264   /// appropriately aligned for their element types and pointing into the
1265   /// same object.
1266   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1267     assert(LHS->getType() == RHS->getType() &&
1268            "Pointer subtraction operand types must match!");
1269     PointerType *ArgType = cast<PointerType>(LHS->getType());
1270     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1271     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1272     Value *Difference = CreateSub(LHS_int, RHS_int);
1273     return CreateExactSDiv(Difference,
1274                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1275                            Name);
1276   }
1277 };
1278
1279 }
1280
1281 #endif