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