Function.cpp 35 KB

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