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