• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Function.cpp - Implement the Global object classes ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Function class for the IR library.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/Function.h"
15 #include "LLVMContextImpl.h"
16 #include "SymbolTableListTraitsImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/CodeGen/ValueTypes.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/InstIterator.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/LeakDetector.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/RWMutex.h"
30 #include "llvm/Support/StringPool.h"
31 #include "llvm/Support/Threading.h"
32 using namespace llvm;
33 
34 // Explicit instantiations of SymbolTableListTraits since some of the methods
35 // are not in the public header file...
36 template class llvm::SymbolTableListTraits<Argument, Function>;
37 template class llvm::SymbolTableListTraits<BasicBlock, Function>;
38 
39 //===----------------------------------------------------------------------===//
40 // Argument Implementation
41 //===----------------------------------------------------------------------===//
42 
anchor()43 void Argument::anchor() { }
44 
Argument(Type * Ty,const Twine & Name,Function * Par)45 Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
46   : Value(Ty, Value::ArgumentVal) {
47   Parent = nullptr;
48 
49   // Make sure that we get added to a function
50   LeakDetector::addGarbageObject(this);
51 
52   if (Par)
53     Par->getArgumentList().push_back(this);
54   setName(Name);
55 }
56 
setParent(Function * parent)57 void Argument::setParent(Function *parent) {
58   if (getParent())
59     LeakDetector::addGarbageObject(this);
60   Parent = parent;
61   if (getParent())
62     LeakDetector::removeGarbageObject(this);
63 }
64 
65 /// getArgNo - Return the index of this formal argument in its containing
66 /// function.  For example in "void foo(int a, float b)" a is 0 and b is 1.
getArgNo() const67 unsigned Argument::getArgNo() const {
68   const Function *F = getParent();
69   assert(F && "Argument is not in a function");
70 
71   Function::const_arg_iterator AI = F->arg_begin();
72   unsigned ArgIdx = 0;
73   for (; &*AI != this; ++AI)
74     ++ArgIdx;
75 
76   return ArgIdx;
77 }
78 
79 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on
80 /// it in its containing function.
hasNonNullAttr() const81 bool Argument::hasNonNullAttr() const {
82   if (!getType()->isPointerTy()) return false;
83   return getParent()->getAttributes().
84     hasAttribute(getArgNo()+1, Attribute::NonNull);
85 }
86 
87 /// hasByValAttr - Return true if this argument has the byval attribute on it
88 /// in its containing function.
hasByValAttr() const89 bool Argument::hasByValAttr() const {
90   if (!getType()->isPointerTy()) return false;
91   return getParent()->getAttributes().
92     hasAttribute(getArgNo()+1, Attribute::ByVal);
93 }
94 
95 /// \brief Return true if this argument has the inalloca attribute on it in
96 /// its containing function.
hasInAllocaAttr() const97 bool Argument::hasInAllocaAttr() const {
98   if (!getType()->isPointerTy()) return false;
99   return getParent()->getAttributes().
100     hasAttribute(getArgNo()+1, Attribute::InAlloca);
101 }
102 
hasByValOrInAllocaAttr() const103 bool Argument::hasByValOrInAllocaAttr() const {
104   if (!getType()->isPointerTy()) return false;
105   AttributeSet Attrs = getParent()->getAttributes();
106   return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
107          Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
108 }
109 
getParamAlignment() const110 unsigned Argument::getParamAlignment() const {
111   assert(getType()->isPointerTy() && "Only pointers have alignments");
112   return getParent()->getParamAlignment(getArgNo()+1);
113 
114 }
115 
116 /// hasNestAttr - Return true if this argument has the nest attribute on
117 /// it in its containing function.
hasNestAttr() const118 bool Argument::hasNestAttr() const {
119   if (!getType()->isPointerTy()) return false;
120   return getParent()->getAttributes().
121     hasAttribute(getArgNo()+1, Attribute::Nest);
122 }
123 
124 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on
125 /// it in its containing function.
hasNoAliasAttr() const126 bool Argument::hasNoAliasAttr() const {
127   if (!getType()->isPointerTy()) return false;
128   return getParent()->getAttributes().
129     hasAttribute(getArgNo()+1, Attribute::NoAlias);
130 }
131 
132 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
133 /// on it in its containing function.
hasNoCaptureAttr() const134 bool Argument::hasNoCaptureAttr() const {
135   if (!getType()->isPointerTy()) return false;
136   return getParent()->getAttributes().
137     hasAttribute(getArgNo()+1, Attribute::NoCapture);
138 }
139 
140 /// hasSRetAttr - Return true if this argument has the sret attribute on
141 /// it in its containing function.
hasStructRetAttr() const142 bool Argument::hasStructRetAttr() const {
143   if (!getType()->isPointerTy()) return false;
144   if (this != getParent()->arg_begin())
145     return false; // StructRet param must be first param
146   return getParent()->getAttributes().
147     hasAttribute(1, Attribute::StructRet);
148 }
149 
150 /// hasReturnedAttr - Return true if this argument has the returned attribute on
151 /// it in its containing function.
hasReturnedAttr() const152 bool Argument::hasReturnedAttr() const {
153   return getParent()->getAttributes().
154     hasAttribute(getArgNo()+1, Attribute::Returned);
155 }
156 
157 /// Return true if this argument has the readonly or readnone attribute on it
158 /// in its containing function.
onlyReadsMemory() const159 bool Argument::onlyReadsMemory() const {
160   return getParent()->getAttributes().
161       hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
162       getParent()->getAttributes().
163       hasAttribute(getArgNo()+1, Attribute::ReadNone);
164 }
165 
166 /// addAttr - Add attributes to an argument.
addAttr(AttributeSet AS)167 void Argument::addAttr(AttributeSet AS) {
168   assert(AS.getNumSlots() <= 1 &&
169          "Trying to add more than one attribute set to an argument!");
170   AttrBuilder B(AS, AS.getSlotIndex(0));
171   getParent()->addAttributes(getArgNo() + 1,
172                              AttributeSet::get(Parent->getContext(),
173                                                getArgNo() + 1, B));
174 }
175 
176 /// removeAttr - Remove attributes from an argument.
removeAttr(AttributeSet AS)177 void Argument::removeAttr(AttributeSet AS) {
178   assert(AS.getNumSlots() <= 1 &&
179          "Trying to remove more than one attribute set from an argument!");
180   AttrBuilder B(AS, AS.getSlotIndex(0));
181   getParent()->removeAttributes(getArgNo() + 1,
182                                 AttributeSet::get(Parent->getContext(),
183                                                   getArgNo() + 1, B));
184 }
185 
186 //===----------------------------------------------------------------------===//
187 // Helper Methods in Function
188 //===----------------------------------------------------------------------===//
189 
getContext() const190 LLVMContext &Function::getContext() const {
191   return getType()->getContext();
192 }
193 
getFunctionType() const194 FunctionType *Function::getFunctionType() const {
195   return cast<FunctionType>(getType()->getElementType());
196 }
197 
isVarArg() const198 bool Function::isVarArg() const {
199   return getFunctionType()->isVarArg();
200 }
201 
getReturnType() const202 Type *Function::getReturnType() const {
203   return getFunctionType()->getReturnType();
204 }
205 
removeFromParent()206 void Function::removeFromParent() {
207   getParent()->getFunctionList().remove(this);
208 }
209 
eraseFromParent()210 void Function::eraseFromParent() {
211   getParent()->getFunctionList().erase(this);
212 }
213 
214 //===----------------------------------------------------------------------===//
215 // Function Implementation
216 //===----------------------------------------------------------------------===//
217 
Function(FunctionType * Ty,LinkageTypes Linkage,const Twine & name,Module * ParentModule)218 Function::Function(FunctionType *Ty, LinkageTypes Linkage,
219                    const Twine &name, Module *ParentModule)
220   : GlobalObject(PointerType::getUnqual(Ty),
221                 Value::FunctionVal, nullptr, 0, Linkage, name) {
222   assert(FunctionType::isValidReturnType(getReturnType()) &&
223          "invalid return type");
224   SymTab = new ValueSymbolTable();
225 
226   // If the function has arguments, mark them as lazily built.
227   if (Ty->getNumParams())
228     setValueSubclassData(1);   // Set the "has lazy arguments" bit.
229 
230   // Make sure that we get added to a function
231   LeakDetector::addGarbageObject(this);
232 
233   if (ParentModule)
234     ParentModule->getFunctionList().push_back(this);
235 
236   // Ensure intrinsics have the right parameter attributes.
237   if (unsigned IID = getIntrinsicID())
238     setAttributes(Intrinsic::getAttributes(getContext(), Intrinsic::ID(IID)));
239 
240 }
241 
~Function()242 Function::~Function() {
243   dropAllReferences();    // After this it is safe to delete instructions.
244 
245   // Delete all of the method arguments and unlink from symbol table...
246   ArgumentList.clear();
247   delete SymTab;
248 
249   // Remove the function from the on-the-side GC table.
250   clearGC();
251 
252   // Remove the intrinsicID from the Cache.
253   if (getValueName() && isIntrinsic())
254     getContext().pImpl->IntrinsicIDCache.erase(this);
255 }
256 
BuildLazyArguments() const257 void Function::BuildLazyArguments() const {
258   // Create the arguments vector, all arguments start out unnamed.
259   FunctionType *FT = getFunctionType();
260   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
261     assert(!FT->getParamType(i)->isVoidTy() &&
262            "Cannot have void typed arguments!");
263     ArgumentList.push_back(new Argument(FT->getParamType(i)));
264   }
265 
266   // Clear the lazy arguments bit.
267   unsigned SDC = getSubclassDataFromValue();
268   const_cast<Function*>(this)->setValueSubclassData(SDC &= ~1);
269 }
270 
arg_size() const271 size_t Function::arg_size() const {
272   return getFunctionType()->getNumParams();
273 }
arg_empty() const274 bool Function::arg_empty() const {
275   return getFunctionType()->getNumParams() == 0;
276 }
277 
setParent(Module * parent)278 void Function::setParent(Module *parent) {
279   if (getParent())
280     LeakDetector::addGarbageObject(this);
281   Parent = parent;
282   if (getParent())
283     LeakDetector::removeGarbageObject(this);
284 }
285 
286 // dropAllReferences() - This function causes all the subinstructions to "let
287 // go" of all references that they are maintaining.  This allows one to
288 // 'delete' a whole class at a time, even though there may be circular
289 // references... first all references are dropped, and all use counts go to
290 // zero.  Then everything is deleted for real.  Note that no operations are
291 // valid on an object that has "dropped all references", except operator
292 // delete.
293 //
dropAllReferences()294 void Function::dropAllReferences() {
295   for (iterator I = begin(), E = end(); I != E; ++I)
296     I->dropAllReferences();
297 
298   // Delete all basic blocks. They are now unused, except possibly by
299   // blockaddresses, but BasicBlock's destructor takes care of those.
300   while (!BasicBlocks.empty())
301     BasicBlocks.begin()->eraseFromParent();
302 
303   // Prefix data is stored in a side table.
304   setPrefixData(nullptr);
305 }
306 
addAttribute(unsigned i,Attribute::AttrKind attr)307 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
308   AttributeSet PAL = getAttributes();
309   PAL = PAL.addAttribute(getContext(), i, attr);
310   setAttributes(PAL);
311 }
312 
addAttributes(unsigned i,AttributeSet attrs)313 void Function::addAttributes(unsigned i, AttributeSet attrs) {
314   AttributeSet PAL = getAttributes();
315   PAL = PAL.addAttributes(getContext(), i, attrs);
316   setAttributes(PAL);
317 }
318 
removeAttributes(unsigned i,AttributeSet attrs)319 void Function::removeAttributes(unsigned i, AttributeSet attrs) {
320   AttributeSet PAL = getAttributes();
321   PAL = PAL.removeAttributes(getContext(), i, attrs);
322   setAttributes(PAL);
323 }
324 
325 // Maintain the GC name for each function in an on-the-side table. This saves
326 // allocating an additional word in Function for programs which do not use GC
327 // (i.e., most programs) at the cost of increased overhead for clients which do
328 // use GC.
329 static DenseMap<const Function*,PooledStringPtr> *GCNames;
330 static StringPool *GCNamePool;
331 static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
332 
hasGC() const333 bool Function::hasGC() const {
334   sys::SmartScopedReader<true> Reader(*GCLock);
335   return GCNames && GCNames->count(this);
336 }
337 
getGC() const338 const char *Function::getGC() const {
339   assert(hasGC() && "Function has no collector");
340   sys::SmartScopedReader<true> Reader(*GCLock);
341   return *(*GCNames)[this];
342 }
343 
setGC(const char * Str)344 void Function::setGC(const char *Str) {
345   sys::SmartScopedWriter<true> Writer(*GCLock);
346   if (!GCNamePool)
347     GCNamePool = new StringPool();
348   if (!GCNames)
349     GCNames = new DenseMap<const Function*,PooledStringPtr>();
350   (*GCNames)[this] = GCNamePool->intern(Str);
351 }
352 
clearGC()353 void Function::clearGC() {
354   sys::SmartScopedWriter<true> Writer(*GCLock);
355   if (GCNames) {
356     GCNames->erase(this);
357     if (GCNames->empty()) {
358       delete GCNames;
359       GCNames = nullptr;
360       if (GCNamePool->empty()) {
361         delete GCNamePool;
362         GCNamePool = nullptr;
363       }
364     }
365   }
366 }
367 
368 /// copyAttributesFrom - copy all additional attributes (those not needed to
369 /// create a Function) from the Function Src to this one.
copyAttributesFrom(const GlobalValue * Src)370 void Function::copyAttributesFrom(const GlobalValue *Src) {
371   assert(isa<Function>(Src) && "Expected a Function!");
372   GlobalObject::copyAttributesFrom(Src);
373   const Function *SrcF = cast<Function>(Src);
374   setCallingConv(SrcF->getCallingConv());
375   setAttributes(SrcF->getAttributes());
376   if (SrcF->hasGC())
377     setGC(SrcF->getGC());
378   else
379     clearGC();
380   if (SrcF->hasPrefixData())
381     setPrefixData(SrcF->getPrefixData());
382   else
383     setPrefixData(nullptr);
384 }
385 
386 /// getIntrinsicID - This method returns the ID number of the specified
387 /// function, or Intrinsic::not_intrinsic if the function is not an
388 /// intrinsic, or if the pointer is null.  This value is always defined to be
389 /// zero to allow easy checking for whether a function is intrinsic or not.  The
390 /// particular intrinsic functions which correspond to this value are defined in
391 /// llvm/Intrinsics.h.  Results are cached in the LLVM context, subsequent
392 /// requests for the same ID return results much faster from the cache.
393 ///
getIntrinsicID() const394 unsigned Function::getIntrinsicID() const {
395   const ValueName *ValName = this->getValueName();
396   if (!ValName || !isIntrinsic())
397     return 0;
398 
399   LLVMContextImpl::IntrinsicIDCacheTy &IntrinsicIDCache =
400     getContext().pImpl->IntrinsicIDCache;
401   if (!IntrinsicIDCache.count(this)) {
402     unsigned Id = lookupIntrinsicID();
403     IntrinsicIDCache[this]=Id;
404     return Id;
405   }
406   return IntrinsicIDCache[this];
407 }
408 
409 /// This private method does the actual lookup of an intrinsic ID when the query
410 /// could not be answered from the cache.
lookupIntrinsicID() const411 unsigned Function::lookupIntrinsicID() const {
412   const ValueName *ValName = this->getValueName();
413   unsigned Len = ValName->getKeyLength();
414   const char *Name = ValName->getKeyData();
415 
416 #define GET_FUNCTION_RECOGNIZER
417 #include "llvm/IR/Intrinsics.gen"
418 #undef GET_FUNCTION_RECOGNIZER
419 
420   return 0;
421 }
422 
getName(ID id,ArrayRef<Type * > Tys)423 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
424   assert(id < num_intrinsics && "Invalid intrinsic ID!");
425   static const char * const Table[] = {
426     "not_intrinsic",
427 #define GET_INTRINSIC_NAME_TABLE
428 #include "llvm/IR/Intrinsics.gen"
429 #undef GET_INTRINSIC_NAME_TABLE
430   };
431   if (Tys.empty())
432     return Table[id];
433   std::string Result(Table[id]);
434   for (unsigned i = 0; i < Tys.size(); ++i) {
435     if (PointerType* PTyp = dyn_cast<PointerType>(Tys[i])) {
436       Result += ".p" + llvm::utostr(PTyp->getAddressSpace()) +
437                 EVT::getEVT(PTyp->getElementType()).getEVTString();
438     }
439     else if (Tys[i])
440       Result += "." + EVT::getEVT(Tys[i]).getEVTString();
441   }
442   return Result;
443 }
444 
445 
446 /// IIT_Info - These are enumerators that describe the entries returned by the
447 /// getIntrinsicInfoTableEntries function.
448 ///
449 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
450 enum IIT_Info {
451   // Common values should be encoded with 0-15.
452   IIT_Done = 0,
453   IIT_I1   = 1,
454   IIT_I8   = 2,
455   IIT_I16  = 3,
456   IIT_I32  = 4,
457   IIT_I64  = 5,
458   IIT_F16  = 6,
459   IIT_F32  = 7,
460   IIT_F64  = 8,
461   IIT_V2   = 9,
462   IIT_V4   = 10,
463   IIT_V8   = 11,
464   IIT_V16  = 12,
465   IIT_V32  = 13,
466   IIT_PTR  = 14,
467   IIT_ARG  = 15,
468 
469   // Values from 16+ are only encodable with the inefficient encoding.
470   IIT_MMX  = 16,
471   IIT_METADATA = 17,
472   IIT_EMPTYSTRUCT = 18,
473   IIT_STRUCT2 = 19,
474   IIT_STRUCT3 = 20,
475   IIT_STRUCT4 = 21,
476   IIT_STRUCT5 = 22,
477   IIT_EXTEND_ARG = 23,
478   IIT_TRUNC_ARG = 24,
479   IIT_ANYPTR = 25,
480   IIT_V1   = 26,
481   IIT_VARARG = 27,
482   IIT_HALF_VEC_ARG = 28
483 };
484 
485 
DecodeIITType(unsigned & NextElt,ArrayRef<unsigned char> Infos,SmallVectorImpl<Intrinsic::IITDescriptor> & OutputTable)486 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
487                       SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
488   IIT_Info Info = IIT_Info(Infos[NextElt++]);
489   unsigned StructElts = 2;
490   using namespace Intrinsic;
491 
492   switch (Info) {
493   case IIT_Done:
494     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
495     return;
496   case IIT_VARARG:
497     OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
498     return;
499   case IIT_MMX:
500     OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
501     return;
502   case IIT_METADATA:
503     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
504     return;
505   case IIT_F16:
506     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
507     return;
508   case IIT_F32:
509     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
510     return;
511   case IIT_F64:
512     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
513     return;
514   case IIT_I1:
515     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
516     return;
517   case IIT_I8:
518     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
519     return;
520   case IIT_I16:
521     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
522     return;
523   case IIT_I32:
524     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
525     return;
526   case IIT_I64:
527     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
528     return;
529   case IIT_V1:
530     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
531     DecodeIITType(NextElt, Infos, OutputTable);
532     return;
533   case IIT_V2:
534     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
535     DecodeIITType(NextElt, Infos, OutputTable);
536     return;
537   case IIT_V4:
538     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
539     DecodeIITType(NextElt, Infos, OutputTable);
540     return;
541   case IIT_V8:
542     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
543     DecodeIITType(NextElt, Infos, OutputTable);
544     return;
545   case IIT_V16:
546     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
547     DecodeIITType(NextElt, Infos, OutputTable);
548     return;
549   case IIT_V32:
550     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
551     DecodeIITType(NextElt, Infos, OutputTable);
552     return;
553   case IIT_PTR:
554     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
555     DecodeIITType(NextElt, Infos, OutputTable);
556     return;
557   case IIT_ANYPTR: {  // [ANYPTR addrspace, subtype]
558     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
559                                              Infos[NextElt++]));
560     DecodeIITType(NextElt, Infos, OutputTable);
561     return;
562   }
563   case IIT_ARG: {
564     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
565     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
566     return;
567   }
568   case IIT_EXTEND_ARG: {
569     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
570     OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
571                                              ArgInfo));
572     return;
573   }
574   case IIT_TRUNC_ARG: {
575     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
576     OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
577                                              ArgInfo));
578     return;
579   }
580   case IIT_HALF_VEC_ARG: {
581     unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
582     OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
583                                              ArgInfo));
584     return;
585   }
586   case IIT_EMPTYSTRUCT:
587     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
588     return;
589   case IIT_STRUCT5: ++StructElts; // FALL THROUGH.
590   case IIT_STRUCT4: ++StructElts; // FALL THROUGH.
591   case IIT_STRUCT3: ++StructElts; // FALL THROUGH.
592   case IIT_STRUCT2: {
593     OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
594 
595     for (unsigned i = 0; i != StructElts; ++i)
596       DecodeIITType(NextElt, Infos, OutputTable);
597     return;
598   }
599   }
600   llvm_unreachable("unhandled");
601 }
602 
603 
604 #define GET_INTRINSIC_GENERATOR_GLOBAL
605 #include "llvm/IR/Intrinsics.gen"
606 #undef GET_INTRINSIC_GENERATOR_GLOBAL
607 
getIntrinsicInfoTableEntries(ID id,SmallVectorImpl<IITDescriptor> & T)608 void Intrinsic::getIntrinsicInfoTableEntries(ID id,
609                                              SmallVectorImpl<IITDescriptor> &T){
610   // Check to see if the intrinsic's type was expressible by the table.
611   unsigned TableVal = IIT_Table[id-1];
612 
613   // Decode the TableVal into an array of IITValues.
614   SmallVector<unsigned char, 8> IITValues;
615   ArrayRef<unsigned char> IITEntries;
616   unsigned NextElt = 0;
617   if ((TableVal >> 31) != 0) {
618     // This is an offset into the IIT_LongEncodingTable.
619     IITEntries = IIT_LongEncodingTable;
620 
621     // Strip sentinel bit.
622     NextElt = (TableVal << 1) >> 1;
623   } else {
624     // Decode the TableVal into an array of IITValues.  If the entry was encoded
625     // into a single word in the table itself, decode it now.
626     do {
627       IITValues.push_back(TableVal & 0xF);
628       TableVal >>= 4;
629     } while (TableVal);
630 
631     IITEntries = IITValues;
632     NextElt = 0;
633   }
634 
635   // Okay, decode the table into the output vector of IITDescriptors.
636   DecodeIITType(NextElt, IITEntries, T);
637   while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
638     DecodeIITType(NextElt, IITEntries, T);
639 }
640 
641 
DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> & Infos,ArrayRef<Type * > Tys,LLVMContext & Context)642 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
643                              ArrayRef<Type*> Tys, LLVMContext &Context) {
644   using namespace Intrinsic;
645   IITDescriptor D = Infos.front();
646   Infos = Infos.slice(1);
647 
648   switch (D.Kind) {
649   case IITDescriptor::Void: return Type::getVoidTy(Context);
650   case IITDescriptor::VarArg: return Type::getVoidTy(Context);
651   case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
652   case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
653   case IITDescriptor::Half: return Type::getHalfTy(Context);
654   case IITDescriptor::Float: return Type::getFloatTy(Context);
655   case IITDescriptor::Double: return Type::getDoubleTy(Context);
656 
657   case IITDescriptor::Integer:
658     return IntegerType::get(Context, D.Integer_Width);
659   case IITDescriptor::Vector:
660     return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
661   case IITDescriptor::Pointer:
662     return PointerType::get(DecodeFixedType(Infos, Tys, Context),
663                             D.Pointer_AddressSpace);
664   case IITDescriptor::Struct: {
665     Type *Elts[5];
666     assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
667     for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
668       Elts[i] = DecodeFixedType(Infos, Tys, Context);
669     return StructType::get(Context, ArrayRef<Type*>(Elts,D.Struct_NumElements));
670   }
671 
672   case IITDescriptor::Argument:
673     return Tys[D.getArgumentNumber()];
674   case IITDescriptor::ExtendArgument: {
675     Type *Ty = Tys[D.getArgumentNumber()];
676     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
677       return VectorType::getExtendedElementVectorType(VTy);
678 
679     return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
680   }
681   case IITDescriptor::TruncArgument: {
682     Type *Ty = Tys[D.getArgumentNumber()];
683     if (VectorType *VTy = dyn_cast<VectorType>(Ty))
684       return VectorType::getTruncatedElementVectorType(VTy);
685 
686     IntegerType *ITy = cast<IntegerType>(Ty);
687     assert(ITy->getBitWidth() % 2 == 0);
688     return IntegerType::get(Context, ITy->getBitWidth() / 2);
689   }
690   case IITDescriptor::HalfVecArgument:
691     return VectorType::getHalfElementsVectorType(cast<VectorType>(
692                                                   Tys[D.getArgumentNumber()]));
693   }
694   llvm_unreachable("unhandled");
695 }
696 
697 
698 
getType(LLVMContext & Context,ID id,ArrayRef<Type * > Tys)699 FunctionType *Intrinsic::getType(LLVMContext &Context,
700                                  ID id, ArrayRef<Type*> Tys) {
701   SmallVector<IITDescriptor, 8> Table;
702   getIntrinsicInfoTableEntries(id, Table);
703 
704   ArrayRef<IITDescriptor> TableRef = Table;
705   Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
706 
707   SmallVector<Type*, 8> ArgTys;
708   while (!TableRef.empty())
709     ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
710 
711   return FunctionType::get(ResultTy, ArgTys, false);
712 }
713 
isOverloaded(ID id)714 bool Intrinsic::isOverloaded(ID id) {
715 #define GET_INTRINSIC_OVERLOAD_TABLE
716 #include "llvm/IR/Intrinsics.gen"
717 #undef GET_INTRINSIC_OVERLOAD_TABLE
718 }
719 
720 /// This defines the "Intrinsic::getAttributes(ID id)" method.
721 #define GET_INTRINSIC_ATTRIBUTES
722 #include "llvm/IR/Intrinsics.gen"
723 #undef GET_INTRINSIC_ATTRIBUTES
724 
getDeclaration(Module * M,ID id,ArrayRef<Type * > Tys)725 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
726   // There can never be multiple globals with the same name of different types,
727   // because intrinsics must be a specific type.
728   return
729     cast<Function>(M->getOrInsertFunction(getName(id, Tys),
730                                           getType(M->getContext(), id, Tys)));
731 }
732 
733 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
734 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
735 #include "llvm/IR/Intrinsics.gen"
736 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
737 
738 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
739 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
740 #include "llvm/IR/Intrinsics.gen"
741 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
742 
743 /// hasAddressTaken - returns true if there are any uses of this function
744 /// other than direct calls or invokes to it.
hasAddressTaken(const User ** PutOffender) const745 bool Function::hasAddressTaken(const User* *PutOffender) const {
746   for (const Use &U : uses()) {
747     const User *FU = U.getUser();
748     if (isa<BlockAddress>(FU))
749       continue;
750     if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
751       return PutOffender ? (*PutOffender = FU, true) : true;
752     ImmutableCallSite CS(cast<Instruction>(FU));
753     if (!CS.isCallee(&U))
754       return PutOffender ? (*PutOffender = FU, true) : true;
755   }
756   return false;
757 }
758 
isDefTriviallyDead() const759 bool Function::isDefTriviallyDead() const {
760   // Check the linkage
761   if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
762       !hasAvailableExternallyLinkage())
763     return false;
764 
765   // Check if the function is used by anything other than a blockaddress.
766   for (const User *U : users())
767     if (!isa<BlockAddress>(U))
768       return false;
769 
770   return true;
771 }
772 
773 /// callsFunctionThatReturnsTwice - Return true if the function has a call to
774 /// setjmp or other function that gcc recognizes as "returning twice".
callsFunctionThatReturnsTwice() const775 bool Function::callsFunctionThatReturnsTwice() const {
776   for (const_inst_iterator
777          I = inst_begin(this), E = inst_end(this); I != E; ++I) {
778     ImmutableCallSite CS(&*I);
779     if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
780       return true;
781   }
782 
783   return false;
784 }
785 
getPrefixData() const786 Constant *Function::getPrefixData() const {
787   assert(hasPrefixData());
788   const LLVMContextImpl::PrefixDataMapTy &PDMap =
789       getContext().pImpl->PrefixDataMap;
790   assert(PDMap.find(this) != PDMap.end());
791   return cast<Constant>(PDMap.find(this)->second->getReturnValue());
792 }
793 
setPrefixData(Constant * PrefixData)794 void Function::setPrefixData(Constant *PrefixData) {
795   if (!PrefixData && !hasPrefixData())
796     return;
797 
798   unsigned SCData = getSubclassDataFromValue();
799   LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
800   ReturnInst *&PDHolder = PDMap[this];
801   if (PrefixData) {
802     if (PDHolder)
803       PDHolder->setOperand(0, PrefixData);
804     else
805       PDHolder = ReturnInst::Create(getContext(), PrefixData);
806     SCData |= 2;
807   } else {
808     delete PDHolder;
809     PDMap.erase(this);
810     SCData &= ~2;
811   }
812   setValueSubclassData(SCData);
813 }
814