Function.cpp 35 KB

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