xref: /llvm-project/llvm/lib/IR/Function.cpp (revision ab105bbf0cb190dac084717c316e5e54dd3fb104)
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 /// \brief This does the actual lookup of an intrinsic ID which
410 /// matches the given function name.
411 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
412   unsigned Len = ValName->getKeyLength();
413   const char *Name = ValName->getKeyData();
414 
415 #define GET_FUNCTION_RECOGNIZER
416 #include "llvm/IR/Intrinsics.gen"
417 #undef GET_FUNCTION_RECOGNIZER
418 
419   return Intrinsic::not_intrinsic;
420 }
421 
422 void Function::recalculateIntrinsicID() {
423   const ValueName *ValName = this->getValueName();
424   if (!ValName || !isIntrinsic()) {
425     IntID = Intrinsic::not_intrinsic;
426     return;
427   }
428   IntID = lookupIntrinsicID(ValName);
429 }
430 
431 /// Returns a stable mangling for the type specified for use in the name
432 /// mangling scheme used by 'any' types in intrinsic signatures.  The mangling
433 /// of named types is simply their name.  Manglings for unnamed types consist
434 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
435 /// combined with the mangling of their component types.  A vararg function
436 /// type will have a suffix of 'vararg'.  Since function types can contain
437 /// other function types, we close a function type mangling with suffix 'f'
438 /// which can't be confused with it's prefix.  This ensures we don't have
439 /// collisions between two unrelated function types. Otherwise, you might
440 /// parse ffXX as f(fXX) or f(fX)X.  (X is a placeholder for any other type.)
441 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
442 /// cases) fall back to the MVT codepath, where they could be mangled to
443 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle
444 /// everything.
445 static std::string getMangledTypeStr(Type* Ty) {
446   std::string Result;
447   if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
448     Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
449       getMangledTypeStr(PTyp->getElementType());
450   } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
451     Result += "a" + llvm::utostr(ATyp->getNumElements()) +
452       getMangledTypeStr(ATyp->getElementType());
453   } else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
454     assert(!STyp->isLiteral() && "TODO: implement literal types");
455     Result += STyp->getName();
456   } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
457     Result += "f_" + getMangledTypeStr(FT->getReturnType());
458     for (size_t i = 0; i < FT->getNumParams(); i++)
459       Result += getMangledTypeStr(FT->getParamType(i));
460     if (FT->isVarArg())
461       Result += "vararg";
462     // Ensure nested function types are distinguishable.
463     Result += "f";
464   } else if (isa<VectorType>(Ty))
465     Result += "v" + utostr(Ty->getVectorNumElements()) +
466       getMangledTypeStr(Ty->getVectorElementType());
467   else if (Ty)
468     Result += EVT::getEVT(Ty).getEVTString();
469   return Result;
470 }
471 
472 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
473   assert(id < num_intrinsics && "Invalid intrinsic ID!");
474   static const char * const Table[] = {
475     "not_intrinsic",
476 #define GET_INTRINSIC_NAME_TABLE
477 #include "llvm/IR/Intrinsics.gen"
478 #undef GET_INTRINSIC_NAME_TABLE
479   };
480   if (Tys.empty())
481     return Table[id];
482   std::string Result(Table[id]);
483   for (unsigned i = 0; i < Tys.size(); ++i) {
484     Result += "." + getMangledTypeStr(Tys[i]);
485   }
486   return Result;
487 }
488 
489 
490 /// IIT_Info - These are enumerators that describe the entries returned by the
491 /// getIntrinsicInfoTableEntries function.
492 ///
493 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
494 enum IIT_Info {
495   // Common values should be encoded with 0-15.
496   IIT_Done = 0,
497   IIT_I1   = 1,
498   IIT_I8   = 2,
499   IIT_I16  = 3,
500   IIT_I32  = 4,
501   IIT_I64  = 5,
502   IIT_F16  = 6,
503   IIT_F32  = 7,
504   IIT_F64  = 8,
505   IIT_V2   = 9,
506   IIT_V4   = 10,
507   IIT_V8   = 11,
508   IIT_V16  = 12,
509   IIT_V32  = 13,
510   IIT_PTR  = 14,
511   IIT_ARG  = 15,
512 
513   // Values from 16+ are only encodable with the inefficient encoding.
514   IIT_V64  = 16,
515   IIT_MMX  = 17,
516   IIT_TOKEN = 18,
517   IIT_METADATA = 19,
518   IIT_EMPTYSTRUCT = 20,
519   IIT_STRUCT2 = 21,
520   IIT_STRUCT3 = 22,
521   IIT_STRUCT4 = 23,
522   IIT_STRUCT5 = 24,
523   IIT_EXTEND_ARG = 25,
524   IIT_TRUNC_ARG = 26,
525   IIT_ANYPTR = 27,
526   IIT_V1   = 28,
527   IIT_VARARG = 29,
528   IIT_HALF_VEC_ARG = 30,
529   IIT_SAME_VEC_WIDTH_ARG = 31,
530   IIT_PTR_TO_ARG = 32,
531   IIT_VEC_OF_PTRS_TO_ELT = 33,
532   IIT_I128 = 34,
533   IIT_V512 = 35,
534   IIT_V1024 = 36
535 };
536 
537 
538 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
539                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
540   IIT_Info Info = IIT_Info(Infos[NextElt++]);
541   unsigned StructElts = 2;
542   using namespace Intrinsic;
543 
544   switch (Info) {
545   case IIT_Done:
546     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
547     return;
548   case IIT_VARARG:
549     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
550     return;
551   case IIT_MMX:
552     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
553     return;
554   case IIT_TOKEN:
555     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
556     return;
557   case IIT_METADATA:
558     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
559     return;
560   case IIT_F16:
561     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
562     return;
563   case IIT_F32:
564     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
565     return;
566   case IIT_F64:
567     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
568     return;
569   case IIT_I1:
570     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
571     return;
572   case IIT_I8:
573     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
574     return;
575   case IIT_I16:
576     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
577     return;
578   case IIT_I32:
579     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
580     return;
581   case IIT_I64:
582     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
583     return;
584   case IIT_I128:
585     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
586     return;
587   case IIT_V1:
588     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
589     DecodeIITType(NextElt, Infos, OutputTable);
590     return;
591   case IIT_V2:
592     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
593     DecodeIITType(NextElt, Infos, OutputTable);
594     return;
595   case IIT_V4:
596     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
597     DecodeIITType(NextElt, Infos, OutputTable);
598     return;
599   case IIT_V8:
600     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
601     DecodeIITType(NextElt, Infos, OutputTable);
602     return;
603   case IIT_V16:
604     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
605     DecodeIITType(NextElt, Infos, OutputTable);
606     return;
607   case IIT_V32:
608     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
609     DecodeIITType(NextElt, Infos, OutputTable);
610     return;
611   case IIT_V64:
612     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
613     DecodeIITType(NextElt, Infos, OutputTable);
614     return;
615   case IIT_V512:
616     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
617     DecodeIITType(NextElt, Infos, OutputTable);
618     return;
619   case IIT_V1024:
620     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
621     DecodeIITType(NextElt, Infos, OutputTable);
622     return;
623   case IIT_PTR:
624     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
625     DecodeIITType(NextElt, Infos, OutputTable);
626     return;
627   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
628     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
629                                              Infos[NextElt++]));
630     DecodeIITType(NextElt, Infos, OutputTable);
631     return;
632   }
633   case IIT_ARG: {
634     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
635     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
636     return;
637   }
638   case IIT_EXTEND_ARG: {
639     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
640     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
641                                              ArgInfo));
642     return;
643   }
644   case IIT_TRUNC_ARG: {
645     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
646     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
647                                              ArgInfo));
648     return;
649   }
650   case IIT_HALF_VEC_ARG: {
651     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
652     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
653                                              ArgInfo));
654     return;
655   }
656   case IIT_SAME_VEC_WIDTH_ARG: {
657     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
658     OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
659                                              ArgInfo));
660     return;
661   }
662   case IIT_PTR_TO_ARG: {
663     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
664     OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
665                                              ArgInfo));
666     return;
667   }
668   case IIT_VEC_OF_PTRS_TO_ELT: {
669     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
670     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
671                                              ArgInfo));
672     return;
673   }
674   case IIT_EMPTYSTRUCT:
675     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
676     return;
677   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
678   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
679   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
680   case IIT_STRUCT2: {
681     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
682 
683     for (unsigned i = 0; i != StructElts; ++i)
684       DecodeIITType(NextElt, Infos, OutputTable);
685     return;
686   }
687   }
688   llvm_unreachable("unhandled");
689 }
690 
691 
692 #define GET_INTRINSIC_GENERATOR_GLOBAL
693 #include "llvm/IR/Intrinsics.gen"
694 #undef GET_INTRINSIC_GENERATOR_GLOBAL
695 
696 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
697                                              SmallVectorImpl<IITDescriptor> &T){
698   // Check to see if the intrinsic's type was expressible by the table.
699   unsigned TableVal = IIT_Table[id-1];
700 
701   // Decode the TableVal into an array of IITValues.
702   SmallVector<unsigned char, 8> IITValues;
703   ArrayRef<unsigned char> IITEntries;
704   unsigned NextElt = 0;
705   if ((TableVal >> 31) != 0) {
706     // This is an offset into the IIT_LongEncodingTable.
707     IITEntries = IIT_LongEncodingTable;
708 
709     // Strip sentinel bit.
710     NextElt = (TableVal << 1) >> 1;
711   } else {
712     // Decode the TableVal into an array of IITValues.  If the entry was encoded
713     // into a single word in the table itself, decode it now.
714     do {
715       IITValues.push_back(TableVal & 0xF);
716       TableVal >>= 4;
717     } while (TableVal);
718 
719     IITEntries = IITValues;
720     NextElt = 0;
721   }
722 
723   // Okay, decode the table into the output vector of IITDescriptors.
724   DecodeIITType(NextElt, IITEntries, T);
725   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
726     DecodeIITType(NextElt, IITEntries, T);
727 }
728 
729 
730 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
731                              ArrayRef<Type*> Tys, LLVMContext &Context) {
732   using namespace Intrinsic;
733   IITDescriptor D = Infos.front();
734   Infos = Infos.slice(1);
735 
736   switch (D.Kind) {
737   case IITDescriptor::Void: return Type::getVoidTy(Context);
738   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
739   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
740   case IITDescriptor::Token: return Type::getTokenTy(Context);
741   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
742   case IITDescriptor::Half: return Type::getHalfTy(Context);
743   case IITDescriptor::Float: return Type::getFloatTy(Context);
744   case IITDescriptor::Double: return Type::getDoubleTy(Context);
745 
746   case IITDescriptor::Integer:
747     return IntegerType::get(Context, D.Integer_Width);
748   case IITDescriptor::Vector:
749     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
750   case IITDescriptor::Pointer:
751     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
752                             D.Pointer_AddressSpace);
753   case IITDescriptor::Struct: {
754     Type *Elts[5];
755     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
756     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
757       Elts[i] = DecodeFixedType(Infos, Tys, Context);
758     return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
759   }
760 
761   case IITDescriptor::Argument:
762     return Tys[D.getArgumentNumber()];
763   case IITDescriptor::ExtendArgument: {
764     Type *Ty = Tys[D.getArgumentNumber()];
765     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
766       return VectorType::getExtendedElementVectorType(VTy);
767 
768     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
769   }
770   case IITDescriptor::TruncArgument: {
771     Type *Ty = Tys[D.getArgumentNumber()];
772     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
773       return VectorType::getTruncatedElementVectorType(VTy);
774 
775     IntegerType *ITy = cast<IntegerType>(Ty);
776     assert(ITy->getBitWidth() % 2 == 0);
777     return IntegerType::get(Context, ITy->getBitWidth() / 2);
778   }
779   case IITDescriptor::HalfVecArgument:
780     return VectorType::getHalfElementsVectorType(cast<VectorType>(
781                                                   Tys[D.getArgumentNumber()]));
782   case IITDescriptor::SameVecWidthArgument: {
783     Type *EltTy = DecodeFixedType(Infos, Tys, Context);
784     Type *Ty = Tys[D.getArgumentNumber()];
785     if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
786       return VectorType::get(EltTy, VTy->getNumElements());
787     }
788     llvm_unreachable("unhandled");
789   }
790   case IITDescriptor::PtrToArgument: {
791     Type *Ty = Tys[D.getArgumentNumber()];
792     return PointerType::getUnqual(Ty);
793   }
794   case IITDescriptor::VecOfPtrsToElt: {
795     Type *Ty = Tys[D.getArgumentNumber()];
796     VectorType *VTy = dyn_cast<VectorType>(Ty);
797     if (!VTy)
798       llvm_unreachable("Expected an argument of Vector Type");
799     Type *EltTy = VTy->getVectorElementType();
800     return VectorType::get(PointerType::getUnqual(EltTy),
801                            VTy->getNumElements());
802   }
803  }
804   llvm_unreachable("unhandled");
805 }
806 
807 
808 
809 FunctionType *Intrinsic::getType(LLVMContext &Context,
810                                  ID id, ArrayRef<Type*> Tys) {
811   SmallVector<IITDescriptor, 8> Table;
812   getIntrinsicInfoTableEntries(id, Table);
813 
814   ArrayRef<IITDescriptor> TableRef = Table;
815   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
816 
817   SmallVector<Type*, 8> ArgTys;
818   while (!TableRef.empty())
819     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
820 
821   // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
822   // If we see void type as the type of the last argument, it is vararg intrinsic
823   if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
824     ArgTys.pop_back();
825     return FunctionType::get(ResultTy, ArgTys, true);
826   }
827   return FunctionType::get(ResultTy, ArgTys, false);
828 }
829 
830 bool Intrinsic::isOverloaded(ID id) {
831 #define GET_INTRINSIC_OVERLOAD_TABLE
832 #include "llvm/IR/Intrinsics.gen"
833 #undef GET_INTRINSIC_OVERLOAD_TABLE
834 }
835 
836 bool Intrinsic::isLeaf(ID id) {
837   switch (id) {
838   default:
839     return true;
840 
841   case Intrinsic::experimental_gc_statepoint:
842   case Intrinsic::experimental_patchpoint_void:
843   case Intrinsic::experimental_patchpoint_i64:
844     return false;
845   }
846 }
847 
848 /// This defines the "Intrinsic::getAttributes(ID id)" method.
849 #define GET_INTRINSIC_ATTRIBUTES
850 #include "llvm/IR/Intrinsics.gen"
851 #undef GET_INTRINSIC_ATTRIBUTES
852 
853 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
854   // There can never be multiple globals with the same name of different types,
855   // because intrinsics must be a specific type.
856   return
857     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
858                                           getType(M->getContext(), id, Tys)));
859 }
860 
861 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
862 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
863 #include "llvm/IR/Intrinsics.gen"
864 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
865 
866 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
867 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
868 #include "llvm/IR/Intrinsics.gen"
869 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
870 
871 /// hasAddressTaken - returns true if there are any uses of this function
872 /// other than direct calls or invokes to it.
873 bool Function::hasAddressTaken(const User* *PutOffender) const {
874   for (const Use &U : uses()) {
875     const User *FU = U.getUser();
876     if (isa<BlockAddress>(FU))
877       continue;
878     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
879       return PutOffender ? (*PutOffender = FU, true) : true;
880     ImmutableCallSite CS(cast<Instruction>(FU));
881     if (!CS.isCallee(&U))
882       return PutOffender ? (*PutOffender = FU, true) : true;
883   }
884   return false;
885 }
886 
887 bool Function::isDefTriviallyDead() const {
888   // Check the linkage
889   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
890       !hasAvailableExternallyLinkage())
891     return false;
892 
893   // Check if the function is used by anything other than a blockaddress.
894   for (const User *U : users())
895     if (!isa<BlockAddress>(U))
896       return false;
897 
898   return true;
899 }
900 
901 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
902 /// setjmp or other function that gcc recognizes as "returning twice".
903 bool Function::callsFunctionThatReturnsTwice() const {
904   for (const_inst_iterator
905          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
906     ImmutableCallSite CS(&*I);
907     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
908       return true;
909   }
910 
911   return false;
912 }
913 
914 Constant *Function::getPersonalityFn() const {
915   assert(hasPersonalityFn() && getNumOperands());
916   return cast<Constant>(Op<0>());
917 }
918 
919 void Function::setPersonalityFn(Constant *Fn) {
920   setHungoffOperand<0>(Fn);
921   setValueSubclassDataBit(3, Fn != nullptr);
922 }
923 
924 Constant *Function::getPrefixData() const {
925   assert(hasPrefixData() && getNumOperands());
926   return cast<Constant>(Op<1>());
927 }
928 
929 void Function::setPrefixData(Constant *PrefixData) {
930   setHungoffOperand<1>(PrefixData);
931   setValueSubclassDataBit(1, PrefixData != nullptr);
932 }
933 
934 Constant *Function::getPrologueData() const {
935   assert(hasPrologueData() && getNumOperands());
936   return cast<Constant>(Op<2>());
937 }
938 
939 void Function::setPrologueData(Constant *PrologueData) {
940   setHungoffOperand<2>(PrologueData);
941   setValueSubclassDataBit(2, PrologueData != nullptr);
942 }
943 
944 void Function::allocHungoffUselist() {
945   // If we've already allocated a uselist, stop here.
946   if (getNumOperands())
947     return;
948 
949   allocHungoffUses(3, /*IsPhi=*/ false);
950   setNumHungOffUseOperands(3);
951 
952   // Initialize the uselist with placeholder operands to allow traversal.
953   auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
954   Op<0>().set(CPN);
955   Op<1>().set(CPN);
956   Op<2>().set(CPN);
957 }
958 
959 template <int Idx>
960 void Function::setHungoffOperand(Constant *C) {
961   if (C) {
962     allocHungoffUselist();
963     Op<Idx>().set(C);
964   } else if (getNumOperands()) {
965     Op<Idx>().set(
966         ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
967   }
968 }
969 
970 void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
971   assert(Bit < 16 && "SubclassData contains only 16 bits");
972   if (On)
973     setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
974   else
975     setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
976 }
977 
978 void Function::setEntryCount(uint64_t Count) {
979   MDBuilder MDB(getContext());
980   setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
981 }
982 
983 Optional<uint64_t> Function::getEntryCount() const {
984   MDNode *MD = getMetadata(LLVMContext::MD_prof);
985   if (MD && MD->getOperand(0))
986     if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
987       if (MDS->getString().equals("function_entry_count")) {
988         ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
989         return CI->getValue().getZExtValue();
990       }
991   return None;
992 }
993