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