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