Function.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. //===- Function.cpp - Implement the Global object classes -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Function class for the IR library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Function.h"
  13. #include "SymbolTableListTraitsImpl.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/None.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringExtras.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/IR/Argument.h"
  23. #include "llvm/IR/Attributes.h"
  24. #include "llvm/IR/BasicBlock.h"
  25. #include "llvm/IR/Constant.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/GlobalValue.h"
  29. #include "llvm/IR/InstIterator.h"
  30. #include "llvm/IR/Instruction.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/Intrinsics.h"
  34. #include "llvm/IR/LLVMContext.h"
  35. #include "llvm/IR/MDBuilder.h"
  36. #include "llvm/IR/Metadata.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/IR/SymbolTableListTraits.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/IR/Use.h"
  41. #include "llvm/IR/User.h"
  42. #include "llvm/IR/Value.h"
  43. #include "llvm/IR/ValueSymbolTable.h"
  44. #include "llvm/Support/Casting.h"
  45. #include "llvm/Support/Compiler.h"
  46. #include "llvm/Support/ErrorHandling.h"
  47. #include <algorithm>
  48. #include <cassert>
  49. #include <cstddef>
  50. #include <cstdint>
  51. #include <cstring>
  52. #include <string>
  53. using namespace llvm;
  54. using ProfileCount = Function::ProfileCount;
  55. // Explicit instantiations of SymbolTableListTraits since some of the methods
  56. // are not in the public header file...
  57. template class llvm::SymbolTableListTraits<BasicBlock>;
  58. //===----------------------------------------------------------------------===//
  59. // Argument Implementation
  60. //===----------------------------------------------------------------------===//
  61. Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
  62. : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
  63. setName(Name);
  64. }
  65. void Argument::setParent(Function *parent) {
  66. Parent = parent;
  67. }
  68. bool Argument::hasNonNullAttr() const {
  69. if (!getType()->isPointerTy()) return false;
  70. if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull))
  71. return true;
  72. else if (getDereferenceableBytes() > 0 &&
  73. !NullPointerIsDefined(getParent(),
  74. getType()->getPointerAddressSpace()))
  75. return true;
  76. return false;
  77. }
  78. bool Argument::hasByValAttr() const {
  79. if (!getType()->isPointerTy()) return false;
  80. return hasAttribute(Attribute::ByVal);
  81. }
  82. bool Argument::hasSwiftSelfAttr() const {
  83. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
  84. }
  85. bool Argument::hasSwiftErrorAttr() const {
  86. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
  87. }
  88. bool Argument::hasInAllocaAttr() const {
  89. if (!getType()->isPointerTy()) return false;
  90. return hasAttribute(Attribute::InAlloca);
  91. }
  92. bool Argument::hasByValOrInAllocaAttr() const {
  93. if (!getType()->isPointerTy()) return false;
  94. AttributeList Attrs = getParent()->getAttributes();
  95. return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) ||
  96. Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca);
  97. }
  98. unsigned Argument::getParamAlignment() const {
  99. assert(getType()->isPointerTy() && "Only pointers have alignments");
  100. return getParent()->getParamAlignment(getArgNo());
  101. }
  102. Type *Argument::getParamByValType() const {
  103. assert(getType()->isPointerTy() && "Only pointers have byval types");
  104. return getParent()->getParamByValType(getArgNo());
  105. }
  106. uint64_t Argument::getDereferenceableBytes() const {
  107. assert(getType()->isPointerTy() &&
  108. "Only pointers have dereferenceable bytes");
  109. return getParent()->getParamDereferenceableBytes(getArgNo());
  110. }
  111. uint64_t Argument::getDereferenceableOrNullBytes() const {
  112. assert(getType()->isPointerTy() &&
  113. "Only pointers have dereferenceable bytes");
  114. return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
  115. }
  116. bool Argument::hasNestAttr() const {
  117. if (!getType()->isPointerTy()) return false;
  118. return hasAttribute(Attribute::Nest);
  119. }
  120. bool Argument::hasNoAliasAttr() const {
  121. if (!getType()->isPointerTy()) return false;
  122. return hasAttribute(Attribute::NoAlias);
  123. }
  124. bool Argument::hasNoCaptureAttr() const {
  125. if (!getType()->isPointerTy()) return false;
  126. return hasAttribute(Attribute::NoCapture);
  127. }
  128. bool Argument::hasStructRetAttr() const {
  129. if (!getType()->isPointerTy()) return false;
  130. return hasAttribute(Attribute::StructRet);
  131. }
  132. bool Argument::hasInRegAttr() const {
  133. return hasAttribute(Attribute::InReg);
  134. }
  135. bool Argument::hasReturnedAttr() const {
  136. return hasAttribute(Attribute::Returned);
  137. }
  138. bool Argument::hasZExtAttr() const {
  139. return hasAttribute(Attribute::ZExt);
  140. }
  141. bool Argument::hasSExtAttr() const {
  142. return hasAttribute(Attribute::SExt);
  143. }
  144. bool Argument::onlyReadsMemory() const {
  145. AttributeList Attrs = getParent()->getAttributes();
  146. return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) ||
  147. Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone);
  148. }
  149. void Argument::addAttrs(AttrBuilder &B) {
  150. AttributeList AL = getParent()->getAttributes();
  151. AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
  152. getParent()->setAttributes(AL);
  153. }
  154. void Argument::addAttr(Attribute::AttrKind Kind) {
  155. getParent()->addParamAttr(getArgNo(), Kind);
  156. }
  157. void Argument::addAttr(Attribute Attr) {
  158. getParent()->addParamAttr(getArgNo(), Attr);
  159. }
  160. void Argument::removeAttr(Attribute::AttrKind Kind) {
  161. getParent()->removeParamAttr(getArgNo(), Kind);
  162. }
  163. bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
  164. return getParent()->hasParamAttribute(getArgNo(), Kind);
  165. }
  166. Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
  167. return getParent()->getParamAttribute(getArgNo(), Kind);
  168. }
  169. //===----------------------------------------------------------------------===//
  170. // Helper Methods in Function
  171. //===----------------------------------------------------------------------===//
  172. LLVMContext &Function::getContext() const {
  173. return getType()->getContext();
  174. }
  175. unsigned Function::getInstructionCount() const {
  176. unsigned NumInstrs = 0;
  177. for (const BasicBlock &BB : BasicBlocks)
  178. NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
  179. BB.instructionsWithoutDebug().end());
  180. return NumInstrs;
  181. }
  182. Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
  183. const Twine &N, Module &M) {
  184. return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
  185. }
  186. void Function::removeFromParent() {
  187. getParent()->getFunctionList().remove(getIterator());
  188. }
  189. void Function::eraseFromParent() {
  190. getParent()->getFunctionList().erase(getIterator());
  191. }
  192. //===----------------------------------------------------------------------===//
  193. // Function Implementation
  194. //===----------------------------------------------------------------------===//
  195. static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
  196. // If AS == -1 and we are passed a valid module pointer we place the function
  197. // in the program address space. Otherwise we default to AS0.
  198. if (AddrSpace == static_cast<unsigned>(-1))
  199. return M ? M->getDataLayout().getProgramAddressSpace() : 0;
  200. return AddrSpace;
  201. }
  202. Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
  203. const Twine &name, Module *ParentModule)
  204. : GlobalObject(Ty, Value::FunctionVal,
  205. OperandTraits<Function>::op_begin(this), 0, Linkage, name,
  206. computeAddrSpace(AddrSpace, ParentModule)),
  207. NumArgs(Ty->getNumParams()) {
  208. assert(FunctionType::isValidReturnType(getReturnType()) &&
  209. "invalid return type");
  210. setGlobalObjectSubClassData(0);
  211. // We only need a symbol table for a function if the context keeps value names
  212. if (!getContext().shouldDiscardValueNames())
  213. SymTab = std::make_unique<ValueSymbolTable>();
  214. // If the function has arguments, mark them as lazily built.
  215. if (Ty->getNumParams())
  216. setValueSubclassData(1); // Set the "has lazy arguments" bit.
  217. if (ParentModule)
  218. ParentModule->getFunctionList().push_back(this);
  219. HasLLVMReservedName = getName().startswith("llvm.");
  220. // Ensure intrinsics have the right parameter attributes.
  221. // Note, the IntID field will have been set in Value::setName if this function
  222. // name is a valid intrinsic ID.
  223. if (IntID)
  224. setAttributes(Intrinsic::getAttributes(getContext(), IntID));
  225. }
  226. Function::~Function() {
  227. dropAllReferences(); // After this it is safe to delete instructions.
  228. // Delete all of the method arguments and unlink from symbol table...
  229. if (Arguments)
  230. clearArguments();
  231. // Remove the function from the on-the-side GC table.
  232. clearGC();
  233. }
  234. void Function::BuildLazyArguments() const {
  235. // Create the arguments vector, all arguments start out unnamed.
  236. auto *FT = getFunctionType();
  237. if (NumArgs > 0) {
  238. Arguments = std::allocator<Argument>().allocate(NumArgs);
  239. for (unsigned i = 0, e = NumArgs; i != e; ++i) {
  240. Type *ArgTy = FT->getParamType(i);
  241. assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
  242. new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
  243. }
  244. }
  245. // Clear the lazy arguments bit.
  246. unsigned SDC = getSubclassDataFromValue();
  247. const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
  248. assert(!hasLazyArguments());
  249. }
  250. static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
  251. return MutableArrayRef<Argument>(Args, Count);
  252. }
  253. void Function::clearArguments() {
  254. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  255. A.setName("");
  256. A.~Argument();
  257. }
  258. std::allocator<Argument>().deallocate(Arguments, NumArgs);
  259. Arguments = nullptr;
  260. }
  261. void Function::stealArgumentListFrom(Function &Src) {
  262. assert(isDeclaration() && "Expected no references to current arguments");
  263. // Drop the current arguments, if any, and set the lazy argument bit.
  264. if (!hasLazyArguments()) {
  265. assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
  266. [](const Argument &A) { return A.use_empty(); }) &&
  267. "Expected arguments to be unused in declaration");
  268. clearArguments();
  269. setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
  270. }
  271. // Nothing to steal if Src has lazy arguments.
  272. if (Src.hasLazyArguments())
  273. return;
  274. // Steal arguments from Src, and fix the lazy argument bits.
  275. assert(arg_size() == Src.arg_size());
  276. Arguments = Src.Arguments;
  277. Src.Arguments = nullptr;
  278. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  279. // FIXME: This does the work of transferNodesFromList inefficiently.
  280. SmallString<128> Name;
  281. if (A.hasName())
  282. Name = A.getName();
  283. if (!Name.empty())
  284. A.setName("");
  285. A.setParent(this);
  286. if (!Name.empty())
  287. A.setName(Name);
  288. }
  289. setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
  290. assert(!hasLazyArguments());
  291. Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
  292. }
  293. // dropAllReferences() - This function causes all the subinstructions to "let
  294. // go" of all references that they are maintaining. This allows one to
  295. // 'delete' a whole class at a time, even though there may be circular
  296. // references... first all references are dropped, and all use counts go to
  297. // zero. Then everything is deleted for real. Note that no operations are
  298. // valid on an object that has "dropped all references", except operator
  299. // delete.
  300. //
  301. void Function::dropAllReferences() {
  302. setIsMaterializable(false);
  303. for (BasicBlock &BB : *this)
  304. BB.dropAllReferences();
  305. // Delete all basic blocks. They are now unused, except possibly by
  306. // blockaddresses, but BasicBlock's destructor takes care of those.
  307. while (!BasicBlocks.empty())
  308. BasicBlocks.begin()->eraseFromParent();
  309. // Drop uses of any optional data (real or placeholder).
  310. if (getNumOperands()) {
  311. User::dropAllReferences();
  312. setNumHungOffUseOperands(0);
  313. setValueSubclassData(getSubclassDataFromValue() & ~0xe);
  314. }
  315. // Metadata is stored in a side-table.
  316. clearMetadata();
  317. }
  318. void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) {
  319. AttributeList PAL = getAttributes();
  320. PAL = PAL.addAttribute(getContext(), i, Kind);
  321. setAttributes(PAL);
  322. }
  323. void Function::addAttribute(unsigned i, Attribute Attr) {
  324. AttributeList PAL = getAttributes();
  325. PAL = PAL.addAttribute(getContext(), i, Attr);
  326. setAttributes(PAL);
  327. }
  328. void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) {
  329. AttributeList PAL = getAttributes();
  330. PAL = PAL.addAttributes(getContext(), i, Attrs);
  331. setAttributes(PAL);
  332. }
  333. void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
  334. AttributeList PAL = getAttributes();
  335. PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind);
  336. setAttributes(PAL);
  337. }
  338. void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
  339. AttributeList PAL = getAttributes();
  340. PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr);
  341. setAttributes(PAL);
  342. }
  343. void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
  344. AttributeList PAL = getAttributes();
  345. PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs);
  346. setAttributes(PAL);
  347. }
  348. void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
  349. AttributeList PAL = getAttributes();
  350. PAL = PAL.removeAttribute(getContext(), i, Kind);
  351. setAttributes(PAL);
  352. }
  353. void Function::removeAttribute(unsigned i, StringRef Kind) {
  354. AttributeList PAL = getAttributes();
  355. PAL = PAL.removeAttribute(getContext(), i, Kind);
  356. setAttributes(PAL);
  357. }
  358. void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) {
  359. AttributeList PAL = getAttributes();
  360. PAL = PAL.removeAttributes(getContext(), i, Attrs);
  361. setAttributes(PAL);
  362. }
  363. void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
  364. AttributeList PAL = getAttributes();
  365. PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
  366. setAttributes(PAL);
  367. }
  368. void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
  369. AttributeList PAL = getAttributes();
  370. PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind);
  371. setAttributes(PAL);
  372. }
  373. void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
  374. AttributeList PAL = getAttributes();
  375. PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs);
  376. setAttributes(PAL);
  377. }
  378. void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
  379. AttributeList PAL = getAttributes();
  380. PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
  381. setAttributes(PAL);
  382. }
  383. void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
  384. AttributeList PAL = getAttributes();
  385. PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
  386. setAttributes(PAL);
  387. }
  388. void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
  389. AttributeList PAL = getAttributes();
  390. PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
  391. setAttributes(PAL);
  392. }
  393. void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
  394. uint64_t Bytes) {
  395. AttributeList PAL = getAttributes();
  396. PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes);
  397. setAttributes(PAL);
  398. }
  399. const std::string &Function::getGC() const {
  400. assert(hasGC() && "Function has no collector");
  401. return getContext().getGC(*this);
  402. }
  403. void Function::setGC(std::string Str) {
  404. setValueSubclassDataBit(14, !Str.empty());
  405. getContext().setGC(*this, std::move(Str));
  406. }
  407. void Function::clearGC() {
  408. if (!hasGC())
  409. return;
  410. getContext().deleteGC(*this);
  411. setValueSubclassDataBit(14, false);
  412. }
  413. /// Copy all additional attributes (those not needed to create a Function) from
  414. /// the Function Src to this one.
  415. void Function::copyAttributesFrom(const Function *Src) {
  416. GlobalObject::copyAttributesFrom(Src);
  417. setCallingConv(Src->getCallingConv());
  418. setAttributes(Src->getAttributes());
  419. if (Src->hasGC())
  420. setGC(Src->getGC());
  421. else
  422. clearGC();
  423. if (Src->hasPersonalityFn())
  424. setPersonalityFn(Src->getPersonalityFn());
  425. if (Src->hasPrefixData())
  426. setPrefixData(Src->getPrefixData());
  427. if (Src->hasPrologueData())
  428. setPrologueData(Src->getPrologueData());
  429. }
  430. /// Table of string intrinsic names indexed by enum value.
  431. static const char * const IntrinsicNameTable[] = {
  432. "not_intrinsic",
  433. #define GET_INTRINSIC_NAME_TABLE
  434. #include "llvm/IR/IntrinsicImpl.inc"
  435. #undef GET_INTRINSIC_NAME_TABLE
  436. };
  437. /// Table of per-target intrinsic name tables.
  438. #define GET_INTRINSIC_TARGET_DATA
  439. #include "llvm/IR/IntrinsicImpl.inc"
  440. #undef GET_INTRINSIC_TARGET_DATA
  441. /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
  442. /// target as \c Name, or the generic table if \c Name is not target specific.
  443. ///
  444. /// Returns the relevant slice of \c IntrinsicNameTable
  445. static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
  446. assert(Name.startswith("llvm."));
  447. ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
  448. // Drop "llvm." and take the first dotted component. That will be the target
  449. // if this is target specific.
  450. StringRef Target = Name.drop_front(5).split('.').first;
  451. auto It = partition_point(
  452. Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
  453. // We've either found the target or just fall back to the generic set, which
  454. // is always first.
  455. const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
  456. return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
  457. }
  458. /// This does the actual lookup of an intrinsic ID which
  459. /// matches the given function name.
  460. Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
  461. ArrayRef<const char *> NameTable = findTargetSubtable(Name);
  462. int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
  463. if (Idx == -1)
  464. return Intrinsic::not_intrinsic;
  465. // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
  466. // an index into a sub-table.
  467. int Adjust = NameTable.data() - IntrinsicNameTable;
  468. Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
  469. // If the intrinsic is not overloaded, require an exact match. If it is
  470. // overloaded, require either exact or prefix match.
  471. const auto MatchSize = strlen(NameTable[Idx]);
  472. assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
  473. bool IsExactMatch = Name.size() == MatchSize;
  474. return IsExactMatch || isOverloaded(ID) ? ID : Intrinsic::not_intrinsic;
  475. }
  476. void Function::recalculateIntrinsicID() {
  477. StringRef Name = getName();
  478. if (!Name.startswith("llvm.")) {
  479. HasLLVMReservedName = false;
  480. IntID = Intrinsic::not_intrinsic;
  481. return;
  482. }
  483. HasLLVMReservedName = true;
  484. IntID = lookupIntrinsicID(Name);
  485. }
  486. /// Returns a stable mangling for the type specified for use in the name
  487. /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
  488. /// of named types is simply their name. Manglings for unnamed types consist
  489. /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
  490. /// combined with the mangling of their component types. A vararg function
  491. /// type will have a suffix of 'vararg'. Since function types can contain
  492. /// other function types, we close a function type mangling with suffix 'f'
  493. /// which can't be confused with it's prefix. This ensures we don't have
  494. /// collisions between two unrelated function types. Otherwise, you might
  495. /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
  496. ///
  497. static std::string getMangledTypeStr(Type* Ty) {
  498. std::string Result;
  499. if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
  500. Result += "p" + utostr(PTyp->getAddressSpace()) +
  501. getMangledTypeStr(PTyp->getElementType());
  502. } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
  503. Result += "a" + utostr(ATyp->getNumElements()) +
  504. getMangledTypeStr(ATyp->getElementType());
  505. } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
  506. if (!STyp->isLiteral()) {
  507. Result += "s_";
  508. Result += STyp->getName();
  509. } else {
  510. Result += "sl_";
  511. for (auto Elem : STyp->elements())
  512. Result += getMangledTypeStr(Elem);
  513. }
  514. // Ensure nested structs are distinguishable.
  515. Result += "s";
  516. } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
  517. Result += "f_" + getMangledTypeStr(FT->getReturnType());
  518. for (size_t i = 0; i < FT->getNumParams(); i++)
  519. Result += getMangledTypeStr(FT->getParamType(i));
  520. if (FT->isVarArg())
  521. Result += "vararg";
  522. // Ensure nested function types are distinguishable.
  523. Result += "f";
  524. } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) {
  525. if (VTy->isScalable())
  526. Result += "nx";
  527. Result += "v" + utostr(VTy->getVectorNumElements()) +
  528. getMangledTypeStr(VTy->getVectorElementType());
  529. } else if (Ty) {
  530. switch (Ty->getTypeID()) {
  531. default: llvm_unreachable("Unhandled type");
  532. case Type::VoidTyID: Result += "isVoid"; break;
  533. case Type::MetadataTyID: Result += "Metadata"; break;
  534. case Type::HalfTyID: Result += "f16"; break;
  535. case Type::FloatTyID: Result += "f32"; break;
  536. case Type::DoubleTyID: Result += "f64"; break;
  537. case Type::X86_FP80TyID: Result += "f80"; break;
  538. case Type::FP128TyID: Result += "f128"; break;
  539. case Type::PPC_FP128TyID: Result += "ppcf128"; break;
  540. case Type::X86_MMXTyID: Result += "x86mmx"; break;
  541. case Type::IntegerTyID:
  542. Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
  543. break;
  544. }
  545. }
  546. return Result;
  547. }
  548. StringRef Intrinsic::getName(ID id) {
  549. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  550. assert(!isOverloaded(id) &&
  551. "This version of getName does not support overloading");
  552. return IntrinsicNameTable[id];
  553. }
  554. std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
  555. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  556. std::string Result(IntrinsicNameTable[id]);
  557. for (Type *Ty : Tys) {
  558. Result += "." + getMangledTypeStr(Ty);
  559. }
  560. return Result;
  561. }
  562. /// IIT_Info - These are enumerators that describe the entries returned by the
  563. /// getIntrinsicInfoTableEntries function.
  564. ///
  565. /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
  566. enum IIT_Info {
  567. // Common values should be encoded with 0-15.
  568. IIT_Done = 0,
  569. IIT_I1 = 1,
  570. IIT_I8 = 2,
  571. IIT_I16 = 3,
  572. IIT_I32 = 4,
  573. IIT_I64 = 5,
  574. IIT_F16 = 6,
  575. IIT_F32 = 7,
  576. IIT_F64 = 8,
  577. IIT_V2 = 9,
  578. IIT_V4 = 10,
  579. IIT_V8 = 11,
  580. IIT_V16 = 12,
  581. IIT_V32 = 13,
  582. IIT_PTR = 14,
  583. IIT_ARG = 15,
  584. // Values from 16+ are only encodable with the inefficient encoding.
  585. IIT_V64 = 16,
  586. IIT_MMX = 17,
  587. IIT_TOKEN = 18,
  588. IIT_METADATA = 19,
  589. IIT_EMPTYSTRUCT = 20,
  590. IIT_STRUCT2 = 21,
  591. IIT_STRUCT3 = 22,
  592. IIT_STRUCT4 = 23,
  593. IIT_STRUCT5 = 24,
  594. IIT_EXTEND_ARG = 25,
  595. IIT_TRUNC_ARG = 26,
  596. IIT_ANYPTR = 27,
  597. IIT_V1 = 28,
  598. IIT_VARARG = 29,
  599. IIT_HALF_VEC_ARG = 30,
  600. IIT_SAME_VEC_WIDTH_ARG = 31,
  601. IIT_PTR_TO_ARG = 32,
  602. IIT_PTR_TO_ELT = 33,
  603. IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
  604. IIT_I128 = 35,
  605. IIT_V512 = 36,
  606. IIT_V1024 = 37,
  607. IIT_STRUCT6 = 38,
  608. IIT_STRUCT7 = 39,
  609. IIT_STRUCT8 = 40,
  610. IIT_F128 = 41,
  611. IIT_VEC_ELEMENT = 42,
  612. IIT_SCALABLE_VEC = 43
  613. };
  614. static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
  615. SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
  616. using namespace Intrinsic;
  617. IIT_Info Info = IIT_Info(Infos[NextElt++]);
  618. unsigned StructElts = 2;
  619. switch (Info) {
  620. case IIT_Done:
  621. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
  622. return;
  623. case IIT_VARARG:
  624. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
  625. return;
  626. case IIT_MMX:
  627. OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
  628. return;
  629. case IIT_TOKEN:
  630. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
  631. return;
  632. case IIT_METADATA:
  633. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
  634. return;
  635. case IIT_F16:
  636. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
  637. return;
  638. case IIT_F32:
  639. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
  640. return;
  641. case IIT_F64:
  642. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
  643. return;
  644. case IIT_F128:
  645. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
  646. return;
  647. case IIT_I1:
  648. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
  649. return;
  650. case IIT_I8:
  651. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  652. return;
  653. case IIT_I16:
  654. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
  655. return;
  656. case IIT_I32:
  657. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
  658. return;
  659. case IIT_I64:
  660. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
  661. return;
  662. case IIT_I128:
  663. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
  664. return;
  665. case IIT_V1:
  666. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
  667. DecodeIITType(NextElt, Infos, OutputTable);
  668. return;
  669. case IIT_V2:
  670. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
  671. DecodeIITType(NextElt, Infos, OutputTable);
  672. return;
  673. case IIT_V4:
  674. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
  675. DecodeIITType(NextElt, Infos, OutputTable);
  676. return;
  677. case IIT_V8:
  678. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
  679. DecodeIITType(NextElt, Infos, OutputTable);
  680. return;
  681. case IIT_V16:
  682. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
  683. DecodeIITType(NextElt, Infos, OutputTable);
  684. return;
  685. case IIT_V32:
  686. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
  687. DecodeIITType(NextElt, Infos, OutputTable);
  688. return;
  689. case IIT_V64:
  690. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
  691. DecodeIITType(NextElt, Infos, OutputTable);
  692. return;
  693. case IIT_V512:
  694. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512));
  695. DecodeIITType(NextElt, Infos, OutputTable);
  696. return;
  697. case IIT_V1024:
  698. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024));
  699. DecodeIITType(NextElt, Infos, OutputTable);
  700. return;
  701. case IIT_PTR:
  702. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
  703. DecodeIITType(NextElt, Infos, OutputTable);
  704. return;
  705. case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
  706. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
  707. Infos[NextElt++]));
  708. DecodeIITType(NextElt, Infos, OutputTable);
  709. return;
  710. }
  711. case IIT_ARG: {
  712. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  713. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
  714. return;
  715. }
  716. case IIT_EXTEND_ARG: {
  717. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  718. OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
  719. ArgInfo));
  720. return;
  721. }
  722. case IIT_TRUNC_ARG: {
  723. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  724. OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
  725. ArgInfo));
  726. return;
  727. }
  728. case IIT_HALF_VEC_ARG: {
  729. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  730. OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
  731. ArgInfo));
  732. return;
  733. }
  734. case IIT_SAME_VEC_WIDTH_ARG: {
  735. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  736. OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
  737. ArgInfo));
  738. return;
  739. }
  740. case IIT_PTR_TO_ARG: {
  741. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  742. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
  743. ArgInfo));
  744. return;
  745. }
  746. case IIT_PTR_TO_ELT: {
  747. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  748. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
  749. return;
  750. }
  751. case IIT_VEC_OF_ANYPTRS_TO_ELT: {
  752. unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  753. unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  754. OutputTable.push_back(
  755. IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
  756. return;
  757. }
  758. case IIT_EMPTYSTRUCT:
  759. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  760. return;
  761. case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH;
  762. case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH;
  763. case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH;
  764. case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH;
  765. case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH;
  766. case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH;
  767. case IIT_STRUCT2: {
  768. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
  769. for (unsigned i = 0; i != StructElts; ++i)
  770. DecodeIITType(NextElt, Infos, OutputTable);
  771. return;
  772. }
  773. case IIT_VEC_ELEMENT: {
  774. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  775. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
  776. ArgInfo));
  777. return;
  778. }
  779. case IIT_SCALABLE_VEC: {
  780. OutputTable.push_back(IITDescriptor::get(IITDescriptor::ScalableVecArgument,
  781. 0));
  782. DecodeIITType(NextElt, Infos, OutputTable);
  783. return;
  784. }
  785. }
  786. llvm_unreachable("unhandled");
  787. }
  788. #define GET_INTRINSIC_GENERATOR_GLOBAL
  789. #include "llvm/IR/IntrinsicImpl.inc"
  790. #undef GET_INTRINSIC_GENERATOR_GLOBAL
  791. void Intrinsic::getIntrinsicInfoTableEntries(ID id,
  792. SmallVectorImpl<IITDescriptor> &T){
  793. // Check to see if the intrinsic's type was expressible by the table.
  794. unsigned TableVal = IIT_Table[id-1];
  795. // Decode the TableVal into an array of IITValues.
  796. SmallVector<unsigned char, 8> IITValues;
  797. ArrayRef<unsigned char> IITEntries;
  798. unsigned NextElt = 0;
  799. if ((TableVal >> 31) != 0) {
  800. // This is an offset into the IIT_LongEncodingTable.
  801. IITEntries = IIT_LongEncodingTable;
  802. // Strip sentinel bit.
  803. NextElt = (TableVal << 1) >> 1;
  804. } else {
  805. // Decode the TableVal into an array of IITValues. If the entry was encoded
  806. // into a single word in the table itself, decode it now.
  807. do {
  808. IITValues.push_back(TableVal & 0xF);
  809. TableVal >>= 4;
  810. } while (TableVal);
  811. IITEntries = IITValues;
  812. NextElt = 0;
  813. }
  814. // Okay, decode the table into the output vector of IITDescriptors.
  815. DecodeIITType(NextElt, IITEntries, T);
  816. while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
  817. DecodeIITType(NextElt, IITEntries, T);
  818. }
  819. static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
  820. ArrayRef<Type*> Tys, LLVMContext &Context) {
  821. using namespace Intrinsic;
  822. IITDescriptor D = Infos.front();
  823. Infos = Infos.slice(1);
  824. switch (D.Kind) {
  825. case IITDescriptor::Void: return Type::getVoidTy(Context);
  826. case IITDescriptor::VarArg: return Type::getVoidTy(Context);
  827. case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
  828. case IITDescriptor::Token: return Type::getTokenTy(Context);
  829. case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
  830. case IITDescriptor::Half: return Type::getHalfTy(Context);
  831. case IITDescriptor::Float: return Type::getFloatTy(Context);
  832. case IITDescriptor::Double: return Type::getDoubleTy(Context);
  833. case IITDescriptor::Quad: return Type::getFP128Ty(Context);
  834. case IITDescriptor::Integer:
  835. return IntegerType::get(Context, D.Integer_Width);
  836. case IITDescriptor::Vector:
  837. return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
  838. case IITDescriptor::Pointer:
  839. return PointerType::get(DecodeFixedType(Infos, Tys, Context),
  840. D.Pointer_AddressSpace);
  841. case IITDescriptor::Struct: {
  842. SmallVector<Type *, 8> Elts;
  843. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  844. Elts.push_back(DecodeFixedType(Infos, Tys, Context));
  845. return StructType::get(Context, Elts);
  846. }
  847. case IITDescriptor::Argument:
  848. return Tys[D.getArgumentNumber()];
  849. case IITDescriptor::ExtendArgument: {
  850. Type *Ty = Tys[D.getArgumentNumber()];
  851. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  852. return VectorType::getExtendedElementVectorType(VTy);
  853. return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
  854. }
  855. case IITDescriptor::TruncArgument: {
  856. Type *Ty = Tys[D.getArgumentNumber()];
  857. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  858. return VectorType::getTruncatedElementVectorType(VTy);
  859. IntegerType *ITy = cast<IntegerType>(Ty);
  860. assert(ITy->getBitWidth() % 2 == 0);
  861. return IntegerType::get(Context, ITy->getBitWidth() / 2);
  862. }
  863. case IITDescriptor::HalfVecArgument:
  864. return VectorType::getHalfElementsVectorType(cast<VectorType>(
  865. Tys[D.getArgumentNumber()]));
  866. case IITDescriptor::SameVecWidthArgument: {
  867. Type *EltTy = DecodeFixedType(Infos, Tys, Context);
  868. Type *Ty = Tys[D.getArgumentNumber()];
  869. if (auto *VTy = dyn_cast<VectorType>(Ty))
  870. return VectorType::get(EltTy, VTy->getElementCount());
  871. return EltTy;
  872. }
  873. case IITDescriptor::PtrToArgument: {
  874. Type *Ty = Tys[D.getArgumentNumber()];
  875. return PointerType::getUnqual(Ty);
  876. }
  877. case IITDescriptor::PtrToElt: {
  878. Type *Ty = Tys[D.getArgumentNumber()];
  879. VectorType *VTy = dyn_cast<VectorType>(Ty);
  880. if (!VTy)
  881. llvm_unreachable("Expected an argument of Vector Type");
  882. Type *EltTy = VTy->getVectorElementType();
  883. return PointerType::getUnqual(EltTy);
  884. }
  885. case IITDescriptor::VecElementArgument: {
  886. Type *Ty = Tys[D.getArgumentNumber()];
  887. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  888. return VTy->getElementType();
  889. llvm_unreachable("Expected an argument of Vector Type");
  890. }
  891. case IITDescriptor::VecOfAnyPtrsToElt:
  892. // Return the overloaded type (which determines the pointers address space)
  893. return Tys[D.getOverloadArgNumber()];
  894. case IITDescriptor::ScalableVecArgument: {
  895. Type *Ty = DecodeFixedType(Infos, Tys, Context);
  896. return VectorType::get(Ty->getVectorElementType(),
  897. { Ty->getVectorNumElements(), true });
  898. }
  899. }
  900. llvm_unreachable("unhandled");
  901. }
  902. FunctionType *Intrinsic::getType(LLVMContext &Context,
  903. ID id, ArrayRef<Type*> Tys) {
  904. SmallVector<IITDescriptor, 8> Table;
  905. getIntrinsicInfoTableEntries(id, Table);
  906. ArrayRef<IITDescriptor> TableRef = Table;
  907. Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
  908. SmallVector<Type*, 8> ArgTys;
  909. while (!TableRef.empty())
  910. ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
  911. // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
  912. // If we see void type as the type of the last argument, it is vararg intrinsic
  913. if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
  914. ArgTys.pop_back();
  915. return FunctionType::get(ResultTy, ArgTys, true);
  916. }
  917. return FunctionType::get(ResultTy, ArgTys, false);
  918. }
  919. bool Intrinsic::isOverloaded(ID id) {
  920. #define GET_INTRINSIC_OVERLOAD_TABLE
  921. #include "llvm/IR/IntrinsicImpl.inc"
  922. #undef GET_INTRINSIC_OVERLOAD_TABLE
  923. }
  924. bool Intrinsic::isLeaf(ID id) {
  925. switch (id) {
  926. default:
  927. return true;
  928. case Intrinsic::experimental_gc_statepoint:
  929. case Intrinsic::experimental_patchpoint_void:
  930. case Intrinsic::experimental_patchpoint_i64:
  931. return false;
  932. }
  933. }
  934. /// This defines the "Intrinsic::getAttributes(ID id)" method.
  935. #define GET_INTRINSIC_ATTRIBUTES
  936. #include "llvm/IR/IntrinsicImpl.inc"
  937. #undef GET_INTRINSIC_ATTRIBUTES
  938. Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
  939. // There can never be multiple globals with the same name of different types,
  940. // because intrinsics must be a specific type.
  941. return cast<Function>(
  942. M->getOrInsertFunction(getName(id, Tys),
  943. getType(M->getContext(), id, Tys))
  944. .getCallee());
  945. }
  946. // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
  947. #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  948. #include "llvm/IR/IntrinsicImpl.inc"
  949. #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
  950. // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
  951. #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  952. #include "llvm/IR/IntrinsicImpl.inc"
  953. #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  954. using DeferredIntrinsicMatchPair =
  955. std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
  956. static bool matchIntrinsicType(
  957. Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
  958. SmallVectorImpl<Type *> &ArgTys,
  959. SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
  960. bool IsDeferredCheck) {
  961. using namespace Intrinsic;
  962. // If we ran out of descriptors, there are too many arguments.
  963. if (Infos.empty()) return true;
  964. // Do this before slicing off the 'front' part
  965. auto InfosRef = Infos;
  966. auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
  967. DeferredChecks.emplace_back(T, InfosRef);
  968. return false;
  969. };
  970. IITDescriptor D = Infos.front();
  971. Infos = Infos.slice(1);
  972. switch (D.Kind) {
  973. case IITDescriptor::Void: return !Ty->isVoidTy();
  974. case IITDescriptor::VarArg: return true;
  975. case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
  976. case IITDescriptor::Token: return !Ty->isTokenTy();
  977. case IITDescriptor::Metadata: return !Ty->isMetadataTy();
  978. case IITDescriptor::Half: return !Ty->isHalfTy();
  979. case IITDescriptor::Float: return !Ty->isFloatTy();
  980. case IITDescriptor::Double: return !Ty->isDoubleTy();
  981. case IITDescriptor::Quad: return !Ty->isFP128Ty();
  982. case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
  983. case IITDescriptor::Vector: {
  984. VectorType *VT = dyn_cast<VectorType>(Ty);
  985. return !VT || VT->getNumElements() != D.Vector_Width ||
  986. matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
  987. DeferredChecks, IsDeferredCheck);
  988. }
  989. case IITDescriptor::Pointer: {
  990. PointerType *PT = dyn_cast<PointerType>(Ty);
  991. return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace ||
  992. matchIntrinsicType(PT->getElementType(), Infos, ArgTys,
  993. DeferredChecks, IsDeferredCheck);
  994. }
  995. case IITDescriptor::Struct: {
  996. StructType *ST = dyn_cast<StructType>(Ty);
  997. if (!ST || ST->getNumElements() != D.Struct_NumElements)
  998. return true;
  999. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  1000. if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
  1001. DeferredChecks, IsDeferredCheck))
  1002. return true;
  1003. return false;
  1004. }
  1005. case IITDescriptor::Argument:
  1006. // If this is the second occurrence of an argument,
  1007. // verify that the later instance matches the previous instance.
  1008. if (D.getArgumentNumber() < ArgTys.size())
  1009. return Ty != ArgTys[D.getArgumentNumber()];
  1010. if (D.getArgumentNumber() > ArgTys.size() ||
  1011. D.getArgumentKind() == IITDescriptor::AK_MatchType)
  1012. return IsDeferredCheck || DeferCheck(Ty);
  1013. assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
  1014. "Table consistency error");
  1015. ArgTys.push_back(Ty);
  1016. switch (D.getArgumentKind()) {
  1017. case IITDescriptor::AK_Any: return false; // Success
  1018. case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
  1019. case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
  1020. case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
  1021. case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
  1022. default: break;
  1023. }
  1024. llvm_unreachable("all argument kinds not covered");
  1025. case IITDescriptor::ExtendArgument: {
  1026. // If this is a forward reference, defer the check for later.
  1027. if (D.getArgumentNumber() >= ArgTys.size())
  1028. return IsDeferredCheck || DeferCheck(Ty);
  1029. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1030. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  1031. NewTy = VectorType::getExtendedElementVectorType(VTy);
  1032. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  1033. NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
  1034. else
  1035. return true;
  1036. return Ty != NewTy;
  1037. }
  1038. case IITDescriptor::TruncArgument: {
  1039. // If this is a forward reference, defer the check for later.
  1040. if (D.getArgumentNumber() >= ArgTys.size())
  1041. return IsDeferredCheck || DeferCheck(Ty);
  1042. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1043. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  1044. NewTy = VectorType::getTruncatedElementVectorType(VTy);
  1045. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  1046. NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
  1047. else
  1048. return true;
  1049. return Ty != NewTy;
  1050. }
  1051. case IITDescriptor::HalfVecArgument:
  1052. // If this is a forward reference, defer the check for later.
  1053. return D.getArgumentNumber() >= ArgTys.size() ||
  1054. !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
  1055. VectorType::getHalfElementsVectorType(
  1056. cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
  1057. case IITDescriptor::SameVecWidthArgument: {
  1058. if (D.getArgumentNumber() >= ArgTys.size()) {
  1059. // Defer check and subsequent check for the vector element type.
  1060. Infos = Infos.slice(1);
  1061. return IsDeferredCheck || DeferCheck(Ty);
  1062. }
  1063. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1064. auto *ThisArgType = dyn_cast<VectorType>(Ty);
  1065. // Both must be vectors of the same number of elements or neither.
  1066. if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
  1067. return true;
  1068. Type *EltTy = Ty;
  1069. if (ThisArgType) {
  1070. if (ReferenceType->getElementCount() !=
  1071. ThisArgType->getElementCount())
  1072. return true;
  1073. EltTy = ThisArgType->getVectorElementType();
  1074. }
  1075. return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
  1076. IsDeferredCheck);
  1077. }
  1078. case IITDescriptor::PtrToArgument: {
  1079. if (D.getArgumentNumber() >= ArgTys.size())
  1080. return IsDeferredCheck || DeferCheck(Ty);
  1081. Type * ReferenceType = ArgTys[D.getArgumentNumber()];
  1082. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  1083. return (!ThisArgType || ThisArgType->getElementType() != ReferenceType);
  1084. }
  1085. case IITDescriptor::PtrToElt: {
  1086. if (D.getArgumentNumber() >= ArgTys.size())
  1087. return IsDeferredCheck || DeferCheck(Ty);
  1088. VectorType * ReferenceType =
  1089. dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
  1090. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  1091. return (!ThisArgType || !ReferenceType ||
  1092. ThisArgType->getElementType() != ReferenceType->getElementType());
  1093. }
  1094. case IITDescriptor::VecOfAnyPtrsToElt: {
  1095. unsigned RefArgNumber = D.getRefArgNumber();
  1096. if (RefArgNumber >= ArgTys.size()) {
  1097. if (IsDeferredCheck)
  1098. return true;
  1099. // If forward referencing, already add the pointer-vector type and
  1100. // defer the checks for later.
  1101. ArgTys.push_back(Ty);
  1102. return DeferCheck(Ty);
  1103. }
  1104. if (!IsDeferredCheck){
  1105. assert(D.getOverloadArgNumber() == ArgTys.size() &&
  1106. "Table consistency error");
  1107. ArgTys.push_back(Ty);
  1108. }
  1109. // Verify the overloaded type "matches" the Ref type.
  1110. // i.e. Ty is a vector with the same width as Ref.
  1111. // Composed of pointers to the same element type as Ref.
  1112. VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
  1113. VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty);
  1114. if (!ThisArgVecTy || !ReferenceType ||
  1115. (ReferenceType->getVectorNumElements() !=
  1116. ThisArgVecTy->getVectorNumElements()))
  1117. return true;
  1118. PointerType *ThisArgEltTy =
  1119. dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType());
  1120. if (!ThisArgEltTy)
  1121. return true;
  1122. return ThisArgEltTy->getElementType() !=
  1123. ReferenceType->getVectorElementType();
  1124. }
  1125. case IITDescriptor::VecElementArgument: {
  1126. if (D.getArgumentNumber() >= ArgTys.size())
  1127. return IsDeferredCheck ? true : DeferCheck(Ty);
  1128. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1129. return !ReferenceType || Ty != ReferenceType->getElementType();
  1130. }
  1131. case IITDescriptor::ScalableVecArgument: {
  1132. VectorType *VTy = dyn_cast<VectorType>(Ty);
  1133. if (!VTy || !VTy->isScalable())
  1134. return true;
  1135. return matchIntrinsicType(VTy, Infos, ArgTys, DeferredChecks,
  1136. IsDeferredCheck);
  1137. }
  1138. }
  1139. llvm_unreachable("unhandled");
  1140. }
  1141. Intrinsic::MatchIntrinsicTypesResult
  1142. Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
  1143. ArrayRef<Intrinsic::IITDescriptor> &Infos,
  1144. SmallVectorImpl<Type *> &ArgTys) {
  1145. SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
  1146. if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
  1147. false))
  1148. return MatchIntrinsicTypes_NoMatchRet;
  1149. unsigned NumDeferredReturnChecks = DeferredChecks.size();
  1150. for (auto Ty : FTy->params())
  1151. if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
  1152. return MatchIntrinsicTypes_NoMatchArg;
  1153. for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
  1154. DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
  1155. if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
  1156. true))
  1157. return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
  1158. : MatchIntrinsicTypes_NoMatchArg;
  1159. }
  1160. return MatchIntrinsicTypes_Match;
  1161. }
  1162. bool
  1163. Intrinsic::matchIntrinsicVarArg(bool isVarArg,
  1164. ArrayRef<Intrinsic::IITDescriptor> &Infos) {
  1165. // If there are no descriptors left, then it can't be a vararg.
  1166. if (Infos.empty())
  1167. return isVarArg;
  1168. // There should be only one descriptor remaining at this point.
  1169. if (Infos.size() != 1)
  1170. return true;
  1171. // Check and verify the descriptor.
  1172. IITDescriptor D = Infos.front();
  1173. Infos = Infos.slice(1);
  1174. if (D.Kind == IITDescriptor::VarArg)
  1175. return !isVarArg;
  1176. return true;
  1177. }
  1178. Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) {
  1179. Intrinsic::ID ID = F->getIntrinsicID();
  1180. if (!ID)
  1181. return None;
  1182. FunctionType *FTy = F->getFunctionType();
  1183. // Accumulate an array of overloaded types for the given intrinsic
  1184. SmallVector<Type *, 4> ArgTys;
  1185. {
  1186. SmallVector<Intrinsic::IITDescriptor, 8> Table;
  1187. getIntrinsicInfoTableEntries(ID, Table);
  1188. ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
  1189. if (Intrinsic::matchIntrinsicSignature(FTy, TableRef, ArgTys))
  1190. return None;
  1191. if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef))
  1192. return None;
  1193. }
  1194. StringRef Name = F->getName();
  1195. if (Name == Intrinsic::getName(ID, ArgTys))
  1196. return None;
  1197. auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
  1198. NewDecl->setCallingConv(F->getCallingConv());
  1199. assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature");
  1200. return NewDecl;
  1201. }
  1202. /// hasAddressTaken - returns true if there are any uses of this function
  1203. /// other than direct calls or invokes to it.
  1204. bool Function::hasAddressTaken(const User* *PutOffender) const {
  1205. for (const Use &U : uses()) {
  1206. const User *FU = U.getUser();
  1207. if (isa<BlockAddress>(FU))
  1208. continue;
  1209. const auto *Call = dyn_cast<CallBase>(FU);
  1210. if (!Call) {
  1211. if (PutOffender)
  1212. *PutOffender = FU;
  1213. return true;
  1214. }
  1215. if (!Call->isCallee(&U)) {
  1216. if (PutOffender)
  1217. *PutOffender = FU;
  1218. return true;
  1219. }
  1220. }
  1221. return false;
  1222. }
  1223. bool Function::isDefTriviallyDead() const {
  1224. // Check the linkage
  1225. if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
  1226. !hasAvailableExternallyLinkage())
  1227. return false;
  1228. // Check if the function is used by anything other than a blockaddress.
  1229. for (const User *U : users())
  1230. if (!isa<BlockAddress>(U))
  1231. return false;
  1232. return true;
  1233. }
  1234. /// callsFunctionThatReturnsTwice - Return true if the function has a call to
  1235. /// setjmp or other function that gcc recognizes as "returning twice".
  1236. bool Function::callsFunctionThatReturnsTwice() const {
  1237. for (const Instruction &I : instructions(this))
  1238. if (const auto *Call = dyn_cast<CallBase>(&I))
  1239. if (Call->hasFnAttr(Attribute::ReturnsTwice))
  1240. return true;
  1241. return false;
  1242. }
  1243. Constant *Function::getPersonalityFn() const {
  1244. assert(hasPersonalityFn() && getNumOperands());
  1245. return cast<Constant>(Op<0>());
  1246. }
  1247. void Function::setPersonalityFn(Constant *Fn) {
  1248. setHungoffOperand<0>(Fn);
  1249. setValueSubclassDataBit(3, Fn != nullptr);
  1250. }
  1251. Constant *Function::getPrefixData() const {
  1252. assert(hasPrefixData() && getNumOperands());
  1253. return cast<Constant>(Op<1>());
  1254. }
  1255. void Function::setPrefixData(Constant *PrefixData) {
  1256. setHungoffOperand<1>(PrefixData);
  1257. setValueSubclassDataBit(1, PrefixData != nullptr);
  1258. }
  1259. Constant *Function::getPrologueData() const {
  1260. assert(hasPrologueData() && getNumOperands());
  1261. return cast<Constant>(Op<2>());
  1262. }
  1263. void Function::setPrologueData(Constant *PrologueData) {
  1264. setHungoffOperand<2>(PrologueData);
  1265. setValueSubclassDataBit(2, PrologueData != nullptr);
  1266. }
  1267. void Function::allocHungoffUselist() {
  1268. // If we've already allocated a uselist, stop here.
  1269. if (getNumOperands())
  1270. return;
  1271. allocHungoffUses(3, /*IsPhi=*/ false);
  1272. setNumHungOffUseOperands(3);
  1273. // Initialize the uselist with placeholder operands to allow traversal.
  1274. auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
  1275. Op<0>().set(CPN);
  1276. Op<1>().set(CPN);
  1277. Op<2>().set(CPN);
  1278. }
  1279. template <int Idx>
  1280. void Function::setHungoffOperand(Constant *C) {
  1281. if (C) {
  1282. allocHungoffUselist();
  1283. Op<Idx>().set(C);
  1284. } else if (getNumOperands()) {
  1285. Op<Idx>().set(
  1286. ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
  1287. }
  1288. }
  1289. void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
  1290. assert(Bit < 16 && "SubclassData contains only 16 bits");
  1291. if (On)
  1292. setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
  1293. else
  1294. setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
  1295. }
  1296. void Function::setEntryCount(ProfileCount Count,
  1297. const DenseSet<GlobalValue::GUID> *S) {
  1298. assert(Count.hasValue());
  1299. #if !defined(NDEBUG)
  1300. auto PrevCount = getEntryCount();
  1301. assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType());
  1302. #endif
  1303. MDBuilder MDB(getContext());
  1304. setMetadata(
  1305. LLVMContext::MD_prof,
  1306. MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
  1307. }
  1308. void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
  1309. const DenseSet<GlobalValue::GUID> *Imports) {
  1310. setEntryCount(ProfileCount(Count, Type), Imports);
  1311. }
  1312. ProfileCount Function::getEntryCount(bool AllowSynthetic) const {
  1313. MDNode *MD = getMetadata(LLVMContext::MD_prof);
  1314. if (MD && MD->getOperand(0))
  1315. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
  1316. if (MDS->getString().equals("function_entry_count")) {
  1317. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1318. uint64_t Count = CI->getValue().getZExtValue();
  1319. // A value of -1 is used for SamplePGO when there were no samples.
  1320. // Treat this the same as unknown.
  1321. if (Count == (uint64_t)-1)
  1322. return ProfileCount::getInvalid();
  1323. return ProfileCount(Count, PCT_Real);
  1324. } else if (AllowSynthetic &&
  1325. MDS->getString().equals("synthetic_function_entry_count")) {
  1326. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1327. uint64_t Count = CI->getValue().getZExtValue();
  1328. return ProfileCount(Count, PCT_Synthetic);
  1329. }
  1330. }
  1331. return ProfileCount::getInvalid();
  1332. }
  1333. DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
  1334. DenseSet<GlobalValue::GUID> R;
  1335. if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
  1336. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
  1337. if (MDS->getString().equals("function_entry_count"))
  1338. for (unsigned i = 2; i < MD->getNumOperands(); i++)
  1339. R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
  1340. ->getValue()
  1341. .getZExtValue());
  1342. return R;
  1343. }
  1344. void Function::setSectionPrefix(StringRef Prefix) {
  1345. MDBuilder MDB(getContext());
  1346. setMetadata(LLVMContext::MD_section_prefix,
  1347. MDB.createFunctionSectionPrefix(Prefix));
  1348. }
  1349. Optional<StringRef> Function::getSectionPrefix() const {
  1350. if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
  1351. assert(cast<MDString>(MD->getOperand(0))
  1352. ->getString()
  1353. .equals("function_section_prefix") &&
  1354. "Metadata not match");
  1355. return cast<MDString>(MD->getOperand(1))->getString();
  1356. }
  1357. return None;
  1358. }
  1359. bool Function::nullPointerIsDefined() const {
  1360. return getFnAttribute("null-pointer-is-valid")
  1361. .getValueAsString()
  1362. .equals("true");
  1363. }
  1364. bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
  1365. if (F && F->nullPointerIsDefined())
  1366. return true;
  1367. if (AS != 0)
  1368. return true;
  1369. return false;
  1370. }