MetadataLoader.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980
  1. //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
  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. #include "MetadataLoader.h"
  10. #include "ValueList.h"
  11. #include "llvm/ADT/APFloat.h"
  12. #include "llvm/ADT/APInt.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.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/Statistic.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Triple.h"
  23. #include "llvm/ADT/Twine.h"
  24. #include "llvm/Bitcode/BitcodeReader.h"
  25. #include "llvm/Bitcode/BitstreamReader.h"
  26. #include "llvm/Bitcode/LLVMBitCodes.h"
  27. #include "llvm/IR/Argument.h"
  28. #include "llvm/IR/Attributes.h"
  29. #include "llvm/IR/AutoUpgrade.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/CallSite.h"
  32. #include "llvm/IR/CallingConv.h"
  33. #include "llvm/IR/Comdat.h"
  34. #include "llvm/IR/Constant.h"
  35. #include "llvm/IR/Constants.h"
  36. #include "llvm/IR/DebugInfo.h"
  37. #include "llvm/IR/DebugInfoMetadata.h"
  38. #include "llvm/IR/DebugLoc.h"
  39. #include "llvm/IR/DerivedTypes.h"
  40. #include "llvm/IR/DiagnosticInfo.h"
  41. #include "llvm/IR/DiagnosticPrinter.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/IR/GVMaterializer.h"
  44. #include "llvm/IR/GlobalAlias.h"
  45. #include "llvm/IR/GlobalIFunc.h"
  46. #include "llvm/IR/GlobalIndirectSymbol.h"
  47. #include "llvm/IR/GlobalObject.h"
  48. #include "llvm/IR/GlobalValue.h"
  49. #include "llvm/IR/GlobalVariable.h"
  50. #include "llvm/IR/InlineAsm.h"
  51. #include "llvm/IR/InstrTypes.h"
  52. #include "llvm/IR/Instruction.h"
  53. #include "llvm/IR/Instructions.h"
  54. #include "llvm/IR/IntrinsicInst.h"
  55. #include "llvm/IR/Intrinsics.h"
  56. #include "llvm/IR/LLVMContext.h"
  57. #include "llvm/IR/Module.h"
  58. #include "llvm/IR/ModuleSummaryIndex.h"
  59. #include "llvm/IR/OperandTraits.h"
  60. #include "llvm/IR/Operator.h"
  61. #include "llvm/IR/TrackingMDRef.h"
  62. #include "llvm/IR/Type.h"
  63. #include "llvm/IR/ValueHandle.h"
  64. #include "llvm/Support/AtomicOrdering.h"
  65. #include "llvm/Support/Casting.h"
  66. #include "llvm/Support/CommandLine.h"
  67. #include "llvm/Support/Compiler.h"
  68. #include "llvm/Support/Debug.h"
  69. #include "llvm/Support/Error.h"
  70. #include "llvm/Support/ErrorHandling.h"
  71. #include "llvm/Support/ManagedStatic.h"
  72. #include "llvm/Support/MemoryBuffer.h"
  73. #include "llvm/Support/raw_ostream.h"
  74. #include <algorithm>
  75. #include <cassert>
  76. #include <cstddef>
  77. #include <cstdint>
  78. #include <deque>
  79. #include <limits>
  80. #include <map>
  81. #include <memory>
  82. #include <string>
  83. #include <system_error>
  84. #include <tuple>
  85. #include <utility>
  86. #include <vector>
  87. using namespace llvm;
  88. #define DEBUG_TYPE "bitcode-reader"
  89. STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
  90. STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
  91. STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
  92. /// Flag whether we need to import full type definitions for ThinLTO.
  93. /// Currently needed for Darwin and LLDB.
  94. static cl::opt<bool> ImportFullTypeDefinitions(
  95. "import-full-type-definitions", cl::init(false), cl::Hidden,
  96. cl::desc("Import full type definitions for ThinLTO."));
  97. static cl::opt<bool> DisableLazyLoading(
  98. "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
  99. cl::desc("Force disable the lazy-loading on-demand of metadata when "
  100. "loading bitcode for importing."));
  101. namespace {
  102. static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
  103. class BitcodeReaderMetadataList {
  104. /// Array of metadata references.
  105. ///
  106. /// Don't use std::vector here. Some versions of libc++ copy (instead of
  107. /// move) on resize, and TrackingMDRef is very expensive to copy.
  108. SmallVector<TrackingMDRef, 1> MetadataPtrs;
  109. /// The set of indices in MetadataPtrs above of forward references that were
  110. /// generated.
  111. SmallDenseSet<unsigned, 1> ForwardReference;
  112. /// The set of indices in MetadataPtrs above of Metadata that need to be
  113. /// resolved.
  114. SmallDenseSet<unsigned, 1> UnresolvedNodes;
  115. /// Structures for resolving old type refs.
  116. struct {
  117. SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
  118. SmallDenseMap<MDString *, DICompositeType *, 1> Final;
  119. SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
  120. SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
  121. } OldTypeRefs;
  122. LLVMContext &Context;
  123. public:
  124. BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
  125. // vector compatibility methods
  126. unsigned size() const { return MetadataPtrs.size(); }
  127. void resize(unsigned N) { MetadataPtrs.resize(N); }
  128. void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
  129. void clear() { MetadataPtrs.clear(); }
  130. Metadata *back() const { return MetadataPtrs.back(); }
  131. void pop_back() { MetadataPtrs.pop_back(); }
  132. bool empty() const { return MetadataPtrs.empty(); }
  133. Metadata *operator[](unsigned i) const {
  134. assert(i < MetadataPtrs.size());
  135. return MetadataPtrs[i];
  136. }
  137. Metadata *lookup(unsigned I) const {
  138. if (I < MetadataPtrs.size())
  139. return MetadataPtrs[I];
  140. return nullptr;
  141. }
  142. void shrinkTo(unsigned N) {
  143. assert(N <= size() && "Invalid shrinkTo request!");
  144. assert(ForwardReference.empty() && "Unexpected forward refs");
  145. assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
  146. MetadataPtrs.resize(N);
  147. }
  148. /// Return the given metadata, creating a replaceable forward reference if
  149. /// necessary.
  150. Metadata *getMetadataFwdRef(unsigned Idx);
  151. /// Return the the given metadata only if it is fully resolved.
  152. ///
  153. /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
  154. /// would give \c false.
  155. Metadata *getMetadataIfResolved(unsigned Idx);
  156. MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
  157. void assignValue(Metadata *MD, unsigned Idx);
  158. void tryToResolveCycles();
  159. bool hasFwdRefs() const { return !ForwardReference.empty(); }
  160. int getNextFwdRef() {
  161. assert(hasFwdRefs());
  162. return *ForwardReference.begin();
  163. }
  164. /// Upgrade a type that had an MDString reference.
  165. void addTypeRef(MDString &UUID, DICompositeType &CT);
  166. /// Upgrade a type that had an MDString reference.
  167. Metadata *upgradeTypeRef(Metadata *MaybeUUID);
  168. /// Upgrade a type ref array that may have MDString references.
  169. Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
  170. private:
  171. Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
  172. };
  173. void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
  174. if (auto *MDN = dyn_cast<MDNode>(MD))
  175. if (!MDN->isResolved())
  176. UnresolvedNodes.insert(Idx);
  177. if (Idx == size()) {
  178. push_back(MD);
  179. return;
  180. }
  181. if (Idx >= size())
  182. resize(Idx + 1);
  183. TrackingMDRef &OldMD = MetadataPtrs[Idx];
  184. if (!OldMD) {
  185. OldMD.reset(MD);
  186. return;
  187. }
  188. // If there was a forward reference to this value, replace it.
  189. TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
  190. PrevMD->replaceAllUsesWith(MD);
  191. ForwardReference.erase(Idx);
  192. }
  193. Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
  194. if (Idx >= size())
  195. resize(Idx + 1);
  196. if (Metadata *MD = MetadataPtrs[Idx])
  197. return MD;
  198. // Track forward refs to be resolved later.
  199. ForwardReference.insert(Idx);
  200. // Create and return a placeholder, which will later be RAUW'd.
  201. ++NumMDNodeTemporary;
  202. Metadata *MD = MDNode::getTemporary(Context, None).release();
  203. MetadataPtrs[Idx].reset(MD);
  204. return MD;
  205. }
  206. Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
  207. Metadata *MD = lookup(Idx);
  208. if (auto *N = dyn_cast_or_null<MDNode>(MD))
  209. if (!N->isResolved())
  210. return nullptr;
  211. return MD;
  212. }
  213. MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
  214. return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
  215. }
  216. void BitcodeReaderMetadataList::tryToResolveCycles() {
  217. if (!ForwardReference.empty())
  218. // Still forward references... can't resolve cycles.
  219. return;
  220. // Give up on finding a full definition for any forward decls that remain.
  221. for (const auto &Ref : OldTypeRefs.FwdDecls)
  222. OldTypeRefs.Final.insert(Ref);
  223. OldTypeRefs.FwdDecls.clear();
  224. // Upgrade from old type ref arrays. In strange cases, this could add to
  225. // OldTypeRefs.Unknown.
  226. for (const auto &Array : OldTypeRefs.Arrays)
  227. Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
  228. OldTypeRefs.Arrays.clear();
  229. // Replace old string-based type refs with the resolved node, if possible.
  230. // If we haven't seen the node, leave it to the verifier to complain about
  231. // the invalid string reference.
  232. for (const auto &Ref : OldTypeRefs.Unknown) {
  233. if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
  234. Ref.second->replaceAllUsesWith(CT);
  235. else
  236. Ref.second->replaceAllUsesWith(Ref.first);
  237. }
  238. OldTypeRefs.Unknown.clear();
  239. if (UnresolvedNodes.empty())
  240. // Nothing to do.
  241. return;
  242. // Resolve any cycles.
  243. for (unsigned I : UnresolvedNodes) {
  244. auto &MD = MetadataPtrs[I];
  245. auto *N = dyn_cast_or_null<MDNode>(MD);
  246. if (!N)
  247. continue;
  248. assert(!N->isTemporary() && "Unexpected forward reference");
  249. N->resolveCycles();
  250. }
  251. // Make sure we return early again until there's another unresolved ref.
  252. UnresolvedNodes.clear();
  253. }
  254. void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
  255. DICompositeType &CT) {
  256. assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
  257. if (CT.isForwardDecl())
  258. OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
  259. else
  260. OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
  261. }
  262. Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
  263. auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
  264. if (LLVM_LIKELY(!UUID))
  265. return MaybeUUID;
  266. if (auto *CT = OldTypeRefs.Final.lookup(UUID))
  267. return CT;
  268. auto &Ref = OldTypeRefs.Unknown[UUID];
  269. if (!Ref)
  270. Ref = MDNode::getTemporary(Context, None);
  271. return Ref.get();
  272. }
  273. Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
  274. auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
  275. if (!Tuple || Tuple->isDistinct())
  276. return MaybeTuple;
  277. // Look through the array immediately if possible.
  278. if (!Tuple->isTemporary())
  279. return resolveTypeRefArray(Tuple);
  280. // Create and return a placeholder to use for now. Eventually
  281. // resolveTypeRefArrays() will be resolve this forward reference.
  282. OldTypeRefs.Arrays.emplace_back(
  283. std::piecewise_construct, std::forward_as_tuple(Tuple),
  284. std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
  285. return OldTypeRefs.Arrays.back().second.get();
  286. }
  287. Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
  288. auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
  289. if (!Tuple || Tuple->isDistinct())
  290. return MaybeTuple;
  291. // Look through the DITypeRefArray, upgrading each DITypeRef.
  292. SmallVector<Metadata *, 32> Ops;
  293. Ops.reserve(Tuple->getNumOperands());
  294. for (Metadata *MD : Tuple->operands())
  295. Ops.push_back(upgradeTypeRef(MD));
  296. return MDTuple::get(Context, Ops);
  297. }
  298. namespace {
  299. class PlaceholderQueue {
  300. // Placeholders would thrash around when moved, so store in a std::deque
  301. // instead of some sort of vector.
  302. std::deque<DistinctMDOperandPlaceholder> PHs;
  303. public:
  304. ~PlaceholderQueue() {
  305. assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed");
  306. }
  307. bool empty() { return PHs.empty(); }
  308. DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
  309. void flush(BitcodeReaderMetadataList &MetadataList);
  310. /// Return the list of temporaries nodes in the queue, these need to be
  311. /// loaded before we can flush the queue.
  312. void getTemporaries(BitcodeReaderMetadataList &MetadataList,
  313. DenseSet<unsigned> &Temporaries) {
  314. for (auto &PH : PHs) {
  315. auto ID = PH.getID();
  316. auto *MD = MetadataList.lookup(ID);
  317. if (!MD) {
  318. Temporaries.insert(ID);
  319. continue;
  320. }
  321. auto *N = dyn_cast_or_null<MDNode>(MD);
  322. if (N && N->isTemporary())
  323. Temporaries.insert(ID);
  324. }
  325. }
  326. };
  327. } // end anonymous namespace
  328. DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
  329. PHs.emplace_back(ID);
  330. return PHs.back();
  331. }
  332. void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
  333. while (!PHs.empty()) {
  334. auto *MD = MetadataList.lookup(PHs.front().getID());
  335. assert(MD && "Flushing placeholder on unassigned MD");
  336. #ifndef NDEBUG
  337. if (auto *MDN = dyn_cast<MDNode>(MD))
  338. assert(MDN->isResolved() &&
  339. "Flushing Placeholder while cycles aren't resolved");
  340. #endif
  341. PHs.front().replaceUseWith(MD);
  342. PHs.pop_front();
  343. }
  344. }
  345. } // anonynous namespace
  346. static Error error(const Twine &Message) {
  347. return make_error<StringError>(
  348. Message, make_error_code(BitcodeError::CorruptedBitcode));
  349. }
  350. class MetadataLoader::MetadataLoaderImpl {
  351. BitcodeReaderMetadataList MetadataList;
  352. BitcodeReaderValueList &ValueList;
  353. BitstreamCursor &Stream;
  354. LLVMContext &Context;
  355. Module &TheModule;
  356. std::function<Type *(unsigned)> getTypeByID;
  357. /// Cursor associated with the lazy-loading of Metadata. This is the easy way
  358. /// to keep around the right "context" (Abbrev list) to be able to jump in
  359. /// the middle of the metadata block and load any record.
  360. BitstreamCursor IndexCursor;
  361. /// Index that keeps track of MDString values.
  362. std::vector<StringRef> MDStringRef;
  363. /// On-demand loading of a single MDString. Requires the index above to be
  364. /// populated.
  365. MDString *lazyLoadOneMDString(unsigned Idx);
  366. /// Index that keeps track of where to find a metadata record in the stream.
  367. std::vector<uint64_t> GlobalMetadataBitPosIndex;
  368. /// Populate the index above to enable lazily loading of metadata, and load
  369. /// the named metadata as well as the transitively referenced global
  370. /// Metadata.
  371. Expected<bool> lazyLoadModuleMetadataBlock();
  372. /// On-demand loading of a single metadata. Requires the index above to be
  373. /// populated.
  374. void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
  375. // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
  376. // point from SP to CU after a block is completly parsed.
  377. std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
  378. /// Functions that need to be matched with subprograms when upgrading old
  379. /// metadata.
  380. SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
  381. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  382. DenseMap<unsigned, unsigned> MDKindMap;
  383. bool StripTBAA = false;
  384. bool HasSeenOldLoopTags = false;
  385. bool NeedUpgradeToDIGlobalVariableExpression = false;
  386. bool NeedDeclareExpressionUpgrade = false;
  387. /// True if metadata is being parsed for a module being ThinLTO imported.
  388. bool IsImporting = false;
  389. Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
  390. PlaceholderQueue &Placeholders, StringRef Blob,
  391. unsigned &NextMetadataNo);
  392. Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
  393. function_ref<void(StringRef)> CallBack);
  394. Error parseGlobalObjectAttachment(GlobalObject &GO,
  395. ArrayRef<uint64_t> Record);
  396. Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
  397. void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
  398. /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
  399. void upgradeCUSubprograms() {
  400. for (auto CU_SP : CUSubprograms)
  401. if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
  402. for (auto &Op : SPs->operands())
  403. if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
  404. SP->replaceUnit(CU_SP.first);
  405. CUSubprograms.clear();
  406. }
  407. /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
  408. void upgradeCUVariables() {
  409. if (!NeedUpgradeToDIGlobalVariableExpression)
  410. return;
  411. // Upgrade list of variables attached to the CUs.
  412. if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
  413. for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
  414. auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
  415. if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
  416. for (unsigned I = 0; I < GVs->getNumOperands(); I++)
  417. if (auto *GV =
  418. dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
  419. auto *DGVE = DIGlobalVariableExpression::getDistinct(
  420. Context, GV, DIExpression::get(Context, {}));
  421. GVs->replaceOperandWith(I, DGVE);
  422. }
  423. }
  424. // Upgrade variables attached to globals.
  425. for (auto &GV : TheModule.globals()) {
  426. SmallVector<MDNode *, 1> MDs;
  427. GV.getMetadata(LLVMContext::MD_dbg, MDs);
  428. GV.eraseMetadata(LLVMContext::MD_dbg);
  429. for (auto *MD : MDs)
  430. if (auto *DGV = dyn_cast_or_null<DIGlobalVariable>(MD)) {
  431. auto *DGVE = DIGlobalVariableExpression::getDistinct(
  432. Context, DGV, DIExpression::get(Context, {}));
  433. GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
  434. } else
  435. GV.addMetadata(LLVMContext::MD_dbg, *MD);
  436. }
  437. }
  438. /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
  439. /// describes a function argument.
  440. void upgradeDeclareExpressions(Function &F) {
  441. if (!NeedDeclareExpressionUpgrade)
  442. return;
  443. for (auto &BB : F)
  444. for (auto &I : BB)
  445. if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
  446. if (auto *DIExpr = DDI->getExpression())
  447. if (DIExpr->startsWithDeref() &&
  448. dyn_cast_or_null<Argument>(DDI->getAddress())) {
  449. SmallVector<uint64_t, 8> Ops;
  450. Ops.append(std::next(DIExpr->elements_begin()),
  451. DIExpr->elements_end());
  452. auto *E = DIExpression::get(Context, Ops);
  453. DDI->setOperand(2, MetadataAsValue::get(Context, E));
  454. }
  455. }
  456. /// Upgrade the expression from previous versions.
  457. Error upgradeDIExpression(uint64_t FromVersion,
  458. MutableArrayRef<uint64_t> &Expr,
  459. SmallVectorImpl<uint64_t> &Buffer) {
  460. auto N = Expr.size();
  461. switch (FromVersion) {
  462. default:
  463. return error("Invalid record");
  464. case 0:
  465. if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
  466. Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
  467. LLVM_FALLTHROUGH;
  468. case 1:
  469. // Move DW_OP_deref to the end.
  470. if (N && Expr[0] == dwarf::DW_OP_deref) {
  471. auto End = Expr.end();
  472. if (Expr.size() >= 3 &&
  473. *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
  474. End = std::prev(End, 3);
  475. std::move(std::next(Expr.begin()), End, Expr.begin());
  476. *std::prev(End) = dwarf::DW_OP_deref;
  477. }
  478. NeedDeclareExpressionUpgrade = true;
  479. LLVM_FALLTHROUGH;
  480. case 2: {
  481. // Change DW_OP_plus to DW_OP_plus_uconst.
  482. // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
  483. auto SubExpr = ArrayRef<uint64_t>(Expr);
  484. while (!SubExpr.empty()) {
  485. // Skip past other operators with their operands
  486. // for this version of the IR, obtained from
  487. // from historic DIExpression::ExprOperand::getSize().
  488. size_t HistoricSize;
  489. switch (SubExpr.front()) {
  490. default:
  491. HistoricSize = 1;
  492. break;
  493. case dwarf::DW_OP_constu:
  494. case dwarf::DW_OP_minus:
  495. case dwarf::DW_OP_plus:
  496. HistoricSize = 2;
  497. break;
  498. case dwarf::DW_OP_LLVM_fragment:
  499. HistoricSize = 3;
  500. break;
  501. }
  502. // If the expression is malformed, make sure we don't
  503. // copy more elements than we should.
  504. HistoricSize = std::min(SubExpr.size(), HistoricSize);
  505. ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize-1);
  506. switch (SubExpr.front()) {
  507. case dwarf::DW_OP_plus:
  508. Buffer.push_back(dwarf::DW_OP_plus_uconst);
  509. Buffer.append(Args.begin(), Args.end());
  510. break;
  511. case dwarf::DW_OP_minus:
  512. Buffer.push_back(dwarf::DW_OP_constu);
  513. Buffer.append(Args.begin(), Args.end());
  514. Buffer.push_back(dwarf::DW_OP_minus);
  515. break;
  516. default:
  517. Buffer.push_back(*SubExpr.begin());
  518. Buffer.append(Args.begin(), Args.end());
  519. break;
  520. }
  521. // Continue with remaining elements.
  522. SubExpr = SubExpr.slice(HistoricSize);
  523. }
  524. Expr = MutableArrayRef<uint64_t>(Buffer);
  525. LLVM_FALLTHROUGH;
  526. }
  527. case 3:
  528. // Up-to-date!
  529. break;
  530. }
  531. return Error::success();
  532. }
  533. void upgradeDebugInfo() {
  534. upgradeCUSubprograms();
  535. upgradeCUVariables();
  536. }
  537. public:
  538. MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
  539. BitcodeReaderValueList &ValueList,
  540. std::function<Type *(unsigned)> getTypeByID,
  541. bool IsImporting)
  542. : MetadataList(TheModule.getContext()), ValueList(ValueList),
  543. Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
  544. getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
  545. Error parseMetadata(bool ModuleLevel);
  546. bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
  547. Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
  548. if (ID < MDStringRef.size())
  549. return lazyLoadOneMDString(ID);
  550. if (auto *MD = MetadataList.lookup(ID))
  551. return MD;
  552. // If lazy-loading is enabled, we try recursively to load the operand
  553. // instead of creating a temporary.
  554. if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
  555. PlaceholderQueue Placeholders;
  556. lazyLoadOneMetadata(ID, Placeholders);
  557. resolveForwardRefsAndPlaceholders(Placeholders);
  558. return MetadataList.lookup(ID);
  559. }
  560. return MetadataList.getMetadataFwdRef(ID);
  561. }
  562. MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
  563. return MetadataList.getMDNodeFwdRefOrNull(Idx);
  564. }
  565. DISubprogram *lookupSubprogramForFunction(Function *F) {
  566. return FunctionsWithSPs.lookup(F);
  567. }
  568. bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
  569. Error parseMetadataAttachment(
  570. Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
  571. Error parseMetadataKinds();
  572. void setStripTBAA(bool Value) { StripTBAA = Value; }
  573. bool isStrippingTBAA() { return StripTBAA; }
  574. unsigned size() const { return MetadataList.size(); }
  575. void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
  576. void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
  577. };
  578. Expected<bool>
  579. MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
  580. IndexCursor = Stream;
  581. SmallVector<uint64_t, 64> Record;
  582. // Get the abbrevs, and preload record positions to make them lazy-loadable.
  583. while (true) {
  584. BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
  585. BitstreamCursor::AF_DontPopBlockAtEnd);
  586. switch (Entry.Kind) {
  587. case BitstreamEntry::SubBlock: // Handled for us already.
  588. case BitstreamEntry::Error:
  589. return error("Malformed block");
  590. case BitstreamEntry::EndBlock: {
  591. return true;
  592. }
  593. case BitstreamEntry::Record: {
  594. // The interesting case.
  595. ++NumMDRecordLoaded;
  596. uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
  597. auto Code = IndexCursor.skipRecord(Entry.ID);
  598. switch (Code) {
  599. case bitc::METADATA_STRINGS: {
  600. // Rewind and parse the strings.
  601. IndexCursor.JumpToBit(CurrentPos);
  602. StringRef Blob;
  603. Record.clear();
  604. IndexCursor.readRecord(Entry.ID, Record, &Blob);
  605. unsigned NumStrings = Record[0];
  606. MDStringRef.reserve(NumStrings);
  607. auto IndexNextMDString = [&](StringRef Str) {
  608. MDStringRef.push_back(Str);
  609. };
  610. if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
  611. return std::move(Err);
  612. break;
  613. }
  614. case bitc::METADATA_INDEX_OFFSET: {
  615. // This is the offset to the index, when we see this we skip all the
  616. // records and load only an index to these.
  617. IndexCursor.JumpToBit(CurrentPos);
  618. Record.clear();
  619. IndexCursor.readRecord(Entry.ID, Record);
  620. if (Record.size() != 2)
  621. return error("Invalid record");
  622. auto Offset = Record[0] + (Record[1] << 32);
  623. auto BeginPos = IndexCursor.GetCurrentBitNo();
  624. IndexCursor.JumpToBit(BeginPos + Offset);
  625. Entry = IndexCursor.advanceSkippingSubblocks(
  626. BitstreamCursor::AF_DontPopBlockAtEnd);
  627. assert(Entry.Kind == BitstreamEntry::Record &&
  628. "Corrupted bitcode: Expected `Record` when trying to find the "
  629. "Metadata index");
  630. Record.clear();
  631. auto Code = IndexCursor.readRecord(Entry.ID, Record);
  632. (void)Code;
  633. assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
  634. "`METADATA_INDEX` when trying "
  635. "to find the Metadata index");
  636. // Delta unpack
  637. auto CurrentValue = BeginPos;
  638. GlobalMetadataBitPosIndex.reserve(Record.size());
  639. for (auto &Elt : Record) {
  640. CurrentValue += Elt;
  641. GlobalMetadataBitPosIndex.push_back(CurrentValue);
  642. }
  643. break;
  644. }
  645. case bitc::METADATA_INDEX:
  646. // We don't expect to get there, the Index is loaded when we encounter
  647. // the offset.
  648. return error("Corrupted Metadata block");
  649. case bitc::METADATA_NAME: {
  650. // Named metadata need to be materialized now and aren't deferred.
  651. IndexCursor.JumpToBit(CurrentPos);
  652. Record.clear();
  653. unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
  654. assert(Code == bitc::METADATA_NAME);
  655. // Read name of the named metadata.
  656. SmallString<8> Name(Record.begin(), Record.end());
  657. Code = IndexCursor.ReadCode();
  658. // Named Metadata comes in two parts, we expect the name to be followed
  659. // by the node
  660. Record.clear();
  661. unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
  662. assert(NextBitCode == bitc::METADATA_NAMED_NODE);
  663. (void)NextBitCode;
  664. // Read named metadata elements.
  665. unsigned Size = Record.size();
  666. NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
  667. for (unsigned i = 0; i != Size; ++i) {
  668. // FIXME: We could use a placeholder here, however NamedMDNode are
  669. // taking MDNode as operand and not using the Metadata infrastructure.
  670. // It is acknowledged by 'TODO: Inherit from Metadata' in the
  671. // NamedMDNode class definition.
  672. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
  673. assert(MD && "Invalid record");
  674. NMD->addOperand(MD);
  675. }
  676. break;
  677. }
  678. case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
  679. // FIXME: we need to do this early because we don't materialize global
  680. // value explicitly.
  681. IndexCursor.JumpToBit(CurrentPos);
  682. Record.clear();
  683. IndexCursor.readRecord(Entry.ID, Record);
  684. if (Record.size() % 2 == 0)
  685. return error("Invalid record");
  686. unsigned ValueID = Record[0];
  687. if (ValueID >= ValueList.size())
  688. return error("Invalid record");
  689. if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
  690. if (Error Err = parseGlobalObjectAttachment(
  691. *GO, ArrayRef<uint64_t>(Record).slice(1)))
  692. return std::move(Err);
  693. break;
  694. }
  695. case bitc::METADATA_KIND:
  696. case bitc::METADATA_STRING_OLD:
  697. case bitc::METADATA_OLD_FN_NODE:
  698. case bitc::METADATA_OLD_NODE:
  699. case bitc::METADATA_VALUE:
  700. case bitc::METADATA_DISTINCT_NODE:
  701. case bitc::METADATA_NODE:
  702. case bitc::METADATA_LOCATION:
  703. case bitc::METADATA_GENERIC_DEBUG:
  704. case bitc::METADATA_SUBRANGE:
  705. case bitc::METADATA_ENUMERATOR:
  706. case bitc::METADATA_BASIC_TYPE:
  707. case bitc::METADATA_DERIVED_TYPE:
  708. case bitc::METADATA_COMPOSITE_TYPE:
  709. case bitc::METADATA_SUBROUTINE_TYPE:
  710. case bitc::METADATA_MODULE:
  711. case bitc::METADATA_FILE:
  712. case bitc::METADATA_COMPILE_UNIT:
  713. case bitc::METADATA_SUBPROGRAM:
  714. case bitc::METADATA_LEXICAL_BLOCK:
  715. case bitc::METADATA_LEXICAL_BLOCK_FILE:
  716. case bitc::METADATA_NAMESPACE:
  717. case bitc::METADATA_MACRO:
  718. case bitc::METADATA_MACRO_FILE:
  719. case bitc::METADATA_TEMPLATE_TYPE:
  720. case bitc::METADATA_TEMPLATE_VALUE:
  721. case bitc::METADATA_GLOBAL_VAR:
  722. case bitc::METADATA_LOCAL_VAR:
  723. case bitc::METADATA_EXPRESSION:
  724. case bitc::METADATA_OBJC_PROPERTY:
  725. case bitc::METADATA_IMPORTED_ENTITY:
  726. case bitc::METADATA_GLOBAL_VAR_EXPR:
  727. // We don't expect to see any of these, if we see one, give up on
  728. // lazy-loading and fallback.
  729. MDStringRef.clear();
  730. GlobalMetadataBitPosIndex.clear();
  731. return false;
  732. }
  733. break;
  734. }
  735. }
  736. }
  737. }
  738. /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
  739. /// module level metadata.
  740. Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
  741. if (!ModuleLevel && MetadataList.hasFwdRefs())
  742. return error("Invalid metadata: fwd refs into function blocks");
  743. // Record the entry position so that we can jump back here and efficiently
  744. // skip the whole block in case we lazy-load.
  745. auto EntryPos = Stream.GetCurrentBitNo();
  746. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  747. return error("Invalid record");
  748. SmallVector<uint64_t, 64> Record;
  749. PlaceholderQueue Placeholders;
  750. // We lazy-load module-level metadata: we build an index for each record, and
  751. // then load individual record as needed, starting with the named metadata.
  752. if (ModuleLevel && IsImporting && MetadataList.empty() &&
  753. !DisableLazyLoading) {
  754. auto SuccessOrErr = lazyLoadModuleMetadataBlock();
  755. if (!SuccessOrErr)
  756. return SuccessOrErr.takeError();
  757. if (SuccessOrErr.get()) {
  758. // An index was successfully created and we will be able to load metadata
  759. // on-demand.
  760. MetadataList.resize(MDStringRef.size() +
  761. GlobalMetadataBitPosIndex.size());
  762. // Reading the named metadata created forward references and/or
  763. // placeholders, that we flush here.
  764. resolveForwardRefsAndPlaceholders(Placeholders);
  765. upgradeDebugInfo();
  766. // Return at the beginning of the block, since it is easy to skip it
  767. // entirely from there.
  768. Stream.ReadBlockEnd(); // Pop the abbrev block context.
  769. Stream.JumpToBit(EntryPos);
  770. if (Stream.SkipBlock())
  771. return error("Invalid record");
  772. return Error::success();
  773. }
  774. // Couldn't load an index, fallback to loading all the block "old-style".
  775. }
  776. unsigned NextMetadataNo = MetadataList.size();
  777. // Read all the records.
  778. while (true) {
  779. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  780. switch (Entry.Kind) {
  781. case BitstreamEntry::SubBlock: // Handled for us already.
  782. case BitstreamEntry::Error:
  783. return error("Malformed block");
  784. case BitstreamEntry::EndBlock:
  785. resolveForwardRefsAndPlaceholders(Placeholders);
  786. upgradeDebugInfo();
  787. return Error::success();
  788. case BitstreamEntry::Record:
  789. // The interesting case.
  790. break;
  791. }
  792. // Read a record.
  793. Record.clear();
  794. StringRef Blob;
  795. ++NumMDRecordLoaded;
  796. unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
  797. if (Error Err =
  798. parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
  799. return Err;
  800. }
  801. }
  802. MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
  803. ++NumMDStringLoaded;
  804. if (Metadata *MD = MetadataList.lookup(ID))
  805. return cast<MDString>(MD);
  806. auto MDS = MDString::get(Context, MDStringRef[ID]);
  807. MetadataList.assignValue(MDS, ID);
  808. return MDS;
  809. }
  810. void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
  811. unsigned ID, PlaceholderQueue &Placeholders) {
  812. assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
  813. assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
  814. // Lookup first if the metadata hasn't already been loaded.
  815. if (auto *MD = MetadataList.lookup(ID)) {
  816. auto *N = dyn_cast_or_null<MDNode>(MD);
  817. if (!N->isTemporary())
  818. return;
  819. }
  820. SmallVector<uint64_t, 64> Record;
  821. StringRef Blob;
  822. IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
  823. auto Entry = IndexCursor.advanceSkippingSubblocks();
  824. ++NumMDRecordLoaded;
  825. unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
  826. if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
  827. report_fatal_error("Can't lazyload MD");
  828. }
  829. /// Ensure that all forward-references and placeholders are resolved.
  830. /// Iteratively lazy-loading metadata on-demand if needed.
  831. void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
  832. PlaceholderQueue &Placeholders) {
  833. DenseSet<unsigned> Temporaries;
  834. while (1) {
  835. // Populate Temporaries with the placeholders that haven't been loaded yet.
  836. Placeholders.getTemporaries(MetadataList, Temporaries);
  837. // If we don't have any temporary, or FwdReference, we're done!
  838. if (Temporaries.empty() && !MetadataList.hasFwdRefs())
  839. break;
  840. // First, load all the temporaries. This can add new placeholders or
  841. // forward references.
  842. for (auto ID : Temporaries)
  843. lazyLoadOneMetadata(ID, Placeholders);
  844. Temporaries.clear();
  845. // Second, load the forward-references. This can also add new placeholders
  846. // or forward references.
  847. while (MetadataList.hasFwdRefs())
  848. lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
  849. }
  850. // At this point we don't have any forward reference remaining, or temporary
  851. // that haven't been loaded. We can safely drop RAUW support and mark cycles
  852. // as resolved.
  853. MetadataList.tryToResolveCycles();
  854. // Finally, everything is in place, we can replace the placeholders operands
  855. // with the final node they refer to.
  856. Placeholders.flush(MetadataList);
  857. }
  858. Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
  859. SmallVectorImpl<uint64_t> &Record, unsigned Code,
  860. PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
  861. bool IsDistinct = false;
  862. auto getMD = [&](unsigned ID) -> Metadata * {
  863. if (ID < MDStringRef.size())
  864. return lazyLoadOneMDString(ID);
  865. if (!IsDistinct) {
  866. if (auto *MD = MetadataList.lookup(ID))
  867. return MD;
  868. // If lazy-loading is enabled, we try recursively to load the operand
  869. // instead of creating a temporary.
  870. if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
  871. // Create a temporary for the node that is referencing the operand we
  872. // will lazy-load. It is needed before recursing in case there are
  873. // uniquing cycles.
  874. MetadataList.getMetadataFwdRef(NextMetadataNo);
  875. lazyLoadOneMetadata(ID, Placeholders);
  876. return MetadataList.lookup(ID);
  877. }
  878. // Return a temporary.
  879. return MetadataList.getMetadataFwdRef(ID);
  880. }
  881. if (auto *MD = MetadataList.getMetadataIfResolved(ID))
  882. return MD;
  883. return &Placeholders.getPlaceholderOp(ID);
  884. };
  885. auto getMDOrNull = [&](unsigned ID) -> Metadata * {
  886. if (ID)
  887. return getMD(ID - 1);
  888. return nullptr;
  889. };
  890. auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
  891. if (ID)
  892. return MetadataList.getMetadataFwdRef(ID - 1);
  893. return nullptr;
  894. };
  895. auto getMDString = [&](unsigned ID) -> MDString * {
  896. // This requires that the ID is not really a forward reference. In
  897. // particular, the MDString must already have been resolved.
  898. auto MDS = getMDOrNull(ID);
  899. return cast_or_null<MDString>(MDS);
  900. };
  901. // Support for old type refs.
  902. auto getDITypeRefOrNull = [&](unsigned ID) {
  903. return MetadataList.upgradeTypeRef(getMDOrNull(ID));
  904. };
  905. #define GET_OR_DISTINCT(CLASS, ARGS) \
  906. (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  907. switch (Code) {
  908. default: // Default behavior: ignore.
  909. break;
  910. case bitc::METADATA_NAME: {
  911. // Read name of the named metadata.
  912. SmallString<8> Name(Record.begin(), Record.end());
  913. Record.clear();
  914. Code = Stream.ReadCode();
  915. ++NumMDRecordLoaded;
  916. unsigned NextBitCode = Stream.readRecord(Code, Record);
  917. if (NextBitCode != bitc::METADATA_NAMED_NODE)
  918. return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
  919. // Read named metadata elements.
  920. unsigned Size = Record.size();
  921. NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
  922. for (unsigned i = 0; i != Size; ++i) {
  923. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
  924. if (!MD)
  925. return error("Invalid record");
  926. NMD->addOperand(MD);
  927. }
  928. break;
  929. }
  930. case bitc::METADATA_OLD_FN_NODE: {
  931. // FIXME: Remove in 4.0.
  932. // This is a LocalAsMetadata record, the only type of function-local
  933. // metadata.
  934. if (Record.size() % 2 == 1)
  935. return error("Invalid record");
  936. // If this isn't a LocalAsMetadata record, we're dropping it. This used
  937. // to be legal, but there's no upgrade path.
  938. auto dropRecord = [&] {
  939. MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
  940. NextMetadataNo++;
  941. };
  942. if (Record.size() != 2) {
  943. dropRecord();
  944. break;
  945. }
  946. Type *Ty = getTypeByID(Record[0]);
  947. if (Ty->isMetadataTy() || Ty->isVoidTy()) {
  948. dropRecord();
  949. break;
  950. }
  951. MetadataList.assignValue(
  952. LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  953. NextMetadataNo);
  954. NextMetadataNo++;
  955. break;
  956. }
  957. case bitc::METADATA_OLD_NODE: {
  958. // FIXME: Remove in 4.0.
  959. if (Record.size() % 2 == 1)
  960. return error("Invalid record");
  961. unsigned Size = Record.size();
  962. SmallVector<Metadata *, 8> Elts;
  963. for (unsigned i = 0; i != Size; i += 2) {
  964. Type *Ty = getTypeByID(Record[i]);
  965. if (!Ty)
  966. return error("Invalid record");
  967. if (Ty->isMetadataTy())
  968. Elts.push_back(getMD(Record[i + 1]));
  969. else if (!Ty->isVoidTy()) {
  970. auto *MD =
  971. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
  972. assert(isa<ConstantAsMetadata>(MD) &&
  973. "Expected non-function-local metadata");
  974. Elts.push_back(MD);
  975. } else
  976. Elts.push_back(nullptr);
  977. }
  978. MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
  979. NextMetadataNo++;
  980. break;
  981. }
  982. case bitc::METADATA_VALUE: {
  983. if (Record.size() != 2)
  984. return error("Invalid record");
  985. Type *Ty = getTypeByID(Record[0]);
  986. if (Ty->isMetadataTy() || Ty->isVoidTy())
  987. return error("Invalid record");
  988. MetadataList.assignValue(
  989. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  990. NextMetadataNo);
  991. NextMetadataNo++;
  992. break;
  993. }
  994. case bitc::METADATA_DISTINCT_NODE:
  995. IsDistinct = true;
  996. LLVM_FALLTHROUGH;
  997. case bitc::METADATA_NODE: {
  998. SmallVector<Metadata *, 8> Elts;
  999. Elts.reserve(Record.size());
  1000. for (unsigned ID : Record)
  1001. Elts.push_back(getMDOrNull(ID));
  1002. MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
  1003. : MDNode::get(Context, Elts),
  1004. NextMetadataNo);
  1005. NextMetadataNo++;
  1006. break;
  1007. }
  1008. case bitc::METADATA_LOCATION: {
  1009. if (Record.size() != 5)
  1010. return error("Invalid record");
  1011. IsDistinct = Record[0];
  1012. unsigned Line = Record[1];
  1013. unsigned Column = Record[2];
  1014. Metadata *Scope = getMD(Record[3]);
  1015. Metadata *InlinedAt = getMDOrNull(Record[4]);
  1016. MetadataList.assignValue(
  1017. GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
  1018. NextMetadataNo);
  1019. NextMetadataNo++;
  1020. break;
  1021. }
  1022. case bitc::METADATA_GENERIC_DEBUG: {
  1023. if (Record.size() < 4)
  1024. return error("Invalid record");
  1025. IsDistinct = Record[0];
  1026. unsigned Tag = Record[1];
  1027. unsigned Version = Record[2];
  1028. if (Tag >= 1u << 16 || Version != 0)
  1029. return error("Invalid record");
  1030. auto *Header = getMDString(Record[3]);
  1031. SmallVector<Metadata *, 8> DwarfOps;
  1032. for (unsigned I = 4, E = Record.size(); I != E; ++I)
  1033. DwarfOps.push_back(getMDOrNull(Record[I]));
  1034. MetadataList.assignValue(
  1035. GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
  1036. NextMetadataNo);
  1037. NextMetadataNo++;
  1038. break;
  1039. }
  1040. case bitc::METADATA_SUBRANGE: {
  1041. if (Record.size() != 3)
  1042. return error("Invalid record");
  1043. IsDistinct = Record[0];
  1044. MetadataList.assignValue(
  1045. GET_OR_DISTINCT(DISubrange,
  1046. (Context, Record[1], unrotateSign(Record[2]))),
  1047. NextMetadataNo);
  1048. NextMetadataNo++;
  1049. break;
  1050. }
  1051. case bitc::METADATA_ENUMERATOR: {
  1052. if (Record.size() != 3)
  1053. return error("Invalid record");
  1054. IsDistinct = Record[0];
  1055. MetadataList.assignValue(
  1056. GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
  1057. getMDString(Record[2]))),
  1058. NextMetadataNo);
  1059. NextMetadataNo++;
  1060. break;
  1061. }
  1062. case bitc::METADATA_BASIC_TYPE: {
  1063. if (Record.size() != 6)
  1064. return error("Invalid record");
  1065. IsDistinct = Record[0];
  1066. MetadataList.assignValue(
  1067. GET_OR_DISTINCT(DIBasicType,
  1068. (Context, Record[1], getMDString(Record[2]), Record[3],
  1069. Record[4], Record[5])),
  1070. NextMetadataNo);
  1071. NextMetadataNo++;
  1072. break;
  1073. }
  1074. case bitc::METADATA_DERIVED_TYPE: {
  1075. if (Record.size() < 12 || Record.size() > 13)
  1076. return error("Invalid record");
  1077. // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
  1078. // that there is no DWARF address space associated with DIDerivedType.
  1079. Optional<unsigned> DWARFAddressSpace;
  1080. if (Record.size() > 12 && Record[12])
  1081. DWARFAddressSpace = Record[12] - 1;
  1082. IsDistinct = Record[0];
  1083. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
  1084. MetadataList.assignValue(
  1085. GET_OR_DISTINCT(DIDerivedType,
  1086. (Context, Record[1], getMDString(Record[2]),
  1087. getMDOrNull(Record[3]), Record[4],
  1088. getDITypeRefOrNull(Record[5]),
  1089. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1090. Record[9], DWARFAddressSpace, Flags,
  1091. getDITypeRefOrNull(Record[11]))),
  1092. NextMetadataNo);
  1093. NextMetadataNo++;
  1094. break;
  1095. }
  1096. case bitc::METADATA_COMPOSITE_TYPE: {
  1097. if (Record.size() != 16)
  1098. return error("Invalid record");
  1099. // If we have a UUID and this is not a forward declaration, lookup the
  1100. // mapping.
  1101. IsDistinct = Record[0] & 0x1;
  1102. bool IsNotUsedInTypeRef = Record[0] >= 2;
  1103. unsigned Tag = Record[1];
  1104. MDString *Name = getMDString(Record[2]);
  1105. Metadata *File = getMDOrNull(Record[3]);
  1106. unsigned Line = Record[4];
  1107. Metadata *Scope = getDITypeRefOrNull(Record[5]);
  1108. Metadata *BaseType = nullptr;
  1109. uint64_t SizeInBits = Record[7];
  1110. if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
  1111. return error("Alignment value is too large");
  1112. uint32_t AlignInBits = Record[8];
  1113. uint64_t OffsetInBits = 0;
  1114. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
  1115. Metadata *Elements = nullptr;
  1116. unsigned RuntimeLang = Record[12];
  1117. Metadata *VTableHolder = nullptr;
  1118. Metadata *TemplateParams = nullptr;
  1119. auto *Identifier = getMDString(Record[15]);
  1120. // If this module is being parsed so that it can be ThinLTO imported
  1121. // into another module, composite types only need to be imported
  1122. // as type declarations (unless full type definitions requested).
  1123. // Create type declarations up front to save memory. Also, buildODRType
  1124. // handles the case where this is type ODRed with a definition needed
  1125. // by the importing module, in which case the existing definition is
  1126. // used.
  1127. if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
  1128. (Tag == dwarf::DW_TAG_enumeration_type ||
  1129. Tag == dwarf::DW_TAG_class_type ||
  1130. Tag == dwarf::DW_TAG_structure_type ||
  1131. Tag == dwarf::DW_TAG_union_type)) {
  1132. Flags = Flags | DINode::FlagFwdDecl;
  1133. } else {
  1134. BaseType = getDITypeRefOrNull(Record[6]);
  1135. OffsetInBits = Record[9];
  1136. Elements = getMDOrNull(Record[11]);
  1137. VTableHolder = getDITypeRefOrNull(Record[13]);
  1138. TemplateParams = getMDOrNull(Record[14]);
  1139. }
  1140. DICompositeType *CT = nullptr;
  1141. if (Identifier)
  1142. CT = DICompositeType::buildODRType(
  1143. Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
  1144. SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  1145. VTableHolder, TemplateParams);
  1146. // Create a node if we didn't get a lazy ODR type.
  1147. if (!CT)
  1148. CT = GET_OR_DISTINCT(DICompositeType,
  1149. (Context, Tag, Name, File, Line, Scope, BaseType,
  1150. SizeInBits, AlignInBits, OffsetInBits, Flags,
  1151. Elements, RuntimeLang, VTableHolder, TemplateParams,
  1152. Identifier));
  1153. if (!IsNotUsedInTypeRef && Identifier)
  1154. MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
  1155. MetadataList.assignValue(CT, NextMetadataNo);
  1156. NextMetadataNo++;
  1157. break;
  1158. }
  1159. case bitc::METADATA_SUBROUTINE_TYPE: {
  1160. if (Record.size() < 3 || Record.size() > 4)
  1161. return error("Invalid record");
  1162. bool IsOldTypeRefArray = Record[0] < 2;
  1163. unsigned CC = (Record.size() > 3) ? Record[3] : 0;
  1164. IsDistinct = Record[0] & 0x1;
  1165. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
  1166. Metadata *Types = getMDOrNull(Record[2]);
  1167. if (LLVM_UNLIKELY(IsOldTypeRefArray))
  1168. Types = MetadataList.upgradeTypeRefArray(Types);
  1169. MetadataList.assignValue(
  1170. GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
  1171. NextMetadataNo);
  1172. NextMetadataNo++;
  1173. break;
  1174. }
  1175. case bitc::METADATA_MODULE: {
  1176. if (Record.size() != 6)
  1177. return error("Invalid record");
  1178. IsDistinct = Record[0];
  1179. MetadataList.assignValue(
  1180. GET_OR_DISTINCT(DIModule,
  1181. (Context, getMDOrNull(Record[1]),
  1182. getMDString(Record[2]), getMDString(Record[3]),
  1183. getMDString(Record[4]), getMDString(Record[5]))),
  1184. NextMetadataNo);
  1185. NextMetadataNo++;
  1186. break;
  1187. }
  1188. case bitc::METADATA_FILE: {
  1189. if (Record.size() != 3 && Record.size() != 5)
  1190. return error("Invalid record");
  1191. IsDistinct = Record[0];
  1192. MetadataList.assignValue(
  1193. GET_OR_DISTINCT(
  1194. DIFile,
  1195. (Context, getMDString(Record[1]), getMDString(Record[2]),
  1196. Record.size() == 3 ? DIFile::CSK_None
  1197. : static_cast<DIFile::ChecksumKind>(Record[3]),
  1198. Record.size() == 3 ? nullptr : getMDString(Record[4]))),
  1199. NextMetadataNo);
  1200. NextMetadataNo++;
  1201. break;
  1202. }
  1203. case bitc::METADATA_COMPILE_UNIT: {
  1204. if (Record.size() < 14 || Record.size() > 18)
  1205. return error("Invalid record");
  1206. // Ignore Record[0], which indicates whether this compile unit is
  1207. // distinct. It's always distinct.
  1208. IsDistinct = true;
  1209. auto *CU = DICompileUnit::getDistinct(
  1210. Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
  1211. Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
  1212. Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
  1213. getMDOrNull(Record[12]), getMDOrNull(Record[13]),
  1214. Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
  1215. Record.size() <= 14 ? 0 : Record[14],
  1216. Record.size() <= 16 ? true : Record[16],
  1217. Record.size() <= 17 ? false : Record[17]);
  1218. MetadataList.assignValue(CU, NextMetadataNo);
  1219. NextMetadataNo++;
  1220. // Move the Upgrade the list of subprograms.
  1221. if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
  1222. CUSubprograms.push_back({CU, SPs});
  1223. break;
  1224. }
  1225. case bitc::METADATA_SUBPROGRAM: {
  1226. if (Record.size() < 18 || Record.size() > 21)
  1227. return error("Invalid record");
  1228. IsDistinct =
  1229. (Record[0] & 1) || Record[8]; // All definitions should be distinct.
  1230. // Version 1 has a Function as Record[15].
  1231. // Version 2 has removed Record[15].
  1232. // Version 3 has the Unit as Record[15].
  1233. // Version 4 added thisAdjustment.
  1234. bool HasUnit = Record[0] >= 2;
  1235. if (HasUnit && Record.size() < 19)
  1236. return error("Invalid record");
  1237. Metadata *CUorFn = getMDOrNull(Record[15]);
  1238. unsigned Offset = Record.size() >= 19 ? 1 : 0;
  1239. bool HasFn = Offset && !HasUnit;
  1240. bool HasThisAdj = Record.size() >= 20;
  1241. bool HasThrownTypes = Record.size() >= 21;
  1242. DISubprogram *SP = GET_OR_DISTINCT(
  1243. DISubprogram,
  1244. (Context,
  1245. getDITypeRefOrNull(Record[1]), // scope
  1246. getMDString(Record[2]), // name
  1247. getMDString(Record[3]), // linkageName
  1248. getMDOrNull(Record[4]), // file
  1249. Record[5], // line
  1250. getMDOrNull(Record[6]), // type
  1251. Record[7], // isLocal
  1252. Record[8], // isDefinition
  1253. Record[9], // scopeLine
  1254. getDITypeRefOrNull(Record[10]), // containingType
  1255. Record[11], // virtuality
  1256. Record[12], // virtualIndex
  1257. HasThisAdj ? Record[19] : 0, // thisAdjustment
  1258. static_cast<DINode::DIFlags>(Record[13]), // flags
  1259. Record[14], // isOptimized
  1260. HasUnit ? CUorFn : nullptr, // unit
  1261. getMDOrNull(Record[15 + Offset]), // templateParams
  1262. getMDOrNull(Record[16 + Offset]), // declaration
  1263. getMDOrNull(Record[17 + Offset]), // variables
  1264. HasThrownTypes ? getMDOrNull(Record[20]) : nullptr // thrownTypes
  1265. ));
  1266. MetadataList.assignValue(SP, NextMetadataNo);
  1267. NextMetadataNo++;
  1268. // Upgrade sp->function mapping to function->sp mapping.
  1269. if (HasFn) {
  1270. if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
  1271. if (auto *F = dyn_cast<Function>(CMD->getValue())) {
  1272. if (F->isMaterializable())
  1273. // Defer until materialized; unmaterialized functions may not have
  1274. // metadata.
  1275. FunctionsWithSPs[F] = SP;
  1276. else if (!F->empty())
  1277. F->setSubprogram(SP);
  1278. }
  1279. }
  1280. break;
  1281. }
  1282. case bitc::METADATA_LEXICAL_BLOCK: {
  1283. if (Record.size() != 5)
  1284. return error("Invalid record");
  1285. IsDistinct = Record[0];
  1286. MetadataList.assignValue(
  1287. GET_OR_DISTINCT(DILexicalBlock,
  1288. (Context, getMDOrNull(Record[1]),
  1289. getMDOrNull(Record[2]), Record[3], Record[4])),
  1290. NextMetadataNo);
  1291. NextMetadataNo++;
  1292. break;
  1293. }
  1294. case bitc::METADATA_LEXICAL_BLOCK_FILE: {
  1295. if (Record.size() != 4)
  1296. return error("Invalid record");
  1297. IsDistinct = Record[0];
  1298. MetadataList.assignValue(
  1299. GET_OR_DISTINCT(DILexicalBlockFile,
  1300. (Context, getMDOrNull(Record[1]),
  1301. getMDOrNull(Record[2]), Record[3])),
  1302. NextMetadataNo);
  1303. NextMetadataNo++;
  1304. break;
  1305. }
  1306. case bitc::METADATA_NAMESPACE: {
  1307. // Newer versions of DINamespace dropped file and line.
  1308. MDString *Name;
  1309. if (Record.size() == 3)
  1310. Name = getMDString(Record[2]);
  1311. else if (Record.size() == 5)
  1312. Name = getMDString(Record[3]);
  1313. else
  1314. return error("Invalid record");
  1315. IsDistinct = Record[0] & 1;
  1316. bool ExportSymbols = Record[0] & 2;
  1317. MetadataList.assignValue(
  1318. GET_OR_DISTINCT(DINamespace,
  1319. (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
  1320. NextMetadataNo);
  1321. NextMetadataNo++;
  1322. break;
  1323. }
  1324. case bitc::METADATA_MACRO: {
  1325. if (Record.size() != 5)
  1326. return error("Invalid record");
  1327. IsDistinct = Record[0];
  1328. MetadataList.assignValue(
  1329. GET_OR_DISTINCT(DIMacro,
  1330. (Context, Record[1], Record[2], getMDString(Record[3]),
  1331. getMDString(Record[4]))),
  1332. NextMetadataNo);
  1333. NextMetadataNo++;
  1334. break;
  1335. }
  1336. case bitc::METADATA_MACRO_FILE: {
  1337. if (Record.size() != 5)
  1338. return error("Invalid record");
  1339. IsDistinct = Record[0];
  1340. MetadataList.assignValue(
  1341. GET_OR_DISTINCT(DIMacroFile,
  1342. (Context, Record[1], Record[2], getMDOrNull(Record[3]),
  1343. getMDOrNull(Record[4]))),
  1344. NextMetadataNo);
  1345. NextMetadataNo++;
  1346. break;
  1347. }
  1348. case bitc::METADATA_TEMPLATE_TYPE: {
  1349. if (Record.size() != 3)
  1350. return error("Invalid record");
  1351. IsDistinct = Record[0];
  1352. MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
  1353. (Context, getMDString(Record[1]),
  1354. getDITypeRefOrNull(Record[2]))),
  1355. NextMetadataNo);
  1356. NextMetadataNo++;
  1357. break;
  1358. }
  1359. case bitc::METADATA_TEMPLATE_VALUE: {
  1360. if (Record.size() != 5)
  1361. return error("Invalid record");
  1362. IsDistinct = Record[0];
  1363. MetadataList.assignValue(
  1364. GET_OR_DISTINCT(DITemplateValueParameter,
  1365. (Context, Record[1], getMDString(Record[2]),
  1366. getDITypeRefOrNull(Record[3]),
  1367. getMDOrNull(Record[4]))),
  1368. NextMetadataNo);
  1369. NextMetadataNo++;
  1370. break;
  1371. }
  1372. case bitc::METADATA_GLOBAL_VAR: {
  1373. if (Record.size() < 11 || Record.size() > 12)
  1374. return error("Invalid record");
  1375. IsDistinct = Record[0] & 1;
  1376. unsigned Version = Record[0] >> 1;
  1377. if (Version == 1) {
  1378. MetadataList.assignValue(
  1379. GET_OR_DISTINCT(DIGlobalVariable,
  1380. (Context, getMDOrNull(Record[1]),
  1381. getMDString(Record[2]), getMDString(Record[3]),
  1382. getMDOrNull(Record[4]), Record[5],
  1383. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1384. getMDOrNull(Record[10]), Record[11])),
  1385. NextMetadataNo);
  1386. NextMetadataNo++;
  1387. } else if (Version == 0) {
  1388. // Upgrade old metadata, which stored a global variable reference or a
  1389. // ConstantInt here.
  1390. NeedUpgradeToDIGlobalVariableExpression = true;
  1391. Metadata *Expr = getMDOrNull(Record[9]);
  1392. uint32_t AlignInBits = 0;
  1393. if (Record.size() > 11) {
  1394. if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
  1395. return error("Alignment value is too large");
  1396. AlignInBits = Record[11];
  1397. }
  1398. GlobalVariable *Attach = nullptr;
  1399. if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
  1400. if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
  1401. Attach = GV;
  1402. Expr = nullptr;
  1403. } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
  1404. Expr = DIExpression::get(Context,
  1405. {dwarf::DW_OP_constu, CI->getZExtValue(),
  1406. dwarf::DW_OP_stack_value});
  1407. } else {
  1408. Expr = nullptr;
  1409. }
  1410. }
  1411. DIGlobalVariable *DGV = GET_OR_DISTINCT(
  1412. DIGlobalVariable,
  1413. (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
  1414. getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
  1415. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1416. getMDOrNull(Record[10]), AlignInBits));
  1417. DIGlobalVariableExpression *DGVE = nullptr;
  1418. if (Attach || Expr)
  1419. DGVE = DIGlobalVariableExpression::getDistinct(
  1420. Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
  1421. if (Attach)
  1422. Attach->addDebugInfo(DGVE);
  1423. auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
  1424. MetadataList.assignValue(MDNode, NextMetadataNo);
  1425. NextMetadataNo++;
  1426. } else
  1427. return error("Invalid record");
  1428. break;
  1429. }
  1430. case bitc::METADATA_LOCAL_VAR: {
  1431. // 10th field is for the obseleted 'inlinedAt:' field.
  1432. if (Record.size() < 8 || Record.size() > 10)
  1433. return error("Invalid record");
  1434. IsDistinct = Record[0] & 1;
  1435. bool HasAlignment = Record[0] & 2;
  1436. // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
  1437. // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
  1438. // this is newer version of record which doesn't have artificial tag.
  1439. bool HasTag = !HasAlignment && Record.size() > 8;
  1440. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
  1441. uint32_t AlignInBits = 0;
  1442. if (HasAlignment) {
  1443. if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
  1444. return error("Alignment value is too large");
  1445. AlignInBits = Record[8 + HasTag];
  1446. }
  1447. MetadataList.assignValue(
  1448. GET_OR_DISTINCT(DILocalVariable,
  1449. (Context, getMDOrNull(Record[1 + HasTag]),
  1450. getMDString(Record[2 + HasTag]),
  1451. getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
  1452. getDITypeRefOrNull(Record[5 + HasTag]),
  1453. Record[6 + HasTag], Flags, AlignInBits)),
  1454. NextMetadataNo);
  1455. NextMetadataNo++;
  1456. break;
  1457. }
  1458. case bitc::METADATA_EXPRESSION: {
  1459. if (Record.size() < 1)
  1460. return error("Invalid record");
  1461. IsDistinct = Record[0] & 1;
  1462. uint64_t Version = Record[0] >> 1;
  1463. auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
  1464. SmallVector<uint64_t, 6> Buffer;
  1465. if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
  1466. return Err;
  1467. MetadataList.assignValue(
  1468. GET_OR_DISTINCT(DIExpression, (Context, Elts)), NextMetadataNo);
  1469. NextMetadataNo++;
  1470. break;
  1471. }
  1472. case bitc::METADATA_GLOBAL_VAR_EXPR: {
  1473. if (Record.size() != 3)
  1474. return error("Invalid record");
  1475. IsDistinct = Record[0];
  1476. Metadata *Expr = getMDOrNull(Record[2]);
  1477. if (!Expr)
  1478. Expr = DIExpression::get(Context, {});
  1479. MetadataList.assignValue(
  1480. GET_OR_DISTINCT(DIGlobalVariableExpression,
  1481. (Context, getMDOrNull(Record[1]), Expr)),
  1482. NextMetadataNo);
  1483. NextMetadataNo++;
  1484. break;
  1485. }
  1486. case bitc::METADATA_OBJC_PROPERTY: {
  1487. if (Record.size() != 8)
  1488. return error("Invalid record");
  1489. IsDistinct = Record[0];
  1490. MetadataList.assignValue(
  1491. GET_OR_DISTINCT(DIObjCProperty,
  1492. (Context, getMDString(Record[1]),
  1493. getMDOrNull(Record[2]), Record[3],
  1494. getMDString(Record[4]), getMDString(Record[5]),
  1495. Record[6], getDITypeRefOrNull(Record[7]))),
  1496. NextMetadataNo);
  1497. NextMetadataNo++;
  1498. break;
  1499. }
  1500. case bitc::METADATA_IMPORTED_ENTITY: {
  1501. if (Record.size() != 6 && Record.size() != 7)
  1502. return error("Invalid record");
  1503. IsDistinct = Record[0];
  1504. bool HasFile = (Record.size() == 7);
  1505. MetadataList.assignValue(
  1506. GET_OR_DISTINCT(DIImportedEntity,
  1507. (Context, Record[1], getMDOrNull(Record[2]),
  1508. getDITypeRefOrNull(Record[3]),
  1509. HasFile ? getMDOrNull(Record[6]) : nullptr,
  1510. HasFile ? Record[4] : 0, getMDString(Record[5]))),
  1511. NextMetadataNo);
  1512. NextMetadataNo++;
  1513. break;
  1514. }
  1515. case bitc::METADATA_STRING_OLD: {
  1516. std::string String(Record.begin(), Record.end());
  1517. // Test for upgrading !llvm.loop.
  1518. HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
  1519. ++NumMDStringLoaded;
  1520. Metadata *MD = MDString::get(Context, String);
  1521. MetadataList.assignValue(MD, NextMetadataNo);
  1522. NextMetadataNo++;
  1523. break;
  1524. }
  1525. case bitc::METADATA_STRINGS: {
  1526. auto CreateNextMDString = [&](StringRef Str) {
  1527. ++NumMDStringLoaded;
  1528. MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
  1529. NextMetadataNo++;
  1530. };
  1531. if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
  1532. return Err;
  1533. break;
  1534. }
  1535. case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
  1536. if (Record.size() % 2 == 0)
  1537. return error("Invalid record");
  1538. unsigned ValueID = Record[0];
  1539. if (ValueID >= ValueList.size())
  1540. return error("Invalid record");
  1541. if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
  1542. if (Error Err = parseGlobalObjectAttachment(
  1543. *GO, ArrayRef<uint64_t>(Record).slice(1)))
  1544. return Err;
  1545. break;
  1546. }
  1547. case bitc::METADATA_KIND: {
  1548. // Support older bitcode files that had METADATA_KIND records in a
  1549. // block with METADATA_BLOCK_ID.
  1550. if (Error Err = parseMetadataKindRecord(Record))
  1551. return Err;
  1552. break;
  1553. }
  1554. }
  1555. return Error::success();
  1556. #undef GET_OR_DISTINCT
  1557. }
  1558. Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
  1559. ArrayRef<uint64_t> Record, StringRef Blob,
  1560. function_ref<void(StringRef)> CallBack) {
  1561. // All the MDStrings in the block are emitted together in a single
  1562. // record. The strings are concatenated and stored in a blob along with
  1563. // their sizes.
  1564. if (Record.size() != 2)
  1565. return error("Invalid record: metadata strings layout");
  1566. unsigned NumStrings = Record[0];
  1567. unsigned StringsOffset = Record[1];
  1568. if (!NumStrings)
  1569. return error("Invalid record: metadata strings with no strings");
  1570. if (StringsOffset > Blob.size())
  1571. return error("Invalid record: metadata strings corrupt offset");
  1572. StringRef Lengths = Blob.slice(0, StringsOffset);
  1573. SimpleBitstreamCursor R(Lengths);
  1574. StringRef Strings = Blob.drop_front(StringsOffset);
  1575. do {
  1576. if (R.AtEndOfStream())
  1577. return error("Invalid record: metadata strings bad length");
  1578. unsigned Size = R.ReadVBR(6);
  1579. if (Strings.size() < Size)
  1580. return error("Invalid record: metadata strings truncated chars");
  1581. CallBack(Strings.slice(0, Size));
  1582. Strings = Strings.drop_front(Size);
  1583. } while (--NumStrings);
  1584. return Error::success();
  1585. }
  1586. Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
  1587. GlobalObject &GO, ArrayRef<uint64_t> Record) {
  1588. assert(Record.size() % 2 == 0);
  1589. for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
  1590. auto K = MDKindMap.find(Record[I]);
  1591. if (K == MDKindMap.end())
  1592. return error("Invalid ID");
  1593. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
  1594. if (!MD)
  1595. return error("Invalid metadata attachment");
  1596. GO.addMetadata(K->second, *MD);
  1597. }
  1598. return Error::success();
  1599. }
  1600. /// Parse metadata attachments.
  1601. Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
  1602. Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
  1603. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1604. return error("Invalid record");
  1605. SmallVector<uint64_t, 64> Record;
  1606. PlaceholderQueue Placeholders;
  1607. while (true) {
  1608. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1609. switch (Entry.Kind) {
  1610. case BitstreamEntry::SubBlock: // Handled for us already.
  1611. case BitstreamEntry::Error:
  1612. return error("Malformed block");
  1613. case BitstreamEntry::EndBlock:
  1614. resolveForwardRefsAndPlaceholders(Placeholders);
  1615. return Error::success();
  1616. case BitstreamEntry::Record:
  1617. // The interesting case.
  1618. break;
  1619. }
  1620. // Read a metadata attachment record.
  1621. Record.clear();
  1622. ++NumMDRecordLoaded;
  1623. switch (Stream.readRecord(Entry.ID, Record)) {
  1624. default: // Default behavior: ignore.
  1625. break;
  1626. case bitc::METADATA_ATTACHMENT: {
  1627. unsigned RecordLength = Record.size();
  1628. if (Record.empty())
  1629. return error("Invalid record");
  1630. if (RecordLength % 2 == 0) {
  1631. // A function attachment.
  1632. if (Error Err = parseGlobalObjectAttachment(F, Record))
  1633. return Err;
  1634. continue;
  1635. }
  1636. // An instruction attachment.
  1637. Instruction *Inst = InstructionList[Record[0]];
  1638. for (unsigned i = 1; i != RecordLength; i = i + 2) {
  1639. unsigned Kind = Record[i];
  1640. DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
  1641. if (I == MDKindMap.end())
  1642. return error("Invalid ID");
  1643. if (I->second == LLVMContext::MD_tbaa && StripTBAA)
  1644. continue;
  1645. auto Idx = Record[i + 1];
  1646. if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
  1647. !MetadataList.lookup(Idx)) {
  1648. // Load the attachment if it is in the lazy-loadable range and hasn't
  1649. // been loaded yet.
  1650. lazyLoadOneMetadata(Idx, Placeholders);
  1651. resolveForwardRefsAndPlaceholders(Placeholders);
  1652. }
  1653. Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
  1654. if (isa<LocalAsMetadata>(Node))
  1655. // Drop the attachment. This used to be legal, but there's no
  1656. // upgrade path.
  1657. break;
  1658. MDNode *MD = dyn_cast_or_null<MDNode>(Node);
  1659. if (!MD)
  1660. return error("Invalid metadata attachment");
  1661. if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
  1662. MD = upgradeInstructionLoopAttachment(*MD);
  1663. if (I->second == LLVMContext::MD_tbaa) {
  1664. assert(!MD->isTemporary() && "should load MDs before attachments");
  1665. MD = UpgradeTBAANode(*MD);
  1666. }
  1667. Inst->setMetadata(I->second, MD);
  1668. }
  1669. break;
  1670. }
  1671. }
  1672. }
  1673. }
  1674. /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
  1675. Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
  1676. SmallVectorImpl<uint64_t> &Record) {
  1677. if (Record.size() < 2)
  1678. return error("Invalid record");
  1679. unsigned Kind = Record[0];
  1680. SmallString<8> Name(Record.begin() + 1, Record.end());
  1681. unsigned NewKind = TheModule.getMDKindID(Name.str());
  1682. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  1683. return error("Conflicting METADATA_KIND records");
  1684. return Error::success();
  1685. }
  1686. /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
  1687. Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
  1688. if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
  1689. return error("Invalid record");
  1690. SmallVector<uint64_t, 64> Record;
  1691. // Read all the records.
  1692. while (true) {
  1693. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1694. switch (Entry.Kind) {
  1695. case BitstreamEntry::SubBlock: // Handled for us already.
  1696. case BitstreamEntry::Error:
  1697. return error("Malformed block");
  1698. case BitstreamEntry::EndBlock:
  1699. return Error::success();
  1700. case BitstreamEntry::Record:
  1701. // The interesting case.
  1702. break;
  1703. }
  1704. // Read a record.
  1705. Record.clear();
  1706. ++NumMDRecordLoaded;
  1707. unsigned Code = Stream.readRecord(Entry.ID, Record);
  1708. switch (Code) {
  1709. default: // Default behavior: ignore.
  1710. break;
  1711. case bitc::METADATA_KIND: {
  1712. if (Error Err = parseMetadataKindRecord(Record))
  1713. return Err;
  1714. break;
  1715. }
  1716. }
  1717. }
  1718. }
  1719. MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
  1720. Pimpl = std::move(RHS.Pimpl);
  1721. return *this;
  1722. }
  1723. MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
  1724. : Pimpl(std::move(RHS.Pimpl)) {}
  1725. MetadataLoader::~MetadataLoader() = default;
  1726. MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
  1727. BitcodeReaderValueList &ValueList,
  1728. bool IsImporting,
  1729. std::function<Type *(unsigned)> getTypeByID)
  1730. : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
  1731. Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
  1732. Error MetadataLoader::parseMetadata(bool ModuleLevel) {
  1733. return Pimpl->parseMetadata(ModuleLevel);
  1734. }
  1735. bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
  1736. /// Return the given metadata, creating a replaceable forward reference if
  1737. /// necessary.
  1738. Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
  1739. return Pimpl->getMetadataFwdRefOrLoad(Idx);
  1740. }
  1741. MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
  1742. return Pimpl->getMDNodeFwdRefOrNull(Idx);
  1743. }
  1744. DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
  1745. return Pimpl->lookupSubprogramForFunction(F);
  1746. }
  1747. Error MetadataLoader::parseMetadataAttachment(
  1748. Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
  1749. return Pimpl->parseMetadataAttachment(F, InstructionList);
  1750. }
  1751. Error MetadataLoader::parseMetadataKinds() {
  1752. return Pimpl->parseMetadataKinds();
  1753. }
  1754. void MetadataLoader::setStripTBAA(bool StripTBAA) {
  1755. return Pimpl->setStripTBAA(StripTBAA);
  1756. }
  1757. bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
  1758. unsigned MetadataLoader::size() const { return Pimpl->size(); }
  1759. void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
  1760. void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
  1761. return Pimpl->upgradeDebugIntrinsics(F);
  1762. }