Address Duncan's comments on r164684:
[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 private:
415   /// \brief Helper to add branch weight metadata onto an instruction.
416   /// \returns The annotated instruction.
417   template <typename InstTy>
418   InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
419     if (Weights)
420       I->setMetadata(LLVMContext::MD_prof, Weights);
421     return I;
422   }
423
424 public:
425   /// CreateRetVoid - Create a 'ret void' instruction.
426   ReturnInst *CreateRetVoid() {
427     return Insert(ReturnInst::Create(Context));
428   }
429
430   /// @verbatim
431   /// CreateRet - Create a 'ret <val>' instruction.
432   /// @endverbatim
433   ReturnInst *CreateRet(Value *V) {
434     return Insert(ReturnInst::Create(Context, V));
435   }
436
437   /// CreateAggregateRet - Create a sequence of N insertvalue instructions,
438   /// with one Value from the retVals array each, that build a aggregate
439   /// return value one value at a time, and a ret instruction to return
440   /// the resulting aggregate value. This is a convenience function for
441   /// code that uses aggregate return values as a vehicle for having
442   /// multiple return values.
443   ///
444   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
445     Value *V = UndefValue::get(getCurrentFunctionReturnType());
446     for (unsigned i = 0; i != N; ++i)
447       V = CreateInsertValue(V, retVals[i], i, "mrv");
448     return Insert(ReturnInst::Create(Context, V));
449   }
450
451   /// CreateBr - Create an unconditional 'br label X' instruction.
452   BranchInst *CreateBr(BasicBlock *Dest) {
453     return Insert(BranchInst::Create(Dest));
454   }
455
456   /// CreateCondBr - Create a conditional 'br Cond, TrueDest, FalseDest'
457   /// instruction.
458   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
459                            MDNode *BranchWeights = 0) {
460     return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
461                                    BranchWeights));
462   }
463
464   /// CreateSwitch - Create a switch instruction with the specified value,
465   /// default dest, and with a hint for the number of cases that will be added
466   /// (for efficient allocation).
467   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
468                            MDNode *BranchWeights = 0) {
469     return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
470                                    BranchWeights));
471   }
472
473   /// CreateIndirectBr - Create an indirect branch instruction with the
474   /// specified address operand, with an optional hint for the number of
475   /// destinations that will be added (for efficient allocation).
476   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
477     return Insert(IndirectBrInst::Create(Addr, NumDests));
478   }
479
480   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
481                            BasicBlock *UnwindDest, const Twine &Name = "") {
482     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest,
483                                      ArrayRef<Value *>()),
484                   Name);
485   }
486   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
487                            BasicBlock *UnwindDest, Value *Arg1,
488                            const Twine &Name = "") {
489     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
490                   Name);
491   }
492   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
493                             BasicBlock *UnwindDest, Value *Arg1,
494                             Value *Arg2, Value *Arg3,
495                             const Twine &Name = "") {
496     Value *Args[] = { Arg1, Arg2, Arg3 };
497     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
498                   Name);
499   }
500   /// CreateInvoke - Create an invoke instruction.
501   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
502                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
503                            const Twine &Name = "") {
504     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
505                   Name);
506   }
507
508   ResumeInst *CreateResume(Value *Exn) {
509     return Insert(ResumeInst::Create(Exn));
510   }
511
512   UnreachableInst *CreateUnreachable() {
513     return Insert(new UnreachableInst(Context));
514   }
515
516   //===--------------------------------------------------------------------===//
517   // Instruction creation methods: Binary Operators
518   //===--------------------------------------------------------------------===//
519 private:
520   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
521                                           Value *LHS, Value *RHS,
522                                           const Twine &Name,
523                                           bool HasNUW, bool HasNSW) {
524     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
525     if (HasNUW) BO->setHasNoUnsignedWrap();
526     if (HasNSW) BO->setHasNoSignedWrap();
527     return BO;
528   }
529
530   Instruction *AddFPMathTag(Instruction *I, MDNode *FPMathTag) const {
531     if (!FPMathTag)
532       FPMathTag = DefaultFPMathTag;
533     if (FPMathTag)
534       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
535     return I;
536   }
537 public:
538   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
539                    bool HasNUW = false, bool HasNSW = false) {
540     if (Constant *LC = dyn_cast<Constant>(LHS))
541       if (Constant *RC = dyn_cast<Constant>(RHS))
542         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
543     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
544                                    HasNUW, HasNSW);
545   }
546   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
547     return CreateAdd(LHS, RHS, Name, false, true);
548   }
549   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
550     return CreateAdd(LHS, RHS, Name, true, false);
551   }
552   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
553                     MDNode *FPMathTag = 0) {
554     if (Constant *LC = dyn_cast<Constant>(LHS))
555       if (Constant *RC = dyn_cast<Constant>(RHS))
556         return Insert(Folder.CreateFAdd(LC, RC), Name);
557     return Insert(AddFPMathTag(BinaryOperator::CreateFAdd(LHS, RHS),
558                                FPMathTag), Name);
559   }
560   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
561                    bool HasNUW = false, bool HasNSW = false) {
562     if (Constant *LC = dyn_cast<Constant>(LHS))
563       if (Constant *RC = dyn_cast<Constant>(RHS))
564         return Insert(Folder.CreateSub(LC, RC), Name);
565     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
566                                    HasNUW, HasNSW);
567   }
568   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
569     return CreateSub(LHS, RHS, Name, false, true);
570   }
571   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
572     return CreateSub(LHS, RHS, Name, true, false);
573   }
574   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
575                     MDNode *FPMathTag = 0) {
576     if (Constant *LC = dyn_cast<Constant>(LHS))
577       if (Constant *RC = dyn_cast<Constant>(RHS))
578         return Insert(Folder.CreateFSub(LC, RC), Name);
579     return Insert(AddFPMathTag(BinaryOperator::CreateFSub(LHS, RHS),
580                                FPMathTag), Name);
581   }
582   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
583                    bool HasNUW = false, bool HasNSW = false) {
584     if (Constant *LC = dyn_cast<Constant>(LHS))
585       if (Constant *RC = dyn_cast<Constant>(RHS))
586         return Insert(Folder.CreateMul(LC, RC), Name);
587     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
588                                    HasNUW, HasNSW);
589   }
590   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
591     return CreateMul(LHS, RHS, Name, false, true);
592   }
593   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
594     return CreateMul(LHS, RHS, Name, true, false);
595   }
596   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
597                     MDNode *FPMathTag = 0) {
598     if (Constant *LC = dyn_cast<Constant>(LHS))
599       if (Constant *RC = dyn_cast<Constant>(RHS))
600         return Insert(Folder.CreateFMul(LC, RC), Name);
601     return Insert(AddFPMathTag(BinaryOperator::CreateFMul(LHS, RHS),
602                                FPMathTag), Name);
603   }
604   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
605                     bool isExact = false) {
606     if (Constant *LC = dyn_cast<Constant>(LHS))
607       if (Constant *RC = dyn_cast<Constant>(RHS))
608         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
609     if (!isExact)
610       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
611     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
612   }
613   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
614     return CreateUDiv(LHS, RHS, Name, true);
615   }
616   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
617                     bool isExact = false) {
618     if (Constant *LC = dyn_cast<Constant>(LHS))
619       if (Constant *RC = dyn_cast<Constant>(RHS))
620         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
621     if (!isExact)
622       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
623     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
624   }
625   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
626     return CreateSDiv(LHS, RHS, Name, true);
627   }
628   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
629                     MDNode *FPMathTag = 0) {
630     if (Constant *LC = dyn_cast<Constant>(LHS))
631       if (Constant *RC = dyn_cast<Constant>(RHS))
632         return Insert(Folder.CreateFDiv(LC, RC), Name);
633     return Insert(AddFPMathTag(BinaryOperator::CreateFDiv(LHS, RHS),
634                                FPMathTag), Name);
635   }
636   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
637     if (Constant *LC = dyn_cast<Constant>(LHS))
638       if (Constant *RC = dyn_cast<Constant>(RHS))
639         return Insert(Folder.CreateURem(LC, RC), Name);
640     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
641   }
642   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
643     if (Constant *LC = dyn_cast<Constant>(LHS))
644       if (Constant *RC = dyn_cast<Constant>(RHS))
645         return Insert(Folder.CreateSRem(LC, RC), Name);
646     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
647   }
648   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
649                     MDNode *FPMathTag = 0) {
650     if (Constant *LC = dyn_cast<Constant>(LHS))
651       if (Constant *RC = dyn_cast<Constant>(RHS))
652         return Insert(Folder.CreateFRem(LC, RC), Name);
653     return Insert(AddFPMathTag(BinaryOperator::CreateFRem(LHS, RHS),
654                                FPMathTag), Name);
655   }
656
657   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
658                    bool HasNUW = false, bool HasNSW = false) {
659     if (Constant *LC = dyn_cast<Constant>(LHS))
660       if (Constant *RC = dyn_cast<Constant>(RHS))
661         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
662     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
663                                    HasNUW, HasNSW);
664   }
665   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
666                    bool HasNUW = false, bool HasNSW = false) {
667     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
668                      HasNUW, HasNSW);
669   }
670   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
671                    bool HasNUW = false, bool HasNSW = false) {
672     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
673                      HasNUW, HasNSW);
674   }
675
676   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
677                     bool isExact = false) {
678     if (Constant *LC = dyn_cast<Constant>(LHS))
679       if (Constant *RC = dyn_cast<Constant>(RHS))
680         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
681     if (!isExact)
682       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
683     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
684   }
685   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
686                     bool isExact = false) {
687     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
688   }
689   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
690                     bool isExact = false) {
691     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
692   }
693
694   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
695                     bool isExact = false) {
696     if (Constant *LC = dyn_cast<Constant>(LHS))
697       if (Constant *RC = dyn_cast<Constant>(RHS))
698         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
699     if (!isExact)
700       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
701     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
702   }
703   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
704                     bool isExact = false) {
705     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
706   }
707   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
708                     bool isExact = false) {
709     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
710   }
711
712   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
713     if (Constant *RC = dyn_cast<Constant>(RHS)) {
714       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
715         return LHS;  // LHS & -1 -> LHS
716       if (Constant *LC = dyn_cast<Constant>(LHS))
717         return Insert(Folder.CreateAnd(LC, RC), Name);
718     }
719     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
720   }
721   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
722     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
723   }
724   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
725     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
726   }
727
728   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
729     if (Constant *RC = dyn_cast<Constant>(RHS)) {
730       if (RC->isNullValue())
731         return LHS;  // LHS | 0 -> LHS
732       if (Constant *LC = dyn_cast<Constant>(LHS))
733         return Insert(Folder.CreateOr(LC, RC), Name);
734     }
735     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
736   }
737   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
738     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
739   }
740   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
741     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
742   }
743
744   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
745     if (Constant *LC = dyn_cast<Constant>(LHS))
746       if (Constant *RC = dyn_cast<Constant>(RHS))
747         return Insert(Folder.CreateXor(LC, RC), Name);
748     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
749   }
750   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
751     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
752   }
753   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
754     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
755   }
756
757   Value *CreateBinOp(Instruction::BinaryOps Opc,
758                      Value *LHS, Value *RHS, const Twine &Name = "") {
759     if (Constant *LC = dyn_cast<Constant>(LHS))
760       if (Constant *RC = dyn_cast<Constant>(RHS))
761         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
762     return Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
763   }
764
765   Value *CreateNeg(Value *V, const Twine &Name = "",
766                    bool HasNUW = false, bool HasNSW = false) {
767     if (Constant *VC = dyn_cast<Constant>(V))
768       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
769     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
770     if (HasNUW) BO->setHasNoUnsignedWrap();
771     if (HasNSW) BO->setHasNoSignedWrap();
772     return BO;
773   }
774   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
775     return CreateNeg(V, Name, false, true);
776   }
777   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
778     return CreateNeg(V, Name, true, false);
779   }
780   Value *CreateFNeg(Value *V, const Twine &Name = "", MDNode *FPMathTag = 0) {
781     if (Constant *VC = dyn_cast<Constant>(V))
782       return Insert(Folder.CreateFNeg(VC), Name);
783     return Insert(AddFPMathTag(BinaryOperator::CreateFNeg(V), FPMathTag), Name);
784   }
785   Value *CreateNot(Value *V, const Twine &Name = "") {
786     if (Constant *VC = dyn_cast<Constant>(V))
787       return Insert(Folder.CreateNot(VC), Name);
788     return Insert(BinaryOperator::CreateNot(V), Name);
789   }
790
791   //===--------------------------------------------------------------------===//
792   // Instruction creation methods: Memory Instructions
793   //===--------------------------------------------------------------------===//
794
795   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = 0,
796                            const Twine &Name = "") {
797     return Insert(new AllocaInst(Ty, ArraySize), Name);
798   }
799   // Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
800   // converting the string to 'bool' for the isVolatile parameter.
801   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
802     return Insert(new LoadInst(Ptr), Name);
803   }
804   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
805     return Insert(new LoadInst(Ptr), Name);
806   }
807   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
808     return Insert(new LoadInst(Ptr, 0, isVolatile), Name);
809   }
810   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
811     return Insert(new StoreInst(Val, Ptr, isVolatile));
812   }
813   // Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")' correctly,
814   // instead of converting the string to 'bool' for the isVolatile parameter.
815   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
816     LoadInst *LI = CreateLoad(Ptr, Name);
817     LI->setAlignment(Align);
818     return LI;
819   }
820   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
821                               const Twine &Name = "") {
822     LoadInst *LI = CreateLoad(Ptr, Name);
823     LI->setAlignment(Align);
824     return LI;
825   }
826   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
827                               const Twine &Name = "") {
828     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
829     LI->setAlignment(Align);
830     return LI;
831   }
832   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
833                                 bool isVolatile = false) {
834     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
835     SI->setAlignment(Align);
836     return SI;
837   }
838   FenceInst *CreateFence(AtomicOrdering Ordering,
839                          SynchronizationScope SynchScope = CrossThread) {
840     return Insert(new FenceInst(Context, Ordering, SynchScope));
841   }
842   AtomicCmpXchgInst *CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
843                                          AtomicOrdering Ordering,
844                                SynchronizationScope SynchScope = CrossThread) {
845     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope));
846   }
847   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
848                                  AtomicOrdering Ordering,
849                                SynchronizationScope SynchScope = CrossThread) {
850     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
851   }
852   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
853                    const Twine &Name = "") {
854     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
855       // Every index must be constant.
856       size_t i, e;
857       for (i = 0, e = IdxList.size(); i != e; ++i)
858         if (!isa<Constant>(IdxList[i]))
859           break;
860       if (i == e)
861         return Insert(Folder.CreateGetElementPtr(PC, IdxList), Name);
862     }
863     return Insert(GetElementPtrInst::Create(Ptr, IdxList), Name);
864   }
865   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
866                            const Twine &Name = "") {
867     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
868       // Every index must be constant.
869       size_t i, e;
870       for (i = 0, e = IdxList.size(); i != e; ++i)
871         if (!isa<Constant>(IdxList[i]))
872           break;
873       if (i == e)
874         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IdxList), Name);
875     }
876     return Insert(GetElementPtrInst::CreateInBounds(Ptr, IdxList), Name);
877   }
878   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
879     if (Constant *PC = dyn_cast<Constant>(Ptr))
880       if (Constant *IC = dyn_cast<Constant>(Idx))
881         return Insert(Folder.CreateGetElementPtr(PC, IC), Name);
882     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
883   }
884   Value *CreateInBoundsGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
885     if (Constant *PC = dyn_cast<Constant>(Ptr))
886       if (Constant *IC = dyn_cast<Constant>(Idx))
887         return Insert(Folder.CreateInBoundsGetElementPtr(PC, IC), Name);
888     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
889   }
890   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
891     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
892
893     if (Constant *PC = dyn_cast<Constant>(Ptr))
894       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
895
896     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
897   }
898   Value *CreateConstInBoundsGEP1_32(Value *Ptr, unsigned Idx0,
899                                     const Twine &Name = "") {
900     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
901
902     if (Constant *PC = dyn_cast<Constant>(Ptr))
903       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
904
905     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
906   }
907   Value *CreateConstGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
908                     const Twine &Name = "") {
909     Value *Idxs[] = {
910       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
911       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
912     };
913
914     if (Constant *PC = dyn_cast<Constant>(Ptr))
915       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
916
917     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
918   }
919   Value *CreateConstInBoundsGEP2_32(Value *Ptr, unsigned Idx0, unsigned Idx1,
920                                     const Twine &Name = "") {
921     Value *Idxs[] = {
922       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
923       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
924     };
925
926     if (Constant *PC = dyn_cast<Constant>(Ptr))
927       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
928
929     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
930   }
931   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
932     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
933
934     if (Constant *PC = dyn_cast<Constant>(Ptr))
935       return Insert(Folder.CreateGetElementPtr(PC, Idx), Name);
936
937     return Insert(GetElementPtrInst::Create(Ptr, Idx), Name);
938   }
939   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
940                                     const Twine &Name = "") {
941     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
942
943     if (Constant *PC = dyn_cast<Constant>(Ptr))
944       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idx), Name);
945
946     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idx), Name);
947   }
948   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
949                     const Twine &Name = "") {
950     Value *Idxs[] = {
951       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
952       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
953     };
954
955     if (Constant *PC = dyn_cast<Constant>(Ptr))
956       return Insert(Folder.CreateGetElementPtr(PC, Idxs), Name);
957
958     return Insert(GetElementPtrInst::Create(Ptr, Idxs), Name);
959   }
960   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
961                                     const Twine &Name = "") {
962     Value *Idxs[] = {
963       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
964       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
965     };
966
967     if (Constant *PC = dyn_cast<Constant>(Ptr))
968       return Insert(Folder.CreateInBoundsGetElementPtr(PC, Idxs), Name);
969
970     return Insert(GetElementPtrInst::CreateInBounds(Ptr, Idxs), Name);
971   }
972   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
973     return CreateConstInBoundsGEP2_32(Ptr, 0, Idx, Name);
974   }
975
976   /// CreateGlobalStringPtr - Same as CreateGlobalString, but return a pointer
977   /// with "i8*" type instead of a pointer to array of i8.
978   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "") {
979     Value *gv = CreateGlobalString(Str, Name);
980     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
981     Value *Args[] = { zero, zero };
982     return CreateInBoundsGEP(gv, Args, Name);
983   }
984
985   //===--------------------------------------------------------------------===//
986   // Instruction creation methods: Cast/Conversion Operators
987   //===--------------------------------------------------------------------===//
988
989   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
990     return CreateCast(Instruction::Trunc, V, DestTy, Name);
991   }
992   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
993     return CreateCast(Instruction::ZExt, V, DestTy, Name);
994   }
995   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
996     return CreateCast(Instruction::SExt, V, DestTy, Name);
997   }
998   /// CreateZExtOrTrunc - Create a ZExt or Trunc from the integer value V to
999   /// DestTy. Return the value untouched if the type of V is already DestTy.
1000   Value *CreateZExtOrTrunc(Value *V, IntegerType *DestTy,
1001                            const Twine &Name = "") {
1002     assert(isa<IntegerType>(V->getType()) && "Can only zero extend integers!");
1003     IntegerType *IntTy = cast<IntegerType>(V->getType());
1004     if (IntTy->getBitWidth() < DestTy->getBitWidth())
1005       return CreateZExt(V, DestTy, Name);
1006     if (IntTy->getBitWidth() > DestTy->getBitWidth())
1007       return CreateTrunc(V, DestTy, Name);
1008     return V;
1009   }
1010   /// CreateSExtOrTrunc - Create a SExt or Trunc from the integer value V to
1011   /// DestTy. Return the value untouched if the type of V is already DestTy.
1012   Value *CreateSExtOrTrunc(Value *V, IntegerType *DestTy,
1013                            const Twine &Name = "") {
1014     assert(isa<IntegerType>(V->getType()) && "Can only sign extend integers!");
1015     IntegerType *IntTy = cast<IntegerType>(V->getType());
1016     if (IntTy->getBitWidth() < DestTy->getBitWidth())
1017       return CreateSExt(V, DestTy, Name);
1018     if (IntTy->getBitWidth() > DestTy->getBitWidth())
1019       return CreateTrunc(V, DestTy, Name);
1020     return V;
1021   }
1022   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1023     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1024   }
1025   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1026     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1027   }
1028   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1029     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1030   }
1031   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1032     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1033   }
1034   Value *CreateFPTrunc(Value *V, Type *DestTy,
1035                        const Twine &Name = "") {
1036     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1037   }
1038   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1039     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1040   }
1041   Value *CreatePtrToInt(Value *V, Type *DestTy,
1042                         const Twine &Name = "") {
1043     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1044   }
1045   Value *CreateIntToPtr(Value *V, Type *DestTy,
1046                         const Twine &Name = "") {
1047     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1048   }
1049   Value *CreateBitCast(Value *V, Type *DestTy,
1050                        const Twine &Name = "") {
1051     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1052   }
1053   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1054                              const Twine &Name = "") {
1055     if (V->getType() == DestTy)
1056       return V;
1057     if (Constant *VC = dyn_cast<Constant>(V))
1058       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1059     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1060   }
1061   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1062                              const Twine &Name = "") {
1063     if (V->getType() == DestTy)
1064       return V;
1065     if (Constant *VC = dyn_cast<Constant>(V))
1066       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1067     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1068   }
1069   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1070                               const Twine &Name = "") {
1071     if (V->getType() == DestTy)
1072       return V;
1073     if (Constant *VC = dyn_cast<Constant>(V))
1074       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1075     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1076   }
1077   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1078                     const Twine &Name = "") {
1079     if (V->getType() == DestTy)
1080       return V;
1081     if (Constant *VC = dyn_cast<Constant>(V))
1082       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1083     return Insert(CastInst::Create(Op, V, DestTy), Name);
1084   }
1085   Value *CreatePointerCast(Value *V, Type *DestTy,
1086                            const Twine &Name = "") {
1087     if (V->getType() == DestTy)
1088       return V;
1089     if (Constant *VC = dyn_cast<Constant>(V))
1090       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1091     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1092   }
1093   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1094                        const Twine &Name = "") {
1095     if (V->getType() == DestTy)
1096       return V;
1097     if (Constant *VC = dyn_cast<Constant>(V))
1098       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1099     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1100   }
1101 private:
1102   // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a compile time
1103   // error, instead of converting the string to bool for the isSigned parameter.
1104   Value *CreateIntCast(Value *, Type *, const char *) LLVM_DELETED_FUNCTION;
1105 public:
1106   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1107     if (V->getType() == DestTy)
1108       return V;
1109     if (Constant *VC = dyn_cast<Constant>(V))
1110       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1111     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1112   }
1113
1114   //===--------------------------------------------------------------------===//
1115   // Instruction creation methods: Compare Instructions
1116   //===--------------------------------------------------------------------===//
1117
1118   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1119     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1120   }
1121   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1122     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1123   }
1124   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1125     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1126   }
1127   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1128     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1129   }
1130   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1131     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1132   }
1133   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1134     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1135   }
1136   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1137     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1138   }
1139   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1140     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1141   }
1142   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1143     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1144   }
1145   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1146     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1147   }
1148
1149   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1150     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name);
1151   }
1152   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1153     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name);
1154   }
1155   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1156     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name);
1157   }
1158   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1159     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name);
1160   }
1161   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1162     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name);
1163   }
1164   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "") {
1165     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name);
1166   }
1167   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "") {
1168     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name);
1169   }
1170   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "") {
1171     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name);
1172   }
1173   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1174     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name);
1175   }
1176   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1177     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name);
1178   }
1179   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1180     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name);
1181   }
1182   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1183     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name);
1184   }
1185   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1186     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name);
1187   }
1188   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1189     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name);
1190   }
1191
1192   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1193                     const Twine &Name = "") {
1194     if (Constant *LC = dyn_cast<Constant>(LHS))
1195       if (Constant *RC = dyn_cast<Constant>(RHS))
1196         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1197     return Insert(new ICmpInst(P, LHS, RHS), Name);
1198   }
1199   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1200                     const Twine &Name = "") {
1201     if (Constant *LC = dyn_cast<Constant>(LHS))
1202       if (Constant *RC = dyn_cast<Constant>(RHS))
1203         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1204     return Insert(new FCmpInst(P, LHS, RHS), Name);
1205   }
1206
1207   //===--------------------------------------------------------------------===//
1208   // Instruction creation methods: Other Instructions
1209   //===--------------------------------------------------------------------===//
1210
1211   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1212                      const Twine &Name = "") {
1213     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1214   }
1215
1216   CallInst *CreateCall(Value *Callee, const Twine &Name = "") {
1217     return Insert(CallInst::Create(Callee), Name);
1218   }
1219   CallInst *CreateCall(Value *Callee, Value *Arg, const Twine &Name = "") {
1220     return Insert(CallInst::Create(Callee, Arg), Name);
1221   }
1222   CallInst *CreateCall2(Value *Callee, Value *Arg1, Value *Arg2,
1223                         const Twine &Name = "") {
1224     Value *Args[] = { Arg1, Arg2 };
1225     return Insert(CallInst::Create(Callee, Args), Name);
1226   }
1227   CallInst *CreateCall3(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1228                         const Twine &Name = "") {
1229     Value *Args[] = { Arg1, Arg2, Arg3 };
1230     return Insert(CallInst::Create(Callee, Args), Name);
1231   }
1232   CallInst *CreateCall4(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1233                         Value *Arg4, const Twine &Name = "") {
1234     Value *Args[] = { Arg1, Arg2, Arg3, Arg4 };
1235     return Insert(CallInst::Create(Callee, Args), Name);
1236   }
1237   CallInst *CreateCall5(Value *Callee, Value *Arg1, Value *Arg2, Value *Arg3,
1238                         Value *Arg4, Value *Arg5, const Twine &Name = "") {
1239     Value *Args[] = { Arg1, Arg2, Arg3, Arg4, Arg5 };
1240     return Insert(CallInst::Create(Callee, Args), Name);
1241   }
1242
1243   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1244                        const Twine &Name = "") {
1245     return Insert(CallInst::Create(Callee, Args), Name);
1246   }
1247
1248   Value *CreateSelect(Value *C, Value *True, Value *False,
1249                       const Twine &Name = "") {
1250     if (Constant *CC = dyn_cast<Constant>(C))
1251       if (Constant *TC = dyn_cast<Constant>(True))
1252         if (Constant *FC = dyn_cast<Constant>(False))
1253           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1254     return Insert(SelectInst::Create(C, True, False), Name);
1255   }
1256
1257   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1258     return Insert(new VAArgInst(List, Ty), Name);
1259   }
1260
1261   Value *CreateExtractElement(Value *Vec, Value *Idx,
1262                               const Twine &Name = "") {
1263     if (Constant *VC = dyn_cast<Constant>(Vec))
1264       if (Constant *IC = dyn_cast<Constant>(Idx))
1265         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1266     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1267   }
1268
1269   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1270                              const Twine &Name = "") {
1271     if (Constant *VC = dyn_cast<Constant>(Vec))
1272       if (Constant *NC = dyn_cast<Constant>(NewElt))
1273         if (Constant *IC = dyn_cast<Constant>(Idx))
1274           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1275     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1276   }
1277
1278   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1279                              const Twine &Name = "") {
1280     if (Constant *V1C = dyn_cast<Constant>(V1))
1281       if (Constant *V2C = dyn_cast<Constant>(V2))
1282         if (Constant *MC = dyn_cast<Constant>(Mask))
1283           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1284     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1285   }
1286
1287   Value *CreateExtractValue(Value *Agg,
1288                             ArrayRef<unsigned> Idxs,
1289                             const Twine &Name = "") {
1290     if (Constant *AggC = dyn_cast<Constant>(Agg))
1291       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1292     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1293   }
1294
1295   Value *CreateInsertValue(Value *Agg, Value *Val,
1296                            ArrayRef<unsigned> Idxs,
1297                            const Twine &Name = "") {
1298     if (Constant *AggC = dyn_cast<Constant>(Agg))
1299       if (Constant *ValC = dyn_cast<Constant>(Val))
1300         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1301     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1302   }
1303
1304   LandingPadInst *CreateLandingPad(Type *Ty, Value *PersFn, unsigned NumClauses,
1305                                    const Twine &Name = "") {
1306     return Insert(LandingPadInst::Create(Ty, PersFn, NumClauses, Name));
1307   }
1308
1309   //===--------------------------------------------------------------------===//
1310   // Utility creation methods
1311   //===--------------------------------------------------------------------===//
1312
1313   /// CreateIsNull - Return an i1 value testing if \p Arg is null.
1314   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1315     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1316                         Name);
1317   }
1318
1319   /// CreateIsNotNull - Return an i1 value testing if \p Arg is not null.
1320   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1321     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1322                         Name);
1323   }
1324
1325   /// CreatePtrDiff - Return the i64 difference between two pointer values,
1326   /// dividing out the size of the pointed-to objects.  This is intended to
1327   /// implement C-style pointer subtraction. As such, the pointers must be
1328   /// appropriately aligned for their element types and pointing into the
1329   /// same object.
1330   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1331     assert(LHS->getType() == RHS->getType() &&
1332            "Pointer subtraction operand types must match!");
1333     PointerType *ArgType = cast<PointerType>(LHS->getType());
1334     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1335     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1336     Value *Difference = CreateSub(LHS_int, RHS_int);
1337     return CreateExactSDiv(Difference,
1338                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1339                            Name);
1340   }
1341 };
1342
1343 }
1344
1345 #endif