Bug Summary

File:llvm/include/llvm/IR/DerivedTypes.h
Warning:line 440, column 24
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Function.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/IR -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/IR -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/IR -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/lib/IR -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/IR/Function.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/lib/IR/Function.cpp

1//===- Function.cpp - Implement the Global object classes -----------------===//
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 Function class for the IR library.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Function.h"
14#include "SymbolTableListTraitsImpl.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseSet.h"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/IR/AbstractCallSite.h"
24#include "llvm/IR/Argument.h"
25#include "llvm/IR/Attributes.h"
26#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/Constant.h"
28#include "llvm/IR/Constants.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalValue.h"
31#include "llvm/IR/InstIterator.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/IntrinsicsAArch64.h"
37#include "llvm/IR/IntrinsicsAMDGPU.h"
38#include "llvm/IR/IntrinsicsARM.h"
39#include "llvm/IR/IntrinsicsBPF.h"
40#include "llvm/IR/IntrinsicsHexagon.h"
41#include "llvm/IR/IntrinsicsMips.h"
42#include "llvm/IR/IntrinsicsNVPTX.h"
43#include "llvm/IR/IntrinsicsPowerPC.h"
44#include "llvm/IR/IntrinsicsR600.h"
45#include "llvm/IR/IntrinsicsRISCV.h"
46#include "llvm/IR/IntrinsicsS390.h"
47#include "llvm/IR/IntrinsicsVE.h"
48#include "llvm/IR/IntrinsicsWebAssembly.h"
49#include "llvm/IR/IntrinsicsX86.h"
50#include "llvm/IR/IntrinsicsXCore.h"
51#include "llvm/IR/LLVMContext.h"
52#include "llvm/IR/MDBuilder.h"
53#include "llvm/IR/Metadata.h"
54#include "llvm/IR/Module.h"
55#include "llvm/IR/Operator.h"
56#include "llvm/IR/SymbolTableListTraits.h"
57#include "llvm/IR/Type.h"
58#include "llvm/IR/Use.h"
59#include "llvm/IR/User.h"
60#include "llvm/IR/Value.h"
61#include "llvm/IR/ValueSymbolTable.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/Compiler.h"
65#include "llvm/Support/ErrorHandling.h"
66#include <algorithm>
67#include <cassert>
68#include <cstddef>
69#include <cstdint>
70#include <cstring>
71#include <string>
72
73using namespace llvm;
74using ProfileCount = Function::ProfileCount;
75
76// Explicit instantiations of SymbolTableListTraits since some of the methods
77// are not in the public header file...
78template class llvm::SymbolTableListTraits<BasicBlock>;
79
80static cl::opt<unsigned> NonGlobalValueMaxNameSize(
81 "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
82 cl::desc("Maximum size for the name of non-global values."));
83
84//===----------------------------------------------------------------------===//
85// Argument Implementation
86//===----------------------------------------------------------------------===//
87
88Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
89 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
90 setName(Name);
91}
92
93void Argument::setParent(Function *parent) {
94 Parent = parent;
95}
96
97bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
98 if (!getType()->isPointerTy()) return false;
99 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) &&
100 (AllowUndefOrPoison ||
101 getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef)))
102 return true;
103 else if (getDereferenceableBytes() > 0 &&
104 !NullPointerIsDefined(getParent(),
105 getType()->getPointerAddressSpace()))
106 return true;
107 return false;
108}
109
110bool Argument::hasByValAttr() const {
111 if (!getType()->isPointerTy()) return false;
112 return hasAttribute(Attribute::ByVal);
113}
114
115bool Argument::hasByRefAttr() const {
116 if (!getType()->isPointerTy())
117 return false;
118 return hasAttribute(Attribute::ByRef);
119}
120
121bool Argument::hasSwiftSelfAttr() const {
122 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
123}
124
125bool Argument::hasSwiftErrorAttr() const {
126 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
127}
128
129bool Argument::hasInAllocaAttr() const {
130 if (!getType()->isPointerTy()) return false;
131 return hasAttribute(Attribute::InAlloca);
132}
133
134bool Argument::hasPreallocatedAttr() const {
135 if (!getType()->isPointerTy())
136 return false;
137 return hasAttribute(Attribute::Preallocated);
138}
139
140bool Argument::hasPassPointeeByValueCopyAttr() const {
141 if (!getType()->isPointerTy()) return false;
142 AttributeList Attrs = getParent()->getAttributes();
143 return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
144 Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
145 Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated);
146}
147
148bool Argument::hasPointeeInMemoryValueAttr() const {
149 if (!getType()->isPointerTy())
150 return false;
151 AttributeList Attrs = getParent()->getAttributes();
152 return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
153 Attrs.hasParamAttr(getArgNo(), Attribute::StructRet) ||
154 Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
155 Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated) ||
156 Attrs.hasParamAttr(getArgNo(), Attribute::ByRef);
157}
158
159/// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
160/// parameter type.
161static Type *getMemoryParamAllocType(AttributeSet ParamAttrs, Type *ArgTy) {
162 // FIXME: All the type carrying attributes are mutually exclusive, so there
163 // should be a single query to get the stored type that handles any of them.
164 if (Type *ByValTy = ParamAttrs.getByValType())
165 return ByValTy;
166 if (Type *ByRefTy = ParamAttrs.getByRefType())
167 return ByRefTy;
168 if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
169 return PreAllocTy;
170 if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
171 return InAllocaTy;
172 if (Type *SRetTy = ParamAttrs.getStructRetType())
173 return SRetTy;
174
175 return nullptr;
176}
177
178uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
179 AttributeSet ParamAttrs =
180 getParent()->getAttributes().getParamAttrs(getArgNo());
181 if (Type *MemTy = getMemoryParamAllocType(ParamAttrs, getType()))
182 return DL.getTypeAllocSize(MemTy);
183 return 0;
184}
185
186Type *Argument::getPointeeInMemoryValueType() const {
187 AttributeSet ParamAttrs =
188 getParent()->getAttributes().getParamAttrs(getArgNo());
189 return getMemoryParamAllocType(ParamAttrs, getType());
190}
191
192unsigned Argument::getParamAlignment() const {
193 assert(getType()->isPointerTy() && "Only pointers have alignments")(static_cast<void> (0));
194 return getParent()->getParamAlignment(getArgNo());
195}
196
197MaybeAlign Argument::getParamAlign() const {
198 assert(getType()->isPointerTy() && "Only pointers have alignments")(static_cast<void> (0));
199 return getParent()->getParamAlign(getArgNo());
200}
201
202MaybeAlign Argument::getParamStackAlign() const {
203 return getParent()->getParamStackAlign(getArgNo());
204}
205
206Type *Argument::getParamByValType() const {
207 assert(getType()->isPointerTy() && "Only pointers have byval types")(static_cast<void> (0));
208 return getParent()->getParamByValType(getArgNo());
209}
210
211Type *Argument::getParamStructRetType() const {
212 assert(getType()->isPointerTy() && "Only pointers have sret types")(static_cast<void> (0));
213 return getParent()->getParamStructRetType(getArgNo());
214}
215
216Type *Argument::getParamByRefType() const {
217 assert(getType()->isPointerTy() && "Only pointers have byref types")(static_cast<void> (0));
218 return getParent()->getParamByRefType(getArgNo());
219}
220
221Type *Argument::getParamInAllocaType() const {
222 assert(getType()->isPointerTy() && "Only pointers have inalloca types")(static_cast<void> (0));
223 return getParent()->getParamInAllocaType(getArgNo());
224}
225
226uint64_t Argument::getDereferenceableBytes() const {
227 assert(getType()->isPointerTy() &&(static_cast<void> (0))
228 "Only pointers have dereferenceable bytes")(static_cast<void> (0));
229 return getParent()->getParamDereferenceableBytes(getArgNo());
230}
231
232uint64_t Argument::getDereferenceableOrNullBytes() const {
233 assert(getType()->isPointerTy() &&(static_cast<void> (0))
234 "Only pointers have dereferenceable bytes")(static_cast<void> (0));
235 return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
236}
237
238bool Argument::hasNestAttr() const {
239 if (!getType()->isPointerTy()) return false;
240 return hasAttribute(Attribute::Nest);
241}
242
243bool Argument::hasNoAliasAttr() const {
244 if (!getType()->isPointerTy()) return false;
245 return hasAttribute(Attribute::NoAlias);
246}
247
248bool Argument::hasNoCaptureAttr() const {
249 if (!getType()->isPointerTy()) return false;
250 return hasAttribute(Attribute::NoCapture);
251}
252
253bool Argument::hasNoFreeAttr() const {
254 if (!getType()->isPointerTy()) return false;
255 return hasAttribute(Attribute::NoFree);
256}
257
258bool Argument::hasStructRetAttr() const {
259 if (!getType()->isPointerTy()) return false;
260 return hasAttribute(Attribute::StructRet);
261}
262
263bool Argument::hasInRegAttr() const {
264 return hasAttribute(Attribute::InReg);
265}
266
267bool Argument::hasReturnedAttr() const {
268 return hasAttribute(Attribute::Returned);
269}
270
271bool Argument::hasZExtAttr() const {
272 return hasAttribute(Attribute::ZExt);
273}
274
275bool Argument::hasSExtAttr() const {
276 return hasAttribute(Attribute::SExt);
277}
278
279bool Argument::onlyReadsMemory() const {
280 AttributeList Attrs = getParent()->getAttributes();
281 return Attrs.hasParamAttr(getArgNo(), Attribute::ReadOnly) ||
282 Attrs.hasParamAttr(getArgNo(), Attribute::ReadNone);
283}
284
285void Argument::addAttrs(AttrBuilder &B) {
286 AttributeList AL = getParent()->getAttributes();
287 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
288 getParent()->setAttributes(AL);
289}
290
291void Argument::addAttr(Attribute::AttrKind Kind) {
292 getParent()->addParamAttr(getArgNo(), Kind);
293}
294
295void Argument::addAttr(Attribute Attr) {
296 getParent()->addParamAttr(getArgNo(), Attr);
297}
298
299void Argument::removeAttr(Attribute::AttrKind Kind) {
300 getParent()->removeParamAttr(getArgNo(), Kind);
301}
302
303void Argument::removeAttrs(const AttrBuilder &B) {
304 AttributeList AL = getParent()->getAttributes();
305 AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), B);
306 getParent()->setAttributes(AL);
307}
308
309bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
310 return getParent()->hasParamAttribute(getArgNo(), Kind);
311}
312
313Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
314 return getParent()->getParamAttribute(getArgNo(), Kind);
315}
316
317//===----------------------------------------------------------------------===//
318// Helper Methods in Function
319//===----------------------------------------------------------------------===//
320
321LLVMContext &Function::getContext() const {
322 return getType()->getContext();
323}
324
325unsigned Function::getInstructionCount() const {
326 unsigned NumInstrs = 0;
327 for (const BasicBlock &BB : BasicBlocks)
328 NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
329 BB.instructionsWithoutDebug().end());
330 return NumInstrs;
331}
332
333Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
334 const Twine &N, Module &M) {
335 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
336}
337
338Function *Function::createWithDefaultAttr(FunctionType *Ty,
339 LinkageTypes Linkage,
340 unsigned AddrSpace, const Twine &N,
341 Module *M) {
342 auto *F = new Function(Ty, Linkage, AddrSpace, N, M);
343 AttrBuilder B;
344 if (M->getUwtable())
345 B.addAttribute(Attribute::UWTable);
346 switch (M->getFramePointer()) {
347 case FramePointerKind::None:
348 // 0 ("none") is the default.
349 break;
350 case FramePointerKind::NonLeaf:
351 B.addAttribute("frame-pointer", "non-leaf");
352 break;
353 case FramePointerKind::All:
354 B.addAttribute("frame-pointer", "all");
355 break;
356 }
357 F->addFnAttrs(B);
358 return F;
359}
360
361void Function::removeFromParent() {
362 getParent()->getFunctionList().remove(getIterator());
363}
364
365void Function::eraseFromParent() {
366 getParent()->getFunctionList().erase(getIterator());
367}
368
369//===----------------------------------------------------------------------===//
370// Function Implementation
371//===----------------------------------------------------------------------===//
372
373static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
374 // If AS == -1 and we are passed a valid module pointer we place the function
375 // in the program address space. Otherwise we default to AS0.
376 if (AddrSpace == static_cast<unsigned>(-1))
377 return M ? M->getDataLayout().getProgramAddressSpace() : 0;
378 return AddrSpace;
379}
380
381Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
382 const Twine &name, Module *ParentModule)
383 : GlobalObject(Ty, Value::FunctionVal,
384 OperandTraits<Function>::op_begin(this), 0, Linkage, name,
385 computeAddrSpace(AddrSpace, ParentModule)),
386 NumArgs(Ty->getNumParams()) {
387 assert(FunctionType::isValidReturnType(getReturnType()) &&(static_cast<void> (0))
388 "invalid return type")(static_cast<void> (0));
389 setGlobalObjectSubClassData(0);
390
391 // We only need a symbol table for a function if the context keeps value names
392 if (!getContext().shouldDiscardValueNames())
393 SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize);
394
395 // If the function has arguments, mark them as lazily built.
396 if (Ty->getNumParams())
397 setValueSubclassData(1); // Set the "has lazy arguments" bit.
398
399 if (ParentModule)
400 ParentModule->getFunctionList().push_back(this);
401
402 HasLLVMReservedName = getName().startswith("llvm.");
403 // Ensure intrinsics have the right parameter attributes.
404 // Note, the IntID field will have been set in Value::setName if this function
405 // name is a valid intrinsic ID.
406 if (IntID)
407 setAttributes(Intrinsic::getAttributes(getContext(), IntID));
408}
409
410Function::~Function() {
411 dropAllReferences(); // After this it is safe to delete instructions.
412
413 // Delete all of the method arguments and unlink from symbol table...
414 if (Arguments)
415 clearArguments();
416
417 // Remove the function from the on-the-side GC table.
418 clearGC();
419}
420
421void Function::BuildLazyArguments() const {
422 // Create the arguments vector, all arguments start out unnamed.
423 auto *FT = getFunctionType();
424 if (NumArgs > 0) {
425 Arguments = std::allocator<Argument>().allocate(NumArgs);
426 for (unsigned i = 0, e = NumArgs; i != e; ++i) {
427 Type *ArgTy = FT->getParamType(i);
428 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!")(static_cast<void> (0));
429 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
430 }
431 }
432
433 // Clear the lazy arguments bit.
434 unsigned SDC = getSubclassDataFromValue();
435 SDC &= ~(1 << 0);
436 const_cast<Function*>(this)->setValueSubclassData(SDC);
437 assert(!hasLazyArguments())(static_cast<void> (0));
438}
439
440static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
441 return MutableArrayRef<Argument>(Args, Count);
442}
443
444bool Function::isConstrainedFPIntrinsic() const {
445 switch (getIntrinsicID()) {
446#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
447 case Intrinsic::INTRINSIC:
448#include "llvm/IR/ConstrainedOps.def"
449 return true;
450#undef INSTRUCTION
451 default:
452 return false;
453 }
454}
455
456void Function::clearArguments() {
457 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
458 A.setName("");
459 A.~Argument();
460 }
461 std::allocator<Argument>().deallocate(Arguments, NumArgs);
462 Arguments = nullptr;
463}
464
465void Function::stealArgumentListFrom(Function &Src) {
466 assert(isDeclaration() && "Expected no references to current arguments")(static_cast<void> (0));
467
468 // Drop the current arguments, if any, and set the lazy argument bit.
469 if (!hasLazyArguments()) {
470 assert(llvm::all_of(makeArgArray(Arguments, NumArgs),(static_cast<void> (0))
471 [](const Argument &A) { return A.use_empty(); }) &&(static_cast<void> (0))
472 "Expected arguments to be unused in declaration")(static_cast<void> (0));
473 clearArguments();
474 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
475 }
476
477 // Nothing to steal if Src has lazy arguments.
478 if (Src.hasLazyArguments())
479 return;
480
481 // Steal arguments from Src, and fix the lazy argument bits.
482 assert(arg_size() == Src.arg_size())(static_cast<void> (0));
483 Arguments = Src.Arguments;
484 Src.Arguments = nullptr;
485 for (Argument &A : makeArgArray(Arguments, NumArgs)) {
486 // FIXME: This does the work of transferNodesFromList inefficiently.
487 SmallString<128> Name;
488 if (A.hasName())
489 Name = A.getName();
490 if (!Name.empty())
491 A.setName("");
492 A.setParent(this);
493 if (!Name.empty())
494 A.setName(Name);
495 }
496
497 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
498 assert(!hasLazyArguments())(static_cast<void> (0));
499 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
500}
501
502// dropAllReferences() - This function causes all the subinstructions to "let
503// go" of all references that they are maintaining. This allows one to
504// 'delete' a whole class at a time, even though there may be circular
505// references... first all references are dropped, and all use counts go to
506// zero. Then everything is deleted for real. Note that no operations are
507// valid on an object that has "dropped all references", except operator
508// delete.
509//
510void Function::dropAllReferences() {
511 setIsMaterializable(false);
512
513 for (BasicBlock &BB : *this)
514 BB.dropAllReferences();
515
516 // Delete all basic blocks. They are now unused, except possibly by
517 // blockaddresses, but BasicBlock's destructor takes care of those.
518 while (!BasicBlocks.empty())
519 BasicBlocks.begin()->eraseFromParent();
520
521 // Drop uses of any optional data (real or placeholder).
522 if (getNumOperands()) {
523 User::dropAllReferences();
524 setNumHungOffUseOperands(0);
525 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
526 }
527
528 // Metadata is stored in a side-table.
529 clearMetadata();
530}
531
532void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {
533 AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr);
534}
535
536void Function::addFnAttr(Attribute::AttrKind Kind) {
537 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind);
538}
539
540void Function::addFnAttr(StringRef Kind, StringRef Val) {
541 AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val);
542}
543
544void Function::addFnAttr(Attribute Attr) {
545 AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr);
546}
547
548void Function::addFnAttrs(const AttrBuilder &Attrs) {
549 AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs);
550}
551
552void Function::addRetAttr(Attribute::AttrKind Kind) {
553 AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind);
554}
555
556void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
557 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind);
558}
559
560void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
561 AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr);
562}
563
564void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
565 AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs);
566}
567
568void Function::removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
569 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
570}
571
572void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {
573 AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
574}
575
576void Function::removeFnAttr(Attribute::AttrKind Kind) {
577 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
578}
579
580void Function::removeFnAttr(StringRef Kind) {
581 AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
582}
583
584void Function::removeFnAttrs(const AttrBuilder &Attrs) {
585 AttributeSets = AttributeSets.removeFnAttributes(getContext(), Attrs);
586}
587
588void Function::removeRetAttr(Attribute::AttrKind Kind) {
589 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
590}
591
592void Function::removeRetAttr(StringRef Kind) {
593 AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
594}
595
596void Function::removeRetAttrs(const AttrBuilder &Attrs) {
597 AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs);
598}
599
600void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
601 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
602}
603
604void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
605 AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
606}
607
608void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
609 AttributeSets =
610 AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs);
611}
612
613void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
614 AttributeSets =
615 AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
616}
617
618bool Function::hasFnAttribute(Attribute::AttrKind Kind) const {
619 return AttributeSets.hasFnAttr(Kind);
620}
621
622bool Function::hasFnAttribute(StringRef Kind) const {
623 return AttributeSets.hasFnAttr(Kind);
624}
625
626bool Function::hasRetAttribute(Attribute::AttrKind Kind) const {
627 return AttributeSets.hasRetAttr(Kind);
628}
629
630bool Function::hasParamAttribute(unsigned ArgNo,
631 Attribute::AttrKind Kind) const {
632 return AttributeSets.hasParamAttr(ArgNo, Kind);
633}
634
635Attribute Function::getAttributeAtIndex(unsigned i,
636 Attribute::AttrKind Kind) const {
637 return AttributeSets.getAttributeAtIndex(i, Kind);
638}
639
640Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {
641 return AttributeSets.getAttributeAtIndex(i, Kind);
642}
643
644Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {
645 return AttributeSets.getFnAttr(Kind);
646}
647
648Attribute Function::getFnAttribute(StringRef Kind) const {
649 return AttributeSets.getFnAttr(Kind);
650}
651
652/// gets the specified attribute from the list of attributes.
653Attribute Function::getParamAttribute(unsigned ArgNo,
654 Attribute::AttrKind Kind) const {
655 return AttributeSets.getParamAttr(ArgNo, Kind);
656}
657
658void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
659 uint64_t Bytes) {
660 AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(),
661 ArgNo, Bytes);
662}
663
664DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {
665 if (&FPType == &APFloat::IEEEsingle()) {
666 Attribute Attr = getFnAttribute("denormal-fp-math-f32");
667 StringRef Val = Attr.getValueAsString();
668 if (!Val.empty())
669 return parseDenormalFPAttribute(Val);
670
671 // If the f32 variant of the attribute isn't specified, try to use the
672 // generic one.
673 }
674
675 Attribute Attr = getFnAttribute("denormal-fp-math");
676 return parseDenormalFPAttribute(Attr.getValueAsString());
677}
678
679const std::string &Function::getGC() const {
680 assert(hasGC() && "Function has no collector")(static_cast<void> (0));
681 return getContext().getGC(*this);
682}
683
684void Function::setGC(std::string Str) {
685 setValueSubclassDataBit(14, !Str.empty());
686 getContext().setGC(*this, std::move(Str));
687}
688
689void Function::clearGC() {
690 if (!hasGC())
691 return;
692 getContext().deleteGC(*this);
693 setValueSubclassDataBit(14, false);
694}
695
696bool Function::hasStackProtectorFnAttr() const {
697 return hasFnAttribute(Attribute::StackProtect) ||
698 hasFnAttribute(Attribute::StackProtectStrong) ||
699 hasFnAttribute(Attribute::StackProtectReq);
700}
701
702/// Copy all additional attributes (those not needed to create a Function) from
703/// the Function Src to this one.
704void Function::copyAttributesFrom(const Function *Src) {
705 GlobalObject::copyAttributesFrom(Src);
706 setCallingConv(Src->getCallingConv());
707 setAttributes(Src->getAttributes());
708 if (Src->hasGC())
709 setGC(Src->getGC());
710 else
711 clearGC();
712 if (Src->hasPersonalityFn())
713 setPersonalityFn(Src->getPersonalityFn());
714 if (Src->hasPrefixData())
715 setPrefixData(Src->getPrefixData());
716 if (Src->hasPrologueData())
717 setPrologueData(Src->getPrologueData());
718}
719
720/// Table of string intrinsic names indexed by enum value.
721static const char * const IntrinsicNameTable[] = {
722 "not_intrinsic",
723#define GET_INTRINSIC_NAME_TABLE
724#include "llvm/IR/IntrinsicImpl.inc"
725#undef GET_INTRINSIC_NAME_TABLE
726};
727
728/// Table of per-target intrinsic name tables.
729#define GET_INTRINSIC_TARGET_DATA
730#include "llvm/IR/IntrinsicImpl.inc"
731#undef GET_INTRINSIC_TARGET_DATA
732
733bool Function::isTargetIntrinsic(Intrinsic::ID IID) {
734 return IID > TargetInfos[0].Count;
735}
736
737bool Function::isTargetIntrinsic() const {
738 return isTargetIntrinsic(IntID);
739}
740
741/// Find the segment of \c IntrinsicNameTable for intrinsics with the same
742/// target as \c Name, or the generic table if \c Name is not target specific.
743///
744/// Returns the relevant slice of \c IntrinsicNameTable
745static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
746 assert(Name.startswith("llvm."))(static_cast<void> (0));
747
748 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
749 // Drop "llvm." and take the first dotted component. That will be the target
750 // if this is target specific.
751 StringRef Target = Name.drop_front(5).split('.').first;
752 auto It = partition_point(
753 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
754 // We've either found the target or just fall back to the generic set, which
755 // is always first.
756 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
757 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
758}
759
760/// This does the actual lookup of an intrinsic ID which
761/// matches the given function name.
762Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
763 ArrayRef<const char *> NameTable = findTargetSubtable(Name);
764 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
765 if (Idx == -1)
766 return Intrinsic::not_intrinsic;
767
768 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
769 // an index into a sub-table.
770 int Adjust = NameTable.data() - IntrinsicNameTable;
771 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
772
773 // If the intrinsic is not overloaded, require an exact match. If it is
774 // overloaded, require either exact or prefix match.
775 const auto MatchSize = strlen(NameTable[Idx]);
776 assert(Name.size() >= MatchSize && "Expected either exact or prefix match")(static_cast<void> (0));
777 bool IsExactMatch = Name.size() == MatchSize;
778 return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
779 : Intrinsic::not_intrinsic;
780}
781
782void Function::recalculateIntrinsicID() {
783 StringRef Name = getName();
784 if (!Name.startswith("llvm.")) {
785 HasLLVMReservedName = false;
786 IntID = Intrinsic::not_intrinsic;
787 return;
788 }
789 HasLLVMReservedName = true;
790 IntID = lookupIntrinsicID(Name);
791}
792
793/// Returns a stable mangling for the type specified for use in the name
794/// mangling scheme used by 'any' types in intrinsic signatures. The mangling
795/// of named types is simply their name. Manglings for unnamed types consist
796/// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
797/// combined with the mangling of their component types. A vararg function
798/// type will have a suffix of 'vararg'. Since function types can contain
799/// other function types, we close a function type mangling with suffix 'f'
800/// which can't be confused with it's prefix. This ensures we don't have
801/// collisions between two unrelated function types. Otherwise, you might
802/// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
803/// The HasUnnamedType boolean is set if an unnamed type was encountered,
804/// indicating that extra care must be taken to ensure a unique name.
805static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {
806 std::string Result;
807 if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) {
808 Result += "p" + utostr(PTyp->getAddressSpace());
809 // Opaque pointer doesn't have pointee type information, so we just mangle
810 // address space for opaque pointer.
811 if (!PTyp->isOpaque())
812 Result += getMangledTypeStr(PTyp->getElementType(), HasUnnamedType);
813 } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) {
814 Result += "a" + utostr(ATyp->getNumElements()) +
815 getMangledTypeStr(ATyp->getElementType(), HasUnnamedType);
816 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
817 if (!STyp->isLiteral()) {
818 Result += "s_";
819 if (STyp->hasName())
820 Result += STyp->getName();
821 else
822 HasUnnamedType = true;
823 } else {
824 Result += "sl_";
825 for (auto Elem : STyp->elements())
826 Result += getMangledTypeStr(Elem, HasUnnamedType);
827 }
828 // Ensure nested structs are distinguishable.
829 Result += "s";
830 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
831 Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType);
832 for (size_t i = 0; i < FT->getNumParams(); i++)
833 Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType);
834 if (FT->isVarArg())
835 Result += "vararg";
836 // Ensure nested function types are distinguishable.
837 Result += "f";
838 } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
839 ElementCount EC = VTy->getElementCount();
840 if (EC.isScalable())
841 Result += "nx";
842 Result += "v" + utostr(EC.getKnownMinValue()) +
843 getMangledTypeStr(VTy->getElementType(), HasUnnamedType);
844 } else if (Ty) {
845 switch (Ty->getTypeID()) {
846 default: llvm_unreachable("Unhandled type")__builtin_unreachable();
847 case Type::VoidTyID: Result += "isVoid"; break;
848 case Type::MetadataTyID: Result += "Metadata"; break;
849 case Type::HalfTyID: Result += "f16"; break;
850 case Type::BFloatTyID: Result += "bf16"; break;
851 case Type::FloatTyID: Result += "f32"; break;
852 case Type::DoubleTyID: Result += "f64"; break;
853 case Type::X86_FP80TyID: Result += "f80"; break;
854 case Type::FP128TyID: Result += "f128"; break;
855 case Type::PPC_FP128TyID: Result += "ppcf128"; break;
856 case Type::X86_MMXTyID: Result += "x86mmx"; break;
857 case Type::X86_AMXTyID: Result += "x86amx"; break;
858 case Type::IntegerTyID:
859 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
860 break;
861 }
862 }
863 return Result;
864}
865
866StringRef Intrinsic::getBaseName(ID id) {
867 assert(id < num_intrinsics && "Invalid intrinsic ID!")(static_cast<void> (0));
868 return IntrinsicNameTable[id];
869}
870
871StringRef Intrinsic::getName(ID id) {
872 assert(id < num_intrinsics && "Invalid intrinsic ID!")(static_cast<void> (0));
873 assert(!Intrinsic::isOverloaded(id) &&(static_cast<void> (0))
874 "This version of getName does not support overloading")(static_cast<void> (0));
875 return getBaseName(id);
876}
877
878static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys,
879 Module *M, FunctionType *FT,
880 bool EarlyModuleCheck) {
881
882 assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!")(static_cast<void> (0));
883 assert((Tys.empty() || Intrinsic::isOverloaded(Id)) &&(static_cast<void> (0))
884 "This version of getName is for overloaded intrinsics only")(static_cast<void> (0));
885 (void)EarlyModuleCheck;
886 assert((!EarlyModuleCheck || M ||(static_cast<void> (0))
887 !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) &&(static_cast<void> (0))
888 "Intrinsic overloading on pointer types need to provide a Module")(static_cast<void> (0));
889 bool HasUnnamedType = false;
890 std::string Result(Intrinsic::getBaseName(Id));
891 for (Type *Ty : Tys)
892 Result += "." + getMangledTypeStr(Ty, HasUnnamedType);
893 if (HasUnnamedType) {
894 assert(M && "unnamed types need a module")(static_cast<void> (0));
895 if (!FT)
896 FT = Intrinsic::getType(M->getContext(), Id, Tys);
897 else
898 assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) &&(static_cast<void> (0))
899 "Provided FunctionType must match arguments")(static_cast<void> (0));
900 return M->getUniqueIntrinsicName(Result, Id, FT);
901 }
902 return Result;
903}
904
905std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M,
906 FunctionType *FT) {
907 assert(M && "We need to have a Module")(static_cast<void> (0));
908 return getIntrinsicNameImpl(Id, Tys, M, FT, true);
909}
910
911std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) {
912 return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false);
913}
914
915/// IIT_Info - These are enumerators that describe the entries returned by the
916/// getIntrinsicInfoTableEntries function.
917///
918/// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
919enum IIT_Info {
920 // Common values should be encoded with 0-15.
921 IIT_Done = 0,
922 IIT_I1 = 1,
923 IIT_I8 = 2,
924 IIT_I16 = 3,
925 IIT_I32 = 4,
926 IIT_I64 = 5,
927 IIT_F16 = 6,
928 IIT_F32 = 7,
929 IIT_F64 = 8,
930 IIT_V2 = 9,
931 IIT_V4 = 10,
932 IIT_V8 = 11,
933 IIT_V16 = 12,
934 IIT_V32 = 13,
935 IIT_PTR = 14,
936 IIT_ARG = 15,
937
938 // Values from 16+ are only encodable with the inefficient encoding.
939 IIT_V64 = 16,
940 IIT_MMX = 17,
941 IIT_TOKEN = 18,
942 IIT_METADATA = 19,
943 IIT_EMPTYSTRUCT = 20,
944 IIT_STRUCT2 = 21,
945 IIT_STRUCT3 = 22,
946 IIT_STRUCT4 = 23,
947 IIT_STRUCT5 = 24,
948 IIT_EXTEND_ARG = 25,
949 IIT_TRUNC_ARG = 26,
950 IIT_ANYPTR = 27,
951 IIT_V1 = 28,
952 IIT_VARARG = 29,
953 IIT_HALF_VEC_ARG = 30,
954 IIT_SAME_VEC_WIDTH_ARG = 31,
955 IIT_PTR_TO_ARG = 32,
956 IIT_PTR_TO_ELT = 33,
957 IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
958 IIT_I128 = 35,
959 IIT_V512 = 36,
960 IIT_V1024 = 37,
961 IIT_STRUCT6 = 38,
962 IIT_STRUCT7 = 39,
963 IIT_STRUCT8 = 40,
964 IIT_F128 = 41,
965 IIT_VEC_ELEMENT = 42,
966 IIT_SCALABLE_VEC = 43,
967 IIT_SUBDIVIDE2_ARG = 44,
968 IIT_SUBDIVIDE4_ARG = 45,
969 IIT_VEC_OF_BITCASTS_TO_INT = 46,
970 IIT_V128 = 47,
971 IIT_BF16 = 48,
972 IIT_STRUCT9 = 49,
973 IIT_V256 = 50,
974 IIT_AMX = 51
975};
976
977static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
978 IIT_Info LastInfo,
979 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
980 using namespace Intrinsic;
981
982 bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
983
984 IIT_Info Info = IIT_Info(Infos[NextElt++]);
985 unsigned StructElts = 2;
986
987 switch (Info) {
988 case IIT_Done:
989 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
990 return;
991 case IIT_VARARG:
992 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
993 return;
994 case IIT_MMX:
995 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
996 return;
997 case IIT_AMX:
998 OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));
999 return;
1000 case IIT_TOKEN:
1001 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
1002 return;
1003 case IIT_METADATA:
1004 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
1005 return;
1006 case IIT_F16:
1007 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
1008 return;
1009 case IIT_BF16:
1010 OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
1011 return;
1012 case IIT_F32:
1013 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
1014 return;
1015 case IIT_F64:
1016 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
1017 return;
1018 case IIT_F128:
1019 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
1020 return;
1021 case IIT_I1:
1022 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
1023 return;
1024 case IIT_I8:
1025 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
1026 return;
1027 case IIT_I16:
1028 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
1029 return;
1030 case IIT_I32:
1031 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
1032 return;
1033 case IIT_I64:
1034 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
1035 return;
1036 case IIT_I128:
1037 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
1038 return;
1039 case IIT_V1:
1040 OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
1041 DecodeIITType(NextElt, Infos, Info, OutputTable);
1042 return;
1043 case IIT_V2:
1044 OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
1045 DecodeIITType(NextElt, Infos, Info, OutputTable);
1046 return;
1047 case IIT_V4:
1048 OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
1049 DecodeIITType(NextElt, Infos, Info, OutputTable);
1050 return;
1051 case IIT_V8:
1052 OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
1053 DecodeIITType(NextElt, Infos, Info, OutputTable);
1054 return;
1055 case IIT_V16:
1056 OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
1057 DecodeIITType(NextElt, Infos, Info, OutputTable);
1058 return;
1059 case IIT_V32:
1060 OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
1061 DecodeIITType(NextElt, Infos, Info, OutputTable);
1062 return;
1063 case IIT_V64:
1064 OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
1065 DecodeIITType(NextElt, Infos, Info, OutputTable);
1066 return;
1067 case IIT_V128:
1068 OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
1069 DecodeIITType(NextElt, Infos, Info, OutputTable);
1070 return;
1071 case IIT_V256:
1072 OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector));
1073 DecodeIITType(NextElt, Infos, Info, OutputTable);
1074 return;
1075 case IIT_V512:
1076 OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
1077 DecodeIITType(NextElt, Infos, Info, OutputTable);
1078 return;
1079 case IIT_V1024:
1080 OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
1081 DecodeIITType(NextElt, Infos, Info, OutputTable);
1082 return;
1083 case IIT_PTR:
1084 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
1085 DecodeIITType(NextElt, Infos, Info, OutputTable);
1086 return;
1087 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
1088 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
1089 Infos[NextElt++]));
1090 DecodeIITType(NextElt, Infos, Info, OutputTable);
1091 return;
1092 }
1093 case IIT_ARG: {
1094 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1095 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
1096 return;
1097 }
1098 case IIT_EXTEND_ARG: {
1099 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1100 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
1101 ArgInfo));
1102 return;
1103 }
1104 case IIT_TRUNC_ARG: {
1105 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1106 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
1107 ArgInfo));
1108 return;
1109 }
1110 case IIT_HALF_VEC_ARG: {
1111 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1112 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
1113 ArgInfo));
1114 return;
1115 }
1116 case IIT_SAME_VEC_WIDTH_ARG: {
1117 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1118 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
1119 ArgInfo));
1120 return;
1121 }
1122 case IIT_PTR_TO_ARG: {
1123 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1124 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
1125 ArgInfo));
1126 return;
1127 }
1128 case IIT_PTR_TO_ELT: {
1129 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1130 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
1131 return;
1132 }
1133 case IIT_VEC_OF_ANYPTRS_TO_ELT: {
1134 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1135 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1136 OutputTable.push_back(
1137 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
1138 return;
1139 }
1140 case IIT_EMPTYSTRUCT:
1141 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
1142 return;
1143 case IIT_STRUCT9: ++StructElts; LLVM_FALLTHROUGH[[gnu::fallthrough]];
1144 case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH[[gnu::fallthrough]];
1145 case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH[[gnu::fallthrough]];
1146 case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH[[gnu::fallthrough]];
1147 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH[[gnu::fallthrough]];
1148 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH[[gnu::fallthrough]];
1149 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH[[gnu::fallthrough]];
1150 case IIT_STRUCT2: {
1151 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
1152
1153 for (unsigned i = 0; i != StructElts; ++i)
1154 DecodeIITType(NextElt, Infos, Info, OutputTable);
1155 return;
1156 }
1157 case IIT_SUBDIVIDE2_ARG: {
1158 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1159 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
1160 ArgInfo));
1161 return;
1162 }
1163 case IIT_SUBDIVIDE4_ARG: {
1164 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1165 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
1166 ArgInfo));
1167 return;
1168 }
1169 case IIT_VEC_ELEMENT: {
1170 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1171 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
1172 ArgInfo));
1173 return;
1174 }
1175 case IIT_SCALABLE_VEC: {
1176 DecodeIITType(NextElt, Infos, Info, OutputTable);
1177 return;
1178 }
1179 case IIT_VEC_OF_BITCASTS_TO_INT: {
1180 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
1181 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
1182 ArgInfo));
1183 return;
1184 }
1185 }
1186 llvm_unreachable("unhandled")__builtin_unreachable();
1187}
1188
1189#define GET_INTRINSIC_GENERATOR_GLOBAL
1190#include "llvm/IR/IntrinsicImpl.inc"
1191#undef GET_INTRINSIC_GENERATOR_GLOBAL
1192
1193void Intrinsic::getIntrinsicInfoTableEntries(ID id,
1194 SmallVectorImpl<IITDescriptor> &T){
1195 // Check to see if the intrinsic's type was expressible by the table.
1196 unsigned TableVal = IIT_Table[id-1];
1197
1198 // Decode the TableVal into an array of IITValues.
1199 SmallVector<unsigned char, 8> IITValues;
1200 ArrayRef<unsigned char> IITEntries;
1201 unsigned NextElt = 0;
1202 if ((TableVal >> 31) != 0) {
1203 // This is an offset into the IIT_LongEncodingTable.
1204 IITEntries = IIT_LongEncodingTable;
1205
1206 // Strip sentinel bit.
1207 NextElt = (TableVal << 1) >> 1;
1208 } else {
1209 // Decode the TableVal into an array of IITValues. If the entry was encoded
1210 // into a single word in the table itself, decode it now.
1211 do {
1212 IITValues.push_back(TableVal & 0xF);
1213 TableVal >>= 4;
1214 } while (TableVal);
1215
1216 IITEntries = IITValues;
1217 NextElt = 0;
1218 }
1219
1220 // Okay, decode the table into the output vector of IITDescriptors.
1221 DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1222 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
1223 DecodeIITType(NextElt, IITEntries, IIT_Done, T);
1224}
1225
1226static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
1227 ArrayRef<Type*> Tys, LLVMContext &Context) {
1228 using namespace Intrinsic;
1229
1230 IITDescriptor D = Infos.front();
1231 Infos = Infos.slice(1);
1232
1233 switch (D.Kind) {
10
Control jumps to 'case VecOfBitcastsToInt:' at line 1314
1234 case IITDescriptor::Void: return Type::getVoidTy(Context);
1235 case IITDescriptor::VarArg: return Type::getVoidTy(Context);
1236 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
1237 case IITDescriptor::AMX: return Type::getX86_AMXTy(Context);
1238 case IITDescriptor::Token: return Type::getTokenTy(Context);
1239 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
1240 case IITDescriptor::Half: return Type::getHalfTy(Context);
1241 case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
1242 case IITDescriptor::Float: return Type::getFloatTy(Context);
1243 case IITDescriptor::Double: return Type::getDoubleTy(Context);
1244 case IITDescriptor::Quad: return Type::getFP128Ty(Context);
1245
1246 case IITDescriptor::Integer:
1247 return IntegerType::get(Context, D.Integer_Width);
1248 case IITDescriptor::Vector:
1249 return VectorType::get(DecodeFixedType(Infos, Tys, Context),
1250 D.Vector_Width);
1251 case IITDescriptor::Pointer:
1252 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
1253 D.Pointer_AddressSpace);
1254 case IITDescriptor::Struct: {
1255 SmallVector<Type *, 8> Elts;
1256 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1257 Elts.push_back(DecodeFixedType(Infos, Tys, Context));
1258 return StructType::get(Context, Elts);
1259 }
1260 case IITDescriptor::Argument:
1261 return Tys[D.getArgumentNumber()];
1262 case IITDescriptor::ExtendArgument: {
1263 Type *Ty = Tys[D.getArgumentNumber()];
1264 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1265 return VectorType::getExtendedElementVectorType(VTy);
1266
1267 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
1268 }
1269 case IITDescriptor::TruncArgument: {
1270 Type *Ty = Tys[D.getArgumentNumber()];
1271 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1272 return VectorType::getTruncatedElementVectorType(VTy);
1273
1274 IntegerType *ITy = cast<IntegerType>(Ty);
1275 assert(ITy->getBitWidth() % 2 == 0)(static_cast<void> (0));
1276 return IntegerType::get(Context, ITy->getBitWidth() / 2);
1277 }
1278 case IITDescriptor::Subdivide2Argument:
1279 case IITDescriptor::Subdivide4Argument: {
1280 Type *Ty = Tys[D.getArgumentNumber()];
1281 VectorType *VTy = dyn_cast<VectorType>(Ty);
1282 assert(VTy && "Expected an argument of Vector Type")(static_cast<void> (0));
1283 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1284 return VectorType::getSubdividedVectorType(VTy, SubDivs);
1285 }
1286 case IITDescriptor::HalfVecArgument:
1287 return VectorType::getHalfElementsVectorType(cast<VectorType>(
1288 Tys[D.getArgumentNumber()]));
1289 case IITDescriptor::SameVecWidthArgument: {
1290 Type *EltTy = DecodeFixedType(Infos, Tys, Context);
1291 Type *Ty = Tys[D.getArgumentNumber()];
1292 if (auto *VTy = dyn_cast<VectorType>(Ty))
1293 return VectorType::get(EltTy, VTy->getElementCount());
1294 return EltTy;
1295 }
1296 case IITDescriptor::PtrToArgument: {
1297 Type *Ty = Tys[D.getArgumentNumber()];
1298 return PointerType::getUnqual(Ty);
1299 }
1300 case IITDescriptor::PtrToElt: {
1301 Type *Ty = Tys[D.getArgumentNumber()];
1302 VectorType *VTy = dyn_cast<VectorType>(Ty);
1303 if (!VTy)
1304 llvm_unreachable("Expected an argument of Vector Type")__builtin_unreachable();
1305 Type *EltTy = VTy->getElementType();
1306 return PointerType::getUnqual(EltTy);
1307 }
1308 case IITDescriptor::VecElementArgument: {
1309 Type *Ty = Tys[D.getArgumentNumber()];
1310 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1311 return VTy->getElementType();
1312 llvm_unreachable("Expected an argument of Vector Type")__builtin_unreachable();
1313 }
1314 case IITDescriptor::VecOfBitcastsToInt: {
1315 Type *Ty = Tys[D.getArgumentNumber()];
1316 VectorType *VTy = dyn_cast<VectorType>(Ty);
11
Assuming 'Ty' is not a 'VectorType'
12
'VTy' initialized to a null pointer value
1317 assert(VTy && "Expected an argument of Vector Type")(static_cast<void> (0));
1318 return VectorType::getInteger(VTy);
13
Passing null pointer value via 1st parameter 'VTy'
14
Calling 'VectorType::getInteger'
1319 }
1320 case IITDescriptor::VecOfAnyPtrsToElt:
1321 // Return the overloaded type (which determines the pointers address space)
1322 return Tys[D.getOverloadArgNumber()];
1323 }
1324 llvm_unreachable("unhandled")__builtin_unreachable();
1325}
1326
1327FunctionType *Intrinsic::getType(LLVMContext &Context,
1328 ID id, ArrayRef<Type*> Tys) {
1329 SmallVector<IITDescriptor, 8> Table;
1330 getIntrinsicInfoTableEntries(id, Table);
1331
1332 ArrayRef<IITDescriptor> TableRef = Table;
1333 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
9
Calling 'DecodeFixedType'
1334
1335 SmallVector<Type*, 8> ArgTys;
1336 while (!TableRef.empty())
1337 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
1338
1339 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
1340 // If we see void type as the type of the last argument, it is vararg intrinsic
1341 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
1342 ArgTys.pop_back();
1343 return FunctionType::get(ResultTy, ArgTys, true);
1344 }
1345 return FunctionType::get(ResultTy, ArgTys, false);
1346}
1347
1348bool Intrinsic::isOverloaded(ID id) {
1349#define GET_INTRINSIC_OVERLOAD_TABLE
1350#include "llvm/IR/IntrinsicImpl.inc"
1351#undef GET_INTRINSIC_OVERLOAD_TABLE
1352}
1353
1354bool Intrinsic::isLeaf(ID id) {
1355 switch (id) {
1356 default:
1357 return true;
1358
1359 case Intrinsic::experimental_gc_statepoint:
1360 case Intrinsic::experimental_patchpoint_void:
1361 case Intrinsic::experimental_patchpoint_i64:
1362 return false;
1363 }
1364}
1365
1366/// This defines the "Intrinsic::getAttributes(ID id)" method.
1367#define GET_INTRINSIC_ATTRIBUTES
1368#include "llvm/IR/IntrinsicImpl.inc"
1369#undef GET_INTRINSIC_ATTRIBUTES
1370
1371Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1372 // There can never be multiple globals with the same name of different types,
1373 // because intrinsics must be a specific type.
1374 auto *FT = getType(M->getContext(), id, Tys);
8
Calling 'getType'
1375 return cast<Function>(
1376 M->getOrInsertFunction(Tys.empty() ? getName(id)
1377 : getName(id, Tys, M, FT),
1378 getType(M->getContext(), id, Tys))
1379 .getCallee());
1380}
1381
1382// This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
1383#define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1384#include "llvm/IR/IntrinsicImpl.inc"
1385#undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1386
1387// This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1388#define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1389#include "llvm/IR/IntrinsicImpl.inc"
1390#undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1391
1392using DeferredIntrinsicMatchPair =
1393 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
1394
1395static bool matchIntrinsicType(
1396 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1397 SmallVectorImpl<Type *> &ArgTys,
1398 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
1399 bool IsDeferredCheck) {
1400 using namespace Intrinsic;
1401
1402 // If we ran out of descriptors, there are too many arguments.
1403 if (Infos.empty()) return true;
1404
1405 // Do this before slicing off the 'front' part
1406 auto InfosRef = Infos;
1407 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
1408 DeferredChecks.emplace_back(T, InfosRef);
1409 return false;
1410 };
1411
1412 IITDescriptor D = Infos.front();
1413 Infos = Infos.slice(1);
1414
1415 switch (D.Kind) {
1416 case IITDescriptor::Void: return !Ty->isVoidTy();
1417 case IITDescriptor::VarArg: return true;
1418 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
1419 case IITDescriptor::AMX: return !Ty->isX86_AMXTy();
1420 case IITDescriptor::Token: return !Ty->isTokenTy();
1421 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1422 case IITDescriptor::Half: return !Ty->isHalfTy();
1423 case IITDescriptor::BFloat: return !Ty->isBFloatTy();
1424 case IITDescriptor::Float: return !Ty->isFloatTy();
1425 case IITDescriptor::Double: return !Ty->isDoubleTy();
1426 case IITDescriptor::Quad: return !Ty->isFP128Ty();
1427 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1428 case IITDescriptor::Vector: {
1429 VectorType *VT = dyn_cast<VectorType>(Ty);
1430 return !VT || VT->getElementCount() != D.Vector_Width ||
1431 matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
1432 DeferredChecks, IsDeferredCheck);
1433 }
1434 case IITDescriptor::Pointer: {
1435 PointerType *PT = dyn_cast<PointerType>(Ty);
1436 if (!PT || PT->getAddressSpace() != D.Pointer_AddressSpace)
1437 return true;
1438 if (!PT->isOpaque())
1439 return matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
1440 DeferredChecks, IsDeferredCheck);
1441 // If typed pointers are supported, do not allow using opaque pointer in
1442 // place of fixed pointer type. This would make the intrinsic signature
1443 // non-unique.
1444 if (Ty->getContext().supportsTypedPointers())
1445 return true;
1446 // Consume IIT descriptors relating to the pointer element type.
1447 while (Infos.front().Kind == IITDescriptor::Pointer)
1448 Infos = Infos.slice(1);
1449 Infos = Infos.slice(1);
1450 return false;
1451 }
1452
1453 case IITDescriptor::Struct: {
1454 StructType *ST = dyn_cast<StructType>(Ty);
1455 if (!ST || ST->getNumElements() != D.Struct_NumElements)
1456 return true;
1457
1458 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1459 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
1460 DeferredChecks, IsDeferredCheck))
1461 return true;
1462 return false;
1463 }
1464
1465 case IITDescriptor::Argument:
1466 // If this is the second occurrence of an argument,
1467 // verify that the later instance matches the previous instance.
1468 if (D.getArgumentNumber() < ArgTys.size())
1469 return Ty != ArgTys[D.getArgumentNumber()];
1470
1471 if (D.getArgumentNumber() > ArgTys.size() ||
1472 D.getArgumentKind() == IITDescriptor::AK_MatchType)
1473 return IsDeferredCheck || DeferCheck(Ty);
1474
1475 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&(static_cast<void> (0))
1476 "Table consistency error")(static_cast<void> (0));
1477 ArgTys.push_back(Ty);
1478
1479 switch (D.getArgumentKind()) {
1480 case IITDescriptor::AK_Any: return false; // Success
1481 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1482 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
1483 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
1484 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1485 default: break;
1486 }
1487 llvm_unreachable("all argument kinds not covered")__builtin_unreachable();
1488
1489 case IITDescriptor::ExtendArgument: {
1490 // If this is a forward reference, defer the check for later.
1491 if (D.getArgumentNumber() >= ArgTys.size())
1492 return IsDeferredCheck || DeferCheck(Ty);
1493
1494 Type *NewTy = ArgTys[D.getArgumentNumber()];
1495 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1496 NewTy = VectorType::getExtendedElementVectorType(VTy);
1497 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1498 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1499 else
1500 return true;
1501
1502 return Ty != NewTy;
1503 }
1504 case IITDescriptor::TruncArgument: {
1505 // If this is a forward reference, defer the check for later.
1506 if (D.getArgumentNumber() >= ArgTys.size())
1507 return IsDeferredCheck || DeferCheck(Ty);
1508
1509 Type *NewTy = ArgTys[D.getArgumentNumber()];
1510 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1511 NewTy = VectorType::getTruncatedElementVectorType(VTy);
1512 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1513 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1514 else
1515 return true;
1516
1517 return Ty != NewTy;
1518 }
1519 case IITDescriptor::HalfVecArgument:
1520 // If this is a forward reference, defer the check for later.
1521 if (D.getArgumentNumber() >= ArgTys.size())
1522 return IsDeferredCheck || DeferCheck(Ty);
1523 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1524 VectorType::getHalfElementsVectorType(
1525 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1526 case IITDescriptor::SameVecWidthArgument: {
1527 if (D.getArgumentNumber() >= ArgTys.size()) {
1528 // Defer check and subsequent check for the vector element type.
1529 Infos = Infos.slice(1);
1530 return IsDeferredCheck || DeferCheck(Ty);
1531 }
1532 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1533 auto *ThisArgType = dyn_cast<VectorType>(Ty);
1534 // Both must be vectors of the same number of elements or neither.
1535 if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
1536 return true;
1537 Type *EltTy = Ty;
1538 if (ThisArgType) {
1539 if (ReferenceType->getElementCount() !=
1540 ThisArgType->getElementCount())
1541 return true;
1542 EltTy = ThisArgType->getElementType();
1543 }
1544 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
1545 IsDeferredCheck);
1546 }
1547 case IITDescriptor::PtrToArgument: {
1548 if (D.getArgumentNumber() >= ArgTys.size())
1549 return IsDeferredCheck || DeferCheck(Ty);
1550 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1551 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1552 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1553 }
1554 case IITDescriptor::PtrToElt: {
1555 if (D.getArgumentNumber() >= ArgTys.size())
1556 return IsDeferredCheck || DeferCheck(Ty);
1557 VectorType * ReferenceType =
1558 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1559 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1560
1561 if (!ThisArgType || !ReferenceType)
1562 return true;
1563 if (!ThisArgType->isOpaque())
1564 return ThisArgType->getElementType() != ReferenceType->getElementType();
1565 // If typed pointers are supported, do not allow opaque pointer to ensure
1566 // uniqueness.
1567 return Ty->getContext().supportsTypedPointers();
1568 }
1569 case IITDescriptor::VecOfAnyPtrsToElt: {
1570 unsigned RefArgNumber = D.getRefArgNumber();
1571 if (RefArgNumber >= ArgTys.size()) {
1572 if (IsDeferredCheck)
1573 return true;
1574 // If forward referencing, already add the pointer-vector type and
1575 // defer the checks for later.
1576 ArgTys.push_back(Ty);
1577 return DeferCheck(Ty);
1578 }
1579
1580 if (!IsDeferredCheck){
1581 assert(D.getOverloadArgNumber() == ArgTys.size() &&(static_cast<void> (0))
1582 "Table consistency error")(static_cast<void> (0));
1583 ArgTys.push_back(Ty);
1584 }
1585
1586 // Verify the overloaded type "matches" the Ref type.
1587 // i.e. Ty is a vector with the same width as Ref.
1588 // Composed of pointers to the same element type as Ref.
1589 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1590 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1591 if (!ThisArgVecTy || !ReferenceType ||
1592 (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
1593 return true;
1594 PointerType *ThisArgEltTy =
1595 dyn_cast<PointerType>(ThisArgVecTy->getElementType());
1596 if (!ThisArgEltTy)
1597 return true;
1598 return !ThisArgEltTy->isOpaqueOrPointeeTypeMatches(
1599 ReferenceType->getElementType());
1600 }
1601 case IITDescriptor::VecElementArgument: {
1602 if (D.getArgumentNumber() >= ArgTys.size())
1603 return IsDeferredCheck ? true : DeferCheck(Ty);
1604 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1605 return !ReferenceType || Ty != ReferenceType->getElementType();
1606 }
1607 case IITDescriptor::Subdivide2Argument:
1608 case IITDescriptor::Subdivide4Argument: {
1609 // If this is a forward reference, defer the check for later.
1610 if (D.getArgumentNumber() >= ArgTys.size())
1611 return IsDeferredCheck || DeferCheck(Ty);
1612
1613 Type *NewTy = ArgTys[D.getArgumentNumber()];
1614 if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
1615 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
1616 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
1617 return Ty != NewTy;
1618 }
1619 return true;
1620 }
1621 case IITDescriptor::VecOfBitcastsToInt: {
1622 if (D.getArgumentNumber() >= ArgTys.size())
1623 return IsDeferredCheck || DeferCheck(Ty);
1624 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1625 auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1626 if (!ThisArgVecTy || !ReferenceType)
1627 return true;
1628 return ThisArgVecTy != VectorType::getInteger(ReferenceType);
1629 }
1630 }
1631 llvm_unreachable("unhandled")__builtin_unreachable();
1632}
1633
1634Intrinsic::MatchIntrinsicTypesResult
1635Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
1636 ArrayRef<Intrinsic::IITDescriptor> &Infos,
1637 SmallVectorImpl<Type *> &ArgTys) {
1638 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
1639 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
1640 false))
1641 return MatchIntrinsicTypes_NoMatchRet;
1642
1643 unsigned NumDeferredReturnChecks = DeferredChecks.size();
1644
1645 for (auto Ty : FTy->params())
1646 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
1647 return MatchIntrinsicTypes_NoMatchArg;
1648
1649 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
1650 DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
1651 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
1652 true))
1653 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
1654 : MatchIntrinsicTypes_NoMatchArg;
1655 }
1656
1657 return MatchIntrinsicTypes_Match;
1658}
1659
1660bool
1661Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1662 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1663 // If there are no descriptors left, then it can't be a vararg.
1664 if (Infos.empty())
1665 return isVarArg;
1666
1667 // There should be only one descriptor remaining at this point.
1668 if (Infos.size() != 1)
1669 return true;
1670
1671 // Check and verify the descriptor.
1672 IITDescriptor D = Infos.front();
1673 Infos = Infos.slice(1);
1674 if (D.Kind == IITDescriptor::VarArg)
1675 return !isVarArg;
1676
1677 return true;
1678}
1679
1680bool Intrinsic::getIntrinsicSignature(Function *F,
1681 SmallVectorImpl<Type *> &ArgTys) {
1682 Intrinsic::ID ID = F->getIntrinsicID();
1683 if (!ID)
1684 return false;
1685
1686 SmallVector<Intrinsic::IITDescriptor, 8> Table;
1687 getIntrinsicInfoTableEntries(ID, Table);
1688 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1689
1690 if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
1691 ArgTys) !=
1692 Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
1693 return false;
1694 }
1695 if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
1696 TableRef))
1697 return false;
1698 return true;
1699}
1700
1701Optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
1702 SmallVector<Type *, 4> ArgTys;
1703 if (!getIntrinsicSignature(F, ArgTys))
1
Taking false branch
1704 return None;
1705
1706 Intrinsic::ID ID = F->getIntrinsicID();
1707 StringRef Name = F->getName();
1708 std::string WantedName =
1709 Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType());
1710 if (Name == WantedName)
2
Assuming the condition is false
3
Taking false branch
1711 return None;
1712
1713 Function *NewDecl = [&] {
4
Calling 'operator()'
1714 if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) {
5
Assuming 'ExistingGV' is null
6
Taking false branch
1715 if (auto *ExistingF = dyn_cast<Function>(ExistingGV))
1716 if (ExistingF->getFunctionType() == F->getFunctionType())
1717 return ExistingF;
1718
1719 // The name already exists, but is not a function or has the wrong
1720 // prototype. Make place for the new one by renaming the old version.
1721 // Either this old version will be removed later on or the module is
1722 // invalid and we'll get an error.
1723 ExistingGV->setName(WantedName + ".renamed");
1724 }
1725 return Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
7
Calling 'getDeclaration'
1726 }();
1727
1728 NewDecl->setCallingConv(F->getCallingConv());
1729 assert(NewDecl->getFunctionType() == F->getFunctionType() &&(static_cast<void> (0))
1730 "Shouldn't change the signature")(static_cast<void> (0));
1731 return NewDecl;
1732}
1733
1734/// hasAddressTaken - returns true if there are any uses of this function
1735/// other than direct calls or invokes to it. Optionally ignores callback
1736/// uses, assume like pointer annotation calls, and references in llvm.used
1737/// and llvm.compiler.used variables.
1738bool Function::hasAddressTaken(const User **PutOffender,
1739 bool IgnoreCallbackUses,
1740 bool IgnoreAssumeLikeCalls,
1741 bool IgnoreLLVMUsed) const {
1742 for (const Use &U : uses()) {
1743 const User *FU = U.getUser();
1744 if (isa<BlockAddress>(FU))
1745 continue;
1746
1747 if (IgnoreCallbackUses) {
1748 AbstractCallSite ACS(&U);
1749 if (ACS && ACS.isCallbackCall())
1750 continue;
1751 }
1752
1753 const auto *Call = dyn_cast<CallBase>(FU);
1754 if (!Call) {
1755 if (IgnoreAssumeLikeCalls) {
1756 if (const auto *FI = dyn_cast<Instruction>(FU)) {
1757 if (FI->isCast() && !FI->user_empty() &&
1758 llvm::all_of(FU->users(), [](const User *U) {
1759 if (const auto *I = dyn_cast<IntrinsicInst>(U))
1760 return I->isAssumeLikeIntrinsic();
1761 return false;
1762 }))
1763 continue;
1764 }
1765 }
1766 if (IgnoreLLVMUsed && !FU->user_empty()) {
1767 const User *FUU = FU;
1768 if (isa<BitCastOperator>(FU) && FU->hasOneUse() &&
1769 !FU->user_begin()->user_empty())
1770 FUU = *FU->user_begin();
1771 if (llvm::all_of(FUU->users(), [](const User *U) {
1772 if (const auto *GV = dyn_cast<GlobalVariable>(U))
1773 return GV->hasName() &&
1774 (GV->getName().equals("llvm.compiler.used") ||
1775 GV->getName().equals("llvm.used"));
1776 return false;
1777 }))
1778 continue;
1779 }
1780 if (PutOffender)
1781 *PutOffender = FU;
1782 return true;
1783 }
1784 if (!Call->isCallee(&U)) {
1785 if (PutOffender)
1786 *PutOffender = FU;
1787 return true;
1788 }
1789 }
1790 return false;
1791}
1792
1793bool Function::isDefTriviallyDead() const {
1794 // Check the linkage
1795 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1796 !hasAvailableExternallyLinkage())
1797 return false;
1798
1799 // Check if the function is used by anything other than a blockaddress.
1800 for (const User *U : users())
1801 if (!isa<BlockAddress>(U))
1802 return false;
1803
1804 return true;
1805}
1806
1807/// callsFunctionThatReturnsTwice - Return true if the function has a call to
1808/// setjmp or other function that gcc recognizes as "returning twice".
1809bool Function::callsFunctionThatReturnsTwice() const {
1810 for (const Instruction &I : instructions(this))
1811 if (const auto *Call = dyn_cast<CallBase>(&I))
1812 if (Call->hasFnAttr(Attribute::ReturnsTwice))
1813 return true;
1814
1815 return false;
1816}
1817
1818Constant *Function::getPersonalityFn() const {
1819 assert(hasPersonalityFn() && getNumOperands())(static_cast<void> (0));
1820 return cast<Constant>(Op<0>());
1821}
1822
1823void Function::setPersonalityFn(Constant *Fn) {
1824 setHungoffOperand<0>(Fn);
1825 setValueSubclassDataBit(3, Fn != nullptr);
1826}
1827
1828Constant *Function::getPrefixData() const {
1829 assert(hasPrefixData() && getNumOperands())(static_cast<void> (0));
1830 return cast<Constant>(Op<1>());
1831}
1832
1833void Function::setPrefixData(Constant *PrefixData) {
1834 setHungoffOperand<1>(PrefixData);
1835 setValueSubclassDataBit(1, PrefixData != nullptr);
1836}
1837
1838Constant *Function::getPrologueData() const {
1839 assert(hasPrologueData() && getNumOperands())(static_cast<void> (0));
1840 return cast<Constant>(Op<2>());
1841}
1842
1843void Function::setPrologueData(Constant *PrologueData) {
1844 setHungoffOperand<2>(PrologueData);
1845 setValueSubclassDataBit(2, PrologueData != nullptr);
1846}
1847
1848void Function::allocHungoffUselist() {
1849 // If we've already allocated a uselist, stop here.
1850 if (getNumOperands())
1851 return;
1852
1853 allocHungoffUses(3, /*IsPhi=*/ false);
1854 setNumHungOffUseOperands(3);
1855
1856 // Initialize the uselist with placeholder operands to allow traversal.
1857 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1858 Op<0>().set(CPN);
1859 Op<1>().set(CPN);
1860 Op<2>().set(CPN);
1861}
1862
1863template <int Idx>
1864void Function::setHungoffOperand(Constant *C) {
1865 if (C) {
1866 allocHungoffUselist();
1867 Op<Idx>().set(C);
1868 } else if (getNumOperands()) {
1869 Op<Idx>().set(
1870 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1871 }
1872}
1873
1874void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1875 assert(Bit < 16 && "SubclassData contains only 16 bits")(static_cast<void> (0));
1876 if (On)
1877 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1878 else
1879 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1880}
1881
1882void Function::setEntryCount(ProfileCount Count,
1883 const DenseSet<GlobalValue::GUID> *S) {
1884 assert(Count.hasValue())(static_cast<void> (0));
1885#if !defined(NDEBUG1)
1886 auto PrevCount = getEntryCount();
1887 assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType())(static_cast<void> (0));
1888#endif
1889
1890 auto ImportGUIDs = getImportGUIDs();
1891 if (S == nullptr && ImportGUIDs.size())
1892 S = &ImportGUIDs;
1893
1894 MDBuilder MDB(getContext());
1895 setMetadata(
1896 LLVMContext::MD_prof,
1897 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1898}
1899
1900void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
1901 const DenseSet<GlobalValue::GUID> *Imports) {
1902 setEntryCount(ProfileCount(Count, Type), Imports);
1903}
1904
1905ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
1906 MDNode *MD = getMetadata(LLVMContext::MD_prof);
1907 if (MD && MD->getOperand(0))
1908 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1909 if (MDS->getString().equals("function_entry_count")) {
1910 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1911 uint64_t Count = CI->getValue().getZExtValue();
1912 // A value of -1 is used for SamplePGO when there were no samples.
1913 // Treat this the same as unknown.
1914 if (Count == (uint64_t)-1)
1915 return ProfileCount::getInvalid();
1916 return ProfileCount(Count, PCT_Real);
1917 } else if (AllowSynthetic &&
1918 MDS->getString().equals("synthetic_function_entry_count")) {
1919 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1920 uint64_t Count = CI->getValue().getZExtValue();
1921 return ProfileCount(Count, PCT_Synthetic);
1922 }
1923 }
1924 return ProfileCount::getInvalid();
1925}
1926
1927DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
1928 DenseSet<GlobalValue::GUID> R;
1929 if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1930 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1931 if (MDS->getString().equals("function_entry_count"))
1932 for (unsigned i = 2; i < MD->getNumOperands(); i++)
1933 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
1934 ->getValue()
1935 .getZExtValue());
1936 return R;
1937}
1938
1939void Function::setSectionPrefix(StringRef Prefix) {
1940 MDBuilder MDB(getContext());
1941 setMetadata(LLVMContext::MD_section_prefix,
1942 MDB.createFunctionSectionPrefix(Prefix));
1943}
1944
1945Optional<StringRef> Function::getSectionPrefix() const {
1946 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
1947 assert(cast<MDString>(MD->getOperand(0))(static_cast<void> (0))
1948 ->getString()(static_cast<void> (0))
1949 .equals("function_section_prefix") &&(static_cast<void> (0))
1950 "Metadata not match")(static_cast<void> (0));
1951 return cast<MDString>(MD->getOperand(1))->getString();
1952 }
1953 return None;
1954}
1955
1956bool Function::nullPointerIsDefined() const {
1957 return hasFnAttribute(Attribute::NullPointerIsValid);
1958}
1959
1960bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1961 if (F && F->nullPointerIsDefined())
1962 return true;
1963
1964 if (AS != 0)
1965 return true;
1966
1967 return false;
1968}

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include/llvm/IR/DerivedTypes.h

1//===- llvm/DerivedTypes.h - Classes for handling data types ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the declarations of classes that represent "derived
10// types". These are things like "arrays of x" or "structure of x, y, z" or
11// "function returning x taking (y,z) as parameters", etc...
12//
13// The implementations of these classes live in the Type.cpp file.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_IR_DERIVEDTYPES_H
18#define LLVM_IR_DERIVEDTYPES_H
19
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/IR/Type.h"
24#include "llvm/Support/Casting.h"
25#include "llvm/Support/Compiler.h"
26#include "llvm/Support/TypeSize.h"
27#include <cassert>
28#include <cstdint>
29
30namespace llvm {
31
32class Value;
33class APInt;
34class LLVMContext;
35
36/// Class to represent integer types. Note that this class is also used to
37/// represent the built-in integer types: Int1Ty, Int8Ty, Int16Ty, Int32Ty and
38/// Int64Ty.
39/// Integer representation type
40class IntegerType : public Type {
41 friend class LLVMContextImpl;
42
43protected:
44 explicit IntegerType(LLVMContext &C, unsigned NumBits) : Type(C, IntegerTyID){
45 setSubclassData(NumBits);
46 }
47
48public:
49 /// This enum is just used to hold constants we need for IntegerType.
50 enum {
51 MIN_INT_BITS = 1, ///< Minimum number of bits that can be specified
52 MAX_INT_BITS = (1<<24)-1 ///< Maximum number of bits that can be specified
53 ///< Note that bit width is stored in the Type classes SubclassData field
54 ///< which has 24 bits. This yields a maximum bit width of 16,777,215
55 ///< bits.
56 };
57
58 /// This static method is the primary way of constructing an IntegerType.
59 /// If an IntegerType with the same NumBits value was previously instantiated,
60 /// that instance will be returned. Otherwise a new one will be created. Only
61 /// one instance with a given NumBits value is ever created.
62 /// Get or create an IntegerType instance.
63 static IntegerType *get(LLVMContext &C, unsigned NumBits);
64
65 /// Returns type twice as wide the input type.
66 IntegerType *getExtendedType() const {
67 return Type::getIntNTy(getContext(), 2 * getScalarSizeInBits());
68 }
69
70 /// Get the number of bits in this IntegerType
71 unsigned getBitWidth() const { return getSubclassData(); }
72
73 /// Return a bitmask with ones set for all of the bits that can be set by an
74 /// unsigned version of this type. This is 0xFF for i8, 0xFFFF for i16, etc.
75 uint64_t getBitMask() const {
76 return ~uint64_t(0UL) >> (64-getBitWidth());
77 }
78
79 /// Return a uint64_t with just the most significant bit set (the sign bit, if
80 /// the value is treated as a signed number).
81 uint64_t getSignBit() const {
82 return 1ULL << (getBitWidth()-1);
83 }
84
85 /// For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
86 /// @returns a bit mask with ones set for all the bits of this type.
87 /// Get a bit mask for this type.
88 APInt getMask() const;
89
90 /// Methods for support type inquiry through isa, cast, and dyn_cast.
91 static bool classof(const Type *T) {
92 return T->getTypeID() == IntegerTyID;
93 }
94};
95
96unsigned Type::getIntegerBitWidth() const {
97 return cast<IntegerType>(this)->getBitWidth();
98}
99
100/// Class to represent function types
101///
102class FunctionType : public Type {
103 FunctionType(Type *Result, ArrayRef<Type*> Params, bool IsVarArgs);
104
105public:
106 FunctionType(const FunctionType &) = delete;
107 FunctionType &operator=(const FunctionType &) = delete;
108
109 /// This static method is the primary way of constructing a FunctionType.
110 static FunctionType *get(Type *Result,
111 ArrayRef<Type*> Params, bool isVarArg);
112
113 /// Create a FunctionType taking no parameters.
114 static FunctionType *get(Type *Result, bool isVarArg);
115
116 /// Return true if the specified type is valid as a return type.
117 static bool isValidReturnType(Type *RetTy);
118
119 /// Return true if the specified type is valid as an argument type.
120 static bool isValidArgumentType(Type *ArgTy);
121
122 bool isVarArg() const { return getSubclassData()!=0; }
123 Type *getReturnType() const { return ContainedTys[0]; }
124
125 using param_iterator = Type::subtype_iterator;
126
127 param_iterator param_begin() const { return ContainedTys + 1; }
128 param_iterator param_end() const { return &ContainedTys[NumContainedTys]; }
129 ArrayRef<Type *> params() const {
130 return makeArrayRef(param_begin(), param_end());
131 }
132
133 /// Parameter type accessors.
134 Type *getParamType(unsigned i) const { return ContainedTys[i+1]; }
135
136 /// Return the number of fixed parameters this function type requires.
137 /// This does not consider varargs.
138 unsigned getNumParams() const { return NumContainedTys - 1; }
139
140 /// Methods for support type inquiry through isa, cast, and dyn_cast.
141 static bool classof(const Type *T) {
142 return T->getTypeID() == FunctionTyID;
143 }
144};
145static_assert(alignof(FunctionType) >= alignof(Type *),
146 "Alignment sufficient for objects appended to FunctionType");
147
148bool Type::isFunctionVarArg() const {
149 return cast<FunctionType>(this)->isVarArg();
150}
151
152Type *Type::getFunctionParamType(unsigned i) const {
153 return cast<FunctionType>(this)->getParamType(i);
154}
155
156unsigned Type::getFunctionNumParams() const {
157 return cast<FunctionType>(this)->getNumParams();
158}
159
160/// A handy container for a FunctionType+Callee-pointer pair, which can be
161/// passed around as a single entity. This assists in replacing the use of
162/// PointerType::getElementType() to access the function's type, since that's
163/// slated for removal as part of the [opaque pointer types] project.
164class FunctionCallee {
165public:
166 // Allow implicit conversion from types which have a getFunctionType member
167 // (e.g. Function and InlineAsm).
168 template <typename T, typename U = decltype(&T::getFunctionType)>
169 FunctionCallee(T *Fn)
170 : FnTy(Fn ? Fn->getFunctionType() : nullptr), Callee(Fn) {}
171
172 FunctionCallee(FunctionType *FnTy, Value *Callee)
173 : FnTy(FnTy), Callee(Callee) {
174 assert((FnTy == nullptr) == (Callee == nullptr))(static_cast<void> (0));
175 }
176
177 FunctionCallee(std::nullptr_t) {}
178
179 FunctionCallee() = default;
180
181 FunctionType *getFunctionType() { return FnTy; }
182
183 Value *getCallee() { return Callee; }
184
185 explicit operator bool() { return Callee; }
186
187private:
188 FunctionType *FnTy = nullptr;
189 Value *Callee = nullptr;
190};
191
192/// Class to represent struct types. There are two different kinds of struct
193/// types: Literal structs and Identified structs.
194///
195/// Literal struct types (e.g. { i32, i32 }) are uniqued structurally, and must
196/// always have a body when created. You can get one of these by using one of
197/// the StructType::get() forms.
198///
199/// Identified structs (e.g. %foo or %42) may optionally have a name and are not
200/// uniqued. The names for identified structs are managed at the LLVMContext
201/// level, so there can only be a single identified struct with a given name in
202/// a particular LLVMContext. Identified structs may also optionally be opaque
203/// (have no body specified). You get one of these by using one of the
204/// StructType::create() forms.
205///
206/// Independent of what kind of struct you have, the body of a struct type are
207/// laid out in memory consecutively with the elements directly one after the
208/// other (if the struct is packed) or (if not packed) with padding between the
209/// elements as defined by DataLayout (which is required to match what the code
210/// generator for a target expects).
211///
212class StructType : public Type {
213 StructType(LLVMContext &C) : Type(C, StructTyID) {}
214
215 enum {
216 /// This is the contents of the SubClassData field.
217 SCDB_HasBody = 1,
218 SCDB_Packed = 2,
219 SCDB_IsLiteral = 4,
220 SCDB_IsSized = 8
221 };
222
223 /// For a named struct that actually has a name, this is a pointer to the
224 /// symbol table entry (maintained by LLVMContext) for the struct.
225 /// This is null if the type is an literal struct or if it is a identified
226 /// type that has an empty name.
227 void *SymbolTableEntry = nullptr;
228
229public:
230 StructType(const StructType &) = delete;
231 StructType &operator=(const StructType &) = delete;
232
233 /// This creates an identified struct.
234 static StructType *create(LLVMContext &Context, StringRef Name);
235 static StructType *create(LLVMContext &Context);
236
237 static StructType *create(ArrayRef<Type *> Elements, StringRef Name,
238 bool isPacked = false);
239 static StructType *create(ArrayRef<Type *> Elements);
240 static StructType *create(LLVMContext &Context, ArrayRef<Type *> Elements,
241 StringRef Name, bool isPacked = false);
242 static StructType *create(LLVMContext &Context, ArrayRef<Type *> Elements);
243 template <class... Tys>
244 static std::enable_if_t<are_base_of<Type, Tys...>::value, StructType *>
245 create(StringRef Name, Type *elt1, Tys *... elts) {
246 assert(elt1 && "Cannot create a struct type with no elements with this")(static_cast<void> (0));
247 return create(ArrayRef<Type *>({elt1, elts...}), Name);
248 }
249
250 /// This static method is the primary way to create a literal StructType.
251 static StructType *get(LLVMContext &Context, ArrayRef<Type*> Elements,
252 bool isPacked = false);
253
254 /// Create an empty structure type.
255 static StructType *get(LLVMContext &Context, bool isPacked = false);
256
257 /// This static method is a convenience method for creating structure types by
258 /// specifying the elements as arguments. Note that this method always returns
259 /// a non-packed struct, and requires at least one element type.
260 template <class... Tys>
261 static std::enable_if_t<are_base_of<Type, Tys...>::value, StructType *>
262 get(Type *elt1, Tys *... elts) {
263 assert(elt1 && "Cannot create a struct type with no elements with this")(static_cast<void> (0));
264 LLVMContext &Ctx = elt1->getContext();
265 return StructType::get(Ctx, ArrayRef<Type *>({elt1, elts...}));
266 }
267
268 /// Return the type with the specified name, or null if there is none by that
269 /// name.
270 static StructType *getTypeByName(LLVMContext &C, StringRef Name);
271
272 bool isPacked() const { return (getSubclassData() & SCDB_Packed) != 0; }
273
274 /// Return true if this type is uniqued by structural equivalence, false if it
275 /// is a struct definition.
276 bool isLiteral() const { return (getSubclassData() & SCDB_IsLiteral) != 0; }
277
278 /// Return true if this is a type with an identity that has no body specified
279 /// yet. These prints as 'opaque' in .ll files.
280 bool isOpaque() const { return (getSubclassData() & SCDB_HasBody) == 0; }
281
282 /// isSized - Return true if this is a sized type.
283 bool isSized(SmallPtrSetImpl<Type *> *Visited = nullptr) const;
284
285 /// Returns true if this struct contains a scalable vector.
286 bool containsScalableVectorType() const;
287
288 /// Return true if this is a named struct that has a non-empty name.
289 bool hasName() const { return SymbolTableEntry != nullptr; }
290
291 /// Return the name for this struct type if it has an identity.
292 /// This may return an empty string for an unnamed struct type. Do not call
293 /// this on an literal type.
294 StringRef getName() const;
295
296 /// Change the name of this type to the specified name, or to a name with a
297 /// suffix if there is a collision. Do not call this on an literal type.
298 void setName(StringRef Name);
299
300 /// Specify a body for an opaque identified type.
301 void setBody(ArrayRef<Type*> Elements, bool isPacked = false);
302
303 template <typename... Tys>
304 std::enable_if_t<are_base_of<Type, Tys...>::value, void>
305 setBody(Type *elt1, Tys *... elts) {
306 assert(elt1 && "Cannot create a struct type with no elements with this")(static_cast<void> (0));
307 setBody(ArrayRef<Type *>({elt1, elts...}));
308 }
309
310 /// Return true if the specified type is valid as a element type.
311 static bool isValidElementType(Type *ElemTy);
312
313 // Iterator access to the elements.
314 using element_iterator = Type::subtype_iterator;
315
316 element_iterator element_begin() const { return ContainedTys; }
317 element_iterator element_end() const { return &ContainedTys[NumContainedTys];}
318 ArrayRef<Type *> elements() const {
319 return makeArrayRef(element_begin(), element_end());
320 }
321
322 /// Return true if this is layout identical to the specified struct.
323 bool isLayoutIdentical(StructType *Other) const;
324
325 /// Random access to the elements
326 unsigned getNumElements() const { return NumContainedTys; }
327 Type *getElementType(unsigned N) const {
328 assert(N < NumContainedTys && "Element number out of range!")(static_cast<void> (0));
329 return ContainedTys[N];
330 }
331 /// Given an index value into the type, return the type of the element.
332 Type *getTypeAtIndex(const Value *V) const;
333 Type *getTypeAtIndex(unsigned N) const { return getElementType(N); }
334 bool indexValid(const Value *V) const;
335 bool indexValid(unsigned Idx) const { return Idx < getNumElements(); }
336
337 /// Methods for support type inquiry through isa, cast, and dyn_cast.
338 static bool classof(const Type *T) {
339 return T->getTypeID() == StructTyID;
340 }
341};
342
343StringRef Type::getStructName() const {
344 return cast<StructType>(this)->getName();
345}
346
347unsigned Type::getStructNumElements() const {
348 return cast<StructType>(this)->getNumElements();
349}
350
351Type *Type::getStructElementType(unsigned N) const {
352 return cast<StructType>(this)->getElementType(N);
353}
354
355/// Class to represent array types.
356class ArrayType : public Type {
357 /// The element type of the array.
358 Type *ContainedType;
359 /// Number of elements in the array.
360 uint64_t NumElements;
361
362 ArrayType(Type *ElType, uint64_t NumEl);
363
364public:
365 ArrayType(const ArrayType &) = delete;
366 ArrayType &operator=(const ArrayType &) = delete;
367
368 uint64_t getNumElements() const { return NumElements; }
369 Type *getElementType() const { return ContainedType; }
370
371 /// This static method is the primary way to construct an ArrayType
372 static ArrayType *get(Type *ElementType, uint64_t NumElements);
373
374 /// Return true if the specified type is valid as a element type.
375 static bool isValidElementType(Type *ElemTy);
376
377 /// Methods for support type inquiry through isa, cast, and dyn_cast.
378 static bool classof(const Type *T) {
379 return T->getTypeID() == ArrayTyID;
380 }
381};
382
383uint64_t Type::getArrayNumElements() const {
384 return cast<ArrayType>(this)->getNumElements();
385}
386
387/// Base class of all SIMD vector types
388class VectorType : public Type {
389 /// A fully specified VectorType is of the form <vscale x n x Ty>. 'n' is the
390 /// minimum number of elements of type Ty contained within the vector, and
391 /// 'vscale x' indicates that the total element count is an integer multiple
392 /// of 'n', where the multiple is either guaranteed to be one, or is
393 /// statically unknown at compile time.
394 ///
395 /// If the multiple is known to be 1, then the extra term is discarded in
396 /// textual IR:
397 ///
398 /// <4 x i32> - a vector containing 4 i32s
399 /// <vscale x 4 x i32> - a vector containing an unknown integer multiple
400 /// of 4 i32s
401
402 /// The element type of the vector.
403 Type *ContainedType;
404
405protected:
406 /// The element quantity of this vector. The meaning of this value depends
407 /// on the type of vector:
408 /// - For FixedVectorType = <ElementQuantity x ty>, there are
409 /// exactly ElementQuantity elements in this vector.
410 /// - For ScalableVectorType = <vscale x ElementQuantity x ty>,
411 /// there are vscale * ElementQuantity elements in this vector, where
412 /// vscale is a runtime-constant integer greater than 0.
413 const unsigned ElementQuantity;
414
415 VectorType(Type *ElType, unsigned EQ, Type::TypeID TID);
416
417public:
418 VectorType(const VectorType &) = delete;
419 VectorType &operator=(const VectorType &) = delete;
420
421 Type *getElementType() const { return ContainedType; }
422
423 /// This static method is the primary way to construct an VectorType.
424 static VectorType *get(Type *ElementType, ElementCount EC);
425
426 static VectorType *get(Type *ElementType, unsigned NumElements,
427 bool Scalable) {
428 return VectorType::get(ElementType,
429 ElementCount::get(NumElements, Scalable));
430 }
431
432 static VectorType *get(Type *ElementType, const VectorType *Other) {
433 return VectorType::get(ElementType, Other->getElementCount());
434 }
435
436 /// This static method gets a VectorType with the same number of elements as
437 /// the input type, and the element type is an integer type of the same width
438 /// as the input element type.
439 static VectorType *getInteger(VectorType *VTy) {
440 unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
15
Called C++ object pointer is null
441 assert(EltBits && "Element size must be of a non-zero size")(static_cast<void> (0));
442 Type *EltTy = IntegerType::get(VTy->getContext(), EltBits);
443 return VectorType::get(EltTy, VTy->getElementCount());
444 }
445
446 /// This static method is like getInteger except that the element types are
447 /// twice as wide as the elements in the input type.
448 static VectorType *getExtendedElementVectorType(VectorType *VTy) {
449 assert(VTy->isIntOrIntVectorTy() && "VTy expected to be a vector of ints.")(static_cast<void> (0));
450 auto *EltTy = cast<IntegerType>(VTy->getElementType());
451 return VectorType::get(EltTy->getExtendedType(), VTy->getElementCount());
452 }
453
454 // This static method gets a VectorType with the same number of elements as
455 // the input type, and the element type is an integer or float type which
456 // is half as wide as the elements in the input type.
457 static VectorType *getTruncatedElementVectorType(VectorType *VTy) {
458 Type *EltTy;
459 if (VTy->getElementType()->isFloatingPointTy()) {
460 switch(VTy->getElementType()->getTypeID()) {
461 case DoubleTyID:
462 EltTy = Type::getFloatTy(VTy->getContext());
463 break;
464 case FloatTyID:
465 EltTy = Type::getHalfTy(VTy->getContext());
466 break;
467 default:
468 llvm_unreachable("Cannot create narrower fp vector element type")__builtin_unreachable();
469 }
470 } else {
471 unsigned EltBits = VTy->getElementType()->getPrimitiveSizeInBits();
472 assert((EltBits & 1) == 0 &&(static_cast<void> (0))
473 "Cannot truncate vector element with odd bit-width")(static_cast<void> (0));
474 EltTy = IntegerType::get(VTy->getContext(), EltBits / 2);
475 }
476 return VectorType::get(EltTy, VTy->getElementCount());
477 }
478
479 // This static method returns a VectorType with a smaller number of elements
480 // of a larger type than the input element type. For example, a <16 x i8>
481 // subdivided twice would return <4 x i32>
482 static VectorType *getSubdividedVectorType(VectorType *VTy, int NumSubdivs) {
483 for (int i = 0; i < NumSubdivs; ++i) {
484 VTy = VectorType::getDoubleElementsVectorType(VTy);
485 VTy = VectorType::getTruncatedElementVectorType(VTy);
486 }
487 return VTy;
488 }
489
490 /// This static method returns a VectorType with half as many elements as the
491 /// input type and the same element type.
492 static VectorType *getHalfElementsVectorType(VectorType *VTy) {
493 auto EltCnt = VTy->getElementCount();
494 assert(EltCnt.isKnownEven() &&(static_cast<void> (0))
495 "Cannot halve vector with odd number of elements.")(static_cast<void> (0));
496 return VectorType::get(VTy->getElementType(),
497 EltCnt.divideCoefficientBy(2));
498 }
499
500 /// This static method returns a VectorType with twice as many elements as the
501 /// input type and the same element type.
502 static VectorType *getDoubleElementsVectorType(VectorType *VTy) {
503 auto EltCnt = VTy->getElementCount();
504 assert((EltCnt.getKnownMinValue() * 2ull) <= UINT_MAX &&(static_cast<void> (0))
505 "Too many elements in vector")(static_cast<void> (0));
506 return VectorType::get(VTy->getElementType(), EltCnt * 2);
507 }
508
509 /// Return true if the specified type is valid as a element type.
510 static bool isValidElementType(Type *ElemTy);
511
512 /// Return an ElementCount instance to represent the (possibly scalable)
513 /// number of elements in the vector.
514 inline ElementCount getElementCount() const;
515
516 /// Methods for support type inquiry through isa, cast, and dyn_cast.
517 static bool classof(const Type *T) {
518 return T->getTypeID() == FixedVectorTyID ||
519 T->getTypeID() == ScalableVectorTyID;
520 }
521};
522
523/// Class to represent fixed width SIMD vectors
524class FixedVectorType : public VectorType {
525protected:
526 FixedVectorType(Type *ElTy, unsigned NumElts)
527 : VectorType(ElTy, NumElts, FixedVectorTyID) {}
528
529public:
530 static FixedVectorType *get(Type *ElementType, unsigned NumElts);
531
532 static FixedVectorType *get(Type *ElementType, const FixedVectorType *FVTy) {
533 return get(ElementType, FVTy->getNumElements());
534 }
535
536 static FixedVectorType *getInteger(FixedVectorType *VTy) {
537 return cast<FixedVectorType>(VectorType::getInteger(VTy));
538 }
539
540 static FixedVectorType *getExtendedElementVectorType(FixedVectorType *VTy) {
541 return cast<FixedVectorType>(VectorType::getExtendedElementVectorType(VTy));
542 }
543
544 static FixedVectorType *getTruncatedElementVectorType(FixedVectorType *VTy) {
545 return cast<FixedVectorType>(
546 VectorType::getTruncatedElementVectorType(VTy));
547 }
548
549 static FixedVectorType *getSubdividedVectorType(FixedVectorType *VTy,
550 int NumSubdivs) {
551 return cast<FixedVectorType>(
552 VectorType::getSubdividedVectorType(VTy, NumSubdivs));
553 }
554
555 static FixedVectorType *getHalfElementsVectorType(FixedVectorType *VTy) {
556 return cast<FixedVectorType>(VectorType::getHalfElementsVectorType(VTy));
557 }
558
559 static FixedVectorType *getDoubleElementsVectorType(FixedVectorType *VTy) {
560 return cast<FixedVectorType>(VectorType::getDoubleElementsVectorType(VTy));
561 }
562
563 static bool classof(const Type *T) {
564 return T->getTypeID() == FixedVectorTyID;
565 }
566
567 unsigned getNumElements() const { return ElementQuantity; }
568};
569
570/// Class to represent scalable SIMD vectors
571class ScalableVectorType : public VectorType {
572protected:
573 ScalableVectorType(Type *ElTy, unsigned MinNumElts)
574 : VectorType(ElTy, MinNumElts, ScalableVectorTyID) {}
575
576public:
577 static ScalableVectorType *get(Type *ElementType, unsigned MinNumElts);
578
579 static ScalableVectorType *get(Type *ElementType,
580 const ScalableVectorType *SVTy) {
581 return get(ElementType, SVTy->getMinNumElements());
582 }
583
584 static ScalableVectorType *getInteger(ScalableVectorType *VTy) {
585 return cast<ScalableVectorType>(VectorType::getInteger(VTy));
586 }
587
588 static ScalableVectorType *
589 getExtendedElementVectorType(ScalableVectorType *VTy) {
590 return cast<ScalableVectorType>(
591 VectorType::getExtendedElementVectorType(VTy));
592 }
593
594 static ScalableVectorType *
595 getTruncatedElementVectorType(ScalableVectorType *VTy) {
596 return cast<ScalableVectorType>(
597 VectorType::getTruncatedElementVectorType(VTy));
598 }
599
600 static ScalableVectorType *getSubdividedVectorType(ScalableVectorType *VTy,
601 int NumSubdivs) {
602 return cast<ScalableVectorType>(
603 VectorType::getSubdividedVectorType(VTy, NumSubdivs));
604 }
605
606 static ScalableVectorType *
607 getHalfElementsVectorType(ScalableVectorType *VTy) {
608 return cast<ScalableVectorType>(VectorType::getHalfElementsVectorType(VTy));
609 }
610
611 static ScalableVectorType *
612 getDoubleElementsVectorType(ScalableVectorType *VTy) {
613 return cast<ScalableVectorType>(
614 VectorType::getDoubleElementsVectorType(VTy));
615 }
616
617 /// Get the minimum number of elements in this vector. The actual number of
618 /// elements in the vector is an integer multiple of this value.
619 uint64_t getMinNumElements() const { return ElementQuantity; }
620
621 static bool classof(const Type *T) {
622 return T->getTypeID() == ScalableVectorTyID;
623 }
624};
625
626inline ElementCount VectorType::getElementCount() const {
627 return ElementCount::get(ElementQuantity, isa<ScalableVectorType>(this));
628}
629
630/// Class to represent pointers.
631class PointerType : public Type {
632 explicit PointerType(Type *ElType, unsigned AddrSpace);
633 explicit PointerType(LLVMContext &C, unsigned AddrSpace);
634
635 Type *PointeeTy;
636
637public:
638 PointerType(const PointerType &) = delete;
639 PointerType &operator=(const PointerType &) = delete;
640
641 /// This constructs a pointer to an object of the specified type in a numbered
642 /// address space.
643 static PointerType *get(Type *ElementType, unsigned AddressSpace);
644 /// This constructs an opaque pointer to an object in a numbered address
645 /// space.
646 static PointerType *get(LLVMContext &C, unsigned AddressSpace);
647
648 /// This constructs a pointer to an object of the specified type in the
649 /// default address space (address space zero).
650 static PointerType *getUnqual(Type *ElementType) {
651 return PointerType::get(ElementType, 0);
652 }
653
654 /// This constructs an opaque pointer to an object in the
655 /// default address space (address space zero).
656 static PointerType *getUnqual(LLVMContext &C) {
657 return PointerType::get(C, 0);
658 }
659
660 /// This constructs a pointer type with the same pointee type as input
661 /// PointerType (or opaque pointer is the input PointerType is opaque) and the
662 /// given address space. This is only useful during the opaque pointer
663 /// transition.
664 /// TODO: remove after opaque pointer transition is complete.
665 static PointerType *getWithSamePointeeType(PointerType *PT,
666 unsigned AddressSpace) {
667 if (PT->isOpaque())
668 return get(PT->getContext(), AddressSpace);
669 return get(PT->getElementType(), AddressSpace);
670 }
671
672 Type *getElementType() const {
673 assert(!isOpaque() && "Attempting to get element type of opaque pointer")(static_cast<void> (0));
674 return PointeeTy;
675 }
676
677 bool isOpaque() const { return !PointeeTy; }
678
679 /// Return true if the specified type is valid as a element type.
680 static bool isValidElementType(Type *ElemTy);
681
682 /// Return true if we can load or store from a pointer to this type.
683 static bool isLoadableOrStorableType(Type *ElemTy);
684
685 /// Return the address space of the Pointer type.
686 inline unsigned getAddressSpace() const { return getSubclassData(); }
687
688 /// Return true if either this is an opaque pointer type or if this pointee
689 /// type matches Ty. Primarily used for checking if an instruction's pointer
690 /// operands are valid types. Will be useless after non-opaque pointers are
691 /// removed.
692 bool isOpaqueOrPointeeTypeMatches(Type *Ty) {
693 return isOpaque() || PointeeTy == Ty;
694 }
695
696 /// Return true if both pointer types have the same element type. Two opaque
697 /// pointers are considered to have the same element type, while an opaque
698 /// and a non-opaque pointer have different element types.
699 /// TODO: Remove after opaque pointer transition is complete.
700 bool hasSameElementTypeAs(PointerType *Other) {
701 return PointeeTy == Other->PointeeTy;
702 }
703
704 /// Implement support type inquiry through isa, cast, and dyn_cast.
705 static bool classof(const Type *T) {
706 return T->getTypeID() == PointerTyID;
707 }
708};
709
710Type *Type::getExtendedType() const {
711 assert((static_cast<void> (0))
712 isIntOrIntVectorTy() &&(static_cast<void> (0))
713 "Original type expected to be a vector of integers or a scalar integer.")(static_cast<void> (0));
714 if (auto *VTy = dyn_cast<VectorType>(this))
715 return VectorType::getExtendedElementVectorType(
716 const_cast<VectorType *>(VTy));
717 return cast<IntegerType>(this)->getExtendedType();
718}
719
720Type *Type::getWithNewType(Type *EltTy) const {
721 if (auto *VTy = dyn_cast<VectorType>(this))
722 return VectorType::get(EltTy, VTy->getElementCount());
723 return EltTy;
724}
725
726Type *Type::getWithNewBitWidth(unsigned NewBitWidth) const {
727 assert((static_cast<void> (0))
728 isIntOrIntVectorTy() &&(static_cast<void> (0))
729 "Original type expected to be a vector of integers or a scalar integer.")(static_cast<void> (0));
730 return getWithNewType(getIntNTy(getContext(), NewBitWidth));
731}
732
733unsigned Type::getPointerAddressSpace() const {
734 return cast<PointerType>(getScalarType())->getAddressSpace();
735}
736
737} // end namespace llvm
738
739#endif // LLVM_IR_DERIVEDTYPES_H