Function.cpp 32 KB

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