Function.cpp 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144
  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/STLExtras.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/IR/AbstractCallSite.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/IntrinsicInst.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/IntrinsicsAArch64.h"
  34. #include "llvm/IR/IntrinsicsAMDGPU.h"
  35. #include "llvm/IR/IntrinsicsARM.h"
  36. #include "llvm/IR/IntrinsicsBPF.h"
  37. #include "llvm/IR/IntrinsicsDirectX.h"
  38. #include "llvm/IR/IntrinsicsHexagon.h"
  39. #include "llvm/IR/IntrinsicsMips.h"
  40. #include "llvm/IR/IntrinsicsNVPTX.h"
  41. #include "llvm/IR/IntrinsicsPowerPC.h"
  42. #include "llvm/IR/IntrinsicsR600.h"
  43. #include "llvm/IR/IntrinsicsRISCV.h"
  44. #include "llvm/IR/IntrinsicsS390.h"
  45. #include "llvm/IR/IntrinsicsVE.h"
  46. #include "llvm/IR/IntrinsicsWebAssembly.h"
  47. #include "llvm/IR/IntrinsicsX86.h"
  48. #include "llvm/IR/IntrinsicsXCore.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/MDBuilder.h"
  51. #include "llvm/IR/Metadata.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/IR/Operator.h"
  54. #include "llvm/IR/SymbolTableListTraits.h"
  55. #include "llvm/IR/Type.h"
  56. #include "llvm/IR/Use.h"
  57. #include "llvm/IR/User.h"
  58. #include "llvm/IR/Value.h"
  59. #include "llvm/IR/ValueSymbolTable.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Compiler.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/ModRef.h"
  65. #include <cassert>
  66. #include <cstddef>
  67. #include <cstdint>
  68. #include <cstring>
  69. #include <string>
  70. using namespace llvm;
  71. using ProfileCount = Function::ProfileCount;
  72. // Explicit instantiations of SymbolTableListTraits since some of the methods
  73. // are not in the public header file...
  74. template class llvm::SymbolTableListTraits<BasicBlock>;
  75. static cl::opt<unsigned> NonGlobalValueMaxNameSize(
  76. "non-global-value-max-name-size", cl::Hidden, cl::init(1024),
  77. cl::desc("Maximum size for the name of non-global values."));
  78. //===----------------------------------------------------------------------===//
  79. // Argument Implementation
  80. //===----------------------------------------------------------------------===//
  81. Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo)
  82. : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) {
  83. setName(Name);
  84. }
  85. void Argument::setParent(Function *parent) {
  86. Parent = parent;
  87. }
  88. bool Argument::hasNonNullAttr(bool AllowUndefOrPoison) const {
  89. if (!getType()->isPointerTy()) return false;
  90. if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull) &&
  91. (AllowUndefOrPoison ||
  92. getParent()->hasParamAttribute(getArgNo(), Attribute::NoUndef)))
  93. return true;
  94. else if (getDereferenceableBytes() > 0 &&
  95. !NullPointerIsDefined(getParent(),
  96. getType()->getPointerAddressSpace()))
  97. return true;
  98. return false;
  99. }
  100. bool Argument::hasByValAttr() const {
  101. if (!getType()->isPointerTy()) return false;
  102. return hasAttribute(Attribute::ByVal);
  103. }
  104. bool Argument::hasByRefAttr() const {
  105. if (!getType()->isPointerTy())
  106. return false;
  107. return hasAttribute(Attribute::ByRef);
  108. }
  109. bool Argument::hasSwiftSelfAttr() const {
  110. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf);
  111. }
  112. bool Argument::hasSwiftErrorAttr() const {
  113. return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError);
  114. }
  115. bool Argument::hasInAllocaAttr() const {
  116. if (!getType()->isPointerTy()) return false;
  117. return hasAttribute(Attribute::InAlloca);
  118. }
  119. bool Argument::hasPreallocatedAttr() const {
  120. if (!getType()->isPointerTy())
  121. return false;
  122. return hasAttribute(Attribute::Preallocated);
  123. }
  124. bool Argument::hasPassPointeeByValueCopyAttr() const {
  125. if (!getType()->isPointerTy()) return false;
  126. AttributeList Attrs = getParent()->getAttributes();
  127. return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
  128. Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
  129. Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated);
  130. }
  131. bool Argument::hasPointeeInMemoryValueAttr() const {
  132. if (!getType()->isPointerTy())
  133. return false;
  134. AttributeList Attrs = getParent()->getAttributes();
  135. return Attrs.hasParamAttr(getArgNo(), Attribute::ByVal) ||
  136. Attrs.hasParamAttr(getArgNo(), Attribute::StructRet) ||
  137. Attrs.hasParamAttr(getArgNo(), Attribute::InAlloca) ||
  138. Attrs.hasParamAttr(getArgNo(), Attribute::Preallocated) ||
  139. Attrs.hasParamAttr(getArgNo(), Attribute::ByRef);
  140. }
  141. /// For a byval, sret, inalloca, or preallocated parameter, get the in-memory
  142. /// parameter type.
  143. static Type *getMemoryParamAllocType(AttributeSet ParamAttrs) {
  144. // FIXME: All the type carrying attributes are mutually exclusive, so there
  145. // should be a single query to get the stored type that handles any of them.
  146. if (Type *ByValTy = ParamAttrs.getByValType())
  147. return ByValTy;
  148. if (Type *ByRefTy = ParamAttrs.getByRefType())
  149. return ByRefTy;
  150. if (Type *PreAllocTy = ParamAttrs.getPreallocatedType())
  151. return PreAllocTy;
  152. if (Type *InAllocaTy = ParamAttrs.getInAllocaType())
  153. return InAllocaTy;
  154. if (Type *SRetTy = ParamAttrs.getStructRetType())
  155. return SRetTy;
  156. return nullptr;
  157. }
  158. uint64_t Argument::getPassPointeeByValueCopySize(const DataLayout &DL) const {
  159. AttributeSet ParamAttrs =
  160. getParent()->getAttributes().getParamAttrs(getArgNo());
  161. if (Type *MemTy = getMemoryParamAllocType(ParamAttrs))
  162. return DL.getTypeAllocSize(MemTy);
  163. return 0;
  164. }
  165. Type *Argument::getPointeeInMemoryValueType() const {
  166. AttributeSet ParamAttrs =
  167. getParent()->getAttributes().getParamAttrs(getArgNo());
  168. return getMemoryParamAllocType(ParamAttrs);
  169. }
  170. MaybeAlign Argument::getParamAlign() const {
  171. assert(getType()->isPointerTy() && "Only pointers have alignments");
  172. return getParent()->getParamAlign(getArgNo());
  173. }
  174. MaybeAlign Argument::getParamStackAlign() const {
  175. return getParent()->getParamStackAlign(getArgNo());
  176. }
  177. Type *Argument::getParamByValType() const {
  178. assert(getType()->isPointerTy() && "Only pointers have byval types");
  179. return getParent()->getParamByValType(getArgNo());
  180. }
  181. Type *Argument::getParamStructRetType() const {
  182. assert(getType()->isPointerTy() && "Only pointers have sret types");
  183. return getParent()->getParamStructRetType(getArgNo());
  184. }
  185. Type *Argument::getParamByRefType() const {
  186. assert(getType()->isPointerTy() && "Only pointers have byref types");
  187. return getParent()->getParamByRefType(getArgNo());
  188. }
  189. Type *Argument::getParamInAllocaType() const {
  190. assert(getType()->isPointerTy() && "Only pointers have inalloca types");
  191. return getParent()->getParamInAllocaType(getArgNo());
  192. }
  193. uint64_t Argument::getDereferenceableBytes() const {
  194. assert(getType()->isPointerTy() &&
  195. "Only pointers have dereferenceable bytes");
  196. return getParent()->getParamDereferenceableBytes(getArgNo());
  197. }
  198. uint64_t Argument::getDereferenceableOrNullBytes() const {
  199. assert(getType()->isPointerTy() &&
  200. "Only pointers have dereferenceable bytes");
  201. return getParent()->getParamDereferenceableOrNullBytes(getArgNo());
  202. }
  203. bool Argument::hasNestAttr() const {
  204. if (!getType()->isPointerTy()) return false;
  205. return hasAttribute(Attribute::Nest);
  206. }
  207. bool Argument::hasNoAliasAttr() const {
  208. if (!getType()->isPointerTy()) return false;
  209. return hasAttribute(Attribute::NoAlias);
  210. }
  211. bool Argument::hasNoCaptureAttr() const {
  212. if (!getType()->isPointerTy()) return false;
  213. return hasAttribute(Attribute::NoCapture);
  214. }
  215. bool Argument::hasNoFreeAttr() const {
  216. if (!getType()->isPointerTy()) return false;
  217. return hasAttribute(Attribute::NoFree);
  218. }
  219. bool Argument::hasStructRetAttr() const {
  220. if (!getType()->isPointerTy()) return false;
  221. return hasAttribute(Attribute::StructRet);
  222. }
  223. bool Argument::hasInRegAttr() const {
  224. return hasAttribute(Attribute::InReg);
  225. }
  226. bool Argument::hasReturnedAttr() const {
  227. return hasAttribute(Attribute::Returned);
  228. }
  229. bool Argument::hasZExtAttr() const {
  230. return hasAttribute(Attribute::ZExt);
  231. }
  232. bool Argument::hasSExtAttr() const {
  233. return hasAttribute(Attribute::SExt);
  234. }
  235. bool Argument::onlyReadsMemory() const {
  236. AttributeList Attrs = getParent()->getAttributes();
  237. return Attrs.hasParamAttr(getArgNo(), Attribute::ReadOnly) ||
  238. Attrs.hasParamAttr(getArgNo(), Attribute::ReadNone);
  239. }
  240. void Argument::addAttrs(AttrBuilder &B) {
  241. AttributeList AL = getParent()->getAttributes();
  242. AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B);
  243. getParent()->setAttributes(AL);
  244. }
  245. void Argument::addAttr(Attribute::AttrKind Kind) {
  246. getParent()->addParamAttr(getArgNo(), Kind);
  247. }
  248. void Argument::addAttr(Attribute Attr) {
  249. getParent()->addParamAttr(getArgNo(), Attr);
  250. }
  251. void Argument::removeAttr(Attribute::AttrKind Kind) {
  252. getParent()->removeParamAttr(getArgNo(), Kind);
  253. }
  254. void Argument::removeAttrs(const AttributeMask &AM) {
  255. AttributeList AL = getParent()->getAttributes();
  256. AL = AL.removeParamAttributes(Parent->getContext(), getArgNo(), AM);
  257. getParent()->setAttributes(AL);
  258. }
  259. bool Argument::hasAttribute(Attribute::AttrKind Kind) const {
  260. return getParent()->hasParamAttribute(getArgNo(), Kind);
  261. }
  262. Attribute Argument::getAttribute(Attribute::AttrKind Kind) const {
  263. return getParent()->getParamAttribute(getArgNo(), Kind);
  264. }
  265. //===----------------------------------------------------------------------===//
  266. // Helper Methods in Function
  267. //===----------------------------------------------------------------------===//
  268. LLVMContext &Function::getContext() const {
  269. return getType()->getContext();
  270. }
  271. unsigned Function::getInstructionCount() const {
  272. unsigned NumInstrs = 0;
  273. for (const BasicBlock &BB : BasicBlocks)
  274. NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(),
  275. BB.instructionsWithoutDebug().end());
  276. return NumInstrs;
  277. }
  278. Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage,
  279. const Twine &N, Module &M) {
  280. return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M);
  281. }
  282. Function *Function::createWithDefaultAttr(FunctionType *Ty,
  283. LinkageTypes Linkage,
  284. unsigned AddrSpace, const Twine &N,
  285. Module *M) {
  286. auto *F = new Function(Ty, Linkage, AddrSpace, N, M);
  287. AttrBuilder B(F->getContext());
  288. UWTableKind UWTable = M->getUwtable();
  289. if (UWTable != UWTableKind::None)
  290. B.addUWTableAttr(UWTable);
  291. switch (M->getFramePointer()) {
  292. case FramePointerKind::None:
  293. // 0 ("none") is the default.
  294. break;
  295. case FramePointerKind::NonLeaf:
  296. B.addAttribute("frame-pointer", "non-leaf");
  297. break;
  298. case FramePointerKind::All:
  299. B.addAttribute("frame-pointer", "all");
  300. break;
  301. }
  302. if (M->getModuleFlag("function_return_thunk_extern"))
  303. B.addAttribute(Attribute::FnRetThunkExtern);
  304. F->addFnAttrs(B);
  305. return F;
  306. }
  307. void Function::removeFromParent() {
  308. getParent()->getFunctionList().remove(getIterator());
  309. }
  310. void Function::eraseFromParent() {
  311. getParent()->getFunctionList().erase(getIterator());
  312. }
  313. void Function::splice(Function::iterator ToIt, Function *FromF,
  314. Function::iterator FromBeginIt,
  315. Function::iterator FromEndIt) {
  316. #ifdef EXPENSIVE_CHECKS
  317. // Check that FromBeginIt is before FromEndIt.
  318. auto FromFEnd = FromF->end();
  319. for (auto It = FromBeginIt; It != FromEndIt; ++It)
  320. assert(It != FromFEnd && "FromBeginIt not before FromEndIt!");
  321. #endif // EXPENSIVE_CHECKS
  322. BasicBlocks.splice(ToIt, FromF->BasicBlocks, FromBeginIt, FromEndIt);
  323. }
  324. Function::iterator Function::erase(Function::iterator FromIt,
  325. Function::iterator ToIt) {
  326. return BasicBlocks.erase(FromIt, ToIt);
  327. }
  328. //===----------------------------------------------------------------------===//
  329. // Function Implementation
  330. //===----------------------------------------------------------------------===//
  331. static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) {
  332. // If AS == -1 and we are passed a valid module pointer we place the function
  333. // in the program address space. Otherwise we default to AS0.
  334. if (AddrSpace == static_cast<unsigned>(-1))
  335. return M ? M->getDataLayout().getProgramAddressSpace() : 0;
  336. return AddrSpace;
  337. }
  338. Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace,
  339. const Twine &name, Module *ParentModule)
  340. : GlobalObject(Ty, Value::FunctionVal,
  341. OperandTraits<Function>::op_begin(this), 0, Linkage, name,
  342. computeAddrSpace(AddrSpace, ParentModule)),
  343. NumArgs(Ty->getNumParams()) {
  344. assert(FunctionType::isValidReturnType(getReturnType()) &&
  345. "invalid return type");
  346. setGlobalObjectSubClassData(0);
  347. // We only need a symbol table for a function if the context keeps value names
  348. if (!getContext().shouldDiscardValueNames())
  349. SymTab = std::make_unique<ValueSymbolTable>(NonGlobalValueMaxNameSize);
  350. // If the function has arguments, mark them as lazily built.
  351. if (Ty->getNumParams())
  352. setValueSubclassData(1); // Set the "has lazy arguments" bit.
  353. if (ParentModule)
  354. ParentModule->getFunctionList().push_back(this);
  355. HasLLVMReservedName = getName().startswith("llvm.");
  356. // Ensure intrinsics have the right parameter attributes.
  357. // Note, the IntID field will have been set in Value::setName if this function
  358. // name is a valid intrinsic ID.
  359. if (IntID)
  360. setAttributes(Intrinsic::getAttributes(getContext(), IntID));
  361. }
  362. Function::~Function() {
  363. dropAllReferences(); // After this it is safe to delete instructions.
  364. // Delete all of the method arguments and unlink from symbol table...
  365. if (Arguments)
  366. clearArguments();
  367. // Remove the function from the on-the-side GC table.
  368. clearGC();
  369. }
  370. void Function::BuildLazyArguments() const {
  371. // Create the arguments vector, all arguments start out unnamed.
  372. auto *FT = getFunctionType();
  373. if (NumArgs > 0) {
  374. Arguments = std::allocator<Argument>().allocate(NumArgs);
  375. for (unsigned i = 0, e = NumArgs; i != e; ++i) {
  376. Type *ArgTy = FT->getParamType(i);
  377. assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!");
  378. new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i);
  379. }
  380. }
  381. // Clear the lazy arguments bit.
  382. unsigned SDC = getSubclassDataFromValue();
  383. SDC &= ~(1 << 0);
  384. const_cast<Function*>(this)->setValueSubclassData(SDC);
  385. assert(!hasLazyArguments());
  386. }
  387. static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) {
  388. return MutableArrayRef<Argument>(Args, Count);
  389. }
  390. bool Function::isConstrainedFPIntrinsic() const {
  391. switch (getIntrinsicID()) {
  392. #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \
  393. case Intrinsic::INTRINSIC:
  394. #include "llvm/IR/ConstrainedOps.def"
  395. return true;
  396. #undef INSTRUCTION
  397. default:
  398. return false;
  399. }
  400. }
  401. void Function::clearArguments() {
  402. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  403. A.setName("");
  404. A.~Argument();
  405. }
  406. std::allocator<Argument>().deallocate(Arguments, NumArgs);
  407. Arguments = nullptr;
  408. }
  409. void Function::stealArgumentListFrom(Function &Src) {
  410. assert(isDeclaration() && "Expected no references to current arguments");
  411. // Drop the current arguments, if any, and set the lazy argument bit.
  412. if (!hasLazyArguments()) {
  413. assert(llvm::all_of(makeArgArray(Arguments, NumArgs),
  414. [](const Argument &A) { return A.use_empty(); }) &&
  415. "Expected arguments to be unused in declaration");
  416. clearArguments();
  417. setValueSubclassData(getSubclassDataFromValue() | (1 << 0));
  418. }
  419. // Nothing to steal if Src has lazy arguments.
  420. if (Src.hasLazyArguments())
  421. return;
  422. // Steal arguments from Src, and fix the lazy argument bits.
  423. assert(arg_size() == Src.arg_size());
  424. Arguments = Src.Arguments;
  425. Src.Arguments = nullptr;
  426. for (Argument &A : makeArgArray(Arguments, NumArgs)) {
  427. // FIXME: This does the work of transferNodesFromList inefficiently.
  428. SmallString<128> Name;
  429. if (A.hasName())
  430. Name = A.getName();
  431. if (!Name.empty())
  432. A.setName("");
  433. A.setParent(this);
  434. if (!Name.empty())
  435. A.setName(Name);
  436. }
  437. setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0));
  438. assert(!hasLazyArguments());
  439. Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0));
  440. }
  441. // dropAllReferences() - This function causes all the subinstructions to "let
  442. // go" of all references that they are maintaining. This allows one to
  443. // 'delete' a whole class at a time, even though there may be circular
  444. // references... first all references are dropped, and all use counts go to
  445. // zero. Then everything is deleted for real. Note that no operations are
  446. // valid on an object that has "dropped all references", except operator
  447. // delete.
  448. //
  449. void Function::dropAllReferences() {
  450. setIsMaterializable(false);
  451. for (BasicBlock &BB : *this)
  452. BB.dropAllReferences();
  453. // Delete all basic blocks. They are now unused, except possibly by
  454. // blockaddresses, but BasicBlock's destructor takes care of those.
  455. while (!BasicBlocks.empty())
  456. BasicBlocks.begin()->eraseFromParent();
  457. // Drop uses of any optional data (real or placeholder).
  458. if (getNumOperands()) {
  459. User::dropAllReferences();
  460. setNumHungOffUseOperands(0);
  461. setValueSubclassData(getSubclassDataFromValue() & ~0xe);
  462. }
  463. // Metadata is stored in a side-table.
  464. clearMetadata();
  465. }
  466. void Function::addAttributeAtIndex(unsigned i, Attribute Attr) {
  467. AttributeSets = AttributeSets.addAttributeAtIndex(getContext(), i, Attr);
  468. }
  469. void Function::addFnAttr(Attribute::AttrKind Kind) {
  470. AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind);
  471. }
  472. void Function::addFnAttr(StringRef Kind, StringRef Val) {
  473. AttributeSets = AttributeSets.addFnAttribute(getContext(), Kind, Val);
  474. }
  475. void Function::addFnAttr(Attribute Attr) {
  476. AttributeSets = AttributeSets.addFnAttribute(getContext(), Attr);
  477. }
  478. void Function::addFnAttrs(const AttrBuilder &Attrs) {
  479. AttributeSets = AttributeSets.addFnAttributes(getContext(), Attrs);
  480. }
  481. void Function::addRetAttr(Attribute::AttrKind Kind) {
  482. AttributeSets = AttributeSets.addRetAttribute(getContext(), Kind);
  483. }
  484. void Function::addRetAttr(Attribute Attr) {
  485. AttributeSets = AttributeSets.addRetAttribute(getContext(), Attr);
  486. }
  487. void Function::addRetAttrs(const AttrBuilder &Attrs) {
  488. AttributeSets = AttributeSets.addRetAttributes(getContext(), Attrs);
  489. }
  490. void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
  491. AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Kind);
  492. }
  493. void Function::addParamAttr(unsigned ArgNo, Attribute Attr) {
  494. AttributeSets = AttributeSets.addParamAttribute(getContext(), ArgNo, Attr);
  495. }
  496. void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) {
  497. AttributeSets = AttributeSets.addParamAttributes(getContext(), ArgNo, Attrs);
  498. }
  499. void Function::removeAttributeAtIndex(unsigned i, Attribute::AttrKind Kind) {
  500. AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
  501. }
  502. void Function::removeAttributeAtIndex(unsigned i, StringRef Kind) {
  503. AttributeSets = AttributeSets.removeAttributeAtIndex(getContext(), i, Kind);
  504. }
  505. void Function::removeFnAttr(Attribute::AttrKind Kind) {
  506. AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
  507. }
  508. void Function::removeFnAttr(StringRef Kind) {
  509. AttributeSets = AttributeSets.removeFnAttribute(getContext(), Kind);
  510. }
  511. void Function::removeFnAttrs(const AttributeMask &AM) {
  512. AttributeSets = AttributeSets.removeFnAttributes(getContext(), AM);
  513. }
  514. void Function::removeRetAttr(Attribute::AttrKind Kind) {
  515. AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
  516. }
  517. void Function::removeRetAttr(StringRef Kind) {
  518. AttributeSets = AttributeSets.removeRetAttribute(getContext(), Kind);
  519. }
  520. void Function::removeRetAttrs(const AttributeMask &Attrs) {
  521. AttributeSets = AttributeSets.removeRetAttributes(getContext(), Attrs);
  522. }
  523. void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) {
  524. AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
  525. }
  526. void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) {
  527. AttributeSets = AttributeSets.removeParamAttribute(getContext(), ArgNo, Kind);
  528. }
  529. void Function::removeParamAttrs(unsigned ArgNo, const AttributeMask &Attrs) {
  530. AttributeSets =
  531. AttributeSets.removeParamAttributes(getContext(), ArgNo, Attrs);
  532. }
  533. void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) {
  534. AttributeSets =
  535. AttributeSets.addDereferenceableParamAttr(getContext(), ArgNo, Bytes);
  536. }
  537. bool Function::hasFnAttribute(Attribute::AttrKind Kind) const {
  538. return AttributeSets.hasFnAttr(Kind);
  539. }
  540. bool Function::hasFnAttribute(StringRef Kind) const {
  541. return AttributeSets.hasFnAttr(Kind);
  542. }
  543. bool Function::hasRetAttribute(Attribute::AttrKind Kind) const {
  544. return AttributeSets.hasRetAttr(Kind);
  545. }
  546. bool Function::hasParamAttribute(unsigned ArgNo,
  547. Attribute::AttrKind Kind) const {
  548. return AttributeSets.hasParamAttr(ArgNo, Kind);
  549. }
  550. Attribute Function::getAttributeAtIndex(unsigned i,
  551. Attribute::AttrKind Kind) const {
  552. return AttributeSets.getAttributeAtIndex(i, Kind);
  553. }
  554. Attribute Function::getAttributeAtIndex(unsigned i, StringRef Kind) const {
  555. return AttributeSets.getAttributeAtIndex(i, Kind);
  556. }
  557. Attribute Function::getFnAttribute(Attribute::AttrKind Kind) const {
  558. return AttributeSets.getFnAttr(Kind);
  559. }
  560. Attribute Function::getFnAttribute(StringRef Kind) const {
  561. return AttributeSets.getFnAttr(Kind);
  562. }
  563. uint64_t Function::getFnAttributeAsParsedInteger(StringRef Name,
  564. uint64_t Default) const {
  565. Attribute A = getFnAttribute(Name);
  566. uint64_t Result = Default;
  567. if (A.isStringAttribute()) {
  568. StringRef Str = A.getValueAsString();
  569. if (Str.getAsInteger(0, Result))
  570. getContext().emitError("cannot parse integer attribute " + Name);
  571. }
  572. return Result;
  573. }
  574. /// gets the specified attribute from the list of attributes.
  575. Attribute Function::getParamAttribute(unsigned ArgNo,
  576. Attribute::AttrKind Kind) const {
  577. return AttributeSets.getParamAttr(ArgNo, Kind);
  578. }
  579. void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo,
  580. uint64_t Bytes) {
  581. AttributeSets = AttributeSets.addDereferenceableOrNullParamAttr(getContext(),
  582. ArgNo, Bytes);
  583. }
  584. DenormalMode Function::getDenormalMode(const fltSemantics &FPType) const {
  585. if (&FPType == &APFloat::IEEEsingle()) {
  586. Attribute Attr = getFnAttribute("denormal-fp-math-f32");
  587. StringRef Val = Attr.getValueAsString();
  588. if (!Val.empty())
  589. return parseDenormalFPAttribute(Val);
  590. // If the f32 variant of the attribute isn't specified, try to use the
  591. // generic one.
  592. }
  593. Attribute Attr = getFnAttribute("denormal-fp-math");
  594. return parseDenormalFPAttribute(Attr.getValueAsString());
  595. }
  596. const std::string &Function::getGC() const {
  597. assert(hasGC() && "Function has no collector");
  598. return getContext().getGC(*this);
  599. }
  600. void Function::setGC(std::string Str) {
  601. setValueSubclassDataBit(14, !Str.empty());
  602. getContext().setGC(*this, std::move(Str));
  603. }
  604. void Function::clearGC() {
  605. if (!hasGC())
  606. return;
  607. getContext().deleteGC(*this);
  608. setValueSubclassDataBit(14, false);
  609. }
  610. bool Function::hasStackProtectorFnAttr() const {
  611. return hasFnAttribute(Attribute::StackProtect) ||
  612. hasFnAttribute(Attribute::StackProtectStrong) ||
  613. hasFnAttribute(Attribute::StackProtectReq);
  614. }
  615. /// Copy all additional attributes (those not needed to create a Function) from
  616. /// the Function Src to this one.
  617. void Function::copyAttributesFrom(const Function *Src) {
  618. GlobalObject::copyAttributesFrom(Src);
  619. setCallingConv(Src->getCallingConv());
  620. setAttributes(Src->getAttributes());
  621. if (Src->hasGC())
  622. setGC(Src->getGC());
  623. else
  624. clearGC();
  625. if (Src->hasPersonalityFn())
  626. setPersonalityFn(Src->getPersonalityFn());
  627. if (Src->hasPrefixData())
  628. setPrefixData(Src->getPrefixData());
  629. if (Src->hasPrologueData())
  630. setPrologueData(Src->getPrologueData());
  631. }
  632. MemoryEffects Function::getMemoryEffects() const {
  633. return getAttributes().getMemoryEffects();
  634. }
  635. void Function::setMemoryEffects(MemoryEffects ME) {
  636. addFnAttr(Attribute::getWithMemoryEffects(getContext(), ME));
  637. }
  638. /// Determine if the function does not access memory.
  639. bool Function::doesNotAccessMemory() const {
  640. return getMemoryEffects().doesNotAccessMemory();
  641. }
  642. void Function::setDoesNotAccessMemory() {
  643. setMemoryEffects(MemoryEffects::none());
  644. }
  645. /// Determine if the function does not access or only reads memory.
  646. bool Function::onlyReadsMemory() const {
  647. return getMemoryEffects().onlyReadsMemory();
  648. }
  649. void Function::setOnlyReadsMemory() {
  650. setMemoryEffects(getMemoryEffects() & MemoryEffects::readOnly());
  651. }
  652. /// Determine if the function does not access or only writes memory.
  653. bool Function::onlyWritesMemory() const {
  654. return getMemoryEffects().onlyWritesMemory();
  655. }
  656. void Function::setOnlyWritesMemory() {
  657. setMemoryEffects(getMemoryEffects() & MemoryEffects::writeOnly());
  658. }
  659. /// Determine if the call can access memmory only using pointers based
  660. /// on its arguments.
  661. bool Function::onlyAccessesArgMemory() const {
  662. return getMemoryEffects().onlyAccessesArgPointees();
  663. }
  664. void Function::setOnlyAccessesArgMemory() {
  665. setMemoryEffects(getMemoryEffects() & MemoryEffects::argMemOnly());
  666. }
  667. /// Determine if the function may only access memory that is
  668. /// inaccessible from the IR.
  669. bool Function::onlyAccessesInaccessibleMemory() const {
  670. return getMemoryEffects().onlyAccessesInaccessibleMem();
  671. }
  672. void Function::setOnlyAccessesInaccessibleMemory() {
  673. setMemoryEffects(getMemoryEffects() & MemoryEffects::inaccessibleMemOnly());
  674. }
  675. /// Determine if the function may only access memory that is
  676. /// either inaccessible from the IR or pointed to by its arguments.
  677. bool Function::onlyAccessesInaccessibleMemOrArgMem() const {
  678. return getMemoryEffects().onlyAccessesInaccessibleOrArgMem();
  679. }
  680. void Function::setOnlyAccessesInaccessibleMemOrArgMem() {
  681. setMemoryEffects(getMemoryEffects() &
  682. MemoryEffects::inaccessibleOrArgMemOnly());
  683. }
  684. /// Table of string intrinsic names indexed by enum value.
  685. static const char * const IntrinsicNameTable[] = {
  686. "not_intrinsic",
  687. #define GET_INTRINSIC_NAME_TABLE
  688. #include "llvm/IR/IntrinsicImpl.inc"
  689. #undef GET_INTRINSIC_NAME_TABLE
  690. };
  691. /// Table of per-target intrinsic name tables.
  692. #define GET_INTRINSIC_TARGET_DATA
  693. #include "llvm/IR/IntrinsicImpl.inc"
  694. #undef GET_INTRINSIC_TARGET_DATA
  695. bool Function::isTargetIntrinsic(Intrinsic::ID IID) {
  696. return IID > TargetInfos[0].Count;
  697. }
  698. bool Function::isTargetIntrinsic() const {
  699. return isTargetIntrinsic(IntID);
  700. }
  701. /// Find the segment of \c IntrinsicNameTable for intrinsics with the same
  702. /// target as \c Name, or the generic table if \c Name is not target specific.
  703. ///
  704. /// Returns the relevant slice of \c IntrinsicNameTable
  705. static ArrayRef<const char *> findTargetSubtable(StringRef Name) {
  706. assert(Name.startswith("llvm."));
  707. ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos);
  708. // Drop "llvm." and take the first dotted component. That will be the target
  709. // if this is target specific.
  710. StringRef Target = Name.drop_front(5).split('.').first;
  711. auto It = partition_point(
  712. Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; });
  713. // We've either found the target or just fall back to the generic set, which
  714. // is always first.
  715. const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0];
  716. return ArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count);
  717. }
  718. /// This does the actual lookup of an intrinsic ID which
  719. /// matches the given function name.
  720. Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) {
  721. ArrayRef<const char *> NameTable = findTargetSubtable(Name);
  722. int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name);
  723. if (Idx == -1)
  724. return Intrinsic::not_intrinsic;
  725. // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have
  726. // an index into a sub-table.
  727. int Adjust = NameTable.data() - IntrinsicNameTable;
  728. Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust);
  729. // If the intrinsic is not overloaded, require an exact match. If it is
  730. // overloaded, require either exact or prefix match.
  731. const auto MatchSize = strlen(NameTable[Idx]);
  732. assert(Name.size() >= MatchSize && "Expected either exact or prefix match");
  733. bool IsExactMatch = Name.size() == MatchSize;
  734. return IsExactMatch || Intrinsic::isOverloaded(ID) ? ID
  735. : Intrinsic::not_intrinsic;
  736. }
  737. void Function::recalculateIntrinsicID() {
  738. StringRef Name = getName();
  739. if (!Name.startswith("llvm.")) {
  740. HasLLVMReservedName = false;
  741. IntID = Intrinsic::not_intrinsic;
  742. return;
  743. }
  744. HasLLVMReservedName = true;
  745. IntID = lookupIntrinsicID(Name);
  746. }
  747. /// Returns a stable mangling for the type specified for use in the name
  748. /// mangling scheme used by 'any' types in intrinsic signatures. The mangling
  749. /// of named types is simply their name. Manglings for unnamed types consist
  750. /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
  751. /// combined with the mangling of their component types. A vararg function
  752. /// type will have a suffix of 'vararg'. Since function types can contain
  753. /// other function types, we close a function type mangling with suffix 'f'
  754. /// which can't be confused with it's prefix. This ensures we don't have
  755. /// collisions between two unrelated function types. Otherwise, you might
  756. /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
  757. /// The HasUnnamedType boolean is set if an unnamed type was encountered,
  758. /// indicating that extra care must be taken to ensure a unique name.
  759. static std::string getMangledTypeStr(Type *Ty, bool &HasUnnamedType) {
  760. std::string Result;
  761. if (PointerType *PTyp = dyn_cast<PointerType>(Ty)) {
  762. Result += "p" + utostr(PTyp->getAddressSpace());
  763. // Opaque pointer doesn't have pointee type information, so we just mangle
  764. // address space for opaque pointer.
  765. if (!PTyp->isOpaque())
  766. Result += getMangledTypeStr(PTyp->getNonOpaquePointerElementType(),
  767. HasUnnamedType);
  768. } else if (ArrayType *ATyp = dyn_cast<ArrayType>(Ty)) {
  769. Result += "a" + utostr(ATyp->getNumElements()) +
  770. getMangledTypeStr(ATyp->getElementType(), HasUnnamedType);
  771. } else if (StructType *STyp = dyn_cast<StructType>(Ty)) {
  772. if (!STyp->isLiteral()) {
  773. Result += "s_";
  774. if (STyp->hasName())
  775. Result += STyp->getName();
  776. else
  777. HasUnnamedType = true;
  778. } else {
  779. Result += "sl_";
  780. for (auto *Elem : STyp->elements())
  781. Result += getMangledTypeStr(Elem, HasUnnamedType);
  782. }
  783. // Ensure nested structs are distinguishable.
  784. Result += "s";
  785. } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) {
  786. Result += "f_" + getMangledTypeStr(FT->getReturnType(), HasUnnamedType);
  787. for (size_t i = 0; i < FT->getNumParams(); i++)
  788. Result += getMangledTypeStr(FT->getParamType(i), HasUnnamedType);
  789. if (FT->isVarArg())
  790. Result += "vararg";
  791. // Ensure nested function types are distinguishable.
  792. Result += "f";
  793. } else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  794. ElementCount EC = VTy->getElementCount();
  795. if (EC.isScalable())
  796. Result += "nx";
  797. Result += "v" + utostr(EC.getKnownMinValue()) +
  798. getMangledTypeStr(VTy->getElementType(), HasUnnamedType);
  799. } else if (TargetExtType *TETy = dyn_cast<TargetExtType>(Ty)) {
  800. Result += "t";
  801. Result += TETy->getName();
  802. for (Type *ParamTy : TETy->type_params())
  803. Result += "_" + getMangledTypeStr(ParamTy, HasUnnamedType);
  804. for (unsigned IntParam : TETy->int_params())
  805. Result += "_" + utostr(IntParam);
  806. // Ensure nested target extension types are distinguishable.
  807. Result += "t";
  808. } else if (Ty) {
  809. switch (Ty->getTypeID()) {
  810. default: llvm_unreachable("Unhandled type");
  811. case Type::VoidTyID: Result += "isVoid"; break;
  812. case Type::MetadataTyID: Result += "Metadata"; break;
  813. case Type::HalfTyID: Result += "f16"; break;
  814. case Type::BFloatTyID: Result += "bf16"; break;
  815. case Type::FloatTyID: Result += "f32"; break;
  816. case Type::DoubleTyID: Result += "f64"; break;
  817. case Type::X86_FP80TyID: Result += "f80"; break;
  818. case Type::FP128TyID: Result += "f128"; break;
  819. case Type::PPC_FP128TyID: Result += "ppcf128"; break;
  820. case Type::X86_MMXTyID: Result += "x86mmx"; break;
  821. case Type::X86_AMXTyID: Result += "x86amx"; break;
  822. case Type::IntegerTyID:
  823. Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth());
  824. break;
  825. }
  826. }
  827. return Result;
  828. }
  829. StringRef Intrinsic::getBaseName(ID id) {
  830. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  831. return IntrinsicNameTable[id];
  832. }
  833. StringRef Intrinsic::getName(ID id) {
  834. assert(id < num_intrinsics && "Invalid intrinsic ID!");
  835. assert(!Intrinsic::isOverloaded(id) &&
  836. "This version of getName does not support overloading");
  837. return getBaseName(id);
  838. }
  839. static std::string getIntrinsicNameImpl(Intrinsic::ID Id, ArrayRef<Type *> Tys,
  840. Module *M, FunctionType *FT,
  841. bool EarlyModuleCheck) {
  842. assert(Id < Intrinsic::num_intrinsics && "Invalid intrinsic ID!");
  843. assert((Tys.empty() || Intrinsic::isOverloaded(Id)) &&
  844. "This version of getName is for overloaded intrinsics only");
  845. (void)EarlyModuleCheck;
  846. assert((!EarlyModuleCheck || M ||
  847. !any_of(Tys, [](Type *T) { return isa<PointerType>(T); })) &&
  848. "Intrinsic overloading on pointer types need to provide a Module");
  849. bool HasUnnamedType = false;
  850. std::string Result(Intrinsic::getBaseName(Id));
  851. for (Type *Ty : Tys)
  852. Result += "." + getMangledTypeStr(Ty, HasUnnamedType);
  853. if (HasUnnamedType) {
  854. assert(M && "unnamed types need a module");
  855. if (!FT)
  856. FT = Intrinsic::getType(M->getContext(), Id, Tys);
  857. else
  858. assert((FT == Intrinsic::getType(M->getContext(), Id, Tys)) &&
  859. "Provided FunctionType must match arguments");
  860. return M->getUniqueIntrinsicName(Result, Id, FT);
  861. }
  862. return Result;
  863. }
  864. std::string Intrinsic::getName(ID Id, ArrayRef<Type *> Tys, Module *M,
  865. FunctionType *FT) {
  866. assert(M && "We need to have a Module");
  867. return getIntrinsicNameImpl(Id, Tys, M, FT, true);
  868. }
  869. std::string Intrinsic::getNameNoUnnamedTypes(ID Id, ArrayRef<Type *> Tys) {
  870. return getIntrinsicNameImpl(Id, Tys, nullptr, nullptr, false);
  871. }
  872. /// IIT_Info - These are enumerators that describe the entries returned by the
  873. /// getIntrinsicInfoTableEntries function.
  874. ///
  875. /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
  876. enum IIT_Info {
  877. // Common values should be encoded with 0-15.
  878. IIT_Done = 0,
  879. IIT_I1 = 1,
  880. IIT_I8 = 2,
  881. IIT_I16 = 3,
  882. IIT_I32 = 4,
  883. IIT_I64 = 5,
  884. IIT_F16 = 6,
  885. IIT_F32 = 7,
  886. IIT_F64 = 8,
  887. IIT_V2 = 9,
  888. IIT_V4 = 10,
  889. IIT_V8 = 11,
  890. IIT_V16 = 12,
  891. IIT_V32 = 13,
  892. IIT_PTR = 14,
  893. IIT_ARG = 15,
  894. // Values from 16+ are only encodable with the inefficient encoding.
  895. IIT_V64 = 16,
  896. IIT_MMX = 17,
  897. IIT_TOKEN = 18,
  898. IIT_METADATA = 19,
  899. IIT_EMPTYSTRUCT = 20,
  900. IIT_STRUCT2 = 21,
  901. IIT_STRUCT3 = 22,
  902. IIT_STRUCT4 = 23,
  903. IIT_STRUCT5 = 24,
  904. IIT_EXTEND_ARG = 25,
  905. IIT_TRUNC_ARG = 26,
  906. IIT_ANYPTR = 27,
  907. IIT_V1 = 28,
  908. IIT_VARARG = 29,
  909. IIT_HALF_VEC_ARG = 30,
  910. IIT_SAME_VEC_WIDTH_ARG = 31,
  911. IIT_PTR_TO_ARG = 32,
  912. IIT_PTR_TO_ELT = 33,
  913. IIT_VEC_OF_ANYPTRS_TO_ELT = 34,
  914. IIT_I128 = 35,
  915. IIT_V512 = 36,
  916. IIT_V1024 = 37,
  917. IIT_STRUCT6 = 38,
  918. IIT_STRUCT7 = 39,
  919. IIT_STRUCT8 = 40,
  920. IIT_F128 = 41,
  921. IIT_VEC_ELEMENT = 42,
  922. IIT_SCALABLE_VEC = 43,
  923. IIT_SUBDIVIDE2_ARG = 44,
  924. IIT_SUBDIVIDE4_ARG = 45,
  925. IIT_VEC_OF_BITCASTS_TO_INT = 46,
  926. IIT_V128 = 47,
  927. IIT_BF16 = 48,
  928. IIT_STRUCT9 = 49,
  929. IIT_V256 = 50,
  930. IIT_AMX = 51,
  931. IIT_PPCF128 = 52,
  932. IIT_V3 = 53,
  933. IIT_EXTERNREF = 54,
  934. IIT_FUNCREF = 55,
  935. IIT_ANYPTR_TO_ELT = 56,
  936. IIT_I2 = 57,
  937. IIT_I4 = 58,
  938. };
  939. static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
  940. IIT_Info LastInfo,
  941. SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
  942. using namespace Intrinsic;
  943. bool IsScalableVector = (LastInfo == IIT_SCALABLE_VEC);
  944. IIT_Info Info = IIT_Info(Infos[NextElt++]);
  945. unsigned StructElts = 2;
  946. switch (Info) {
  947. case IIT_Done:
  948. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
  949. return;
  950. case IIT_VARARG:
  951. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
  952. return;
  953. case IIT_MMX:
  954. OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
  955. return;
  956. case IIT_AMX:
  957. OutputTable.push_back(IITDescriptor::get(IITDescriptor::AMX, 0));
  958. return;
  959. case IIT_TOKEN:
  960. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0));
  961. return;
  962. case IIT_METADATA:
  963. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
  964. return;
  965. case IIT_F16:
  966. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
  967. return;
  968. case IIT_BF16:
  969. OutputTable.push_back(IITDescriptor::get(IITDescriptor::BFloat, 0));
  970. return;
  971. case IIT_F32:
  972. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
  973. return;
  974. case IIT_F64:
  975. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
  976. return;
  977. case IIT_F128:
  978. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0));
  979. return;
  980. case IIT_PPCF128:
  981. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PPCQuad, 0));
  982. return;
  983. case IIT_I1:
  984. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
  985. return;
  986. case IIT_I2:
  987. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 2));
  988. return;
  989. case IIT_I4:
  990. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 4));
  991. return;
  992. case IIT_I8:
  993. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  994. return;
  995. case IIT_I16:
  996. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
  997. return;
  998. case IIT_I32:
  999. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
  1000. return;
  1001. case IIT_I64:
  1002. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
  1003. return;
  1004. case IIT_I128:
  1005. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
  1006. return;
  1007. case IIT_V1:
  1008. OutputTable.push_back(IITDescriptor::getVector(1, IsScalableVector));
  1009. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1010. return;
  1011. case IIT_V2:
  1012. OutputTable.push_back(IITDescriptor::getVector(2, IsScalableVector));
  1013. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1014. return;
  1015. case IIT_V3:
  1016. OutputTable.push_back(IITDescriptor::getVector(3, IsScalableVector));
  1017. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1018. return;
  1019. case IIT_V4:
  1020. OutputTable.push_back(IITDescriptor::getVector(4, IsScalableVector));
  1021. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1022. return;
  1023. case IIT_V8:
  1024. OutputTable.push_back(IITDescriptor::getVector(8, IsScalableVector));
  1025. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1026. return;
  1027. case IIT_V16:
  1028. OutputTable.push_back(IITDescriptor::getVector(16, IsScalableVector));
  1029. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1030. return;
  1031. case IIT_V32:
  1032. OutputTable.push_back(IITDescriptor::getVector(32, IsScalableVector));
  1033. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1034. return;
  1035. case IIT_V64:
  1036. OutputTable.push_back(IITDescriptor::getVector(64, IsScalableVector));
  1037. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1038. return;
  1039. case IIT_V128:
  1040. OutputTable.push_back(IITDescriptor::getVector(128, IsScalableVector));
  1041. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1042. return;
  1043. case IIT_V256:
  1044. OutputTable.push_back(IITDescriptor::getVector(256, IsScalableVector));
  1045. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1046. return;
  1047. case IIT_V512:
  1048. OutputTable.push_back(IITDescriptor::getVector(512, IsScalableVector));
  1049. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1050. return;
  1051. case IIT_V1024:
  1052. OutputTable.push_back(IITDescriptor::getVector(1024, IsScalableVector));
  1053. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1054. return;
  1055. case IIT_EXTERNREF:
  1056. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 10));
  1057. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  1058. return;
  1059. case IIT_FUNCREF:
  1060. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 20));
  1061. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
  1062. return;
  1063. case IIT_PTR:
  1064. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
  1065. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1066. return;
  1067. case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
  1068. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
  1069. Infos[NextElt++]));
  1070. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1071. return;
  1072. }
  1073. case IIT_ARG: {
  1074. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1075. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
  1076. return;
  1077. }
  1078. case IIT_EXTEND_ARG: {
  1079. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1080. OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
  1081. ArgInfo));
  1082. return;
  1083. }
  1084. case IIT_TRUNC_ARG: {
  1085. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1086. OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
  1087. ArgInfo));
  1088. return;
  1089. }
  1090. case IIT_HALF_VEC_ARG: {
  1091. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1092. OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
  1093. ArgInfo));
  1094. return;
  1095. }
  1096. case IIT_SAME_VEC_WIDTH_ARG: {
  1097. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1098. OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
  1099. ArgInfo));
  1100. return;
  1101. }
  1102. case IIT_PTR_TO_ARG: {
  1103. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1104. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
  1105. ArgInfo));
  1106. return;
  1107. }
  1108. case IIT_PTR_TO_ELT: {
  1109. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1110. OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo));
  1111. return;
  1112. }
  1113. case IIT_ANYPTR_TO_ELT: {
  1114. unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1115. unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1116. OutputTable.push_back(
  1117. IITDescriptor::get(IITDescriptor::AnyPtrToElt, ArgNo, RefNo));
  1118. return;
  1119. }
  1120. case IIT_VEC_OF_ANYPTRS_TO_ELT: {
  1121. unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1122. unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1123. OutputTable.push_back(
  1124. IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo));
  1125. return;
  1126. }
  1127. case IIT_EMPTYSTRUCT:
  1128. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
  1129. return;
  1130. case IIT_STRUCT9: ++StructElts; [[fallthrough]];
  1131. case IIT_STRUCT8: ++StructElts; [[fallthrough]];
  1132. case IIT_STRUCT7: ++StructElts; [[fallthrough]];
  1133. case IIT_STRUCT6: ++StructElts; [[fallthrough]];
  1134. case IIT_STRUCT5: ++StructElts; [[fallthrough]];
  1135. case IIT_STRUCT4: ++StructElts; [[fallthrough]];
  1136. case IIT_STRUCT3: ++StructElts; [[fallthrough]];
  1137. case IIT_STRUCT2: {
  1138. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
  1139. for (unsigned i = 0; i != StructElts; ++i)
  1140. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1141. return;
  1142. }
  1143. case IIT_SUBDIVIDE2_ARG: {
  1144. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1145. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument,
  1146. ArgInfo));
  1147. return;
  1148. }
  1149. case IIT_SUBDIVIDE4_ARG: {
  1150. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1151. OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument,
  1152. ArgInfo));
  1153. return;
  1154. }
  1155. case IIT_VEC_ELEMENT: {
  1156. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1157. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument,
  1158. ArgInfo));
  1159. return;
  1160. }
  1161. case IIT_SCALABLE_VEC: {
  1162. DecodeIITType(NextElt, Infos, Info, OutputTable);
  1163. return;
  1164. }
  1165. case IIT_VEC_OF_BITCASTS_TO_INT: {
  1166. unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
  1167. OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfBitcastsToInt,
  1168. ArgInfo));
  1169. return;
  1170. }
  1171. }
  1172. llvm_unreachable("unhandled");
  1173. }
  1174. #define GET_INTRINSIC_GENERATOR_GLOBAL
  1175. #include "llvm/IR/IntrinsicImpl.inc"
  1176. #undef GET_INTRINSIC_GENERATOR_GLOBAL
  1177. void Intrinsic::getIntrinsicInfoTableEntries(ID id,
  1178. SmallVectorImpl<IITDescriptor> &T){
  1179. // Check to see if the intrinsic's type was expressible by the table.
  1180. unsigned TableVal = IIT_Table[id-1];
  1181. // Decode the TableVal into an array of IITValues.
  1182. SmallVector<unsigned char, 8> IITValues;
  1183. ArrayRef<unsigned char> IITEntries;
  1184. unsigned NextElt = 0;
  1185. if ((TableVal >> 31) != 0) {
  1186. // This is an offset into the IIT_LongEncodingTable.
  1187. IITEntries = IIT_LongEncodingTable;
  1188. // Strip sentinel bit.
  1189. NextElt = (TableVal << 1) >> 1;
  1190. } else {
  1191. // Decode the TableVal into an array of IITValues. If the entry was encoded
  1192. // into a single word in the table itself, decode it now.
  1193. do {
  1194. IITValues.push_back(TableVal & 0xF);
  1195. TableVal >>= 4;
  1196. } while (TableVal);
  1197. IITEntries = IITValues;
  1198. NextElt = 0;
  1199. }
  1200. // Okay, decode the table into the output vector of IITDescriptors.
  1201. DecodeIITType(NextElt, IITEntries, IIT_Done, T);
  1202. while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
  1203. DecodeIITType(NextElt, IITEntries, IIT_Done, T);
  1204. }
  1205. static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
  1206. ArrayRef<Type*> Tys, LLVMContext &Context) {
  1207. using namespace Intrinsic;
  1208. IITDescriptor D = Infos.front();
  1209. Infos = Infos.slice(1);
  1210. switch (D.Kind) {
  1211. case IITDescriptor::Void: return Type::getVoidTy(Context);
  1212. case IITDescriptor::VarArg: return Type::getVoidTy(Context);
  1213. case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
  1214. case IITDescriptor::AMX: return Type::getX86_AMXTy(Context);
  1215. case IITDescriptor::Token: return Type::getTokenTy(Context);
  1216. case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
  1217. case IITDescriptor::Half: return Type::getHalfTy(Context);
  1218. case IITDescriptor::BFloat: return Type::getBFloatTy(Context);
  1219. case IITDescriptor::Float: return Type::getFloatTy(Context);
  1220. case IITDescriptor::Double: return Type::getDoubleTy(Context);
  1221. case IITDescriptor::Quad: return Type::getFP128Ty(Context);
  1222. case IITDescriptor::PPCQuad: return Type::getPPC_FP128Ty(Context);
  1223. case IITDescriptor::Integer:
  1224. return IntegerType::get(Context, D.Integer_Width);
  1225. case IITDescriptor::Vector:
  1226. return VectorType::get(DecodeFixedType(Infos, Tys, Context),
  1227. D.Vector_Width);
  1228. case IITDescriptor::Pointer:
  1229. return PointerType::get(DecodeFixedType(Infos, Tys, Context),
  1230. D.Pointer_AddressSpace);
  1231. case IITDescriptor::Struct: {
  1232. SmallVector<Type *, 8> Elts;
  1233. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  1234. Elts.push_back(DecodeFixedType(Infos, Tys, Context));
  1235. return StructType::get(Context, Elts);
  1236. }
  1237. case IITDescriptor::Argument:
  1238. return Tys[D.getArgumentNumber()];
  1239. case IITDescriptor::ExtendArgument: {
  1240. Type *Ty = Tys[D.getArgumentNumber()];
  1241. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  1242. return VectorType::getExtendedElementVectorType(VTy);
  1243. return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
  1244. }
  1245. case IITDescriptor::TruncArgument: {
  1246. Type *Ty = Tys[D.getArgumentNumber()];
  1247. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  1248. return VectorType::getTruncatedElementVectorType(VTy);
  1249. IntegerType *ITy = cast<IntegerType>(Ty);
  1250. assert(ITy->getBitWidth() % 2 == 0);
  1251. return IntegerType::get(Context, ITy->getBitWidth() / 2);
  1252. }
  1253. case IITDescriptor::Subdivide2Argument:
  1254. case IITDescriptor::Subdivide4Argument: {
  1255. Type *Ty = Tys[D.getArgumentNumber()];
  1256. VectorType *VTy = dyn_cast<VectorType>(Ty);
  1257. assert(VTy && "Expected an argument of Vector Type");
  1258. int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
  1259. return VectorType::getSubdividedVectorType(VTy, SubDivs);
  1260. }
  1261. case IITDescriptor::HalfVecArgument:
  1262. return VectorType::getHalfElementsVectorType(cast<VectorType>(
  1263. Tys[D.getArgumentNumber()]));
  1264. case IITDescriptor::SameVecWidthArgument: {
  1265. Type *EltTy = DecodeFixedType(Infos, Tys, Context);
  1266. Type *Ty = Tys[D.getArgumentNumber()];
  1267. if (auto *VTy = dyn_cast<VectorType>(Ty))
  1268. return VectorType::get(EltTy, VTy->getElementCount());
  1269. return EltTy;
  1270. }
  1271. case IITDescriptor::PtrToArgument: {
  1272. Type *Ty = Tys[D.getArgumentNumber()];
  1273. return PointerType::getUnqual(Ty);
  1274. }
  1275. case IITDescriptor::PtrToElt: {
  1276. Type *Ty = Tys[D.getArgumentNumber()];
  1277. VectorType *VTy = dyn_cast<VectorType>(Ty);
  1278. if (!VTy)
  1279. llvm_unreachable("Expected an argument of Vector Type");
  1280. Type *EltTy = VTy->getElementType();
  1281. return PointerType::getUnqual(EltTy);
  1282. }
  1283. case IITDescriptor::VecElementArgument: {
  1284. Type *Ty = Tys[D.getArgumentNumber()];
  1285. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  1286. return VTy->getElementType();
  1287. llvm_unreachable("Expected an argument of Vector Type");
  1288. }
  1289. case IITDescriptor::VecOfBitcastsToInt: {
  1290. Type *Ty = Tys[D.getArgumentNumber()];
  1291. VectorType *VTy = dyn_cast<VectorType>(Ty);
  1292. assert(VTy && "Expected an argument of Vector Type");
  1293. return VectorType::getInteger(VTy);
  1294. }
  1295. case IITDescriptor::VecOfAnyPtrsToElt:
  1296. // Return the overloaded type (which determines the pointers address space)
  1297. return Tys[D.getOverloadArgNumber()];
  1298. case IITDescriptor::AnyPtrToElt:
  1299. // Return the overloaded type (which determines the pointers address space)
  1300. return Tys[D.getOverloadArgNumber()];
  1301. }
  1302. llvm_unreachable("unhandled");
  1303. }
  1304. FunctionType *Intrinsic::getType(LLVMContext &Context,
  1305. ID id, ArrayRef<Type*> Tys) {
  1306. SmallVector<IITDescriptor, 8> Table;
  1307. getIntrinsicInfoTableEntries(id, Table);
  1308. ArrayRef<IITDescriptor> TableRef = Table;
  1309. Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
  1310. SmallVector<Type*, 8> ArgTys;
  1311. while (!TableRef.empty())
  1312. ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
  1313. // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
  1314. // If we see void type as the type of the last argument, it is vararg intrinsic
  1315. if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
  1316. ArgTys.pop_back();
  1317. return FunctionType::get(ResultTy, ArgTys, true);
  1318. }
  1319. return FunctionType::get(ResultTy, ArgTys, false);
  1320. }
  1321. bool Intrinsic::isOverloaded(ID id) {
  1322. #define GET_INTRINSIC_OVERLOAD_TABLE
  1323. #include "llvm/IR/IntrinsicImpl.inc"
  1324. #undef GET_INTRINSIC_OVERLOAD_TABLE
  1325. }
  1326. /// This defines the "Intrinsic::getAttributes(ID id)" method.
  1327. #define GET_INTRINSIC_ATTRIBUTES
  1328. #include "llvm/IR/IntrinsicImpl.inc"
  1329. #undef GET_INTRINSIC_ATTRIBUTES
  1330. Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
  1331. // There can never be multiple globals with the same name of different types,
  1332. // because intrinsics must be a specific type.
  1333. auto *FT = getType(M->getContext(), id, Tys);
  1334. return cast<Function>(
  1335. M->getOrInsertFunction(
  1336. Tys.empty() ? getName(id) : getName(id, Tys, M, FT), FT)
  1337. .getCallee());
  1338. }
  1339. // This defines the "Intrinsic::getIntrinsicForClangBuiltin()" method.
  1340. #define GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN
  1341. #include "llvm/IR/IntrinsicImpl.inc"
  1342. #undef GET_LLVM_INTRINSIC_FOR_CLANG_BUILTIN
  1343. // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
  1344. #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  1345. #include "llvm/IR/IntrinsicImpl.inc"
  1346. #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
  1347. using DeferredIntrinsicMatchPair =
  1348. std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>;
  1349. static bool matchIntrinsicType(
  1350. Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos,
  1351. SmallVectorImpl<Type *> &ArgTys,
  1352. SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks,
  1353. bool IsDeferredCheck) {
  1354. using namespace Intrinsic;
  1355. // If we ran out of descriptors, there are too many arguments.
  1356. if (Infos.empty()) return true;
  1357. // Do this before slicing off the 'front' part
  1358. auto InfosRef = Infos;
  1359. auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) {
  1360. DeferredChecks.emplace_back(T, InfosRef);
  1361. return false;
  1362. };
  1363. IITDescriptor D = Infos.front();
  1364. Infos = Infos.slice(1);
  1365. switch (D.Kind) {
  1366. case IITDescriptor::Void: return !Ty->isVoidTy();
  1367. case IITDescriptor::VarArg: return true;
  1368. case IITDescriptor::MMX: return !Ty->isX86_MMXTy();
  1369. case IITDescriptor::AMX: return !Ty->isX86_AMXTy();
  1370. case IITDescriptor::Token: return !Ty->isTokenTy();
  1371. case IITDescriptor::Metadata: return !Ty->isMetadataTy();
  1372. case IITDescriptor::Half: return !Ty->isHalfTy();
  1373. case IITDescriptor::BFloat: return !Ty->isBFloatTy();
  1374. case IITDescriptor::Float: return !Ty->isFloatTy();
  1375. case IITDescriptor::Double: return !Ty->isDoubleTy();
  1376. case IITDescriptor::Quad: return !Ty->isFP128Ty();
  1377. case IITDescriptor::PPCQuad: return !Ty->isPPC_FP128Ty();
  1378. case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width);
  1379. case IITDescriptor::Vector: {
  1380. VectorType *VT = dyn_cast<VectorType>(Ty);
  1381. return !VT || VT->getElementCount() != D.Vector_Width ||
  1382. matchIntrinsicType(VT->getElementType(), Infos, ArgTys,
  1383. DeferredChecks, IsDeferredCheck);
  1384. }
  1385. case IITDescriptor::Pointer: {
  1386. PointerType *PT = dyn_cast<PointerType>(Ty);
  1387. if (!PT || PT->getAddressSpace() != D.Pointer_AddressSpace)
  1388. return true;
  1389. if (!PT->isOpaque()) {
  1390. /* Manually consume a pointer to empty struct descriptor, which is
  1391. * used for externref. We don't want to enforce that the struct is
  1392. * anonymous in this case. (This renders externref intrinsics
  1393. * non-unique, but this will go away with opaque pointers anyway.) */
  1394. if (Infos.front().Kind == IITDescriptor::Struct &&
  1395. Infos.front().Struct_NumElements == 0) {
  1396. Infos = Infos.slice(1);
  1397. return false;
  1398. }
  1399. return matchIntrinsicType(PT->getNonOpaquePointerElementType(), Infos,
  1400. ArgTys, DeferredChecks, IsDeferredCheck);
  1401. }
  1402. // Consume IIT descriptors relating to the pointer element type.
  1403. // FIXME: Intrinsic type matching of nested single value types or even
  1404. // aggregates doesn't work properly with opaque pointers but hopefully
  1405. // doesn't happen in practice.
  1406. while (Infos.front().Kind == IITDescriptor::Pointer ||
  1407. Infos.front().Kind == IITDescriptor::Vector)
  1408. Infos = Infos.slice(1);
  1409. assert((Infos.front().Kind != IITDescriptor::Argument ||
  1410. Infos.front().getArgumentKind() == IITDescriptor::AK_MatchType) &&
  1411. "Unsupported polymorphic pointer type with opaque pointer");
  1412. Infos = Infos.slice(1);
  1413. return false;
  1414. }
  1415. case IITDescriptor::Struct: {
  1416. StructType *ST = dyn_cast<StructType>(Ty);
  1417. if (!ST || !ST->isLiteral() || ST->isPacked() ||
  1418. ST->getNumElements() != D.Struct_NumElements)
  1419. return true;
  1420. for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i)
  1421. if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys,
  1422. DeferredChecks, IsDeferredCheck))
  1423. return true;
  1424. return false;
  1425. }
  1426. case IITDescriptor::Argument:
  1427. // If this is the second occurrence of an argument,
  1428. // verify that the later instance matches the previous instance.
  1429. if (D.getArgumentNumber() < ArgTys.size())
  1430. return Ty != ArgTys[D.getArgumentNumber()];
  1431. if (D.getArgumentNumber() > ArgTys.size() ||
  1432. D.getArgumentKind() == IITDescriptor::AK_MatchType)
  1433. return IsDeferredCheck || DeferCheck(Ty);
  1434. assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck &&
  1435. "Table consistency error");
  1436. ArgTys.push_back(Ty);
  1437. switch (D.getArgumentKind()) {
  1438. case IITDescriptor::AK_Any: return false; // Success
  1439. case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy();
  1440. case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy();
  1441. case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty);
  1442. case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty);
  1443. default: break;
  1444. }
  1445. llvm_unreachable("all argument kinds not covered");
  1446. case IITDescriptor::ExtendArgument: {
  1447. // If this is a forward reference, defer the check for later.
  1448. if (D.getArgumentNumber() >= ArgTys.size())
  1449. return IsDeferredCheck || DeferCheck(Ty);
  1450. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1451. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  1452. NewTy = VectorType::getExtendedElementVectorType(VTy);
  1453. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  1454. NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth());
  1455. else
  1456. return true;
  1457. return Ty != NewTy;
  1458. }
  1459. case IITDescriptor::TruncArgument: {
  1460. // If this is a forward reference, defer the check for later.
  1461. if (D.getArgumentNumber() >= ArgTys.size())
  1462. return IsDeferredCheck || DeferCheck(Ty);
  1463. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1464. if (VectorType *VTy = dyn_cast<VectorType>(NewTy))
  1465. NewTy = VectorType::getTruncatedElementVectorType(VTy);
  1466. else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy))
  1467. NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2);
  1468. else
  1469. return true;
  1470. return Ty != NewTy;
  1471. }
  1472. case IITDescriptor::HalfVecArgument:
  1473. // If this is a forward reference, defer the check for later.
  1474. if (D.getArgumentNumber() >= ArgTys.size())
  1475. return IsDeferredCheck || DeferCheck(Ty);
  1476. return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) ||
  1477. VectorType::getHalfElementsVectorType(
  1478. cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty;
  1479. case IITDescriptor::SameVecWidthArgument: {
  1480. if (D.getArgumentNumber() >= ArgTys.size()) {
  1481. // Defer check and subsequent check for the vector element type.
  1482. Infos = Infos.slice(1);
  1483. return IsDeferredCheck || DeferCheck(Ty);
  1484. }
  1485. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1486. auto *ThisArgType = dyn_cast<VectorType>(Ty);
  1487. // Both must be vectors of the same number of elements or neither.
  1488. if ((ReferenceType != nullptr) != (ThisArgType != nullptr))
  1489. return true;
  1490. Type *EltTy = Ty;
  1491. if (ThisArgType) {
  1492. if (ReferenceType->getElementCount() !=
  1493. ThisArgType->getElementCount())
  1494. return true;
  1495. EltTy = ThisArgType->getElementType();
  1496. }
  1497. return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks,
  1498. IsDeferredCheck);
  1499. }
  1500. case IITDescriptor::PtrToArgument: {
  1501. if (D.getArgumentNumber() >= ArgTys.size())
  1502. return IsDeferredCheck || DeferCheck(Ty);
  1503. Type * ReferenceType = ArgTys[D.getArgumentNumber()];
  1504. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  1505. return (!ThisArgType ||
  1506. !ThisArgType->isOpaqueOrPointeeTypeMatches(ReferenceType));
  1507. }
  1508. case IITDescriptor::PtrToElt: {
  1509. if (D.getArgumentNumber() >= ArgTys.size())
  1510. return IsDeferredCheck || DeferCheck(Ty);
  1511. VectorType * ReferenceType =
  1512. dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]);
  1513. PointerType *ThisArgType = dyn_cast<PointerType>(Ty);
  1514. if (!ThisArgType || !ReferenceType)
  1515. return true;
  1516. return !ThisArgType->isOpaqueOrPointeeTypeMatches(
  1517. ReferenceType->getElementType());
  1518. }
  1519. case IITDescriptor::AnyPtrToElt: {
  1520. unsigned RefArgNumber = D.getRefArgNumber();
  1521. if (RefArgNumber >= ArgTys.size()) {
  1522. if (IsDeferredCheck)
  1523. return true;
  1524. // If forward referencing, already add the pointer type and
  1525. // defer the checks for later.
  1526. ArgTys.push_back(Ty);
  1527. return DeferCheck(Ty);
  1528. }
  1529. if (!IsDeferredCheck) {
  1530. assert(D.getOverloadArgNumber() == ArgTys.size() &&
  1531. "Table consistency error");
  1532. ArgTys.push_back(Ty);
  1533. }
  1534. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
  1535. auto *ThisArgType = dyn_cast<PointerType>(Ty);
  1536. if (!ThisArgType || !ReferenceType)
  1537. return true;
  1538. return !ThisArgType->isOpaqueOrPointeeTypeMatches(
  1539. ReferenceType->getElementType());
  1540. }
  1541. case IITDescriptor::VecOfAnyPtrsToElt: {
  1542. unsigned RefArgNumber = D.getRefArgNumber();
  1543. if (RefArgNumber >= ArgTys.size()) {
  1544. if (IsDeferredCheck)
  1545. return true;
  1546. // If forward referencing, already add the pointer-vector type and
  1547. // defer the checks for later.
  1548. ArgTys.push_back(Ty);
  1549. return DeferCheck(Ty);
  1550. }
  1551. if (!IsDeferredCheck){
  1552. assert(D.getOverloadArgNumber() == ArgTys.size() &&
  1553. "Table consistency error");
  1554. ArgTys.push_back(Ty);
  1555. }
  1556. // Verify the overloaded type "matches" the Ref type.
  1557. // i.e. Ty is a vector with the same width as Ref.
  1558. // Composed of pointers to the same element type as Ref.
  1559. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]);
  1560. auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
  1561. if (!ThisArgVecTy || !ReferenceType ||
  1562. (ReferenceType->getElementCount() != ThisArgVecTy->getElementCount()))
  1563. return true;
  1564. PointerType *ThisArgEltTy =
  1565. dyn_cast<PointerType>(ThisArgVecTy->getElementType());
  1566. if (!ThisArgEltTy)
  1567. return true;
  1568. return !ThisArgEltTy->isOpaqueOrPointeeTypeMatches(
  1569. ReferenceType->getElementType());
  1570. }
  1571. case IITDescriptor::VecElementArgument: {
  1572. if (D.getArgumentNumber() >= ArgTys.size())
  1573. return IsDeferredCheck ? true : DeferCheck(Ty);
  1574. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1575. return !ReferenceType || Ty != ReferenceType->getElementType();
  1576. }
  1577. case IITDescriptor::Subdivide2Argument:
  1578. case IITDescriptor::Subdivide4Argument: {
  1579. // If this is a forward reference, defer the check for later.
  1580. if (D.getArgumentNumber() >= ArgTys.size())
  1581. return IsDeferredCheck || DeferCheck(Ty);
  1582. Type *NewTy = ArgTys[D.getArgumentNumber()];
  1583. if (auto *VTy = dyn_cast<VectorType>(NewTy)) {
  1584. int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2;
  1585. NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs);
  1586. return Ty != NewTy;
  1587. }
  1588. return true;
  1589. }
  1590. case IITDescriptor::VecOfBitcastsToInt: {
  1591. if (D.getArgumentNumber() >= ArgTys.size())
  1592. return IsDeferredCheck || DeferCheck(Ty);
  1593. auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]);
  1594. auto *ThisArgVecTy = dyn_cast<VectorType>(Ty);
  1595. if (!ThisArgVecTy || !ReferenceType)
  1596. return true;
  1597. return ThisArgVecTy != VectorType::getInteger(ReferenceType);
  1598. }
  1599. }
  1600. llvm_unreachable("unhandled");
  1601. }
  1602. Intrinsic::MatchIntrinsicTypesResult
  1603. Intrinsic::matchIntrinsicSignature(FunctionType *FTy,
  1604. ArrayRef<Intrinsic::IITDescriptor> &Infos,
  1605. SmallVectorImpl<Type *> &ArgTys) {
  1606. SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks;
  1607. if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks,
  1608. false))
  1609. return MatchIntrinsicTypes_NoMatchRet;
  1610. unsigned NumDeferredReturnChecks = DeferredChecks.size();
  1611. for (auto *Ty : FTy->params())
  1612. if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false))
  1613. return MatchIntrinsicTypes_NoMatchArg;
  1614. for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) {
  1615. DeferredIntrinsicMatchPair &Check = DeferredChecks[I];
  1616. if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks,
  1617. true))
  1618. return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet
  1619. : MatchIntrinsicTypes_NoMatchArg;
  1620. }
  1621. return MatchIntrinsicTypes_Match;
  1622. }
  1623. bool
  1624. Intrinsic::matchIntrinsicVarArg(bool isVarArg,
  1625. ArrayRef<Intrinsic::IITDescriptor> &Infos) {
  1626. // If there are no descriptors left, then it can't be a vararg.
  1627. if (Infos.empty())
  1628. return isVarArg;
  1629. // There should be only one descriptor remaining at this point.
  1630. if (Infos.size() != 1)
  1631. return true;
  1632. // Check and verify the descriptor.
  1633. IITDescriptor D = Infos.front();
  1634. Infos = Infos.slice(1);
  1635. if (D.Kind == IITDescriptor::VarArg)
  1636. return !isVarArg;
  1637. return true;
  1638. }
  1639. bool Intrinsic::getIntrinsicSignature(Function *F,
  1640. SmallVectorImpl<Type *> &ArgTys) {
  1641. Intrinsic::ID ID = F->getIntrinsicID();
  1642. if (!ID)
  1643. return false;
  1644. SmallVector<Intrinsic::IITDescriptor, 8> Table;
  1645. getIntrinsicInfoTableEntries(ID, Table);
  1646. ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
  1647. if (Intrinsic::matchIntrinsicSignature(F->getFunctionType(), TableRef,
  1648. ArgTys) !=
  1649. Intrinsic::MatchIntrinsicTypesResult::MatchIntrinsicTypes_Match) {
  1650. return false;
  1651. }
  1652. if (Intrinsic::matchIntrinsicVarArg(F->getFunctionType()->isVarArg(),
  1653. TableRef))
  1654. return false;
  1655. return true;
  1656. }
  1657. std::optional<Function *> Intrinsic::remangleIntrinsicFunction(Function *F) {
  1658. SmallVector<Type *, 4> ArgTys;
  1659. if (!getIntrinsicSignature(F, ArgTys))
  1660. return std::nullopt;
  1661. Intrinsic::ID ID = F->getIntrinsicID();
  1662. StringRef Name = F->getName();
  1663. std::string WantedName =
  1664. Intrinsic::getName(ID, ArgTys, F->getParent(), F->getFunctionType());
  1665. if (Name == WantedName)
  1666. return std::nullopt;
  1667. Function *NewDecl = [&] {
  1668. if (auto *ExistingGV = F->getParent()->getNamedValue(WantedName)) {
  1669. if (auto *ExistingF = dyn_cast<Function>(ExistingGV))
  1670. if (ExistingF->getFunctionType() == F->getFunctionType())
  1671. return ExistingF;
  1672. // The name already exists, but is not a function or has the wrong
  1673. // prototype. Make place for the new one by renaming the old version.
  1674. // Either this old version will be removed later on or the module is
  1675. // invalid and we'll get an error.
  1676. ExistingGV->setName(WantedName + ".renamed");
  1677. }
  1678. return Intrinsic::getDeclaration(F->getParent(), ID, ArgTys);
  1679. }();
  1680. NewDecl->setCallingConv(F->getCallingConv());
  1681. assert(NewDecl->getFunctionType() == F->getFunctionType() &&
  1682. "Shouldn't change the signature");
  1683. return NewDecl;
  1684. }
  1685. /// hasAddressTaken - returns true if there are any uses of this function
  1686. /// other than direct calls or invokes to it. Optionally ignores callback
  1687. /// uses, assume like pointer annotation calls, and references in llvm.used
  1688. /// and llvm.compiler.used variables.
  1689. bool Function::hasAddressTaken(const User **PutOffender,
  1690. bool IgnoreCallbackUses,
  1691. bool IgnoreAssumeLikeCalls, bool IgnoreLLVMUsed,
  1692. bool IgnoreARCAttachedCall) const {
  1693. for (const Use &U : uses()) {
  1694. const User *FU = U.getUser();
  1695. if (isa<BlockAddress>(FU))
  1696. continue;
  1697. if (IgnoreCallbackUses) {
  1698. AbstractCallSite ACS(&U);
  1699. if (ACS && ACS.isCallbackCall())
  1700. continue;
  1701. }
  1702. const auto *Call = dyn_cast<CallBase>(FU);
  1703. if (!Call) {
  1704. if (IgnoreAssumeLikeCalls &&
  1705. isa<BitCastOperator, AddrSpaceCastOperator>(FU) &&
  1706. all_of(FU->users(), [](const User *U) {
  1707. if (const auto *I = dyn_cast<IntrinsicInst>(U))
  1708. return I->isAssumeLikeIntrinsic();
  1709. return false;
  1710. })) {
  1711. continue;
  1712. }
  1713. if (IgnoreLLVMUsed && !FU->user_empty()) {
  1714. const User *FUU = FU;
  1715. if (isa<BitCastOperator, AddrSpaceCastOperator>(FU) &&
  1716. FU->hasOneUse() && !FU->user_begin()->user_empty())
  1717. FUU = *FU->user_begin();
  1718. if (llvm::all_of(FUU->users(), [](const User *U) {
  1719. if (const auto *GV = dyn_cast<GlobalVariable>(U))
  1720. return GV->hasName() &&
  1721. (GV->getName().equals("llvm.compiler.used") ||
  1722. GV->getName().equals("llvm.used"));
  1723. return false;
  1724. }))
  1725. continue;
  1726. }
  1727. if (PutOffender)
  1728. *PutOffender = FU;
  1729. return true;
  1730. }
  1731. if (IgnoreAssumeLikeCalls) {
  1732. if (const auto *I = dyn_cast<IntrinsicInst>(Call))
  1733. if (I->isAssumeLikeIntrinsic())
  1734. continue;
  1735. }
  1736. if (!Call->isCallee(&U) || Call->getFunctionType() != getFunctionType()) {
  1737. if (IgnoreARCAttachedCall &&
  1738. Call->isOperandBundleOfType(LLVMContext::OB_clang_arc_attachedcall,
  1739. U.getOperandNo()))
  1740. continue;
  1741. if (PutOffender)
  1742. *PutOffender = FU;
  1743. return true;
  1744. }
  1745. }
  1746. return false;
  1747. }
  1748. bool Function::isDefTriviallyDead() const {
  1749. // Check the linkage
  1750. if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
  1751. !hasAvailableExternallyLinkage())
  1752. return false;
  1753. // Check if the function is used by anything other than a blockaddress.
  1754. for (const User *U : users())
  1755. if (!isa<BlockAddress>(U))
  1756. return false;
  1757. return true;
  1758. }
  1759. /// callsFunctionThatReturnsTwice - Return true if the function has a call to
  1760. /// setjmp or other function that gcc recognizes as "returning twice".
  1761. bool Function::callsFunctionThatReturnsTwice() const {
  1762. for (const Instruction &I : instructions(this))
  1763. if (const auto *Call = dyn_cast<CallBase>(&I))
  1764. if (Call->hasFnAttr(Attribute::ReturnsTwice))
  1765. return true;
  1766. return false;
  1767. }
  1768. Constant *Function::getPersonalityFn() const {
  1769. assert(hasPersonalityFn() && getNumOperands());
  1770. return cast<Constant>(Op<0>());
  1771. }
  1772. void Function::setPersonalityFn(Constant *Fn) {
  1773. setHungoffOperand<0>(Fn);
  1774. setValueSubclassDataBit(3, Fn != nullptr);
  1775. }
  1776. Constant *Function::getPrefixData() const {
  1777. assert(hasPrefixData() && getNumOperands());
  1778. return cast<Constant>(Op<1>());
  1779. }
  1780. void Function::setPrefixData(Constant *PrefixData) {
  1781. setHungoffOperand<1>(PrefixData);
  1782. setValueSubclassDataBit(1, PrefixData != nullptr);
  1783. }
  1784. Constant *Function::getPrologueData() const {
  1785. assert(hasPrologueData() && getNumOperands());
  1786. return cast<Constant>(Op<2>());
  1787. }
  1788. void Function::setPrologueData(Constant *PrologueData) {
  1789. setHungoffOperand<2>(PrologueData);
  1790. setValueSubclassDataBit(2, PrologueData != nullptr);
  1791. }
  1792. void Function::allocHungoffUselist() {
  1793. // If we've already allocated a uselist, stop here.
  1794. if (getNumOperands())
  1795. return;
  1796. allocHungoffUses(3, /*IsPhi=*/ false);
  1797. setNumHungOffUseOperands(3);
  1798. // Initialize the uselist with placeholder operands to allow traversal.
  1799. auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0));
  1800. Op<0>().set(CPN);
  1801. Op<1>().set(CPN);
  1802. Op<2>().set(CPN);
  1803. }
  1804. template <int Idx>
  1805. void Function::setHungoffOperand(Constant *C) {
  1806. if (C) {
  1807. allocHungoffUselist();
  1808. Op<Idx>().set(C);
  1809. } else if (getNumOperands()) {
  1810. Op<Idx>().set(
  1811. ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)));
  1812. }
  1813. }
  1814. void Function::setValueSubclassDataBit(unsigned Bit, bool On) {
  1815. assert(Bit < 16 && "SubclassData contains only 16 bits");
  1816. if (On)
  1817. setValueSubclassData(getSubclassDataFromValue() | (1 << Bit));
  1818. else
  1819. setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit));
  1820. }
  1821. void Function::setEntryCount(ProfileCount Count,
  1822. const DenseSet<GlobalValue::GUID> *S) {
  1823. #if !defined(NDEBUG)
  1824. auto PrevCount = getEntryCount();
  1825. assert(!PrevCount || PrevCount->getType() == Count.getType());
  1826. #endif
  1827. auto ImportGUIDs = getImportGUIDs();
  1828. if (S == nullptr && ImportGUIDs.size())
  1829. S = &ImportGUIDs;
  1830. MDBuilder MDB(getContext());
  1831. setMetadata(
  1832. LLVMContext::MD_prof,
  1833. MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S));
  1834. }
  1835. void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type,
  1836. const DenseSet<GlobalValue::GUID> *Imports) {
  1837. setEntryCount(ProfileCount(Count, Type), Imports);
  1838. }
  1839. std::optional<ProfileCount> Function::getEntryCount(bool AllowSynthetic) const {
  1840. MDNode *MD = getMetadata(LLVMContext::MD_prof);
  1841. if (MD && MD->getOperand(0))
  1842. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) {
  1843. if (MDS->getString().equals("function_entry_count")) {
  1844. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1845. uint64_t Count = CI->getValue().getZExtValue();
  1846. // A value of -1 is used for SamplePGO when there were no samples.
  1847. // Treat this the same as unknown.
  1848. if (Count == (uint64_t)-1)
  1849. return std::nullopt;
  1850. return ProfileCount(Count, PCT_Real);
  1851. } else if (AllowSynthetic &&
  1852. MDS->getString().equals("synthetic_function_entry_count")) {
  1853. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
  1854. uint64_t Count = CI->getValue().getZExtValue();
  1855. return ProfileCount(Count, PCT_Synthetic);
  1856. }
  1857. }
  1858. return std::nullopt;
  1859. }
  1860. DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const {
  1861. DenseSet<GlobalValue::GUID> R;
  1862. if (MDNode *MD = getMetadata(LLVMContext::MD_prof))
  1863. if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
  1864. if (MDS->getString().equals("function_entry_count"))
  1865. for (unsigned i = 2; i < MD->getNumOperands(); i++)
  1866. R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i))
  1867. ->getValue()
  1868. .getZExtValue());
  1869. return R;
  1870. }
  1871. void Function::setSectionPrefix(StringRef Prefix) {
  1872. MDBuilder MDB(getContext());
  1873. setMetadata(LLVMContext::MD_section_prefix,
  1874. MDB.createFunctionSectionPrefix(Prefix));
  1875. }
  1876. std::optional<StringRef> Function::getSectionPrefix() const {
  1877. if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) {
  1878. assert(cast<MDString>(MD->getOperand(0))
  1879. ->getString()
  1880. .equals("function_section_prefix") &&
  1881. "Metadata not match");
  1882. return cast<MDString>(MD->getOperand(1))->getString();
  1883. }
  1884. return std::nullopt;
  1885. }
  1886. bool Function::nullPointerIsDefined() const {
  1887. return hasFnAttribute(Attribute::NullPointerIsValid);
  1888. }
  1889. bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) {
  1890. if (F && F->nullPointerIsDefined())
  1891. return true;
  1892. if (AS != 0)
  1893. return true;
  1894. return false;
  1895. }