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