1 //===-- Function.cpp - Implement the Global object classes ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Function class for the IR library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Function.h"
15 #include "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/CodeGen/ValueTypes.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/MDBuilder.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/RWMutex.h"
31 #include "llvm/Support/StringPool.h"
32 #include "llvm/Support/Threading.h"
35 // Explicit instantiations of SymbolTableListTraits since some of the methods
36 // are not in the public header file...
37 template class llvm::SymbolTableListTraits<Argument>;
38 template class llvm::SymbolTableListTraits<BasicBlock>;
40 //===----------------------------------------------------------------------===//
41 // Argument Implementation
42 //===----------------------------------------------------------------------===//
44 void Argument::anchor() { }
46 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
47 : Value(Ty, Value::ArgumentVal) {
51 Par->getArgumentList().push_back(this);
55 void Argument::setParent(Function *parent) {
59 /// getArgNo - Return the index of this formal argument in its containing
60 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
61 unsigned Argument::getArgNo() const {
62 const Function *F = getParent();
63 assert(F && "Argument is not in a function");
65 Function::const_arg_iterator AI = F->arg_begin();
67 for (; &*AI != this; ++AI)
73 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
74 /// it in its containing function. Also returns true if at least one byte is
75 /// known to be dereferenceable and the pointer is in addrspace(0).
76 bool Argument::hasNonNullAttr() const {
77 if (!getType()->isPointerTy()) return false;
78 if (getParent()->getAttributes().
79 hasAttribute(getArgNo()+1, Attribute::NonNull))
81 else if (getDereferenceableBytes() > 0 &&
82 getType()->getPointerAddressSpace() == 0)
87 /// hasByValAttr - Return true if this argument has the byval attribute on it
88 /// in its containing function.
89 bool Argument::hasByValAttr() const {
90 if (!getType()->isPointerTy()) return false;
91 return hasAttribute(Attribute::ByVal);
94 bool Argument::hasSwiftSelfAttr() const {
95 return getParent()->getAttributes().
96 hasAttribute(getArgNo()+1, Attribute::SwiftSelf);
99 bool Argument::hasSwiftErrorAttr() const {
100 return getParent()->getAttributes().
101 hasAttribute(getArgNo()+1, Attribute::SwiftError);
104 /// \brief Return true if this argument has the inalloca attribute on it in
105 /// its containing function.
106 bool Argument::hasInAllocaAttr() const {
107 if (!getType()->isPointerTy()) return false;
108 return hasAttribute(Attribute::InAlloca);
111 bool Argument::hasByValOrInAllocaAttr() const {
112 if (!getType()->isPointerTy()) return false;
113 AttributeSet Attrs = getParent()->getAttributes();
114 return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
115 Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
118 unsigned Argument::getParamAlignment() const {
119 assert(getType()->isPointerTy() && "Only pointers have alignments");
120 return getParent()->getParamAlignment(getArgNo()+1);
124 uint64_t Argument::getDereferenceableBytes() const {
125 assert(getType()->isPointerTy() &&
126 "Only pointers have dereferenceable bytes");
127 return getParent()->getDereferenceableBytes(getArgNo()+1);
130 uint64_t Argument::getDereferenceableOrNullBytes() const {
131 assert(getType()->isPointerTy() &&
132 "Only pointers have dereferenceable bytes");
133 return getParent()->getDereferenceableOrNullBytes(getArgNo()+1);
136 /// hasNestAttr - Return true if this argument has the nest attribute on
137 /// it in its containing function.
138 bool Argument::hasNestAttr() const {
139 if (!getType()->isPointerTy()) return false;
140 return hasAttribute(Attribute::Nest);
143 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
144 /// it in its containing function.
145 bool Argument::hasNoAliasAttr() const {
146 if (!getType()->isPointerTy()) return false;
147 return hasAttribute(Attribute::NoAlias);
150 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
151 /// on it in its containing function.
152 bool Argument::hasNoCaptureAttr() const {
153 if (!getType()->isPointerTy()) return false;
154 return hasAttribute(Attribute::NoCapture);
157 /// hasSRetAttr - Return true if this argument has the sret attribute on
158 /// it in its containing function.
159 bool Argument::hasStructRetAttr() const {
160 if (!getType()->isPointerTy()) return false;
161 return hasAttribute(Attribute::StructRet);
164 /// hasReturnedAttr - Return true if this argument has the returned attribute on
165 /// it in its containing function.
166 bool Argument::hasReturnedAttr() const {
167 return hasAttribute(Attribute::Returned);
170 /// hasZExtAttr - Return true if this argument has the zext attribute on it in
171 /// its containing function.
172 bool Argument::hasZExtAttr() const {
173 return hasAttribute(Attribute::ZExt);
176 /// hasSExtAttr Return true if this argument has the sext attribute on it in its
177 /// containing function.
178 bool Argument::hasSExtAttr() const {
179 return hasAttribute(Attribute::SExt);
182 /// Return true if this argument has the readonly or readnone attribute on it
183 /// in its containing function.
184 bool Argument::onlyReadsMemory() const {
185 return getParent()->getAttributes().
186 hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
187 getParent()->getAttributes().
188 hasAttribute(getArgNo()+1, Attribute::ReadNone);
191 /// addAttr - Add attributes to an argument.
192 void Argument::addAttr(AttributeSet AS) {
193 assert(AS.getNumSlots() <= 1 &&
194 "Trying to add more than one attribute set to an argument!");
195 AttrBuilder B(AS, AS.getSlotIndex(0));
196 getParent()->addAttributes(getArgNo() + 1,
197 AttributeSet::get(Parent->getContext(),
201 /// removeAttr - Remove attributes from an argument.
202 void Argument::removeAttr(AttributeSet AS) {
203 assert(AS.getNumSlots() <= 1 &&
204 "Trying to remove more than one attribute set from an argument!");
205 AttrBuilder B(AS, AS.getSlotIndex(0));
206 getParent()->removeAttributes(getArgNo() + 1,
207 AttributeSet::get(Parent->getContext(),
211 /// hasAttribute - Checks if an argument has a given attribute.
212 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
213 return getParent()->hasAttribute(getArgNo() + 1, Kind);
216 //===----------------------------------------------------------------------===//
217 // Helper Methods in Function
218 //===----------------------------------------------------------------------===//
220 bool Function::isMaterializable() const {
221 return getGlobalObjectSubClassData() & (1 << IsMaterializableBit);
224 void Function::setIsMaterializable(bool V) {
225 unsigned Mask = 1 << IsMaterializableBit;
226 setGlobalObjectSubClassData((~Mask & getGlobalObjectSubClassData()) |
230 LLVMContext &Function::getContext() const {
231 return getType()->getContext();
234 FunctionType *Function::getFunctionType() const {
235 return cast<FunctionType>(getValueType());
238 bool Function::isVarArg() const {
239 return getFunctionType()->isVarArg();
242 Type *Function::getReturnType() const {
243 return getFunctionType()->getReturnType();
246 void Function::removeFromParent() {
247 getParent()->getFunctionList().remove(getIterator());
250 void Function::eraseFromParent() {
251 getParent()->getFunctionList().erase(getIterator());
254 //===----------------------------------------------------------------------===//
255 // Function Implementation
256 //===----------------------------------------------------------------------===//
258 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
259 Module *ParentModule)
260 : GlobalObject(Ty, Value::FunctionVal,
261 OperandTraits<Function>::op_begin(this), 0, Linkage, name) {
262 assert(FunctionType::isValidReturnType(getReturnType()) &&
263 "invalid return type");
264 setGlobalObjectSubClassData(0);
265 SymTab = new ValueSymbolTable();
267 // If the function has arguments, mark them as lazily built.
268 if (Ty->getNumParams())
269 setValueSubclassData(1); // Set the "has lazy arguments" bit.
272 ParentModule->getFunctionList().push_back(this);
274 // Ensure intrinsics have the right parameter attributes.
275 // Note, the IntID field will have been set in Value::setName if this function
276 // name is a valid intrinsic ID.
278 setAttributes(Intrinsic::getAttributes(getContext(), IntID));
281 Function::~Function() {
282 dropAllReferences(); // After this it is safe to delete instructions.
284 // Delete all of the method arguments and unlink from symbol table...
285 ArgumentList.clear();
288 // Remove the function from the on-the-side GC table.
292 void Function::BuildLazyArguments() const {
293 // Create the arguments vector, all arguments start out unnamed.
294 FunctionType *FT = getFunctionType();
295 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
296 assert(!FT->getParamType(i)->isVoidTy() &&
297 "Cannot have void typed arguments!");
298 ArgumentList.push_back(new Argument(FT->getParamType(i)));
301 // Clear the lazy arguments bit.
302 unsigned SDC = getSubclassDataFromValue();
303 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
306 void Function::stealArgumentListFrom(Function &Src) {
307 assert(isDeclaration() && "Expected no references to current arguments");
309 // Drop the current arguments, if any, and set the lazy argument bit.
310 if (!hasLazyArguments()) {
311 assert(llvm::all_of(ArgumentList,
312 [](const Argument &A) { return A.use_empty(); }) &&
313 "Expected arguments to be unused in declaration");
314 ArgumentList.clear();
315 setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
318 // Nothing to steal if Src has lazy arguments.
319 if (Src.hasLazyArguments())
322 // Steal arguments from Src, and fix the lazy argument bits.
323 ArgumentList.splice(ArgumentList.end(), Src.ArgumentList);
324 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
325 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
328 size_t Function::arg_size() const {
329 return getFunctionType()->getNumParams();
331 bool Function::arg_empty() const {
332 return getFunctionType()->getNumParams() == 0;
335 void Function::setParent(Module *parent) {
339 // dropAllReferences() - This function causes all the subinstructions to "let
340 // go" of all references that they are maintaining. This allows one to
341 // 'delete' a whole class at a time, even though there may be circular
342 // references... first all references are dropped, and all use counts go to
343 // zero. Then everything is deleted for real. Note that no operations are
344 // valid on an object that has "dropped all references", except operator
347 void Function::dropAllReferences() {
348 setIsMaterializable(false);
350 for (BasicBlock &BB : *this)
351 BB.dropAllReferences();
353 // Delete all basic blocks. They are now unused, except possibly by
354 // blockaddresses, but BasicBlock's destructor takes care of those.
355 while (!BasicBlocks.empty())
356 BasicBlocks.begin()->eraseFromParent();
358 // Drop uses of any optional data (real or placeholder).
359 if (getNumOperands()) {
360 User::dropAllReferences();
361 setNumHungOffUseOperands(0);
362 setValueSubclassData(getSubclassDataFromValue() & ~0xe);
365 // Metadata is stored in a side-table.
369 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
370 AttributeSet PAL = getAttributes();
371 PAL = PAL.addAttribute(getContext(), i, Kind);
375 void Function::addAttribute(unsigned i, Attribute Attr) {
376 AttributeSet PAL = getAttributes();
377 PAL = PAL.addAttribute(getContext(), i, Attr);
381 void Function::addAttributes(unsigned i, AttributeSet Attrs) {
382 AttributeSet PAL = getAttributes();
383 PAL = PAL.addAttributes(getContext(), i, Attrs);
387 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
388 AttributeSet PAL = getAttributes();
389 PAL = PAL.removeAttribute(getContext(), i, Kind);
393 void Function::removeAttribute(unsigned i, StringRef Kind) {
394 AttributeSet PAL = getAttributes();
395 PAL = PAL.removeAttribute(getContext(), i, Kind);
399 void Function::removeAttributes(unsigned i, AttributeSet Attrs) {
400 AttributeSet PAL = getAttributes();
401 PAL = PAL.removeAttributes(getContext(), i, Attrs);
405 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
406 AttributeSet PAL = getAttributes();
407 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
411 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
412 AttributeSet PAL = getAttributes();
413 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
417 const std::string &Function::getGC() const {
418 assert(hasGC() && "Function has no collector");
419 return getContext().getGC(*this);
422 void Function::setGC(std::string Str) {
423 setValueSubclassDataBit(14, !Str.empty());
424 getContext().setGC(*this, std::move(Str));
427 void Function::clearGC() {
430 getContext().deleteGC(*this);
431 setValueSubclassDataBit(14, false);
434 /// Copy all additional attributes (those not needed to create a Function) from
435 /// the Function Src to this one.
436 void Function::copyAttributesFrom(const GlobalValue *Src) {
437 GlobalObject::copyAttributesFrom(Src);
438 const Function *SrcF = dyn_cast<Function>(Src);
442 setCallingConv(SrcF->getCallingConv());
443 setAttributes(SrcF->getAttributes());
445 setGC(SrcF->getGC());
448 if (SrcF->hasPersonalityFn())
449 setPersonalityFn(SrcF->getPersonalityFn());
450 if (SrcF->hasPrefixData())
451 setPrefixData(SrcF->getPrefixData());
452 if (SrcF->hasPrologueData())
453 setPrologueData(SrcF->getPrologueData());
456 /// Table of string intrinsic names indexed by enum value.
457 static const char * const IntrinsicNameTable[] = {
459 #define GET_INTRINSIC_NAME_TABLE
460 #include "llvm/IR/Intrinsics.gen"
461 #undef GET_INTRINSIC_NAME_TABLE
464 /// Table of per-target intrinsic name tables.
465 #define GET_INTRINSIC_TARGET_DATA
466 #include "llvm/IR/Intrinsics.gen"
467 #undef GET_INTRINSIC_TARGET_DATA
469 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
470 /// target as \c Name, or the generic table if \c Name is not target specific.
472 /// Returns the relevant slice of \c IntrinsicNameTable
473 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
474 assert(Name.startswith("llvm."));
476 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
477 // Drop "llvm." and take the first dotted component. That will be the target
478 // if this is target specific.
479 StringRef Target = Name.drop_front(5).split('.').first;
480 auto It = std::lower_bound(Targets.begin(), Targets.end(), Target,
481 [](const IntrinsicTargetInfo &TI,
482 StringRef Target) { return TI.Name < Target; });
483 // We've either found the target or just fall back to the generic set, which
485 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
486 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
489 /// \brief This does the actual lookup of an intrinsic ID which
490 /// matches the given function name.
491 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
492 StringRef Name = ValName->getKey();
494 ArrayRef<const char *> NameTable = findTargetSubtable(Name);
495 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
497 return Intrinsic::not_intrinsic;
499 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
500 // an index into a sub-table.
501 int Adjust = NameTable.data() - IntrinsicNameTable;
502 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
504 // If the intrinsic is not overloaded, require an exact match. If it is
505 // overloaded, require a prefix match.
506 bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]);
507 return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
510 void Function::recalculateIntrinsicID() {
511 const ValueName *ValName = this->getValueName();
512 if (!ValName || !isIntrinsic()) {
513 IntID = Intrinsic::not_intrinsic;
516 IntID = lookupIntrinsicID(ValName);
519 /// Returns a stable mangling for the type specified for use in the name
520 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
521 /// of named types is simply their name. Manglings for unnamed types consist
522 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
523 /// combined with the mangling of their component types. A vararg function
524 /// type will have a suffix of 'vararg'. Since function types can contain
525 /// other function types, we close a function type mangling with suffix 'f'
526 /// which can't be confused with it's prefix. This ensures we don't have
527 /// collisions between two unrelated function types. Otherwise, you might
528 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
529 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
530 /// cases) fall back to the MVT codepath, where they could be mangled to
531 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
533 static std::string getMangledTypeStr(Type* Ty) {
535 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
536 Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
537 getMangledTypeStr(PTyp->getElementType());
538 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
539 Result += "a" + llvm::utostr(ATyp->getNumElements()) +
540 getMangledTypeStr(ATyp->getElementType());
541 } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
542 assert(!STyp->isLiteral() && "TODO: implement literal types");
543 Result += STyp->getName();
544 } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
545 Result += "f_" + getMangledTypeStr(FT->getReturnType());
546 for (size_t i = 0; i < FT->getNumParams(); i++)
547 Result += getMangledTypeStr(FT->getParamType(i));
550 // Ensure nested function types are distinguishable.
552 } else if (isa<VectorType>(Ty))
553 Result += "v" + utostr(Ty->getVectorNumElements()) +
554 getMangledTypeStr(Ty->getVectorElementType());
556 Result += EVT::getEVT(Ty).getEVTString();
560 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
561 assert(id < num_intrinsics && "Invalid intrinsic ID!");
562 std::string Result(IntrinsicNameTable[id]);
563 for (Type *Ty : Tys) {
564 Result += "." + getMangledTypeStr(Ty);
570 /// IIT_Info - These are enumerators that describe the entries returned by the
571 /// getIntrinsicInfoTableEntries function.
573 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
575 // Common values should be encoded with 0-15.
593 // Values from 16+ are only encodable with the inefficient encoding.
598 IIT_EMPTYSTRUCT = 20,
608 IIT_HALF_VEC_ARG = 30,
609 IIT_SAME_VEC_WIDTH_ARG = 31,
611 IIT_VEC_OF_PTRS_TO_ELT = 33,
618 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
619 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
620 IIT_Info Info = IIT_Info(Infos[NextElt++]);
621 unsigned StructElts = 2;
622 using namespace Intrinsic;
626 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
629 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
632 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
635 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
638 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
641 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
644 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
647 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
650 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
653 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
656 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
659 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
662 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
665 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
668 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
669 DecodeIITType(NextElt, Infos, OutputTable);
672 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
673 DecodeIITType(NextElt, Infos, OutputTable);
676 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
677 DecodeIITType(NextElt, Infos, OutputTable);
680 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
681 DecodeIITType(NextElt, Infos, OutputTable);
684 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
685 DecodeIITType(NextElt, Infos, OutputTable);
688 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
689 DecodeIITType(NextElt, Infos, OutputTable);
692 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
693 DecodeIITType(NextElt, Infos, OutputTable);
696 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
697 DecodeIITType(NextElt, Infos, OutputTable);
700 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
701 DecodeIITType(NextElt, Infos, OutputTable);
704 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
705 DecodeIITType(NextElt, Infos, OutputTable);
707 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
708 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
710 DecodeIITType(NextElt, Infos, OutputTable);
714 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
715 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
718 case IIT_EXTEND_ARG: {
719 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
720 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
724 case IIT_TRUNC_ARG: {
725 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
726 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
730 case IIT_HALF_VEC_ARG: {
731 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
732 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
736 case IIT_SAME_VEC_WIDTH_ARG: {
737 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
738 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
742 case IIT_PTR_TO_ARG: {
743 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
744 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
748 case IIT_VEC_OF_PTRS_TO_ELT: {
749 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
750 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
754 case IIT_EMPTYSTRUCT:
755 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
757 case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
758 case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
759 case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
761 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
763 for (unsigned i = 0; i != StructElts; ++i)
764 DecodeIITType(NextElt, Infos, OutputTable);
768 llvm_unreachable("unhandled");
772 #define GET_INTRINSIC_GENERATOR_GLOBAL
773 #include "llvm/IR/Intrinsics.gen"
774 #undef GET_INTRINSIC_GENERATOR_GLOBAL
776 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
777 SmallVectorImpl<IITDescriptor> &T){
778 // Check to see if the intrinsic's type was expressible by the table.
779 unsigned TableVal = IIT_Table[id-1];
781 // Decode the TableVal into an array of IITValues.
782 SmallVector<unsigned char, 8> IITValues;
783 ArrayRef<unsigned char> IITEntries;
784 unsigned NextElt = 0;
785 if ((TableVal >> 31) != 0) {
786 // This is an offset into the IIT_LongEncodingTable.
787 IITEntries = IIT_LongEncodingTable;
789 // Strip sentinel bit.
790 NextElt = (TableVal << 1) >> 1;
792 // Decode the TableVal into an array of IITValues. If the entry was encoded
793 // into a single word in the table itself, decode it now.
795 IITValues.push_back(TableVal & 0xF);
799 IITEntries = IITValues;
803 // Okay, decode the table into the output vector of IITDescriptors.
804 DecodeIITType(NextElt, IITEntries, T);
805 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
806 DecodeIITType(NextElt, IITEntries, T);
810 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
811 ArrayRef<Type*> Tys, LLVMContext &Context) {
812 using namespace Intrinsic;
813 IITDescriptor D = Infos.front();
814 Infos = Infos.slice(1);
817 case IITDescriptor::Void: return Type::getVoidTy(Context);
818 case IITDescriptor::VarArg: return Type::getVoidTy(Context);
819 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
820 case IITDescriptor::Token: return Type::getTokenTy(Context);
821 case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
822 case IITDescriptor::Half: return Type::getHalfTy(Context);
823 case IITDescriptor::Float: return Type::getFloatTy(Context);
824 case IITDescriptor::Double: return Type::getDoubleTy(Context);
826 case IITDescriptor::Integer:
827 return IntegerType::get(Context, D.Integer_Width);
828 case IITDescriptor::Vector:
829 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
830 case IITDescriptor::Pointer:
831 return PointerType::get(DecodeFixedType(Infos, Tys, Context),
832 D.Pointer_AddressSpace);
833 case IITDescriptor::Struct: {
835 assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
836 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
837 Elts[i] = DecodeFixedType(Infos, Tys, Context);
838 return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
841 case IITDescriptor::Argument:
842 return Tys[D.getArgumentNumber()];
843 case IITDescriptor::ExtendArgument: {
844 Type *Ty = Tys[D.getArgumentNumber()];
845 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
846 return VectorType::getExtendedElementVectorType(VTy);
848 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
850 case IITDescriptor::TruncArgument: {
851 Type *Ty = Tys[D.getArgumentNumber()];
852 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
853 return VectorType::getTruncatedElementVectorType(VTy);
855 IntegerType *ITy = cast<IntegerType>(Ty);
856 assert(ITy->getBitWidth() % 2 == 0);
857 return IntegerType::get(Context, ITy->getBitWidth() / 2);
859 case IITDescriptor::HalfVecArgument:
860 return VectorType::getHalfElementsVectorType(cast<VectorType>(
861 Tys[D.getArgumentNumber()]));
862 case IITDescriptor::SameVecWidthArgument: {
863 Type *EltTy = DecodeFixedType(Infos, Tys, Context);
864 Type *Ty = Tys[D.getArgumentNumber()];
865 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
866 return VectorType::get(EltTy, VTy->getNumElements());
868 llvm_unreachable("unhandled");
870 case IITDescriptor::PtrToArgument: {
871 Type *Ty = Tys[D.getArgumentNumber()];
872 return PointerType::getUnqual(Ty);
874 case IITDescriptor::VecOfPtrsToElt: {
875 Type *Ty = Tys[D.getArgumentNumber()];
876 VectorType *VTy = dyn_cast<VectorType>(Ty);
878 llvm_unreachable("Expected an argument of Vector Type");
879 Type *EltTy = VTy->getVectorElementType();
880 return VectorType::get(PointerType::getUnqual(EltTy),
881 VTy->getNumElements());
884 llvm_unreachable("unhandled");
889 FunctionType *Intrinsic::getType(LLVMContext &Context,
890 ID id, ArrayRef<Type*> Tys) {
891 SmallVector<IITDescriptor, 8> Table;
892 getIntrinsicInfoTableEntries(id, Table);
894 ArrayRef<IITDescriptor> TableRef = Table;
895 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
897 SmallVector<Type*, 8> ArgTys;
898 while (!TableRef.empty())
899 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
901 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
902 // If we see void type as the type of the last argument, it is vararg intrinsic
903 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
905 return FunctionType::get(ResultTy, ArgTys, true);
907 return FunctionType::get(ResultTy, ArgTys, false);
910 bool Intrinsic::isOverloaded(ID id) {
911 #define GET_INTRINSIC_OVERLOAD_TABLE
912 #include "llvm/IR/Intrinsics.gen"
913 #undef GET_INTRINSIC_OVERLOAD_TABLE
916 bool Intrinsic::isLeaf(ID id) {
921 case Intrinsic::experimental_gc_statepoint:
922 case Intrinsic::experimental_patchpoint_void:
923 case Intrinsic::experimental_patchpoint_i64:
928 /// This defines the "Intrinsic::getAttributes(ID id)" method.
929 #define GET_INTRINSIC_ATTRIBUTES
930 #include "llvm/IR/Intrinsics.gen"
931 #undef GET_INTRINSIC_ATTRIBUTES
933 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
934 // There can never be multiple globals with the same name of different types,
935 // because intrinsics must be a specific type.
937 cast<Function>(M->getOrInsertFunction(getName(id, Tys),
938 getType(M->getContext(), id, Tys)));
941 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
942 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
943 #include "llvm/IR/Intrinsics.gen"
944 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
946 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
947 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
948 #include "llvm/IR/Intrinsics.gen"
949 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
951 bool Intrinsic::matchIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
952 SmallVectorImpl<Type*> &ArgTys) {
953 using namespace Intrinsic;
955 // If we ran out of descriptors, there are too many arguments.
956 if (Infos.empty()) return true;
957 IITDescriptor D = Infos.front();
958 Infos = Infos.slice(1);
961 case IITDescriptor::Void: return !Ty->isVoidTy();
962 case IITDescriptor::VarArg: return true;
963 case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
964 case IITDescriptor::Token: return !Ty->isTokenTy();
965 case IITDescriptor::Metadata: return !Ty->isMetadataTy();
966 case IITDescriptor::Half: return !Ty->isHalfTy();
967 case IITDescriptor::Float: return !Ty->isFloatTy();
968 case IITDescriptor::Double: return !Ty->isDoubleTy();
969 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
970 case IITDescriptor::Vector: {
971 VectorType *VT = dyn_cast<VectorType>(Ty);
972 return !VT || VT->getNumElements() != D.Vector_Width ||
973 matchIntrinsicType(VT->getElementType(), Infos, ArgTys);
975 case IITDescriptor::Pointer: {
976 PointerType *PT = dyn_cast<PointerType>(Ty);
977 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
978 matchIntrinsicType(PT->getElementType(), Infos, ArgTys);
981 case IITDescriptor::Struct: {
982 StructType *ST = dyn_cast<StructType>(Ty);
983 if (!ST || ST->getNumElements() != D.Struct_NumElements)
986 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
987 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys))
992 case IITDescriptor::Argument:
993 // Two cases here - If this is the second occurrence of an argument, verify
994 // that the later instance matches the previous instance.
995 if (D.getArgumentNumber() < ArgTys.size())
996 return Ty != ArgTys[D.getArgumentNumber()];
998 // Otherwise, if this is the first instance of an argument, record it and
999 // verify the "Any" kind.
1000 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
1001 ArgTys.push_back(Ty);
1003 switch (D.getArgumentKind()) {
1004 case IITDescriptor::AK_Any: return false; // Success
1005 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1006 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
1007 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
1008 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1010 llvm_unreachable("all argument kinds not covered");
1012 case IITDescriptor::ExtendArgument: {
1013 // This may only be used when referring to a previous vector argument.
1014 if (D.getArgumentNumber() >= ArgTys.size())
1017 Type *NewTy = ArgTys[D.getArgumentNumber()];
1018 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1019 NewTy = VectorType::getExtendedElementVectorType(VTy);
1020 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1021 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1027 case IITDescriptor::TruncArgument: {
1028 // This may only be used when referring to a previous vector argument.
1029 if (D.getArgumentNumber() >= ArgTys.size())
1032 Type *NewTy = ArgTys[D.getArgumentNumber()];
1033 if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1034 NewTy = VectorType::getTruncatedElementVectorType(VTy);
1035 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1036 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1042 case IITDescriptor::HalfVecArgument:
1043 // This may only be used when referring to a previous vector argument.
1044 return D.getArgumentNumber() >= ArgTys.size() ||
1045 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1046 VectorType::getHalfElementsVectorType(
1047 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1048 case IITDescriptor::SameVecWidthArgument: {
1049 if (D.getArgumentNumber() >= ArgTys.size())
1051 VectorType * ReferenceType =
1052 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1053 VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
1054 if (!ThisArgType || !ReferenceType ||
1055 (ReferenceType->getVectorNumElements() !=
1056 ThisArgType->getVectorNumElements()))
1058 return matchIntrinsicType(ThisArgType->getVectorElementType(),
1061 case IITDescriptor::PtrToArgument: {
1062 if (D.getArgumentNumber() >= ArgTys.size())
1064 Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1065 PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1066 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1068 case IITDescriptor::VecOfPtrsToElt: {
1069 if (D.getArgumentNumber() >= ArgTys.size())
1071 VectorType * ReferenceType =
1072 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1073 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1074 if (!ThisArgVecTy || !ReferenceType ||
1075 (ReferenceType->getVectorNumElements() !=
1076 ThisArgVecTy->getVectorNumElements()))
1078 PointerType *ThisArgEltTy =
1079 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
1082 return ThisArgEltTy->getElementType() !=
1083 ReferenceType->getVectorElementType();
1086 llvm_unreachable("unhandled");
1090 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1091 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1092 // If there are no descriptors left, then it can't be a vararg.
1096 // There should be only one descriptor remaining at this point.
1097 if (Infos.size() != 1)
1100 // Check and verify the descriptor.
1101 IITDescriptor D = Infos.front();
1102 Infos = Infos.slice(1);
1103 if (D.Kind == IITDescriptor::VarArg)
1109 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) {
1110 Intrinsic::ID ID = F->getIntrinsicID();
1114 FunctionType *FTy = F->getFunctionType();
1115 // Accumulate an array of overloaded types for the given intrinsic
1116 SmallVector<Type *, 4> ArgTys;
1118 SmallVector<Intrinsic::IITDescriptor, 8> Table;
1119 getIntrinsicInfoTableEntries(ID, Table);
1120 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1122 // If we encounter any problems matching the signature with the descriptor
1123 // just give up remangling. It's up to verifier to report the discrepancy.
1124 if (Intrinsic::matchIntrinsicType(FTy->getReturnType(), TableRef, ArgTys))
1126 for (auto Ty : FTy->params())
1127 if (Intrinsic::matchIntrinsicType(Ty, TableRef, ArgTys))
1129 if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef))
1133 StringRef Name = F->getName();
1134 if (Name == Intrinsic::getName(ID, ArgTys))
1137 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1138 NewDecl->setCallingConv(F->getCallingConv());
1139 assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature");
1143 /// hasAddressTaken - returns true if there are any uses of this function
1144 /// other than direct calls or invokes to it.
1145 bool Function::hasAddressTaken(const User* *PutOffender) const {
1146 for (const Use &U : uses()) {
1147 const User *FU = U.getUser();
1148 if (isa<BlockAddress>(FU))
1150 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) {
1155 ImmutableCallSite CS(cast<Instruction>(FU));
1156 if (!CS.isCallee(&U)) {
1165 bool Function::isDefTriviallyDead() const {
1166 // Check the linkage
1167 if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1168 !hasAvailableExternallyLinkage())
1171 // Check if the function is used by anything other than a blockaddress.
1172 for (const User *U : users())
1173 if (!isa<BlockAddress>(U))
1179 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1180 /// setjmp or other function that gcc recognizes as "returning twice".
1181 bool Function::callsFunctionThatReturnsTwice() const {
1182 for (const_inst_iterator
1183 I = inst_begin(this), E = inst_end(this); I != E; ++I) {
1184 ImmutableCallSite CS(&*I);
1185 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
1192 Constant *Function::getPersonalityFn() const {
1193 assert(hasPersonalityFn() && getNumOperands());
1194 return cast<Constant>(Op<0>());
1197 void Function::setPersonalityFn(Constant *Fn) {
1198 setHungoffOperand<0>(Fn);
1199 setValueSubclassDataBit(3, Fn != nullptr);
1202 Constant *Function::getPrefixData() const {
1203 assert(hasPrefixData() && getNumOperands());
1204 return cast<Constant>(Op<1>());
1207 void Function::setPrefixData(Constant *PrefixData) {
1208 setHungoffOperand<1>(PrefixData);
1209 setValueSubclassDataBit(1, PrefixData != nullptr);
1212 Constant *Function::getPrologueData() const {
1213 assert(hasPrologueData() && getNumOperands());
1214 return cast<Constant>(Op<2>());
1217 void Function::setPrologueData(Constant *PrologueData) {
1218 setHungoffOperand<2>(PrologueData);
1219 setValueSubclassDataBit(2, PrologueData != nullptr);
1222 void Function::allocHungoffUselist() {
1223 // If we've already allocated a uselist, stop here.
1224 if (getNumOperands())
1227 allocHungoffUses(3, /*IsPhi=*/ false);
1228 setNumHungOffUseOperands(3);
1230 // Initialize the uselist with placeholder operands to allow traversal.
1231 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1238 void Function::setHungoffOperand(Constant *C) {
1240 allocHungoffUselist();
1242 } else if (getNumOperands()) {
1244 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1248 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1249 assert(Bit < 16 && "SubclassData contains only 16 bits");
1251 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1253 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1256 void Function::setEntryCount(uint64_t Count) {
1257 MDBuilder MDB(getContext());
1258 setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
1261 Optional<uint64_t> Function::getEntryCount() const {
1262 MDNode *MD = getMetadata(LLVMContext::MD_prof);
1263 if (MD && MD->getOperand(0))
1264 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1265 if (MDS->getString().equals("function_entry_count")) {
1266 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1267 return CI->getValue().getZExtValue();