1 //===- IRBuilder.cpp - Builder for LLVM Instrs ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the IRBuilder class, which is used as a convenient way
10 // to create LLVM instructions with a consistent and simplified interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/IRBuilder.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/IR/Constant.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalValue.h"
22 #include "llvm/IR/GlobalVariable.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/NoFolder.h"
28 #include "llvm/IR/Statepoint.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/MathExtras.h"
33 #include <cassert>
34 #include <cstdint>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 /// CreateGlobalString - Make a new global variable with an initializer that
40 /// has array of i8 type filled in with the nul terminated string value
41 /// specified.  If Name is specified, it is the name of the global variable
42 /// created.
43 GlobalVariable *IRBuilderBase::CreateGlobalString(StringRef Str,
44                                                   const Twine &Name,
45                                                   unsigned AddressSpace) {
46   Constant *StrConstant = ConstantDataArray::getString(Context, Str);
47   Module &M = *BB->getParent()->getParent();
48   auto *GV = new GlobalVariable(M, StrConstant->getType(), true,
49                                 GlobalValue::PrivateLinkage, StrConstant, Name,
50                                 nullptr, GlobalVariable::NotThreadLocal,
51                                 AddressSpace);
52   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
53   GV->setAlignment(Align(1));
54   return GV;
55 }
56 
57 Type *IRBuilderBase::getCurrentFunctionReturnType() const {
58   assert(BB && BB->getParent() && "No current function!");
59   return BB->getParent()->getReturnType();
60 }
61 
62 Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) {
63   auto *PT = cast<PointerType>(Ptr->getType());
64   if (PT->getElementType()->isIntegerTy(8))
65     return Ptr;
66 
67   // Otherwise, we need to insert a bitcast.
68   PT = getInt8PtrTy(PT->getAddressSpace());
69   BitCastInst *BCI = new BitCastInst(Ptr, PT, "");
70   BB->getInstList().insert(InsertPt, BCI);
71   SetInstDebugLocation(BCI);
72   return BCI;
73 }
74 
75 static CallInst *createCallHelper(Function *Callee, ArrayRef<Value *> Ops,
76                                   IRBuilderBase *Builder,
77                                   const Twine &Name = "",
78                                   Instruction *FMFSource = nullptr) {
79   CallInst *CI = CallInst::Create(Callee, Ops, Name);
80   if (FMFSource)
81     CI->copyFastMathFlags(FMFSource);
82   Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI);
83   Builder->SetInstDebugLocation(CI);
84   return CI;
85 }
86 
87 static InvokeInst *createInvokeHelper(Function *Invokee, BasicBlock *NormalDest,
88                                       BasicBlock *UnwindDest,
89                                       ArrayRef<Value *> Ops,
90                                       IRBuilderBase *Builder,
91                                       const Twine &Name = "") {
92   InvokeInst *II =
93       InvokeInst::Create(Invokee, NormalDest, UnwindDest, Ops, Name);
94   Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),
95                                                   II);
96   Builder->SetInstDebugLocation(II);
97   return II;
98 }
99 
100 CallInst *IRBuilderBase::CreateMemSet(Value *Ptr, Value *Val, Value *Size,
101                                       MaybeAlign Align, bool isVolatile,
102                                       MDNode *TBAATag, MDNode *ScopeTag,
103                                       MDNode *NoAliasTag) {
104   Ptr = getCastedInt8PtrValue(Ptr);
105   Value *Ops[] = {Ptr, Val, Size, getInt1(isVolatile)};
106   Type *Tys[] = { Ptr->getType(), Size->getType() };
107   Module *M = BB->getParent()->getParent();
108   Function *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
109 
110   CallInst *CI = createCallHelper(TheFn, Ops, this);
111 
112   if (Align)
113     cast<MemSetInst>(CI)->setDestAlignment(Align->value());
114 
115   // Set the TBAA info if present.
116   if (TBAATag)
117     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
118 
119   if (ScopeTag)
120     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
121 
122   if (NoAliasTag)
123     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
124 
125   return CI;
126 }
127 
128 CallInst *IRBuilderBase::CreateElementUnorderedAtomicMemSet(
129     Value *Ptr, Value *Val, Value *Size, Align Alignment, uint32_t ElementSize,
130     MDNode *TBAATag, MDNode *ScopeTag, MDNode *NoAliasTag) {
131 
132   Ptr = getCastedInt8PtrValue(Ptr);
133   Value *Ops[] = {Ptr, Val, Size, getInt32(ElementSize)};
134   Type *Tys[] = {Ptr->getType(), Size->getType()};
135   Module *M = BB->getParent()->getParent();
136   Function *TheFn = Intrinsic::getDeclaration(
137       M, Intrinsic::memset_element_unordered_atomic, Tys);
138 
139   CallInst *CI = createCallHelper(TheFn, Ops, this);
140 
141   cast<AtomicMemSetInst>(CI)->setDestAlignment(Alignment);
142 
143   // Set the TBAA info if present.
144   if (TBAATag)
145     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
146 
147   if (ScopeTag)
148     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
149 
150   if (NoAliasTag)
151     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
152 
153   return CI;
154 }
155 
156 CallInst *IRBuilderBase::CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,
157                                       unsigned SrcAlign, Value *Size,
158                                       bool isVolatile, MDNode *TBAATag,
159                                       MDNode *TBAAStructTag, MDNode *ScopeTag,
160                                       MDNode *NoAliasTag) {
161   return CreateMemCpy(Dst, MaybeAlign(DstAlign), Src, MaybeAlign(SrcAlign),
162                       Size, isVolatile, TBAATag, TBAAStructTag, ScopeTag,
163                       NoAliasTag);
164 }
165 
166 CallInst *IRBuilderBase::CreateMemCpy(Value *Dst, MaybeAlign DstAlign,
167                                       Value *Src, MaybeAlign SrcAlign,
168                                       Value *Size, bool isVolatile,
169                                       MDNode *TBAATag, MDNode *TBAAStructTag,
170                                       MDNode *ScopeTag, MDNode *NoAliasTag) {
171   Dst = getCastedInt8PtrValue(Dst);
172   Src = getCastedInt8PtrValue(Src);
173 
174   Value *Ops[] = {Dst, Src, Size, getInt1(isVolatile)};
175   Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
176   Module *M = BB->getParent()->getParent();
177   Function *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
178 
179   CallInst *CI = createCallHelper(TheFn, Ops, this);
180 
181   auto* MCI = cast<MemCpyInst>(CI);
182   if (DstAlign)
183     MCI->setDestAlignment(*DstAlign);
184   if (SrcAlign)
185     MCI->setSourceAlignment(*SrcAlign);
186 
187   // Set the TBAA info if present.
188   if (TBAATag)
189     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
190 
191   // Set the TBAA Struct info if present.
192   if (TBAAStructTag)
193     CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
194 
195   if (ScopeTag)
196     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
197 
198   if (NoAliasTag)
199     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
200 
201   return CI;
202 }
203 
204 CallInst *IRBuilderBase::CreateMemCpyInline(Value *Dst, MaybeAlign DstAlign,
205                                             Value *Src, MaybeAlign SrcAlign,
206                                             Value *Size) {
207   Dst = getCastedInt8PtrValue(Dst);
208   Src = getCastedInt8PtrValue(Src);
209   Value *IsVolatile = getInt1(false);
210 
211   Value *Ops[] = {Dst, Src, Size, IsVolatile};
212   Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
213   Function *F = BB->getParent();
214   Module *M = F->getParent();
215   Function *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy_inline, Tys);
216 
217   CallInst *CI = createCallHelper(TheFn, Ops, this);
218 
219   auto *MCI = cast<MemCpyInlineInst>(CI);
220   if (DstAlign)
221     MCI->setDestAlignment(*DstAlign);
222   if (SrcAlign)
223     MCI->setSourceAlignment(*SrcAlign);
224 
225   return CI;
226 }
227 
228 CallInst *IRBuilderBase::CreateElementUnorderedAtomicMemCpy(
229     Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
230     uint32_t ElementSize, MDNode *TBAATag, MDNode *TBAAStructTag,
231     MDNode *ScopeTag, MDNode *NoAliasTag) {
232   assert(DstAlign >= ElementSize &&
233          "Pointer alignment must be at least element size");
234   assert(SrcAlign >= ElementSize &&
235          "Pointer alignment must be at least element size");
236   Dst = getCastedInt8PtrValue(Dst);
237   Src = getCastedInt8PtrValue(Src);
238 
239   Value *Ops[] = {Dst, Src, Size, getInt32(ElementSize)};
240   Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
241   Module *M = BB->getParent()->getParent();
242   Function *TheFn = Intrinsic::getDeclaration(
243       M, Intrinsic::memcpy_element_unordered_atomic, Tys);
244 
245   CallInst *CI = createCallHelper(TheFn, Ops, this);
246 
247   // Set the alignment of the pointer args.
248   auto *AMCI = cast<AtomicMemCpyInst>(CI);
249   AMCI->setDestAlignment(DstAlign);
250   AMCI->setSourceAlignment(SrcAlign);
251 
252   // Set the TBAA info if present.
253   if (TBAATag)
254     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
255 
256   // Set the TBAA Struct info if present.
257   if (TBAAStructTag)
258     CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
259 
260   if (ScopeTag)
261     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
262 
263   if (NoAliasTag)
264     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
265 
266   return CI;
267 }
268 
269 CallInst *IRBuilderBase::CreateMemMove(Value *Dst, MaybeAlign DstAlign,
270                                        Value *Src, MaybeAlign SrcAlign,
271                                        Value *Size, bool isVolatile,
272                                        MDNode *TBAATag, MDNode *ScopeTag,
273                                        MDNode *NoAliasTag) {
274   Dst = getCastedInt8PtrValue(Dst);
275   Src = getCastedInt8PtrValue(Src);
276 
277   Value *Ops[] = {Dst, Src, Size, getInt1(isVolatile)};
278   Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
279   Module *M = BB->getParent()->getParent();
280   Function *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys);
281 
282   CallInst *CI = createCallHelper(TheFn, Ops, this);
283 
284   auto *MMI = cast<MemMoveInst>(CI);
285   if (DstAlign)
286     MMI->setDestAlignment(*DstAlign);
287   if (SrcAlign)
288     MMI->setSourceAlignment(*SrcAlign);
289 
290   // Set the TBAA info if present.
291   if (TBAATag)
292     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
293 
294   if (ScopeTag)
295     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
296 
297   if (NoAliasTag)
298     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
299 
300   return CI;
301 }
302 
303 CallInst *IRBuilderBase::CreateElementUnorderedAtomicMemMove(
304     Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
305     uint32_t ElementSize, MDNode *TBAATag, MDNode *TBAAStructTag,
306     MDNode *ScopeTag, MDNode *NoAliasTag) {
307   assert(DstAlign >= ElementSize &&
308          "Pointer alignment must be at least element size");
309   assert(SrcAlign >= ElementSize &&
310          "Pointer alignment must be at least element size");
311   Dst = getCastedInt8PtrValue(Dst);
312   Src = getCastedInt8PtrValue(Src);
313 
314   Value *Ops[] = {Dst, Src, Size, getInt32(ElementSize)};
315   Type *Tys[] = {Dst->getType(), Src->getType(), Size->getType()};
316   Module *M = BB->getParent()->getParent();
317   Function *TheFn = Intrinsic::getDeclaration(
318       M, Intrinsic::memmove_element_unordered_atomic, Tys);
319 
320   CallInst *CI = createCallHelper(TheFn, Ops, this);
321 
322   // Set the alignment of the pointer args.
323   CI->addParamAttr(0, Attribute::getWithAlignment(CI->getContext(), DstAlign));
324   CI->addParamAttr(1, Attribute::getWithAlignment(CI->getContext(), SrcAlign));
325 
326   // Set the TBAA info if present.
327   if (TBAATag)
328     CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
329 
330   // Set the TBAA Struct info if present.
331   if (TBAAStructTag)
332     CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
333 
334   if (ScopeTag)
335     CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
336 
337   if (NoAliasTag)
338     CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
339 
340   return CI;
341 }
342 
343 static CallInst *getReductionIntrinsic(IRBuilderBase *Builder, Intrinsic::ID ID,
344                                     Value *Src) {
345   Module *M = Builder->GetInsertBlock()->getParent()->getParent();
346   Value *Ops[] = {Src};
347   Type *Tys[] = { Src->getType() };
348   auto Decl = Intrinsic::getDeclaration(M, ID, Tys);
349   return createCallHelper(Decl, Ops, Builder);
350 }
351 
352 CallInst *IRBuilderBase::CreateFAddReduce(Value *Acc, Value *Src) {
353   Module *M = GetInsertBlock()->getParent()->getParent();
354   Value *Ops[] = {Acc, Src};
355   Type *Tys[] = {Acc->getType(), Src->getType()};
356   auto Decl = Intrinsic::getDeclaration(
357       M, Intrinsic::experimental_vector_reduce_v2_fadd, Tys);
358   return createCallHelper(Decl, Ops, this);
359 }
360 
361 CallInst *IRBuilderBase::CreateFMulReduce(Value *Acc, Value *Src) {
362   Module *M = GetInsertBlock()->getParent()->getParent();
363   Value *Ops[] = {Acc, Src};
364   Type *Tys[] = {Acc->getType(), Src->getType()};
365   auto Decl = Intrinsic::getDeclaration(
366       M, Intrinsic::experimental_vector_reduce_v2_fmul, Tys);
367   return createCallHelper(Decl, Ops, this);
368 }
369 
370 CallInst *IRBuilderBase::CreateAddReduce(Value *Src) {
371   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_add,
372                                Src);
373 }
374 
375 CallInst *IRBuilderBase::CreateMulReduce(Value *Src) {
376   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_mul,
377                                Src);
378 }
379 
380 CallInst *IRBuilderBase::CreateAndReduce(Value *Src) {
381   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_and,
382                                Src);
383 }
384 
385 CallInst *IRBuilderBase::CreateOrReduce(Value *Src) {
386   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_or,
387                                Src);
388 }
389 
390 CallInst *IRBuilderBase::CreateXorReduce(Value *Src) {
391   return getReductionIntrinsic(this, Intrinsic::experimental_vector_reduce_xor,
392                                Src);
393 }
394 
395 CallInst *IRBuilderBase::CreateIntMaxReduce(Value *Src, bool IsSigned) {
396   auto ID = IsSigned ? Intrinsic::experimental_vector_reduce_smax
397                      : Intrinsic::experimental_vector_reduce_umax;
398   return getReductionIntrinsic(this, ID, Src);
399 }
400 
401 CallInst *IRBuilderBase::CreateIntMinReduce(Value *Src, bool IsSigned) {
402   auto ID = IsSigned ? Intrinsic::experimental_vector_reduce_smin
403                      : Intrinsic::experimental_vector_reduce_umin;
404   return getReductionIntrinsic(this, ID, Src);
405 }
406 
407 CallInst *IRBuilderBase::CreateFPMaxReduce(Value *Src, bool NoNaN) {
408   auto Rdx = getReductionIntrinsic(
409       this, Intrinsic::experimental_vector_reduce_fmax, Src);
410   if (NoNaN) {
411     FastMathFlags FMF;
412     FMF.setNoNaNs();
413     Rdx->setFastMathFlags(FMF);
414   }
415   return Rdx;
416 }
417 
418 CallInst *IRBuilderBase::CreateFPMinReduce(Value *Src, bool NoNaN) {
419   auto Rdx = getReductionIntrinsic(
420       this, Intrinsic::experimental_vector_reduce_fmin, Src);
421   if (NoNaN) {
422     FastMathFlags FMF;
423     FMF.setNoNaNs();
424     Rdx->setFastMathFlags(FMF);
425   }
426   return Rdx;
427 }
428 
429 CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) {
430   assert(isa<PointerType>(Ptr->getType()) &&
431          "lifetime.start only applies to pointers.");
432   Ptr = getCastedInt8PtrValue(Ptr);
433   if (!Size)
434     Size = getInt64(-1);
435   else
436     assert(Size->getType() == getInt64Ty() &&
437            "lifetime.start requires the size to be an i64");
438   Value *Ops[] = { Size, Ptr };
439   Module *M = BB->getParent()->getParent();
440   Function *TheFn =
441       Intrinsic::getDeclaration(M, Intrinsic::lifetime_start, {Ptr->getType()});
442   return createCallHelper(TheFn, Ops, this);
443 }
444 
445 CallInst *IRBuilderBase::CreateLifetimeEnd(Value *Ptr, ConstantInt *Size) {
446   assert(isa<PointerType>(Ptr->getType()) &&
447          "lifetime.end only applies to pointers.");
448   Ptr = getCastedInt8PtrValue(Ptr);
449   if (!Size)
450     Size = getInt64(-1);
451   else
452     assert(Size->getType() == getInt64Ty() &&
453            "lifetime.end requires the size to be an i64");
454   Value *Ops[] = { Size, Ptr };
455   Module *M = BB->getParent()->getParent();
456   Function *TheFn =
457       Intrinsic::getDeclaration(M, Intrinsic::lifetime_end, {Ptr->getType()});
458   return createCallHelper(TheFn, Ops, this);
459 }
460 
461 CallInst *IRBuilderBase::CreateInvariantStart(Value *Ptr, ConstantInt *Size) {
462 
463   assert(isa<PointerType>(Ptr->getType()) &&
464          "invariant.start only applies to pointers.");
465   Ptr = getCastedInt8PtrValue(Ptr);
466   if (!Size)
467     Size = getInt64(-1);
468   else
469     assert(Size->getType() == getInt64Ty() &&
470            "invariant.start requires the size to be an i64");
471 
472   Value *Ops[] = {Size, Ptr};
473   // Fill in the single overloaded type: memory object type.
474   Type *ObjectPtr[1] = {Ptr->getType()};
475   Module *M = BB->getParent()->getParent();
476   Function *TheFn =
477       Intrinsic::getDeclaration(M, Intrinsic::invariant_start, ObjectPtr);
478   return createCallHelper(TheFn, Ops, this);
479 }
480 
481 CallInst *IRBuilderBase::CreateAssumption(Value *Cond) {
482   assert(Cond->getType() == getInt1Ty() &&
483          "an assumption condition must be of type i1");
484 
485   Value *Ops[] = { Cond };
486   Module *M = BB->getParent()->getParent();
487   Function *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume);
488   return createCallHelper(FnAssume, Ops, this);
489 }
490 
491 /// Create a call to a Masked Load intrinsic.
492 /// \p Ptr       - base pointer for the load
493 /// \p Alignment - alignment of the source location
494 /// \p Mask      - vector of booleans which indicates what vector lanes should
495 ///                be accessed in memory
496 /// \p PassThru  - pass-through value that is used to fill the masked-off lanes
497 ///                of the result
498 /// \p Name      - name of the result variable
499 CallInst *IRBuilderBase::CreateMaskedLoad(Value *Ptr, Align Alignment,
500                                           Value *Mask, Value *PassThru,
501                                           const Twine &Name) {
502   auto *PtrTy = cast<PointerType>(Ptr->getType());
503   Type *DataTy = PtrTy->getElementType();
504   assert(DataTy->isVectorTy() && "Ptr should point to a vector");
505   assert(Mask && "Mask should not be all-ones (null)");
506   if (!PassThru)
507     PassThru = UndefValue::get(DataTy);
508   Type *OverloadedTypes[] = { DataTy, PtrTy };
509   Value *Ops[] = {Ptr, getInt32(Alignment.value()), Mask, PassThru};
510   return CreateMaskedIntrinsic(Intrinsic::masked_load, Ops,
511                                OverloadedTypes, Name);
512 }
513 
514 /// Create a call to a Masked Store intrinsic.
515 /// \p Val       - data to be stored,
516 /// \p Ptr       - base pointer for the store
517 /// \p Alignment - alignment of the destination location
518 /// \p Mask      - vector of booleans which indicates what vector lanes should
519 ///                be accessed in memory
520 CallInst *IRBuilderBase::CreateMaskedStore(Value *Val, Value *Ptr,
521                                            Align Alignment, Value *Mask) {
522   auto *PtrTy = cast<PointerType>(Ptr->getType());
523   Type *DataTy = PtrTy->getElementType();
524   assert(DataTy->isVectorTy() && "Ptr should point to a vector");
525   assert(Mask && "Mask should not be all-ones (null)");
526   Type *OverloadedTypes[] = { DataTy, PtrTy };
527   Value *Ops[] = {Val, Ptr, getInt32(Alignment.value()), Mask};
528   return CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, OverloadedTypes);
529 }
530 
531 /// Create a call to a Masked intrinsic, with given intrinsic Id,
532 /// an array of operands - Ops, and an array of overloaded types -
533 /// OverloadedTypes.
534 CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id,
535                                                ArrayRef<Value *> Ops,
536                                                ArrayRef<Type *> OverloadedTypes,
537                                                const Twine &Name) {
538   Module *M = BB->getParent()->getParent();
539   Function *TheFn = Intrinsic::getDeclaration(M, Id, OverloadedTypes);
540   return createCallHelper(TheFn, Ops, this, Name);
541 }
542 
543 /// Create a call to a Masked Gather intrinsic.
544 /// \p Ptrs     - vector of pointers for loading
545 /// \p Align    - alignment for one element
546 /// \p Mask     - vector of booleans which indicates what vector lanes should
547 ///               be accessed in memory
548 /// \p PassThru - pass-through value that is used to fill the masked-off lanes
549 ///               of the result
550 /// \p Name     - name of the result variable
551 CallInst *IRBuilderBase::CreateMaskedGather(Value *Ptrs, Align Alignment,
552                                             Value *Mask, Value *PassThru,
553                                             const Twine &Name) {
554   auto PtrsTy = cast<VectorType>(Ptrs->getType());
555   auto PtrTy = cast<PointerType>(PtrsTy->getElementType());
556   unsigned NumElts = PtrsTy->getVectorNumElements();
557   Type *DataTy = VectorType::get(PtrTy->getElementType(), NumElts);
558 
559   if (!Mask)
560     Mask = Constant::getAllOnesValue(VectorType::get(Type::getInt1Ty(Context),
561                                      NumElts));
562 
563   if (!PassThru)
564     PassThru = UndefValue::get(DataTy);
565 
566   Type *OverloadedTypes[] = {DataTy, PtrsTy};
567   Value *Ops[] = {Ptrs, getInt32(Alignment.value()), Mask, PassThru};
568 
569   // We specify only one type when we create this intrinsic. Types of other
570   // arguments are derived from this type.
571   return CreateMaskedIntrinsic(Intrinsic::masked_gather, Ops, OverloadedTypes,
572                                Name);
573 }
574 
575 /// Create a call to a Masked Scatter intrinsic.
576 /// \p Data  - data to be stored,
577 /// \p Ptrs  - the vector of pointers, where the \p Data elements should be
578 ///            stored
579 /// \p Align - alignment for one element
580 /// \p Mask  - vector of booleans which indicates what vector lanes should
581 ///            be accessed in memory
582 CallInst *IRBuilderBase::CreateMaskedScatter(Value *Data, Value *Ptrs,
583                                              Align Alignment, Value *Mask) {
584   auto PtrsTy = cast<VectorType>(Ptrs->getType());
585   auto DataTy = cast<VectorType>(Data->getType());
586   unsigned NumElts = PtrsTy->getVectorNumElements();
587 
588 #ifndef NDEBUG
589   auto PtrTy = cast<PointerType>(PtrsTy->getElementType());
590   assert(NumElts == DataTy->getVectorNumElements() &&
591          PtrTy->getElementType() == DataTy->getElementType() &&
592          "Incompatible pointer and data types");
593 #endif
594 
595   if (!Mask)
596     Mask = Constant::getAllOnesValue(VectorType::get(Type::getInt1Ty(Context),
597                                      NumElts));
598 
599   Type *OverloadedTypes[] = {DataTy, PtrsTy};
600   Value *Ops[] = {Data, Ptrs, getInt32(Alignment.value()), Mask};
601 
602   // We specify only one type when we create this intrinsic. Types of other
603   // arguments are derived from this type.
604   return CreateMaskedIntrinsic(Intrinsic::masked_scatter, Ops, OverloadedTypes);
605 }
606 
607 template <typename T0, typename T1, typename T2, typename T3>
608 static std::vector<Value *>
609 getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes,
610                   Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
611                   ArrayRef<T1> TransitionArgs, ArrayRef<T2> DeoptArgs,
612                   ArrayRef<T3> GCArgs) {
613   std::vector<Value *> Args;
614   Args.push_back(B.getInt64(ID));
615   Args.push_back(B.getInt32(NumPatchBytes));
616   Args.push_back(ActualCallee);
617   Args.push_back(B.getInt32(CallArgs.size()));
618   Args.push_back(B.getInt32(Flags));
619   Args.insert(Args.end(), CallArgs.begin(), CallArgs.end());
620   Args.push_back(B.getInt32(TransitionArgs.size()));
621   Args.insert(Args.end(), TransitionArgs.begin(), TransitionArgs.end());
622   Args.push_back(B.getInt32(DeoptArgs.size()));
623   Args.insert(Args.end(), DeoptArgs.begin(), DeoptArgs.end());
624   Args.insert(Args.end(), GCArgs.begin(), GCArgs.end());
625 
626   return Args;
627 }
628 
629 template <typename T0, typename T1, typename T2, typename T3>
630 static CallInst *CreateGCStatepointCallCommon(
631     IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
632     Value *ActualCallee, uint32_t Flags, ArrayRef<T0> CallArgs,
633     ArrayRef<T1> TransitionArgs, ArrayRef<T2> DeoptArgs, ArrayRef<T3> GCArgs,
634     const Twine &Name) {
635   // Extract out the type of the callee.
636   auto *FuncPtrType = cast<PointerType>(ActualCallee->getType());
637   assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
638          "actual callee must be a callable value");
639 
640   Module *M = Builder->GetInsertBlock()->getParent()->getParent();
641   // Fill in the one generic type'd argument (the function is also vararg)
642   Type *ArgTypes[] = { FuncPtrType };
643   Function *FnStatepoint =
644     Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_statepoint,
645                               ArgTypes);
646 
647   std::vector<Value *> Args =
648       getStatepointArgs(*Builder, ID, NumPatchBytes, ActualCallee, Flags,
649                         CallArgs, TransitionArgs, DeoptArgs, GCArgs);
650   return createCallHelper(FnStatepoint, Args, Builder, Name);
651 }
652 
653 CallInst *IRBuilderBase::CreateGCStatepointCall(
654     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
655     ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs,
656     ArrayRef<Value *> GCArgs, const Twine &Name) {
657   return CreateGCStatepointCallCommon<Value *, Value *, Value *, Value *>(
658       this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
659       CallArgs, None /* No Transition Args */, DeoptArgs, GCArgs, Name);
660 }
661 
662 CallInst *IRBuilderBase::CreateGCStatepointCall(
663     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee, uint32_t Flags,
664     ArrayRef<Use> CallArgs, ArrayRef<Use> TransitionArgs,
665     ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
666   return CreateGCStatepointCallCommon<Use, Use, Use, Value *>(
667       this, ID, NumPatchBytes, ActualCallee, Flags, CallArgs, TransitionArgs,
668       DeoptArgs, GCArgs, Name);
669 }
670 
671 CallInst *IRBuilderBase::CreateGCStatepointCall(
672     uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
673     ArrayRef<Use> CallArgs, ArrayRef<Value *> DeoptArgs,
674     ArrayRef<Value *> GCArgs, const Twine &Name) {
675   return CreateGCStatepointCallCommon<Use, Value *, Value *, Value *>(
676       this, ID, NumPatchBytes, ActualCallee, uint32_t(StatepointFlags::None),
677       CallArgs, None, DeoptArgs, GCArgs, Name);
678 }
679 
680 template <typename T0, typename T1, typename T2, typename T3>
681 static InvokeInst *CreateGCStatepointInvokeCommon(
682     IRBuilderBase *Builder, uint64_t ID, uint32_t NumPatchBytes,
683     Value *ActualInvokee, BasicBlock *NormalDest, BasicBlock *UnwindDest,
684     uint32_t Flags, ArrayRef<T0> InvokeArgs, ArrayRef<T1> TransitionArgs,
685     ArrayRef<T2> DeoptArgs, ArrayRef<T3> GCArgs, const Twine &Name) {
686   // Extract out the type of the callee.
687   auto *FuncPtrType = cast<PointerType>(ActualInvokee->getType());
688   assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
689          "actual callee must be a callable value");
690 
691   Module *M = Builder->GetInsertBlock()->getParent()->getParent();
692   // Fill in the one generic type'd argument (the function is also vararg)
693   Function *FnStatepoint = Intrinsic::getDeclaration(
694       M, Intrinsic::experimental_gc_statepoint, {FuncPtrType});
695 
696   std::vector<Value *> Args =
697       getStatepointArgs(*Builder, ID, NumPatchBytes, ActualInvokee, Flags,
698                         InvokeArgs, TransitionArgs, DeoptArgs, GCArgs);
699   return createInvokeHelper(FnStatepoint, NormalDest, UnwindDest, Args, Builder,
700                             Name);
701 }
702 
703 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
704     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
705     BasicBlock *NormalDest, BasicBlock *UnwindDest,
706     ArrayRef<Value *> InvokeArgs, ArrayRef<Value *> DeoptArgs,
707     ArrayRef<Value *> GCArgs, const Twine &Name) {
708   return CreateGCStatepointInvokeCommon<Value *, Value *, Value *, Value *>(
709       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
710       uint32_t(StatepointFlags::None), InvokeArgs, None /* No Transition Args*/,
711       DeoptArgs, GCArgs, Name);
712 }
713 
714 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
715     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
716     BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
717     ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
718     ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
719   return CreateGCStatepointInvokeCommon<Use, Use, Use, Value *>(
720       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest, Flags,
721       InvokeArgs, TransitionArgs, DeoptArgs, GCArgs, Name);
722 }
723 
724 InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
725     uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
726     BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
727     ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
728   return CreateGCStatepointInvokeCommon<Use, Value *, Value *, Value *>(
729       this, ID, NumPatchBytes, ActualInvokee, NormalDest, UnwindDest,
730       uint32_t(StatepointFlags::None), InvokeArgs, None, DeoptArgs, GCArgs,
731       Name);
732 }
733 
734 CallInst *IRBuilderBase::CreateGCResult(Instruction *Statepoint,
735                                        Type *ResultType,
736                                        const Twine &Name) {
737  Intrinsic::ID ID = Intrinsic::experimental_gc_result;
738  Module *M = BB->getParent()->getParent();
739  Type *Types[] = {ResultType};
740  Function *FnGCResult = Intrinsic::getDeclaration(M, ID, Types);
741 
742  Value *Args[] = {Statepoint};
743  return createCallHelper(FnGCResult, Args, this, Name);
744 }
745 
746 CallInst *IRBuilderBase::CreateGCRelocate(Instruction *Statepoint,
747                                          int BaseOffset,
748                                          int DerivedOffset,
749                                          Type *ResultType,
750                                          const Twine &Name) {
751  Module *M = BB->getParent()->getParent();
752  Type *Types[] = {ResultType};
753  Function *FnGCRelocate =
754      Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
755 
756  Value *Args[] = {Statepoint,
757                   getInt32(BaseOffset),
758                   getInt32(DerivedOffset)};
759  return createCallHelper(FnGCRelocate, Args, this, Name);
760 }
761 
762 CallInst *IRBuilderBase::CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
763                                               Instruction *FMFSource,
764                                               const Twine &Name) {
765   Module *M = BB->getModule();
766   Function *Fn = Intrinsic::getDeclaration(M, ID, {V->getType()});
767   return createCallHelper(Fn, {V}, this, Name, FMFSource);
768 }
769 
770 CallInst *IRBuilderBase::CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS,
771                                                Value *RHS,
772                                                Instruction *FMFSource,
773                                                const Twine &Name) {
774   Module *M = BB->getModule();
775   Function *Fn = Intrinsic::getDeclaration(M, ID, { LHS->getType() });
776   return createCallHelper(Fn, {LHS, RHS}, this, Name, FMFSource);
777 }
778 
779 CallInst *IRBuilderBase::CreateIntrinsic(Intrinsic::ID ID,
780                                          ArrayRef<Type *> Types,
781                                          ArrayRef<Value *> Args,
782                                          Instruction *FMFSource,
783                                          const Twine &Name) {
784   Module *M = BB->getModule();
785   Function *Fn = Intrinsic::getDeclaration(M, ID, Types);
786   return createCallHelper(Fn, Args, this, Name, FMFSource);
787 }
788 
789 IRBuilderDefaultInserter::~IRBuilderDefaultInserter() {}
790 IRBuilderCallbackInserter::~IRBuilderCallbackInserter() {}
791 IRBuilderFolder::~IRBuilderFolder() {}
792 void ConstantFolder::anchor() {}
793 void NoFolder::anchor() {}
794