1 //===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the IRBuilder class, which is used as a convenient way
10 // to create LLVM instructions with a consistent and simplified interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_IR_IRBUILDER_H
15 #define LLVM_IR_IRBUILDER_H
16 
17 #include "llvm-c/Types.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/ConstantFolder.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/InstrTypes.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/AtomicOrdering.h"
42 #include "llvm/Support/CBindingWrapping.h"
43 #include "llvm/Support/Casting.h"
44 #include <cassert>
45 #include <cstddef>
46 #include <cstdint>
47 #include <functional>
48 #include <utility>
49 
50 namespace llvm {
51 
52 class APInt;
53 class MDNode;
54 class Use;
55 
56 /// This provides the default implementation of the IRBuilder
57 /// 'InsertHelper' method that is called whenever an instruction is created by
58 /// IRBuilder and needs to be inserted.
59 ///
60 /// By default, this inserts the instruction at the insertion point.
61 class IRBuilderDefaultInserter {
62 protected:
63   void InsertHelper(Instruction *I, const Twine &Name,
64                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
65     if (BB) BB->getInstList().insert(InsertPt, I);
66     I->setName(Name);
67   }
68 };
69 
70 /// Provides an 'InsertHelper' that calls a user-provided callback after
71 /// performing the default insertion.
72 class IRBuilderCallbackInserter : IRBuilderDefaultInserter {
73   std::function<void(Instruction *)> Callback;
74 
75 public:
76   IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
77       : Callback(std::move(Callback)) {}
78 
79 protected:
80   void InsertHelper(Instruction *I, const Twine &Name,
81                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
82     IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
83     Callback(I);
84   }
85 };
86 
87 /// Common base class shared among various IRBuilders.
88 class IRBuilderBase {
89   DebugLoc CurDbgLocation;
90 
91 protected:
92   BasicBlock *BB;
93   BasicBlock::iterator InsertPt;
94   LLVMContext &Context;
95 
96   MDNode *DefaultFPMathTag;
97   FastMathFlags FMF;
98 
99   bool IsFPConstrained;
100   fp::ExceptionBehavior DefaultConstrainedExcept;
101   fp::RoundingMode DefaultConstrainedRounding;
102 
103   ArrayRef<OperandBundleDef> DefaultOperandBundles;
104 
105 public:
106   IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr,
107                 ArrayRef<OperandBundleDef> OpBundles = None)
108       : Context(context), DefaultFPMathTag(FPMathTag), IsFPConstrained(false),
109         DefaultConstrainedExcept(fp::ebStrict),
110         DefaultConstrainedRounding(fp::rmDynamic),
111         DefaultOperandBundles(OpBundles) {
112     ClearInsertionPoint();
113   }
114 
115   //===--------------------------------------------------------------------===//
116   // Builder configuration methods
117   //===--------------------------------------------------------------------===//
118 
119   /// Clear the insertion point: created instructions will not be
120   /// inserted into a block.
121   void ClearInsertionPoint() {
122     BB = nullptr;
123     InsertPt = BasicBlock::iterator();
124   }
125 
126   BasicBlock *GetInsertBlock() const { return BB; }
127   BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
128   LLVMContext &getContext() const { return Context; }
129 
130   /// This specifies that created instructions should be appended to the
131   /// end of the specified block.
132   void SetInsertPoint(BasicBlock *TheBB) {
133     BB = TheBB;
134     InsertPt = BB->end();
135   }
136 
137   /// This specifies that created instructions should be inserted before
138   /// the specified instruction.
139   void SetInsertPoint(Instruction *I) {
140     BB = I->getParent();
141     InsertPt = I->getIterator();
142     assert(InsertPt != BB->end() && "Can't read debug loc from end()");
143     SetCurrentDebugLocation(I->getDebugLoc());
144   }
145 
146   /// This specifies that created instructions should be inserted at the
147   /// specified point.
148   void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
149     BB = TheBB;
150     InsertPt = IP;
151     if (IP != TheBB->end())
152       SetCurrentDebugLocation(IP->getDebugLoc());
153   }
154 
155   /// Set location information used by debugging information.
156   void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
157 
158   /// Get location information used by debugging information.
159   const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
160 
161   /// If this builder has a current debug location, set it on the
162   /// specified instruction.
163   void SetInstDebugLocation(Instruction *I) const {
164     if (CurDbgLocation)
165       I->setDebugLoc(CurDbgLocation);
166   }
167 
168   /// Get the return type of the current function that we're emitting
169   /// into.
170   Type *getCurrentFunctionReturnType() const;
171 
172   /// InsertPoint - A saved insertion point.
173   class InsertPoint {
174     BasicBlock *Block = nullptr;
175     BasicBlock::iterator Point;
176 
177   public:
178     /// Creates a new insertion point which doesn't point to anything.
179     InsertPoint() = default;
180 
181     /// Creates a new insertion point at the given location.
182     InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
183         : Block(InsertBlock), Point(InsertPoint) {}
184 
185     /// Returns true if this insert point is set.
186     bool isSet() const { return (Block != nullptr); }
187 
188     BasicBlock *getBlock() const { return Block; }
189     BasicBlock::iterator getPoint() const { return Point; }
190   };
191 
192   /// Returns the current insert point.
193   InsertPoint saveIP() const {
194     return InsertPoint(GetInsertBlock(), GetInsertPoint());
195   }
196 
197   /// Returns the current insert point, clearing it in the process.
198   InsertPoint saveAndClearIP() {
199     InsertPoint IP(GetInsertBlock(), GetInsertPoint());
200     ClearInsertionPoint();
201     return IP;
202   }
203 
204   /// Sets the current insert point to a previously-saved location.
205   void restoreIP(InsertPoint IP) {
206     if (IP.isSet())
207       SetInsertPoint(IP.getBlock(), IP.getPoint());
208     else
209       ClearInsertionPoint();
210   }
211 
212   /// Get the floating point math metadata being used.
213   MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
214 
215   /// Get the flags to be applied to created floating point ops
216   FastMathFlags getFastMathFlags() const { return FMF; }
217 
218   /// Clear the fast-math flags.
219   void clearFastMathFlags() { FMF.clear(); }
220 
221   /// Set the floating point math metadata to be used.
222   void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
223 
224   /// Set the fast-math flags to be used with generated fp-math operators
225   void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
226 
227   /// Enable/Disable use of constrained floating point math. When
228   /// enabled the CreateF<op>() calls instead create constrained
229   /// floating point intrinsic calls. Fast math flags are unaffected
230   /// by this setting.
231   void setIsFPConstrained(bool IsCon) { IsFPConstrained = IsCon; }
232 
233   /// Query for the use of constrained floating point math
234   bool getIsFPConstrained() { return IsFPConstrained; }
235 
236   /// Set the exception handling to be used with constrained floating point
237   void setDefaultConstrainedExcept(fp::ExceptionBehavior NewExcept) {
238     DefaultConstrainedExcept = NewExcept;
239   }
240 
241   /// Set the rounding mode handling to be used with constrained floating point
242   void setDefaultConstrainedRounding(fp::RoundingMode NewRounding) {
243     DefaultConstrainedRounding = NewRounding;
244   }
245 
246   /// Get the exception handling used with constrained floating point
247   fp::ExceptionBehavior getDefaultConstrainedExcept() {
248     return DefaultConstrainedExcept;
249   }
250 
251   /// Get the rounding mode handling used with constrained floating point
252   fp::RoundingMode getDefaultConstrainedRounding() {
253     return DefaultConstrainedRounding;
254   }
255 
256   void setConstrainedFPFunctionAttr() {
257     assert(BB && "Must have a basic block to set any function attributes!");
258 
259     Function *F = BB->getParent();
260     if (!F->hasFnAttribute(Attribute::StrictFP)) {
261       F->addFnAttr(Attribute::StrictFP);
262     }
263   }
264 
265   void setConstrainedFPCallAttr(CallInst *I) {
266     if (!I->hasFnAttr(Attribute::StrictFP))
267       I->addAttribute(AttributeList::FunctionIndex, Attribute::StrictFP);
268   }
269 
270   //===--------------------------------------------------------------------===//
271   // RAII helpers.
272   //===--------------------------------------------------------------------===//
273 
274   // RAII object that stores the current insertion point and restores it
275   // when the object is destroyed. This includes the debug location.
276   class InsertPointGuard {
277     IRBuilderBase &Builder;
278     AssertingVH<BasicBlock> Block;
279     BasicBlock::iterator Point;
280     DebugLoc DbgLoc;
281 
282   public:
283     InsertPointGuard(IRBuilderBase &B)
284         : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
285           DbgLoc(B.getCurrentDebugLocation()) {}
286 
287     InsertPointGuard(const InsertPointGuard &) = delete;
288     InsertPointGuard &operator=(const InsertPointGuard &) = delete;
289 
290     ~InsertPointGuard() {
291       Builder.restoreIP(InsertPoint(Block, Point));
292       Builder.SetCurrentDebugLocation(DbgLoc);
293     }
294   };
295 
296   // RAII object that stores the current fast math settings and restores
297   // them when the object is destroyed.
298   class FastMathFlagGuard {
299     IRBuilderBase &Builder;
300     FastMathFlags FMF;
301     MDNode *FPMathTag;
302 
303   public:
304     FastMathFlagGuard(IRBuilderBase &B)
305         : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
306 
307     FastMathFlagGuard(const FastMathFlagGuard &) = delete;
308     FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
309 
310     ~FastMathFlagGuard() {
311       Builder.FMF = FMF;
312       Builder.DefaultFPMathTag = FPMathTag;
313     }
314   };
315 
316   //===--------------------------------------------------------------------===//
317   // Miscellaneous creation methods.
318   //===--------------------------------------------------------------------===//
319 
320   /// Make a new global variable with initializer type i8*
321   ///
322   /// Make a new global variable with an initializer that has array of i8 type
323   /// filled in with the null terminated string value specified.  The new global
324   /// variable will be marked mergable with any others of the same contents.  If
325   /// Name is specified, it is the name of the global variable created.
326   GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
327                                      unsigned AddressSpace = 0);
328 
329   /// Get a constant value representing either true or false.
330   ConstantInt *getInt1(bool V) {
331     return ConstantInt::get(getInt1Ty(), V);
332   }
333 
334   /// Get the constant value for i1 true.
335   ConstantInt *getTrue() {
336     return ConstantInt::getTrue(Context);
337   }
338 
339   /// Get the constant value for i1 false.
340   ConstantInt *getFalse() {
341     return ConstantInt::getFalse(Context);
342   }
343 
344   /// Get a constant 8-bit value.
345   ConstantInt *getInt8(uint8_t C) {
346     return ConstantInt::get(getInt8Ty(), C);
347   }
348 
349   /// Get a constant 16-bit value.
350   ConstantInt *getInt16(uint16_t C) {
351     return ConstantInt::get(getInt16Ty(), C);
352   }
353 
354   /// Get a constant 32-bit value.
355   ConstantInt *getInt32(uint32_t C) {
356     return ConstantInt::get(getInt32Ty(), C);
357   }
358 
359   /// Get a constant 64-bit value.
360   ConstantInt *getInt64(uint64_t C) {
361     return ConstantInt::get(getInt64Ty(), C);
362   }
363 
364   /// Get a constant N-bit value, zero extended or truncated from
365   /// a 64-bit value.
366   ConstantInt *getIntN(unsigned N, uint64_t C) {
367     return ConstantInt::get(getIntNTy(N), C);
368   }
369 
370   /// Get a constant integer value.
371   ConstantInt *getInt(const APInt &AI) {
372     return ConstantInt::get(Context, AI);
373   }
374 
375   //===--------------------------------------------------------------------===//
376   // Type creation methods
377   //===--------------------------------------------------------------------===//
378 
379   /// Fetch the type representing a single bit
380   IntegerType *getInt1Ty() {
381     return Type::getInt1Ty(Context);
382   }
383 
384   /// Fetch the type representing an 8-bit integer.
385   IntegerType *getInt8Ty() {
386     return Type::getInt8Ty(Context);
387   }
388 
389   /// Fetch the type representing a 16-bit integer.
390   IntegerType *getInt16Ty() {
391     return Type::getInt16Ty(Context);
392   }
393 
394   /// Fetch the type representing a 32-bit integer.
395   IntegerType *getInt32Ty() {
396     return Type::getInt32Ty(Context);
397   }
398 
399   /// Fetch the type representing a 64-bit integer.
400   IntegerType *getInt64Ty() {
401     return Type::getInt64Ty(Context);
402   }
403 
404   /// Fetch the type representing a 128-bit integer.
405   IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
406 
407   /// Fetch the type representing an N-bit integer.
408   IntegerType *getIntNTy(unsigned N) {
409     return Type::getIntNTy(Context, N);
410   }
411 
412   /// Fetch the type representing a 16-bit floating point value.
413   Type *getHalfTy() {
414     return Type::getHalfTy(Context);
415   }
416 
417   /// Fetch the type representing a 32-bit floating point value.
418   Type *getFloatTy() {
419     return Type::getFloatTy(Context);
420   }
421 
422   /// Fetch the type representing a 64-bit floating point value.
423   Type *getDoubleTy() {
424     return Type::getDoubleTy(Context);
425   }
426 
427   /// Fetch the type representing void.
428   Type *getVoidTy() {
429     return Type::getVoidTy(Context);
430   }
431 
432   /// Fetch the type representing a pointer to an 8-bit integer value.
433   PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
434     return Type::getInt8PtrTy(Context, AddrSpace);
435   }
436 
437   /// Fetch the type representing a pointer to an integer value.
438   IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
439     return DL.getIntPtrType(Context, AddrSpace);
440   }
441 
442   //===--------------------------------------------------------------------===//
443   // Intrinsic creation methods
444   //===--------------------------------------------------------------------===//
445 
446   /// Create and insert a memset to the specified pointer and the
447   /// specified value.
448   ///
449   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
450   /// specified, it will be added to the instruction. Likewise with alias.scope
451   /// and noalias tags.
452   CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size,
453                          MaybeAlign Align, bool isVolatile = false,
454                          MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr,
455                          MDNode *NoAliasTag = nullptr) {
456     return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
457                         TBAATag, ScopeTag, NoAliasTag);
458   }
459 
460   CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, MaybeAlign Align,
461                          bool isVolatile = false, MDNode *TBAATag = nullptr,
462                          MDNode *ScopeTag = nullptr,
463                          MDNode *NoAliasTag = nullptr);
464 
465   /// Create and insert an element unordered-atomic memset of the region of
466   /// memory starting at the given pointer to the given value.
467   ///
468   /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
469   /// specified, it will be added to the instruction. Likewise with alias.scope
470   /// and noalias tags.
471   /// FIXME: Remove this function once transition to Align is over.
472   /// Use the version that takes Align instead of this one.
473   LLVM_ATTRIBUTE_DEPRECATED(
474       CallInst *CreateElementUnorderedAtomicMemSet(
475           Value *Ptr, Value *Val, uint64_t Size, unsigned Alignment,
476           uint32_t ElementSize, MDNode *TBAATag = nullptr,
477           MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr),
478       "Use the version that takes Align instead of this one") {
479     return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size),
480                                               Align(Alignment), ElementSize,
481                                               TBAATag, ScopeTag, NoAliasTag);
482   }
483 
484   CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
485                                                uint64_t Size, Align Alignment,
486                                                uint32_t ElementSize,
487                                                MDNode *TBAATag = nullptr,
488                                                MDNode *ScopeTag = nullptr,
489                                                MDNode *NoAliasTag = nullptr) {
490     return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size),
491                                               Align(Alignment), ElementSize,
492                                               TBAATag, ScopeTag, NoAliasTag);
493   }
494 
495   /// FIXME: Remove this function once transition to Align is over.
496   /// Use the version that takes Align instead of this one.
497   LLVM_ATTRIBUTE_DEPRECATED(
498       CallInst *CreateElementUnorderedAtomicMemSet(
499           Value *Ptr, Value *Val, Value *Size, unsigned Alignment,
500           uint32_t ElementSize, MDNode *TBAATag = nullptr,
501           MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr),
502       "Use the version that takes Align instead of this one") {
503     return CreateElementUnorderedAtomicMemSet(Ptr, Val, Size, Align(Alignment),
504                                               ElementSize, TBAATag, ScopeTag,
505                                               NoAliasTag);
506   }
507 
508   CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
509                                                Value *Size, Align Alignment,
510                                                uint32_t ElementSize,
511                                                MDNode *TBAATag = nullptr,
512                                                MDNode *ScopeTag = nullptr,
513                                                MDNode *NoAliasTag = nullptr);
514 
515   /// Create and insert a memcpy between the specified pointers.
516   ///
517   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
518   /// specified, it will be added to the instruction. Likewise with alias.scope
519   /// and noalias tags.
520   /// FIXME: Remove this function once transition to Align is over.
521   /// Use the version that takes MaybeAlign instead of this one.
522   LLVM_ATTRIBUTE_DEPRECATED(
523       CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,
524                              unsigned SrcAlign, uint64_t Size,
525                              bool isVolatile = false, MDNode *TBAATag = nullptr,
526                              MDNode *TBAAStructTag = nullptr,
527                              MDNode *ScopeTag = nullptr,
528                              MDNode *NoAliasTag = nullptr),
529       "Use the version that takes MaybeAlign instead") {
530     return CreateMemCpy(Dst, MaybeAlign(DstAlign), Src, MaybeAlign(SrcAlign),
531                         getInt64(Size), isVolatile, TBAATag, TBAAStructTag,
532                         ScopeTag, NoAliasTag);
533   }
534 
535   CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
536                          MaybeAlign SrcAlign, uint64_t Size,
537                          bool isVolatile = false, MDNode *TBAATag = nullptr,
538                          MDNode *TBAAStructTag = nullptr,
539                          MDNode *ScopeTag = nullptr,
540                          MDNode *NoAliasTag = nullptr) {
541     return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
542                         isVolatile, TBAATag, TBAAStructTag, ScopeTag,
543                         NoAliasTag);
544   }
545 
546   /// FIXME: Remove this function once transition to Align is over.
547   /// Use the version that takes MaybeAlign instead of this one.
548   LLVM_ATTRIBUTE_DEPRECATED(
549       CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,
550                              unsigned SrcAlign, Value *Size,
551                              bool isVolatile = false, MDNode *TBAATag = nullptr,
552                              MDNode *TBAAStructTag = nullptr,
553                              MDNode *ScopeTag = nullptr,
554                              MDNode *NoAliasTag = nullptr),
555       "Use the version that takes MaybeAlign instead");
556   CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
557                          MaybeAlign SrcAlign, Value *Size,
558                          bool isVolatile = false, MDNode *TBAATag = nullptr,
559                          MDNode *TBAAStructTag = nullptr,
560                          MDNode *ScopeTag = nullptr,
561                          MDNode *NoAliasTag = nullptr);
562 
563   /// Create and insert an element unordered-atomic memcpy between the
564   /// specified pointers.
565   ///
566   /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, respectively.
567   ///
568   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
569   /// specified, it will be added to the instruction. Likewise with alias.scope
570   /// and noalias tags.
571   CallInst *CreateElementUnorderedAtomicMemCpy(
572       Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
573       uint64_t Size, uint32_t ElementSize, MDNode *TBAATag = nullptr,
574       MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
575       MDNode *NoAliasTag = nullptr) {
576     return CreateElementUnorderedAtomicMemCpy(
577         Dst, DstAlign, Src, SrcAlign, getInt64(Size), ElementSize, TBAATag,
578         TBAAStructTag, ScopeTag, NoAliasTag);
579   }
580 
581   CallInst *CreateElementUnorderedAtomicMemCpy(
582       Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size,
583       uint32_t ElementSize, MDNode *TBAATag = nullptr,
584       MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
585       MDNode *NoAliasTag = nullptr);
586 
587   /// Create and insert a memmove between the specified
588   /// pointers.
589   ///
590   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
591   /// specified, it will be added to the instruction. Likewise with alias.scope
592   /// and noalias tags.
593   /// FIXME: Remove this function once transition to Align is over.
594   /// Use the version that takes MaybeAlign instead of this one.
595   LLVM_ATTRIBUTE_DEPRECATED(
596       CallInst *CreateMemMove(
597           Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
598           uint64_t Size, bool isVolatile = false, MDNode *TBAATag = nullptr,
599           MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr),
600       "Use the version that takes MaybeAlign") {
601     return CreateMemMove(Dst, MaybeAlign(DstAlign), Src, MaybeAlign(SrcAlign),
602                          getInt64(Size), isVolatile, TBAATag, ScopeTag,
603                          NoAliasTag);
604   }
605   CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
606                           MaybeAlign SrcAlign, uint64_t Size,
607                           bool isVolatile = false, MDNode *TBAATag = nullptr,
608                           MDNode *ScopeTag = nullptr,
609                           MDNode *NoAliasTag = nullptr) {
610     return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
611                          isVolatile, TBAATag, ScopeTag, NoAliasTag);
612   }
613   /// FIXME: Remove this function once transition to Align is over.
614   /// Use the version that takes MaybeAlign instead of this one.
615   LLVM_ATTRIBUTE_DEPRECATED(
616       CallInst *CreateMemMove(
617           Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
618           Value *Size, bool isVolatile = false, MDNode *TBAATag = nullptr,
619           MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr),
620       "Use the version that takes MaybeAlign") {
621     return CreateMemMove(Dst, MaybeAlign(DstAlign), Src, MaybeAlign(SrcAlign),
622                          Size, isVolatile, TBAATag, ScopeTag, NoAliasTag);
623   }
624   CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
625                           MaybeAlign SrcAlign, Value *Size,
626                           bool isVolatile = false, MDNode *TBAATag = nullptr,
627                           MDNode *ScopeTag = nullptr,
628                           MDNode *NoAliasTag = nullptr);
629 
630   /// \brief Create and insert an element unordered-atomic memmove between the
631   /// specified pointers.
632   ///
633   /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers,
634   /// respectively.
635   ///
636   /// If the pointers aren't i8*, they will be converted.  If a TBAA tag is
637   /// specified, it will be added to the instruction. Likewise with alias.scope
638   /// and noalias tags.
639   CallInst *CreateElementUnorderedAtomicMemMove(
640       Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
641       uint64_t Size, uint32_t ElementSize, MDNode *TBAATag = nullptr,
642       MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
643       MDNode *NoAliasTag = nullptr) {
644     return CreateElementUnorderedAtomicMemMove(
645         Dst, DstAlign, Src, SrcAlign, getInt64(Size), ElementSize, TBAATag,
646         TBAAStructTag, ScopeTag, NoAliasTag);
647   }
648 
649   CallInst *CreateElementUnorderedAtomicMemMove(
650       Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size,
651       uint32_t ElementSize, MDNode *TBAATag = nullptr,
652       MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
653       MDNode *NoAliasTag = nullptr);
654 
655   /// Create a vector fadd reduction intrinsic of the source vector.
656   /// The first parameter is a scalar accumulator value for ordered reductions.
657   CallInst *CreateFAddReduce(Value *Acc, Value *Src);
658 
659   /// Create a vector fmul reduction intrinsic of the source vector.
660   /// The first parameter is a scalar accumulator value for ordered reductions.
661   CallInst *CreateFMulReduce(Value *Acc, Value *Src);
662 
663   /// Create a vector int add reduction intrinsic of the source vector.
664   CallInst *CreateAddReduce(Value *Src);
665 
666   /// Create a vector int mul reduction intrinsic of the source vector.
667   CallInst *CreateMulReduce(Value *Src);
668 
669   /// Create a vector int AND reduction intrinsic of the source vector.
670   CallInst *CreateAndReduce(Value *Src);
671 
672   /// Create a vector int OR reduction intrinsic of the source vector.
673   CallInst *CreateOrReduce(Value *Src);
674 
675   /// Create a vector int XOR reduction intrinsic of the source vector.
676   CallInst *CreateXorReduce(Value *Src);
677 
678   /// Create a vector integer max reduction intrinsic of the source
679   /// vector.
680   CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
681 
682   /// Create a vector integer min reduction intrinsic of the source
683   /// vector.
684   CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
685 
686   /// Create a vector float max reduction intrinsic of the source
687   /// vector.
688   CallInst *CreateFPMaxReduce(Value *Src, bool NoNaN = false);
689 
690   /// Create a vector float min reduction intrinsic of the source
691   /// vector.
692   CallInst *CreateFPMinReduce(Value *Src, bool NoNaN = false);
693 
694   /// Create a lifetime.start intrinsic.
695   ///
696   /// If the pointer isn't i8* it will be converted.
697   CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
698 
699   /// Create a lifetime.end intrinsic.
700   ///
701   /// If the pointer isn't i8* it will be converted.
702   CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
703 
704   /// Create a call to invariant.start intrinsic.
705   ///
706   /// If the pointer isn't i8* it will be converted.
707   CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
708 
709   /// Create a call to Masked Load intrinsic
710   CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
711                              Value *PassThru = nullptr, const Twine &Name = "");
712 
713   /// Create a call to Masked Store intrinsic
714   CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
715                               Value *Mask);
716 
717   /// Create a call to Masked Gather intrinsic
718   CallInst *CreateMaskedGather(Value *Ptrs, unsigned Align,
719                                Value *Mask = nullptr,
720                                Value *PassThru = nullptr,
721                                const Twine& Name = "");
722 
723   /// Create a call to Masked Scatter intrinsic
724   CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Align,
725                                 Value *Mask = nullptr);
726 
727   /// Create an assume intrinsic call that allows the optimizer to
728   /// assume that the provided condition will be true.
729   CallInst *CreateAssumption(Value *Cond);
730 
731   /// Create a call to the experimental.gc.statepoint intrinsic to
732   /// start a new statepoint sequence.
733   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
734                                    Value *ActualCallee,
735                                    ArrayRef<Value *> CallArgs,
736                                    ArrayRef<Value *> DeoptArgs,
737                                    ArrayRef<Value *> GCArgs,
738                                    const Twine &Name = "");
739 
740   /// Create a call to the experimental.gc.statepoint intrinsic to
741   /// start a new statepoint sequence.
742   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
743                                    Value *ActualCallee, uint32_t Flags,
744                                    ArrayRef<Use> CallArgs,
745                                    ArrayRef<Use> TransitionArgs,
746                                    ArrayRef<Use> DeoptArgs,
747                                    ArrayRef<Value *> GCArgs,
748                                    const Twine &Name = "");
749 
750   /// Conveninence function for the common case when CallArgs are filled
751   /// in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
752   /// .get()'ed to get the Value pointer.
753   CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
754                                    Value *ActualCallee, ArrayRef<Use> CallArgs,
755                                    ArrayRef<Value *> DeoptArgs,
756                                    ArrayRef<Value *> GCArgs,
757                                    const Twine &Name = "");
758 
759   /// Create an invoke to the experimental.gc.statepoint intrinsic to
760   /// start a new statepoint sequence.
761   InvokeInst *
762   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
763                            Value *ActualInvokee, BasicBlock *NormalDest,
764                            BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
765                            ArrayRef<Value *> DeoptArgs,
766                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
767 
768   /// Create an invoke to the experimental.gc.statepoint intrinsic to
769   /// start a new statepoint sequence.
770   InvokeInst *CreateGCStatepointInvoke(
771       uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
772       BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
773       ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
774       ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
775       const Twine &Name = "");
776 
777   // Convenience function for the common case when CallArgs are filled in using
778   // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
779   // get the Value *.
780   InvokeInst *
781   CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
782                            Value *ActualInvokee, BasicBlock *NormalDest,
783                            BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
784                            ArrayRef<Value *> DeoptArgs,
785                            ArrayRef<Value *> GCArgs, const Twine &Name = "");
786 
787   /// Create a call to the experimental.gc.result intrinsic to extract
788   /// the result from a call wrapped in a statepoint.
789   CallInst *CreateGCResult(Instruction *Statepoint,
790                            Type *ResultType,
791                            const Twine &Name = "");
792 
793   /// Create a call to the experimental.gc.relocate intrinsics to
794   /// project the relocated value of one pointer from the statepoint.
795   CallInst *CreateGCRelocate(Instruction *Statepoint,
796                              int BaseOffset,
797                              int DerivedOffset,
798                              Type *ResultType,
799                              const Twine &Name = "");
800 
801   /// Create a call to intrinsic \p ID with 1 operand which is mangled on its
802   /// type.
803   CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
804                                  Instruction *FMFSource = nullptr,
805                                  const Twine &Name = "");
806 
807   /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
808   /// first type.
809   CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS,
810                                   Instruction *FMFSource = nullptr,
811                                   const Twine &Name = "");
812 
813   /// Create a call to intrinsic \p ID with \p args, mangled using \p Types. If
814   /// \p FMFSource is provided, copy fast-math-flags from that instruction to
815   /// the intrinsic.
816   CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types,
817                             ArrayRef<Value *> Args,
818                             Instruction *FMFSource = nullptr,
819                             const Twine &Name = "");
820 
821   /// Create call to the minnum intrinsic.
822   CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
823     return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
824   }
825 
826   /// Create call to the maxnum intrinsic.
827   CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
828     return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
829   }
830 
831   /// Create call to the minimum intrinsic.
832   CallInst *CreateMinimum(Value *LHS, Value *RHS, const Twine &Name = "") {
833     return CreateBinaryIntrinsic(Intrinsic::minimum, LHS, RHS, nullptr, Name);
834   }
835 
836   /// Create call to the maximum intrinsic.
837   CallInst *CreateMaximum(Value *LHS, Value *RHS, const Twine &Name = "") {
838     return CreateBinaryIntrinsic(Intrinsic::maximum, LHS, RHS, nullptr, Name);
839   }
840 
841 private:
842   /// Create a call to a masked intrinsic with given Id.
843   CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
844                                   ArrayRef<Type *> OverloadedTypes,
845                                   const Twine &Name = "");
846 
847   Value *getCastedInt8PtrValue(Value *Ptr);
848 };
849 
850 /// This provides a uniform API for creating instructions and inserting
851 /// them into a basic block: either at the end of a BasicBlock, or at a specific
852 /// iterator location in a block.
853 ///
854 /// Note that the builder does not expose the full generality of LLVM
855 /// instructions.  For access to extra instruction properties, use the mutators
856 /// (e.g. setVolatile) on the instructions after they have been
857 /// created. Convenience state exists to specify fast-math flags and fp-math
858 /// tags.
859 ///
860 /// The first template argument specifies a class to use for creating constants.
861 /// This defaults to creating minimally folded constants.  The second template
862 /// argument allows clients to specify custom insertion hooks that are called on
863 /// every newly created insertion.
864 template <typename T = ConstantFolder,
865           typename Inserter = IRBuilderDefaultInserter>
866 class IRBuilder : public IRBuilderBase, public Inserter {
867   T Folder;
868 
869 public:
870   IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
871             MDNode *FPMathTag = nullptr,
872             ArrayRef<OperandBundleDef> OpBundles = None)
873       : IRBuilderBase(C, FPMathTag, OpBundles), Inserter(std::move(I)),
874         Folder(F) {}
875 
876   explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
877                      ArrayRef<OperandBundleDef> OpBundles = None)
878       : IRBuilderBase(C, FPMathTag, OpBundles) {}
879 
880   explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr,
881                      ArrayRef<OperandBundleDef> OpBundles = None)
882       : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
883     SetInsertPoint(TheBB);
884   }
885 
886   explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
887                      ArrayRef<OperandBundleDef> OpBundles = None)
888       : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles) {
889     SetInsertPoint(TheBB);
890   }
891 
892   explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
893                      ArrayRef<OperandBundleDef> OpBundles = None)
894       : IRBuilderBase(IP->getContext(), FPMathTag, OpBundles) {
895     SetInsertPoint(IP);
896   }
897 
898   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T &F,
899             MDNode *FPMathTag = nullptr,
900             ArrayRef<OperandBundleDef> OpBundles = None)
901       : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
902     SetInsertPoint(TheBB, IP);
903   }
904 
905   IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
906             MDNode *FPMathTag = nullptr,
907             ArrayRef<OperandBundleDef> OpBundles = None)
908       : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles) {
909     SetInsertPoint(TheBB, IP);
910   }
911 
912   /// Get the constant folder being used.
913   const T &getFolder() { return Folder; }
914 
915   /// Insert and return the specified instruction.
916   template<typename InstTy>
917   InstTy *Insert(InstTy *I, const Twine &Name = "") const {
918     this->InsertHelper(I, Name, BB, InsertPt);
919     this->SetInstDebugLocation(I);
920     return I;
921   }
922 
923   /// No-op overload to handle constants.
924   Constant *Insert(Constant *C, const Twine& = "") const {
925     return C;
926   }
927 
928   //===--------------------------------------------------------------------===//
929   // Instruction creation methods: Terminators
930   //===--------------------------------------------------------------------===//
931 
932 private:
933   /// Helper to add branch weight and unpredictable metadata onto an
934   /// instruction.
935   /// \returns The annotated instruction.
936   template <typename InstTy>
937   InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
938     if (Weights)
939       I->setMetadata(LLVMContext::MD_prof, Weights);
940     if (Unpredictable)
941       I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
942     return I;
943   }
944 
945 public:
946   /// Create a 'ret void' instruction.
947   ReturnInst *CreateRetVoid() {
948     return Insert(ReturnInst::Create(Context));
949   }
950 
951   /// Create a 'ret <val>' instruction.
952   ReturnInst *CreateRet(Value *V) {
953     return Insert(ReturnInst::Create(Context, V));
954   }
955 
956   /// Create a sequence of N insertvalue instructions,
957   /// with one Value from the retVals array each, that build a aggregate
958   /// return value one value at a time, and a ret instruction to return
959   /// the resulting aggregate value.
960   ///
961   /// This is a convenience function for code that uses aggregate return values
962   /// as a vehicle for having multiple return values.
963   ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
964     Value *V = UndefValue::get(getCurrentFunctionReturnType());
965     for (unsigned i = 0; i != N; ++i)
966       V = CreateInsertValue(V, retVals[i], i, "mrv");
967     return Insert(ReturnInst::Create(Context, V));
968   }
969 
970   /// Create an unconditional 'br label X' instruction.
971   BranchInst *CreateBr(BasicBlock *Dest) {
972     return Insert(BranchInst::Create(Dest));
973   }
974 
975   /// Create a conditional 'br Cond, TrueDest, FalseDest'
976   /// instruction.
977   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
978                            MDNode *BranchWeights = nullptr,
979                            MDNode *Unpredictable = nullptr) {
980     return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
981                                     BranchWeights, Unpredictable));
982   }
983 
984   /// Create a conditional 'br Cond, TrueDest, FalseDest'
985   /// instruction. Copy branch meta data if available.
986   BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
987                            Instruction *MDSrc) {
988     BranchInst *Br = BranchInst::Create(True, False, Cond);
989     if (MDSrc) {
990       unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
991                         LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
992       Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
993     }
994     return Insert(Br);
995   }
996 
997   /// Create a switch instruction with the specified value, default dest,
998   /// and with a hint for the number of cases that will be added (for efficient
999   /// allocation).
1000   SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
1001                            MDNode *BranchWeights = nullptr,
1002                            MDNode *Unpredictable = nullptr) {
1003     return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
1004                                     BranchWeights, Unpredictable));
1005   }
1006 
1007   /// Create an indirect branch instruction with the specified address
1008   /// operand, with an optional hint for the number of destinations that will be
1009   /// added (for efficient allocation).
1010   IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
1011     return Insert(IndirectBrInst::Create(Addr, NumDests));
1012   }
1013 
1014   /// Create an invoke instruction.
1015   InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
1016                            BasicBlock *NormalDest, BasicBlock *UnwindDest,
1017                            ArrayRef<Value *> Args,
1018                            ArrayRef<OperandBundleDef> OpBundles,
1019                            const Twine &Name = "") {
1020     return Insert(
1021         InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, OpBundles),
1022         Name);
1023   }
1024   InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
1025                            BasicBlock *NormalDest, BasicBlock *UnwindDest,
1026                            ArrayRef<Value *> Args = None,
1027                            const Twine &Name = "") {
1028     return Insert(InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args),
1029                   Name);
1030   }
1031 
1032   InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
1033                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
1034                            ArrayRef<OperandBundleDef> OpBundles,
1035                            const Twine &Name = "") {
1036     return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
1037                         NormalDest, UnwindDest, Args, OpBundles, Name);
1038   }
1039 
1040   InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
1041                            BasicBlock *UnwindDest,
1042                            ArrayRef<Value *> Args = None,
1043                            const Twine &Name = "") {
1044     return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
1045                         NormalDest, UnwindDest, Args, Name);
1046   }
1047 
1048   // Deprecated [opaque pointer types]
1049   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
1050                            BasicBlock *UnwindDest, ArrayRef<Value *> Args,
1051                            ArrayRef<OperandBundleDef> OpBundles,
1052                            const Twine &Name = "") {
1053     return CreateInvoke(
1054         cast<FunctionType>(
1055             cast<PointerType>(Callee->getType())->getElementType()),
1056         Callee, NormalDest, UnwindDest, Args, OpBundles, Name);
1057   }
1058 
1059   // Deprecated [opaque pointer types]
1060   InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
1061                            BasicBlock *UnwindDest,
1062                            ArrayRef<Value *> Args = None,
1063                            const Twine &Name = "") {
1064     return CreateInvoke(
1065         cast<FunctionType>(
1066             cast<PointerType>(Callee->getType())->getElementType()),
1067         Callee, NormalDest, UnwindDest, Args, Name);
1068   }
1069 
1070   /// \brief Create a callbr instruction.
1071   CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
1072                            BasicBlock *DefaultDest,
1073                            ArrayRef<BasicBlock *> IndirectDests,
1074                            ArrayRef<Value *> Args = None,
1075                            const Twine &Name = "") {
1076     return Insert(CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests,
1077                                      Args), Name);
1078   }
1079   CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
1080                            BasicBlock *DefaultDest,
1081                            ArrayRef<BasicBlock *> IndirectDests,
1082                            ArrayRef<Value *> Args,
1083                            ArrayRef<OperandBundleDef> OpBundles,
1084                            const Twine &Name = "") {
1085     return Insert(
1086         CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
1087                            OpBundles), Name);
1088   }
1089 
1090   CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
1091                            ArrayRef<BasicBlock *> IndirectDests,
1092                            ArrayRef<Value *> Args = None,
1093                            const Twine &Name = "") {
1094     return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
1095                         DefaultDest, IndirectDests, Args, Name);
1096   }
1097   CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
1098                            ArrayRef<BasicBlock *> IndirectDests,
1099                            ArrayRef<Value *> Args,
1100                            ArrayRef<OperandBundleDef> OpBundles,
1101                            const Twine &Name = "") {
1102     return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
1103                         DefaultDest, IndirectDests, Args, Name);
1104   }
1105 
1106   ResumeInst *CreateResume(Value *Exn) {
1107     return Insert(ResumeInst::Create(Exn));
1108   }
1109 
1110   CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
1111                                       BasicBlock *UnwindBB = nullptr) {
1112     return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
1113   }
1114 
1115   CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
1116                                      unsigned NumHandlers,
1117                                      const Twine &Name = "") {
1118     return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
1119                   Name);
1120   }
1121 
1122   CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
1123                                const Twine &Name = "") {
1124     return Insert(CatchPadInst::Create(ParentPad, Args), Name);
1125   }
1126 
1127   CleanupPadInst *CreateCleanupPad(Value *ParentPad,
1128                                    ArrayRef<Value *> Args = None,
1129                                    const Twine &Name = "") {
1130     return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
1131   }
1132 
1133   CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
1134     return Insert(CatchReturnInst::Create(CatchPad, BB));
1135   }
1136 
1137   UnreachableInst *CreateUnreachable() {
1138     return Insert(new UnreachableInst(Context));
1139   }
1140 
1141   //===--------------------------------------------------------------------===//
1142   // Instruction creation methods: Binary Operators
1143   //===--------------------------------------------------------------------===//
1144 private:
1145   BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
1146                                           Value *LHS, Value *RHS,
1147                                           const Twine &Name,
1148                                           bool HasNUW, bool HasNSW) {
1149     BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
1150     if (HasNUW) BO->setHasNoUnsignedWrap();
1151     if (HasNSW) BO->setHasNoSignedWrap();
1152     return BO;
1153   }
1154 
1155   Instruction *setFPAttrs(Instruction *I, MDNode *FPMD,
1156                           FastMathFlags FMF) const {
1157     if (!FPMD)
1158       FPMD = DefaultFPMathTag;
1159     if (FPMD)
1160       I->setMetadata(LLVMContext::MD_fpmath, FPMD);
1161     I->setFastMathFlags(FMF);
1162     return I;
1163   }
1164 
1165   Value *foldConstant(Instruction::BinaryOps Opc, Value *L,
1166                       Value *R, const Twine &Name) const {
1167     auto *LC = dyn_cast<Constant>(L);
1168     auto *RC = dyn_cast<Constant>(R);
1169     return (LC && RC) ? Insert(Folder.CreateBinOp(Opc, LC, RC), Name) : nullptr;
1170   }
1171 
1172   Value *getConstrainedFPRounding(Optional<fp::RoundingMode> Rounding) {
1173     fp::RoundingMode UseRounding = DefaultConstrainedRounding;
1174 
1175     if (Rounding.hasValue())
1176       UseRounding = Rounding.getValue();
1177 
1178     Optional<StringRef> RoundingStr = RoundingModeToStr(UseRounding);
1179     assert(RoundingStr.hasValue() && "Garbage strict rounding mode!");
1180     auto *RoundingMDS = MDString::get(Context, RoundingStr.getValue());
1181 
1182     return MetadataAsValue::get(Context, RoundingMDS);
1183   }
1184 
1185   Value *getConstrainedFPExcept(Optional<fp::ExceptionBehavior> Except) {
1186     fp::ExceptionBehavior UseExcept = DefaultConstrainedExcept;
1187 
1188     if (Except.hasValue())
1189       UseExcept = Except.getValue();
1190 
1191     Optional<StringRef> ExceptStr = ExceptionBehaviorToStr(UseExcept);
1192     assert(ExceptStr.hasValue() && "Garbage strict exception behavior!");
1193     auto *ExceptMDS = MDString::get(Context, ExceptStr.getValue());
1194 
1195     return MetadataAsValue::get(Context, ExceptMDS);
1196   }
1197 
1198   Value *getConstrainedFPPredicate(CmpInst::Predicate Predicate) {
1199     assert(CmpInst::isFPPredicate(Predicate) &&
1200            Predicate != CmpInst::FCMP_FALSE &&
1201            Predicate != CmpInst::FCMP_TRUE &&
1202            "Invalid constrained FP comparison predicate!");
1203 
1204     StringRef PredicateStr = CmpInst::getPredicateName(Predicate);
1205     auto *PredicateMDS = MDString::get(Context, PredicateStr);
1206 
1207     return MetadataAsValue::get(Context, PredicateMDS);
1208   }
1209 
1210 public:
1211   Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
1212                    bool HasNUW = false, bool HasNSW = false) {
1213     if (auto *LC = dyn_cast<Constant>(LHS))
1214       if (auto *RC = dyn_cast<Constant>(RHS))
1215         return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
1216     return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
1217                                    HasNUW, HasNSW);
1218   }
1219 
1220   Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
1221     return CreateAdd(LHS, RHS, Name, false, true);
1222   }
1223 
1224   Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
1225     return CreateAdd(LHS, RHS, Name, true, false);
1226   }
1227 
1228   Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
1229                    bool HasNUW = false, bool HasNSW = false) {
1230     if (auto *LC = dyn_cast<Constant>(LHS))
1231       if (auto *RC = dyn_cast<Constant>(RHS))
1232         return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
1233     return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
1234                                    HasNUW, HasNSW);
1235   }
1236 
1237   Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1238     return CreateSub(LHS, RHS, Name, false, true);
1239   }
1240 
1241   Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1242     return CreateSub(LHS, RHS, Name, true, false);
1243   }
1244 
1245   Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
1246                    bool HasNUW = false, bool HasNSW = false) {
1247     if (auto *LC = dyn_cast<Constant>(LHS))
1248       if (auto *RC = dyn_cast<Constant>(RHS))
1249         return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
1250     return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
1251                                    HasNUW, HasNSW);
1252   }
1253 
1254   Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1255     return CreateMul(LHS, RHS, Name, false, true);
1256   }
1257 
1258   Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1259     return CreateMul(LHS, RHS, Name, true, false);
1260   }
1261 
1262   Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1263                     bool isExact = false) {
1264     if (auto *LC = dyn_cast<Constant>(LHS))
1265       if (auto *RC = dyn_cast<Constant>(RHS))
1266         return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
1267     if (!isExact)
1268       return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
1269     return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
1270   }
1271 
1272   Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1273     return CreateUDiv(LHS, RHS, Name, true);
1274   }
1275 
1276   Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1277                     bool isExact = false) {
1278     if (auto *LC = dyn_cast<Constant>(LHS))
1279       if (auto *RC = dyn_cast<Constant>(RHS))
1280         return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
1281     if (!isExact)
1282       return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
1283     return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
1284   }
1285 
1286   Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1287     return CreateSDiv(LHS, RHS, Name, true);
1288   }
1289 
1290   Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
1291     if (Value *V = foldConstant(Instruction::URem, LHS, RHS, Name)) return V;
1292     return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
1293   }
1294 
1295   Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
1296     if (Value *V = foldConstant(Instruction::SRem, LHS, RHS, Name)) return V;
1297     return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
1298   }
1299 
1300   Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
1301                    bool HasNUW = false, bool HasNSW = false) {
1302     if (auto *LC = dyn_cast<Constant>(LHS))
1303       if (auto *RC = dyn_cast<Constant>(RHS))
1304         return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
1305     return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
1306                                    HasNUW, HasNSW);
1307   }
1308 
1309   Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
1310                    bool HasNUW = false, bool HasNSW = false) {
1311     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1312                      HasNUW, HasNSW);
1313   }
1314 
1315   Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
1316                    bool HasNUW = false, bool HasNSW = false) {
1317     return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1318                      HasNUW, HasNSW);
1319   }
1320 
1321   Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
1322                     bool isExact = false) {
1323     if (auto *LC = dyn_cast<Constant>(LHS))
1324       if (auto *RC = dyn_cast<Constant>(RHS))
1325         return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
1326     if (!isExact)
1327       return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
1328     return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
1329   }
1330 
1331   Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1332                     bool isExact = false) {
1333     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1334   }
1335 
1336   Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1337                     bool isExact = false) {
1338     return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1339   }
1340 
1341   Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
1342                     bool isExact = false) {
1343     if (auto *LC = dyn_cast<Constant>(LHS))
1344       if (auto *RC = dyn_cast<Constant>(RHS))
1345         return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
1346     if (!isExact)
1347       return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
1348     return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
1349   }
1350 
1351   Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1352                     bool isExact = false) {
1353     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1354   }
1355 
1356   Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1357                     bool isExact = false) {
1358     return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1359   }
1360 
1361   Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
1362     if (auto *RC = dyn_cast<Constant>(RHS)) {
1363       if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isMinusOne())
1364         return LHS;  // LHS & -1 -> LHS
1365       if (auto *LC = dyn_cast<Constant>(LHS))
1366         return Insert(Folder.CreateAnd(LC, RC), Name);
1367     }
1368     return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
1369   }
1370 
1371   Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1372     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1373   }
1374 
1375   Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1376     return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1377   }
1378 
1379   Value *CreateAnd(ArrayRef<Value*> Ops) {
1380     assert(!Ops.empty());
1381     Value *Accum = Ops[0];
1382     for (unsigned i = 1; i < Ops.size(); i++)
1383       Accum = CreateAnd(Accum, Ops[i]);
1384     return Accum;
1385   }
1386 
1387   Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
1388     if (auto *RC = dyn_cast<Constant>(RHS)) {
1389       if (RC->isNullValue())
1390         return LHS;  // LHS | 0 -> LHS
1391       if (auto *LC = dyn_cast<Constant>(LHS))
1392         return Insert(Folder.CreateOr(LC, RC), Name);
1393     }
1394     return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
1395   }
1396 
1397   Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1398     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1399   }
1400 
1401   Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1402     return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1403   }
1404 
1405   Value *CreateOr(ArrayRef<Value*> Ops) {
1406     assert(!Ops.empty());
1407     Value *Accum = Ops[0];
1408     for (unsigned i = 1; i < Ops.size(); i++)
1409       Accum = CreateOr(Accum, Ops[i]);
1410     return Accum;
1411   }
1412 
1413   Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
1414     if (Value *V = foldConstant(Instruction::Xor, LHS, RHS, Name)) return V;
1415     return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
1416   }
1417 
1418   Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1419     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1420   }
1421 
1422   Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1423     return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1424   }
1425 
1426   Value *CreateFAdd(Value *L, Value *R, const Twine &Name = "",
1427                     MDNode *FPMD = nullptr) {
1428     if (IsFPConstrained)
1429       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
1430                                       L, R, nullptr, Name, FPMD);
1431 
1432     if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1433     Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), FPMD, FMF);
1434     return Insert(I, Name);
1435   }
1436 
1437   /// Copy fast-math-flags from an instruction rather than using the builder's
1438   /// default FMF.
1439   Value *CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource,
1440                        const Twine &Name = "") {
1441     if (IsFPConstrained)
1442       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fadd,
1443                                       L, R, FMFSource, Name);
1444 
1445     if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1446     Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), nullptr,
1447                                 FMFSource->getFastMathFlags());
1448     return Insert(I, Name);
1449   }
1450 
1451   Value *CreateFSub(Value *L, Value *R, const Twine &Name = "",
1452                     MDNode *FPMD = nullptr) {
1453     if (IsFPConstrained)
1454       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
1455                                       L, R, nullptr, Name, FPMD);
1456 
1457     if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1458     Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), FPMD, FMF);
1459     return Insert(I, Name);
1460   }
1461 
1462   /// Copy fast-math-flags from an instruction rather than using the builder's
1463   /// default FMF.
1464   Value *CreateFSubFMF(Value *L, Value *R, Instruction *FMFSource,
1465                        const Twine &Name = "") {
1466     if (IsFPConstrained)
1467       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fsub,
1468                                       L, R, FMFSource, Name);
1469 
1470     if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1471     Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), nullptr,
1472                                 FMFSource->getFastMathFlags());
1473     return Insert(I, Name);
1474   }
1475 
1476   Value *CreateFMul(Value *L, Value *R, const Twine &Name = "",
1477                     MDNode *FPMD = nullptr) {
1478     if (IsFPConstrained)
1479       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
1480                                       L, R, nullptr, Name, FPMD);
1481 
1482     if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1483     Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), FPMD, FMF);
1484     return Insert(I, Name);
1485   }
1486 
1487   /// Copy fast-math-flags from an instruction rather than using the builder's
1488   /// default FMF.
1489   Value *CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource,
1490                        const Twine &Name = "") {
1491     if (IsFPConstrained)
1492       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fmul,
1493                                       L, R, FMFSource, Name);
1494 
1495     if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1496     Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), nullptr,
1497                                 FMFSource->getFastMathFlags());
1498     return Insert(I, Name);
1499   }
1500 
1501   Value *CreateFDiv(Value *L, Value *R, const Twine &Name = "",
1502                     MDNode *FPMD = nullptr) {
1503     if (IsFPConstrained)
1504       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
1505                                       L, R, nullptr, Name, FPMD);
1506 
1507     if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1508     Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), FPMD, FMF);
1509     return Insert(I, Name);
1510   }
1511 
1512   /// Copy fast-math-flags from an instruction rather than using the builder's
1513   /// default FMF.
1514   Value *CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource,
1515                        const Twine &Name = "") {
1516     if (IsFPConstrained)
1517       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_fdiv,
1518                                       L, R, FMFSource, Name);
1519 
1520     if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1521     Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), nullptr,
1522                                 FMFSource->getFastMathFlags());
1523     return Insert(I, Name);
1524   }
1525 
1526   Value *CreateFRem(Value *L, Value *R, const Twine &Name = "",
1527                     MDNode *FPMD = nullptr) {
1528     if (IsFPConstrained)
1529       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
1530                                       L, R, nullptr, Name, FPMD);
1531 
1532     if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1533     Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), FPMD, FMF);
1534     return Insert(I, Name);
1535   }
1536 
1537   /// Copy fast-math-flags from an instruction rather than using the builder's
1538   /// default FMF.
1539   Value *CreateFRemFMF(Value *L, Value *R, Instruction *FMFSource,
1540                        const Twine &Name = "") {
1541     if (IsFPConstrained)
1542       return CreateConstrainedFPBinOp(Intrinsic::experimental_constrained_frem,
1543                                       L, R, FMFSource, Name);
1544 
1545     if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1546     Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), nullptr,
1547                                 FMFSource->getFastMathFlags());
1548     return Insert(I, Name);
1549   }
1550 
1551   Value *CreateBinOp(Instruction::BinaryOps Opc,
1552                      Value *LHS, Value *RHS, const Twine &Name = "",
1553                      MDNode *FPMathTag = nullptr) {
1554     if (Value *V = foldConstant(Opc, LHS, RHS, Name)) return V;
1555     Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
1556     if (isa<FPMathOperator>(BinOp))
1557       setFPAttrs(BinOp, FPMathTag, FMF);
1558     return Insert(BinOp, Name);
1559   }
1560 
1561   CallInst *CreateConstrainedFPBinOp(
1562       Intrinsic::ID ID, Value *L, Value *R, Instruction *FMFSource = nullptr,
1563       const Twine &Name = "", MDNode *FPMathTag = nullptr,
1564       Optional<fp::RoundingMode> Rounding = None,
1565       Optional<fp::ExceptionBehavior> Except = None) {
1566     Value *RoundingV = getConstrainedFPRounding(Rounding);
1567     Value *ExceptV = getConstrainedFPExcept(Except);
1568 
1569     FastMathFlags UseFMF = FMF;
1570     if (FMFSource)
1571       UseFMF = FMFSource->getFastMathFlags();
1572 
1573     CallInst *C = CreateIntrinsic(ID, {L->getType()},
1574                                   {L, R, RoundingV, ExceptV}, nullptr, Name);
1575     setConstrainedFPCallAttr(C);
1576     setFPAttrs(C, FPMathTag, UseFMF);
1577     return C;
1578   }
1579 
1580   Value *CreateNeg(Value *V, const Twine &Name = "",
1581                    bool HasNUW = false, bool HasNSW = false) {
1582     if (auto *VC = dyn_cast<Constant>(V))
1583       return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
1584     BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
1585     if (HasNUW) BO->setHasNoUnsignedWrap();
1586     if (HasNSW) BO->setHasNoSignedWrap();
1587     return BO;
1588   }
1589 
1590   Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1591     return CreateNeg(V, Name, false, true);
1592   }
1593 
1594   Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1595     return CreateNeg(V, Name, true, false);
1596   }
1597 
1598   Value *CreateFNeg(Value *V, const Twine &Name = "",
1599                     MDNode *FPMathTag = nullptr) {
1600     if (auto *VC = dyn_cast<Constant>(V))
1601       return Insert(Folder.CreateFNeg(VC), Name);
1602     return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), FPMathTag, FMF),
1603                   Name);
1604   }
1605 
1606   /// Copy fast-math-flags from an instruction rather than using the builder's
1607   /// default FMF.
1608   Value *CreateFNegFMF(Value *V, Instruction *FMFSource,
1609                        const Twine &Name = "") {
1610    if (auto *VC = dyn_cast<Constant>(V))
1611      return Insert(Folder.CreateFNeg(VC), Name);
1612    return Insert(setFPAttrs(UnaryOperator::CreateFNeg(V), nullptr,
1613                             FMFSource->getFastMathFlags()),
1614                  Name);
1615   }
1616 
1617   Value *CreateNot(Value *V, const Twine &Name = "") {
1618     if (auto *VC = dyn_cast<Constant>(V))
1619       return Insert(Folder.CreateNot(VC), Name);
1620     return Insert(BinaryOperator::CreateNot(V), Name);
1621   }
1622 
1623   Value *CreateUnOp(Instruction::UnaryOps Opc,
1624                     Value *V, const Twine &Name = "",
1625                     MDNode *FPMathTag = nullptr) {
1626     if (auto *VC = dyn_cast<Constant>(V))
1627       return Insert(Folder.CreateUnOp(Opc, VC), Name);
1628     Instruction *UnOp = UnaryOperator::Create(Opc, V);
1629     if (isa<FPMathOperator>(UnOp))
1630       setFPAttrs(UnOp, FPMathTag, FMF);
1631     return Insert(UnOp, Name);
1632   }
1633 
1634   /// Create either a UnaryOperator or BinaryOperator depending on \p Opc.
1635   /// Correct number of operands must be passed accordingly.
1636   Value *CreateNAryOp(unsigned Opc, ArrayRef<Value *> Ops,
1637                       const Twine &Name = "",
1638                       MDNode *FPMathTag = nullptr) {
1639     if (Instruction::isBinaryOp(Opc)) {
1640       assert(Ops.size() == 2 && "Invalid number of operands!");
1641       return CreateBinOp(static_cast<Instruction::BinaryOps>(Opc),
1642                          Ops[0], Ops[1], Name, FPMathTag);
1643     }
1644     if (Instruction::isUnaryOp(Opc)) {
1645       assert(Ops.size() == 1 && "Invalid number of operands!");
1646       return CreateUnOp(static_cast<Instruction::UnaryOps>(Opc),
1647                         Ops[0], Name, FPMathTag);
1648     }
1649     llvm_unreachable("Unexpected opcode!");
1650   }
1651 
1652   //===--------------------------------------------------------------------===//
1653   // Instruction creation methods: Memory Instructions
1654   //===--------------------------------------------------------------------===//
1655 
1656   AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
1657                            Value *ArraySize = nullptr, const Twine &Name = "") {
1658     return Insert(new AllocaInst(Ty, AddrSpace, ArraySize), Name);
1659   }
1660 
1661   AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1662                            const Twine &Name = "") {
1663     const DataLayout &DL = BB->getParent()->getParent()->getDataLayout();
1664     return Insert(new AllocaInst(Ty, DL.getAllocaAddrSpace(), ArraySize), Name);
1665   }
1666 
1667   /// Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of
1668   /// converting the string to 'bool' for the isVolatile parameter.
1669   LoadInst *CreateLoad(Type *Ty, Value *Ptr, const char *Name) {
1670     return Insert(new LoadInst(Ty, Ptr), Name);
1671   }
1672 
1673   LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1674     return Insert(new LoadInst(Ty, Ptr), Name);
1675   }
1676 
1677   LoadInst *CreateLoad(Type *Ty, Value *Ptr, bool isVolatile,
1678                        const Twine &Name = "") {
1679     return Insert(new LoadInst(Ty, Ptr, Twine(), isVolatile), Name);
1680   }
1681 
1682   // Deprecated [opaque pointer types]
1683   LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1684     return CreateLoad(Ptr->getType()->getPointerElementType(), Ptr, Name);
1685   }
1686 
1687   // Deprecated [opaque pointer types]
1688   LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1689     return CreateLoad(Ptr->getType()->getPointerElementType(), Ptr, Name);
1690   }
1691 
1692   // Deprecated [opaque pointer types]
1693   LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1694     return CreateLoad(Ptr->getType()->getPointerElementType(), Ptr, isVolatile,
1695                       Name);
1696   }
1697 
1698   StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1699     return Insert(new StoreInst(Val, Ptr, isVolatile));
1700   }
1701 
1702   /// Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1703   /// correctly, instead of converting the string to 'bool' for the isVolatile
1704   /// parameter.
1705   /// FIXME: Remove this function once transition to Align is over.
1706   /// Use the version that takes MaybeAlign instead of this one.
1707   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align,
1708                               const char *Name) {
1709     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(Align), Name);
1710   }
1711   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1712                               const char *Name) {
1713     LoadInst *LI = CreateLoad(Ty, Ptr, Name);
1714     LI->setAlignment(Align);
1715     return LI;
1716   }
1717   /// FIXME: Remove this function once transition to Align is over.
1718   /// Use the version that takes MaybeAlign instead of this one.
1719   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align,
1720                               const Twine &Name = "") {
1721     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(Align), Name);
1722   }
1723   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1724                               const Twine &Name = "") {
1725     LoadInst *LI = CreateLoad(Ty, Ptr, Name);
1726     LI->setAlignment(Align);
1727     return LI;
1728   }
1729   /// FIXME: Remove this function once transition to Align is over.
1730   /// Use the version that takes MaybeAlign instead of this one.
1731   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, unsigned Align,
1732                               bool isVolatile, const Twine &Name = "") {
1733     return CreateAlignedLoad(Ty, Ptr, MaybeAlign(Align), isVolatile, Name);
1734   }
1735   LoadInst *CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align,
1736                               bool isVolatile, const Twine &Name = "") {
1737     LoadInst *LI = CreateLoad(Ty, Ptr, isVolatile, Name);
1738     LI->setAlignment(Align);
1739     return LI;
1740   }
1741 
1742   // Deprecated [opaque pointer types]
1743   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1744     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1745                              Align, Name);
1746   }
1747   // Deprecated [opaque pointer types]
1748   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1749                               const Twine &Name = "") {
1750     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1751                              Align, Name);
1752   }
1753   // Deprecated [opaque pointer types]
1754   LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1755                               const Twine &Name = "") {
1756     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1757                              Align, isVolatile, Name);
1758   }
1759   // Deprecated [opaque pointer types]
1760   LoadInst *CreateAlignedLoad(Value *Ptr, MaybeAlign Align, const char *Name) {
1761     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1762                              Align, Name);
1763   }
1764   // Deprecated [opaque pointer types]
1765   LoadInst *CreateAlignedLoad(Value *Ptr, MaybeAlign Align,
1766                               const Twine &Name = "") {
1767     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1768                              Align, Name);
1769   }
1770   // Deprecated [opaque pointer types]
1771   LoadInst *CreateAlignedLoad(Value *Ptr, MaybeAlign Align, bool isVolatile,
1772                               const Twine &Name = "") {
1773     return CreateAlignedLoad(Ptr->getType()->getPointerElementType(), Ptr,
1774                              Align, isVolatile, Name);
1775   }
1776 
1777   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1778                                 bool isVolatile = false) {
1779     StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1780     SI->setAlignment(MaybeAlign(Align));
1781     return SI;
1782   }
1783   StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align,
1784                                 bool isVolatile = false) {
1785     return CreateAlignedStore(Val, Ptr, Align ? Align->value() : 0, isVolatile);
1786   }
1787   FenceInst *CreateFence(AtomicOrdering Ordering,
1788                          SyncScope::ID SSID = SyncScope::System,
1789                          const Twine &Name = "") {
1790     return Insert(new FenceInst(Context, Ordering, SSID), Name);
1791   }
1792 
1793   AtomicCmpXchgInst *
1794   CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1795                       AtomicOrdering SuccessOrdering,
1796                       AtomicOrdering FailureOrdering,
1797                       SyncScope::ID SSID = SyncScope::System) {
1798     return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1799                                         FailureOrdering, SSID));
1800   }
1801 
1802   AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1803                                  AtomicOrdering Ordering,
1804                                  SyncScope::ID SSID = SyncScope::System) {
1805     return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SSID));
1806   }
1807 
1808   Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1809                    const Twine &Name = "") {
1810     return CreateGEP(nullptr, Ptr, IdxList, Name);
1811   }
1812 
1813   Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1814                    const Twine &Name = "") {
1815     if (auto *PC = dyn_cast<Constant>(Ptr)) {
1816       // Every index must be constant.
1817       size_t i, e;
1818       for (i = 0, e = IdxList.size(); i != e; ++i)
1819         if (!isa<Constant>(IdxList[i]))
1820           break;
1821       if (i == e)
1822         return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1823     }
1824     return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1825   }
1826 
1827   Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1828                            const Twine &Name = "") {
1829     return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1830   }
1831 
1832   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1833                            const Twine &Name = "") {
1834     if (auto *PC = dyn_cast<Constant>(Ptr)) {
1835       // Every index must be constant.
1836       size_t i, e;
1837       for (i = 0, e = IdxList.size(); i != e; ++i)
1838         if (!isa<Constant>(IdxList[i]))
1839           break;
1840       if (i == e)
1841         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1842                       Name);
1843     }
1844     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1845   }
1846 
1847   Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1848     return CreateGEP(nullptr, Ptr, Idx, Name);
1849   }
1850 
1851   Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1852     if (auto *PC = dyn_cast<Constant>(Ptr))
1853       if (auto *IC = dyn_cast<Constant>(Idx))
1854         return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1855     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1856   }
1857 
1858   Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1859                            const Twine &Name = "") {
1860     if (auto *PC = dyn_cast<Constant>(Ptr))
1861       if (auto *IC = dyn_cast<Constant>(Idx))
1862         return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1863     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1864   }
1865 
1866   Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1867     return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1868   }
1869 
1870   Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1871                             const Twine &Name = "") {
1872     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1873 
1874     if (auto *PC = dyn_cast<Constant>(Ptr))
1875       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1876 
1877     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1878   }
1879 
1880   Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1881                                     const Twine &Name = "") {
1882     Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1883 
1884     if (auto *PC = dyn_cast<Constant>(Ptr))
1885       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1886 
1887     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1888   }
1889 
1890   Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1891                             const Twine &Name = "") {
1892     Value *Idxs[] = {
1893       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1894       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1895     };
1896 
1897     if (auto *PC = dyn_cast<Constant>(Ptr))
1898       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1899 
1900     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1901   }
1902 
1903   Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1904                                     unsigned Idx1, const Twine &Name = "") {
1905     Value *Idxs[] = {
1906       ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1907       ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1908     };
1909 
1910     if (auto *PC = dyn_cast<Constant>(Ptr))
1911       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1912 
1913     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1914   }
1915 
1916   Value *CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1917                             const Twine &Name = "") {
1918     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1919 
1920     if (auto *PC = dyn_cast<Constant>(Ptr))
1921       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1922 
1923     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1924   }
1925 
1926   Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1927     return CreateConstGEP1_64(nullptr, Ptr, Idx0, Name);
1928   }
1929 
1930   Value *CreateConstInBoundsGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1931                                     const Twine &Name = "") {
1932     Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1933 
1934     if (auto *PC = dyn_cast<Constant>(Ptr))
1935       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1936 
1937     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1938   }
1939 
1940   Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1941                                     const Twine &Name = "") {
1942     return CreateConstInBoundsGEP1_64(nullptr, Ptr, Idx0, Name);
1943   }
1944 
1945   Value *CreateConstGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1946                             const Twine &Name = "") {
1947     Value *Idxs[] = {
1948       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1949       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1950     };
1951 
1952     if (auto *PC = dyn_cast<Constant>(Ptr))
1953       return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1954 
1955     return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1956   }
1957 
1958   Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1959                             const Twine &Name = "") {
1960     return CreateConstGEP2_64(nullptr, Ptr, Idx0, Idx1, Name);
1961   }
1962 
1963   Value *CreateConstInBoundsGEP2_64(Type *Ty, Value *Ptr, uint64_t Idx0,
1964                                     uint64_t Idx1, const Twine &Name = "") {
1965     Value *Idxs[] = {
1966       ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1967       ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1968     };
1969 
1970     if (auto *PC = dyn_cast<Constant>(Ptr))
1971       return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1972 
1973     return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1974   }
1975 
1976   Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1977                                     const Twine &Name = "") {
1978     return CreateConstInBoundsGEP2_64(nullptr, Ptr, Idx0, Idx1, Name);
1979   }
1980 
1981   Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1982                          const Twine &Name = "") {
1983     return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1984   }
1985 
1986   Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1987     return CreateConstInBoundsGEP2_32(nullptr, Ptr, 0, Idx, Name);
1988   }
1989 
1990   /// Same as CreateGlobalString, but return a pointer with "i8*" type
1991   /// instead of a pointer to array of i8.
1992   Constant *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1993                                   unsigned AddressSpace = 0) {
1994     GlobalVariable *GV = CreateGlobalString(Str, Name, AddressSpace);
1995     Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1996     Constant *Indices[] = {Zero, Zero};
1997     return ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV,
1998                                                   Indices);
1999   }
2000 
2001   //===--------------------------------------------------------------------===//
2002   // Instruction creation methods: Cast/Conversion Operators
2003   //===--------------------------------------------------------------------===//
2004 
2005   Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
2006     return CreateCast(Instruction::Trunc, V, DestTy, Name);
2007   }
2008 
2009   Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
2010     return CreateCast(Instruction::ZExt, V, DestTy, Name);
2011   }
2012 
2013   Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
2014     return CreateCast(Instruction::SExt, V, DestTy, Name);
2015   }
2016 
2017   /// Create a ZExt or Trunc from the integer value V to DestTy. Return
2018   /// the value untouched if the type of V is already DestTy.
2019   Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
2020                            const Twine &Name = "") {
2021     assert(V->getType()->isIntOrIntVectorTy() &&
2022            DestTy->isIntOrIntVectorTy() &&
2023            "Can only zero extend/truncate integers!");
2024     Type *VTy = V->getType();
2025     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
2026       return CreateZExt(V, DestTy, Name);
2027     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
2028       return CreateTrunc(V, DestTy, Name);
2029     return V;
2030   }
2031 
2032   /// Create a SExt or Trunc from the integer value V to DestTy. Return
2033   /// the value untouched if the type of V is already DestTy.
2034   Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
2035                            const Twine &Name = "") {
2036     assert(V->getType()->isIntOrIntVectorTy() &&
2037            DestTy->isIntOrIntVectorTy() &&
2038            "Can only sign extend/truncate integers!");
2039     Type *VTy = V->getType();
2040     if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
2041       return CreateSExt(V, DestTy, Name);
2042     if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
2043       return CreateTrunc(V, DestTy, Name);
2044     return V;
2045   }
2046 
2047   Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = "") {
2048     if (IsFPConstrained)
2049       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptoui,
2050                                      V, DestTy, nullptr, Name);
2051     return CreateCast(Instruction::FPToUI, V, DestTy, Name);
2052   }
2053 
2054   Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = "") {
2055     if (IsFPConstrained)
2056       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fptosi,
2057                                      V, DestTy, nullptr, Name);
2058     return CreateCast(Instruction::FPToSI, V, DestTy, Name);
2059   }
2060 
2061   Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
2062     if (IsFPConstrained)
2063       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_uitofp,
2064                                      V, DestTy, nullptr, Name);
2065     return CreateCast(Instruction::UIToFP, V, DestTy, Name);
2066   }
2067 
2068   Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
2069     if (IsFPConstrained)
2070       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_sitofp,
2071                                      V, DestTy, nullptr, Name);
2072     return CreateCast(Instruction::SIToFP, V, DestTy, Name);
2073   }
2074 
2075   Value *CreateFPTrunc(Value *V, Type *DestTy,
2076                        const Twine &Name = "") {
2077     if (IsFPConstrained)
2078       return CreateConstrainedFPCast(
2079           Intrinsic::experimental_constrained_fptrunc, V, DestTy, nullptr,
2080           Name);
2081     return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
2082   }
2083 
2084   Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
2085     if (IsFPConstrained)
2086       return CreateConstrainedFPCast(Intrinsic::experimental_constrained_fpext,
2087                                      V, DestTy, nullptr, Name);
2088     return CreateCast(Instruction::FPExt, V, DestTy, Name);
2089   }
2090 
2091   Value *CreatePtrToInt(Value *V, Type *DestTy,
2092                         const Twine &Name = "") {
2093     return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
2094   }
2095 
2096   Value *CreateIntToPtr(Value *V, Type *DestTy,
2097                         const Twine &Name = "") {
2098     return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
2099   }
2100 
2101   Value *CreateBitCast(Value *V, Type *DestTy,
2102                        const Twine &Name = "") {
2103     return CreateCast(Instruction::BitCast, V, DestTy, Name);
2104   }
2105 
2106   Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
2107                              const Twine &Name = "") {
2108     return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
2109   }
2110 
2111   Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
2112                              const Twine &Name = "") {
2113     if (V->getType() == DestTy)
2114       return V;
2115     if (auto *VC = dyn_cast<Constant>(V))
2116       return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
2117     return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
2118   }
2119 
2120   Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
2121                              const Twine &Name = "") {
2122     if (V->getType() == DestTy)
2123       return V;
2124     if (auto *VC = dyn_cast<Constant>(V))
2125       return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
2126     return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
2127   }
2128 
2129   Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
2130                               const Twine &Name = "") {
2131     if (V->getType() == DestTy)
2132       return V;
2133     if (auto *VC = dyn_cast<Constant>(V))
2134       return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
2135     return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
2136   }
2137 
2138   Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
2139                     const Twine &Name = "") {
2140     if (V->getType() == DestTy)
2141       return V;
2142     if (auto *VC = dyn_cast<Constant>(V))
2143       return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
2144     return Insert(CastInst::Create(Op, V, DestTy), Name);
2145   }
2146 
2147   Value *CreatePointerCast(Value *V, Type *DestTy,
2148                            const Twine &Name = "") {
2149     if (V->getType() == DestTy)
2150       return V;
2151     if (auto *VC = dyn_cast<Constant>(V))
2152       return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
2153     return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
2154   }
2155 
2156   Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
2157                                              const Twine &Name = "") {
2158     if (V->getType() == DestTy)
2159       return V;
2160 
2161     if (auto *VC = dyn_cast<Constant>(V)) {
2162       return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
2163                     Name);
2164     }
2165 
2166     return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
2167                   Name);
2168   }
2169 
2170   Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
2171                        const Twine &Name = "") {
2172     if (V->getType() == DestTy)
2173       return V;
2174     if (auto *VC = dyn_cast<Constant>(V))
2175       return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
2176     return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
2177   }
2178 
2179   Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
2180                                 const Twine &Name = "") {
2181     if (V->getType() == DestTy)
2182       return V;
2183     if (V->getType()->isPtrOrPtrVectorTy() && DestTy->isIntOrIntVectorTy())
2184       return CreatePtrToInt(V, DestTy, Name);
2185     if (V->getType()->isIntOrIntVectorTy() && DestTy->isPtrOrPtrVectorTy())
2186       return CreateIntToPtr(V, DestTy, Name);
2187 
2188     return CreateBitCast(V, DestTy, Name);
2189   }
2190 
2191   Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
2192     if (V->getType() == DestTy)
2193       return V;
2194     if (auto *VC = dyn_cast<Constant>(V))
2195       return Insert(Folder.CreateFPCast(VC, DestTy), Name);
2196     return Insert(CastInst::CreateFPCast(V, DestTy), Name);
2197   }
2198 
2199   CallInst *CreateConstrainedFPCast(
2200       Intrinsic::ID ID, Value *V, Type *DestTy,
2201       Instruction *FMFSource = nullptr, const Twine &Name = "",
2202       MDNode *FPMathTag = nullptr,
2203       Optional<fp::RoundingMode> Rounding = None,
2204       Optional<fp::ExceptionBehavior> Except = None) {
2205     Value *ExceptV = getConstrainedFPExcept(Except);
2206 
2207     FastMathFlags UseFMF = FMF;
2208     if (FMFSource)
2209       UseFMF = FMFSource->getFastMathFlags();
2210 
2211     CallInst *C;
2212     bool HasRoundingMD = false;
2213     switch (ID) {
2214     default:
2215       break;
2216 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)  \
2217     case Intrinsic::INTRINSIC:                                \
2218       HasRoundingMD = ROUND_MODE;                             \
2219       break;
2220 #include "llvm/IR/ConstrainedOps.def"
2221     }
2222     if (HasRoundingMD) {
2223       Value *RoundingV = getConstrainedFPRounding(Rounding);
2224       C = CreateIntrinsic(ID, {DestTy, V->getType()}, {V, RoundingV, ExceptV},
2225                           nullptr, Name);
2226     } else
2227       C = CreateIntrinsic(ID, {DestTy, V->getType()}, {V, ExceptV}, nullptr,
2228                           Name);
2229 
2230     setConstrainedFPCallAttr(C);
2231 
2232     if (isa<FPMathOperator>(C))
2233       setFPAttrs(C, FPMathTag, UseFMF);
2234     return C;
2235   }
2236 
2237   // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
2238   // compile time error, instead of converting the string to bool for the
2239   // isSigned parameter.
2240   Value *CreateIntCast(Value *, Type *, const char *) = delete;
2241 
2242   //===--------------------------------------------------------------------===//
2243   // Instruction creation methods: Compare Instructions
2244   //===--------------------------------------------------------------------===//
2245 
2246   Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
2247     return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
2248   }
2249 
2250   Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
2251     return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
2252   }
2253 
2254   Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
2255     return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
2256   }
2257 
2258   Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
2259     return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
2260   }
2261 
2262   Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
2263     return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
2264   }
2265 
2266   Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
2267     return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
2268   }
2269 
2270   Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
2271     return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
2272   }
2273 
2274   Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
2275     return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
2276   }
2277 
2278   Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
2279     return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
2280   }
2281 
2282   Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
2283     return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
2284   }
2285 
2286   Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
2287                        MDNode *FPMathTag = nullptr) {
2288     return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
2289   }
2290 
2291   Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
2292                        MDNode *FPMathTag = nullptr) {
2293     return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
2294   }
2295 
2296   Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
2297                        MDNode *FPMathTag = nullptr) {
2298     return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
2299   }
2300 
2301   Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
2302                        MDNode *FPMathTag = nullptr) {
2303     return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
2304   }
2305 
2306   Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
2307                        MDNode *FPMathTag = nullptr) {
2308     return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
2309   }
2310 
2311   Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
2312                        MDNode *FPMathTag = nullptr) {
2313     return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
2314   }
2315 
2316   Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
2317                        MDNode *FPMathTag = nullptr) {
2318     return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
2319   }
2320 
2321   Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
2322                        MDNode *FPMathTag = nullptr) {
2323     return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
2324   }
2325 
2326   Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
2327                        MDNode *FPMathTag = nullptr) {
2328     return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
2329   }
2330 
2331   Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
2332                        MDNode *FPMathTag = nullptr) {
2333     return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
2334   }
2335 
2336   Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
2337                        MDNode *FPMathTag = nullptr) {
2338     return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
2339   }
2340 
2341   Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
2342                        MDNode *FPMathTag = nullptr) {
2343     return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
2344   }
2345 
2346   Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
2347                        MDNode *FPMathTag = nullptr) {
2348     return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
2349   }
2350 
2351   Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
2352                        MDNode *FPMathTag = nullptr) {
2353     return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
2354   }
2355 
2356   Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
2357                     const Twine &Name = "") {
2358     if (auto *LC = dyn_cast<Constant>(LHS))
2359       if (auto *RC = dyn_cast<Constant>(RHS))
2360         return Insert(Folder.CreateICmp(P, LC, RC), Name);
2361     return Insert(new ICmpInst(P, LHS, RHS), Name);
2362   }
2363 
2364   // Create a quiet floating-point comparison (i.e. one that raises an FP
2365   // exception only in the case where an input is a signaling NaN).
2366   // Note that this differs from CreateFCmpS only if IsFPConstrained is true.
2367   Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
2368                     const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2369     if (IsFPConstrained)
2370       return CreateConstrainedFPCmp(Intrinsic::experimental_constrained_fcmp,
2371                                     P, LHS, RHS, Name);
2372 
2373     if (auto *LC = dyn_cast<Constant>(LHS))
2374       if (auto *RC = dyn_cast<Constant>(RHS))
2375         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
2376     return Insert(setFPAttrs(new FCmpInst(P, LHS, RHS), FPMathTag, FMF), Name);
2377   }
2378 
2379   // Create a signaling floating-point comparison (i.e. one that raises an FP
2380   // exception whenever an input is any NaN, signaling or quiet).
2381   // Note that this differs from CreateFCmp only if IsFPConstrained is true.
2382   Value *CreateFCmpS(CmpInst::Predicate P, Value *LHS, Value *RHS,
2383                      const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2384     if (IsFPConstrained)
2385       return CreateConstrainedFPCmp(Intrinsic::experimental_constrained_fcmps,
2386                                     P, LHS, RHS, Name);
2387 
2388     if (auto *LC = dyn_cast<Constant>(LHS))
2389       if (auto *RC = dyn_cast<Constant>(RHS))
2390         return Insert(Folder.CreateFCmp(P, LC, RC), Name);
2391     return Insert(setFPAttrs(new FCmpInst(P, LHS, RHS), FPMathTag, FMF), Name);
2392   }
2393 
2394   CallInst *CreateConstrainedFPCmp(
2395       Intrinsic::ID ID, CmpInst::Predicate P, Value *L, Value *R,
2396       const Twine &Name = "",
2397       Optional<fp::ExceptionBehavior> Except = None) {
2398     Value *PredicateV = getConstrainedFPPredicate(P);
2399     Value *ExceptV = getConstrainedFPExcept(Except);
2400 
2401     CallInst *C = CreateIntrinsic(ID, {L->getType()},
2402                                   {L, R, PredicateV, ExceptV}, nullptr, Name);
2403     setConstrainedFPCallAttr(C);
2404     return C;
2405   }
2406 
2407   //===--------------------------------------------------------------------===//
2408   // Instruction creation methods: Other Instructions
2409   //===--------------------------------------------------------------------===//
2410 
2411   PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
2412                      const Twine &Name = "") {
2413     PHINode *Phi = PHINode::Create(Ty, NumReservedValues);
2414     if (isa<FPMathOperator>(Phi))
2415       setFPAttrs(Phi, nullptr /* MDNode* */, FMF);
2416     return Insert(Phi, Name);
2417   }
2418 
2419   CallInst *CreateCall(FunctionType *FTy, Value *Callee,
2420                        ArrayRef<Value *> Args = None, const Twine &Name = "",
2421                        MDNode *FPMathTag = nullptr) {
2422     CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
2423     if (IsFPConstrained)
2424       setConstrainedFPCallAttr(CI);
2425     if (isa<FPMathOperator>(CI))
2426       setFPAttrs(CI, FPMathTag, FMF);
2427     return Insert(CI, Name);
2428   }
2429 
2430   CallInst *CreateCall(FunctionType *FTy, Value *Callee, ArrayRef<Value *> Args,
2431                        ArrayRef<OperandBundleDef> OpBundles,
2432                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2433     CallInst *CI = CallInst::Create(FTy, Callee, Args, OpBundles);
2434     if (IsFPConstrained)
2435       setConstrainedFPCallAttr(CI);
2436     if (isa<FPMathOperator>(CI))
2437       setFPAttrs(CI, FPMathTag, FMF);
2438     return Insert(CI, Name);
2439   }
2440 
2441   CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args = None,
2442                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2443     return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args, Name,
2444                       FPMathTag);
2445   }
2446 
2447   CallInst *CreateCall(FunctionCallee Callee, ArrayRef<Value *> Args,
2448                        ArrayRef<OperandBundleDef> OpBundles,
2449                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2450     return CreateCall(Callee.getFunctionType(), Callee.getCallee(), Args,
2451                       OpBundles, Name, FPMathTag);
2452   }
2453 
2454   // Deprecated [opaque pointer types]
2455   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
2456                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2457     return CreateCall(
2458         cast<FunctionType>(Callee->getType()->getPointerElementType()), Callee,
2459         Args, Name, FPMathTag);
2460   }
2461 
2462   // Deprecated [opaque pointer types]
2463   CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
2464                        ArrayRef<OperandBundleDef> OpBundles,
2465                        const Twine &Name = "", MDNode *FPMathTag = nullptr) {
2466     return CreateCall(
2467         cast<FunctionType>(Callee->getType()->getPointerElementType()), Callee,
2468         Args, OpBundles, Name, FPMathTag);
2469   }
2470 
2471   CallInst *CreateConstrainedFPCall(
2472       Function *Callee, ArrayRef<Value *> Args, const Twine &Name = "",
2473       Optional<fp::RoundingMode> Rounding = None,
2474       Optional<fp::ExceptionBehavior> Except = None) {
2475     llvm::SmallVector<Value *, 6> UseArgs;
2476 
2477     for (auto *OneArg : Args)
2478       UseArgs.push_back(OneArg);
2479     bool HasRoundingMD = false;
2480     switch (Callee->getIntrinsicID()) {
2481     default:
2482       break;
2483 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)  \
2484     case Intrinsic::INTRINSIC:                                \
2485       HasRoundingMD = ROUND_MODE;                             \
2486       break;
2487 #include "llvm/IR/ConstrainedOps.def"
2488     }
2489     if (HasRoundingMD)
2490       UseArgs.push_back(getConstrainedFPRounding(Rounding));
2491     UseArgs.push_back(getConstrainedFPExcept(Except));
2492 
2493     CallInst *C = CreateCall(Callee, UseArgs, Name);
2494     setConstrainedFPCallAttr(C);
2495     return C;
2496   }
2497 
2498   Value *CreateSelect(Value *C, Value *True, Value *False,
2499                       const Twine &Name = "", Instruction *MDFrom = nullptr) {
2500     if (auto *CC = dyn_cast<Constant>(C))
2501       if (auto *TC = dyn_cast<Constant>(True))
2502         if (auto *FC = dyn_cast<Constant>(False))
2503           return Insert(Folder.CreateSelect(CC, TC, FC), Name);
2504 
2505     SelectInst *Sel = SelectInst::Create(C, True, False);
2506     if (MDFrom) {
2507       MDNode *Prof = MDFrom->getMetadata(LLVMContext::MD_prof);
2508       MDNode *Unpred = MDFrom->getMetadata(LLVMContext::MD_unpredictable);
2509       Sel = addBranchMetadata(Sel, Prof, Unpred);
2510     }
2511     if (isa<FPMathOperator>(Sel))
2512       setFPAttrs(Sel, nullptr /* MDNode* */, FMF);
2513     return Insert(Sel, Name);
2514   }
2515 
2516   VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
2517     return Insert(new VAArgInst(List, Ty), Name);
2518   }
2519 
2520   Value *CreateExtractElement(Value *Vec, Value *Idx,
2521                               const Twine &Name = "") {
2522     if (auto *VC = dyn_cast<Constant>(Vec))
2523       if (auto *IC = dyn_cast<Constant>(Idx))
2524         return Insert(Folder.CreateExtractElement(VC, IC), Name);
2525     return Insert(ExtractElementInst::Create(Vec, Idx), Name);
2526   }
2527 
2528   Value *CreateExtractElement(Value *Vec, uint64_t Idx,
2529                               const Twine &Name = "") {
2530     return CreateExtractElement(Vec, getInt64(Idx), Name);
2531   }
2532 
2533   Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
2534                              const Twine &Name = "") {
2535     if (auto *VC = dyn_cast<Constant>(Vec))
2536       if (auto *NC = dyn_cast<Constant>(NewElt))
2537         if (auto *IC = dyn_cast<Constant>(Idx))
2538           return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
2539     return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
2540   }
2541 
2542   Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
2543                              const Twine &Name = "") {
2544     return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
2545   }
2546 
2547   Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
2548                              const Twine &Name = "") {
2549     if (auto *V1C = dyn_cast<Constant>(V1))
2550       if (auto *V2C = dyn_cast<Constant>(V2))
2551         if (auto *MC = dyn_cast<Constant>(Mask))
2552           return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
2553     return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
2554   }
2555 
2556   Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<uint32_t> IntMask,
2557                              const Twine &Name = "") {
2558     Value *Mask = ConstantDataVector::get(Context, IntMask);
2559     return CreateShuffleVector(V1, V2, Mask, Name);
2560   }
2561 
2562   Value *CreateExtractValue(Value *Agg,
2563                             ArrayRef<unsigned> Idxs,
2564                             const Twine &Name = "") {
2565     if (auto *AggC = dyn_cast<Constant>(Agg))
2566       return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
2567     return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
2568   }
2569 
2570   Value *CreateInsertValue(Value *Agg, Value *Val,
2571                            ArrayRef<unsigned> Idxs,
2572                            const Twine &Name = "") {
2573     if (auto *AggC = dyn_cast<Constant>(Agg))
2574       if (auto *ValC = dyn_cast<Constant>(Val))
2575         return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
2576     return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
2577   }
2578 
2579   LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
2580                                    const Twine &Name = "") {
2581     return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
2582   }
2583 
2584   Value *CreateFreeze(Value *V, const Twine &Name = "") {
2585     return Insert(new FreezeInst(V), Name);
2586   }
2587 
2588   //===--------------------------------------------------------------------===//
2589   // Utility creation methods
2590   //===--------------------------------------------------------------------===//
2591 
2592   /// Return an i1 value testing if \p Arg is null.
2593   Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
2594     return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
2595                         Name);
2596   }
2597 
2598   /// Return an i1 value testing if \p Arg is not null.
2599   Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
2600     return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
2601                         Name);
2602   }
2603 
2604   /// Return the i64 difference between two pointer values, dividing out
2605   /// the size of the pointed-to objects.
2606   ///
2607   /// This is intended to implement C-style pointer subtraction. As such, the
2608   /// pointers must be appropriately aligned for their element types and
2609   /// pointing into the same object.
2610   Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
2611     assert(LHS->getType() == RHS->getType() &&
2612            "Pointer subtraction operand types must match!");
2613     auto *ArgType = cast<PointerType>(LHS->getType());
2614     Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
2615     Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
2616     Value *Difference = CreateSub(LHS_int, RHS_int);
2617     return CreateExactSDiv(Difference,
2618                            ConstantExpr::getSizeOf(ArgType->getElementType()),
2619                            Name);
2620   }
2621 
2622   /// Create a launder.invariant.group intrinsic call. If Ptr type is
2623   /// different from pointer to i8, it's casted to pointer to i8 in the same
2624   /// address space before call and casted back to Ptr type after call.
2625   Value *CreateLaunderInvariantGroup(Value *Ptr) {
2626     assert(isa<PointerType>(Ptr->getType()) &&
2627            "launder.invariant.group only applies to pointers.");
2628     // FIXME: we could potentially avoid casts to/from i8*.
2629     auto *PtrType = Ptr->getType();
2630     auto *Int8PtrTy = getInt8PtrTy(PtrType->getPointerAddressSpace());
2631     if (PtrType != Int8PtrTy)
2632       Ptr = CreateBitCast(Ptr, Int8PtrTy);
2633     Module *M = BB->getParent()->getParent();
2634     Function *FnLaunderInvariantGroup = Intrinsic::getDeclaration(
2635         M, Intrinsic::launder_invariant_group, {Int8PtrTy});
2636 
2637     assert(FnLaunderInvariantGroup->getReturnType() == Int8PtrTy &&
2638            FnLaunderInvariantGroup->getFunctionType()->getParamType(0) ==
2639                Int8PtrTy &&
2640            "LaunderInvariantGroup should take and return the same type");
2641 
2642     CallInst *Fn = CreateCall(FnLaunderInvariantGroup, {Ptr});
2643 
2644     if (PtrType != Int8PtrTy)
2645       return CreateBitCast(Fn, PtrType);
2646     return Fn;
2647   }
2648 
2649   /// \brief Create a strip.invariant.group intrinsic call. If Ptr type is
2650   /// different from pointer to i8, it's casted to pointer to i8 in the same
2651   /// address space before call and casted back to Ptr type after call.
2652   Value *CreateStripInvariantGroup(Value *Ptr) {
2653     assert(isa<PointerType>(Ptr->getType()) &&
2654            "strip.invariant.group only applies to pointers.");
2655 
2656     // FIXME: we could potentially avoid casts to/from i8*.
2657     auto *PtrType = Ptr->getType();
2658     auto *Int8PtrTy = getInt8PtrTy(PtrType->getPointerAddressSpace());
2659     if (PtrType != Int8PtrTy)
2660       Ptr = CreateBitCast(Ptr, Int8PtrTy);
2661     Module *M = BB->getParent()->getParent();
2662     Function *FnStripInvariantGroup = Intrinsic::getDeclaration(
2663         M, Intrinsic::strip_invariant_group, {Int8PtrTy});
2664 
2665     assert(FnStripInvariantGroup->getReturnType() == Int8PtrTy &&
2666            FnStripInvariantGroup->getFunctionType()->getParamType(0) ==
2667                Int8PtrTy &&
2668            "StripInvariantGroup should take and return the same type");
2669 
2670     CallInst *Fn = CreateCall(FnStripInvariantGroup, {Ptr});
2671 
2672     if (PtrType != Int8PtrTy)
2673       return CreateBitCast(Fn, PtrType);
2674     return Fn;
2675   }
2676 
2677   /// Return a vector value that contains \arg V broadcasted to \p
2678   /// NumElts elements.
2679   Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
2680     assert(NumElts > 0 && "Cannot splat to an empty vector!");
2681 
2682     // First insert it into an undef vector so we can shuffle it.
2683     Type *I32Ty = getInt32Ty();
2684     Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
2685     V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
2686                             Name + ".splatinsert");
2687 
2688     // Shuffle the value across the desired number of elements.
2689     Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
2690     return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
2691   }
2692 
2693   /// Return a value that has been extracted from a larger integer type.
2694   Value *CreateExtractInteger(const DataLayout &DL, Value *From,
2695                               IntegerType *ExtractedTy, uint64_t Offset,
2696                               const Twine &Name) {
2697     auto *IntTy = cast<IntegerType>(From->getType());
2698     assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
2699                DL.getTypeStoreSize(IntTy) &&
2700            "Element extends past full value");
2701     uint64_t ShAmt = 8 * Offset;
2702     Value *V = From;
2703     if (DL.isBigEndian())
2704       ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
2705                    DL.getTypeStoreSize(ExtractedTy) - Offset);
2706     if (ShAmt) {
2707       V = CreateLShr(V, ShAmt, Name + ".shift");
2708     }
2709     assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
2710            "Cannot extract to a larger integer!");
2711     if (ExtractedTy != IntTy) {
2712       V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
2713     }
2714     return V;
2715   }
2716 
2717   Value *CreatePreserveArrayAccessIndex(Type *ElTy, Value *Base,
2718                                         unsigned Dimension, unsigned LastIndex,
2719                                         MDNode *DbgInfo) {
2720     assert(isa<PointerType>(Base->getType()) &&
2721            "Invalid Base ptr type for preserve.array.access.index.");
2722     auto *BaseType = Base->getType();
2723 
2724     Value *LastIndexV = getInt32(LastIndex);
2725     Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
2726     SmallVector<Value *, 4> IdxList;
2727     for (unsigned I = 0; I < Dimension; ++I)
2728       IdxList.push_back(Zero);
2729     IdxList.push_back(LastIndexV);
2730 
2731     Type *ResultType =
2732         GetElementPtrInst::getGEPReturnType(ElTy, Base, IdxList);
2733 
2734     Module *M = BB->getParent()->getParent();
2735     Function *FnPreserveArrayAccessIndex = Intrinsic::getDeclaration(
2736         M, Intrinsic::preserve_array_access_index, {ResultType, BaseType});
2737 
2738     Value *DimV = getInt32(Dimension);
2739     CallInst *Fn =
2740         CreateCall(FnPreserveArrayAccessIndex, {Base, DimV, LastIndexV});
2741     if (DbgInfo)
2742       Fn->setMetadata(LLVMContext::MD_preserve_access_index, DbgInfo);
2743 
2744     return Fn;
2745   }
2746 
2747   Value *CreatePreserveUnionAccessIndex(Value *Base, unsigned FieldIndex,
2748                                         MDNode *DbgInfo) {
2749     assert(isa<PointerType>(Base->getType()) &&
2750            "Invalid Base ptr type for preserve.union.access.index.");
2751     auto *BaseType = Base->getType();
2752 
2753     Module *M = BB->getParent()->getParent();
2754     Function *FnPreserveUnionAccessIndex = Intrinsic::getDeclaration(
2755         M, Intrinsic::preserve_union_access_index, {BaseType, BaseType});
2756 
2757     Value *DIIndex = getInt32(FieldIndex);
2758     CallInst *Fn =
2759         CreateCall(FnPreserveUnionAccessIndex, {Base, DIIndex});
2760     if (DbgInfo)
2761       Fn->setMetadata(LLVMContext::MD_preserve_access_index, DbgInfo);
2762 
2763     return Fn;
2764   }
2765 
2766   Value *CreatePreserveStructAccessIndex(Type *ElTy, Value *Base,
2767                                          unsigned Index, unsigned FieldIndex,
2768                                          MDNode *DbgInfo) {
2769     assert(isa<PointerType>(Base->getType()) &&
2770            "Invalid Base ptr type for preserve.struct.access.index.");
2771     auto *BaseType = Base->getType();
2772 
2773     Value *GEPIndex = getInt32(Index);
2774     Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
2775     Type *ResultType =
2776         GetElementPtrInst::getGEPReturnType(ElTy, Base, {Zero, GEPIndex});
2777 
2778     Module *M = BB->getParent()->getParent();
2779     Function *FnPreserveStructAccessIndex = Intrinsic::getDeclaration(
2780         M, Intrinsic::preserve_struct_access_index, {ResultType, BaseType});
2781 
2782     Value *DIIndex = getInt32(FieldIndex);
2783     CallInst *Fn = CreateCall(FnPreserveStructAccessIndex,
2784                               {Base, GEPIndex, DIIndex});
2785     if (DbgInfo)
2786       Fn->setMetadata(LLVMContext::MD_preserve_access_index, DbgInfo);
2787 
2788     return Fn;
2789   }
2790 
2791 private:
2792   /// Helper function that creates an assume intrinsic call that
2793   /// represents an alignment assumption on the provided Ptr, Mask, Type
2794   /// and Offset. It may be sometimes useful to do some other logic
2795   /// based on this alignment check, thus it can be stored into 'TheCheck'.
2796   CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL,
2797                                             Value *PtrValue, Value *Mask,
2798                                             Type *IntPtrTy, Value *OffsetValue,
2799                                             Value **TheCheck) {
2800     Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2801 
2802     if (OffsetValue) {
2803       bool IsOffsetZero = false;
2804       if (const auto *CI = dyn_cast<ConstantInt>(OffsetValue))
2805         IsOffsetZero = CI->isZero();
2806 
2807       if (!IsOffsetZero) {
2808         if (OffsetValue->getType() != IntPtrTy)
2809           OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
2810                                       "offsetcast");
2811         PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2812       }
2813     }
2814 
2815     Value *Zero = ConstantInt::get(IntPtrTy, 0);
2816     Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
2817     Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2818     if (TheCheck)
2819       *TheCheck = InvCond;
2820 
2821     return CreateAssumption(InvCond);
2822   }
2823 
2824 public:
2825   /// Create an assume intrinsic call that represents an alignment
2826   /// assumption on the provided pointer.
2827   ///
2828   /// An optional offset can be provided, and if it is provided, the offset
2829   /// must be subtracted from the provided pointer to get the pointer with the
2830   /// specified alignment.
2831   ///
2832   /// It may be sometimes useful to do some other logic
2833   /// based on this alignment check, thus it can be stored into 'TheCheck'.
2834   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
2835                                       unsigned Alignment,
2836                                       Value *OffsetValue = nullptr,
2837                                       Value **TheCheck = nullptr) {
2838     assert(isa<PointerType>(PtrValue->getType()) &&
2839            "trying to create an alignment assumption on a non-pointer?");
2840     assert(Alignment != 0 && "Invalid Alignment");
2841     auto *PtrTy = cast<PointerType>(PtrValue->getType());
2842     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
2843 
2844     Value *Mask = ConstantInt::get(IntPtrTy, Alignment - 1);
2845     return CreateAlignmentAssumptionHelper(DL, PtrValue, Mask, IntPtrTy,
2846                                            OffsetValue, TheCheck);
2847   }
2848 
2849   /// Create an assume intrinsic call that represents an alignment
2850   /// assumption on the provided pointer.
2851   ///
2852   /// An optional offset can be provided, and if it is provided, the offset
2853   /// must be subtracted from the provided pointer to get the pointer with the
2854   /// specified alignment.
2855   ///
2856   /// It may be sometimes useful to do some other logic
2857   /// based on this alignment check, thus it can be stored into 'TheCheck'.
2858   ///
2859   /// This overload handles the condition where the Alignment is dependent
2860   /// on an existing value rather than a static value.
2861   CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
2862                                       Value *Alignment,
2863                                       Value *OffsetValue = nullptr,
2864                                       Value **TheCheck = nullptr) {
2865     assert(isa<PointerType>(PtrValue->getType()) &&
2866            "trying to create an alignment assumption on a non-pointer?");
2867     auto *PtrTy = cast<PointerType>(PtrValue->getType());
2868     Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
2869 
2870     if (Alignment->getType() != IntPtrTy)
2871       Alignment = CreateIntCast(Alignment, IntPtrTy, /*isSigned*/ false,
2872                                 "alignmentcast");
2873 
2874     Value *Mask = CreateSub(Alignment, ConstantInt::get(IntPtrTy, 1), "mask");
2875 
2876     return CreateAlignmentAssumptionHelper(DL, PtrValue, Mask, IntPtrTy,
2877                                            OffsetValue, TheCheck);
2878   }
2879 };
2880 
2881 // Create wrappers for C Binding types (see CBindingWrapping.h).
2882 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
2883 
2884 } // end namespace llvm
2885 
2886 #endif // LLVM_IR_IRBUILDER_H
2887