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