blob: 0af53c5b3f412287dae12c4a51ed432a434bde7b [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the IRBuilder class, which is used as a convenient way
11// to create LLVM instructions with a consistent and simplified interface.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_IRBUILDER_H
16#define LLVM_IR_IRBUILDER_H
17
18#include "llvm-c/Types.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/ConstantFolder.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DebugLoc.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/Operator.h"
39#include "llvm/IR/Type.h"
40#include "llvm/IR/Value.h"
41#include "llvm/IR/ValueHandle.h"
42#include "llvm/Support/AtomicOrdering.h"
43#include "llvm/Support/CBindingWrapping.h"
44#include "llvm/Support/Casting.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <functional>
49#include <utility>
50
51namespace llvm {
52
53class APInt;
54class MDNode;
55class Use;
56
Andrew Scullcdfcccc2018-10-05 20:58:37 +010057/// This provides the default implementation of the IRBuilder
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010058/// 'InsertHelper' method that is called whenever an instruction is created by
59/// IRBuilder and needs to be inserted.
60///
61/// By default, this inserts the instruction at the insertion point.
62class IRBuilderDefaultInserter {
63protected:
64 void InsertHelper(Instruction *I, const Twine &Name,
65 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
66 if (BB) BB->getInstList().insert(InsertPt, I);
67 I->setName(Name);
68 }
69};
70
71/// Provides an 'InsertHelper' that calls a user-provided callback after
72/// performing the default insertion.
73class IRBuilderCallbackInserter : IRBuilderDefaultInserter {
74 std::function<void(Instruction *)> Callback;
75
76public:
77 IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
78 : Callback(std::move(Callback)) {}
79
80protected:
81 void InsertHelper(Instruction *I, const Twine &Name,
82 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
83 IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
84 Callback(I);
85 }
86};
87
Andrew Scullcdfcccc2018-10-05 20:58:37 +010088/// Common base class shared among various IRBuilders.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010089class IRBuilderBase {
90 DebugLoc CurDbgLocation;
91
92protected:
93 BasicBlock *BB;
94 BasicBlock::iterator InsertPt;
95 LLVMContext &Context;
96
97 MDNode *DefaultFPMathTag;
98 FastMathFlags FMF;
99
100 ArrayRef<OperandBundleDef> DefaultOperandBundles;
101
102public:
103 IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr,
104 ArrayRef<OperandBundleDef> OpBundles = None)
105 : Context(context), DefaultFPMathTag(FPMathTag),
106 DefaultOperandBundles(OpBundles) {
107 ClearInsertionPoint();
108 }
109
110 //===--------------------------------------------------------------------===//
111 // Builder configuration methods
112 //===--------------------------------------------------------------------===//
113
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100114 /// Clear the insertion point: created instructions will not be
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100115 /// inserted into a block.
116 void ClearInsertionPoint() {
117 BB = nullptr;
118 InsertPt = BasicBlock::iterator();
119 }
120
121 BasicBlock *GetInsertBlock() const { return BB; }
122 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
123 LLVMContext &getContext() const { return Context; }
124
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100125 /// This specifies that created instructions should be appended to the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100126 /// end of the specified block.
127 void SetInsertPoint(BasicBlock *TheBB) {
128 BB = TheBB;
129 InsertPt = BB->end();
130 }
131
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100132 /// This specifies that created instructions should be inserted before
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100133 /// the specified instruction.
134 void SetInsertPoint(Instruction *I) {
135 BB = I->getParent();
136 InsertPt = I->getIterator();
137 assert(InsertPt != BB->end() && "Can't read debug loc from end()");
138 SetCurrentDebugLocation(I->getDebugLoc());
139 }
140
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100141 /// This specifies that created instructions should be inserted at the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100142 /// specified point.
143 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
144 BB = TheBB;
145 InsertPt = IP;
146 if (IP != TheBB->end())
147 SetCurrentDebugLocation(IP->getDebugLoc());
148 }
149
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100150 /// Set location information used by debugging information.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100151 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
152
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100153 /// Get location information used by debugging information.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100154 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
155
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100156 /// If this builder has a current debug location, set it on the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100157 /// specified instruction.
158 void SetInstDebugLocation(Instruction *I) const {
159 if (CurDbgLocation)
160 I->setDebugLoc(CurDbgLocation);
161 }
162
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100163 /// Get the return type of the current function that we're emitting
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100164 /// into.
165 Type *getCurrentFunctionReturnType() const;
166
167 /// InsertPoint - A saved insertion point.
168 class InsertPoint {
169 BasicBlock *Block = nullptr;
170 BasicBlock::iterator Point;
171
172 public:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100173 /// Creates a new insertion point which doesn't point to anything.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100174 InsertPoint() = default;
175
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100176 /// Creates a new insertion point at the given location.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100177 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
178 : Block(InsertBlock), Point(InsertPoint) {}
179
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100180 /// Returns true if this insert point is set.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100181 bool isSet() const { return (Block != nullptr); }
182
183 BasicBlock *getBlock() const { return Block; }
184 BasicBlock::iterator getPoint() const { return Point; }
185 };
186
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100187 /// Returns the current insert point.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100188 InsertPoint saveIP() const {
189 return InsertPoint(GetInsertBlock(), GetInsertPoint());
190 }
191
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100192 /// Returns the current insert point, clearing it in the process.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100193 InsertPoint saveAndClearIP() {
194 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
195 ClearInsertionPoint();
196 return IP;
197 }
198
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100199 /// Sets the current insert point to a previously-saved location.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100200 void restoreIP(InsertPoint IP) {
201 if (IP.isSet())
202 SetInsertPoint(IP.getBlock(), IP.getPoint());
203 else
204 ClearInsertionPoint();
205 }
206
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100207 /// Get the floating point math metadata being used.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100208 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
209
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100210 /// Get the flags to be applied to created floating point ops
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100211 FastMathFlags getFastMathFlags() const { return FMF; }
212
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100213 /// Clear the fast-math flags.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100214 void clearFastMathFlags() { FMF.clear(); }
215
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100216 /// Set the floating point math metadata to be used.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100217 void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
218
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100219 /// Set the fast-math flags to be used with generated fp-math operators
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100220 void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
221
222 //===--------------------------------------------------------------------===//
223 // RAII helpers.
224 //===--------------------------------------------------------------------===//
225
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100226 // RAII object that stores the current insertion point and restores it
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100227 // when the object is destroyed. This includes the debug location.
228 class InsertPointGuard {
229 IRBuilderBase &Builder;
230 AssertingVH<BasicBlock> Block;
231 BasicBlock::iterator Point;
232 DebugLoc DbgLoc;
233
234 public:
235 InsertPointGuard(IRBuilderBase &B)
236 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
237 DbgLoc(B.getCurrentDebugLocation()) {}
238
239 InsertPointGuard(const InsertPointGuard &) = delete;
240 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
241
242 ~InsertPointGuard() {
243 Builder.restoreIP(InsertPoint(Block, Point));
244 Builder.SetCurrentDebugLocation(DbgLoc);
245 }
246 };
247
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100248 // RAII object that stores the current fast math settings and restores
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100249 // them when the object is destroyed.
250 class FastMathFlagGuard {
251 IRBuilderBase &Builder;
252 FastMathFlags FMF;
253 MDNode *FPMathTag;
254
255 public:
256 FastMathFlagGuard(IRBuilderBase &B)
257 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
258
259 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
260 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
261
262 ~FastMathFlagGuard() {
263 Builder.FMF = FMF;
264 Builder.DefaultFPMathTag = FPMathTag;
265 }
266 };
267
268 //===--------------------------------------------------------------------===//
269 // Miscellaneous creation methods.
270 //===--------------------------------------------------------------------===//
271
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100272 /// Make a new global variable with initializer type i8*
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100273 ///
274 /// Make a new global variable with an initializer that has array of i8 type
275 /// filled in with the null terminated string value specified. The new global
276 /// variable will be marked mergable with any others of the same contents. If
277 /// Name is specified, it is the name of the global variable created.
278 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
279 unsigned AddressSpace = 0);
280
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100281 /// Get a constant value representing either true or false.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100282 ConstantInt *getInt1(bool V) {
283 return ConstantInt::get(getInt1Ty(), V);
284 }
285
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100286 /// Get the constant value for i1 true.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100287 ConstantInt *getTrue() {
288 return ConstantInt::getTrue(Context);
289 }
290
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100291 /// Get the constant value for i1 false.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100292 ConstantInt *getFalse() {
293 return ConstantInt::getFalse(Context);
294 }
295
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100296 /// Get a constant 8-bit value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100297 ConstantInt *getInt8(uint8_t C) {
298 return ConstantInt::get(getInt8Ty(), C);
299 }
300
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100301 /// Get a constant 16-bit value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100302 ConstantInt *getInt16(uint16_t C) {
303 return ConstantInt::get(getInt16Ty(), C);
304 }
305
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100306 /// Get a constant 32-bit value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100307 ConstantInt *getInt32(uint32_t C) {
308 return ConstantInt::get(getInt32Ty(), C);
309 }
310
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100311 /// Get a constant 64-bit value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100312 ConstantInt *getInt64(uint64_t C) {
313 return ConstantInt::get(getInt64Ty(), C);
314 }
315
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100316 /// Get a constant N-bit value, zero extended or truncated from
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100317 /// a 64-bit value.
318 ConstantInt *getIntN(unsigned N, uint64_t C) {
319 return ConstantInt::get(getIntNTy(N), C);
320 }
321
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100322 /// Get a constant integer value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100323 ConstantInt *getInt(const APInt &AI) {
324 return ConstantInt::get(Context, AI);
325 }
326
327 //===--------------------------------------------------------------------===//
328 // Type creation methods
329 //===--------------------------------------------------------------------===//
330
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100331 /// Fetch the type representing a single bit
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100332 IntegerType *getInt1Ty() {
333 return Type::getInt1Ty(Context);
334 }
335
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100336 /// Fetch the type representing an 8-bit integer.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100337 IntegerType *getInt8Ty() {
338 return Type::getInt8Ty(Context);
339 }
340
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100341 /// Fetch the type representing a 16-bit integer.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100342 IntegerType *getInt16Ty() {
343 return Type::getInt16Ty(Context);
344 }
345
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100346 /// Fetch the type representing a 32-bit integer.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100347 IntegerType *getInt32Ty() {
348 return Type::getInt32Ty(Context);
349 }
350
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100351 /// Fetch the type representing a 64-bit integer.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100352 IntegerType *getInt64Ty() {
353 return Type::getInt64Ty(Context);
354 }
355
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100356 /// Fetch the type representing a 128-bit integer.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100357 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
358
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100359 /// Fetch the type representing an N-bit integer.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100360 IntegerType *getIntNTy(unsigned N) {
361 return Type::getIntNTy(Context, N);
362 }
363
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100364 /// Fetch the type representing a 16-bit floating point value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100365 Type *getHalfTy() {
366 return Type::getHalfTy(Context);
367 }
368
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100369 /// Fetch the type representing a 32-bit floating point value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100370 Type *getFloatTy() {
371 return Type::getFloatTy(Context);
372 }
373
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100374 /// Fetch the type representing a 64-bit floating point value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100375 Type *getDoubleTy() {
376 return Type::getDoubleTy(Context);
377 }
378
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100379 /// Fetch the type representing void.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100380 Type *getVoidTy() {
381 return Type::getVoidTy(Context);
382 }
383
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100384 /// Fetch the type representing a pointer to an 8-bit integer value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100385 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
386 return Type::getInt8PtrTy(Context, AddrSpace);
387 }
388
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100389 /// Fetch the type representing a pointer to an integer value.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100390 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
391 return DL.getIntPtrType(Context, AddrSpace);
392 }
393
394 //===--------------------------------------------------------------------===//
395 // Intrinsic creation methods
396 //===--------------------------------------------------------------------===//
397
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100398 /// Create and insert a memset to the specified pointer and the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100399 /// specified value.
400 ///
401 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
402 /// specified, it will be added to the instruction. Likewise with alias.scope
403 /// and noalias tags.
404 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
405 bool isVolatile = false, MDNode *TBAATag = nullptr,
406 MDNode *ScopeTag = nullptr,
407 MDNode *NoAliasTag = nullptr) {
408 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
409 TBAATag, ScopeTag, NoAliasTag);
410 }
411
412 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
413 bool isVolatile = false, MDNode *TBAATag = nullptr,
414 MDNode *ScopeTag = nullptr,
415 MDNode *NoAliasTag = nullptr);
416
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100417 /// Create and insert an element unordered-atomic memset of the region of
418 /// memory starting at the given pointer to the given value.
419 ///
420 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
421 /// specified, it will be added to the instruction. Likewise with alias.scope
422 /// and noalias tags.
423 CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
424 uint64_t Size, unsigned Align,
425 uint32_t ElementSize,
426 MDNode *TBAATag = nullptr,
427 MDNode *ScopeTag = nullptr,
428 MDNode *NoAliasTag = nullptr) {
429 return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size), Align,
430 ElementSize, TBAATag, ScopeTag,
431 NoAliasTag);
432 }
433
434 CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
435 Value *Size, unsigned Align,
436 uint32_t ElementSize,
437 MDNode *TBAATag = nullptr,
438 MDNode *ScopeTag = nullptr,
439 MDNode *NoAliasTag = nullptr);
440
441 /// Create and insert a memcpy between the specified pointers.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100442 ///
443 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
444 /// specified, it will be added to the instruction. Likewise with alias.scope
445 /// and noalias tags.
446 CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,
447 unsigned SrcAlign, uint64_t Size,
448 bool isVolatile = false, MDNode *TBAATag = nullptr,
449 MDNode *TBAAStructTag = nullptr,
450 MDNode *ScopeTag = nullptr,
451 MDNode *NoAliasTag = nullptr) {
452 return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
453 isVolatile, TBAATag, TBAAStructTag, ScopeTag,
454 NoAliasTag);
455 }
456
457 CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,
458 unsigned SrcAlign, Value *Size,
459 bool isVolatile = false, MDNode *TBAATag = nullptr,
460 MDNode *TBAAStructTag = nullptr,
461 MDNode *ScopeTag = nullptr,
462 MDNode *NoAliasTag = nullptr);
463
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100464 /// Create and insert an element unordered-atomic memcpy between the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100465 /// specified pointers.
466 ///
467 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, respectively.
468 ///
469 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
470 /// specified, it will be added to the instruction. Likewise with alias.scope
471 /// and noalias tags.
472 CallInst *CreateElementUnorderedAtomicMemCpy(
473 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
474 uint64_t Size, uint32_t ElementSize, MDNode *TBAATag = nullptr,
475 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
476 MDNode *NoAliasTag = nullptr) {
477 return CreateElementUnorderedAtomicMemCpy(
478 Dst, DstAlign, Src, SrcAlign, getInt64(Size), ElementSize, TBAATag,
479 TBAAStructTag, ScopeTag, NoAliasTag);
480 }
481
482 CallInst *CreateElementUnorderedAtomicMemCpy(
483 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size,
484 uint32_t ElementSize, MDNode *TBAATag = nullptr,
485 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
486 MDNode *NoAliasTag = nullptr);
487
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100488 /// Create and insert a memmove between the specified
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100489 /// pointers.
490 ///
491 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
492 /// specified, it will be added to the instruction. Likewise with alias.scope
493 /// and noalias tags.
494 CallInst *CreateMemMove(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
495 uint64_t Size, bool isVolatile = false,
496 MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr,
497 MDNode *NoAliasTag = nullptr) {
498 return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size), isVolatile,
499 TBAATag, ScopeTag, NoAliasTag);
500 }
501
502 CallInst *CreateMemMove(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
503 Value *Size, bool isVolatile = false, MDNode *TBAATag = nullptr,
504 MDNode *ScopeTag = nullptr,
505 MDNode *NoAliasTag = nullptr);
506
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100507 /// \brief Create and insert an element unordered-atomic memmove between the
508 /// specified pointers.
509 ///
510 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers,
511 /// respectively.
512 ///
513 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
514 /// specified, it will be added to the instruction. Likewise with alias.scope
515 /// and noalias tags.
516 CallInst *CreateElementUnorderedAtomicMemMove(
517 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
518 uint64_t Size, uint32_t ElementSize, MDNode *TBAATag = nullptr,
519 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
520 MDNode *NoAliasTag = nullptr) {
521 return CreateElementUnorderedAtomicMemMove(
522 Dst, DstAlign, Src, SrcAlign, getInt64(Size), ElementSize, TBAATag,
523 TBAAStructTag, ScopeTag, NoAliasTag);
524 }
525
526 CallInst *CreateElementUnorderedAtomicMemMove(
527 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size,
528 uint32_t ElementSize, MDNode *TBAATag = nullptr,
529 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
530 MDNode *NoAliasTag = nullptr);
531
532 /// Create a vector fadd reduction intrinsic of the source vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100533 /// The first parameter is a scalar accumulator value for ordered reductions.
534 CallInst *CreateFAddReduce(Value *Acc, Value *Src);
535
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100536 /// Create a vector fmul reduction intrinsic of the source vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100537 /// The first parameter is a scalar accumulator value for ordered reductions.
538 CallInst *CreateFMulReduce(Value *Acc, Value *Src);
539
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100540 /// Create a vector int add reduction intrinsic of the source vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100541 CallInst *CreateAddReduce(Value *Src);
542
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100543 /// Create a vector int mul reduction intrinsic of the source vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100544 CallInst *CreateMulReduce(Value *Src);
545
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100546 /// Create a vector int AND reduction intrinsic of the source vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100547 CallInst *CreateAndReduce(Value *Src);
548
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100549 /// Create a vector int OR reduction intrinsic of the source vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100550 CallInst *CreateOrReduce(Value *Src);
551
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100552 /// Create a vector int XOR reduction intrinsic of the source vector.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100553 CallInst *CreateXorReduce(Value *Src);
554
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100555 /// Create a vector integer max reduction intrinsic of the source
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100556 /// vector.
557 CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
558
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100559 /// Create a vector integer min reduction intrinsic of the source
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100560 /// vector.
561 CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
562
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100563 /// Create a vector float max reduction intrinsic of the source
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100564 /// vector.
565 CallInst *CreateFPMaxReduce(Value *Src, bool NoNaN = false);
566
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100567 /// Create a vector float min reduction intrinsic of the source
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100568 /// vector.
569 CallInst *CreateFPMinReduce(Value *Src, bool NoNaN = false);
570
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100571 /// Create a lifetime.start intrinsic.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100572 ///
573 /// If the pointer isn't i8* it will be converted.
574 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
575
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100576 /// Create a lifetime.end intrinsic.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100577 ///
578 /// If the pointer isn't i8* it will be converted.
579 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
580
581 /// Create a call to invariant.start intrinsic.
582 ///
583 /// If the pointer isn't i8* it will be converted.
584 CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
585
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100586 /// Create a call to Masked Load intrinsic
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100587 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
588 Value *PassThru = nullptr, const Twine &Name = "");
589
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100590 /// Create a call to Masked Store intrinsic
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100591 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
592 Value *Mask);
593
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100594 /// Create a call to Masked Gather intrinsic
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100595 CallInst *CreateMaskedGather(Value *Ptrs, unsigned Align,
596 Value *Mask = nullptr,
597 Value *PassThru = nullptr,
598 const Twine& Name = "");
599
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100600 /// Create a call to Masked Scatter intrinsic
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100601 CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Align,
602 Value *Mask = nullptr);
603
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100604 /// Create an assume intrinsic call that allows the optimizer to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100605 /// assume that the provided condition will be true.
606 CallInst *CreateAssumption(Value *Cond);
607
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100608 /// Create a call to the experimental.gc.statepoint intrinsic to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100609 /// start a new statepoint sequence.
610 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
611 Value *ActualCallee,
612 ArrayRef<Value *> CallArgs,
613 ArrayRef<Value *> DeoptArgs,
614 ArrayRef<Value *> GCArgs,
615 const Twine &Name = "");
616
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100617 /// Create a call to the experimental.gc.statepoint intrinsic to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100618 /// start a new statepoint sequence.
619 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
620 Value *ActualCallee, uint32_t Flags,
621 ArrayRef<Use> CallArgs,
622 ArrayRef<Use> TransitionArgs,
623 ArrayRef<Use> DeoptArgs,
624 ArrayRef<Value *> GCArgs,
625 const Twine &Name = "");
626
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100627 /// Conveninence function for the common case when CallArgs are filled
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100628 /// in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
629 /// .get()'ed to get the Value pointer.
630 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
631 Value *ActualCallee, ArrayRef<Use> CallArgs,
632 ArrayRef<Value *> DeoptArgs,
633 ArrayRef<Value *> GCArgs,
634 const Twine &Name = "");
635
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100636 /// Create an invoke to the experimental.gc.statepoint intrinsic to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100637 /// start a new statepoint sequence.
638 InvokeInst *
639 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
640 Value *ActualInvokee, BasicBlock *NormalDest,
641 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
642 ArrayRef<Value *> DeoptArgs,
643 ArrayRef<Value *> GCArgs, const Twine &Name = "");
644
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100645 /// Create an invoke to the experimental.gc.statepoint intrinsic to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100646 /// start a new statepoint sequence.
647 InvokeInst *CreateGCStatepointInvoke(
648 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
649 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
650 ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
651 ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
652 const Twine &Name = "");
653
Andrew Scull0372a572018-11-16 15:47:06 +0000654 // Convenience function for the common case when CallArgs are filled in using
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100655 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
656 // get the Value *.
657 InvokeInst *
658 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
659 Value *ActualInvokee, BasicBlock *NormalDest,
660 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
661 ArrayRef<Value *> DeoptArgs,
662 ArrayRef<Value *> GCArgs, const Twine &Name = "");
663
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100664 /// Create a call to the experimental.gc.result intrinsic to extract
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100665 /// the result from a call wrapped in a statepoint.
666 CallInst *CreateGCResult(Instruction *Statepoint,
667 Type *ResultType,
668 const Twine &Name = "");
669
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100670 /// Create a call to the experimental.gc.relocate intrinsics to
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100671 /// project the relocated value of one pointer from the statepoint.
672 CallInst *CreateGCRelocate(Instruction *Statepoint,
673 int BaseOffset,
674 int DerivedOffset,
675 Type *ResultType,
676 const Twine &Name = "");
677
Andrew Scull0372a572018-11-16 15:47:06 +0000678 /// Create a call to intrinsic \p ID with 1 operand which is mangled on its
679 /// type.
680 CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
681 Instruction *FMFSource = nullptr,
682 const Twine &Name = "");
683
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100684 /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
685 /// first type.
Andrew Scull0372a572018-11-16 15:47:06 +0000686 CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS,
687 Instruction *FMFSource = nullptr,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100688 const Twine &Name = "");
689
Andrew Scull0372a572018-11-16 15:47:06 +0000690 /// Create a call to intrinsic \p ID with \p args, mangled using \p Types. If
691 /// \p FMFSource is provided, copy fast-math-flags from that instruction to
692 /// the intrinsic.
693 CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types,
694 ArrayRef<Value *> Args,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100695 Instruction *FMFSource = nullptr,
696 const Twine &Name = "");
697
698 /// Create call to the minnum intrinsic.
699 CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
Andrew Scull0372a572018-11-16 15:47:06 +0000700 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100701 }
702
703 /// Create call to the maxnum intrinsic.
704 CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
Andrew Scull0372a572018-11-16 15:47:06 +0000705 return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100706 }
707
708private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100709 /// Create a call to a masked intrinsic with given Id.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100710 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
711 ArrayRef<Type *> OverloadedTypes,
712 const Twine &Name = "");
713
714 Value *getCastedInt8PtrValue(Value *Ptr);
715};
716
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100717/// This provides a uniform API for creating instructions and inserting
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100718/// them into a basic block: either at the end of a BasicBlock, or at a specific
719/// iterator location in a block.
720///
721/// Note that the builder does not expose the full generality of LLVM
722/// instructions. For access to extra instruction properties, use the mutators
723/// (e.g. setVolatile) on the instructions after they have been
724/// created. Convenience state exists to specify fast-math flags and fp-math
725/// tags.
726///
727/// The first template argument specifies a class to use for creating constants.
728/// This defaults to creating minimally folded constants. The second template
729/// argument allows clients to specify custom insertion hooks that are called on
730/// every newly created insertion.
731template <typename T = ConstantFolder,
732 typename Inserter = IRBuilderDefaultInserter>
733class IRBuilder : public IRBuilderBase, public Inserter {
734 T Folder;
735
736public:
737 IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
738 MDNode *FPMathTag = nullptr,
739 ArrayRef<OperandBundleDef> OpBundles = None)
740 : IRBuilderBase(C, FPMathTag, OpBundles), Inserter(std::move(I)),
741 Folder(F) {}
742
743 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
744 ArrayRef<OperandBundleDef> OpBundles = None)
745 : IRBuilderBase(C, FPMathTag, OpBundles) {}
746
747 explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr,
748 ArrayRef<OperandBundleDef> OpBundles = None)
749 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
750 SetInsertPoint(TheBB);
751 }
752
753 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
754 ArrayRef<OperandBundleDef> OpBundles = None)
755 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles) {
756 SetInsertPoint(TheBB);
757 }
758
759 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
760 ArrayRef<OperandBundleDef> OpBundles = None)
761 : IRBuilderBase(IP->getContext(), FPMathTag, OpBundles) {
762 SetInsertPoint(IP);
763 }
764
765 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T &F,
766 MDNode *FPMathTag = nullptr,
767 ArrayRef<OperandBundleDef> OpBundles = None)
768 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
769 SetInsertPoint(TheBB, IP);
770 }
771
772 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
773 MDNode *FPMathTag = nullptr,
774 ArrayRef<OperandBundleDef> OpBundles = None)
775 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles) {
776 SetInsertPoint(TheBB, IP);
777 }
778
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100779 /// Get the constant folder being used.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100780 const T &getFolder() { return Folder; }
781
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100782 /// Insert and return the specified instruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100783 template<typename InstTy>
784 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
785 this->InsertHelper(I, Name, BB, InsertPt);
786 this->SetInstDebugLocation(I);
787 return I;
788 }
789
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100790 /// No-op overload to handle constants.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100791 Constant *Insert(Constant *C, const Twine& = "") const {
792 return C;
793 }
794
795 //===--------------------------------------------------------------------===//
796 // Instruction creation methods: Terminators
797 //===--------------------------------------------------------------------===//
798
799private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100800 /// Helper to add branch weight and unpredictable metadata onto an
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100801 /// instruction.
802 /// \returns The annotated instruction.
803 template <typename InstTy>
804 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
805 if (Weights)
806 I->setMetadata(LLVMContext::MD_prof, Weights);
807 if (Unpredictable)
808 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
809 return I;
810 }
811
812public:
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100813 /// Create a 'ret void' instruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100814 ReturnInst *CreateRetVoid() {
815 return Insert(ReturnInst::Create(Context));
816 }
817
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100818 /// Create a 'ret <val>' instruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100819 ReturnInst *CreateRet(Value *V) {
820 return Insert(ReturnInst::Create(Context, V));
821 }
822
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100823 /// Create a sequence of N insertvalue instructions,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100824 /// with one Value from the retVals array each, that build a aggregate
825 /// return value one value at a time, and a ret instruction to return
826 /// the resulting aggregate value.
827 ///
828 /// This is a convenience function for code that uses aggregate return values
829 /// as a vehicle for having multiple return values.
830 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
831 Value *V = UndefValue::get(getCurrentFunctionReturnType());
832 for (unsigned i = 0; i != N; ++i)
833 V = CreateInsertValue(V, retVals[i], i, "mrv");
834 return Insert(ReturnInst::Create(Context, V));
835 }
836
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100837 /// Create an unconditional 'br label X' instruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100838 BranchInst *CreateBr(BasicBlock *Dest) {
839 return Insert(BranchInst::Create(Dest));
840 }
841
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100842 /// Create a conditional 'br Cond, TrueDest, FalseDest'
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100843 /// instruction.
844 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
845 MDNode *BranchWeights = nullptr,
846 MDNode *Unpredictable = nullptr) {
847 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
848 BranchWeights, Unpredictable));
849 }
850
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100851 /// Create a conditional 'br Cond, TrueDest, FalseDest'
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100852 /// instruction. Copy branch meta data if available.
853 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
854 Instruction *MDSrc) {
855 BranchInst *Br = BranchInst::Create(True, False, Cond);
856 if (MDSrc) {
857 unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
858 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
859 Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
860 }
861 return Insert(Br);
862 }
863
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100864 /// Create a switch instruction with the specified value, default dest,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100865 /// and with a hint for the number of cases that will be added (for efficient
866 /// allocation).
867 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
868 MDNode *BranchWeights = nullptr,
869 MDNode *Unpredictable = nullptr) {
870 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
871 BranchWeights, Unpredictable));
872 }
873
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100874 /// Create an indirect branch instruction with the specified address
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100875 /// operand, with an optional hint for the number of destinations that will be
876 /// added (for efficient allocation).
877 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
878 return Insert(IndirectBrInst::Create(Addr, NumDests));
879 }
880
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100881 /// Create an invoke instruction.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100882 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
883 BasicBlock *UnwindDest,
884 ArrayRef<Value *> Args = None,
885 const Twine &Name = "") {
886 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
887 Name);
888 }
889 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
890 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
891 ArrayRef<OperandBundleDef> OpBundles,
892 const Twine &Name = "") {
893 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args,
894 OpBundles), Name);
895 }
896
897 ResumeInst *CreateResume(Value *Exn) {
898 return Insert(ResumeInst::Create(Exn));
899 }
900
901 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
902 BasicBlock *UnwindBB = nullptr) {
903 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
904 }
905
906 CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
907 unsigned NumHandlers,
908 const Twine &Name = "") {
909 return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
910 Name);
911 }
912
913 CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
914 const Twine &Name = "") {
915 return Insert(CatchPadInst::Create(ParentPad, Args), Name);
916 }
917
918 CleanupPadInst *CreateCleanupPad(Value *ParentPad,
919 ArrayRef<Value *> Args = None,
920 const Twine &Name = "") {
921 return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
922 }
923
924 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
925 return Insert(CatchReturnInst::Create(CatchPad, BB));
926 }
927
928 UnreachableInst *CreateUnreachable() {
929 return Insert(new UnreachableInst(Context));
930 }
931
932 //===--------------------------------------------------------------------===//
933 // Instruction creation methods: Binary Operators
934 //===--------------------------------------------------------------------===//
935private:
936 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
937 Value *LHS, Value *RHS,
938 const Twine &Name,
939 bool HasNUW, bool HasNSW) {
940 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
941 if (HasNUW) BO->setHasNoUnsignedWrap();
942 if (HasNSW) BO->setHasNoSignedWrap();
943 return BO;
944 }
945
946 Instruction *setFPAttrs(Instruction *I, MDNode *FPMD,
947 FastMathFlags FMF) const {
948 if (!FPMD)
949 FPMD = DefaultFPMathTag;
950 if (FPMD)
951 I->setMetadata(LLVMContext::MD_fpmath, FPMD);
952 I->setFastMathFlags(FMF);
953 return I;
954 }
955
956 Value *foldConstant(Instruction::BinaryOps Opc, Value *L,
957 Value *R, const Twine &Name = nullptr) const {
958 auto *LC = dyn_cast<Constant>(L);
959 auto *RC = dyn_cast<Constant>(R);
960 return (LC && RC) ? Insert(Folder.CreateBinOp(Opc, LC, RC), Name) : nullptr;
961 }
962
963public:
964 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
965 bool HasNUW = false, bool HasNSW = false) {
966 if (auto *LC = dyn_cast<Constant>(LHS))
967 if (auto *RC = dyn_cast<Constant>(RHS))
968 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
969 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
970 HasNUW, HasNSW);
971 }
972
973 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
974 return CreateAdd(LHS, RHS, Name, false, true);
975 }
976
977 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
978 return CreateAdd(LHS, RHS, Name, true, false);
979 }
980
981 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
982 bool HasNUW = false, bool HasNSW = false) {
983 if (auto *LC = dyn_cast<Constant>(LHS))
984 if (auto *RC = dyn_cast<Constant>(RHS))
985 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
986 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
987 HasNUW, HasNSW);
988 }
989
990 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
991 return CreateSub(LHS, RHS, Name, false, true);
992 }
993
994 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
995 return CreateSub(LHS, RHS, Name, true, false);
996 }
997
998 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
999 bool HasNUW = false, bool HasNSW = false) {
1000 if (auto *LC = dyn_cast<Constant>(LHS))
1001 if (auto *RC = dyn_cast<Constant>(RHS))
1002 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
1003 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
1004 HasNUW, HasNSW);
1005 }
1006
1007 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1008 return CreateMul(LHS, RHS, Name, false, true);
1009 }
1010
1011 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1012 return CreateMul(LHS, RHS, Name, true, false);
1013 }
1014
1015 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1016 bool isExact = false) {
1017 if (auto *LC = dyn_cast<Constant>(LHS))
1018 if (auto *RC = dyn_cast<Constant>(RHS))
1019 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
1020 if (!isExact)
1021 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
1022 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
1023 }
1024
1025 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1026 return CreateUDiv(LHS, RHS, Name, true);
1027 }
1028
1029 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1030 bool isExact = false) {
1031 if (auto *LC = dyn_cast<Constant>(LHS))
1032 if (auto *RC = dyn_cast<Constant>(RHS))
1033 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
1034 if (!isExact)
1035 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
1036 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
1037 }
1038
1039 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1040 return CreateSDiv(LHS, RHS, Name, true);
1041 }
1042
1043 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
1044 if (Value *V = foldConstant(Instruction::URem, LHS, RHS, Name)) return V;
1045 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
1046 }
1047
1048 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
1049 if (Value *V = foldConstant(Instruction::SRem, LHS, RHS, Name)) return V;
1050 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
1051 }
1052
1053 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
1054 bool HasNUW = false, bool HasNSW = false) {
1055 if (auto *LC = dyn_cast<Constant>(LHS))
1056 if (auto *RC = dyn_cast<Constant>(RHS))
1057 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
1058 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
1059 HasNUW, HasNSW);
1060 }
1061
1062 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
1063 bool HasNUW = false, bool HasNSW = false) {
1064 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1065 HasNUW, HasNSW);
1066 }
1067
1068 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
1069 bool HasNUW = false, bool HasNSW = false) {
1070 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1071 HasNUW, HasNSW);
1072 }
1073
1074 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
1075 bool isExact = false) {
1076 if (auto *LC = dyn_cast<Constant>(LHS))
1077 if (auto *RC = dyn_cast<Constant>(RHS))
1078 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
1079 if (!isExact)
1080 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
1081 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
1082 }
1083
1084 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1085 bool isExact = false) {
1086 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1087 }
1088
1089 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1090 bool isExact = false) {
1091 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1092 }
1093
1094 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
1095 bool isExact = false) {
1096 if (auto *LC = dyn_cast<Constant>(LHS))
1097 if (auto *RC = dyn_cast<Constant>(RHS))
1098 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
1099 if (!isExact)
1100 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
1101 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
1102 }
1103
1104 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1105 bool isExact = false) {
1106 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1107 }
1108
1109 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1110 bool isExact = false) {
1111 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1112 }
1113
1114 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
1115 if (auto *RC = dyn_cast<Constant>(RHS)) {
1116 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isMinusOne())
1117 return LHS; // LHS & -1 -> LHS
1118 if (auto *LC = dyn_cast<Constant>(LHS))
1119 return Insert(Folder.CreateAnd(LC, RC), Name);
1120 }
1121 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
1122 }
1123
1124 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1125 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1126 }
1127
1128 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1129 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1130 }
1131
1132 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
1133 if (auto *RC = dyn_cast<Constant>(RHS)) {
1134 if (RC->isNullValue())
1135 return LHS; // LHS | 0 -> LHS
1136 if (auto *LC = dyn_cast<Constant>(LHS))
1137 return Insert(Folder.CreateOr(LC, RC), Name);
1138 }
1139 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
1140 }
1141
1142 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1143 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1144 }
1145
1146 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1147 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1148 }
1149
1150 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
1151 if (Value *V = foldConstant(Instruction::Xor, LHS, RHS, Name)) return V;
1152 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
1153 }
1154
1155 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1156 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1157 }
1158
1159 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1160 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1161 }
1162
1163 Value *CreateFAdd(Value *L, Value *R, const Twine &Name = "",
1164 MDNode *FPMD = nullptr) {
1165 if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1166 Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), FPMD, FMF);
1167 return Insert(I, Name);
1168 }
1169
1170 /// Copy fast-math-flags from an instruction rather than using the builder's
1171 /// default FMF.
1172 Value *CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource,
1173 const Twine &Name = "") {
1174 if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1175 Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), nullptr,
1176 FMFSource->getFastMathFlags());
1177 return Insert(I, Name);
1178 }
1179
1180 Value *CreateFSub(Value *L, Value *R, const Twine &Name = "",
1181 MDNode *FPMD = nullptr) {
1182 if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1183 Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), FPMD, FMF);
1184 return Insert(I, Name);
1185 }
1186
1187 /// Copy fast-math-flags from an instruction rather than using the builder's
1188 /// default FMF.
1189 Value *CreateFSubFMF(Value *L, Value *R, Instruction *FMFSource,
1190 const Twine &Name = "") {
1191 if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1192 Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), nullptr,
1193 FMFSource->getFastMathFlags());
1194 return Insert(I, Name);
1195 }
1196
1197 Value *CreateFMul(Value *L, Value *R, const Twine &Name = "",
1198 MDNode *FPMD = nullptr) {
1199 if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1200 Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), FPMD, FMF);
1201 return Insert(I, Name);
1202 }
1203
1204 /// Copy fast-math-flags from an instruction rather than using the builder's
1205 /// default FMF.
1206 Value *CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource,
1207 const Twine &Name = "") {
1208 if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1209 Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), nullptr,
1210 FMFSource->getFastMathFlags());
1211 return Insert(I, Name);
1212 }
1213
1214 Value *CreateFDiv(Value *L, Value *R, const Twine &Name = "",
1215 MDNode *FPMD = nullptr) {
1216 if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1217 Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), FPMD, FMF);
1218 return Insert(I, Name);
1219 }
1220
1221 /// Copy fast-math-flags from an instruction rather than using the builder's
1222 /// default FMF.
1223 Value *CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource,
1224 const Twine &Name = "") {
1225 if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1226 Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), nullptr,
1227 FMFSource->getFastMathFlags());
1228 return Insert(I, Name);
1229 }
1230
1231 Value *CreateFRem(Value *L, Value *R, const Twine &Name = "",
1232 MDNode *FPMD = nullptr) {
1233 if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1234 Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), FPMD, FMF);
1235 return Insert(I, Name);
1236 }
1237
1238 /// Copy fast-math-flags from an instruction rather than using the builder's
1239 /// default FMF.
1240 Value *CreateFRemFMF(Value *L, Value *R, Instruction *FMFSource,
1241 const Twine &Name = "") {
1242 if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1243 Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), nullptr,
1244 FMFSource->getFastMathFlags());
1245 return Insert(I, Name);
1246 }
1247
1248 Value *CreateBinOp(Instruction::BinaryOps Opc,
1249 Value *LHS, Value *RHS, const Twine &Name = "",
1250 MDNode *FPMathTag = nullptr) {
1251 if (Value *V = foldConstant(Opc, LHS, RHS, Name)) return V;
1252 Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
1253 if (isa<FPMathOperator>(BinOp))
1254 BinOp = setFPAttrs(BinOp, FPMathTag, FMF);
1255 return Insert(BinOp, Name);
1256 }
1257
1258 Value *CreateNeg(Value *V, const Twine &Name = "",
1259 bool HasNUW = false, bool HasNSW = false) {
1260 if (auto *VC = dyn_cast<Constant>(V))
1261 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
1262 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
1263 if (HasNUW) BO->setHasNoUnsignedWrap();
1264 if (HasNSW) BO->setHasNoSignedWrap();
1265 return BO;
1266 }
1267
1268 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1269 return CreateNeg(V, Name, false, true);
1270 }
1271
1272 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1273 return CreateNeg(V, Name, true, false);
1274 }
1275
1276 Value *CreateFNeg(Value *V, const Twine &Name = "",
1277 MDNode *FPMathTag = nullptr) {
1278 if (auto *VC = dyn_cast<Constant>(V))
1279 return Insert(Folder.CreateFNeg(VC), Name);
1280 return Insert(setFPAttrs(BinaryOperator::CreateFNeg(V), FPMathTag, FMF),
1281 Name);
1282 }
1283
1284 Value *CreateNot(Value *V, const Twine &Name = "") {
1285 if (auto *VC = dyn_cast<Constant>(V))
1286 return Insert(Folder.CreateNot(VC), Name);
1287 return Insert(BinaryOperator::CreateNot(V), Name);
1288 }
1289
1290 //===--------------------------------------------------------------------===//
1291 // Instruction creation methods: Memory Instructions
1292 //===--------------------------------------------------------------------===//
1293
1294 AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
1295 Value *ArraySize = nullptr, const Twine &Name = "") {
1296 return Insert(new AllocaInst(Ty, AddrSpace, ArraySize), Name);
1297 }
1298
1299 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1300 const Twine &Name = "") {
1301 const DataLayout &DL = BB->getParent()->getParent()->getDataLayout();
1302 return Insert(new AllocaInst(Ty, DL.getAllocaAddrSpace(), ArraySize), Name);
1303 }
1304
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001305 /// Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001306 /// converting the string to 'bool' for the isVolatile parameter.
1307 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1308 return Insert(new LoadInst(Ptr), Name);
1309 }
1310
1311 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1312 return Insert(new LoadInst(Ptr), Name);
1313 }
1314
1315 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1316 return Insert(new LoadInst(Ty, Ptr), Name);
1317 }
1318
1319 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1320 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1321 }
1322
1323 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1324 return Insert(new StoreInst(Val, Ptr, isVolatile));
1325 }
1326
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001327 /// Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001328 /// correctly, instead of converting the string to 'bool' for the isVolatile
1329 /// parameter.
1330 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1331 LoadInst *LI = CreateLoad(Ptr, Name);
1332 LI->setAlignment(Align);
1333 return LI;
1334 }
1335 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1336 const Twine &Name = "") {
1337 LoadInst *LI = CreateLoad(Ptr, Name);
1338 LI->setAlignment(Align);
1339 return LI;
1340 }
1341 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1342 const Twine &Name = "") {
1343 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1344 LI->setAlignment(Align);
1345 return LI;
1346 }
1347
1348 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1349 bool isVolatile = false) {
1350 StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1351 SI->setAlignment(Align);
1352 return SI;
1353 }
1354
1355 FenceInst *CreateFence(AtomicOrdering Ordering,
1356 SyncScope::ID SSID = SyncScope::System,
1357 const Twine &Name = "") {
1358 return Insert(new FenceInst(Context, Ordering, SSID), Name);
1359 }
1360
1361 AtomicCmpXchgInst *
1362 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1363 AtomicOrdering SuccessOrdering,
1364 AtomicOrdering FailureOrdering,
1365 SyncScope::ID SSID = SyncScope::System) {
1366 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1367 FailureOrdering, SSID));
1368 }
1369
1370 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1371 AtomicOrdering Ordering,
1372 SyncScope::ID SSID = SyncScope::System) {
1373 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SSID));
1374 }
1375
1376 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1377 const Twine &Name = "") {
1378 return CreateGEP(nullptr, Ptr, IdxList, Name);
1379 }
1380
1381 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1382 const Twine &Name = "") {
1383 if (auto *PC = dyn_cast<Constant>(Ptr)) {
1384 // Every index must be constant.
1385 size_t i, e;
1386 for (i = 0, e = IdxList.size(); i != e; ++i)
1387 if (!isa<Constant>(IdxList[i]))
1388 break;
1389 if (i == e)
1390 return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1391 }
1392 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1393 }
1394
1395 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1396 const Twine &Name = "") {
1397 return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1398 }
1399
1400 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1401 const Twine &Name = "") {
1402 if (auto *PC = dyn_cast<Constant>(Ptr)) {
1403 // Every index must be constant.
1404 size_t i, e;
1405 for (i = 0, e = IdxList.size(); i != e; ++i)
1406 if (!isa<Constant>(IdxList[i]))
1407 break;
1408 if (i == e)
1409 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1410 Name);
1411 }
1412 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1413 }
1414
1415 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1416 return CreateGEP(nullptr, Ptr, Idx, Name);
1417 }
1418
1419 Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1420 if (auto *PC = dyn_cast<Constant>(Ptr))
1421 if (auto *IC = dyn_cast<Constant>(Idx))
1422 return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1423 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1424 }
1425
1426 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1427 const Twine &Name = "") {
1428 if (auto *PC = dyn_cast<Constant>(Ptr))
1429 if (auto *IC = dyn_cast<Constant>(Idx))
1430 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1431 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1432 }
1433
1434 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1435 return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1436 }
1437
1438 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1439 const Twine &Name = "") {
1440 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1441
1442 if (auto *PC = dyn_cast<Constant>(Ptr))
1443 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1444
1445 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1446 }
1447
1448 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1449 const Twine &Name = "") {
1450 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1451
1452 if (auto *PC = dyn_cast<Constant>(Ptr))
1453 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1454
1455 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1456 }
1457
1458 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1459 const Twine &Name = "") {
1460 Value *Idxs[] = {
1461 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1462 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1463 };
1464
1465 if (auto *PC = dyn_cast<Constant>(Ptr))
1466 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1467
1468 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1469 }
1470
1471 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1472 unsigned Idx1, const Twine &Name = "") {
1473 Value *Idxs[] = {
1474 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1475 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1476 };
1477
1478 if (auto *PC = dyn_cast<Constant>(Ptr))
1479 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1480
1481 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1482 }
1483
1484 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1485 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1486
1487 if (auto *PC = dyn_cast<Constant>(Ptr))
1488 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1489
1490 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1491 }
1492
1493 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1494 const Twine &Name = "") {
1495 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1496
1497 if (auto *PC = dyn_cast<Constant>(Ptr))
1498 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1499
1500 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1501 }
1502
1503 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1504 const Twine &Name = "") {
1505 Value *Idxs[] = {
1506 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1507 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1508 };
1509
1510 if (auto *PC = dyn_cast<Constant>(Ptr))
1511 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1512
1513 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1514 }
1515
1516 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1517 const Twine &Name = "") {
1518 Value *Idxs[] = {
1519 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1520 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1521 };
1522
1523 if (auto *PC = dyn_cast<Constant>(Ptr))
1524 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1525 Name);
1526
1527 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1528 }
1529
1530 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1531 const Twine &Name = "") {
1532 return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1533 }
1534
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001535 Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1536 return CreateConstInBoundsGEP2_32(nullptr, Ptr, 0, Idx, Name);
1537 }
1538
1539 /// Same as CreateGlobalString, but return a pointer with "i8*" type
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001540 /// instead of a pointer to array of i8.
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001541 Constant *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1542 unsigned AddressSpace = 0) {
1543 GlobalVariable *GV = CreateGlobalString(Str, Name, AddressSpace);
1544 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1545 Constant *Indices[] = {Zero, Zero};
1546 return ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV,
1547 Indices);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001548 }
1549
1550 //===--------------------------------------------------------------------===//
1551 // Instruction creation methods: Cast/Conversion Operators
1552 //===--------------------------------------------------------------------===//
1553
1554 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1555 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1556 }
1557
1558 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1559 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1560 }
1561
1562 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1563 return CreateCast(Instruction::SExt, V, DestTy, Name);
1564 }
1565
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001566 /// Create a ZExt or Trunc from the integer value V to DestTy. Return
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001567 /// the value untouched if the type of V is already DestTy.
1568 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1569 const Twine &Name = "") {
1570 assert(V->getType()->isIntOrIntVectorTy() &&
1571 DestTy->isIntOrIntVectorTy() &&
1572 "Can only zero extend/truncate integers!");
1573 Type *VTy = V->getType();
1574 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1575 return CreateZExt(V, DestTy, Name);
1576 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1577 return CreateTrunc(V, DestTy, Name);
1578 return V;
1579 }
1580
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001581 /// Create a SExt or Trunc from the integer value V to DestTy. Return
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001582 /// the value untouched if the type of V is already DestTy.
1583 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1584 const Twine &Name = "") {
1585 assert(V->getType()->isIntOrIntVectorTy() &&
1586 DestTy->isIntOrIntVectorTy() &&
1587 "Can only sign extend/truncate integers!");
1588 Type *VTy = V->getType();
1589 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1590 return CreateSExt(V, DestTy, Name);
1591 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1592 return CreateTrunc(V, DestTy, Name);
1593 return V;
1594 }
1595
1596 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1597 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1598 }
1599
1600 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1601 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1602 }
1603
1604 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1605 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1606 }
1607
1608 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1609 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1610 }
1611
1612 Value *CreateFPTrunc(Value *V, Type *DestTy,
1613 const Twine &Name = "") {
1614 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1615 }
1616
1617 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1618 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1619 }
1620
1621 Value *CreatePtrToInt(Value *V, Type *DestTy,
1622 const Twine &Name = "") {
1623 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1624 }
1625
1626 Value *CreateIntToPtr(Value *V, Type *DestTy,
1627 const Twine &Name = "") {
1628 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1629 }
1630
1631 Value *CreateBitCast(Value *V, Type *DestTy,
1632 const Twine &Name = "") {
1633 return CreateCast(Instruction::BitCast, V, DestTy, Name);
1634 }
1635
1636 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1637 const Twine &Name = "") {
1638 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1639 }
1640
1641 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1642 const Twine &Name = "") {
1643 if (V->getType() == DestTy)
1644 return V;
1645 if (auto *VC = dyn_cast<Constant>(V))
1646 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1647 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1648 }
1649
1650 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1651 const Twine &Name = "") {
1652 if (V->getType() == DestTy)
1653 return V;
1654 if (auto *VC = dyn_cast<Constant>(V))
1655 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1656 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1657 }
1658
1659 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1660 const Twine &Name = "") {
1661 if (V->getType() == DestTy)
1662 return V;
1663 if (auto *VC = dyn_cast<Constant>(V))
1664 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1665 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1666 }
1667
1668 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1669 const Twine &Name = "") {
1670 if (V->getType() == DestTy)
1671 return V;
1672 if (auto *VC = dyn_cast<Constant>(V))
1673 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1674 return Insert(CastInst::Create(Op, V, DestTy), Name);
1675 }
1676
1677 Value *CreatePointerCast(Value *V, Type *DestTy,
1678 const Twine &Name = "") {
1679 if (V->getType() == DestTy)
1680 return V;
1681 if (auto *VC = dyn_cast<Constant>(V))
1682 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1683 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1684 }
1685
1686 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1687 const Twine &Name = "") {
1688 if (V->getType() == DestTy)
1689 return V;
1690
1691 if (auto *VC = dyn_cast<Constant>(V)) {
1692 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1693 Name);
1694 }
1695
1696 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1697 Name);
1698 }
1699
1700 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1701 const Twine &Name = "") {
1702 if (V->getType() == DestTy)
1703 return V;
1704 if (auto *VC = dyn_cast<Constant>(V))
1705 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1706 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1707 }
1708
1709 Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1710 const Twine &Name = "") {
1711 if (V->getType() == DestTy)
1712 return V;
1713 if (V->getType()->isPtrOrPtrVectorTy() && DestTy->isIntOrIntVectorTy())
1714 return CreatePtrToInt(V, DestTy, Name);
1715 if (V->getType()->isIntOrIntVectorTy() && DestTy->isPtrOrPtrVectorTy())
1716 return CreateIntToPtr(V, DestTy, Name);
1717
1718 return CreateBitCast(V, DestTy, Name);
1719 }
1720
1721 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1722 if (V->getType() == DestTy)
1723 return V;
1724 if (auto *VC = dyn_cast<Constant>(V))
1725 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1726 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1727 }
1728
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001729 // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001730 // compile time error, instead of converting the string to bool for the
1731 // isSigned parameter.
1732 Value *CreateIntCast(Value *, Type *, const char *) = delete;
1733
1734 //===--------------------------------------------------------------------===//
1735 // Instruction creation methods: Compare Instructions
1736 //===--------------------------------------------------------------------===//
1737
1738 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1739 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1740 }
1741
1742 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1743 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1744 }
1745
1746 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1747 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1748 }
1749
1750 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1751 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1752 }
1753
1754 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1755 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1756 }
1757
1758 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1759 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1760 }
1761
1762 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1763 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1764 }
1765
1766 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1767 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1768 }
1769
1770 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1771 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1772 }
1773
1774 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1775 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1776 }
1777
1778 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1779 MDNode *FPMathTag = nullptr) {
1780 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1781 }
1782
1783 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1784 MDNode *FPMathTag = nullptr) {
1785 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1786 }
1787
1788 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1789 MDNode *FPMathTag = nullptr) {
1790 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1791 }
1792
1793 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1794 MDNode *FPMathTag = nullptr) {
1795 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1796 }
1797
1798 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1799 MDNode *FPMathTag = nullptr) {
1800 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1801 }
1802
1803 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1804 MDNode *FPMathTag = nullptr) {
1805 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1806 }
1807
1808 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1809 MDNode *FPMathTag = nullptr) {
1810 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1811 }
1812
1813 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1814 MDNode *FPMathTag = nullptr) {
1815 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1816 }
1817
1818 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1819 MDNode *FPMathTag = nullptr) {
1820 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1821 }
1822
1823 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1824 MDNode *FPMathTag = nullptr) {
1825 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1826 }
1827
1828 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1829 MDNode *FPMathTag = nullptr) {
1830 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1831 }
1832
1833 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1834 MDNode *FPMathTag = nullptr) {
1835 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1836 }
1837
1838 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1839 MDNode *FPMathTag = nullptr) {
1840 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1841 }
1842
1843 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1844 MDNode *FPMathTag = nullptr) {
1845 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1846 }
1847
1848 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1849 const Twine &Name = "") {
1850 if (auto *LC = dyn_cast<Constant>(LHS))
1851 if (auto *RC = dyn_cast<Constant>(RHS))
1852 return Insert(Folder.CreateICmp(P, LC, RC), Name);
1853 return Insert(new ICmpInst(P, LHS, RHS), Name);
1854 }
1855
1856 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1857 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1858 if (auto *LC = dyn_cast<Constant>(LHS))
1859 if (auto *RC = dyn_cast<Constant>(RHS))
1860 return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1861 return Insert(setFPAttrs(new FCmpInst(P, LHS, RHS), FPMathTag, FMF), Name);
1862 }
1863
1864 //===--------------------------------------------------------------------===//
1865 // Instruction creation methods: Other Instructions
1866 //===--------------------------------------------------------------------===//
1867
1868 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1869 const Twine &Name = "") {
1870 return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1871 }
1872
1873 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1874 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1875 auto *PTy = cast<PointerType>(Callee->getType());
1876 auto *FTy = cast<FunctionType>(PTy->getElementType());
1877 return CreateCall(FTy, Callee, Args, Name, FPMathTag);
1878 }
1879
1880 CallInst *CreateCall(FunctionType *FTy, Value *Callee,
1881 ArrayRef<Value *> Args, const Twine &Name = "",
1882 MDNode *FPMathTag = nullptr) {
1883 CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
1884 if (isa<FPMathOperator>(CI))
1885 CI = cast<CallInst>(setFPAttrs(CI, FPMathTag, FMF));
1886 return Insert(CI, Name);
1887 }
1888
1889 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1890 ArrayRef<OperandBundleDef> OpBundles,
1891 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1892 CallInst *CI = CallInst::Create(Callee, Args, OpBundles);
1893 if (isa<FPMathOperator>(CI))
1894 CI = cast<CallInst>(setFPAttrs(CI, FPMathTag, FMF));
1895 return Insert(CI, Name);
1896 }
1897
1898 CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1899 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1900 return CreateCall(Callee->getFunctionType(), Callee, Args, Name, FPMathTag);
1901 }
1902
1903 Value *CreateSelect(Value *C, Value *True, Value *False,
1904 const Twine &Name = "", Instruction *MDFrom = nullptr) {
1905 if (auto *CC = dyn_cast<Constant>(C))
1906 if (auto *TC = dyn_cast<Constant>(True))
1907 if (auto *FC = dyn_cast<Constant>(False))
1908 return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1909
1910 SelectInst *Sel = SelectInst::Create(C, True, False);
1911 if (MDFrom) {
1912 MDNode *Prof = MDFrom->getMetadata(LLVMContext::MD_prof);
1913 MDNode *Unpred = MDFrom->getMetadata(LLVMContext::MD_unpredictable);
1914 Sel = addBranchMetadata(Sel, Prof, Unpred);
1915 }
1916 return Insert(Sel, Name);
1917 }
1918
1919 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1920 return Insert(new VAArgInst(List, Ty), Name);
1921 }
1922
1923 Value *CreateExtractElement(Value *Vec, Value *Idx,
1924 const Twine &Name = "") {
1925 if (auto *VC = dyn_cast<Constant>(Vec))
1926 if (auto *IC = dyn_cast<Constant>(Idx))
1927 return Insert(Folder.CreateExtractElement(VC, IC), Name);
1928 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1929 }
1930
1931 Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1932 const Twine &Name = "") {
1933 return CreateExtractElement(Vec, getInt64(Idx), Name);
1934 }
1935
1936 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1937 const Twine &Name = "") {
1938 if (auto *VC = dyn_cast<Constant>(Vec))
1939 if (auto *NC = dyn_cast<Constant>(NewElt))
1940 if (auto *IC = dyn_cast<Constant>(Idx))
1941 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1942 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1943 }
1944
1945 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1946 const Twine &Name = "") {
1947 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1948 }
1949
1950 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1951 const Twine &Name = "") {
1952 if (auto *V1C = dyn_cast<Constant>(V1))
1953 if (auto *V2C = dyn_cast<Constant>(V2))
1954 if (auto *MC = dyn_cast<Constant>(Mask))
1955 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1956 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1957 }
1958
1959 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<uint32_t> IntMask,
1960 const Twine &Name = "") {
1961 Value *Mask = ConstantDataVector::get(Context, IntMask);
1962 return CreateShuffleVector(V1, V2, Mask, Name);
1963 }
1964
1965 Value *CreateExtractValue(Value *Agg,
1966 ArrayRef<unsigned> Idxs,
1967 const Twine &Name = "") {
1968 if (auto *AggC = dyn_cast<Constant>(Agg))
1969 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1970 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1971 }
1972
1973 Value *CreateInsertValue(Value *Agg, Value *Val,
1974 ArrayRef<unsigned> Idxs,
1975 const Twine &Name = "") {
1976 if (auto *AggC = dyn_cast<Constant>(Agg))
1977 if (auto *ValC = dyn_cast<Constant>(Val))
1978 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1979 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1980 }
1981
1982 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1983 const Twine &Name = "") {
1984 return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1985 }
1986
1987 //===--------------------------------------------------------------------===//
1988 // Utility creation methods
1989 //===--------------------------------------------------------------------===//
1990
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001991 /// Return an i1 value testing if \p Arg is null.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001992 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
1993 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
1994 Name);
1995 }
1996
Andrew Scullcdfcccc2018-10-05 20:58:37 +01001997 /// Return an i1 value testing if \p Arg is not null.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001998 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
1999 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
2000 Name);
2001 }
2002
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002003 /// Return the i64 difference between two pointer values, dividing out
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002004 /// the size of the pointed-to objects.
2005 ///
2006 /// This is intended to implement C-style pointer subtraction. As such, the
2007 /// pointers must be appropriately aligned for their element types and
2008 /// pointing into the same object.
2009 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
2010 assert(LHS->getType() == RHS->getType() &&
2011 "Pointer subtraction operand types must match!");
2012 auto *ArgType = cast<PointerType>(LHS->getType());
2013 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
2014 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
2015 Value *Difference = CreateSub(LHS_int, RHS_int);
2016 return CreateExactSDiv(Difference,
2017 ConstantExpr::getSizeOf(ArgType->getElementType()),
2018 Name);
2019 }
2020
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002021 /// Create a launder.invariant.group intrinsic call. If Ptr type is
2022 /// different from pointer to i8, it's casted to pointer to i8 in the same
2023 /// address space before call and casted back to Ptr type after call.
2024 Value *CreateLaunderInvariantGroup(Value *Ptr) {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002025 assert(isa<PointerType>(Ptr->getType()) &&
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002026 "launder.invariant.group only applies to pointers.");
2027 // FIXME: we could potentially avoid casts to/from i8*.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002028 auto *PtrType = Ptr->getType();
2029 auto *Int8PtrTy = getInt8PtrTy(PtrType->getPointerAddressSpace());
2030 if (PtrType != Int8PtrTy)
2031 Ptr = CreateBitCast(Ptr, Int8PtrTy);
2032 Module *M = BB->getParent()->getParent();
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002033 Function *FnLaunderInvariantGroup = Intrinsic::getDeclaration(
2034 M, Intrinsic::launder_invariant_group, {Int8PtrTy});
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002035
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002036 assert(FnLaunderInvariantGroup->getReturnType() == Int8PtrTy &&
2037 FnLaunderInvariantGroup->getFunctionType()->getParamType(0) ==
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002038 Int8PtrTy &&
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002039 "LaunderInvariantGroup should take and return the same type");
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002040
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002041 CallInst *Fn = CreateCall(FnLaunderInvariantGroup, {Ptr});
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002042
2043 if (PtrType != Int8PtrTy)
2044 return CreateBitCast(Fn, PtrType);
2045 return Fn;
2046 }
2047
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002048 /// \brief Create a strip.invariant.group intrinsic call. If Ptr type is
2049 /// different from pointer to i8, it's casted to pointer to i8 in the same
2050 /// address space before call and casted back to Ptr type after call.
2051 Value *CreateStripInvariantGroup(Value *Ptr) {
2052 assert(isa<PointerType>(Ptr->getType()) &&
2053 "strip.invariant.group only applies to pointers.");
2054
2055 // FIXME: we could potentially avoid casts to/from i8*.
2056 auto *PtrType = Ptr->getType();
2057 auto *Int8PtrTy = getInt8PtrTy(PtrType->getPointerAddressSpace());
2058 if (PtrType != Int8PtrTy)
2059 Ptr = CreateBitCast(Ptr, Int8PtrTy);
2060 Module *M = BB->getParent()->getParent();
2061 Function *FnStripInvariantGroup = Intrinsic::getDeclaration(
2062 M, Intrinsic::strip_invariant_group, {Int8PtrTy});
2063
2064 assert(FnStripInvariantGroup->getReturnType() == Int8PtrTy &&
2065 FnStripInvariantGroup->getFunctionType()->getParamType(0) ==
2066 Int8PtrTy &&
2067 "StripInvariantGroup should take and return the same type");
2068
2069 CallInst *Fn = CreateCall(FnStripInvariantGroup, {Ptr});
2070
2071 if (PtrType != Int8PtrTy)
2072 return CreateBitCast(Fn, PtrType);
2073 return Fn;
2074 }
2075
2076 /// Return a vector value that contains \arg V broadcasted to \p
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002077 /// NumElts elements.
2078 Value *CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name = "") {
2079 assert(NumElts > 0 && "Cannot splat to an empty vector!");
2080
2081 // First insert it into an undef vector so we can shuffle it.
2082 Type *I32Ty = getInt32Ty();
2083 Value *Undef = UndefValue::get(VectorType::get(V->getType(), NumElts));
2084 V = CreateInsertElement(Undef, V, ConstantInt::get(I32Ty, 0),
2085 Name + ".splatinsert");
2086
2087 // Shuffle the value across the desired number of elements.
2088 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32Ty, NumElts));
2089 return CreateShuffleVector(V, Undef, Zeros, Name + ".splat");
2090 }
2091
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002092 /// Return a value that has been extracted from a larger integer type.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002093 Value *CreateExtractInteger(const DataLayout &DL, Value *From,
2094 IntegerType *ExtractedTy, uint64_t Offset,
2095 const Twine &Name) {
2096 auto *IntTy = cast<IntegerType>(From->getType());
2097 assert(DL.getTypeStoreSize(ExtractedTy) + Offset <=
2098 DL.getTypeStoreSize(IntTy) &&
2099 "Element extends past full value");
2100 uint64_t ShAmt = 8 * Offset;
2101 Value *V = From;
2102 if (DL.isBigEndian())
2103 ShAmt = 8 * (DL.getTypeStoreSize(IntTy) -
2104 DL.getTypeStoreSize(ExtractedTy) - Offset);
2105 if (ShAmt) {
2106 V = CreateLShr(V, ShAmt, Name + ".shift");
2107 }
2108 assert(ExtractedTy->getBitWidth() <= IntTy->getBitWidth() &&
2109 "Cannot extract to a larger integer!");
2110 if (ExtractedTy != IntTy) {
2111 V = CreateTrunc(V, ExtractedTy, Name + ".trunc");
2112 }
2113 return V;
2114 }
2115
2116private:
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002117 /// Helper function that creates an assume intrinsic call that
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002118 /// represents an alignment assumption on the provided Ptr, Mask, Type
2119 /// and Offset.
2120 CallInst *CreateAlignmentAssumptionHelper(const DataLayout &DL,
2121 Value *PtrValue, Value *Mask,
2122 Type *IntPtrTy,
2123 Value *OffsetValue) {
2124 Value *PtrIntValue = CreatePtrToInt(PtrValue, IntPtrTy, "ptrint");
2125
2126 if (OffsetValue) {
2127 bool IsOffsetZero = false;
2128 if (const auto *CI = dyn_cast<ConstantInt>(OffsetValue))
2129 IsOffsetZero = CI->isZero();
2130
2131 if (!IsOffsetZero) {
2132 if (OffsetValue->getType() != IntPtrTy)
2133 OffsetValue = CreateIntCast(OffsetValue, IntPtrTy, /*isSigned*/ true,
2134 "offsetcast");
2135 PtrIntValue = CreateSub(PtrIntValue, OffsetValue, "offsetptr");
2136 }
2137 }
2138
2139 Value *Zero = ConstantInt::get(IntPtrTy, 0);
2140 Value *MaskedPtr = CreateAnd(PtrIntValue, Mask, "maskedptr");
2141 Value *InvCond = CreateICmpEQ(MaskedPtr, Zero, "maskcond");
2142 return CreateAssumption(InvCond);
2143 }
2144
2145public:
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002146 /// Create an assume intrinsic call that represents an alignment
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002147 /// assumption on the provided pointer.
2148 ///
2149 /// An optional offset can be provided, and if it is provided, the offset
2150 /// must be subtracted from the provided pointer to get the pointer with the
2151 /// specified alignment.
2152 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
2153 unsigned Alignment,
2154 Value *OffsetValue = nullptr) {
2155 assert(isa<PointerType>(PtrValue->getType()) &&
2156 "trying to create an alignment assumption on a non-pointer?");
2157 auto *PtrTy = cast<PointerType>(PtrValue->getType());
2158 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
2159
2160 Value *Mask = ConstantInt::get(IntPtrTy, Alignment > 0 ? Alignment - 1 : 0);
2161 return CreateAlignmentAssumptionHelper(DL, PtrValue, Mask, IntPtrTy,
2162 OffsetValue);
2163 }
2164
Andrew Scullcdfcccc2018-10-05 20:58:37 +01002165 /// Create an assume intrinsic call that represents an alignment
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01002166 /// assumption on the provided pointer.
2167 ///
2168 /// An optional offset can be provided, and if it is provided, the offset
2169 /// must be subtracted from the provided pointer to get the pointer with the
2170 /// specified alignment.
2171 ///
2172 /// This overload handles the condition where the Alignment is dependent
2173 /// on an existing value rather than a static value.
2174 CallInst *CreateAlignmentAssumption(const DataLayout &DL, Value *PtrValue,
2175 Value *Alignment,
2176 Value *OffsetValue = nullptr) {
2177 assert(isa<PointerType>(PtrValue->getType()) &&
2178 "trying to create an alignment assumption on a non-pointer?");
2179 auto *PtrTy = cast<PointerType>(PtrValue->getType());
2180 Type *IntPtrTy = getIntPtrTy(DL, PtrTy->getAddressSpace());
2181
2182 if (Alignment->getType() != IntPtrTy)
2183 Alignment = CreateIntCast(Alignment, IntPtrTy, /*isSigned*/ true,
2184 "alignmentcast");
2185 Value *IsPositive =
2186 CreateICmp(CmpInst::ICMP_SGT, Alignment,
2187 ConstantInt::get(Alignment->getType(), 0), "ispositive");
2188 Value *PositiveMask =
2189 CreateSub(Alignment, ConstantInt::get(IntPtrTy, 1), "positivemask");
2190 Value *Mask = CreateSelect(IsPositive, PositiveMask,
2191 ConstantInt::get(IntPtrTy, 0), "mask");
2192
2193 return CreateAlignmentAssumptionHelper(DL, PtrValue, Mask, IntPtrTy,
2194 OffsetValue);
2195 }
2196};
2197
2198// Create wrappers for C Binding types (see CBindingWrapping.h).
2199DEFINE_SIMPLE_CONVERSION_FUNCTIONS(IRBuilder<>, LLVMBuilderRef)
2200
2201} // end namespace llvm
2202
2203#endif // LLVM_IR_IRBUILDER_H