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