[IR] Cleanup some formatting issues in the EH instructions
[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/ConstantFolder.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/ValueHandle.h"
30 #include "llvm/Support/CBindingWrapping.h"
31
32 namespace llvm {
33 class MDNode;
34
35 /// \brief This provides the default implementation of the IRBuilder
36 /// 'InsertHelper' method that is called whenever an instruction is created by
37 /// IRBuilder and needs to be inserted.
38 ///
39 /// By default, this inserts the instruction at the insertion point.
40 template <bool preserveNames = true>
41 class IRBuilderDefaultInserter {
42 protected:
43   void InsertHelper(Instruction *I, const Twine &Name,
44                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
45     if (BB) BB->getInstList().insert(InsertPt, I);
46     if (preserveNames)
47       I->setName(Name);
48   }
49 };
50
51 /// \brief Common base class shared among various IRBuilders.
52 class IRBuilderBase {
53   DebugLoc CurDbgLocation;
54 protected:
55   BasicBlock *BB;
56   BasicBlock::iterator InsertPt;
57   LLVMContext &Context;
58
59   MDNode *DefaultFPMathTag;
60   FastMathFlags FMF;
61 public:
62
63   IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr)
64     : Context(context), DefaultFPMathTag(FPMathTag), FMF() {
65     ClearInsertionPoint();
66   }
67
68   //===--------------------------------------------------------------------===//
69   // Builder configuration methods
70   //===--------------------------------------------------------------------===//
71
72   /// \brief Clear the insertion point: created instructions will not be
73   /// inserted into a block.
74   void ClearInsertionPoint() {
75     BB = nullptr;
76     InsertPt = nullptr;
77   }
78
79   BasicBlock *GetInsertBlock() const { return BB; }
80   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
81   LLVMContext &getContext() const { return Context; }
82
83   /// \brief This specifies that created instructions should be appended to the
84   /// end of the specified block.
85   void SetInsertPoint(BasicBlock *TheBB) {
86     BB = TheBB;
87     InsertPt = BB->end();
88   }
89
90   /// \brief This specifies that created instructions should be inserted before
91   /// the specified instruction.
92   void SetInsertPoint(Instruction *I) {
93     BB = I->getParent();
94     InsertPt = I;
95     assert(I != BB->end() && "Can't read debug loc from end()");
96     SetCurrentDebugLocation(I->getDebugLoc());
97   }
98
99   /// \brief This specifies that created instructions should be inserted at the
100   /// specified point.
101   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
102     BB = TheBB;
103     InsertPt = IP;
104     if (IP != TheBB->end())
105       SetCurrentDebugLocation(IP->getDebugLoc());
106   }
107
108   /// \brief Set location information used by debugging information.
109   void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
110
111   /// \brief Get location information used by debugging information.
112   const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
113
114   /// \brief If this builder has a current debug location, set it on the
115   /// specified instruction.
116   void SetInstDebugLocation(Instruction *I) const {
117     if (CurDbgLocation)
118       I->setDebugLoc(CurDbgLocation);
119   }
120
121   /// \brief Get the return type of the current function that we're emitting
122   /// into.
123   Type *getCurrentFunctionReturnType() const;
124
125   /// InsertPoint - A saved insertion point.
126   class InsertPoint {
127     BasicBlock *Block;
128     BasicBlock::iterator Point;
129
130   public:
131     /// \brief Creates a new insertion point which doesn't point to anything.
132     InsertPoint() : Block(nullptr) {}
133
134     /// \brief Creates a new insertion point at the given location.
135     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
136       : Block(InsertBlock), Point(InsertPoint) {}
137
138     /// \brief Returns true if this insert point is set.
139     bool isSet() const { return (Block != nullptr); }
140
141     llvm::BasicBlock *getBlock() const { return Block; }
142     llvm::BasicBlock::iterator getPoint() const { return Point; }
143   };
144
145   /// \brief Returns the current insert point.
146   InsertPoint saveIP() const {
147     return InsertPoint(GetInsertBlock(), GetInsertPoint());
148   }
149
150   /// \brief Returns the current insert point, clearing it in the process.
151   InsertPoint saveAndClearIP() {
152     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
153     ClearInsertionPoint();
154     return IP;
155   }
156
157   /// \brief Sets the current insert point to a previously-saved location.
158   void restoreIP(InsertPoint IP) {
159     if (IP.isSet())
160       SetInsertPoint(IP.getBlock(), IP.getPoint());
161     else
162       ClearInsertionPoint();
163   }
164
165   /// \brief Get the floating point math metadata being used.
166   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
167
168   /// \brief Get the flags to be applied to created floating point ops
169   FastMathFlags getFastMathFlags() const { return FMF; }
170
171   /// \brief Clear the fast-math flags.
172   void clearFastMathFlags() { FMF.clear(); }
173
174   /// \brief Set the floating point math metadata to be used.
175   void SetDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
176
177   /// \brief Set the fast-math flags to be used with generated fp-math operators
178   void SetFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
179
180   //===--------------------------------------------------------------------===//
181   // RAII helpers.
182   //===--------------------------------------------------------------------===//
183
184   // \brief RAII object that stores the current insertion point and restores it
185   // when the object is destroyed. This includes the debug location.
186   class InsertPointGuard {
187     IRBuilderBase &Builder;
188     AssertingVH<BasicBlock> Block;
189     BasicBlock::iterator Point;
190     DebugLoc DbgLoc;
191
192     InsertPointGuard(const InsertPointGuard &) = delete;
193     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
194
195   public:
196     InsertPointGuard(IRBuilderBase &B)
197         : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
198           DbgLoc(B.getCurrentDebugLocation()) {}
199
200     ~InsertPointGuard() {
201       Builder.restoreIP(InsertPoint(Block, Point));
202       Builder.SetCurrentDebugLocation(DbgLoc);
203     }
204   };
205
206   // \brief RAII object that stores the current fast math settings and restores
207   // them when the object is destroyed.
208   class FastMathFlagGuard {
209     IRBuilderBase &Builder;
210     FastMathFlags FMF;
211     MDNode *FPMathTag;
212
213     FastMathFlagGuard(const FastMathFlagGuard &) = delete;
214     FastMathFlagGuard &operator=(
215         const FastMathFlagGuard &) = delete;
216
217   public:
218     FastMathFlagGuard(IRBuilderBase &B)
219         : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
220
221     ~FastMathFlagGuard() {
222       Builder.FMF = FMF;
223       Builder.DefaultFPMathTag = FPMathTag;
224     }
225   };
226
227   //===--------------------------------------------------------------------===//
228   // Miscellaneous creation methods.
229   //===--------------------------------------------------------------------===//
230
231   /// \brief Make a new global variable with initializer type i8*
232   ///
233   /// Make a new global variable with an initializer that has array of i8 type
234   /// filled in with the null terminated string value specified.  The new global
235   /// variable will be marked mergable with any others of the same contents.  If
236   /// Name is specified, it is the name of the global variable created.
237   GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
238                                      unsigned AddressSpace = 0);
239
240   /// \brief Get a constant value representing either true or false.
241   ConstantInt *getInt1(bool V) {
242     return ConstantInt::get(getInt1Ty(), V);
243   }
244
245   /// \brief Get the constant value for i1 true.
246   ConstantInt *getTrue() {
247     return ConstantInt::getTrue(Context);
248   }
249
250   /// \brief Get the constant value for i1 false.
251   ConstantInt *getFalse() {
252     return ConstantInt::getFalse(Context);
253   }
254
255   /// \brief Get a constant 8-bit value.
256   ConstantInt *getInt8(uint8_t C) {
257     return ConstantInt::get(getInt8Ty(), C);
258   }
259
260   /// \brief Get a constant 16-bit value.
261   ConstantInt *getInt16(uint16_t C) {
262     return ConstantInt::get(getInt16Ty(), C);
263   }
264
265   /// \brief Get a constant 32-bit value.
266   ConstantInt *getInt32(uint32_t C) {
267     return ConstantInt::get(getInt32Ty(), C);
268   }
269
270   /// \brief Get a constant 64-bit value.
271   ConstantInt *getInt64(uint64_t C) {
272     return ConstantInt::get(getInt64Ty(), C);
273   }
274
275   /// \brief Get a constant N-bit value, zero extended or truncated from
276   /// a 64-bit value.
277   ConstantInt *getIntN(unsigned N, uint64_t C) {
278     return ConstantInt::get(getIntNTy(N), C);
279   }
280
281   /// \brief Get a constant integer value.
282   ConstantInt *getInt(const APInt &AI) {
283     return ConstantInt::get(Context, AI);
284   }
285
286   //===--------------------------------------------------------------------===//
287   // Type creation methods
288   //===--------------------------------------------------------------------===//
289
290   /// \brief Fetch the type representing a single bit
291   IntegerType *getInt1Ty() {
292     return Type::getInt1Ty(Context);
293   }
294
295   /// \brief Fetch the type representing an 8-bit integer.
296   IntegerType *getInt8Ty() {
297     return Type::getInt8Ty(Context);
298   }
299
300   /// \brief Fetch the type representing a 16-bit integer.
301   IntegerType *getInt16Ty() {
302     return Type::getInt16Ty(Context);
303   }
304
305   /// \brief Fetch the type representing a 32-bit integer.
306   IntegerType *getInt32Ty() {
307     return Type::getInt32Ty(Context);
308   }
309
310   /// \brief Fetch the type representing a 64-bit integer.
311   IntegerType *getInt64Ty() {
312     return Type::getInt64Ty(Context);
313   }
314
315   /// \brief Fetch the type representing a 128-bit integer.
316   IntegerType *getInt128Ty() {
317     return Type::getInt128Ty(Context);
318   }
319   
320   /// \brief Fetch the type representing an N-bit integer.
321   IntegerType *getIntNTy(unsigned N) {
322     return Type::getIntNTy(Context, N);
323   }
324
325   /// \brief Fetch the type representing a 16-bit floating point value.
326   Type *getHalfTy() {
327     return Type::getHalfTy(Context);
328   }
329
330   /// \brief Fetch the type representing a 32-bit floating point value.
331   Type *getFloatTy() {
332     return Type::getFloatTy(Context);
333   }
334
335   /// \brief Fetch the type representing a 64-bit floating point value.
336   Type *getDoubleTy() {
337     return Type::getDoubleTy(Context);
338   }
339
340   /// \brief Fetch the type representing void.
341   Type *getVoidTy() {
342     return Type::getVoidTy(Context);
343   }
344
345   /// \brief Fetch the type representing a pointer to an 8-bit integer value.
346   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
347     return Type::getInt8PtrTy(Context, AddrSpace);
348   }
349
350   /// \brief Fetch the type representing a pointer to an integer value.
351   IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
352     return DL.getIntPtrType(Context, AddrSpace);
353   }
354
355   //===--------------------------------------------------------------------===//
356   // Intrinsic creation methods
357   //===--------------------------------------------------------------------===//
358
359   /// \brief Create and insert a memset to the specified pointer and the
360   /// specified value.
361   ///
362   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
363   /// specified, it will be added to the instruction. Likewise with alias.scope
364   /// and noalias tags.
365   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
366                          bool isVolatile = false, MDNode *TBAATag = nullptr,
367                          MDNode *ScopeTag = nullptr,
368                          MDNode *NoAliasTag = nullptr) {
369     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
370                         TBAATag, ScopeTag, NoAliasTag);
371   }
372
373   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
374                          bool isVolatile = false, MDNode *TBAATag = nullptr,
375                          MDNode *ScopeTag = nullptr,
376                          MDNode *NoAliasTag = nullptr);
377
378   /// \brief Create and insert a memcpy between the specified pointers.
379   ///
380   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
381   /// specified, it will be added to the instruction. Likewise with alias.scope
382   /// and noalias tags.
383   CallInst *CreateMemCpy(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
384                          bool isVolatile = false, MDNode *TBAATag = nullptr,
385                          MDNode *TBAAStructTag = nullptr,
386                          MDNode *ScopeTag = nullptr,
387                          MDNode *NoAliasTag = nullptr) {
388     return CreateMemCpy(Dst, Src, getInt64(Size), Align, isVolatile, TBAATag,
389                         TBAAStructTag, ScopeTag, NoAliasTag);
390   }
391
392   CallInst *CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
393                          bool isVolatile = false, MDNode *TBAATag = nullptr,
394                          MDNode *TBAAStructTag = nullptr,
395                          MDNode *ScopeTag = nullptr,
396                          MDNode *NoAliasTag = nullptr);
397
398   /// \brief Create and insert a memmove between the specified
399   /// pointers.
400   ///
401   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
402   /// specified, it will be added to the instruction. Likewise with alias.scope
403   /// and noalias tags.
404   CallInst *CreateMemMove(Value *Dst, Value *Src, uint64_t Size, unsigned Align,
405                           bool isVolatile = false, MDNode *TBAATag = nullptr,
406                           MDNode *ScopeTag = nullptr,
407                           MDNode *NoAliasTag = nullptr) {
408     return CreateMemMove(Dst, Src, getInt64(Size), Align, isVolatile,
409                          TBAATag, ScopeTag, NoAliasTag);
410   }
411
412   CallInst *CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
413                           bool isVolatile = false, MDNode *TBAATag = nullptr,
414                           MDNode *ScopeTag = nullptr,
415                           MDNode *NoAliasTag = nullptr);
416
417   /// \brief Create a lifetime.start intrinsic.
418   ///
419   /// If the pointer isn't i8* it will be converted.
420   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
421
422   /// \brief Create a lifetime.end intrinsic.
423   ///
424   /// If the pointer isn't i8* it will be converted.
425   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
426
427   /// \brief Create a call to Masked Load intrinsic
428   CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
429                              Value *PassThru = 0, const Twine &Name = "");
430
431   /// \brief Create a call to Masked Store intrinsic
432   CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
433                               Value *Mask);
434
435   /// \brief Create an assume intrinsic call that allows the optimizer to
436   /// assume that the provided condition will be true.
437   CallInst *CreateAssumption(Value *Cond);
438
439   /// \brief Create a call to the experimental.gc.statepoint intrinsic to
440   /// start a new statepoint sequence.
441   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
442                                    Value *ActualCallee,
443                                    ArrayRef<Value *> CallArgs,
444                                    ArrayRef<Value *> DeoptArgs,
445                                    ArrayRef<Value *> GCArgs,
446                                    const Twine &Name = "");
447
448   // \brief Conveninence function for the common case when CallArgs are filled
449   // in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
450   // .get()'ed to get the Value pointer.
451   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
452                                    Value *ActualCallee, ArrayRef<Use> CallArgs,
453                                    ArrayRef<Value *> DeoptArgs,
454                                    ArrayRef<Value *> GCArgs,
455                                    const Twine &Name = "");
456
457   /// brief Create an invoke to the experimental.gc.statepoint intrinsic to
458   /// start a new statepoint sequence.
459   InvokeInst *
460   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
461                            Value *ActualInvokee, BasicBlock *NormalDest,
462                            BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
463                            ArrayRef<Value *> DeoptArgs,
464                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
465
466   // Conveninence function for the common case when CallArgs are filled in using
467   // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
468   // get the Value *.
469   InvokeInst *
470   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
471                            Value *ActualInvokee, BasicBlock *NormalDest,
472                            BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
473                            ArrayRef<Value *> DeoptArgs,
474                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
475
476   /// \brief Create a call to the experimental.gc.result intrinsic to extract
477   /// the result from a call wrapped in a statepoint.
478   CallInst *CreateGCResult(Instruction *Statepoint,
479                            Type *ResultType,
480                            const Twine &Name = "");
481
482   /// \brief Create a call to the experimental.gc.relocate intrinsics to
483   /// project the relocated value of one pointer from the statepoint.
484   CallInst *CreateGCRelocate(Instruction *Statepoint,
485                              int BaseOffset,
486                              int DerivedOffset,
487                              Type *ResultType,
488                              const Twine &Name = "");
489
490 private:
491   /// \brief Create a call to a masked intrinsic with given Id.
492   /// Masked intrinsic has only one overloaded type - data type.
493   CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
494                                   Type *DataTy, const Twine &Name = "");
495
496   Value *getCastedInt8PtrValue(Value *Ptr);
497 };
498
499 /// \brief This provides a uniform API for creating instructions and inserting
500 /// them into a basic block: either at the end of a BasicBlock, or at a specific
501 /// iterator location in a block.
502 ///
503 /// Note that the builder does not expose the full generality of LLVM
504 /// instructions.  For access to extra instruction properties, use the mutators
505 /// (e.g. setVolatile) on the instructions after they have been
506 /// created. Convenience state exists to specify fast-math flags and fp-math
507 /// tags.
508 ///
509 /// The first template argument handles whether or not to preserve names in the
510 /// final instruction output. This defaults to on.  The second template argument
511 /// specifies a class to use for creating constants.  This defaults to creating
512 /// minimally folded constants.  The third template argument allows clients to
513 /// specify custom insertion hooks that are called on every newly created
514 /// insertion.
515 template<bool preserveNames = true, typename T = ConstantFolder,
516          typename Inserter = IRBuilderDefaultInserter<preserveNames> >
517 class IRBuilder : public IRBuilderBase, public Inserter {
518   T Folder;
519 public:
520   IRBuilder(LLVMContext &C, const T &F, const Inserter &I = Inserter(),
521             MDNode *FPMathTag = nullptr)
522     : IRBuilderBase(C, FPMathTag), Inserter(I), Folder(F) {
523   }
524
525   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr)
526     : IRBuilderBase(C, FPMathTag), Folder() {
527   }
528
529   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr)
530     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
531     SetInsertPoint(TheBB);
532   }
533
534   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr)
535     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
536     SetInsertPoint(TheBB);
537   }
538
539   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr)
540     : IRBuilderBase(IP->getContext(), FPMathTag), Folder() {
541     SetInsertPoint(IP);
542   }
543
544   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T& F,
545             MDNode *FPMathTag = nullptr)
546     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder(F) {
547     SetInsertPoint(TheBB, IP);
548   }
549
550   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
551             MDNode *FPMathTag = nullptr)
552     : IRBuilderBase(TheBB->getContext(), FPMathTag), Folder() {
553     SetInsertPoint(TheBB, IP);
554   }
555
556   /// \brief Get the constant folder being used.
557   const T &getFolder() { return Folder; }
558
559   /// \brief Return true if this builder is configured to actually add the
560   /// requested names to IR created through it.
561   bool isNamePreserving() const { return preserveNames; }
562
563   /// \brief Insert and return the specified instruction.
564   template<typename InstTy>
565   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
566     this->InsertHelper(I, Name, BB, InsertPt);
567     this->SetInstDebugLocation(I);
568     return I;
569   }
570
571   /// \brief No-op overload to handle constants.
572   Constant *Insert(Constant *C, const Twine& = "") const {
573     return C;
574   }
575
576   //===--------------------------------------------------------------------===//
577   // Instruction creation methods: Terminators
578   //===--------------------------------------------------------------------===//
579
580 private:
581   /// \brief Helper to add branch weight metadata onto an instruction.
582   /// \returns The annotated instruction.
583   template <typename InstTy>
584   InstTy *addBranchWeights(InstTy *I, MDNode *Weights) {
585     if (Weights)
586       I->setMetadata(LLVMContext::MD_prof, Weights);
587     return I;
588   }
589
590 public:
591   /// \brief Create a 'ret void' instruction.
592   ReturnInst *CreateRetVoid() {
593     return Insert(ReturnInst::Create(Context));
594   }
595
596   /// \brief Create a 'ret <val>' instruction.
597   ReturnInst *CreateRet(Value *V) {
598     return Insert(ReturnInst::Create(Context, V));
599   }
600
601   /// \brief Create a sequence of N insertvalue instructions,
602   /// with one Value from the retVals array each, that build a aggregate
603   /// return value one value at a time, and a ret instruction to return
604   /// the resulting aggregate value.
605   ///
606   /// This is a convenience function for code that uses aggregate return values
607   /// as a vehicle for having multiple return values.
608   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
609     Value *V = UndefValue::get(getCurrentFunctionReturnType());
610     for (unsigned i = 0; i != N; ++i)
611       V = CreateInsertValue(V, retVals[i], i, "mrv");
612     return Insert(ReturnInst::Create(Context, V));
613   }
614
615   /// \brief Create an unconditional 'br label X' instruction.
616   BranchInst *CreateBr(BasicBlock *Dest) {
617     return Insert(BranchInst::Create(Dest));
618   }
619
620   /// \brief Create a conditional 'br Cond, TrueDest, FalseDest'
621   /// instruction.
622   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
623                            MDNode *BranchWeights = nullptr) {
624     return Insert(addBranchWeights(BranchInst::Create(True, False, Cond),
625                                    BranchWeights));
626   }
627
628   /// \brief Create a switch instruction with the specified value, default dest,
629   /// and with a hint for the number of cases that will be added (for efficient
630   /// allocation).
631   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
632                            MDNode *BranchWeights = nullptr) {
633     return Insert(addBranchWeights(SwitchInst::Create(V, Dest, NumCases),
634                                    BranchWeights));
635   }
636
637   /// \brief Create an indirect branch instruction with the specified address
638   /// operand, with an optional hint for the number of destinations that will be
639   /// added (for efficient allocation).
640   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
641     return Insert(IndirectBrInst::Create(Addr, NumDests));
642   }
643
644   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
645                            BasicBlock *UnwindDest, const Twine &Name = "") {
646     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, None),
647                   Name);
648   }
649   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
650                            BasicBlock *UnwindDest, Value *Arg1,
651                            const Twine &Name = "") {
652     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Arg1),
653                   Name);
654   }
655   InvokeInst *CreateInvoke3(Value *Callee, BasicBlock *NormalDest,
656                             BasicBlock *UnwindDest, Value *Arg1,
657                             Value *Arg2, Value *Arg3,
658                             const Twine &Name = "") {
659     Value *Args[] = { Arg1, Arg2, Arg3 };
660     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
661                   Name);
662   }
663   /// \brief Create an invoke instruction.
664   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
665                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
666                            const Twine &Name = "") {
667     return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
668                   Name);
669   }
670
671   ResumeInst *CreateResume(Value *Exn) {
672     return Insert(ResumeInst::Create(Exn));
673   }
674
675   CleanupReturnInst *CreateCleanupRet(BasicBlock *UnwindBB = nullptr,
676                                       Value *RetVal = nullptr) {
677     return Insert(CleanupReturnInst::Create(Context, RetVal, UnwindBB));
678   }
679
680   CatchPadInst *CreateCatchPad(Type *Ty, BasicBlock *NormalDest,
681                                BasicBlock *UnwindDest, ArrayRef<Value *> Args,
682                                const Twine &Name = "") {
683     return Insert(CatchPadInst::Create(Ty, NormalDest, UnwindDest, Args), Name);
684   }
685
686   CatchEndPadInst *CreateCatchEndPad(BasicBlock *UnwindBB = nullptr) {
687     return Insert(CatchEndPadInst::Create(Context, UnwindBB));
688   }
689
690   TerminatePadInst *CreateTerminatePad(BasicBlock *UnwindBB = nullptr,
691                                        ArrayRef<Value *> Args = {},
692                                        const Twine &Name = "") {
693     return Insert(TerminatePadInst::Create(Context, UnwindBB, Args), Name);
694   }
695
696   CleanupPadInst *CreateCleanupPad(Type *Ty, ArrayRef<Value *> Args,
697                                    const Twine &Name = "") {
698     return Insert(CleanupPadInst::Create(Ty, Args), Name);
699   }
700
701   CatchReturnInst *CreateCatchRet(BasicBlock *BB) {
702     return Insert(CatchReturnInst::Create(BB));
703   }
704
705   UnreachableInst *CreateUnreachable() {
706     return Insert(new UnreachableInst(Context));
707   }
708
709   //===--------------------------------------------------------------------===//
710   // Instruction creation methods: Binary Operators
711   //===--------------------------------------------------------------------===//
712 private:
713   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
714                                           Value *LHS, Value *RHS,
715                                           const Twine &Name,
716                                           bool HasNUW, bool HasNSW) {
717     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
718     if (HasNUW) BO->setHasNoUnsignedWrap();
719     if (HasNSW) BO->setHasNoSignedWrap();
720     return BO;
721   }
722
723   Instruction *AddFPMathAttributes(Instruction *I,
724                                    MDNode *FPMathTag,
725                                    FastMathFlags FMF) const {
726     if (!FPMathTag)
727       FPMathTag = DefaultFPMathTag;
728     if (FPMathTag)
729       I->setMetadata(LLVMContext::MD_fpmath, FPMathTag);
730     I->setFastMathFlags(FMF);
731     return I;
732   }
733 public:
734   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
735                    bool HasNUW = false, bool HasNSW = false) {
736     if (Constant *LC = dyn_cast<Constant>(LHS))
737       if (Constant *RC = dyn_cast<Constant>(RHS))
738         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
739     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
740                                    HasNUW, HasNSW);
741   }
742   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
743     return CreateAdd(LHS, RHS, Name, false, true);
744   }
745   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
746     return CreateAdd(LHS, RHS, Name, true, false);
747   }
748   Value *CreateFAdd(Value *LHS, Value *RHS, const Twine &Name = "",
749                     MDNode *FPMathTag = nullptr) {
750     if (Constant *LC = dyn_cast<Constant>(LHS))
751       if (Constant *RC = dyn_cast<Constant>(RHS))
752         return Insert(Folder.CreateFAdd(LC, RC), Name);
753     return Insert(AddFPMathAttributes(BinaryOperator::CreateFAdd(LHS, RHS),
754                                       FPMathTag, FMF), Name);
755   }
756   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
757                    bool HasNUW = false, bool HasNSW = false) {
758     if (Constant *LC = dyn_cast<Constant>(LHS))
759       if (Constant *RC = dyn_cast<Constant>(RHS))
760         return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
761     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
762                                    HasNUW, HasNSW);
763   }
764   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
765     return CreateSub(LHS, RHS, Name, false, true);
766   }
767   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
768     return CreateSub(LHS, RHS, Name, true, false);
769   }
770   Value *CreateFSub(Value *LHS, Value *RHS, const Twine &Name = "",
771                     MDNode *FPMathTag = nullptr) {
772     if (Constant *LC = dyn_cast<Constant>(LHS))
773       if (Constant *RC = dyn_cast<Constant>(RHS))
774         return Insert(Folder.CreateFSub(LC, RC), Name);
775     return Insert(AddFPMathAttributes(BinaryOperator::CreateFSub(LHS, RHS),
776                                       FPMathTag, FMF), Name);
777   }
778   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
779                    bool HasNUW = false, bool HasNSW = false) {
780     if (Constant *LC = dyn_cast<Constant>(LHS))
781       if (Constant *RC = dyn_cast<Constant>(RHS))
782         return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
783     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
784                                    HasNUW, HasNSW);
785   }
786   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
787     return CreateMul(LHS, RHS, Name, false, true);
788   }
789   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
790     return CreateMul(LHS, RHS, Name, true, false);
791   }
792   Value *CreateFMul(Value *LHS, Value *RHS, const Twine &Name = "",
793                     MDNode *FPMathTag = nullptr) {
794     if (Constant *LC = dyn_cast<Constant>(LHS))
795       if (Constant *RC = dyn_cast<Constant>(RHS))
796         return Insert(Folder.CreateFMul(LC, RC), Name);
797     return Insert(AddFPMathAttributes(BinaryOperator::CreateFMul(LHS, RHS),
798                                       FPMathTag, FMF), Name);
799   }
800   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
801                     bool isExact = false) {
802     if (Constant *LC = dyn_cast<Constant>(LHS))
803       if (Constant *RC = dyn_cast<Constant>(RHS))
804         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
805     if (!isExact)
806       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
807     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
808   }
809   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
810     return CreateUDiv(LHS, RHS, Name, true);
811   }
812   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
813                     bool isExact = false) {
814     if (Constant *LC = dyn_cast<Constant>(LHS))
815       if (Constant *RC = dyn_cast<Constant>(RHS))
816         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
817     if (!isExact)
818       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
819     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
820   }
821   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
822     return CreateSDiv(LHS, RHS, Name, true);
823   }
824   Value *CreateFDiv(Value *LHS, Value *RHS, const Twine &Name = "",
825                     MDNode *FPMathTag = nullptr) {
826     if (Constant *LC = dyn_cast<Constant>(LHS))
827       if (Constant *RC = dyn_cast<Constant>(RHS))
828         return Insert(Folder.CreateFDiv(LC, RC), Name);
829     return Insert(AddFPMathAttributes(BinaryOperator::CreateFDiv(LHS, RHS),
830                                       FPMathTag, FMF), Name);
831   }
832   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
833     if (Constant *LC = dyn_cast<Constant>(LHS))
834       if (Constant *RC = dyn_cast<Constant>(RHS))
835         return Insert(Folder.CreateURem(LC, RC), Name);
836     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
837   }
838   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
839     if (Constant *LC = dyn_cast<Constant>(LHS))
840       if (Constant *RC = dyn_cast<Constant>(RHS))
841         return Insert(Folder.CreateSRem(LC, RC), Name);
842     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
843   }
844   Value *CreateFRem(Value *LHS, Value *RHS, const Twine &Name = "",
845                     MDNode *FPMathTag = nullptr) {
846     if (Constant *LC = dyn_cast<Constant>(LHS))
847       if (Constant *RC = dyn_cast<Constant>(RHS))
848         return Insert(Folder.CreateFRem(LC, RC), Name);
849     return Insert(AddFPMathAttributes(BinaryOperator::CreateFRem(LHS, RHS),
850                                       FPMathTag, FMF), Name);
851   }
852
853   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
854                    bool HasNUW = false, bool HasNSW = false) {
855     if (Constant *LC = dyn_cast<Constant>(LHS))
856       if (Constant *RC = dyn_cast<Constant>(RHS))
857         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
858     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
859                                    HasNUW, HasNSW);
860   }
861   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
862                    bool HasNUW = false, bool HasNSW = false) {
863     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
864                      HasNUW, HasNSW);
865   }
866   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
867                    bool HasNUW = false, bool HasNSW = false) {
868     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
869                      HasNUW, HasNSW);
870   }
871
872   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
873                     bool isExact = false) {
874     if (Constant *LC = dyn_cast<Constant>(LHS))
875       if (Constant *RC = dyn_cast<Constant>(RHS))
876         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
877     if (!isExact)
878       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
879     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
880   }
881   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
882                     bool isExact = false) {
883     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
884   }
885   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
886                     bool isExact = false) {
887     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
888   }
889
890   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
891                     bool isExact = false) {
892     if (Constant *LC = dyn_cast<Constant>(LHS))
893       if (Constant *RC = dyn_cast<Constant>(RHS))
894         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
895     if (!isExact)
896       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
897     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
898   }
899   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
900                     bool isExact = false) {
901     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
902   }
903   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
904                     bool isExact = false) {
905     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
906   }
907
908   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
909     if (Constant *RC = dyn_cast<Constant>(RHS)) {
910       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isAllOnesValue())
911         return LHS;  // LHS & -1 -> LHS
912       if (Constant *LC = dyn_cast<Constant>(LHS))
913         return Insert(Folder.CreateAnd(LC, RC), Name);
914     }
915     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
916   }
917   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
918     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
919   }
920   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
921     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
922   }
923
924   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
925     if (Constant *RC = dyn_cast<Constant>(RHS)) {
926       if (RC->isNullValue())
927         return LHS;  // LHS | 0 -> LHS
928       if (Constant *LC = dyn_cast<Constant>(LHS))
929         return Insert(Folder.CreateOr(LC, RC), Name);
930     }
931     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
932   }
933   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
934     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
935   }
936   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
937     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
938   }
939
940   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
941     if (Constant *LC = dyn_cast<Constant>(LHS))
942       if (Constant *RC = dyn_cast<Constant>(RHS))
943         return Insert(Folder.CreateXor(LC, RC), Name);
944     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
945   }
946   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
947     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
948   }
949   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
950     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
951   }
952
953   Value *CreateBinOp(Instruction::BinaryOps Opc,
954                      Value *LHS, Value *RHS, const Twine &Name = "",
955                      MDNode *FPMathTag = nullptr) {
956     if (Constant *LC = dyn_cast<Constant>(LHS))
957       if (Constant *RC = dyn_cast<Constant>(RHS))
958         return Insert(Folder.CreateBinOp(Opc, LC, RC), Name);
959     llvm::Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
960     if (isa<FPMathOperator>(BinOp))
961       BinOp = AddFPMathAttributes(BinOp, FPMathTag, FMF);
962     return Insert(BinOp, Name);
963   }
964
965   Value *CreateNeg(Value *V, const Twine &Name = "",
966                    bool HasNUW = false, bool HasNSW = false) {
967     if (Constant *VC = dyn_cast<Constant>(V))
968       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
969     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
970     if (HasNUW) BO->setHasNoUnsignedWrap();
971     if (HasNSW) BO->setHasNoSignedWrap();
972     return BO;
973   }
974   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
975     return CreateNeg(V, Name, false, true);
976   }
977   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
978     return CreateNeg(V, Name, true, false);
979   }
980   Value *CreateFNeg(Value *V, const Twine &Name = "",
981                     MDNode *FPMathTag = nullptr) {
982     if (Constant *VC = dyn_cast<Constant>(V))
983       return Insert(Folder.CreateFNeg(VC), Name);
984     return Insert(AddFPMathAttributes(BinaryOperator::CreateFNeg(V),
985                                       FPMathTag, FMF), Name);
986   }
987   Value *CreateNot(Value *V, const Twine &Name = "") {
988     if (Constant *VC = dyn_cast<Constant>(V))
989       return Insert(Folder.CreateNot(VC), Name);
990     return Insert(BinaryOperator::CreateNot(V), Name);
991   }
992
993   //===--------------------------------------------------------------------===//
994   // Instruction creation methods: Memory Instructions
995   //===--------------------------------------------------------------------===//
996
997   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
998                            const Twine &Name = "") {
999     return Insert(new AllocaInst(Ty, ArraySize), Name);
1000   }
1001   // \brief Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
1002   // converting the string to 'bool' for the isVolatile parameter.
1003   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1004     return Insert(new LoadInst(Ptr), Name);
1005   }
1006   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1007     return Insert(new LoadInst(Ptr), Name);
1008   }
1009   LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1010     return Insert(new LoadInst(Ty, Ptr), Name);
1011   }
1012   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1013     return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1014   }
1015   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1016     return Insert(new StoreInst(Val, Ptr, isVolatile));
1017   }
1018   // \brief Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1019   // correctly, instead of converting the string to 'bool' for the isVolatile
1020   // parameter.
1021   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1022     LoadInst *LI = CreateLoad(Ptr, Name);
1023     LI->setAlignment(Align);
1024     return LI;
1025   }
1026   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1027                               const Twine &Name = "") {
1028     LoadInst *LI = CreateLoad(Ptr, Name);
1029     LI->setAlignment(Align);
1030     return LI;
1031   }
1032   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1033                               const Twine &Name = "") {
1034     LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1035     LI->setAlignment(Align);
1036     return LI;
1037   }
1038   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1039                                 bool isVolatile = false) {
1040     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1041     SI->setAlignment(Align);
1042     return SI;
1043   }
1044   FenceInst *CreateFence(AtomicOrdering Ordering,
1045                          SynchronizationScope SynchScope = CrossThread,
1046                          const Twine &Name = "") {
1047     return Insert(new FenceInst(Context, Ordering, SynchScope), Name);
1048   }
1049   AtomicCmpXchgInst *
1050   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1051                       AtomicOrdering SuccessOrdering,
1052                       AtomicOrdering FailureOrdering,
1053                       SynchronizationScope SynchScope = CrossThread) {
1054     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1055                                         FailureOrdering, SynchScope));
1056   }
1057   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1058                                  AtomicOrdering Ordering,
1059                                SynchronizationScope SynchScope = CrossThread) {
1060     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SynchScope));
1061   }
1062   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1063                    const Twine &Name = "") {
1064     return CreateGEP(nullptr, Ptr, IdxList, Name);
1065   }
1066   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1067                    const Twine &Name = "") {
1068     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1069       // Every index must be constant.
1070       size_t i, e;
1071       for (i = 0, e = IdxList.size(); i != e; ++i)
1072         if (!isa<Constant>(IdxList[i]))
1073           break;
1074       if (i == e)
1075         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1076     }
1077     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1078   }
1079   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1080                            const Twine &Name = "") {
1081     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1082   }
1083   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1084                            const Twine &Name = "") {
1085     if (Constant *PC = dyn_cast<Constant>(Ptr)) {
1086       // Every index must be constant.
1087       size_t i, e;
1088       for (i = 0, e = IdxList.size(); i != e; ++i)
1089         if (!isa<Constant>(IdxList[i]))
1090           break;
1091       if (i == e)
1092         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1093                       Name);
1094     }
1095     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1096   }
1097   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1098     return CreateGEP(nullptr, Ptr, Idx, Name);
1099   }
1100   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1101     if (Constant *PC = dyn_cast<Constant>(Ptr))
1102       if (Constant *IC = dyn_cast<Constant>(Idx))
1103         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1104     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1105   }
1106   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1107                            const Twine &Name = "") {
1108     if (Constant *PC = dyn_cast<Constant>(Ptr))
1109       if (Constant *IC = dyn_cast<Constant>(Idx))
1110         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1111     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1112   }
1113   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1114     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1115   }
1116   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1117                             const Twine &Name = "") {
1118     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1119
1120     if (Constant *PC = dyn_cast<Constant>(Ptr))
1121       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1122
1123     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1124   }
1125   Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1126                                     const Twine &Name = "") {
1127     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1128
1129     if (Constant *PC = dyn_cast<Constant>(Ptr))
1130       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1131
1132     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1133   }
1134   Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1135                             const Twine &Name = "") {
1136     Value *Idxs[] = {
1137       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1138       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1139     };
1140
1141     if (Constant *PC = dyn_cast<Constant>(Ptr))
1142       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1143
1144     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1145   }
1146   Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1147                                     unsigned Idx1, const Twine &Name = "") {
1148     Value *Idxs[] = {
1149       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1150       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1151     };
1152
1153     if (Constant *PC = dyn_cast<Constant>(Ptr))
1154       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1155
1156     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1157   }
1158   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1159     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1160
1161     if (Constant *PC = dyn_cast<Constant>(Ptr))
1162       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1163
1164     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1165   }
1166   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1167                                     const Twine &Name = "") {
1168     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1169
1170     if (Constant *PC = dyn_cast<Constant>(Ptr))
1171       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1172
1173     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1174   }
1175   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1176                     const Twine &Name = "") {
1177     Value *Idxs[] = {
1178       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1179       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1180     };
1181
1182     if (Constant *PC = dyn_cast<Constant>(Ptr))
1183       return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1184
1185     return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1186   }
1187   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1188                                     const Twine &Name = "") {
1189     Value *Idxs[] = {
1190       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1191       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1192     };
1193
1194     if (Constant *PC = dyn_cast<Constant>(Ptr))
1195       return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1196                     Name);
1197
1198     return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1199   }
1200   Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1201                          const Twine &Name = "") {
1202     return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1203   }
1204
1205   /// \brief Same as CreateGlobalString, but return a pointer with "i8*" type
1206   /// instead of a pointer to array of i8.
1207   Value *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1208                                unsigned AddressSpace = 0) {
1209     GlobalVariable *gv = CreateGlobalString(Str, Name, AddressSpace);
1210     Value *zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1211     Value *Args[] = { zero, zero };
1212     return CreateInBoundsGEP(gv->getValueType(), gv, Args, Name);
1213   }
1214
1215   //===--------------------------------------------------------------------===//
1216   // Instruction creation methods: Cast/Conversion Operators
1217   //===--------------------------------------------------------------------===//
1218
1219   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1220     return CreateCast(Instruction::Trunc, V, DestTy, Name);
1221   }
1222   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1223     return CreateCast(Instruction::ZExt, V, DestTy, Name);
1224   }
1225   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1226     return CreateCast(Instruction::SExt, V, DestTy, Name);
1227   }
1228   /// \brief Create a ZExt or Trunc from the integer value V to DestTy. Return
1229   /// the value untouched if the type of V is already DestTy.
1230   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1231                            const Twine &Name = "") {
1232     assert(V->getType()->isIntOrIntVectorTy() &&
1233            DestTy->isIntOrIntVectorTy() &&
1234            "Can only zero extend/truncate integers!");
1235     Type *VTy = V->getType();
1236     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1237       return CreateZExt(V, DestTy, Name);
1238     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1239       return CreateTrunc(V, DestTy, Name);
1240     return V;
1241   }
1242   /// \brief Create a SExt or Trunc from the integer value V to DestTy. Return
1243   /// the value untouched if the type of V is already DestTy.
1244   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1245                            const Twine &Name = "") {
1246     assert(V->getType()->isIntOrIntVectorTy() &&
1247            DestTy->isIntOrIntVectorTy() &&
1248            "Can only sign extend/truncate integers!");
1249     Type *VTy = V->getType();
1250     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1251       return CreateSExt(V, DestTy, Name);
1252     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1253       return CreateTrunc(V, DestTy, Name);
1254     return V;
1255   }
1256   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1257     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1258   }
1259   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1260     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1261   }
1262   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1263     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1264   }
1265   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1266     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1267   }
1268   Value *CreateFPTrunc(Value *V, Type *DestTy,
1269                        const Twine &Name = "") {
1270     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1271   }
1272   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1273     return CreateCast(Instruction::FPExt, V, DestTy, Name);
1274   }
1275   Value *CreatePtrToInt(Value *V, Type *DestTy,
1276                         const Twine &Name = "") {
1277     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1278   }
1279   Value *CreateIntToPtr(Value *V, Type *DestTy,
1280                         const Twine &Name = "") {
1281     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1282   }
1283   Value *CreateBitCast(Value *V, Type *DestTy,
1284                        const Twine &Name = "") {
1285     return CreateCast(Instruction::BitCast, V, DestTy, Name);
1286   }
1287   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1288                              const Twine &Name = "") {
1289     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1290   }
1291   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1292                              const Twine &Name = "") {
1293     if (V->getType() == DestTy)
1294       return V;
1295     if (Constant *VC = dyn_cast<Constant>(V))
1296       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1297     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1298   }
1299   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1300                              const Twine &Name = "") {
1301     if (V->getType() == DestTy)
1302       return V;
1303     if (Constant *VC = dyn_cast<Constant>(V))
1304       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1305     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1306   }
1307   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1308                               const Twine &Name = "") {
1309     if (V->getType() == DestTy)
1310       return V;
1311     if (Constant *VC = dyn_cast<Constant>(V))
1312       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1313     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1314   }
1315   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1316                     const Twine &Name = "") {
1317     if (V->getType() == DestTy)
1318       return V;
1319     if (Constant *VC = dyn_cast<Constant>(V))
1320       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1321     return Insert(CastInst::Create(Op, V, DestTy), Name);
1322   }
1323   Value *CreatePointerCast(Value *V, Type *DestTy,
1324                            const Twine &Name = "") {
1325     if (V->getType() == DestTy)
1326       return V;
1327     if (Constant *VC = dyn_cast<Constant>(V))
1328       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1329     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1330   }
1331
1332   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1333                                              const Twine &Name = "") {
1334     if (V->getType() == DestTy)
1335       return V;
1336
1337     if (Constant *VC = dyn_cast<Constant>(V)) {
1338       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1339                     Name);
1340     }
1341
1342     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1343                   Name);
1344   }
1345
1346   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1347                        const Twine &Name = "") {
1348     if (V->getType() == DestTy)
1349       return V;
1350     if (Constant *VC = dyn_cast<Constant>(V))
1351       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1352     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1353   }
1354
1355   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1356                                 const Twine &Name = "") {
1357     if (V->getType() == DestTy)
1358       return V;
1359     if (V->getType()->isPointerTy() && DestTy->isIntegerTy())
1360       return CreatePtrToInt(V, DestTy, Name);
1361     if (V->getType()->isIntegerTy() && DestTy->isPointerTy())
1362       return CreateIntToPtr(V, DestTy, Name);
1363
1364     return CreateBitCast(V, DestTy, Name);
1365   }
1366 private:
1367   // \brief Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1368   // compile time error, instead of converting the string to bool for the
1369   // isSigned parameter.
1370   Value *CreateIntCast(Value *, Type *, const char *) = delete;
1371 public:
1372   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1373     if (V->getType() == DestTy)
1374       return V;
1375     if (Constant *VC = dyn_cast<Constant>(V))
1376       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1377     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1378   }
1379
1380   //===--------------------------------------------------------------------===//
1381   // Instruction creation methods: Compare Instructions
1382   //===--------------------------------------------------------------------===//
1383
1384   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1385     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1386   }
1387   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1388     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1389   }
1390   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1391     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1392   }
1393   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1394     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1395   }
1396   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1397     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1398   }
1399   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1400     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1401   }
1402   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1403     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1404   }
1405   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1406     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1407   }
1408   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1409     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1410   }
1411   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1412     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1413   }
1414
1415   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1416                        MDNode *FPMathTag = nullptr) {
1417     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1418   }
1419   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1420                        MDNode *FPMathTag = nullptr) {
1421     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1422   }
1423   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1424                        MDNode *FPMathTag = nullptr) {
1425     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1426   }
1427   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1428                        MDNode *FPMathTag = nullptr) {
1429     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1430   }
1431   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1432                        MDNode *FPMathTag = nullptr) {
1433     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1434   }
1435   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1436                        MDNode *FPMathTag = nullptr) {
1437     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1438   }
1439   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1440                        MDNode *FPMathTag = nullptr) {
1441     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1442   }
1443   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1444                        MDNode *FPMathTag = nullptr) {
1445     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1446   }
1447   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1448                        MDNode *FPMathTag = nullptr) {
1449     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1450   }
1451   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1452                        MDNode *FPMathTag = nullptr) {
1453     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1454   }
1455   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1456                        MDNode *FPMathTag = nullptr) {
1457     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1458   }
1459   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1460                        MDNode *FPMathTag = nullptr) {
1461     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1462   }
1463   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1464                        MDNode *FPMathTag = nullptr) {
1465     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1466   }
1467   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1468                        MDNode *FPMathTag = nullptr) {
1469     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1470   }
1471
1472   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1473                     const Twine &Name = "") {
1474     if (Constant *LC = dyn_cast<Constant>(LHS))
1475       if (Constant *RC = dyn_cast<Constant>(RHS))
1476         return Insert(Folder.CreateICmp(P, LC, RC), Name);
1477     return Insert(new ICmpInst(P, LHS, RHS), Name);
1478   }
1479   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1480                     const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1481     if (Constant *LC = dyn_cast<Constant>(LHS))
1482       if (Constant *RC = dyn_cast<Constant>(RHS))
1483         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1484     return Insert(AddFPMathAttributes(new FCmpInst(P, LHS, RHS),
1485                                       FPMathTag, FMF), Name);
1486   }
1487
1488   //===--------------------------------------------------------------------===//
1489   // Instruction creation methods: Other Instructions
1490   //===--------------------------------------------------------------------===//
1491
1492   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1493                      const Twine &Name = "") {
1494     return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1495   }
1496
1497   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1498                        const Twine &Name = "") {
1499     return Insert(CallInst::Create(Callee, Args), Name);
1500   }
1501
1502   CallInst *CreateCall(llvm::FunctionType *FTy, Value *Callee,
1503                        ArrayRef<Value *> Args, const Twine &Name = "") {
1504     return Insert(CallInst::Create(FTy, Callee, Args), Name);
1505   }
1506
1507   CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1508                        const Twine &Name = "") {
1509     return CreateCall(Callee->getFunctionType(), Callee, Args, Name);
1510   }
1511
1512   Value *CreateSelect(Value *C, Value *True, Value *False,
1513                       const Twine &Name = "") {
1514     if (Constant *CC = dyn_cast<Constant>(C))
1515       if (Constant *TC = dyn_cast<Constant>(True))
1516         if (Constant *FC = dyn_cast<Constant>(False))
1517           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1518     return Insert(SelectInst::Create(C, True, False), Name);
1519   }
1520
1521   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1522     return Insert(new VAArgInst(List, Ty), Name);
1523   }
1524
1525   Value *CreateExtractElement(Value *Vec, Value *Idx,
1526                               const Twine &Name = "") {
1527     if (Constant *VC = dyn_cast<Constant>(Vec))
1528       if (Constant *IC = dyn_cast<Constant>(Idx))
1529         return Insert(Folder.CreateExtractElement(VC, IC), Name);
1530     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1531   }
1532
1533   Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1534                               const Twine &Name = "") {
1535     return CreateExtractElement(Vec, getInt64(Idx), Name);
1536   }
1537
1538   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1539                              const Twine &Name = "") {
1540     if (Constant *VC = dyn_cast<Constant>(Vec))
1541       if (Constant *NC = dyn_cast<Constant>(NewElt))
1542         if (Constant *IC = dyn_cast<Constant>(Idx))
1543           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1544     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1545   }
1546
1547   Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1548                              const Twine &Name = "") {
1549     return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1550   }
1551
1552   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1553                              const Twine &Name = "") {
1554     if (Constant *V1C = dyn_cast<Constant>(V1))
1555       if (Constant *V2C = dyn_cast<Constant>(V2))
1556         if (Constant *MC = dyn_cast<Constant>(Mask))
1557           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1558     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1559   }
1560
1561   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<int> IntMask,
1562                              const Twine &Name = "") {
1563     size_t MaskSize = IntMask.size();
1564     SmallVector<Constant*, 8> MaskVec(MaskSize);
1565     for (size_t i = 0; i != MaskSize; ++i)
1566       MaskVec[i] = getInt32(IntMask[i]);
1567     Value *Mask = ConstantVector::get(MaskVec);
1568     return CreateShuffleVector(V1, V2, Mask, Name);
1569   }
1570
1571   Value *CreateExtractValue(Value *Agg,
1572                             ArrayRef<unsigned> Idxs,
1573                             const Twine &Name = "") {
1574     if (Constant *AggC = dyn_cast<Constant>(Agg))
1575       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1576     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1577   }
1578
1579   Value *CreateInsertValue(Value *Agg, Value *Val,
1580                            ArrayRef<unsigned> Idxs,
1581                            const Twine &Name = "") {
1582     if (Constant *AggC = dyn_cast<Constant>(Agg))
1583       if (Constant *ValC = dyn_cast<Constant>(Val))
1584         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1585     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1586   }
1587
1588   LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1589                                    const Twine &Name = "") {
1590     return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1591   }
1592
1593   //===--------------------------------------------------------------------===//
1594   // Utility creation methods
1595   //===--------------------------------------------------------------------===//
1596
1597   /// \brief Return an i1 value testing if \p Arg is null.
1598   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1599     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1600                         Name);
1601   }
1602
1603   /// \brief Return an i1 value testing if \p Arg is not null.
1604   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1605     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
1606                         Name);
1607   }
1608
1609   /// \brief Return the i64 difference between two pointer values, dividing out
1610   /// the size of the pointed-to objects.
1611   ///
1612   /// This is intended to implement C-style pointer subtraction. As such, the
1613   /// pointers must be appropriately aligned for their element types and
1614   /// pointing into the same object.
1615   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
1616     assert(LHS->getType() == RHS->getType() &&
1617            "Pointer subtraction operand types must match!");
1618     PointerType *ArgType = cast<PointerType>(LHS->getType());
1619     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
1620     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
1621     Value *Difference = CreateSub(LHS_int, RHS_int);
1622     return CreateExactSDiv(Difference,
1623                            ConstantExpr::getSizeOf(ArgType->getElementType()),
1624                            Name);
1625   }
1626
1627   /// \brief Return a vector value that contains \arg V broadcasted to \p
1628   /// NumElts elements.
1629   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
1630     assert(NumElts > 0 && "Cannot splat to an empty vector!");
1631
1632     // First insert it into an undef vector so we can shuffle it.
1633     Type *I32Ty = getInt32Ty();
1634     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
1635     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
1636                             Name + ".splatinsert");
1637
1638     // Shuffle the value across the desired number of elements.
1639     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
1640     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
1641   }
1642
1643   /// \brief Return a value that has been extracted from a larger integer type.
1644   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
1645                               IntegerType *ExtractedTy, uint64_t Offset,
1646                               const Twine &Name) {
1647     IntegerType *IntTy = cast<IntegerType>(From->getType());
1648     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
1649                DL.getTypeStoreSize(IntTy) &&
1650            "Element extends past full value");
1651     uint64_t ShAmt = 8 * Offset;
1652     Value *V = From;
1653     if (DL.isBigEndian())
1654       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
1655                    DL.getTypeStoreSize(ExtractedTy) - Offset);
1656     if (ShAmt) {
1657       V = CreateLShr(V, ShAmt, Name + ".shift");
1658     }
1659     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
1660            "Cannot extract to a larger integer!");
1661     if (ExtractedTy != IntTy) {
1662       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
1663     }
1664     return V;
1665   }
1666
1667   /// \brief Create an assume intrinsic call that represents an alignment
1668   /// assumption on the provided pointer.
1669   ///
1670   /// An optional offset can be provided, and if it is provided, the offset
1671   /// must be subtracted from the provided pointer to get the pointer with the
1672   /// specified alignment.
1673   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
1674                                       unsigned Alignment,
1675                                       Value *OffsetValue = nullptr) {
1676     assert(isa<PointerType>(PtrValue->getType()) &&
1677            "trying to create an alignment assumption on a non-pointer?");
1678
1679     PointerType *PtrTy = cast<PointerType>(PtrValue->getType());
1680     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
1681     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
1682
1683     Value *Mask = ConstantInt::get(IntPtrTy,
1684       Alignment > 0 ? Alignment - 1 : 0);
1685     if (OffsetValue) {
1686       bool IsOffsetZero = false;
1687       if (ConstantInt *CI = dyn_cast<ConstantInt>(OffsetValue))
1688         IsOffsetZero = CI->isZero();
1689
1690       if (!IsOffsetZero) {
1691         if (OffsetValue->getType() != IntPtrTy)
1692           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
1693                                       "offsetcast");
1694         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
1695       }
1696     }
1697
1698     Value *Zero = ConstantInt::get(IntPtrTy, 0);
1699     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
1700     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
1701
1702     return CreateAssumption(InvCond);
1703   }
1704 };
1705
1706 // Create wrappers for C Binding types (see CBindingWrapping.h).
1707 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
1708
1709 }
1710
1711 #endif