xref: /llvm-project/llvm/lib/IR/Function.cpp (revision c2752daa6bf70786ebbb448208af8fb62a431ecc)
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 "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/InstIterator.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/MDBuilder.h"
28 #include "llvm/IR/Metadata.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/RWMutex.h"
32 #include "llvm/Support/StringPool.h"
33 #include "llvm/Support/Threading.h"
34 using namespace llvm;
35 
36 // Explicit instantiations of SymbolTableListTraits since some of the methods
37 // are not in the public header file...
38 template class llvm::SymbolTableListTraits<Argument>;
39 template class llvm::SymbolTableListTraits<BasicBlock>;
40 
41 //===----------------------------------------------------------------------===//
42 // Argument Implementation
43 //===----------------------------------------------------------------------===//
44 
45 void Argument::anchor() { }
46 
47 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
48   : Value(Ty, Value::ArgumentVal) {
49   Parent = nullptr;
50 
51   if (Par)
52     Par->getArgumentList().push_back(this);
53   setName(Name);
54 }
55 
56 void Argument::setParent(Function *parent) {
57   Parent = parent;
58 }
59 
60 /// getArgNo - Return the index of this formal argument in its containing
61 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
62 unsigned Argument::getArgNo() const {
63   const Function *F = getParent();
64   assert(F && "Argument is not in a function");
65 
66   Function::const_arg_iterator AI = F->arg_begin();
67   unsigned ArgIdx = 0;
68   for (; &*AI != this; ++AI)
69     ++ArgIdx;
70 
71   return ArgIdx;
72 }
73 
74 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
75 /// it in its containing function. Also returns true if at least one byte is
76 /// known to be dereferenceable and the pointer is in addrspace(0).
77 bool Argument::hasNonNullAttr() const {
78   if (!getType()->isPointerTy()) return false;
79   if (getParent()->getAttributes().
80         hasAttribute(getArgNo()+1, Attribute::NonNull))
81     return true;
82   else if (getDereferenceableBytes() > 0 &&
83            getType()->getPointerAddressSpace() == 0)
84     return true;
85   return false;
86 }
87 
88 /// hasByValAttr - Return true if this argument has the byval attribute on it
89 /// in its containing function.
90 bool Argument::hasByValAttr() const {
91   if (!getType()->isPointerTy()) return false;
92   return getParent()->getAttributes().
93     hasAttribute(getArgNo()+1, Attribute::ByVal);
94 }
95 
96 /// \brief Return true if this argument has the inalloca attribute on it in
97 /// its containing function.
98 bool Argument::hasInAllocaAttr() const {
99   if (!getType()->isPointerTy()) return false;
100   return getParent()->getAttributes().
101     hasAttribute(getArgNo()+1, Attribute::InAlloca);
102 }
103 
104 bool Argument::hasByValOrInAllocaAttr() const {
105   if (!getType()->isPointerTy()) return false;
106   AttributeSet Attrs = getParent()->getAttributes();
107   return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
108          Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
109 }
110 
111 unsigned Argument::getParamAlignment() const {
112   assert(getType()->isPointerTy() && "Only pointers have alignments");
113   return getParent()->getParamAlignment(getArgNo()+1);
114 
115 }
116 
117 uint64_t Argument::getDereferenceableBytes() const {
118   assert(getType()->isPointerTy() &&
119          "Only pointers have dereferenceable bytes");
120   return getParent()->getDereferenceableBytes(getArgNo()+1);
121 }
122 
123 uint64_t Argument::getDereferenceableOrNullBytes() const {
124   assert(getType()->isPointerTy() &&
125          "Only pointers have dereferenceable bytes");
126   return getParent()->getDereferenceableOrNullBytes(getArgNo()+1);
127 }
128 
129 /// hasNestAttr - Return true if this argument has the nest attribute on
130 /// it in its containing function.
131 bool Argument::hasNestAttr() const {
132   if (!getType()->isPointerTy()) return false;
133   return getParent()->getAttributes().
134     hasAttribute(getArgNo()+1, Attribute::Nest);
135 }
136 
137 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
138 /// it in its containing function.
139 bool Argument::hasNoAliasAttr() const {
140   if (!getType()->isPointerTy()) return false;
141   return getParent()->getAttributes().
142     hasAttribute(getArgNo()+1, Attribute::NoAlias);
143 }
144 
145 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
146 /// on it in its containing function.
147 bool Argument::hasNoCaptureAttr() const {
148   if (!getType()->isPointerTy()) return false;
149   return getParent()->getAttributes().
150     hasAttribute(getArgNo()+1, Attribute::NoCapture);
151 }
152 
153 /// hasSRetAttr - Return true if this argument has the sret attribute on
154 /// it in its containing function.
155 bool Argument::hasStructRetAttr() const {
156   if (!getType()->isPointerTy()) return false;
157   return getParent()->getAttributes().
158     hasAttribute(getArgNo()+1, Attribute::StructRet);
159 }
160 
161 /// hasReturnedAttr - Return true if this argument has the returned attribute on
162 /// it in its containing function.
163 bool Argument::hasReturnedAttr() const {
164   return getParent()->getAttributes().
165     hasAttribute(getArgNo()+1, Attribute::Returned);
166 }
167 
168 /// hasZExtAttr - Return true if this argument has the zext attribute on it in
169 /// its containing function.
170 bool Argument::hasZExtAttr() const {
171   return getParent()->getAttributes().
172     hasAttribute(getArgNo()+1, Attribute::ZExt);
173 }
174 
175 /// hasSExtAttr Return true if this argument has the sext attribute on it in its
176 /// containing function.
177 bool Argument::hasSExtAttr() const {
178   return getParent()->getAttributes().
179     hasAttribute(getArgNo()+1, Attribute::SExt);
180 }
181 
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);
189 }
190 
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(),
198                                                getArgNo() + 1, B));
199 }
200 
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(),
208                                                   getArgNo() + 1, B));
209 }
210 
211 //===----------------------------------------------------------------------===//
212 // Helper Methods in Function
213 //===----------------------------------------------------------------------===//
214 
215 bool Function::isMaterializable() const {
216   return getGlobalObjectSubClassData() & IsMaterializableBit;
217 }
218 
219 void Function::setIsMaterializable(bool V) {
220   setGlobalObjectBit(IsMaterializableBit, V);
221 }
222 
223 LLVMContext &Function::getContext() const {
224   return getType()->getContext();
225 }
226 
227 FunctionType *Function::getFunctionType() const {
228   return cast<FunctionType>(getValueType());
229 }
230 
231 bool Function::isVarArg() const {
232   return getFunctionType()->isVarArg();
233 }
234 
235 Type *Function::getReturnType() const {
236   return getFunctionType()->getReturnType();
237 }
238 
239 void Function::removeFromParent() {
240   getParent()->getFunctionList().remove(getIterator());
241 }
242 
243 void Function::eraseFromParent() {
244   getParent()->getFunctionList().erase(getIterator());
245 }
246 
247 //===----------------------------------------------------------------------===//
248 // Function Implementation
249 //===----------------------------------------------------------------------===//
250 
251 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
252                    Module *ParentModule)
253     : GlobalObject(Ty, Value::FunctionVal,
254                    OperandTraits<Function>::op_begin(this), 0, Linkage, name) {
255   assert(FunctionType::isValidReturnType(getReturnType()) &&
256          "invalid return type");
257   setGlobalObjectSubClassData(0);
258   SymTab = new ValueSymbolTable();
259 
260   // If the function has arguments, mark them as lazily built.
261   if (Ty->getNumParams())
262     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
263 
264   if (ParentModule)
265     ParentModule->getFunctionList().push_back(this);
266 
267   // Ensure intrinsics have the right parameter attributes.
268   // Note, the IntID field will have been set in Value::setName if this function
269   // name is a valid intrinsic ID.
270   if (IntID)
271     setAttributes(Intrinsic::getAttributes(getContext(), IntID));
272 }
273 
274 Function::~Function() {
275   dropAllReferences();    // After this it is safe to delete instructions.
276 
277   // Delete all of the method arguments and unlink from symbol table...
278   ArgumentList.clear();
279   delete SymTab;
280 
281   // Remove the function from the on-the-side GC table.
282   clearGC();
283 }
284 
285 void Function::BuildLazyArguments() const {
286   // Create the arguments vector, all arguments start out unnamed.
287   FunctionType *FT = getFunctionType();
288   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
289     assert(!FT->getParamType(i)->isVoidTy() &&
290            "Cannot have void typed arguments!");
291     ArgumentList.push_back(new Argument(FT->getParamType(i)));
292   }
293 
294   // Clear the lazy arguments bit.
295   unsigned SDC = getSubclassDataFromValue();
296   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
297 }
298 
299 size_t Function::arg_size() const {
300   return getFunctionType()->getNumParams();
301 }
302 bool Function::arg_empty() const {
303   return getFunctionType()->getNumParams() == 0;
304 }
305 
306 void Function::setParent(Module *parent) {
307   Parent = parent;
308 }
309 
310 // dropAllReferences() - This function causes all the subinstructions to "let
311 // go" of all references that they are maintaining.  This allows one to
312 // 'delete' a whole class at a time, even though there may be circular
313 // references... first all references are dropped, and all use counts go to
314 // zero.  Then everything is deleted for real.  Note that no operations are
315 // valid on an object that has "dropped all references", except operator
316 // delete.
317 //
318 void Function::dropAllReferences() {
319   setIsMaterializable(false);
320 
321   for (iterator I = begin(), E = end(); I != E; ++I)
322     I->dropAllReferences();
323 
324   // Delete all basic blocks. They are now unused, except possibly by
325   // blockaddresses, but BasicBlock's destructor takes care of those.
326   while (!BasicBlocks.empty())
327     BasicBlocks.begin()->eraseFromParent();
328 
329   // Drop uses of any optional data (real or placeholder).
330   if (getNumOperands()) {
331     User::dropAllReferences();
332     setNumHungOffUseOperands(0);
333     setValueSubclassData(getSubclassDataFromValue() & ~0xe);
334   }
335 
336   // Metadata is stored in a side-table.
337   clearMetadata();
338 }
339 
340 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
341   AttributeSet PAL = getAttributes();
342   PAL = PAL.addAttribute(getContext(), i, attr);
343   setAttributes(PAL);
344 }
345 
346 void Function::addAttributes(unsigned i, AttributeSet attrs) {
347   AttributeSet PAL = getAttributes();
348   PAL = PAL.addAttributes(getContext(), i, attrs);
349   setAttributes(PAL);
350 }
351 
352 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
353   AttributeSet PAL = getAttributes();
354   PAL = PAL.removeAttributes(getContext(), i, attrs);
355   setAttributes(PAL);
356 }
357 
358 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
359   AttributeSet PAL = getAttributes();
360   PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
361   setAttributes(PAL);
362 }
363 
364 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
365   AttributeSet PAL = getAttributes();
366   PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
367   setAttributes(PAL);
368 }
369 
370 const std::string &Function::getGC() const {
371   assert(hasGC() && "Function has no collector");
372   return getContext().getGC(*this);
373 }
374 
375 void Function::setGC(const std::string Str) {
376   setValueSubclassDataBit(14, !Str.empty());
377   getContext().setGC(*this, std::move(Str));
378 }
379 
380 void Function::clearGC() {
381   if (!hasGC())
382     return;
383   getContext().deleteGC(*this);
384   setValueSubclassDataBit(14, false);
385 }
386 
387 /// Copy all additional attributes (those not needed to create a Function) from
388 /// the Function Src to this one.
389 void Function::copyAttributesFrom(const GlobalValue *Src) {
390   GlobalObject::copyAttributesFrom(Src);
391   const Function *SrcF = dyn_cast<Function>(Src);
392   if (!SrcF)
393     return;
394 
395   setCallingConv(SrcF->getCallingConv());
396   setAttributes(SrcF->getAttributes());
397   if (SrcF->hasGC())
398     setGC(SrcF->getGC());
399   else
400     clearGC();
401   if (SrcF->hasPersonalityFn())
402     setPersonalityFn(SrcF->getPersonalityFn());
403   if (SrcF->hasPrefixData())
404     setPrefixData(SrcF->getPrefixData());
405   if (SrcF->hasPrologueData())
406     setPrologueData(SrcF->getPrologueData());
407 }
408 
409 /// Table of string intrinsic names indexed by enum value.
410 static const char * const IntrinsicNameTable[] = {
411   "not_intrinsic",
412 #define GET_INTRINSIC_NAME_TABLE
413 #include "llvm/IR/Intrinsics.gen"
414 #undef GET_INTRINSIC_NAME_TABLE
415 };
416 
417 /// \brief This does the actual lookup of an intrinsic ID which
418 /// matches the given function name.
419 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
420   StringRef Name = ValName->getKey();
421 
422   ArrayRef<const char *> NameTable(&IntrinsicNameTable[1],
423                                    std::end(IntrinsicNameTable));
424   int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
425   Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + 1);
426   if (ID == Intrinsic::not_intrinsic)
427     return ID;
428 
429   // If the intrinsic is not overloaded, require an exact match. If it is
430   // overloaded, require a prefix match.
431   bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]);
432   return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
433 }
434 
435 void Function::recalculateIntrinsicID() {
436   const ValueName *ValName = this->getValueName();
437   if (!ValName || !isIntrinsic()) {
438     IntID = Intrinsic::not_intrinsic;
439     return;
440   }
441   IntID = lookupIntrinsicID(ValName);
442 }
443 
444 /// Returns a stable mangling for the type specified for use in the name
445 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
446 /// of named types is simply their name.  Manglings for unnamed types consist
447 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
448 /// combined with the mangling of their component types.  A vararg function
449 /// type will have a suffix of 'vararg'.  Since function types can contain
450 /// other function types, we close a function type mangling with suffix 'f'
451 /// which can't be confused with it's prefix.  This ensures we don't have
452 /// collisions between two unrelated function types. Otherwise, you might
453 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
454 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
455 /// cases) fall back to the MVT codepath, where they could be mangled to
456 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
457 /// everything.
458 static std::string getMangledTypeStr(Type* Ty) {
459   std::string Result;
460   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
461     Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
462       getMangledTypeStr(PTyp->getElementType());
463   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
464     Result += "a" + llvm::utostr(ATyp->getNumElements()) +
465       getMangledTypeStr(ATyp->getElementType());
466   } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
467     assert(!STyp->isLiteral() && "TODO: implement literal types");
468     Result += STyp->getName();
469   } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
470     Result += "f_" + getMangledTypeStr(FT->getReturnType());
471     for (size_t i = 0; i < FT->getNumParams(); i++)
472       Result += getMangledTypeStr(FT->getParamType(i));
473     if (FT->isVarArg())
474       Result += "vararg";
475     // Ensure nested function types are distinguishable.
476     Result += "f";
477   } else if (isa<VectorType>(Ty))
478     Result += "v" + utostr(Ty->getVectorNumElements()) +
479       getMangledTypeStr(Ty->getVectorElementType());
480   else if (Ty)
481     Result += EVT::getEVT(Ty).getEVTString();
482   return Result;
483 }
484 
485 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
486   assert(id < num_intrinsics && "Invalid intrinsic ID!");
487   if (Tys.empty())
488     return IntrinsicNameTable[id];
489   std::string Result(IntrinsicNameTable[id]);
490   for (unsigned i = 0; i < Tys.size(); ++i) {
491     Result += "." + getMangledTypeStr(Tys[i]);
492   }
493   return Result;
494 }
495 
496 
497 /// IIT_Info - These are enumerators that describe the entries returned by the
498 /// getIntrinsicInfoTableEntries function.
499 ///
500 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
501 enum IIT_Info {
502   // Common values should be encoded with 0-15.
503   IIT_Done = 0,
504   IIT_I1   = 1,
505   IIT_I8   = 2,
506   IIT_I16  = 3,
507   IIT_I32  = 4,
508   IIT_I64  = 5,
509   IIT_F16  = 6,
510   IIT_F32  = 7,
511   IIT_F64  = 8,
512   IIT_V2   = 9,
513   IIT_V4   = 10,
514   IIT_V8   = 11,
515   IIT_V16  = 12,
516   IIT_V32  = 13,
517   IIT_PTR  = 14,
518   IIT_ARG  = 15,
519 
520   // Values from 16+ are only encodable with the inefficient encoding.
521   IIT_V64  = 16,
522   IIT_MMX  = 17,
523   IIT_TOKEN = 18,
524   IIT_METADATA = 19,
525   IIT_EMPTYSTRUCT = 20,
526   IIT_STRUCT2 = 21,
527   IIT_STRUCT3 = 22,
528   IIT_STRUCT4 = 23,
529   IIT_STRUCT5 = 24,
530   IIT_EXTEND_ARG = 25,
531   IIT_TRUNC_ARG = 26,
532   IIT_ANYPTR = 27,
533   IIT_V1   = 28,
534   IIT_VARARG = 29,
535   IIT_HALF_VEC_ARG = 30,
536   IIT_SAME_VEC_WIDTH_ARG = 31,
537   IIT_PTR_TO_ARG = 32,
538   IIT_VEC_OF_PTRS_TO_ELT = 33,
539   IIT_I128 = 34,
540   IIT_V512 = 35,
541   IIT_V1024 = 36
542 };
543 
544 
545 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
546                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
547   IIT_Info Info = IIT_Info(Infos[NextElt++]);
548   unsigned StructElts = 2;
549   using namespace Intrinsic;
550 
551   switch (Info) {
552   case IIT_Done:
553     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
554     return;
555   case IIT_VARARG:
556     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
557     return;
558   case IIT_MMX:
559     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
560     return;
561   case IIT_TOKEN:
562     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
563     return;
564   case IIT_METADATA:
565     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
566     return;
567   case IIT_F16:
568     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
569     return;
570   case IIT_F32:
571     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
572     return;
573   case IIT_F64:
574     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
575     return;
576   case IIT_I1:
577     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
578     return;
579   case IIT_I8:
580     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
581     return;
582   case IIT_I16:
583     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
584     return;
585   case IIT_I32:
586     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
587     return;
588   case IIT_I64:
589     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
590     return;
591   case IIT_I128:
592     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
593     return;
594   case IIT_V1:
595     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
596     DecodeIITType(NextElt, Infos, OutputTable);
597     return;
598   case IIT_V2:
599     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
600     DecodeIITType(NextElt, Infos, OutputTable);
601     return;
602   case IIT_V4:
603     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
604     DecodeIITType(NextElt, Infos, OutputTable);
605     return;
606   case IIT_V8:
607     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
608     DecodeIITType(NextElt, Infos, OutputTable);
609     return;
610   case IIT_V16:
611     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
612     DecodeIITType(NextElt, Infos, OutputTable);
613     return;
614   case IIT_V32:
615     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
616     DecodeIITType(NextElt, Infos, OutputTable);
617     return;
618   case IIT_V64:
619     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
620     DecodeIITType(NextElt, Infos, OutputTable);
621     return;
622   case IIT_V512:
623     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
624     DecodeIITType(NextElt, Infos, OutputTable);
625     return;
626   case IIT_V1024:
627     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
628     DecodeIITType(NextElt, Infos, OutputTable);
629     return;
630   case IIT_PTR:
631     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
632     DecodeIITType(NextElt, Infos, OutputTable);
633     return;
634   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
635     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
636                                              Infos[NextElt++]));
637     DecodeIITType(NextElt, Infos, OutputTable);
638     return;
639   }
640   case IIT_ARG: {
641     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
642     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
643     return;
644   }
645   case IIT_EXTEND_ARG: {
646     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
647     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
648                                              ArgInfo));
649     return;
650   }
651   case IIT_TRUNC_ARG: {
652     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
653     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
654                                              ArgInfo));
655     return;
656   }
657   case IIT_HALF_VEC_ARG: {
658     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
659     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
660                                              ArgInfo));
661     return;
662   }
663   case IIT_SAME_VEC_WIDTH_ARG: {
664     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
665     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
666                                              ArgInfo));
667     return;
668   }
669   case IIT_PTR_TO_ARG: {
670     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
671     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
672                                              ArgInfo));
673     return;
674   }
675   case IIT_VEC_OF_PTRS_TO_ELT: {
676     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
677     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
678                                              ArgInfo));
679     return;
680   }
681   case IIT_EMPTYSTRUCT:
682     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
683     return;
684   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
685   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
686   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
687   case IIT_STRUCT2: {
688     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
689 
690     for (unsigned i = 0; i != StructElts; ++i)
691       DecodeIITType(NextElt, Infos, OutputTable);
692     return;
693   }
694   }
695   llvm_unreachable("unhandled");
696 }
697 
698 
699 #define GET_INTRINSIC_GENERATOR_GLOBAL
700 #include "llvm/IR/Intrinsics.gen"
701 #undef GET_INTRINSIC_GENERATOR_GLOBAL
702 
703 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
704                                              SmallVectorImpl<IITDescriptor> &T){
705   // Check to see if the intrinsic's type was expressible by the table.
706   unsigned TableVal = IIT_Table[id-1];
707 
708   // Decode the TableVal into an array of IITValues.
709   SmallVector<unsigned char, 8> IITValues;
710   ArrayRef<unsigned char> IITEntries;
711   unsigned NextElt = 0;
712   if ((TableVal >> 31) != 0) {
713     // This is an offset into the IIT_LongEncodingTable.
714     IITEntries = IIT_LongEncodingTable;
715 
716     // Strip sentinel bit.
717     NextElt = (TableVal << 1) >> 1;
718   } else {
719     // Decode the TableVal into an array of IITValues.  If the entry was encoded
720     // into a single word in the table itself, decode it now.
721     do {
722       IITValues.push_back(TableVal & 0xF);
723       TableVal >>= 4;
724     } while (TableVal);
725 
726     IITEntries = IITValues;
727     NextElt = 0;
728   }
729 
730   // Okay, decode the table into the output vector of IITDescriptors.
731   DecodeIITType(NextElt, IITEntries, T);
732   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
733     DecodeIITType(NextElt, IITEntries, T);
734 }
735 
736 
737 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
738                              ArrayRef<Type*> Tys, LLVMContext &Context) {
739   using namespace Intrinsic;
740   IITDescriptor D = Infos.front();
741   Infos = Infos.slice(1);
742 
743   switch (D.Kind) {
744   case IITDescriptor::Void: return Type::getVoidTy(Context);
745   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
746   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
747   case IITDescriptor::Token: return Type::getTokenTy(Context);
748   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
749   case IITDescriptor::Half: return Type::getHalfTy(Context);
750   case IITDescriptor::Float: return Type::getFloatTy(Context);
751   case IITDescriptor::Double: return Type::getDoubleTy(Context);
752 
753   case IITDescriptor::Integer:
754     return IntegerType::get(Context, D.Integer_Width);
755   case IITDescriptor::Vector:
756     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
757   case IITDescriptor::Pointer:
758     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
759                             D.Pointer_AddressSpace);
760   case IITDescriptor::Struct: {
761     Type *Elts[5];
762     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
763     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
764       Elts[i] = DecodeFixedType(Infos, Tys, Context);
765     return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
766   }
767 
768   case IITDescriptor::Argument:
769     return Tys[D.getArgumentNumber()];
770   case IITDescriptor::ExtendArgument: {
771     Type *Ty = Tys[D.getArgumentNumber()];
772     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
773       return VectorType::getExtendedElementVectorType(VTy);
774 
775     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
776   }
777   case IITDescriptor::TruncArgument: {
778     Type *Ty = Tys[D.getArgumentNumber()];
779     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
780       return VectorType::getTruncatedElementVectorType(VTy);
781 
782     IntegerType *ITy = cast<IntegerType>(Ty);
783     assert(ITy->getBitWidth() % 2 == 0);
784     return IntegerType::get(Context, ITy->getBitWidth() / 2);
785   }
786   case IITDescriptor::HalfVecArgument:
787     return VectorType::getHalfElementsVectorType(cast<VectorType>(
788                                                   Tys[D.getArgumentNumber()]));
789   case IITDescriptor::SameVecWidthArgument: {
790     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
791     Type *Ty = Tys[D.getArgumentNumber()];
792     if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
793       return VectorType::get(EltTy, VTy->getNumElements());
794     }
795     llvm_unreachable("unhandled");
796   }
797   case IITDescriptor::PtrToArgument: {
798     Type *Ty = Tys[D.getArgumentNumber()];
799     return PointerType::getUnqual(Ty);
800   }
801   case IITDescriptor::VecOfPtrsToElt: {
802     Type *Ty = Tys[D.getArgumentNumber()];
803     VectorType *VTy = dyn_cast<VectorType>(Ty);
804     if (!VTy)
805       llvm_unreachable("Expected an argument of Vector Type");
806     Type *EltTy = VTy->getVectorElementType();
807     return VectorType::get(PointerType::getUnqual(EltTy),
808                            VTy->getNumElements());
809   }
810  }
811   llvm_unreachable("unhandled");
812 }
813 
814 
815 
816 FunctionType *Intrinsic::getType(LLVMContext &Context,
817                                  ID id, ArrayRef<Type*> Tys) {
818   SmallVector<IITDescriptor, 8> Table;
819   getIntrinsicInfoTableEntries(id, Table);
820 
821   ArrayRef<IITDescriptor> TableRef = Table;
822   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
823 
824   SmallVector<Type*, 8> ArgTys;
825   while (!TableRef.empty())
826     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
827 
828   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
829   // If we see void type as the type of the last argument, it is vararg intrinsic
830   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
831     ArgTys.pop_back();
832     return FunctionType::get(ResultTy, ArgTys, true);
833   }
834   return FunctionType::get(ResultTy, ArgTys, false);
835 }
836 
837 bool Intrinsic::isOverloaded(ID id) {
838 #define GET_INTRINSIC_OVERLOAD_TABLE
839 #include "llvm/IR/Intrinsics.gen"
840 #undef GET_INTRINSIC_OVERLOAD_TABLE
841 }
842 
843 bool Intrinsic::isLeaf(ID id) {
844   switch (id) {
845   default:
846     return true;
847 
848   case Intrinsic::experimental_gc_statepoint:
849   case Intrinsic::experimental_patchpoint_void:
850   case Intrinsic::experimental_patchpoint_i64:
851     return false;
852   }
853 }
854 
855 /// This defines the "Intrinsic::getAttributes(ID id)" method.
856 #define GET_INTRINSIC_ATTRIBUTES
857 #include "llvm/IR/Intrinsics.gen"
858 #undef GET_INTRINSIC_ATTRIBUTES
859 
860 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
861   // There can never be multiple globals with the same name of different types,
862   // because intrinsics must be a specific type.
863   return
864     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
865                                           getType(M->getContext(), id, Tys)));
866 }
867 
868 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
869 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
870 #include "llvm/IR/Intrinsics.gen"
871 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
872 
873 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
874 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
875 #include "llvm/IR/Intrinsics.gen"
876 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
877 
878 /// hasAddressTaken - returns true if there are any uses of this function
879 /// other than direct calls or invokes to it.
880 bool Function::hasAddressTaken(const User* *PutOffender) const {
881   for (const Use &U : uses()) {
882     const User *FU = U.getUser();
883     if (isa<BlockAddress>(FU))
884       continue;
885     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
886       return PutOffender ? (*PutOffender = FU, true) : true;
887     ImmutableCallSite CS(cast<Instruction>(FU));
888     if (!CS.isCallee(&U))
889       return PutOffender ? (*PutOffender = FU, true) : true;
890   }
891   return false;
892 }
893 
894 bool Function::isDefTriviallyDead() const {
895   // Check the linkage
896   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
897       !hasAvailableExternallyLinkage())
898     return false;
899 
900   // Check if the function is used by anything other than a blockaddress.
901   for (const User *U : users())
902     if (!isa<BlockAddress>(U))
903       return false;
904 
905   return true;
906 }
907 
908 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
909 /// setjmp or other function that gcc recognizes as "returning twice".
910 bool Function::callsFunctionThatReturnsTwice() const {
911   for (const_inst_iterator
912          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
913     ImmutableCallSite CS(&*I);
914     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
915       return true;
916   }
917 
918   return false;
919 }
920 
921 Constant *Function::getPersonalityFn() const {
922   assert(hasPersonalityFn() && getNumOperands());
923   return cast<Constant>(Op<0>());
924 }
925 
926 void Function::setPersonalityFn(Constant *Fn) {
927   setHungoffOperand<0>(Fn);
928   setValueSubclassDataBit(3, Fn != nullptr);
929 }
930 
931 Constant *Function::getPrefixData() const {
932   assert(hasPrefixData() && getNumOperands());
933   return cast<Constant>(Op<1>());
934 }
935 
936 void Function::setPrefixData(Constant *PrefixData) {
937   setHungoffOperand<1>(PrefixData);
938   setValueSubclassDataBit(1, PrefixData != nullptr);
939 }
940 
941 Constant *Function::getPrologueData() const {
942   assert(hasPrologueData() && getNumOperands());
943   return cast<Constant>(Op<2>());
944 }
945 
946 void Function::setPrologueData(Constant *PrologueData) {
947   setHungoffOperand<2>(PrologueData);
948   setValueSubclassDataBit(2, PrologueData != nullptr);
949 }
950 
951 void Function::allocHungoffUselist() {
952   // If we've already allocated a uselist, stop here.
953   if (getNumOperands())
954     return;
955 
956   allocHungoffUses(3, /*IsPhi=*/ false);
957   setNumHungOffUseOperands(3);
958 
959   // Initialize the uselist with placeholder operands to allow traversal.
960   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
961   Op<0>().set(CPN);
962   Op<1>().set(CPN);
963   Op<2>().set(CPN);
964 }
965 
966 template <int Idx>
967 void Function::setHungoffOperand(Constant *C) {
968   if (C) {
969     allocHungoffUselist();
970     Op<Idx>().set(C);
971   } else if (getNumOperands()) {
972     Op<Idx>().set(
973         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
974   }
975 }
976 
977 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
978   assert(Bit < 16 && "SubclassData contains only 16 bits");
979   if (On)
980     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
981   else
982     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
983 }
984 
985 void Function::setEntryCount(uint64_t Count) {
986   MDBuilder MDB(getContext());
987   setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
988 }
989 
990 Optional<uint64_t> Function::getEntryCount() const {
991   MDNode *MD = getMetadata(LLVMContext::MD_prof);
992   if (MD && MD->getOperand(0))
993     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
994       if (MDS->getString().equals("function_entry_count")) {
995         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
996         return CI->getValue().getZExtValue();
997       }
998   return None;
999 }
1000