Function.cpp 62 KB

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