• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- Function.cpp - Implement the Global object classes -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Function class for the IR library.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/Function.h"
15 #include "SymbolTableListTraitsImpl.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/Argument.h"
25 #include "llvm/IR/Attributes.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/CallSite.h"
28 #include "llvm/IR/Constant.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/InstIterator.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/MDBuilder.h"
39 #include "llvm/IR/Metadata.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/SymbolTableListTraits.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/Use.h"
44 #include "llvm/IR/User.h"
45 #include "llvm/IR/Value.h"
46 #include "llvm/IR/ValueSymbolTable.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include <algorithm>
51 #include <cassert>
52 #include <cstddef>
53 #include <cstdint>
54 #include <cstring>
55 #include <string>
56 
57 using namespace llvm;
58 using ProfileCount = Function::ProfileCount;
59 
60 // Explicit instantiations of SymbolTableListTraits since some of the methods
61 // are not in the public header file...
62 template class llvm::SymbolTableListTraits<BasicBlock>;
63 
64 //===----------------------------------------------------------------------===//
65 // Argument Implementation
66 //===----------------------------------------------------------------------===//
67 
Argument(Type * Ty,const Twine & Name,Function * Par,unsigned ArgNo)68 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
69     : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
70   setName(Name);
71 }
72 
setParent(Function * parent)73 void Argument::setParent(Function *parent) {
74   Parent = parent;
75 }
76 
hasNonNullAttr() const77 bool Argument::hasNonNullAttr() const {
78   if (!getType()->isPointerTy()) return false;
79   if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
80     return true;
81   else if (getDereferenceableBytes() > 0 &&
82            !NullPointerIsDefined(getParent(),
83                                  getType()->getPointerAddressSpace()))
84     return true;
85   return false;
86 }
87 
hasByValAttr() const88 bool Argument::hasByValAttr() const {
89   if (!getType()->isPointerTy()) return false;
90   return hasAttribute(Attribute::ByVal);
91 }
92 
hasSwiftSelfAttr() const93 bool Argument::hasSwiftSelfAttr() const {
94   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
95 }
96 
hasSwiftErrorAttr() const97 bool Argument::hasSwiftErrorAttr() const {
98   return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
99 }
100 
hasInAllocaAttr() const101 bool Argument::hasInAllocaAttr() const {
102   if (!getType()->isPointerTy()) return false;
103   return hasAttribute(Attribute::InAlloca);
104 }
105 
hasByValOrInAllocaAttr() const106 bool Argument::hasByValOrInAllocaAttr() const {
107   if (!getType()->isPointerTy()) return false;
108   AttributeList Attrs = getParent()->getAttributes();
109   return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
110          Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca);
111 }
112 
getParamAlignment() const113 unsigned Argument::getParamAlignment() const {
114   assert(getType()->isPointerTy() && "Only pointers have alignments");
115   return getParent()->getParamAlignment(getArgNo());
116 }
117 
getDereferenceableBytes() const118 uint64_t Argument::getDereferenceableBytes() const {
119   assert(getType()->isPointerTy() &&
120          "Only pointers have dereferenceable bytes");
121   return getParent()->getParamDereferenceableBytes(getArgNo());
122 }
123 
getDereferenceableOrNullBytes() const124 uint64_t Argument::getDereferenceableOrNullBytes() const {
125   assert(getType()->isPointerTy() &&
126          "Only pointers have dereferenceable bytes");
127   return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
128 }
129 
hasNestAttr() const130 bool Argument::hasNestAttr() const {
131   if (!getType()->isPointerTy()) return false;
132   return hasAttribute(Attribute::Nest);
133 }
134 
hasNoAliasAttr() const135 bool Argument::hasNoAliasAttr() const {
136   if (!getType()->isPointerTy()) return false;
137   return hasAttribute(Attribute::NoAlias);
138 }
139 
hasNoCaptureAttr() const140 bool Argument::hasNoCaptureAttr() const {
141   if (!getType()->isPointerTy()) return false;
142   return hasAttribute(Attribute::NoCapture);
143 }
144 
hasStructRetAttr() const145 bool Argument::hasStructRetAttr() const {
146   if (!getType()->isPointerTy()) return false;
147   return hasAttribute(Attribute::StructRet);
148 }
149 
hasReturnedAttr() const150 bool Argument::hasReturnedAttr() const {
151   return hasAttribute(Attribute::Returned);
152 }
153 
hasZExtAttr() const154 bool Argument::hasZExtAttr() const {
155   return hasAttribute(Attribute::ZExt);
156 }
157 
hasSExtAttr() const158 bool Argument::hasSExtAttr() const {
159   return hasAttribute(Attribute::SExt);
160 }
161 
onlyReadsMemory() const162 bool Argument::onlyReadsMemory() const {
163   AttributeList Attrs = getParent()->getAttributes();
164   return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
165          Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
166 }
167 
addAttrs(AttrBuilder & B)168 void Argument::addAttrs(AttrBuilder &B) {
169   AttributeList AL = getParent()->getAttributes();
170   AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
171   getParent()->setAttributes(AL);
172 }
173 
addAttr(Attribute::AttrKind Kind)174 void Argument::addAttr(Attribute::AttrKind Kind) {
175   getParent()->addParamAttr(getArgNo(), Kind);
176 }
177 
addAttr(Attribute Attr)178 void Argument::addAttr(Attribute Attr) {
179   getParent()->addParamAttr(getArgNo(), Attr);
180 }
181 
removeAttr(Attribute::AttrKind Kind)182 void Argument::removeAttr(Attribute::AttrKind Kind) {
183   getParent()->removeParamAttr(getArgNo(), Kind);
184 }
185 
hasAttribute(Attribute::AttrKind Kind) const186 bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
187   return getParent()->hasParamAttribute(getArgNo(), Kind);
188 }
189 
190 //===----------------------------------------------------------------------===//
191 // Helper Methods in Function
192 //===----------------------------------------------------------------------===//
193 
getContext() const194 LLVMContext &Function::getContext() const {
195   return getType()->getContext();
196 }
197 
getInstructionCount()198 unsigned Function::getInstructionCount() {
199   unsigned NumInstrs = 0;
200   for (BasicBlock &BB : BasicBlocks)
201     NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
202                                BB.instructionsWithoutDebug().end());
203   return NumInstrs;
204 }
205 
removeFromParent()206 void Function::removeFromParent() {
207   getParent()->getFunctionList().remove(getIterator());
208 }
209 
eraseFromParent()210 void Function::eraseFromParent() {
211   getParent()->getFunctionList().erase(getIterator());
212 }
213 
214 //===----------------------------------------------------------------------===//
215 // Function Implementation
216 //===----------------------------------------------------------------------===//
217 
Function(FunctionType * Ty,LinkageTypes Linkage,const Twine & name,Module * ParentModule)218 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
219                    Module *ParentModule)
220     : GlobalObject(Ty, Value::FunctionVal,
221                    OperandTraits<Function>::op_begin(this), 0, Linkage, name),
222       NumArgs(Ty->getNumParams()) {
223   assert(FunctionType::isValidReturnType(getReturnType()) &&
224          "invalid return type");
225   setGlobalObjectSubClassData(0);
226 
227   // We only need a symbol table for a function if the context keeps value names
228   if (!getContext().shouldDiscardValueNames())
229     SymTab = make_unique<ValueSymbolTable>();
230 
231   // If the function has arguments, mark them as lazily built.
232   if (Ty->getNumParams())
233     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
234 
235   if (ParentModule)
236     ParentModule->getFunctionList().push_back(this);
237 
238   HasLLVMReservedName = getName().startswith("llvm.");
239   // Ensure intrinsics have the right parameter attributes.
240   // Note, the IntID field will have been set in Value::setName if this function
241   // name is a valid intrinsic ID.
242   if (IntID)
243     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
244 }
245 
~Function()246 Function::~Function() {
247   dropAllReferences();    // After this it is safe to delete instructions.
248 
249   // Delete all of the method arguments and unlink from symbol table...
250   if (Arguments)
251     clearArguments();
252 
253   // Remove the function from the on-the-side GC table.
254   clearGC();
255 }
256 
BuildLazyArguments() const257 void Function::BuildLazyArguments() const {
258   // Create the arguments vector, all arguments start out unnamed.
259   auto *FT = getFunctionType();
260   if (NumArgs > 0) {
261     Arguments = std::allocator<Argument>().allocate(NumArgs);
262     for (unsigned i = 0, e = NumArgs; i != e; ++i) {
263       Type *ArgTy = FT->getParamType(i);
264       assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
265       new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
266     }
267   }
268 
269   // Clear the lazy arguments bit.
270   unsigned SDC = getSubclassDataFromValue();
271   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
272   assert(!hasLazyArguments());
273 }
274 
makeArgArray(Argument * Args,size_t Count)275 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
276   return MutableArrayRef<Argument>(Args, Count);
277 }
278 
clearArguments()279 void Function::clearArguments() {
280   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
281     A.setName("");
282     A.~Argument();
283   }
284   std::allocator<Argument>().deallocate(Arguments, NumArgs);
285   Arguments = nullptr;
286 }
287 
stealArgumentListFrom(Function & Src)288 void Function::stealArgumentListFrom(Function &Src) {
289   assert(isDeclaration() && "Expected no references to current arguments");
290 
291   // Drop the current arguments, if any, and set the lazy argument bit.
292   if (!hasLazyArguments()) {
293     assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
294                         [](const Argument &A) { return A.use_empty(); }) &&
295            "Expected arguments to be unused in declaration");
296     clearArguments();
297     setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
298   }
299 
300   // Nothing to steal if Src has lazy arguments.
301   if (Src.hasLazyArguments())
302     return;
303 
304   // Steal arguments from Src, and fix the lazy argument bits.
305   assert(arg_size() == Src.arg_size());
306   Arguments = Src.Arguments;
307   Src.Arguments = nullptr;
308   for (Argument &A : makeArgArray(Arguments, NumArgs)) {
309     // FIXME: This does the work of transferNodesFromList inefficiently.
310     SmallString<128> Name;
311     if (A.hasName())
312       Name = A.getName();
313     if (!Name.empty())
314       A.setName("");
315     A.setParent(this);
316     if (!Name.empty())
317       A.setName(Name);
318   }
319 
320   setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
321   assert(!hasLazyArguments());
322   Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
323 }
324 
325 // dropAllReferences() - This function causes all the subinstructions to "let
326 // go" of all references that they are maintaining.  This allows one to
327 // 'delete' a whole class at a time, even though there may be circular
328 // references... first all references are dropped, and all use counts go to
329 // zero.  Then everything is deleted for real.  Note that no operations are
330 // valid on an object that has "dropped all references", except operator
331 // delete.
332 //
dropAllReferences()333 void Function::dropAllReferences() {
334   setIsMaterializable(false);
335 
336   for (BasicBlock &BB : *this)
337     BB.dropAllReferences();
338 
339   // Delete all basic blocks. They are now unused, except possibly by
340   // blockaddresses, but BasicBlock's destructor takes care of those.
341   while (!BasicBlocks.empty())
342     BasicBlocks.begin()->eraseFromParent();
343 
344   // Drop uses of any optional data (real or placeholder).
345   if (getNumOperands()) {
346     User::dropAllReferences();
347     setNumHungOffUseOperands(0);
348     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
349   }
350 
351   // Metadata is stored in a side-table.
352   clearMetadata();
353 }
354 
addAttribute(unsigned i,Attribute::AttrKind Kind)355 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
356   AttributeList PAL = getAttributes();
357   PAL = PAL.addAttribute(getContext(), i, Kind);
358   setAttributes(PAL);
359 }
360 
addAttribute(unsigned i,Attribute Attr)361 void Function::addAttribute(unsigned i, Attribute Attr) {
362   AttributeList PAL = getAttributes();
363   PAL = PAL.addAttribute(getContext(), i, Attr);
364   setAttributes(PAL);
365 }
366 
addAttributes(unsigned i,const AttrBuilder & Attrs)367 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
368   AttributeList PAL = getAttributes();
369   PAL = PAL.addAttributes(getContext(), i, Attrs);
370   setAttributes(PAL);
371 }
372 
addParamAttr(unsigned ArgNo,Attribute::AttrKind Kind)373 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
374   AttributeList PAL = getAttributes();
375   PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
376   setAttributes(PAL);
377 }
378 
addParamAttr(unsigned ArgNo,Attribute Attr)379 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
380   AttributeList PAL = getAttributes();
381   PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
382   setAttributes(PAL);
383 }
384 
addParamAttrs(unsigned ArgNo,const AttrBuilder & Attrs)385 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
386   AttributeList PAL = getAttributes();
387   PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
388   setAttributes(PAL);
389 }
390 
removeAttribute(unsigned i,Attribute::AttrKind Kind)391 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
392   AttributeList PAL = getAttributes();
393   PAL = PAL.removeAttribute(getContext(), i, Kind);
394   setAttributes(PAL);
395 }
396 
removeAttribute(unsigned i,StringRef Kind)397 void Function::removeAttribute(unsigned i, StringRef Kind) {
398   AttributeList PAL = getAttributes();
399   PAL = PAL.removeAttribute(getContext(), i, Kind);
400   setAttributes(PAL);
401 }
402 
removeAttributes(unsigned i,const AttrBuilder & Attrs)403 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
404   AttributeList PAL = getAttributes();
405   PAL = PAL.removeAttributes(getContext(), i, Attrs);
406   setAttributes(PAL);
407 }
408 
removeParamAttr(unsigned ArgNo,Attribute::AttrKind Kind)409 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
410   AttributeList PAL = getAttributes();
411   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
412   setAttributes(PAL);
413 }
414 
removeParamAttr(unsigned ArgNo,StringRef Kind)415 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
416   AttributeList PAL = getAttributes();
417   PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
418   setAttributes(PAL);
419 }
420 
removeParamAttrs(unsigned ArgNo,const AttrBuilder & Attrs)421 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
422   AttributeList PAL = getAttributes();
423   PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
424   setAttributes(PAL);
425 }
426 
addDereferenceableAttr(unsigned i,uint64_t Bytes)427 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
428   AttributeList PAL = getAttributes();
429   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
430   setAttributes(PAL);
431 }
432 
addDereferenceableParamAttr(unsigned ArgNo,uint64_t Bytes)433 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
434   AttributeList PAL = getAttributes();
435   PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
436   setAttributes(PAL);
437 }
438 
addDereferenceableOrNullAttr(unsigned i,uint64_t Bytes)439 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
440   AttributeList PAL = getAttributes();
441   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
442   setAttributes(PAL);
443 }
444 
addDereferenceableOrNullParamAttr(unsigned ArgNo,uint64_t Bytes)445 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
446                                                  uint64_t Bytes) {
447   AttributeList PAL = getAttributes();
448   PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
449   setAttributes(PAL);
450 }
451 
getGC() const452 const std::string &Function::getGC() const {
453   assert(hasGC() && "Function has no collector");
454   return getContext().getGC(*this);
455 }
456 
setGC(std::string Str)457 void Function::setGC(std::string Str) {
458   setValueSubclassDataBit(14, !Str.empty());
459   getContext().setGC(*this, std::move(Str));
460 }
461 
clearGC()462 void Function::clearGC() {
463   if (!hasGC())
464     return;
465   getContext().deleteGC(*this);
466   setValueSubclassDataBit(14, false);
467 }
468 
469 /// Copy all additional attributes (those not needed to create a Function) from
470 /// the Function Src to this one.
copyAttributesFrom(const Function * Src)471 void Function::copyAttributesFrom(const Function *Src) {
472   GlobalObject::copyAttributesFrom(Src);
473   setCallingConv(Src->getCallingConv());
474   setAttributes(Src->getAttributes());
475   if (Src->hasGC())
476     setGC(Src->getGC());
477   else
478     clearGC();
479   if (Src->hasPersonalityFn())
480     setPersonalityFn(Src->getPersonalityFn());
481   if (Src->hasPrefixData())
482     setPrefixData(Src->getPrefixData());
483   if (Src->hasPrologueData())
484     setPrologueData(Src->getPrologueData());
485 }
486 
487 /// Table of string intrinsic names indexed by enum value.
488 static const char * const IntrinsicNameTable[] = {
489   "not_intrinsic",
490 #define GET_INTRINSIC_NAME_TABLE
491 #include "llvm/IR/IntrinsicImpl.inc"
492 #undef GET_INTRINSIC_NAME_TABLE
493 };
494 
495 /// Table of per-target intrinsic name tables.
496 #define GET_INTRINSIC_TARGET_DATA
497 #include "llvm/IR/IntrinsicImpl.inc"
498 #undef GET_INTRINSIC_TARGET_DATA
499 
500 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
501 /// target as \c Name, or the generic table if \c Name is not target specific.
502 ///
503 /// Returns the relevant slice of \c IntrinsicNameTable
findTargetSubtable(StringRef Name)504 static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
505   assert(Name.startswith("llvm."));
506 
507   ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
508   // Drop "llvm." and take the first dotted component. That will be the target
509   // if this is target specific.
510   StringRef Target = Name.drop_front(5).split('.').first;
511   auto It = std::lower_bound(Targets.begin(), Targets.end(), Target,
512                              [](const IntrinsicTargetInfo &TI,
513                                 StringRef Target) { return TI.Name < Target; });
514   // We've either found the target or just fall back to the generic set, which
515   // is always first.
516   const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
517   return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
518 }
519 
520 /// This does the actual lookup of an intrinsic ID which
521 /// matches the given function name.
lookupIntrinsicID(StringRef Name)522 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
523   ArrayRef<const char *> NameTable = findTargetSubtable(Name);
524   int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
525   if (Idx == -1)
526     return Intrinsic::not_intrinsic;
527 
528   // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
529   // an index into a sub-table.
530   int Adjust = NameTable.data() - IntrinsicNameTable;
531   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
532 
533   // If the intrinsic is not overloaded, require an exact match. If it is
534   // overloaded, require either exact or prefix match.
535   const auto MatchSize = strlen(NameTable[Idx]);
536   assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
537   bool IsExactMatch = Name.size() == MatchSize;
538   return IsExactMatch || isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
539 }
540 
recalculateIntrinsicID()541 void Function::recalculateIntrinsicID() {
542   StringRef Name = getName();
543   if (!Name.startswith("llvm.")) {
544     HasLLVMReservedName = false;
545     IntID = Intrinsic::not_intrinsic;
546     return;
547   }
548   HasLLVMReservedName = true;
549   IntID = lookupIntrinsicID(Name);
550 }
551 
552 /// Returns a stable mangling for the type specified for use in the name
553 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
554 /// of named types is simply their name.  Manglings for unnamed types consist
555 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
556 /// combined with the mangling of their component types.  A vararg function
557 /// type will have a suffix of 'vararg'.  Since function types can contain
558 /// other function types, we close a function type mangling with suffix 'f'
559 /// which can't be confused with it's prefix.  This ensures we don't have
560 /// collisions between two unrelated function types. Otherwise, you might
561 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
562 ///
getMangledTypeStr(Type * Ty)563 static std::string getMangledTypeStr(Type* Ty) {
564   std::string Result;
565   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
566     Result += "p" + utostr(PTyp->getAddressSpace()) +
567       getMangledTypeStr(PTyp->getElementType());
568   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
569     Result += "a" + utostr(ATyp->getNumElements()) +
570       getMangledTypeStr(ATyp->getElementType());
571   } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
572     if (!STyp->isLiteral()) {
573       Result += "s_";
574       Result += STyp->getName();
575     } else {
576       Result += "sl_";
577       for (auto Elem : STyp->elements())
578         Result += getMangledTypeStr(Elem);
579     }
580     // Ensure nested structs are distinguishable.
581     Result += "s";
582   } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
583     Result += "f_" + getMangledTypeStr(FT->getReturnType());
584     for (size_t i = 0; i < FT->getNumParams(); i++)
585       Result += getMangledTypeStr(FT->getParamType(i));
586     if (FT->isVarArg())
587       Result += "vararg";
588     // Ensure nested function types are distinguishable.
589     Result += "f";
590   } else if (isa<VectorType>(Ty)) {
591     Result += "v" + utostr(Ty->getVectorNumElements()) +
592       getMangledTypeStr(Ty->getVectorElementType());
593   } else if (Ty) {
594     switch (Ty->getTypeID()) {
595     default: llvm_unreachable("Unhandled type");
596     case Type::VoidTyID:      Result += "isVoid";   break;
597     case Type::MetadataTyID:  Result += "Metadata"; break;
598     case Type::HalfTyID:      Result += "f16";      break;
599     case Type::FloatTyID:     Result += "f32";      break;
600     case Type::DoubleTyID:    Result += "f64";      break;
601     case Type::X86_FP80TyID:  Result += "f80";      break;
602     case Type::FP128TyID:     Result += "f128";     break;
603     case Type::PPC_FP128TyID: Result += "ppcf128";  break;
604     case Type::X86_MMXTyID:   Result += "x86mmx";   break;
605     case Type::IntegerTyID:
606       Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
607       break;
608     }
609   }
610   return Result;
611 }
612 
getName(ID id)613 StringRef Intrinsic::getName(ID id) {
614   assert(id < num_intrinsics && "Invalid intrinsic ID!");
615   assert(!isOverloaded(id) &&
616          "This version of getName does not support overloading");
617   return IntrinsicNameTable[id];
618 }
619 
getName(ID id,ArrayRef<Type * > Tys)620 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
621   assert(id < num_intrinsics && "Invalid intrinsic ID!");
622   std::string Result(IntrinsicNameTable[id]);
623   for (Type *Ty : Tys) {
624     Result += "." + getMangledTypeStr(Ty);
625   }
626   return Result;
627 }
628 
629 /// IIT_Info - These are enumerators that describe the entries returned by the
630 /// getIntrinsicInfoTableEntries function.
631 ///
632 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
633 enum IIT_Info {
634   // Common values should be encoded with 0-15.
635   IIT_Done = 0,
636   IIT_I1   = 1,
637   IIT_I8   = 2,
638   IIT_I16  = 3,
639   IIT_I32  = 4,
640   IIT_I64  = 5,
641   IIT_F16  = 6,
642   IIT_F32  = 7,
643   IIT_F64  = 8,
644   IIT_V2   = 9,
645   IIT_V4   = 10,
646   IIT_V8   = 11,
647   IIT_V16  = 12,
648   IIT_V32  = 13,
649   IIT_PTR  = 14,
650   IIT_ARG  = 15,
651 
652   // Values from 16+ are only encodable with the inefficient encoding.
653   IIT_V64  = 16,
654   IIT_MMX  = 17,
655   IIT_TOKEN = 18,
656   IIT_METADATA = 19,
657   IIT_EMPTYSTRUCT = 20,
658   IIT_STRUCT2 = 21,
659   IIT_STRUCT3 = 22,
660   IIT_STRUCT4 = 23,
661   IIT_STRUCT5 = 24,
662   IIT_EXTEND_ARG = 25,
663   IIT_TRUNC_ARG = 26,
664   IIT_ANYPTR = 27,
665   IIT_V1   = 28,
666   IIT_VARARG = 29,
667   IIT_HALF_VEC_ARG = 30,
668   IIT_SAME_VEC_WIDTH_ARG = 31,
669   IIT_PTR_TO_ARG = 32,
670   IIT_PTR_TO_ELT = 33,
671   IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
672   IIT_I128 = 35,
673   IIT_V512 = 36,
674   IIT_V1024 = 37,
675   IIT_STRUCT6 = 38,
676   IIT_STRUCT7 = 39,
677   IIT_STRUCT8 = 40,
678   IIT_F128 = 41
679 };
680 
DecodeIITType(unsigned & NextElt,ArrayRef<unsigned char> Infos,SmallVectorImpl<Intrinsic::IITDescriptor> & OutputTable)681 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
682                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
683   using namespace Intrinsic;
684 
685   IIT_Info Info = IIT_Info(Infos[NextElt++]);
686   unsigned StructElts = 2;
687 
688   switch (Info) {
689   case IIT_Done:
690     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
691     return;
692   case IIT_VARARG:
693     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
694     return;
695   case IIT_MMX:
696     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
697     return;
698   case IIT_TOKEN:
699     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
700     return;
701   case IIT_METADATA:
702     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
703     return;
704   case IIT_F16:
705     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
706     return;
707   case IIT_F32:
708     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
709     return;
710   case IIT_F64:
711     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
712     return;
713   case IIT_F128:
714     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
715     return;
716   case IIT_I1:
717     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
718     return;
719   case IIT_I8:
720     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
721     return;
722   case IIT_I16:
723     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
724     return;
725   case IIT_I32:
726     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
727     return;
728   case IIT_I64:
729     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
730     return;
731   case IIT_I128:
732     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
733     return;
734   case IIT_V1:
735     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
736     DecodeIITType(NextElt, Infos, OutputTable);
737     return;
738   case IIT_V2:
739     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
740     DecodeIITType(NextElt, Infos, OutputTable);
741     return;
742   case IIT_V4:
743     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
744     DecodeIITType(NextElt, Infos, OutputTable);
745     return;
746   case IIT_V8:
747     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
748     DecodeIITType(NextElt, Infos, OutputTable);
749     return;
750   case IIT_V16:
751     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
752     DecodeIITType(NextElt, Infos, OutputTable);
753     return;
754   case IIT_V32:
755     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
756     DecodeIITType(NextElt, Infos, OutputTable);
757     return;
758   case IIT_V64:
759     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
760     DecodeIITType(NextElt, Infos, OutputTable);
761     return;
762   case IIT_V512:
763     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
764     DecodeIITType(NextElt, Infos, OutputTable);
765     return;
766   case IIT_V1024:
767     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
768     DecodeIITType(NextElt, Infos, OutputTable);
769     return;
770   case IIT_PTR:
771     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
772     DecodeIITType(NextElt, Infos, OutputTable);
773     return;
774   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
775     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
776                                              Infos[NextElt++]));
777     DecodeIITType(NextElt, Infos, OutputTable);
778     return;
779   }
780   case IIT_ARG: {
781     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
782     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
783     return;
784   }
785   case IIT_EXTEND_ARG: {
786     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
787     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
788                                              ArgInfo));
789     return;
790   }
791   case IIT_TRUNC_ARG: {
792     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
793     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
794                                              ArgInfo));
795     return;
796   }
797   case IIT_HALF_VEC_ARG: {
798     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
799     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
800                                              ArgInfo));
801     return;
802   }
803   case IIT_SAME_VEC_WIDTH_ARG: {
804     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
805     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
806                                              ArgInfo));
807     return;
808   }
809   case IIT_PTR_TO_ARG: {
810     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
811     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
812                                              ArgInfo));
813     return;
814   }
815   case IIT_PTR_TO_ELT: {
816     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
817     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
818     return;
819   }
820   case IIT_VEC_OF_ANYPTRS_TO_ELT: {
821     unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
822     unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
823     OutputTable.push_back(
824         IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
825     return;
826   }
827   case IIT_EMPTYSTRUCT:
828     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
829     return;
830   case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
831   case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
832   case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
833   case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
834   case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
835   case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
836   case IIT_STRUCT2: {
837     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
838 
839     for (unsigned i = 0; i != StructElts; ++i)
840       DecodeIITType(NextElt, Infos, OutputTable);
841     return;
842   }
843   }
844   llvm_unreachable("unhandled");
845 }
846 
847 #define GET_INTRINSIC_GENERATOR_GLOBAL
848 #include "llvm/IR/IntrinsicImpl.inc"
849 #undef GET_INTRINSIC_GENERATOR_GLOBAL
850 
getIntrinsicInfoTableEntries(ID id,SmallVectorImpl<IITDescriptor> & T)851 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
852                                              SmallVectorImpl<IITDescriptor> &T){
853   // Check to see if the intrinsic's type was expressible by the table.
854   unsigned TableVal = IIT_Table[id-1];
855 
856   // Decode the TableVal into an array of IITValues.
857   SmallVector<unsigned char, 8> IITValues;
858   ArrayRef<unsigned char> IITEntries;
859   unsigned NextElt = 0;
860   if ((TableVal >> 31) != 0) {
861     // This is an offset into the IIT_LongEncodingTable.
862     IITEntries = IIT_LongEncodingTable;
863 
864     // Strip sentinel bit.
865     NextElt = (TableVal << 1) >> 1;
866   } else {
867     // Decode the TableVal into an array of IITValues.  If the entry was encoded
868     // into a single word in the table itself, decode it now.
869     do {
870       IITValues.push_back(TableVal & 0xF);
871       TableVal >>= 4;
872     } while (TableVal);
873 
874     IITEntries = IITValues;
875     NextElt = 0;
876   }
877 
878   // Okay, decode the table into the output vector of IITDescriptors.
879   DecodeIITType(NextElt, IITEntries, T);
880   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
881     DecodeIITType(NextElt, IITEntries, T);
882 }
883 
DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> & Infos,ArrayRef<Type * > Tys,LLVMContext & Context)884 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
885                              ArrayRef<Type*> Tys, LLVMContext &Context) {
886   using namespace Intrinsic;
887 
888   IITDescriptor D = Infos.front();
889   Infos = Infos.slice(1);
890 
891   switch (D.Kind) {
892   case IITDescriptor::Void: return Type::getVoidTy(Context);
893   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
894   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
895   case IITDescriptor::Token: return Type::getTokenTy(Context);
896   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
897   case IITDescriptor::Half: return Type::getHalfTy(Context);
898   case IITDescriptor::Float: return Type::getFloatTy(Context);
899   case IITDescriptor::Double: return Type::getDoubleTy(Context);
900   case IITDescriptor::Quad: return Type::getFP128Ty(Context);
901 
902   case IITDescriptor::Integer:
903     return IntegerType::get(Context, D.Integer_Width);
904   case IITDescriptor::Vector:
905     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
906   case IITDescriptor::Pointer:
907     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
908                             D.Pointer_AddressSpace);
909   case IITDescriptor::Struct: {
910     SmallVector<Type *, 8> Elts;
911     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
912       Elts.push_back(DecodeFixedType(Infos, Tys, Context));
913     return StructType::get(Context, Elts);
914   }
915   case IITDescriptor::Argument:
916     return Tys[D.getArgumentNumber()];
917   case IITDescriptor::ExtendArgument: {
918     Type *Ty = Tys[D.getArgumentNumber()];
919     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
920       return VectorType::getExtendedElementVectorType(VTy);
921 
922     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
923   }
924   case IITDescriptor::TruncArgument: {
925     Type *Ty = Tys[D.getArgumentNumber()];
926     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
927       return VectorType::getTruncatedElementVectorType(VTy);
928 
929     IntegerType *ITy = cast<IntegerType>(Ty);
930     assert(ITy->getBitWidth() % 2 == 0);
931     return IntegerType::get(Context, ITy->getBitWidth() / 2);
932   }
933   case IITDescriptor::HalfVecArgument:
934     return VectorType::getHalfElementsVectorType(cast<VectorType>(
935                                                   Tys[D.getArgumentNumber()]));
936   case IITDescriptor::SameVecWidthArgument: {
937     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
938     Type *Ty = Tys[D.getArgumentNumber()];
939     if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
940       return VectorType::get(EltTy, VTy->getNumElements());
941     }
942     llvm_unreachable("unhandled");
943   }
944   case IITDescriptor::PtrToArgument: {
945     Type *Ty = Tys[D.getArgumentNumber()];
946     return PointerType::getUnqual(Ty);
947   }
948   case IITDescriptor::PtrToElt: {
949     Type *Ty = Tys[D.getArgumentNumber()];
950     VectorType *VTy = dyn_cast<VectorType>(Ty);
951     if (!VTy)
952       llvm_unreachable("Expected an argument of Vector Type");
953     Type *EltTy = VTy->getVectorElementType();
954     return PointerType::getUnqual(EltTy);
955   }
956   case IITDescriptor::VecOfAnyPtrsToElt:
957     // Return the overloaded type (which determines the pointers address space)
958     return Tys[D.getOverloadArgNumber()];
959   }
960   llvm_unreachable("unhandled");
961 }
962 
getType(LLVMContext & Context,ID id,ArrayRef<Type * > Tys)963 FunctionType *Intrinsic::getType(LLVMContext &Context,
964                                  ID id, ArrayRef<Type*> Tys) {
965   SmallVector<IITDescriptor, 8> Table;
966   getIntrinsicInfoTableEntries(id, Table);
967 
968   ArrayRef<IITDescriptor> TableRef = Table;
969   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
970 
971   SmallVector<Type*, 8> ArgTys;
972   while (!TableRef.empty())
973     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
974 
975   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
976   // If we see void type as the type of the last argument, it is vararg intrinsic
977   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
978     ArgTys.pop_back();
979     return FunctionType::get(ResultTy, ArgTys, true);
980   }
981   return FunctionType::get(ResultTy, ArgTys, false);
982 }
983 
isOverloaded(ID id)984 bool Intrinsic::isOverloaded(ID id) {
985 #define GET_INTRINSIC_OVERLOAD_TABLE
986 #include "llvm/IR/IntrinsicImpl.inc"
987 #undef GET_INTRINSIC_OVERLOAD_TABLE
988 }
989 
isLeaf(ID id)990 bool Intrinsic::isLeaf(ID id) {
991   switch (id) {
992   default:
993     return true;
994 
995   case Intrinsic::experimental_gc_statepoint:
996   case Intrinsic::experimental_patchpoint_void:
997   case Intrinsic::experimental_patchpoint_i64:
998     return false;
999   }
1000 }
1001 
1002 /// This defines the "Intrinsic::getAttributes(ID id)" method.
1003 #define GET_INTRINSIC_ATTRIBUTES
1004 #include "llvm/IR/IntrinsicImpl.inc"
1005 #undef GET_INTRINSIC_ATTRIBUTES
1006 
getDeclaration(Module * M,ID id,ArrayRef<Type * > Tys)1007 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
1008   // There can never be multiple globals with the same name of different types,
1009   // because intrinsics must be a specific type.
1010   return
1011     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
1012                                           getType(M->getContext(), id, Tys)));
1013 }
1014 
1015 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
1016 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1017 #include "llvm/IR/IntrinsicImpl.inc"
1018 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
1019 
1020 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
1021 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1022 #include "llvm/IR/IntrinsicImpl.inc"
1023 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
1024 
matchIntrinsicType(Type * Ty,ArrayRef<Intrinsic::IITDescriptor> & Infos,SmallVectorImpl<Type * > & ArgTys)1025 bool Intrinsic::matchIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
1026                                    SmallVectorImpl<Type*> &ArgTys) {
1027   using namespace Intrinsic;
1028 
1029   // If we ran out of descriptors, there are too many arguments.
1030   if (Infos.empty()) return true;
1031   IITDescriptor D = Infos.front();
1032   Infos = Infos.slice(1);
1033 
1034   switch (D.Kind) {
1035     case IITDescriptor::Void: return !Ty->isVoidTy();
1036     case IITDescriptor::VarArg: return true;
1037     case IITDescriptor::MMX:  return !Ty->isX86_MMXTy();
1038     case IITDescriptor::Token: return !Ty->isTokenTy();
1039     case IITDescriptor::Metadata: return !Ty->isMetadataTy();
1040     case IITDescriptor::Half: return !Ty->isHalfTy();
1041     case IITDescriptor::Float: return !Ty->isFloatTy();
1042     case IITDescriptor::Double: return !Ty->isDoubleTy();
1043     case IITDescriptor::Quad: return !Ty->isFP128Ty();
1044     case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
1045     case IITDescriptor::Vector: {
1046       VectorType *VT = dyn_cast<VectorType>(Ty);
1047       return !VT || VT->getNumElements() != D.Vector_Width ||
1048              matchIntrinsicType(VT->getElementType(), Infos, ArgTys);
1049     }
1050     case IITDescriptor::Pointer: {
1051       PointerType *PT = dyn_cast<PointerType>(Ty);
1052       return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
1053              matchIntrinsicType(PT->getElementType(), Infos, ArgTys);
1054     }
1055 
1056     case IITDescriptor::Struct: {
1057       StructType *ST = dyn_cast<StructType>(Ty);
1058       if (!ST || ST->getNumElements() != D.Struct_NumElements)
1059         return true;
1060 
1061       for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
1062         if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys))
1063           return true;
1064       return false;
1065     }
1066 
1067     case IITDescriptor::Argument:
1068       // Two cases here - If this is the second occurrence of an argument, verify
1069       // that the later instance matches the previous instance.
1070       if (D.getArgumentNumber() < ArgTys.size())
1071         return Ty != ArgTys[D.getArgumentNumber()];
1072 
1073           // Otherwise, if this is the first instance of an argument, record it and
1074           // verify the "Any" kind.
1075           assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error");
1076           ArgTys.push_back(Ty);
1077 
1078           switch (D.getArgumentKind()) {
1079             case IITDescriptor::AK_Any:        return false; // Success
1080             case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
1081             case IITDescriptor::AK_AnyFloat:   return !Ty->isFPOrFPVectorTy();
1082             case IITDescriptor::AK_AnyVector:  return !isa<VectorType>(Ty);
1083             case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
1084           }
1085           llvm_unreachable("all argument kinds not covered");
1086 
1087     case IITDescriptor::ExtendArgument: {
1088       // This may only be used when referring to a previous vector argument.
1089       if (D.getArgumentNumber() >= ArgTys.size())
1090         return true;
1091 
1092       Type *NewTy = ArgTys[D.getArgumentNumber()];
1093       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1094         NewTy = VectorType::getExtendedElementVectorType(VTy);
1095       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1096         NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
1097       else
1098         return true;
1099 
1100       return Ty != NewTy;
1101     }
1102     case IITDescriptor::TruncArgument: {
1103       // This may only be used when referring to a previous vector argument.
1104       if (D.getArgumentNumber() >= ArgTys.size())
1105         return true;
1106 
1107       Type *NewTy = ArgTys[D.getArgumentNumber()];
1108       if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
1109         NewTy = VectorType::getTruncatedElementVectorType(VTy);
1110       else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
1111         NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
1112       else
1113         return true;
1114 
1115       return Ty != NewTy;
1116     }
1117     case IITDescriptor::HalfVecArgument:
1118       // This may only be used when referring to a previous vector argument.
1119       return D.getArgumentNumber() >= ArgTys.size() ||
1120              !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
1121              VectorType::getHalfElementsVectorType(
1122                      cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
1123     case IITDescriptor::SameVecWidthArgument: {
1124       if (D.getArgumentNumber() >= ArgTys.size())
1125         return true;
1126       VectorType * ReferenceType =
1127         dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
1128       VectorType *ThisArgType = dyn_cast<VectorType>(Ty);
1129       if (!ThisArgType || !ReferenceType ||
1130           (ReferenceType->getVectorNumElements() !=
1131            ThisArgType->getVectorNumElements()))
1132         return true;
1133       return matchIntrinsicType(ThisArgType->getVectorElementType(),
1134                                 Infos, ArgTys);
1135     }
1136     case IITDescriptor::PtrToArgument: {
1137       if (D.getArgumentNumber() >= ArgTys.size())
1138         return true;
1139       Type * ReferenceType = ArgTys[D.getArgumentNumber()];
1140       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1141       return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
1142     }
1143     case IITDescriptor::PtrToElt: {
1144       if (D.getArgumentNumber() >= ArgTys.size())
1145         return true;
1146       VectorType * ReferenceType =
1147         dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
1148       PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
1149 
1150       return (!ThisArgType || !ReferenceType ||
1151               ThisArgType->getElementType() != ReferenceType->getElementType());
1152     }
1153     case IITDescriptor::VecOfAnyPtrsToElt: {
1154       unsigned RefArgNumber = D.getRefArgNumber();
1155 
1156       // This may only be used when referring to a previous argument.
1157       if (RefArgNumber >= ArgTys.size())
1158         return true;
1159 
1160       // Record the overloaded type
1161       assert(D.getOverloadArgNumber() == ArgTys.size() &&
1162              "Table consistency error");
1163       ArgTys.push_back(Ty);
1164 
1165       // Verify the overloaded type "matches" the Ref type.
1166       // i.e. Ty is a vector with the same width as Ref.
1167       // Composed of pointers to the same element type as Ref.
1168       VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
1169       VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
1170       if (!ThisArgVecTy || !ReferenceType ||
1171           (ReferenceType->getVectorNumElements() !=
1172            ThisArgVecTy->getVectorNumElements()))
1173         return true;
1174       PointerType *ThisArgEltTy =
1175               dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
1176       if (!ThisArgEltTy)
1177         return true;
1178       return ThisArgEltTy->getElementType() !=
1179              ReferenceType->getVectorElementType();
1180     }
1181   }
1182   llvm_unreachable("unhandled");
1183 }
1184 
1185 bool
matchIntrinsicVarArg(bool isVarArg,ArrayRef<Intrinsic::IITDescriptor> & Infos)1186 Intrinsic::matchIntrinsicVarArg(bool isVarArg,
1187                                 ArrayRef<Intrinsic::IITDescriptor> &Infos) {
1188   // If there are no descriptors left, then it can't be a vararg.
1189   if (Infos.empty())
1190     return isVarArg;
1191 
1192   // There should be only one descriptor remaining at this point.
1193   if (Infos.size() != 1)
1194     return true;
1195 
1196   // Check and verify the descriptor.
1197   IITDescriptor D = Infos.front();
1198   Infos = Infos.slice(1);
1199   if (D.Kind == IITDescriptor::VarArg)
1200     return !isVarArg;
1201 
1202   return true;
1203 }
1204 
remangleIntrinsicFunction(Function * F)1205 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) {
1206   Intrinsic::ID ID = F->getIntrinsicID();
1207   if (!ID)
1208     return None;
1209 
1210   FunctionType *FTy = F->getFunctionType();
1211   // Accumulate an array of overloaded types for the given intrinsic
1212   SmallVector<Type *, 4> ArgTys;
1213   {
1214     SmallVector<Intrinsic::IITDescriptor, 8> Table;
1215     getIntrinsicInfoTableEntries(ID, Table);
1216     ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
1217 
1218     // If we encounter any problems matching the signature with the descriptor
1219     // just give up remangling. It's up to verifier to report the discrepancy.
1220     if (Intrinsic::matchIntrinsicType(FTy->getReturnType(), TableRef, ArgTys))
1221       return None;
1222     for (auto Ty : FTy->params())
1223       if (Intrinsic::matchIntrinsicType(Ty, TableRef, ArgTys))
1224         return None;
1225     if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef))
1226       return None;
1227   }
1228 
1229   StringRef Name = F->getName();
1230   if (Name == Intrinsic::getName(ID, ArgTys))
1231     return None;
1232 
1233   auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
1234   NewDecl->setCallingConv(F->getCallingConv());
1235   assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature");
1236   return NewDecl;
1237 }
1238 
1239 /// hasAddressTaken - returns true if there are any uses of this function
1240 /// other than direct calls or invokes to it.
hasAddressTaken(const User ** PutOffender) const1241 bool Function::hasAddressTaken(const User* *PutOffender) const {
1242   for (const Use &U : uses()) {
1243     const User *FU = U.getUser();
1244     if (isa<BlockAddress>(FU))
1245       continue;
1246     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) {
1247       if (PutOffender)
1248         *PutOffender = FU;
1249       return true;
1250     }
1251     ImmutableCallSite CS(cast<Instruction>(FU));
1252     if (!CS.isCallee(&U)) {
1253       if (PutOffender)
1254         *PutOffender = FU;
1255       return true;
1256     }
1257   }
1258   return false;
1259 }
1260 
isDefTriviallyDead() const1261 bool Function::isDefTriviallyDead() const {
1262   // Check the linkage
1263   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
1264       !hasAvailableExternallyLinkage())
1265     return false;
1266 
1267   // Check if the function is used by anything other than a blockaddress.
1268   for (const User *U : users())
1269     if (!isa<BlockAddress>(U))
1270       return false;
1271 
1272   return true;
1273 }
1274 
1275 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
1276 /// setjmp or other function that gcc recognizes as "returning twice".
callsFunctionThatReturnsTwice() const1277 bool Function::callsFunctionThatReturnsTwice() const {
1278   for (const_inst_iterator
1279          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
1280     ImmutableCallSite CS(&*I);
1281     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
1282       return true;
1283   }
1284 
1285   return false;
1286 }
1287 
getPersonalityFn() const1288 Constant *Function::getPersonalityFn() const {
1289   assert(hasPersonalityFn() && getNumOperands());
1290   return cast<Constant>(Op<0>());
1291 }
1292 
setPersonalityFn(Constant * Fn)1293 void Function::setPersonalityFn(Constant *Fn) {
1294   setHungoffOperand<0>(Fn);
1295   setValueSubclassDataBit(3, Fn != nullptr);
1296 }
1297 
getPrefixData() const1298 Constant *Function::getPrefixData() const {
1299   assert(hasPrefixData() && getNumOperands());
1300   return cast<Constant>(Op<1>());
1301 }
1302 
setPrefixData(Constant * PrefixData)1303 void Function::setPrefixData(Constant *PrefixData) {
1304   setHungoffOperand<1>(PrefixData);
1305   setValueSubclassDataBit(1, PrefixData != nullptr);
1306 }
1307 
getPrologueData() const1308 Constant *Function::getPrologueData() const {
1309   assert(hasPrologueData() && getNumOperands());
1310   return cast<Constant>(Op<2>());
1311 }
1312 
setPrologueData(Constant * PrologueData)1313 void Function::setPrologueData(Constant *PrologueData) {
1314   setHungoffOperand<2>(PrologueData);
1315   setValueSubclassDataBit(2, PrologueData != nullptr);
1316 }
1317 
allocHungoffUselist()1318 void Function::allocHungoffUselist() {
1319   // If we've already allocated a uselist, stop here.
1320   if (getNumOperands())
1321     return;
1322 
1323   allocHungoffUses(3, /*IsPhi=*/ false);
1324   setNumHungOffUseOperands(3);
1325 
1326   // Initialize the uselist with placeholder operands to allow traversal.
1327   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
1328   Op<0>().set(CPN);
1329   Op<1>().set(CPN);
1330   Op<2>().set(CPN);
1331 }
1332 
1333 template <int Idx>
setHungoffOperand(Constant * C)1334 void Function::setHungoffOperand(Constant *C) {
1335   if (C) {
1336     allocHungoffUselist();
1337     Op<Idx>().set(C);
1338   } else if (getNumOperands()) {
1339     Op<Idx>().set(
1340         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
1341   }
1342 }
1343 
setValueSubclassDataBit(unsigned Bit,bool On)1344 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
1345   assert(Bit < 16 && "SubclassData contains only 16 bits");
1346   if (On)
1347     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
1348   else
1349     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
1350 }
1351 
setEntryCount(ProfileCount Count,const DenseSet<GlobalValue::GUID> * S)1352 void Function::setEntryCount(ProfileCount Count,
1353                              const DenseSet<GlobalValue::GUID> *S) {
1354   assert(Count.hasValue());
1355 #if !defined(NDEBUG)
1356   auto PrevCount = getEntryCount();
1357   assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
1358 #endif
1359   MDBuilder MDB(getContext());
1360   setMetadata(
1361       LLVMContext::MD_prof,
1362       MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
1363 }
1364 
setEntryCount(uint64_t Count,Function::ProfileCountType Type,const DenseSet<GlobalValue::GUID> * Imports)1365 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
1366                              const DenseSet<GlobalValue::GUID> *Imports) {
1367   setEntryCount(ProfileCount(Count, Type), Imports);
1368 }
1369 
getEntryCount() const1370 ProfileCount Function::getEntryCount() const {
1371   MDNode *MD = getMetadata(LLVMContext::MD_prof);
1372   if (MD && MD->getOperand(0))
1373     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
1374       if (MDS->getString().equals("function_entry_count")) {
1375         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1376         uint64_t Count = CI->getValue().getZExtValue();
1377         // A value of -1 is used for SamplePGO when there were no samples.
1378         // Treat this the same as unknown.
1379         if (Count == (uint64_t)-1)
1380           return ProfileCount::getInvalid();
1381         return ProfileCount(Count, PCT_Real);
1382       } else if (MDS->getString().equals("synthetic_function_entry_count")) {
1383         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
1384         uint64_t Count = CI->getValue().getZExtValue();
1385         return ProfileCount(Count, PCT_Synthetic);
1386       }
1387     }
1388   return ProfileCount::getInvalid();
1389 }
1390 
getImportGUIDs() const1391 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
1392   DenseSet<GlobalValue::GUID> R;
1393   if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
1394     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
1395       if (MDS->getString().equals("function_entry_count"))
1396         for (unsigned i = 2; i < MD->getNumOperands(); i++)
1397           R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
1398                        ->getValue()
1399                        .getZExtValue());
1400   return R;
1401 }
1402 
setSectionPrefix(StringRef Prefix)1403 void Function::setSectionPrefix(StringRef Prefix) {
1404   MDBuilder MDB(getContext());
1405   setMetadata(LLVMContext::MD_section_prefix,
1406               MDB.createFunctionSectionPrefix(Prefix));
1407 }
1408 
getSectionPrefix() const1409 Optional<StringRef> Function::getSectionPrefix() const {
1410   if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
1411     assert(cast<MDString>(MD->getOperand(0))
1412                ->getString()
1413                .equals("function_section_prefix") &&
1414            "Metadata not match");
1415     return cast<MDString>(MD->getOperand(1))->getString();
1416   }
1417   return None;
1418 }
1419 
nullPointerIsDefined() const1420 bool Function::nullPointerIsDefined() const {
1421   return getFnAttribute("null-pointer-is-valid")
1422           .getValueAsString()
1423           .equals("true");
1424 }
1425 
NullPointerIsDefined(const Function * F,unsigned AS)1426 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
1427   if (F && F->nullPointerIsDefined())
1428     return true;
1429 
1430   if (AS != 0)
1431     return true;
1432 
1433   return false;
1434 }
1435