DebugInfoMetadata.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  1. //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===//
  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 debug info Metadata classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/DebugInfoMetadata.h"
  13. #include "LLVMContextImpl.h"
  14. #include "MetadataImpl.h"
  15. #include "llvm/ADT/SmallSet.h"
  16. #include "llvm/ADT/StringSwitch.h"
  17. #include "llvm/IR/DIBuilder.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include <numeric>
  21. using namespace llvm;
  22. DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
  23. unsigned Column, ArrayRef<Metadata *> MDs,
  24. bool ImplicitCode)
  25. : MDNode(C, DILocationKind, Storage, MDs) {
  26. assert((MDs.size() == 1 || MDs.size() == 2) &&
  27. "Expected a scope and optional inlined-at");
  28. // Set line and column.
  29. assert(Column < (1u << 16) && "Expected 16-bit column");
  30. SubclassData32 = Line;
  31. SubclassData16 = Column;
  32. setImplicitCode(ImplicitCode);
  33. }
  34. static void adjustColumn(unsigned &Column) {
  35. // Set to unknown on overflow. We only have 16 bits to play with here.
  36. if (Column >= (1u << 16))
  37. Column = 0;
  38. }
  39. DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
  40. unsigned Column, Metadata *Scope,
  41. Metadata *InlinedAt, bool ImplicitCode,
  42. StorageType Storage, bool ShouldCreate) {
  43. // Fixup column.
  44. adjustColumn(Column);
  45. if (Storage == Uniqued) {
  46. if (auto *N = getUniqued(Context.pImpl->DILocations,
  47. DILocationInfo::KeyTy(Line, Column, Scope,
  48. InlinedAt, ImplicitCode)))
  49. return N;
  50. if (!ShouldCreate)
  51. return nullptr;
  52. } else {
  53. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  54. }
  55. SmallVector<Metadata *, 2> Ops;
  56. Ops.push_back(Scope);
  57. if (InlinedAt)
  58. Ops.push_back(InlinedAt);
  59. return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column,
  60. Ops, ImplicitCode),
  61. Storage, Context.pImpl->DILocations);
  62. }
  63. const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
  64. const DILocation *LocB) {
  65. if (!LocA || !LocB)
  66. return nullptr;
  67. if (LocA == LocB)
  68. return LocA;
  69. SmallPtrSet<DILocation *, 5> InlinedLocationsA;
  70. for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
  71. InlinedLocationsA.insert(L);
  72. SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
  73. DIScope *S = LocA->getScope();
  74. DILocation *L = LocA->getInlinedAt();
  75. while (S) {
  76. Locations.insert(std::make_pair(S, L));
  77. S = S->getScope();
  78. if (!S && L) {
  79. S = L->getScope();
  80. L = L->getInlinedAt();
  81. }
  82. }
  83. const DILocation *Result = LocB;
  84. S = LocB->getScope();
  85. L = LocB->getInlinedAt();
  86. while (S) {
  87. if (Locations.count(std::make_pair(S, L)))
  88. break;
  89. S = S->getScope();
  90. if (!S && L) {
  91. S = L->getScope();
  92. L = L->getInlinedAt();
  93. }
  94. }
  95. // If the two locations are irreconsilable, just pick one. This is misleading,
  96. // but on the other hand, it's a "line 0" location.
  97. if (!S || !isa<DILocalScope>(S))
  98. S = LocA->getScope();
  99. return DILocation::get(Result->getContext(), 0, 0, S, L);
  100. }
  101. Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) {
  102. SmallVector<unsigned, 3> Components = {BD, DF, CI};
  103. uint64_t RemainingWork = 0U;
  104. // We use RemainingWork to figure out if we have no remaining components to
  105. // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
  106. // encode anything for the latter 2.
  107. // Since any of the input components is at most 32 bits, their sum will be
  108. // less than 34 bits, and thus RemainingWork won't overflow.
  109. RemainingWork = std::accumulate(Components.begin(), Components.end(), RemainingWork);
  110. int I = 0;
  111. unsigned Ret = 0;
  112. unsigned NextBitInsertionIndex = 0;
  113. while (RemainingWork > 0) {
  114. unsigned C = Components[I++];
  115. RemainingWork -= C;
  116. unsigned EC = encodeComponent(C);
  117. Ret |= (EC << NextBitInsertionIndex);
  118. NextBitInsertionIndex += encodingBits(C);
  119. }
  120. // Encoding may be unsuccessful because of overflow. We determine success by
  121. // checking equivalence of components before & after encoding. Alternatively,
  122. // we could determine Success during encoding, but the current alternative is
  123. // simpler.
  124. unsigned TBD, TDF, TCI = 0;
  125. decodeDiscriminator(Ret, TBD, TDF, TCI);
  126. if (TBD == BD && TDF == DF && TCI == CI)
  127. return Ret;
  128. return None;
  129. }
  130. void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
  131. unsigned &CI) {
  132. BD = getUnsignedFromPrefixEncoding(D);
  133. DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
  134. CI = getUnsignedFromPrefixEncoding(
  135. getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
  136. }
  137. DINode::DIFlags DINode::getFlag(StringRef Flag) {
  138. return StringSwitch<DIFlags>(Flag)
  139. #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
  140. #include "llvm/IR/DebugInfoFlags.def"
  141. .Default(DINode::FlagZero);
  142. }
  143. StringRef DINode::getFlagString(DIFlags Flag) {
  144. switch (Flag) {
  145. #define HANDLE_DI_FLAG(ID, NAME) \
  146. case Flag##NAME: \
  147. return "DIFlag" #NAME;
  148. #include "llvm/IR/DebugInfoFlags.def"
  149. }
  150. return "";
  151. }
  152. DINode::DIFlags DINode::splitFlags(DIFlags Flags,
  153. SmallVectorImpl<DIFlags> &SplitFlags) {
  154. // Flags that are packed together need to be specially handled, so
  155. // that, for example, we emit "DIFlagPublic" and not
  156. // "DIFlagPrivate | DIFlagProtected".
  157. if (DIFlags A = Flags & FlagAccessibility) {
  158. if (A == FlagPrivate)
  159. SplitFlags.push_back(FlagPrivate);
  160. else if (A == FlagProtected)
  161. SplitFlags.push_back(FlagProtected);
  162. else
  163. SplitFlags.push_back(FlagPublic);
  164. Flags &= ~A;
  165. }
  166. if (DIFlags R = Flags & FlagPtrToMemberRep) {
  167. if (R == FlagSingleInheritance)
  168. SplitFlags.push_back(FlagSingleInheritance);
  169. else if (R == FlagMultipleInheritance)
  170. SplitFlags.push_back(FlagMultipleInheritance);
  171. else
  172. SplitFlags.push_back(FlagVirtualInheritance);
  173. Flags &= ~R;
  174. }
  175. if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
  176. Flags &= ~FlagIndirectVirtualBase;
  177. SplitFlags.push_back(FlagIndirectVirtualBase);
  178. }
  179. #define HANDLE_DI_FLAG(ID, NAME) \
  180. if (DIFlags Bit = Flags & Flag##NAME) { \
  181. SplitFlags.push_back(Bit); \
  182. Flags &= ~Bit; \
  183. }
  184. #include "llvm/IR/DebugInfoFlags.def"
  185. return Flags;
  186. }
  187. DIScope *DIScope::getScope() const {
  188. if (auto *T = dyn_cast<DIType>(this))
  189. return T->getScope();
  190. if (auto *SP = dyn_cast<DISubprogram>(this))
  191. return SP->getScope();
  192. if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
  193. return LB->getScope();
  194. if (auto *NS = dyn_cast<DINamespace>(this))
  195. return NS->getScope();
  196. if (auto *CB = dyn_cast<DICommonBlock>(this))
  197. return CB->getScope();
  198. if (auto *M = dyn_cast<DIModule>(this))
  199. return M->getScope();
  200. assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
  201. "Unhandled type of scope.");
  202. return nullptr;
  203. }
  204. StringRef DIScope::getName() const {
  205. if (auto *T = dyn_cast<DIType>(this))
  206. return T->getName();
  207. if (auto *SP = dyn_cast<DISubprogram>(this))
  208. return SP->getName();
  209. if (auto *NS = dyn_cast<DINamespace>(this))
  210. return NS->getName();
  211. if (auto *CB = dyn_cast<DICommonBlock>(this))
  212. return CB->getName();
  213. if (auto *M = dyn_cast<DIModule>(this))
  214. return M->getName();
  215. assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
  216. isa<DICompileUnit>(this)) &&
  217. "Unhandled type of scope.");
  218. return "";
  219. }
  220. #ifndef NDEBUG
  221. static bool isCanonical(const MDString *S) {
  222. return !S || !S->getString().empty();
  223. }
  224. #endif
  225. GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
  226. MDString *Header,
  227. ArrayRef<Metadata *> DwarfOps,
  228. StorageType Storage, bool ShouldCreate) {
  229. unsigned Hash = 0;
  230. if (Storage == Uniqued) {
  231. GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
  232. if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
  233. return N;
  234. if (!ShouldCreate)
  235. return nullptr;
  236. Hash = Key.getHash();
  237. } else {
  238. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  239. }
  240. // Use a nullptr for empty headers.
  241. assert(isCanonical(Header) && "Expected canonical MDString");
  242. Metadata *PreOps[] = {Header};
  243. return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
  244. Context, Storage, Hash, Tag, PreOps, DwarfOps),
  245. Storage, Context.pImpl->GenericDINodes);
  246. }
  247. void GenericDINode::recalculateHash() {
  248. setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
  249. }
  250. #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
  251. #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
  252. #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS) \
  253. do { \
  254. if (Storage == Uniqued) { \
  255. if (auto *N = getUniqued(Context.pImpl->CLASS##s, \
  256. CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS)))) \
  257. return N; \
  258. if (!ShouldCreate) \
  259. return nullptr; \
  260. } else { \
  261. assert(ShouldCreate && \
  262. "Expected non-uniqued nodes to always be created"); \
  263. } \
  264. } while (false)
  265. #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \
  266. return storeImpl(new (array_lengthof(OPS)) \
  267. CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \
  268. Storage, Context.pImpl->CLASS##s)
  269. #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \
  270. return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \
  271. Storage, Context.pImpl->CLASS##s)
  272. #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \
  273. return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS), \
  274. Storage, Context.pImpl->CLASS##s)
  275. #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS) \
  276. return storeImpl(new (NUM_OPS) \
  277. CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \
  278. Storage, Context.pImpl->CLASS##s)
  279. DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
  280. StorageType Storage, bool ShouldCreate) {
  281. auto *CountNode = ConstantAsMetadata::get(
  282. ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
  283. return getImpl(Context, CountNode, Lo, Storage, ShouldCreate);
  284. }
  285. DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
  286. int64_t Lo, StorageType Storage,
  287. bool ShouldCreate) {
  288. DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, Lo));
  289. Metadata *Ops[] = { CountNode };
  290. DEFINE_GETIMPL_STORE(DISubrange, (CountNode, Lo), Ops);
  291. }
  292. DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, int64_t Value,
  293. bool IsUnsigned, MDString *Name,
  294. StorageType Storage, bool ShouldCreate) {
  295. assert(isCanonical(Name) && "Expected canonical MDString");
  296. DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
  297. Metadata *Ops[] = {Name};
  298. DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
  299. }
  300. DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
  301. MDString *Name, uint64_t SizeInBits,
  302. uint32_t AlignInBits, unsigned Encoding,
  303. DIFlags Flags, StorageType Storage,
  304. bool ShouldCreate) {
  305. assert(isCanonical(Name) && "Expected canonical MDString");
  306. DEFINE_GETIMPL_LOOKUP(DIBasicType,
  307. (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
  308. Metadata *Ops[] = {nullptr, nullptr, Name};
  309. DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding,
  310. Flags), Ops);
  311. }
  312. Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
  313. switch (getEncoding()) {
  314. case dwarf::DW_ATE_signed:
  315. case dwarf::DW_ATE_signed_char:
  316. return Signedness::Signed;
  317. case dwarf::DW_ATE_unsigned:
  318. case dwarf::DW_ATE_unsigned_char:
  319. return Signedness::Unsigned;
  320. default:
  321. return None;
  322. }
  323. }
  324. DIDerivedType *DIDerivedType::getImpl(
  325. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
  326. unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
  327. uint32_t AlignInBits, uint64_t OffsetInBits,
  328. Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
  329. StorageType Storage, bool ShouldCreate) {
  330. assert(isCanonical(Name) && "Expected canonical MDString");
  331. DEFINE_GETIMPL_LOOKUP(DIDerivedType,
  332. (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  333. AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
  334. ExtraData));
  335. Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
  336. DEFINE_GETIMPL_STORE(
  337. DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
  338. DWARFAddressSpace, Flags), Ops);
  339. }
  340. DICompositeType *DICompositeType::getImpl(
  341. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
  342. unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
  343. uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
  344. Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
  345. Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
  346. StorageType Storage, bool ShouldCreate) {
  347. assert(isCanonical(Name) && "Expected canonical MDString");
  348. // Keep this in sync with buildODRType.
  349. DEFINE_GETIMPL_LOOKUP(
  350. DICompositeType, (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  351. AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  352. VTableHolder, TemplateParams, Identifier, Discriminator));
  353. Metadata *Ops[] = {File, Scope, Name, BaseType,
  354. Elements, VTableHolder, TemplateParams, Identifier,
  355. Discriminator};
  356. DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
  357. AlignInBits, OffsetInBits, Flags),
  358. Ops);
  359. }
  360. DICompositeType *DICompositeType::buildODRType(
  361. LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
  362. Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
  363. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  364. DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
  365. Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator) {
  366. assert(!Identifier.getString().empty() && "Expected valid identifier");
  367. if (!Context.isODRUniquingDebugTypes())
  368. return nullptr;
  369. auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
  370. if (!CT)
  371. return CT = DICompositeType::getDistinct(
  372. Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  373. AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  374. VTableHolder, TemplateParams, &Identifier, Discriminator);
  375. // Only mutate CT if it's a forward declaration and the new operands aren't.
  376. assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
  377. if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
  378. return CT;
  379. // Mutate CT in place. Keep this in sync with getImpl.
  380. CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
  381. Flags);
  382. Metadata *Ops[] = {File, Scope, Name, BaseType,
  383. Elements, VTableHolder, TemplateParams, &Identifier,
  384. Discriminator};
  385. assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
  386. "Mismatched number of operands");
  387. for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
  388. if (Ops[I] != CT->getOperand(I))
  389. CT->setOperand(I, Ops[I]);
  390. return CT;
  391. }
  392. DICompositeType *DICompositeType::getODRType(
  393. LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
  394. Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
  395. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  396. DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
  397. Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator) {
  398. assert(!Identifier.getString().empty() && "Expected valid identifier");
  399. if (!Context.isODRUniquingDebugTypes())
  400. return nullptr;
  401. auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
  402. if (!CT)
  403. CT = DICompositeType::getDistinct(
  404. Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  405. AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
  406. TemplateParams, &Identifier, Discriminator);
  407. return CT;
  408. }
  409. DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
  410. MDString &Identifier) {
  411. assert(!Identifier.getString().empty() && "Expected valid identifier");
  412. if (!Context.isODRUniquingDebugTypes())
  413. return nullptr;
  414. return Context.pImpl->DITypeMap->lookup(&Identifier);
  415. }
  416. DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
  417. uint8_t CC, Metadata *TypeArray,
  418. StorageType Storage,
  419. bool ShouldCreate) {
  420. DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
  421. Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
  422. DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
  423. }
  424. // FIXME: Implement this string-enum correspondence with a .def file and macros,
  425. // so that the association is explicit rather than implied.
  426. static const char *ChecksumKindName[DIFile::CSK_Last] = {
  427. "CSK_MD5",
  428. "CSK_SHA1"
  429. };
  430. StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
  431. assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
  432. // The first space was originally the CSK_None variant, which is now
  433. // obsolete, but the space is still reserved in ChecksumKind, so we account
  434. // for it here.
  435. return ChecksumKindName[CSKind - 1];
  436. }
  437. Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
  438. return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
  439. .Case("CSK_MD5", DIFile::CSK_MD5)
  440. .Case("CSK_SHA1", DIFile::CSK_SHA1)
  441. .Default(None);
  442. }
  443. DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
  444. MDString *Directory,
  445. Optional<DIFile::ChecksumInfo<MDString *>> CS,
  446. Optional<MDString *> Source, StorageType Storage,
  447. bool ShouldCreate) {
  448. assert(isCanonical(Filename) && "Expected canonical MDString");
  449. assert(isCanonical(Directory) && "Expected canonical MDString");
  450. assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
  451. assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
  452. DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
  453. Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
  454. Source.getValueOr(nullptr)};
  455. DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
  456. }
  457. DICompileUnit *DICompileUnit::getImpl(
  458. LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
  459. MDString *Producer, bool IsOptimized, MDString *Flags,
  460. unsigned RuntimeVersion, MDString *SplitDebugFilename,
  461. unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
  462. Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
  463. uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
  464. unsigned NameTableKind, bool RangesBaseAddress, StorageType Storage,
  465. bool ShouldCreate) {
  466. assert(Storage != Uniqued && "Cannot unique DICompileUnit");
  467. assert(isCanonical(Producer) && "Expected canonical MDString");
  468. assert(isCanonical(Flags) && "Expected canonical MDString");
  469. assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
  470. Metadata *Ops[] = {
  471. File, Producer, Flags, SplitDebugFilename,
  472. EnumTypes, RetainedTypes, GlobalVariables, ImportedEntities,
  473. Macros};
  474. return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
  475. Context, Storage, SourceLanguage, IsOptimized,
  476. RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
  477. DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
  478. Ops),
  479. Storage);
  480. }
  481. Optional<DICompileUnit::DebugEmissionKind>
  482. DICompileUnit::getEmissionKind(StringRef Str) {
  483. return StringSwitch<Optional<DebugEmissionKind>>(Str)
  484. .Case("NoDebug", NoDebug)
  485. .Case("FullDebug", FullDebug)
  486. .Case("LineTablesOnly", LineTablesOnly)
  487. .Case("DebugDirectivesOnly", DebugDirectivesOnly)
  488. .Default(None);
  489. }
  490. Optional<DICompileUnit::DebugNameTableKind>
  491. DICompileUnit::getNameTableKind(StringRef Str) {
  492. return StringSwitch<Optional<DebugNameTableKind>>(Str)
  493. .Case("Default", DebugNameTableKind::Default)
  494. .Case("GNU", DebugNameTableKind::GNU)
  495. .Case("None", DebugNameTableKind::None)
  496. .Default(None);
  497. }
  498. const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
  499. switch (EK) {
  500. case NoDebug: return "NoDebug";
  501. case FullDebug: return "FullDebug";
  502. case LineTablesOnly: return "LineTablesOnly";
  503. case DebugDirectivesOnly: return "DebugDirectivesOnly";
  504. }
  505. return nullptr;
  506. }
  507. const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
  508. switch (NTK) {
  509. case DebugNameTableKind::Default:
  510. return nullptr;
  511. case DebugNameTableKind::GNU:
  512. return "GNU";
  513. case DebugNameTableKind::None:
  514. return "None";
  515. }
  516. return nullptr;
  517. }
  518. DISubprogram *DILocalScope::getSubprogram() const {
  519. if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
  520. return Block->getScope()->getSubprogram();
  521. return const_cast<DISubprogram *>(cast<DISubprogram>(this));
  522. }
  523. DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
  524. if (auto *File = dyn_cast<DILexicalBlockFile>(this))
  525. return File->getScope()->getNonLexicalBlockFileScope();
  526. return const_cast<DILocalScope *>(this);
  527. }
  528. DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
  529. return StringSwitch<DISPFlags>(Flag)
  530. #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
  531. #include "llvm/IR/DebugInfoFlags.def"
  532. .Default(SPFlagZero);
  533. }
  534. StringRef DISubprogram::getFlagString(DISPFlags Flag) {
  535. switch (Flag) {
  536. // Appease a warning.
  537. case SPFlagVirtuality:
  538. return "";
  539. #define HANDLE_DISP_FLAG(ID, NAME) \
  540. case SPFlag##NAME: \
  541. return "DISPFlag" #NAME;
  542. #include "llvm/IR/DebugInfoFlags.def"
  543. }
  544. return "";
  545. }
  546. DISubprogram::DISPFlags
  547. DISubprogram::splitFlags(DISPFlags Flags,
  548. SmallVectorImpl<DISPFlags> &SplitFlags) {
  549. // Multi-bit fields can require special handling. In our case, however, the
  550. // only multi-bit field is virtuality, and all its values happen to be
  551. // single-bit values, so the right behavior just falls out.
  552. #define HANDLE_DISP_FLAG(ID, NAME) \
  553. if (DISPFlags Bit = Flags & SPFlag##NAME) { \
  554. SplitFlags.push_back(Bit); \
  555. Flags &= ~Bit; \
  556. }
  557. #include "llvm/IR/DebugInfoFlags.def"
  558. return Flags;
  559. }
  560. DISubprogram *DISubprogram::getImpl(
  561. LLVMContext &Context, Metadata *Scope, MDString *Name,
  562. MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
  563. unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
  564. int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
  565. Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
  566. Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) {
  567. assert(isCanonical(Name) && "Expected canonical MDString");
  568. assert(isCanonical(LinkageName) && "Expected canonical MDString");
  569. DEFINE_GETIMPL_LOOKUP(DISubprogram,
  570. (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
  571. ContainingType, VirtualIndex, ThisAdjustment, Flags,
  572. SPFlags, Unit, TemplateParams, Declaration,
  573. RetainedNodes, ThrownTypes));
  574. SmallVector<Metadata *, 11> Ops = {
  575. File, Scope, Name, LinkageName, Type, Unit,
  576. Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes};
  577. if (!ThrownTypes) {
  578. Ops.pop_back();
  579. if (!TemplateParams) {
  580. Ops.pop_back();
  581. if (!ContainingType)
  582. Ops.pop_back();
  583. }
  584. }
  585. DEFINE_GETIMPL_STORE_N(
  586. DISubprogram,
  587. (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
  588. Ops.size());
  589. }
  590. bool DISubprogram::describes(const Function *F) const {
  591. assert(F && "Invalid function");
  592. if (F->getSubprogram() == this)
  593. return true;
  594. StringRef Name = getLinkageName();
  595. if (Name.empty())
  596. Name = getName();
  597. return F->getName() == Name;
  598. }
  599. DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
  600. Metadata *File, unsigned Line,
  601. unsigned Column, StorageType Storage,
  602. bool ShouldCreate) {
  603. // Fixup column.
  604. adjustColumn(Column);
  605. assert(Scope && "Expected scope");
  606. DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
  607. Metadata *Ops[] = {File, Scope};
  608. DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
  609. }
  610. DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
  611. Metadata *Scope, Metadata *File,
  612. unsigned Discriminator,
  613. StorageType Storage,
  614. bool ShouldCreate) {
  615. assert(Scope && "Expected scope");
  616. DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
  617. Metadata *Ops[] = {File, Scope};
  618. DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
  619. }
  620. DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
  621. MDString *Name, bool ExportSymbols,
  622. StorageType Storage, bool ShouldCreate) {
  623. assert(isCanonical(Name) && "Expected canonical MDString");
  624. DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
  625. // The nullptr is for DIScope's File operand. This should be refactored.
  626. Metadata *Ops[] = {nullptr, Scope, Name};
  627. DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
  628. }
  629. DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
  630. Metadata *Decl, MDString *Name,
  631. Metadata *File, unsigned LineNo,
  632. StorageType Storage, bool ShouldCreate) {
  633. assert(isCanonical(Name) && "Expected canonical MDString");
  634. DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
  635. // The nullptr is for DIScope's File operand. This should be refactored.
  636. Metadata *Ops[] = {Scope, Decl, Name, File};
  637. DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
  638. }
  639. DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *Scope,
  640. MDString *Name, MDString *ConfigurationMacros,
  641. MDString *IncludePath, MDString *ISysRoot,
  642. StorageType Storage, bool ShouldCreate) {
  643. assert(isCanonical(Name) && "Expected canonical MDString");
  644. DEFINE_GETIMPL_LOOKUP(
  645. DIModule, (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot));
  646. Metadata *Ops[] = {Scope, Name, ConfigurationMacros, IncludePath, ISysRoot};
  647. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIModule, Ops);
  648. }
  649. DITemplateTypeParameter *DITemplateTypeParameter::getImpl(LLVMContext &Context,
  650. MDString *Name,
  651. Metadata *Type,
  652. StorageType Storage,
  653. bool ShouldCreate) {
  654. assert(isCanonical(Name) && "Expected canonical MDString");
  655. DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type));
  656. Metadata *Ops[] = {Name, Type};
  657. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DITemplateTypeParameter, Ops);
  658. }
  659. DITemplateValueParameter *DITemplateValueParameter::getImpl(
  660. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
  661. Metadata *Value, StorageType Storage, bool ShouldCreate) {
  662. assert(isCanonical(Name) && "Expected canonical MDString");
  663. DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, (Tag, Name, Type, Value));
  664. Metadata *Ops[] = {Name, Type, Value};
  665. DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag), Ops);
  666. }
  667. DIGlobalVariable *
  668. DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
  669. MDString *LinkageName, Metadata *File, unsigned Line,
  670. Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
  671. Metadata *StaticDataMemberDeclaration,
  672. Metadata *TemplateParams, uint32_t AlignInBits,
  673. StorageType Storage, bool ShouldCreate) {
  674. assert(isCanonical(Name) && "Expected canonical MDString");
  675. assert(isCanonical(LinkageName) && "Expected canonical MDString");
  676. DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
  677. Type, IsLocalToUnit, IsDefinition,
  678. StaticDataMemberDeclaration,
  679. TemplateParams, AlignInBits));
  680. Metadata *Ops[] = {Scope,
  681. Name,
  682. File,
  683. Type,
  684. Name,
  685. LinkageName,
  686. StaticDataMemberDeclaration,
  687. TemplateParams};
  688. DEFINE_GETIMPL_STORE(DIGlobalVariable,
  689. (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
  690. }
  691. DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
  692. MDString *Name, Metadata *File,
  693. unsigned Line, Metadata *Type,
  694. unsigned Arg, DIFlags Flags,
  695. uint32_t AlignInBits,
  696. StorageType Storage,
  697. bool ShouldCreate) {
  698. // 64K ought to be enough for any frontend.
  699. assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
  700. assert(Scope && "Expected scope");
  701. assert(isCanonical(Name) && "Expected canonical MDString");
  702. DEFINE_GETIMPL_LOOKUP(DILocalVariable,
  703. (Scope, Name, File, Line, Type, Arg, Flags,
  704. AlignInBits));
  705. Metadata *Ops[] = {Scope, Name, File, Type};
  706. DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
  707. }
  708. Optional<uint64_t> DIVariable::getSizeInBits() const {
  709. // This is used by the Verifier so be mindful of broken types.
  710. const Metadata *RawType = getRawType();
  711. while (RawType) {
  712. // Try to get the size directly.
  713. if (auto *T = dyn_cast<DIType>(RawType))
  714. if (uint64_t Size = T->getSizeInBits())
  715. return Size;
  716. if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
  717. // Look at the base type.
  718. RawType = DT->getRawBaseType();
  719. continue;
  720. }
  721. // Missing type or size.
  722. break;
  723. }
  724. // Fail gracefully.
  725. return None;
  726. }
  727. DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
  728. MDString *Name, Metadata *File, unsigned Line,
  729. StorageType Storage,
  730. bool ShouldCreate) {
  731. assert(Scope && "Expected scope");
  732. assert(isCanonical(Name) && "Expected canonical MDString");
  733. DEFINE_GETIMPL_LOOKUP(DILabel,
  734. (Scope, Name, File, Line));
  735. Metadata *Ops[] = {Scope, Name, File};
  736. DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
  737. }
  738. DIExpression *DIExpression::getImpl(LLVMContext &Context,
  739. ArrayRef<uint64_t> Elements,
  740. StorageType Storage, bool ShouldCreate) {
  741. DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
  742. DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
  743. }
  744. unsigned DIExpression::ExprOperand::getSize() const {
  745. switch (getOp()) {
  746. case dwarf::DW_OP_LLVM_convert:
  747. case dwarf::DW_OP_LLVM_fragment:
  748. return 3;
  749. case dwarf::DW_OP_constu:
  750. case dwarf::DW_OP_deref_size:
  751. case dwarf::DW_OP_plus_uconst:
  752. return 2;
  753. default:
  754. return 1;
  755. }
  756. }
  757. bool DIExpression::isValid() const {
  758. for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
  759. // Check that there's space for the operand.
  760. if (I->get() + I->getSize() > E->get())
  761. return false;
  762. // Check that the operand is valid.
  763. switch (I->getOp()) {
  764. default:
  765. return false;
  766. case dwarf::DW_OP_LLVM_fragment:
  767. // A fragment operator must appear at the end.
  768. return I->get() + I->getSize() == E->get();
  769. case dwarf::DW_OP_stack_value: {
  770. // Must be the last one or followed by a DW_OP_LLVM_fragment.
  771. if (I->get() + I->getSize() == E->get())
  772. break;
  773. auto J = I;
  774. if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
  775. return false;
  776. break;
  777. }
  778. case dwarf::DW_OP_swap: {
  779. // Must be more than one implicit element on the stack.
  780. // FIXME: A better way to implement this would be to add a local variable
  781. // that keeps track of the stack depth and introduce something like a
  782. // DW_LLVM_OP_implicit_location as a placeholder for the location this
  783. // DIExpression is attached to, or else pass the number of implicit stack
  784. // elements into isValid.
  785. if (getNumElements() == 1)
  786. return false;
  787. break;
  788. }
  789. case dwarf::DW_OP_LLVM_convert:
  790. case dwarf::DW_OP_constu:
  791. case dwarf::DW_OP_plus_uconst:
  792. case dwarf::DW_OP_plus:
  793. case dwarf::DW_OP_minus:
  794. case dwarf::DW_OP_mul:
  795. case dwarf::DW_OP_div:
  796. case dwarf::DW_OP_mod:
  797. case dwarf::DW_OP_or:
  798. case dwarf::DW_OP_and:
  799. case dwarf::DW_OP_xor:
  800. case dwarf::DW_OP_shl:
  801. case dwarf::DW_OP_shr:
  802. case dwarf::DW_OP_shra:
  803. case dwarf::DW_OP_deref:
  804. case dwarf::DW_OP_deref_size:
  805. case dwarf::DW_OP_xderef:
  806. case dwarf::DW_OP_lit0:
  807. case dwarf::DW_OP_not:
  808. case dwarf::DW_OP_dup:
  809. break;
  810. }
  811. }
  812. return true;
  813. }
  814. bool DIExpression::isImplicit() const {
  815. unsigned N = getNumElements();
  816. if (isValid() && N > 0) {
  817. switch (getElement(N-1)) {
  818. case dwarf::DW_OP_stack_value: return true;
  819. case dwarf::DW_OP_LLVM_fragment:
  820. return N > 1 && getElement(N-2) == dwarf::DW_OP_stack_value;
  821. default: break;
  822. }
  823. }
  824. return false;
  825. }
  826. Optional<DIExpression::FragmentInfo>
  827. DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
  828. for (auto I = Start; I != End; ++I)
  829. if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
  830. DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
  831. return Info;
  832. }
  833. return None;
  834. }
  835. void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
  836. int64_t Offset) {
  837. if (Offset > 0) {
  838. Ops.push_back(dwarf::DW_OP_plus_uconst);
  839. Ops.push_back(Offset);
  840. } else if (Offset < 0) {
  841. Ops.push_back(dwarf::DW_OP_constu);
  842. Ops.push_back(-Offset);
  843. Ops.push_back(dwarf::DW_OP_minus);
  844. }
  845. }
  846. bool DIExpression::extractIfOffset(int64_t &Offset) const {
  847. if (getNumElements() == 0) {
  848. Offset = 0;
  849. return true;
  850. }
  851. if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
  852. Offset = Elements[1];
  853. return true;
  854. }
  855. if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
  856. if (Elements[2] == dwarf::DW_OP_plus) {
  857. Offset = Elements[1];
  858. return true;
  859. }
  860. if (Elements[2] == dwarf::DW_OP_minus) {
  861. Offset = -Elements[1];
  862. return true;
  863. }
  864. }
  865. return false;
  866. }
  867. const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
  868. unsigned &AddrClass) {
  869. const unsigned PatternSize = 4;
  870. if (Expr->Elements.size() >= PatternSize &&
  871. Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
  872. Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
  873. Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
  874. AddrClass = Expr->Elements[PatternSize - 3];
  875. if (Expr->Elements.size() == PatternSize)
  876. return nullptr;
  877. return DIExpression::get(Expr->getContext(),
  878. makeArrayRef(&*Expr->Elements.begin(),
  879. Expr->Elements.size() - PatternSize));
  880. }
  881. return Expr;
  882. }
  883. DIExpression *DIExpression::prepend(const DIExpression *Expr, bool DerefBefore,
  884. int64_t Offset, bool DerefAfter,
  885. bool StackValue) {
  886. SmallVector<uint64_t, 8> Ops;
  887. if (DerefBefore)
  888. Ops.push_back(dwarf::DW_OP_deref);
  889. appendOffset(Ops, Offset);
  890. if (DerefAfter)
  891. Ops.push_back(dwarf::DW_OP_deref);
  892. return prependOpcodes(Expr, Ops, StackValue);
  893. }
  894. DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
  895. SmallVectorImpl<uint64_t> &Ops,
  896. bool StackValue) {
  897. assert(Expr && "Can't prepend ops to this expression");
  898. // If there are no ops to prepend, do not even add the DW_OP_stack_value.
  899. if (Ops.empty())
  900. StackValue = false;
  901. for (auto Op : Expr->expr_ops()) {
  902. // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
  903. if (StackValue) {
  904. if (Op.getOp() == dwarf::DW_OP_stack_value)
  905. StackValue = false;
  906. else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
  907. Ops.push_back(dwarf::DW_OP_stack_value);
  908. StackValue = false;
  909. }
  910. }
  911. Op.appendToVector(Ops);
  912. }
  913. if (StackValue)
  914. Ops.push_back(dwarf::DW_OP_stack_value);
  915. return DIExpression::get(Expr->getContext(), Ops);
  916. }
  917. DIExpression *DIExpression::append(const DIExpression *Expr,
  918. ArrayRef<uint64_t> Ops) {
  919. assert(Expr && !Ops.empty() && "Can't append ops to this expression");
  920. // Copy Expr's current op list.
  921. SmallVector<uint64_t, 16> NewOps;
  922. for (auto Op : Expr->expr_ops()) {
  923. // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
  924. if (Op.getOp() == dwarf::DW_OP_stack_value ||
  925. Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
  926. NewOps.append(Ops.begin(), Ops.end());
  927. // Ensure that the new opcodes are only appended once.
  928. Ops = None;
  929. }
  930. Op.appendToVector(NewOps);
  931. }
  932. NewOps.append(Ops.begin(), Ops.end());
  933. return DIExpression::get(Expr->getContext(), NewOps);
  934. }
  935. DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
  936. ArrayRef<uint64_t> Ops) {
  937. assert(Expr && !Ops.empty() && "Can't append ops to this expression");
  938. assert(none_of(Ops,
  939. [](uint64_t Op) {
  940. return Op == dwarf::DW_OP_stack_value ||
  941. Op == dwarf::DW_OP_LLVM_fragment;
  942. }) &&
  943. "Can't append this op");
  944. // Append a DW_OP_deref after Expr's current op list if it's non-empty and
  945. // has no DW_OP_stack_value.
  946. //
  947. // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
  948. Optional<FragmentInfo> FI = Expr->getFragmentInfo();
  949. unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
  950. ArrayRef<uint64_t> ExprOpsBeforeFragment =
  951. Expr->getElements().drop_back(DropUntilStackValue);
  952. bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
  953. (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
  954. bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
  955. // Append a DW_OP_deref after Expr's current op list if needed, then append
  956. // the new ops, and finally ensure that a single DW_OP_stack_value is present.
  957. SmallVector<uint64_t, 16> NewOps;
  958. if (NeedsDeref)
  959. NewOps.push_back(dwarf::DW_OP_deref);
  960. NewOps.append(Ops.begin(), Ops.end());
  961. if (NeedsStackValue)
  962. NewOps.push_back(dwarf::DW_OP_stack_value);
  963. return DIExpression::append(Expr, NewOps);
  964. }
  965. Optional<DIExpression *> DIExpression::createFragmentExpression(
  966. const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
  967. SmallVector<uint64_t, 8> Ops;
  968. // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
  969. if (Expr) {
  970. for (auto Op : Expr->expr_ops()) {
  971. switch (Op.getOp()) {
  972. default: break;
  973. case dwarf::DW_OP_plus:
  974. case dwarf::DW_OP_minus:
  975. // We can't safely split arithmetic into multiple fragments because we
  976. // can't express carry-over between fragments.
  977. //
  978. // FIXME: We *could* preserve the lowest fragment of a constant offset
  979. // operation if the offset fits into SizeInBits.
  980. return None;
  981. case dwarf::DW_OP_LLVM_fragment: {
  982. // Make the new offset point into the existing fragment.
  983. uint64_t FragmentOffsetInBits = Op.getArg(0);
  984. uint64_t FragmentSizeInBits = Op.getArg(1);
  985. (void)FragmentSizeInBits;
  986. assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
  987. "new fragment outside of original fragment");
  988. OffsetInBits += FragmentOffsetInBits;
  989. continue;
  990. }
  991. }
  992. Op.appendToVector(Ops);
  993. }
  994. }
  995. Ops.push_back(dwarf::DW_OP_LLVM_fragment);
  996. Ops.push_back(OffsetInBits);
  997. Ops.push_back(SizeInBits);
  998. return DIExpression::get(Expr->getContext(), Ops);
  999. }
  1000. bool DIExpression::isConstant() const {
  1001. // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?.
  1002. if (getNumElements() != 3 && getNumElements() != 6)
  1003. return false;
  1004. if (getElement(0) != dwarf::DW_OP_constu ||
  1005. getElement(2) != dwarf::DW_OP_stack_value)
  1006. return false;
  1007. if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment)
  1008. return false;
  1009. return true;
  1010. }
  1011. DIGlobalVariableExpression *
  1012. DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
  1013. Metadata *Expression, StorageType Storage,
  1014. bool ShouldCreate) {
  1015. DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
  1016. Metadata *Ops[] = {Variable, Expression};
  1017. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
  1018. }
  1019. DIObjCProperty *DIObjCProperty::getImpl(
  1020. LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
  1021. MDString *GetterName, MDString *SetterName, unsigned Attributes,
  1022. Metadata *Type, StorageType Storage, bool ShouldCreate) {
  1023. assert(isCanonical(Name) && "Expected canonical MDString");
  1024. assert(isCanonical(GetterName) && "Expected canonical MDString");
  1025. assert(isCanonical(SetterName) && "Expected canonical MDString");
  1026. DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
  1027. SetterName, Attributes, Type));
  1028. Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
  1029. DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
  1030. }
  1031. DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
  1032. Metadata *Scope, Metadata *Entity,
  1033. Metadata *File, unsigned Line,
  1034. MDString *Name, StorageType Storage,
  1035. bool ShouldCreate) {
  1036. assert(isCanonical(Name) && "Expected canonical MDString");
  1037. DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
  1038. (Tag, Scope, Entity, File, Line, Name));
  1039. Metadata *Ops[] = {Scope, Entity, Name, File};
  1040. DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
  1041. }
  1042. DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
  1043. unsigned Line, MDString *Name, MDString *Value,
  1044. StorageType Storage, bool ShouldCreate) {
  1045. assert(isCanonical(Name) && "Expected canonical MDString");
  1046. DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
  1047. Metadata *Ops[] = { Name, Value };
  1048. DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
  1049. }
  1050. DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
  1051. unsigned Line, Metadata *File,
  1052. Metadata *Elements, StorageType Storage,
  1053. bool ShouldCreate) {
  1054. DEFINE_GETIMPL_LOOKUP(DIMacroFile,
  1055. (MIType, Line, File, Elements));
  1056. Metadata *Ops[] = { File, Elements };
  1057. DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
  1058. }