MetadataLoader.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  1. //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
  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. #include "MetadataLoader.h"
  9. #include "ValueList.h"
  10. #include "llvm/ADT/APFloat.h"
  11. #include "llvm/ADT/APInt.h"
  12. #include "llvm/ADT/ArrayRef.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/DenseSet.h"
  15. #include "llvm/ADT/None.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/ADT/StringRef.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/Bitcode/BitcodeReader.h"
  22. #include "llvm/Bitcode/LLVMBitCodes.h"
  23. #include "llvm/Bitstream/BitstreamReader.h"
  24. #include "llvm/IR/Argument.h"
  25. #include "llvm/IR/Attributes.h"
  26. #include "llvm/IR/AutoUpgrade.h"
  27. #include "llvm/IR/BasicBlock.h"
  28. #include "llvm/IR/CallingConv.h"
  29. #include "llvm/IR/Comdat.h"
  30. #include "llvm/IR/Constant.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DebugInfo.h"
  33. #include "llvm/IR/DebugInfoMetadata.h"
  34. #include "llvm/IR/DebugLoc.h"
  35. #include "llvm/IR/DerivedTypes.h"
  36. #include "llvm/IR/DiagnosticPrinter.h"
  37. #include "llvm/IR/Function.h"
  38. #include "llvm/IR/GVMaterializer.h"
  39. #include "llvm/IR/GlobalAlias.h"
  40. #include "llvm/IR/GlobalIFunc.h"
  41. #include "llvm/IR/GlobalObject.h"
  42. #include "llvm/IR/GlobalValue.h"
  43. #include "llvm/IR/GlobalVariable.h"
  44. #include "llvm/IR/InlineAsm.h"
  45. #include "llvm/IR/InstrTypes.h"
  46. #include "llvm/IR/Instruction.h"
  47. #include "llvm/IR/Instructions.h"
  48. #include "llvm/IR/IntrinsicInst.h"
  49. #include "llvm/IR/Intrinsics.h"
  50. #include "llvm/IR/LLVMContext.h"
  51. #include "llvm/IR/Module.h"
  52. #include "llvm/IR/ModuleSummaryIndex.h"
  53. #include "llvm/IR/OperandTraits.h"
  54. #include "llvm/IR/TrackingMDRef.h"
  55. #include "llvm/IR/Type.h"
  56. #include "llvm/IR/ValueHandle.h"
  57. #include "llvm/Support/AtomicOrdering.h"
  58. #include "llvm/Support/Casting.h"
  59. #include "llvm/Support/CommandLine.h"
  60. #include "llvm/Support/Compiler.h"
  61. #include "llvm/Support/Debug.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Support/ManagedStatic.h"
  64. #include "llvm/Support/MemoryBuffer.h"
  65. #include "llvm/Support/raw_ostream.h"
  66. #include <algorithm>
  67. #include <cassert>
  68. #include <cstddef>
  69. #include <cstdint>
  70. #include <deque>
  71. #include <limits>
  72. #include <map>
  73. #include <string>
  74. #include <system_error>
  75. #include <tuple>
  76. #include <utility>
  77. #include <vector>
  78. using namespace llvm;
  79. #define DEBUG_TYPE "bitcode-reader"
  80. STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
  81. STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
  82. STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
  83. /// Flag whether we need to import full type definitions for ThinLTO.
  84. /// Currently needed for Darwin and LLDB.
  85. static cl::opt<bool> ImportFullTypeDefinitions(
  86. "import-full-type-definitions", cl::init(false), cl::Hidden,
  87. cl::desc("Import full type definitions for ThinLTO."));
  88. static cl::opt<bool> DisableLazyLoading(
  89. "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
  90. cl::desc("Force disable the lazy-loading on-demand of metadata when "
  91. "loading bitcode for importing."));
  92. namespace {
  93. static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
  94. class BitcodeReaderMetadataList {
  95. /// Array of metadata references.
  96. ///
  97. /// Don't use std::vector here. Some versions of libc++ copy (instead of
  98. /// move) on resize, and TrackingMDRef is very expensive to copy.
  99. SmallVector<TrackingMDRef, 1> MetadataPtrs;
  100. /// The set of indices in MetadataPtrs above of forward references that were
  101. /// generated.
  102. SmallDenseSet<unsigned, 1> ForwardReference;
  103. /// The set of indices in MetadataPtrs above of Metadata that need to be
  104. /// resolved.
  105. SmallDenseSet<unsigned, 1> UnresolvedNodes;
  106. /// Structures for resolving old type refs.
  107. struct {
  108. SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
  109. SmallDenseMap<MDString *, DICompositeType *, 1> Final;
  110. SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
  111. SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
  112. } OldTypeRefs;
  113. LLVMContext &Context;
  114. /// Maximum number of valid references. Forward references exceeding the
  115. /// maximum must be invalid.
  116. unsigned RefsUpperBound;
  117. public:
  118. BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
  119. : Context(C),
  120. RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
  121. RefsUpperBound)) {}
  122. // vector compatibility methods
  123. unsigned size() const { return MetadataPtrs.size(); }
  124. void resize(unsigned N) { MetadataPtrs.resize(N); }
  125. void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
  126. void clear() { MetadataPtrs.clear(); }
  127. Metadata *back() const { return MetadataPtrs.back(); }
  128. void pop_back() { MetadataPtrs.pop_back(); }
  129. bool empty() const { return MetadataPtrs.empty(); }
  130. Metadata *operator[](unsigned i) const {
  131. assert(i < MetadataPtrs.size());
  132. return MetadataPtrs[i];
  133. }
  134. Metadata *lookup(unsigned I) const {
  135. if (I < MetadataPtrs.size())
  136. return MetadataPtrs[I];
  137. return nullptr;
  138. }
  139. void shrinkTo(unsigned N) {
  140. assert(N <= size() && "Invalid shrinkTo request!");
  141. assert(ForwardReference.empty() && "Unexpected forward refs");
  142. assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
  143. MetadataPtrs.resize(N);
  144. }
  145. /// Return the given metadata, creating a replaceable forward reference if
  146. /// necessary.
  147. Metadata *getMetadataFwdRef(unsigned Idx);
  148. /// Return the given metadata only if it is fully resolved.
  149. ///
  150. /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
  151. /// would give \c false.
  152. Metadata *getMetadataIfResolved(unsigned Idx);
  153. MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
  154. void assignValue(Metadata *MD, unsigned Idx);
  155. void tryToResolveCycles();
  156. bool hasFwdRefs() const { return !ForwardReference.empty(); }
  157. int getNextFwdRef() {
  158. assert(hasFwdRefs());
  159. return *ForwardReference.begin();
  160. }
  161. /// Upgrade a type that had an MDString reference.
  162. void addTypeRef(MDString &UUID, DICompositeType &CT);
  163. /// Upgrade a type that had an MDString reference.
  164. Metadata *upgradeTypeRef(Metadata *MaybeUUID);
  165. /// Upgrade a type ref array that may have MDString references.
  166. Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
  167. private:
  168. Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
  169. };
  170. void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
  171. if (auto *MDN = dyn_cast<MDNode>(MD))
  172. if (!MDN->isResolved())
  173. UnresolvedNodes.insert(Idx);
  174. if (Idx == size()) {
  175. push_back(MD);
  176. return;
  177. }
  178. if (Idx >= size())
  179. resize(Idx + 1);
  180. TrackingMDRef &OldMD = MetadataPtrs[Idx];
  181. if (!OldMD) {
  182. OldMD.reset(MD);
  183. return;
  184. }
  185. // If there was a forward reference to this value, replace it.
  186. TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
  187. PrevMD->replaceAllUsesWith(MD);
  188. ForwardReference.erase(Idx);
  189. }
  190. Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
  191. // Bail out for a clearly invalid value.
  192. if (Idx >= RefsUpperBound)
  193. return nullptr;
  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 DIType *.
  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() &&
  306. "PlaceholderQueue hasn't been flushed before being destroyed");
  307. }
  308. bool empty() const { return PHs.empty(); }
  309. DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
  310. void flush(BitcodeReaderMetadataList &MetadataList);
  311. /// Return the list of temporaries nodes in the queue, these need to be
  312. /// loaded before we can flush the queue.
  313. void getTemporaries(BitcodeReaderMetadataList &MetadataList,
  314. DenseSet<unsigned> &Temporaries) {
  315. for (auto &PH : PHs) {
  316. auto ID = PH.getID();
  317. auto *MD = MetadataList.lookup(ID);
  318. if (!MD) {
  319. Temporaries.insert(ID);
  320. continue;
  321. }
  322. auto *N = dyn_cast_or_null<MDNode>(MD);
  323. if (N && N->isTemporary())
  324. Temporaries.insert(ID);
  325. }
  326. }
  327. };
  328. } // end anonymous namespace
  329. DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
  330. PHs.emplace_back(ID);
  331. return PHs.back();
  332. }
  333. void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
  334. while (!PHs.empty()) {
  335. auto *MD = MetadataList.lookup(PHs.front().getID());
  336. assert(MD && "Flushing placeholder on unassigned MD");
  337. #ifndef NDEBUG
  338. if (auto *MDN = dyn_cast<MDNode>(MD))
  339. assert(MDN->isResolved() &&
  340. "Flushing Placeholder while cycles aren't resolved");
  341. #endif
  342. PHs.front().replaceUseWith(MD);
  343. PHs.pop_front();
  344. }
  345. }
  346. } // anonymous namespace
  347. static Error error(const Twine &Message) {
  348. return make_error<StringError>(
  349. Message, make_error_code(BitcodeError::CorruptedBitcode));
  350. }
  351. class MetadataLoader::MetadataLoaderImpl {
  352. BitcodeReaderMetadataList MetadataList;
  353. BitcodeReaderValueList &ValueList;
  354. BitstreamCursor &Stream;
  355. LLVMContext &Context;
  356. Module &TheModule;
  357. std::function<Type *(unsigned)> getTypeByID;
  358. /// Cursor associated with the lazy-loading of Metadata. This is the easy way
  359. /// to keep around the right "context" (Abbrev list) to be able to jump in
  360. /// the middle of the metadata block and load any record.
  361. BitstreamCursor IndexCursor;
  362. /// Index that keeps track of MDString values.
  363. std::vector<StringRef> MDStringRef;
  364. /// On-demand loading of a single MDString. Requires the index above to be
  365. /// populated.
  366. MDString *lazyLoadOneMDString(unsigned Idx);
  367. /// Index that keeps track of where to find a metadata record in the stream.
  368. std::vector<uint64_t> GlobalMetadataBitPosIndex;
  369. /// Cursor position of the start of the global decl attachments, to enable
  370. /// loading using the index built for lazy loading, instead of forward
  371. /// references.
  372. uint64_t GlobalDeclAttachmentPos = 0;
  373. #ifndef NDEBUG
  374. /// Baisic correctness check that we end up parsing all of the global decl
  375. /// attachments.
  376. unsigned NumGlobalDeclAttachSkipped = 0;
  377. unsigned NumGlobalDeclAttachParsed = 0;
  378. #endif
  379. /// Load the global decl attachments, using the index built for lazy loading.
  380. Expected<bool> loadGlobalDeclAttachments();
  381. /// Populate the index above to enable lazily loading of metadata, and load
  382. /// the named metadata as well as the transitively referenced global
  383. /// Metadata.
  384. Expected<bool> lazyLoadModuleMetadataBlock();
  385. /// On-demand loading of a single metadata. Requires the index above to be
  386. /// populated.
  387. void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
  388. // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
  389. // point from SP to CU after a block is completly parsed.
  390. std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
  391. /// Functions that need to be matched with subprograms when upgrading old
  392. /// metadata.
  393. SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
  394. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  395. DenseMap<unsigned, unsigned> MDKindMap;
  396. bool StripTBAA = false;
  397. bool HasSeenOldLoopTags = false;
  398. bool NeedUpgradeToDIGlobalVariableExpression = false;
  399. bool NeedDeclareExpressionUpgrade = false;
  400. /// True if metadata is being parsed for a module being ThinLTO imported.
  401. bool IsImporting = false;
  402. Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
  403. PlaceholderQueue &Placeholders, StringRef Blob,
  404. unsigned &NextMetadataNo);
  405. Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
  406. function_ref<void(StringRef)> CallBack);
  407. Error parseGlobalObjectAttachment(GlobalObject &GO,
  408. ArrayRef<uint64_t> Record);
  409. Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
  410. void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
  411. /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
  412. void upgradeCUSubprograms() {
  413. for (auto CU_SP : CUSubprograms)
  414. if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
  415. for (auto &Op : SPs->operands())
  416. if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
  417. SP->replaceUnit(CU_SP.first);
  418. CUSubprograms.clear();
  419. }
  420. /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
  421. void upgradeCUVariables() {
  422. if (!NeedUpgradeToDIGlobalVariableExpression)
  423. return;
  424. // Upgrade list of variables attached to the CUs.
  425. if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
  426. for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
  427. auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
  428. if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
  429. for (unsigned I = 0; I < GVs->getNumOperands(); I++)
  430. if (auto *GV =
  431. dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
  432. auto *DGVE = DIGlobalVariableExpression::getDistinct(
  433. Context, GV, DIExpression::get(Context, {}));
  434. GVs->replaceOperandWith(I, DGVE);
  435. }
  436. }
  437. // Upgrade variables attached to globals.
  438. for (auto &GV : TheModule.globals()) {
  439. SmallVector<MDNode *, 1> MDs;
  440. GV.getMetadata(LLVMContext::MD_dbg, MDs);
  441. GV.eraseMetadata(LLVMContext::MD_dbg);
  442. for (auto *MD : MDs)
  443. if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
  444. auto *DGVE = DIGlobalVariableExpression::getDistinct(
  445. Context, DGV, DIExpression::get(Context, {}));
  446. GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
  447. } else
  448. GV.addMetadata(LLVMContext::MD_dbg, *MD);
  449. }
  450. }
  451. /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
  452. /// describes a function argument.
  453. void upgradeDeclareExpressions(Function &F) {
  454. if (!NeedDeclareExpressionUpgrade)
  455. return;
  456. for (auto &BB : F)
  457. for (auto &I : BB)
  458. if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
  459. if (auto *DIExpr = DDI->getExpression())
  460. if (DIExpr->startsWithDeref() &&
  461. isa_and_nonnull<Argument>(DDI->getAddress())) {
  462. SmallVector<uint64_t, 8> Ops;
  463. Ops.append(std::next(DIExpr->elements_begin()),
  464. DIExpr->elements_end());
  465. DDI->setExpression(DIExpression::get(Context, Ops));
  466. }
  467. }
  468. /// Upgrade the expression from previous versions.
  469. Error upgradeDIExpression(uint64_t FromVersion,
  470. MutableArrayRef<uint64_t> &Expr,
  471. SmallVectorImpl<uint64_t> &Buffer) {
  472. auto N = Expr.size();
  473. switch (FromVersion) {
  474. default:
  475. return error("Invalid record");
  476. case 0:
  477. if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
  478. Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
  479. LLVM_FALLTHROUGH;
  480. case 1:
  481. // Move DW_OP_deref to the end.
  482. if (N && Expr[0] == dwarf::DW_OP_deref) {
  483. auto End = Expr.end();
  484. if (Expr.size() >= 3 &&
  485. *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
  486. End = std::prev(End, 3);
  487. std::move(std::next(Expr.begin()), End, Expr.begin());
  488. *std::prev(End) = dwarf::DW_OP_deref;
  489. }
  490. NeedDeclareExpressionUpgrade = true;
  491. LLVM_FALLTHROUGH;
  492. case 2: {
  493. // Change DW_OP_plus to DW_OP_plus_uconst.
  494. // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
  495. auto SubExpr = ArrayRef<uint64_t>(Expr);
  496. while (!SubExpr.empty()) {
  497. // Skip past other operators with their operands
  498. // for this version of the IR, obtained from
  499. // from historic DIExpression::ExprOperand::getSize().
  500. size_t HistoricSize;
  501. switch (SubExpr.front()) {
  502. default:
  503. HistoricSize = 1;
  504. break;
  505. case dwarf::DW_OP_constu:
  506. case dwarf::DW_OP_minus:
  507. case dwarf::DW_OP_plus:
  508. HistoricSize = 2;
  509. break;
  510. case dwarf::DW_OP_LLVM_fragment:
  511. HistoricSize = 3;
  512. break;
  513. }
  514. // If the expression is malformed, make sure we don't
  515. // copy more elements than we should.
  516. HistoricSize = std::min(SubExpr.size(), HistoricSize);
  517. ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
  518. switch (SubExpr.front()) {
  519. case dwarf::DW_OP_plus:
  520. Buffer.push_back(dwarf::DW_OP_plus_uconst);
  521. Buffer.append(Args.begin(), Args.end());
  522. break;
  523. case dwarf::DW_OP_minus:
  524. Buffer.push_back(dwarf::DW_OP_constu);
  525. Buffer.append(Args.begin(), Args.end());
  526. Buffer.push_back(dwarf::DW_OP_minus);
  527. break;
  528. default:
  529. Buffer.push_back(*SubExpr.begin());
  530. Buffer.append(Args.begin(), Args.end());
  531. break;
  532. }
  533. // Continue with remaining elements.
  534. SubExpr = SubExpr.slice(HistoricSize);
  535. }
  536. Expr = MutableArrayRef<uint64_t>(Buffer);
  537. LLVM_FALLTHROUGH;
  538. }
  539. case 3:
  540. // Up-to-date!
  541. break;
  542. }
  543. return Error::success();
  544. }
  545. void upgradeDebugInfo() {
  546. upgradeCUSubprograms();
  547. upgradeCUVariables();
  548. }
  549. public:
  550. MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
  551. BitcodeReaderValueList &ValueList,
  552. std::function<Type *(unsigned)> getTypeByID,
  553. bool IsImporting)
  554. : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
  555. ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
  556. TheModule(TheModule), getTypeByID(std::move(getTypeByID)),
  557. IsImporting(IsImporting) {}
  558. Error parseMetadata(bool ModuleLevel);
  559. bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
  560. Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
  561. if (ID < MDStringRef.size())
  562. return lazyLoadOneMDString(ID);
  563. if (auto *MD = MetadataList.lookup(ID))
  564. return MD;
  565. // If lazy-loading is enabled, we try recursively to load the operand
  566. // instead of creating a temporary.
  567. if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
  568. PlaceholderQueue Placeholders;
  569. lazyLoadOneMetadata(ID, Placeholders);
  570. resolveForwardRefsAndPlaceholders(Placeholders);
  571. return MetadataList.lookup(ID);
  572. }
  573. return MetadataList.getMetadataFwdRef(ID);
  574. }
  575. DISubprogram *lookupSubprogramForFunction(Function *F) {
  576. return FunctionsWithSPs.lookup(F);
  577. }
  578. bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
  579. Error parseMetadataAttachment(
  580. Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
  581. Error parseMetadataKinds();
  582. void setStripTBAA(bool Value) { StripTBAA = Value; }
  583. bool isStrippingTBAA() const { return StripTBAA; }
  584. unsigned size() const { return MetadataList.size(); }
  585. void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
  586. void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
  587. };
  588. Expected<bool>
  589. MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
  590. IndexCursor = Stream;
  591. SmallVector<uint64_t, 64> Record;
  592. GlobalDeclAttachmentPos = 0;
  593. // Get the abbrevs, and preload record positions to make them lazy-loadable.
  594. while (true) {
  595. uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
  596. BitstreamEntry Entry;
  597. if (Error E =
  598. IndexCursor
  599. .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
  600. .moveInto(Entry))
  601. return std::move(E);
  602. switch (Entry.Kind) {
  603. case BitstreamEntry::SubBlock: // Handled for us already.
  604. case BitstreamEntry::Error:
  605. return error("Malformed block");
  606. case BitstreamEntry::EndBlock: {
  607. return true;
  608. }
  609. case BitstreamEntry::Record: {
  610. // The interesting case.
  611. ++NumMDRecordLoaded;
  612. uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
  613. unsigned Code;
  614. if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
  615. return std::move(E);
  616. switch (Code) {
  617. case bitc::METADATA_STRINGS: {
  618. // Rewind and parse the strings.
  619. if (Error Err = IndexCursor.JumpToBit(CurrentPos))
  620. return std::move(Err);
  621. StringRef Blob;
  622. Record.clear();
  623. if (Expected<unsigned> MaybeRecord =
  624. IndexCursor.readRecord(Entry.ID, Record, &Blob))
  625. ;
  626. else
  627. return MaybeRecord.takeError();
  628. unsigned NumStrings = Record[0];
  629. MDStringRef.reserve(NumStrings);
  630. auto IndexNextMDString = [&](StringRef Str) {
  631. MDStringRef.push_back(Str);
  632. };
  633. if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
  634. return std::move(Err);
  635. break;
  636. }
  637. case bitc::METADATA_INDEX_OFFSET: {
  638. // This is the offset to the index, when we see this we skip all the
  639. // records and load only an index to these.
  640. if (Error Err = IndexCursor.JumpToBit(CurrentPos))
  641. return std::move(Err);
  642. Record.clear();
  643. if (Expected<unsigned> MaybeRecord =
  644. IndexCursor.readRecord(Entry.ID, Record))
  645. ;
  646. else
  647. return MaybeRecord.takeError();
  648. if (Record.size() != 2)
  649. return error("Invalid record");
  650. auto Offset = Record[0] + (Record[1] << 32);
  651. auto BeginPos = IndexCursor.GetCurrentBitNo();
  652. if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
  653. return std::move(Err);
  654. Expected<BitstreamEntry> MaybeEntry =
  655. IndexCursor.advanceSkippingSubblocks(
  656. BitstreamCursor::AF_DontPopBlockAtEnd);
  657. if (!MaybeEntry)
  658. return MaybeEntry.takeError();
  659. Entry = MaybeEntry.get();
  660. assert(Entry.Kind == BitstreamEntry::Record &&
  661. "Corrupted bitcode: Expected `Record` when trying to find the "
  662. "Metadata index");
  663. Record.clear();
  664. if (Expected<unsigned> MaybeCode =
  665. IndexCursor.readRecord(Entry.ID, Record))
  666. assert(MaybeCode.get() == bitc::METADATA_INDEX &&
  667. "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
  668. "find the Metadata index");
  669. else
  670. return MaybeCode.takeError();
  671. // Delta unpack
  672. auto CurrentValue = BeginPos;
  673. GlobalMetadataBitPosIndex.reserve(Record.size());
  674. for (auto &Elt : Record) {
  675. CurrentValue += Elt;
  676. GlobalMetadataBitPosIndex.push_back(CurrentValue);
  677. }
  678. break;
  679. }
  680. case bitc::METADATA_INDEX:
  681. // We don't expect to get there, the Index is loaded when we encounter
  682. // the offset.
  683. return error("Corrupted Metadata block");
  684. case bitc::METADATA_NAME: {
  685. // Named metadata need to be materialized now and aren't deferred.
  686. if (Error Err = IndexCursor.JumpToBit(CurrentPos))
  687. return std::move(Err);
  688. Record.clear();
  689. unsigned Code;
  690. if (Expected<unsigned> MaybeCode =
  691. IndexCursor.readRecord(Entry.ID, Record)) {
  692. Code = MaybeCode.get();
  693. assert(Code == bitc::METADATA_NAME);
  694. } else
  695. return MaybeCode.takeError();
  696. // Read name of the named metadata.
  697. SmallString<8> Name(Record.begin(), Record.end());
  698. if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
  699. Code = MaybeCode.get();
  700. else
  701. return MaybeCode.takeError();
  702. // Named Metadata comes in two parts, we expect the name to be followed
  703. // by the node
  704. Record.clear();
  705. if (Expected<unsigned> MaybeNextBitCode =
  706. IndexCursor.readRecord(Code, Record))
  707. assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
  708. else
  709. return MaybeNextBitCode.takeError();
  710. // Read named metadata elements.
  711. unsigned Size = Record.size();
  712. NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
  713. for (unsigned i = 0; i != Size; ++i) {
  714. // FIXME: We could use a placeholder here, however NamedMDNode are
  715. // taking MDNode as operand and not using the Metadata infrastructure.
  716. // It is acknowledged by 'TODO: Inherit from Metadata' in the
  717. // NamedMDNode class definition.
  718. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
  719. assert(MD && "Invalid metadata: expect fwd ref to MDNode");
  720. NMD->addOperand(MD);
  721. }
  722. break;
  723. }
  724. case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
  725. if (!GlobalDeclAttachmentPos)
  726. GlobalDeclAttachmentPos = SavedPos;
  727. #ifndef NDEBUG
  728. NumGlobalDeclAttachSkipped++;
  729. #endif
  730. break;
  731. }
  732. case bitc::METADATA_KIND:
  733. case bitc::METADATA_STRING_OLD:
  734. case bitc::METADATA_OLD_FN_NODE:
  735. case bitc::METADATA_OLD_NODE:
  736. case bitc::METADATA_VALUE:
  737. case bitc::METADATA_DISTINCT_NODE:
  738. case bitc::METADATA_NODE:
  739. case bitc::METADATA_LOCATION:
  740. case bitc::METADATA_GENERIC_DEBUG:
  741. case bitc::METADATA_SUBRANGE:
  742. case bitc::METADATA_ENUMERATOR:
  743. case bitc::METADATA_BASIC_TYPE:
  744. case bitc::METADATA_STRING_TYPE:
  745. case bitc::METADATA_DERIVED_TYPE:
  746. case bitc::METADATA_COMPOSITE_TYPE:
  747. case bitc::METADATA_SUBROUTINE_TYPE:
  748. case bitc::METADATA_MODULE:
  749. case bitc::METADATA_FILE:
  750. case bitc::METADATA_COMPILE_UNIT:
  751. case bitc::METADATA_SUBPROGRAM:
  752. case bitc::METADATA_LEXICAL_BLOCK:
  753. case bitc::METADATA_LEXICAL_BLOCK_FILE:
  754. case bitc::METADATA_NAMESPACE:
  755. case bitc::METADATA_COMMON_BLOCK:
  756. case bitc::METADATA_MACRO:
  757. case bitc::METADATA_MACRO_FILE:
  758. case bitc::METADATA_TEMPLATE_TYPE:
  759. case bitc::METADATA_TEMPLATE_VALUE:
  760. case bitc::METADATA_GLOBAL_VAR:
  761. case bitc::METADATA_LOCAL_VAR:
  762. case bitc::METADATA_LABEL:
  763. case bitc::METADATA_EXPRESSION:
  764. case bitc::METADATA_OBJC_PROPERTY:
  765. case bitc::METADATA_IMPORTED_ENTITY:
  766. case bitc::METADATA_GLOBAL_VAR_EXPR:
  767. case bitc::METADATA_GENERIC_SUBRANGE:
  768. // We don't expect to see any of these, if we see one, give up on
  769. // lazy-loading and fallback.
  770. MDStringRef.clear();
  771. GlobalMetadataBitPosIndex.clear();
  772. return false;
  773. }
  774. break;
  775. }
  776. }
  777. }
  778. }
  779. // Load the global decl attachments after building the lazy loading index.
  780. // We don't load them "lazily" - all global decl attachments must be
  781. // parsed since they aren't materialized on demand. However, by delaying
  782. // their parsing until after the index is created, we can use the index
  783. // instead of creating temporaries.
  784. Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
  785. // Nothing to do if we didn't find any of these metadata records.
  786. if (!GlobalDeclAttachmentPos)
  787. return true;
  788. // Use a temporary cursor so that we don't mess up the main Stream cursor or
  789. // the lazy loading IndexCursor (which holds the necessary abbrev ids).
  790. BitstreamCursor TempCursor = Stream;
  791. SmallVector<uint64_t, 64> Record;
  792. // Jump to the position before the first global decl attachment, so we can
  793. // scan for the first BitstreamEntry record.
  794. if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
  795. return std::move(Err);
  796. while (true) {
  797. BitstreamEntry Entry;
  798. if (Error E =
  799. TempCursor
  800. .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
  801. .moveInto(Entry))
  802. return std::move(E);
  803. switch (Entry.Kind) {
  804. case BitstreamEntry::SubBlock: // Handled for us already.
  805. case BitstreamEntry::Error:
  806. return error("Malformed block");
  807. case BitstreamEntry::EndBlock:
  808. // Check that we parsed them all.
  809. assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
  810. return true;
  811. case BitstreamEntry::Record:
  812. break;
  813. }
  814. uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
  815. Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
  816. if (!MaybeCode)
  817. return MaybeCode.takeError();
  818. if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
  819. // Anything other than a global decl attachment signals the end of
  820. // these records. Check that we parsed them all.
  821. assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
  822. return true;
  823. }
  824. #ifndef NDEBUG
  825. NumGlobalDeclAttachParsed++;
  826. #endif
  827. // FIXME: we need to do this early because we don't materialize global
  828. // value explicitly.
  829. if (Error Err = TempCursor.JumpToBit(CurrentPos))
  830. return std::move(Err);
  831. Record.clear();
  832. if (Expected<unsigned> MaybeRecord =
  833. TempCursor.readRecord(Entry.ID, Record))
  834. ;
  835. else
  836. return MaybeRecord.takeError();
  837. if (Record.size() % 2 == 0)
  838. return error("Invalid record");
  839. unsigned ValueID = Record[0];
  840. if (ValueID >= ValueList.size())
  841. return error("Invalid record");
  842. if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
  843. // Need to save and restore the current position since
  844. // parseGlobalObjectAttachment will resolve all forward references which
  845. // would require parsing from locations stored in the index.
  846. CurrentPos = TempCursor.GetCurrentBitNo();
  847. if (Error Err = parseGlobalObjectAttachment(
  848. *GO, ArrayRef<uint64_t>(Record).slice(1)))
  849. return std::move(Err);
  850. if (Error Err = TempCursor.JumpToBit(CurrentPos))
  851. return std::move(Err);
  852. }
  853. }
  854. }
  855. /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
  856. /// module level metadata.
  857. Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
  858. if (!ModuleLevel && MetadataList.hasFwdRefs())
  859. return error("Invalid metadata: fwd refs into function blocks");
  860. // Record the entry position so that we can jump back here and efficiently
  861. // skip the whole block in case we lazy-load.
  862. auto EntryPos = Stream.GetCurrentBitNo();
  863. if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  864. return Err;
  865. SmallVector<uint64_t, 64> Record;
  866. PlaceholderQueue Placeholders;
  867. // We lazy-load module-level metadata: we build an index for each record, and
  868. // then load individual record as needed, starting with the named metadata.
  869. if (ModuleLevel && IsImporting && MetadataList.empty() &&
  870. !DisableLazyLoading) {
  871. auto SuccessOrErr = lazyLoadModuleMetadataBlock();
  872. if (!SuccessOrErr)
  873. return SuccessOrErr.takeError();
  874. if (SuccessOrErr.get()) {
  875. // An index was successfully created and we will be able to load metadata
  876. // on-demand.
  877. MetadataList.resize(MDStringRef.size() +
  878. GlobalMetadataBitPosIndex.size());
  879. // Now that we have built the index, load the global decl attachments
  880. // that were deferred during that process. This avoids creating
  881. // temporaries.
  882. SuccessOrErr = loadGlobalDeclAttachments();
  883. if (!SuccessOrErr)
  884. return SuccessOrErr.takeError();
  885. assert(SuccessOrErr.get());
  886. // Reading the named metadata created forward references and/or
  887. // placeholders, that we flush here.
  888. resolveForwardRefsAndPlaceholders(Placeholders);
  889. upgradeDebugInfo();
  890. // Return at the beginning of the block, since it is easy to skip it
  891. // entirely from there.
  892. Stream.ReadBlockEnd(); // Pop the abbrev block context.
  893. if (Error Err = IndexCursor.JumpToBit(EntryPos))
  894. return Err;
  895. if (Error Err = Stream.SkipBlock()) {
  896. // FIXME this drops the error on the floor, which
  897. // ThinLTO/X86/debuginfo-cu-import.ll relies on.
  898. consumeError(std::move(Err));
  899. return Error::success();
  900. }
  901. return Error::success();
  902. }
  903. // Couldn't load an index, fallback to loading all the block "old-style".
  904. }
  905. unsigned NextMetadataNo = MetadataList.size();
  906. // Read all the records.
  907. while (true) {
  908. BitstreamEntry Entry;
  909. if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
  910. return E;
  911. switch (Entry.Kind) {
  912. case BitstreamEntry::SubBlock: // Handled for us already.
  913. case BitstreamEntry::Error:
  914. return error("Malformed block");
  915. case BitstreamEntry::EndBlock:
  916. resolveForwardRefsAndPlaceholders(Placeholders);
  917. upgradeDebugInfo();
  918. return Error::success();
  919. case BitstreamEntry::Record:
  920. // The interesting case.
  921. break;
  922. }
  923. // Read a record.
  924. Record.clear();
  925. StringRef Blob;
  926. ++NumMDRecordLoaded;
  927. if (Expected<unsigned> MaybeCode =
  928. Stream.readRecord(Entry.ID, Record, &Blob)) {
  929. if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
  930. Blob, NextMetadataNo))
  931. return Err;
  932. } else
  933. return MaybeCode.takeError();
  934. }
  935. }
  936. MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
  937. ++NumMDStringLoaded;
  938. if (Metadata *MD = MetadataList.lookup(ID))
  939. return cast<MDString>(MD);
  940. auto MDS = MDString::get(Context, MDStringRef[ID]);
  941. MetadataList.assignValue(MDS, ID);
  942. return MDS;
  943. }
  944. void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
  945. unsigned ID, PlaceholderQueue &Placeholders) {
  946. assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
  947. assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
  948. // Lookup first if the metadata hasn't already been loaded.
  949. if (auto *MD = MetadataList.lookup(ID)) {
  950. auto *N = cast<MDNode>(MD);
  951. if (!N->isTemporary())
  952. return;
  953. }
  954. SmallVector<uint64_t, 64> Record;
  955. StringRef Blob;
  956. if (Error Err = IndexCursor.JumpToBit(
  957. GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
  958. report_fatal_error("lazyLoadOneMetadata failed jumping: " +
  959. Twine(toString(std::move(Err))));
  960. BitstreamEntry Entry;
  961. if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
  962. // FIXME this drops the error on the floor.
  963. report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
  964. Twine(toString(std::move(E))));
  965. ++NumMDRecordLoaded;
  966. if (Expected<unsigned> MaybeCode =
  967. IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
  968. if (Error Err =
  969. parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
  970. report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
  971. Twine(toString(std::move(Err))));
  972. } else
  973. report_fatal_error("Can't lazyload MD: " +
  974. Twine(toString(MaybeCode.takeError())));
  975. }
  976. /// Ensure that all forward-references and placeholders are resolved.
  977. /// Iteratively lazy-loading metadata on-demand if needed.
  978. void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
  979. PlaceholderQueue &Placeholders) {
  980. DenseSet<unsigned> Temporaries;
  981. while (true) {
  982. // Populate Temporaries with the placeholders that haven't been loaded yet.
  983. Placeholders.getTemporaries(MetadataList, Temporaries);
  984. // If we don't have any temporary, or FwdReference, we're done!
  985. if (Temporaries.empty() && !MetadataList.hasFwdRefs())
  986. break;
  987. // First, load all the temporaries. This can add new placeholders or
  988. // forward references.
  989. for (auto ID : Temporaries)
  990. lazyLoadOneMetadata(ID, Placeholders);
  991. Temporaries.clear();
  992. // Second, load the forward-references. This can also add new placeholders
  993. // or forward references.
  994. while (MetadataList.hasFwdRefs())
  995. lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
  996. }
  997. // At this point we don't have any forward reference remaining, or temporary
  998. // that haven't been loaded. We can safely drop RAUW support and mark cycles
  999. // as resolved.
  1000. MetadataList.tryToResolveCycles();
  1001. // Finally, everything is in place, we can replace the placeholders operands
  1002. // with the final node they refer to.
  1003. Placeholders.flush(MetadataList);
  1004. }
  1005. Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
  1006. SmallVectorImpl<uint64_t> &Record, unsigned Code,
  1007. PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
  1008. bool IsDistinct = false;
  1009. auto getMD = [&](unsigned ID) -> Metadata * {
  1010. if (ID < MDStringRef.size())
  1011. return lazyLoadOneMDString(ID);
  1012. if (!IsDistinct) {
  1013. if (auto *MD = MetadataList.lookup(ID))
  1014. return MD;
  1015. // If lazy-loading is enabled, we try recursively to load the operand
  1016. // instead of creating a temporary.
  1017. if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
  1018. // Create a temporary for the node that is referencing the operand we
  1019. // will lazy-load. It is needed before recursing in case there are
  1020. // uniquing cycles.
  1021. MetadataList.getMetadataFwdRef(NextMetadataNo);
  1022. lazyLoadOneMetadata(ID, Placeholders);
  1023. return MetadataList.lookup(ID);
  1024. }
  1025. // Return a temporary.
  1026. return MetadataList.getMetadataFwdRef(ID);
  1027. }
  1028. if (auto *MD = MetadataList.getMetadataIfResolved(ID))
  1029. return MD;
  1030. return &Placeholders.getPlaceholderOp(ID);
  1031. };
  1032. auto getMDOrNull = [&](unsigned ID) -> Metadata * {
  1033. if (ID)
  1034. return getMD(ID - 1);
  1035. return nullptr;
  1036. };
  1037. auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
  1038. if (ID)
  1039. return MetadataList.getMetadataFwdRef(ID - 1);
  1040. return nullptr;
  1041. };
  1042. auto getMDString = [&](unsigned ID) -> MDString * {
  1043. // This requires that the ID is not really a forward reference. In
  1044. // particular, the MDString must already have been resolved.
  1045. auto MDS = getMDOrNull(ID);
  1046. return cast_or_null<MDString>(MDS);
  1047. };
  1048. // Support for old type refs.
  1049. auto getDITypeRefOrNull = [&](unsigned ID) {
  1050. return MetadataList.upgradeTypeRef(getMDOrNull(ID));
  1051. };
  1052. #define GET_OR_DISTINCT(CLASS, ARGS) \
  1053. (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  1054. switch (Code) {
  1055. default: // Default behavior: ignore.
  1056. break;
  1057. case bitc::METADATA_NAME: {
  1058. // Read name of the named metadata.
  1059. SmallString<8> Name(Record.begin(), Record.end());
  1060. Record.clear();
  1061. if (Error E = Stream.ReadCode().moveInto(Code))
  1062. return E;
  1063. ++NumMDRecordLoaded;
  1064. if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
  1065. if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
  1066. return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
  1067. } else
  1068. return MaybeNextBitCode.takeError();
  1069. // Read named metadata elements.
  1070. unsigned Size = Record.size();
  1071. NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
  1072. for (unsigned i = 0; i != Size; ++i) {
  1073. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
  1074. if (!MD)
  1075. return error("Invalid named metadata: expect fwd ref to MDNode");
  1076. NMD->addOperand(MD);
  1077. }
  1078. break;
  1079. }
  1080. case bitc::METADATA_OLD_FN_NODE: {
  1081. // Deprecated, but still needed to read old bitcode files.
  1082. // This is a LocalAsMetadata record, the only type of function-local
  1083. // metadata.
  1084. if (Record.size() % 2 == 1)
  1085. return error("Invalid record");
  1086. // If this isn't a LocalAsMetadata record, we're dropping it. This used
  1087. // to be legal, but there's no upgrade path.
  1088. auto dropRecord = [&] {
  1089. MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
  1090. NextMetadataNo++;
  1091. };
  1092. if (Record.size() != 2) {
  1093. dropRecord();
  1094. break;
  1095. }
  1096. Type *Ty = getTypeByID(Record[0]);
  1097. if (Ty->isMetadataTy() || Ty->isVoidTy()) {
  1098. dropRecord();
  1099. break;
  1100. }
  1101. MetadataList.assignValue(
  1102. LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  1103. NextMetadataNo);
  1104. NextMetadataNo++;
  1105. break;
  1106. }
  1107. case bitc::METADATA_OLD_NODE: {
  1108. // Deprecated, but still needed to read old bitcode files.
  1109. if (Record.size() % 2 == 1)
  1110. return error("Invalid record");
  1111. unsigned Size = Record.size();
  1112. SmallVector<Metadata *, 8> Elts;
  1113. for (unsigned i = 0; i != Size; i += 2) {
  1114. Type *Ty = getTypeByID(Record[i]);
  1115. if (!Ty)
  1116. return error("Invalid record");
  1117. if (Ty->isMetadataTy())
  1118. Elts.push_back(getMD(Record[i + 1]));
  1119. else if (!Ty->isVoidTy()) {
  1120. auto *MD =
  1121. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
  1122. assert(isa<ConstantAsMetadata>(MD) &&
  1123. "Expected non-function-local metadata");
  1124. Elts.push_back(MD);
  1125. } else
  1126. Elts.push_back(nullptr);
  1127. }
  1128. MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
  1129. NextMetadataNo++;
  1130. break;
  1131. }
  1132. case bitc::METADATA_VALUE: {
  1133. if (Record.size() != 2)
  1134. return error("Invalid record");
  1135. Type *Ty = getTypeByID(Record[0]);
  1136. if (Ty->isMetadataTy() || Ty->isVoidTy())
  1137. return error("Invalid record");
  1138. MetadataList.assignValue(
  1139. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  1140. NextMetadataNo);
  1141. NextMetadataNo++;
  1142. break;
  1143. }
  1144. case bitc::METADATA_DISTINCT_NODE:
  1145. IsDistinct = true;
  1146. LLVM_FALLTHROUGH;
  1147. case bitc::METADATA_NODE: {
  1148. SmallVector<Metadata *, 8> Elts;
  1149. Elts.reserve(Record.size());
  1150. for (unsigned ID : Record)
  1151. Elts.push_back(getMDOrNull(ID));
  1152. MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
  1153. : MDNode::get(Context, Elts),
  1154. NextMetadataNo);
  1155. NextMetadataNo++;
  1156. break;
  1157. }
  1158. case bitc::METADATA_LOCATION: {
  1159. if (Record.size() != 5 && Record.size() != 6)
  1160. return error("Invalid record");
  1161. IsDistinct = Record[0];
  1162. unsigned Line = Record[1];
  1163. unsigned Column = Record[2];
  1164. Metadata *Scope = getMD(Record[3]);
  1165. Metadata *InlinedAt = getMDOrNull(Record[4]);
  1166. bool ImplicitCode = Record.size() == 6 && Record[5];
  1167. MetadataList.assignValue(
  1168. GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
  1169. ImplicitCode)),
  1170. NextMetadataNo);
  1171. NextMetadataNo++;
  1172. break;
  1173. }
  1174. case bitc::METADATA_GENERIC_DEBUG: {
  1175. if (Record.size() < 4)
  1176. return error("Invalid record");
  1177. IsDistinct = Record[0];
  1178. unsigned Tag = Record[1];
  1179. unsigned Version = Record[2];
  1180. if (Tag >= 1u << 16 || Version != 0)
  1181. return error("Invalid record");
  1182. auto *Header = getMDString(Record[3]);
  1183. SmallVector<Metadata *, 8> DwarfOps;
  1184. for (unsigned I = 4, E = Record.size(); I != E; ++I)
  1185. DwarfOps.push_back(getMDOrNull(Record[I]));
  1186. MetadataList.assignValue(
  1187. GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
  1188. NextMetadataNo);
  1189. NextMetadataNo++;
  1190. break;
  1191. }
  1192. case bitc::METADATA_SUBRANGE: {
  1193. Metadata *Val = nullptr;
  1194. // Operand 'count' is interpreted as:
  1195. // - Signed integer (version 0)
  1196. // - Metadata node (version 1)
  1197. // Operand 'lowerBound' is interpreted as:
  1198. // - Signed integer (version 0 and 1)
  1199. // - Metadata node (version 2)
  1200. // Operands 'upperBound' and 'stride' are interpreted as:
  1201. // - Metadata node (version 2)
  1202. switch (Record[0] >> 1) {
  1203. case 0:
  1204. Val = GET_OR_DISTINCT(DISubrange,
  1205. (Context, Record[1], unrotateSign(Record[2])));
  1206. break;
  1207. case 1:
  1208. Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
  1209. unrotateSign(Record[2])));
  1210. break;
  1211. case 2:
  1212. Val = GET_OR_DISTINCT(
  1213. DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
  1214. getMDOrNull(Record[3]), getMDOrNull(Record[4])));
  1215. break;
  1216. default:
  1217. return error("Invalid record: Unsupported version of DISubrange");
  1218. }
  1219. MetadataList.assignValue(Val, NextMetadataNo);
  1220. IsDistinct = Record[0] & 1;
  1221. NextMetadataNo++;
  1222. break;
  1223. }
  1224. case bitc::METADATA_GENERIC_SUBRANGE: {
  1225. Metadata *Val = nullptr;
  1226. Val = GET_OR_DISTINCT(DIGenericSubrange,
  1227. (Context, getMDOrNull(Record[1]),
  1228. getMDOrNull(Record[2]), getMDOrNull(Record[3]),
  1229. getMDOrNull(Record[4])));
  1230. MetadataList.assignValue(Val, NextMetadataNo);
  1231. IsDistinct = Record[0] & 1;
  1232. NextMetadataNo++;
  1233. break;
  1234. }
  1235. case bitc::METADATA_ENUMERATOR: {
  1236. if (Record.size() < 3)
  1237. return error("Invalid record");
  1238. IsDistinct = Record[0] & 1;
  1239. bool IsUnsigned = Record[0] & 2;
  1240. bool IsBigInt = Record[0] & 4;
  1241. APInt Value;
  1242. if (IsBigInt) {
  1243. const uint64_t BitWidth = Record[1];
  1244. const size_t NumWords = Record.size() - 3;
  1245. Value = readWideAPInt(makeArrayRef(&Record[3], NumWords), BitWidth);
  1246. } else
  1247. Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
  1248. MetadataList.assignValue(
  1249. GET_OR_DISTINCT(DIEnumerator,
  1250. (Context, Value, IsUnsigned, getMDString(Record[2]))),
  1251. NextMetadataNo);
  1252. NextMetadataNo++;
  1253. break;
  1254. }
  1255. case bitc::METADATA_BASIC_TYPE: {
  1256. if (Record.size() < 6 || Record.size() > 7)
  1257. return error("Invalid record");
  1258. IsDistinct = Record[0];
  1259. DINode::DIFlags Flags = (Record.size() > 6)
  1260. ? static_cast<DINode::DIFlags>(Record[6])
  1261. : DINode::FlagZero;
  1262. MetadataList.assignValue(
  1263. GET_OR_DISTINCT(DIBasicType,
  1264. (Context, Record[1], getMDString(Record[2]), Record[3],
  1265. Record[4], Record[5], Flags)),
  1266. NextMetadataNo);
  1267. NextMetadataNo++;
  1268. break;
  1269. }
  1270. case bitc::METADATA_STRING_TYPE: {
  1271. if (Record.size() > 9 || Record.size() < 8)
  1272. return error("Invalid record");
  1273. IsDistinct = Record[0];
  1274. bool SizeIs8 = Record.size() == 8;
  1275. // StringLocationExp (i.e. Record[5]) is added at a later time
  1276. // than the other fields. The code here enables backward compatibility.
  1277. Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
  1278. unsigned Offset = SizeIs8 ? 5 : 6;
  1279. MetadataList.assignValue(
  1280. GET_OR_DISTINCT(DIStringType,
  1281. (Context, Record[1], getMDString(Record[2]),
  1282. getMDOrNull(Record[3]), getMDOrNull(Record[4]),
  1283. StringLocationExp, Record[Offset], Record[Offset + 1],
  1284. Record[Offset + 2])),
  1285. NextMetadataNo);
  1286. NextMetadataNo++;
  1287. break;
  1288. }
  1289. case bitc::METADATA_DERIVED_TYPE: {
  1290. if (Record.size() < 12 || Record.size() > 14)
  1291. return error("Invalid record");
  1292. // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
  1293. // that there is no DWARF address space associated with DIDerivedType.
  1294. Optional<unsigned> DWARFAddressSpace;
  1295. if (Record.size() > 12 && Record[12])
  1296. DWARFAddressSpace = Record[12] - 1;
  1297. Metadata *Annotations = nullptr;
  1298. if (Record.size() > 13 && Record[13])
  1299. Annotations = getMDOrNull(Record[13]);
  1300. IsDistinct = Record[0];
  1301. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
  1302. MetadataList.assignValue(
  1303. GET_OR_DISTINCT(DIDerivedType,
  1304. (Context, Record[1], getMDString(Record[2]),
  1305. getMDOrNull(Record[3]), Record[4],
  1306. getDITypeRefOrNull(Record[5]),
  1307. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1308. Record[9], DWARFAddressSpace, Flags,
  1309. getDITypeRefOrNull(Record[11]), Annotations)),
  1310. NextMetadataNo);
  1311. NextMetadataNo++;
  1312. break;
  1313. }
  1314. case bitc::METADATA_COMPOSITE_TYPE: {
  1315. if (Record.size() < 16 || Record.size() > 22)
  1316. return error("Invalid record");
  1317. // If we have a UUID and this is not a forward declaration, lookup the
  1318. // mapping.
  1319. IsDistinct = Record[0] & 0x1;
  1320. bool IsNotUsedInTypeRef = Record[0] >= 2;
  1321. unsigned Tag = Record[1];
  1322. MDString *Name = getMDString(Record[2]);
  1323. Metadata *File = getMDOrNull(Record[3]);
  1324. unsigned Line = Record[4];
  1325. Metadata *Scope = getDITypeRefOrNull(Record[5]);
  1326. Metadata *BaseType = nullptr;
  1327. uint64_t SizeInBits = Record[7];
  1328. if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
  1329. return error("Alignment value is too large");
  1330. uint32_t AlignInBits = Record[8];
  1331. uint64_t OffsetInBits = 0;
  1332. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
  1333. Metadata *Elements = nullptr;
  1334. unsigned RuntimeLang = Record[12];
  1335. Metadata *VTableHolder = nullptr;
  1336. Metadata *TemplateParams = nullptr;
  1337. Metadata *Discriminator = nullptr;
  1338. Metadata *DataLocation = nullptr;
  1339. Metadata *Associated = nullptr;
  1340. Metadata *Allocated = nullptr;
  1341. Metadata *Rank = nullptr;
  1342. Metadata *Annotations = nullptr;
  1343. auto *Identifier = getMDString(Record[15]);
  1344. // If this module is being parsed so that it can be ThinLTO imported
  1345. // into another module, composite types only need to be imported
  1346. // as type declarations (unless full type definitions requested).
  1347. // Create type declarations up front to save memory. Also, buildODRType
  1348. // handles the case where this is type ODRed with a definition needed
  1349. // by the importing module, in which case the existing definition is
  1350. // used.
  1351. if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
  1352. (Tag == dwarf::DW_TAG_enumeration_type ||
  1353. Tag == dwarf::DW_TAG_class_type ||
  1354. Tag == dwarf::DW_TAG_structure_type ||
  1355. Tag == dwarf::DW_TAG_union_type)) {
  1356. Flags = Flags | DINode::FlagFwdDecl;
  1357. } else {
  1358. BaseType = getDITypeRefOrNull(Record[6]);
  1359. OffsetInBits = Record[9];
  1360. Elements = getMDOrNull(Record[11]);
  1361. VTableHolder = getDITypeRefOrNull(Record[13]);
  1362. TemplateParams = getMDOrNull(Record[14]);
  1363. if (Record.size() > 16)
  1364. Discriminator = getMDOrNull(Record[16]);
  1365. if (Record.size() > 17)
  1366. DataLocation = getMDOrNull(Record[17]);
  1367. if (Record.size() > 19) {
  1368. Associated = getMDOrNull(Record[18]);
  1369. Allocated = getMDOrNull(Record[19]);
  1370. }
  1371. if (Record.size() > 20) {
  1372. Rank = getMDOrNull(Record[20]);
  1373. }
  1374. if (Record.size() > 21) {
  1375. Annotations = getMDOrNull(Record[21]);
  1376. }
  1377. }
  1378. DICompositeType *CT = nullptr;
  1379. if (Identifier)
  1380. CT = DICompositeType::buildODRType(
  1381. Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
  1382. SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  1383. VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
  1384. Allocated, Rank, Annotations);
  1385. // Create a node if we didn't get a lazy ODR type.
  1386. if (!CT)
  1387. CT = GET_OR_DISTINCT(DICompositeType,
  1388. (Context, Tag, Name, File, Line, Scope, BaseType,
  1389. SizeInBits, AlignInBits, OffsetInBits, Flags,
  1390. Elements, RuntimeLang, VTableHolder, TemplateParams,
  1391. Identifier, Discriminator, DataLocation, Associated,
  1392. Allocated, Rank, Annotations));
  1393. if (!IsNotUsedInTypeRef && Identifier)
  1394. MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
  1395. MetadataList.assignValue(CT, NextMetadataNo);
  1396. NextMetadataNo++;
  1397. break;
  1398. }
  1399. case bitc::METADATA_SUBROUTINE_TYPE: {
  1400. if (Record.size() < 3 || Record.size() > 4)
  1401. return error("Invalid record");
  1402. bool IsOldTypeRefArray = Record[0] < 2;
  1403. unsigned CC = (Record.size() > 3) ? Record[3] : 0;
  1404. IsDistinct = Record[0] & 0x1;
  1405. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
  1406. Metadata *Types = getMDOrNull(Record[2]);
  1407. if (LLVM_UNLIKELY(IsOldTypeRefArray))
  1408. Types = MetadataList.upgradeTypeRefArray(Types);
  1409. MetadataList.assignValue(
  1410. GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
  1411. NextMetadataNo);
  1412. NextMetadataNo++;
  1413. break;
  1414. }
  1415. case bitc::METADATA_MODULE: {
  1416. if (Record.size() < 5 || Record.size() > 9)
  1417. return error("Invalid record");
  1418. unsigned Offset = Record.size() >= 8 ? 2 : 1;
  1419. IsDistinct = Record[0];
  1420. MetadataList.assignValue(
  1421. GET_OR_DISTINCT(
  1422. DIModule,
  1423. (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
  1424. getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
  1425. getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
  1426. getMDString(Record[4 + Offset]),
  1427. Record.size() <= 7 ? 0 : Record[7],
  1428. Record.size() <= 8 ? false : Record[8])),
  1429. NextMetadataNo);
  1430. NextMetadataNo++;
  1431. break;
  1432. }
  1433. case bitc::METADATA_FILE: {
  1434. if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
  1435. return error("Invalid record");
  1436. IsDistinct = Record[0];
  1437. Optional<DIFile::ChecksumInfo<MDString *>> Checksum;
  1438. // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
  1439. // is not present. This matches up with the old internal representation,
  1440. // and the old encoding for CSK_None in the ChecksumKind. The new
  1441. // representation reserves the value 0 in the ChecksumKind to continue to
  1442. // encode None in a backwards-compatible way.
  1443. if (Record.size() > 4 && Record[3] && Record[4])
  1444. Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
  1445. getMDString(Record[4]));
  1446. MetadataList.assignValue(
  1447. GET_OR_DISTINCT(
  1448. DIFile,
  1449. (Context, getMDString(Record[1]), getMDString(Record[2]), Checksum,
  1450. Record.size() > 5 ? Optional<MDString *>(getMDString(Record[5]))
  1451. : None)),
  1452. NextMetadataNo);
  1453. NextMetadataNo++;
  1454. break;
  1455. }
  1456. case bitc::METADATA_COMPILE_UNIT: {
  1457. if (Record.size() < 14 || Record.size() > 22)
  1458. return error("Invalid record");
  1459. // Ignore Record[0], which indicates whether this compile unit is
  1460. // distinct. It's always distinct.
  1461. IsDistinct = true;
  1462. auto *CU = DICompileUnit::getDistinct(
  1463. Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
  1464. Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
  1465. Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
  1466. getMDOrNull(Record[12]), getMDOrNull(Record[13]),
  1467. Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
  1468. Record.size() <= 14 ? 0 : Record[14],
  1469. Record.size() <= 16 ? true : Record[16],
  1470. Record.size() <= 17 ? false : Record[17],
  1471. Record.size() <= 18 ? 0 : Record[18],
  1472. Record.size() <= 19 ? false : Record[19],
  1473. Record.size() <= 20 ? nullptr : getMDString(Record[20]),
  1474. Record.size() <= 21 ? nullptr : getMDString(Record[21]));
  1475. MetadataList.assignValue(CU, NextMetadataNo);
  1476. NextMetadataNo++;
  1477. // Move the Upgrade the list of subprograms.
  1478. if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
  1479. CUSubprograms.push_back({CU, SPs});
  1480. break;
  1481. }
  1482. case bitc::METADATA_SUBPROGRAM: {
  1483. if (Record.size() < 18 || Record.size() > 21)
  1484. return error("Invalid record");
  1485. bool HasSPFlags = Record[0] & 4;
  1486. DINode::DIFlags Flags;
  1487. DISubprogram::DISPFlags SPFlags;
  1488. if (!HasSPFlags)
  1489. Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
  1490. else {
  1491. Flags = static_cast<DINode::DIFlags>(Record[11]);
  1492. SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
  1493. }
  1494. // Support for old metadata when
  1495. // subprogram specific flags are placed in DIFlags.
  1496. const unsigned DIFlagMainSubprogram = 1 << 21;
  1497. bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
  1498. if (HasOldMainSubprogramFlag)
  1499. // Remove old DIFlagMainSubprogram from DIFlags.
  1500. // Note: This assumes that any future use of bit 21 defaults to it
  1501. // being 0.
  1502. Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
  1503. if (HasOldMainSubprogramFlag && HasSPFlags)
  1504. SPFlags |= DISubprogram::SPFlagMainSubprogram;
  1505. else if (!HasSPFlags)
  1506. SPFlags = DISubprogram::toSPFlags(
  1507. /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
  1508. /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
  1509. /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
  1510. // All definitions should be distinct.
  1511. IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
  1512. // Version 1 has a Function as Record[15].
  1513. // Version 2 has removed Record[15].
  1514. // Version 3 has the Unit as Record[15].
  1515. // Version 4 added thisAdjustment.
  1516. // Version 5 repacked flags into DISPFlags, changing many element numbers.
  1517. bool HasUnit = Record[0] & 2;
  1518. if (!HasSPFlags && HasUnit && Record.size() < 19)
  1519. return error("Invalid record");
  1520. if (HasSPFlags && !HasUnit)
  1521. return error("Invalid record");
  1522. // Accommodate older formats.
  1523. bool HasFn = false;
  1524. bool HasThisAdj = true;
  1525. bool HasThrownTypes = true;
  1526. bool HasAnnotations = false;
  1527. unsigned OffsetA = 0;
  1528. unsigned OffsetB = 0;
  1529. if (!HasSPFlags) {
  1530. OffsetA = 2;
  1531. OffsetB = 2;
  1532. if (Record.size() >= 19) {
  1533. HasFn = !HasUnit;
  1534. OffsetB++;
  1535. }
  1536. HasThisAdj = Record.size() >= 20;
  1537. HasThrownTypes = Record.size() >= 21;
  1538. } else {
  1539. HasAnnotations = Record.size() >= 19;
  1540. }
  1541. Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
  1542. DISubprogram *SP = GET_OR_DISTINCT(
  1543. DISubprogram,
  1544. (Context,
  1545. getDITypeRefOrNull(Record[1]), // scope
  1546. getMDString(Record[2]), // name
  1547. getMDString(Record[3]), // linkageName
  1548. getMDOrNull(Record[4]), // file
  1549. Record[5], // line
  1550. getMDOrNull(Record[6]), // type
  1551. Record[7 + OffsetA], // scopeLine
  1552. getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
  1553. Record[10 + OffsetA], // virtualIndex
  1554. HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
  1555. Flags, // flags
  1556. SPFlags, // SPFlags
  1557. HasUnit ? CUorFn : nullptr, // unit
  1558. getMDOrNull(Record[13 + OffsetB]), // templateParams
  1559. getMDOrNull(Record[14 + OffsetB]), // declaration
  1560. getMDOrNull(Record[15 + OffsetB]), // retainedNodes
  1561. HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
  1562. : nullptr, // thrownTypes
  1563. HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
  1564. : nullptr // annotations
  1565. ));
  1566. MetadataList.assignValue(SP, NextMetadataNo);
  1567. NextMetadataNo++;
  1568. // Upgrade sp->function mapping to function->sp mapping.
  1569. if (HasFn) {
  1570. if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
  1571. if (auto *F = dyn_cast<Function>(CMD->getValue())) {
  1572. if (F->isMaterializable())
  1573. // Defer until materialized; unmaterialized functions may not have
  1574. // metadata.
  1575. FunctionsWithSPs[F] = SP;
  1576. else if (!F->empty())
  1577. F->setSubprogram(SP);
  1578. }
  1579. }
  1580. break;
  1581. }
  1582. case bitc::METADATA_LEXICAL_BLOCK: {
  1583. if (Record.size() != 5)
  1584. return error("Invalid record");
  1585. IsDistinct = Record[0];
  1586. MetadataList.assignValue(
  1587. GET_OR_DISTINCT(DILexicalBlock,
  1588. (Context, getMDOrNull(Record[1]),
  1589. getMDOrNull(Record[2]), Record[3], Record[4])),
  1590. NextMetadataNo);
  1591. NextMetadataNo++;
  1592. break;
  1593. }
  1594. case bitc::METADATA_LEXICAL_BLOCK_FILE: {
  1595. if (Record.size() != 4)
  1596. return error("Invalid record");
  1597. IsDistinct = Record[0];
  1598. MetadataList.assignValue(
  1599. GET_OR_DISTINCT(DILexicalBlockFile,
  1600. (Context, getMDOrNull(Record[1]),
  1601. getMDOrNull(Record[2]), Record[3])),
  1602. NextMetadataNo);
  1603. NextMetadataNo++;
  1604. break;
  1605. }
  1606. case bitc::METADATA_COMMON_BLOCK: {
  1607. IsDistinct = Record[0] & 1;
  1608. MetadataList.assignValue(
  1609. GET_OR_DISTINCT(DICommonBlock,
  1610. (Context, getMDOrNull(Record[1]),
  1611. getMDOrNull(Record[2]), getMDString(Record[3]),
  1612. getMDOrNull(Record[4]), Record[5])),
  1613. NextMetadataNo);
  1614. NextMetadataNo++;
  1615. break;
  1616. }
  1617. case bitc::METADATA_NAMESPACE: {
  1618. // Newer versions of DINamespace dropped file and line.
  1619. MDString *Name;
  1620. if (Record.size() == 3)
  1621. Name = getMDString(Record[2]);
  1622. else if (Record.size() == 5)
  1623. Name = getMDString(Record[3]);
  1624. else
  1625. return error("Invalid record");
  1626. IsDistinct = Record[0] & 1;
  1627. bool ExportSymbols = Record[0] & 2;
  1628. MetadataList.assignValue(
  1629. GET_OR_DISTINCT(DINamespace,
  1630. (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
  1631. NextMetadataNo);
  1632. NextMetadataNo++;
  1633. break;
  1634. }
  1635. case bitc::METADATA_MACRO: {
  1636. if (Record.size() != 5)
  1637. return error("Invalid record");
  1638. IsDistinct = Record[0];
  1639. MetadataList.assignValue(
  1640. GET_OR_DISTINCT(DIMacro,
  1641. (Context, Record[1], Record[2], getMDString(Record[3]),
  1642. getMDString(Record[4]))),
  1643. NextMetadataNo);
  1644. NextMetadataNo++;
  1645. break;
  1646. }
  1647. case bitc::METADATA_MACRO_FILE: {
  1648. if (Record.size() != 5)
  1649. return error("Invalid record");
  1650. IsDistinct = Record[0];
  1651. MetadataList.assignValue(
  1652. GET_OR_DISTINCT(DIMacroFile,
  1653. (Context, Record[1], Record[2], getMDOrNull(Record[3]),
  1654. getMDOrNull(Record[4]))),
  1655. NextMetadataNo);
  1656. NextMetadataNo++;
  1657. break;
  1658. }
  1659. case bitc::METADATA_TEMPLATE_TYPE: {
  1660. if (Record.size() < 3 || Record.size() > 4)
  1661. return error("Invalid record");
  1662. IsDistinct = Record[0];
  1663. MetadataList.assignValue(
  1664. GET_OR_DISTINCT(DITemplateTypeParameter,
  1665. (Context, getMDString(Record[1]),
  1666. getDITypeRefOrNull(Record[2]),
  1667. (Record.size() == 4) ? getMDOrNull(Record[3])
  1668. : getMDOrNull(false))),
  1669. NextMetadataNo);
  1670. NextMetadataNo++;
  1671. break;
  1672. }
  1673. case bitc::METADATA_TEMPLATE_VALUE: {
  1674. if (Record.size() < 5 || Record.size() > 6)
  1675. return error("Invalid record");
  1676. IsDistinct = Record[0];
  1677. MetadataList.assignValue(
  1678. GET_OR_DISTINCT(
  1679. DITemplateValueParameter,
  1680. (Context, Record[1], getMDString(Record[2]),
  1681. getDITypeRefOrNull(Record[3]),
  1682. (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
  1683. (Record.size() == 6) ? getMDOrNull(Record[5])
  1684. : getMDOrNull(Record[4]))),
  1685. NextMetadataNo);
  1686. NextMetadataNo++;
  1687. break;
  1688. }
  1689. case bitc::METADATA_GLOBAL_VAR: {
  1690. if (Record.size() < 11 || Record.size() > 13)
  1691. return error("Invalid record");
  1692. IsDistinct = Record[0] & 1;
  1693. unsigned Version = Record[0] >> 1;
  1694. if (Version == 2) {
  1695. Metadata *Annotations = nullptr;
  1696. if (Record.size() > 12)
  1697. Annotations = getMDOrNull(Record[12]);
  1698. MetadataList.assignValue(
  1699. GET_OR_DISTINCT(DIGlobalVariable,
  1700. (Context, getMDOrNull(Record[1]),
  1701. getMDString(Record[2]), getMDString(Record[3]),
  1702. getMDOrNull(Record[4]), Record[5],
  1703. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1704. getMDOrNull(Record[9]), getMDOrNull(Record[10]),
  1705. Record[11], Annotations)),
  1706. NextMetadataNo);
  1707. NextMetadataNo++;
  1708. } else if (Version == 1) {
  1709. // No upgrade necessary. A null field will be introduced to indicate
  1710. // that no parameter information is available.
  1711. MetadataList.assignValue(
  1712. GET_OR_DISTINCT(
  1713. DIGlobalVariable,
  1714. (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
  1715. getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
  1716. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1717. getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
  1718. NextMetadataNo);
  1719. NextMetadataNo++;
  1720. } else if (Version == 0) {
  1721. // Upgrade old metadata, which stored a global variable reference or a
  1722. // ConstantInt here.
  1723. NeedUpgradeToDIGlobalVariableExpression = true;
  1724. Metadata *Expr = getMDOrNull(Record[9]);
  1725. uint32_t AlignInBits = 0;
  1726. if (Record.size() > 11) {
  1727. if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
  1728. return error("Alignment value is too large");
  1729. AlignInBits = Record[11];
  1730. }
  1731. GlobalVariable *Attach = nullptr;
  1732. if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
  1733. if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
  1734. Attach = GV;
  1735. Expr = nullptr;
  1736. } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
  1737. Expr = DIExpression::get(Context,
  1738. {dwarf::DW_OP_constu, CI->getZExtValue(),
  1739. dwarf::DW_OP_stack_value});
  1740. } else {
  1741. Expr = nullptr;
  1742. }
  1743. }
  1744. DIGlobalVariable *DGV = GET_OR_DISTINCT(
  1745. DIGlobalVariable,
  1746. (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
  1747. getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
  1748. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1749. getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
  1750. DIGlobalVariableExpression *DGVE = nullptr;
  1751. if (Attach || Expr)
  1752. DGVE = DIGlobalVariableExpression::getDistinct(
  1753. Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
  1754. if (Attach)
  1755. Attach->addDebugInfo(DGVE);
  1756. auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
  1757. MetadataList.assignValue(MDNode, NextMetadataNo);
  1758. NextMetadataNo++;
  1759. } else
  1760. return error("Invalid record");
  1761. break;
  1762. }
  1763. case bitc::METADATA_LOCAL_VAR: {
  1764. // 10th field is for the obseleted 'inlinedAt:' field.
  1765. if (Record.size() < 8 || Record.size() > 10)
  1766. return error("Invalid record");
  1767. IsDistinct = Record[0] & 1;
  1768. bool HasAlignment = Record[0] & 2;
  1769. // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
  1770. // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
  1771. // this is newer version of record which doesn't have artificial tag.
  1772. bool HasTag = !HasAlignment && Record.size() > 8;
  1773. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
  1774. uint32_t AlignInBits = 0;
  1775. Metadata *Annotations = nullptr;
  1776. if (HasAlignment) {
  1777. if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
  1778. return error("Alignment value is too large");
  1779. AlignInBits = Record[8];
  1780. if (Record.size() > 9)
  1781. Annotations = getMDOrNull(Record[9]);
  1782. }
  1783. MetadataList.assignValue(
  1784. GET_OR_DISTINCT(DILocalVariable,
  1785. (Context, getMDOrNull(Record[1 + HasTag]),
  1786. getMDString(Record[2 + HasTag]),
  1787. getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
  1788. getDITypeRefOrNull(Record[5 + HasTag]),
  1789. Record[6 + HasTag], Flags, AlignInBits, Annotations)),
  1790. NextMetadataNo);
  1791. NextMetadataNo++;
  1792. break;
  1793. }
  1794. case bitc::METADATA_LABEL: {
  1795. if (Record.size() != 5)
  1796. return error("Invalid record");
  1797. IsDistinct = Record[0] & 1;
  1798. MetadataList.assignValue(
  1799. GET_OR_DISTINCT(DILabel, (Context, getMDOrNull(Record[1]),
  1800. getMDString(Record[2]),
  1801. getMDOrNull(Record[3]), Record[4])),
  1802. NextMetadataNo);
  1803. NextMetadataNo++;
  1804. break;
  1805. }
  1806. case bitc::METADATA_EXPRESSION: {
  1807. if (Record.size() < 1)
  1808. return error("Invalid record");
  1809. IsDistinct = Record[0] & 1;
  1810. uint64_t Version = Record[0] >> 1;
  1811. auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
  1812. SmallVector<uint64_t, 6> Buffer;
  1813. if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
  1814. return Err;
  1815. MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
  1816. NextMetadataNo);
  1817. NextMetadataNo++;
  1818. break;
  1819. }
  1820. case bitc::METADATA_GLOBAL_VAR_EXPR: {
  1821. if (Record.size() != 3)
  1822. return error("Invalid record");
  1823. IsDistinct = Record[0];
  1824. Metadata *Expr = getMDOrNull(Record[2]);
  1825. if (!Expr)
  1826. Expr = DIExpression::get(Context, {});
  1827. MetadataList.assignValue(
  1828. GET_OR_DISTINCT(DIGlobalVariableExpression,
  1829. (Context, getMDOrNull(Record[1]), Expr)),
  1830. NextMetadataNo);
  1831. NextMetadataNo++;
  1832. break;
  1833. }
  1834. case bitc::METADATA_OBJC_PROPERTY: {
  1835. if (Record.size() != 8)
  1836. return error("Invalid record");
  1837. IsDistinct = Record[0];
  1838. MetadataList.assignValue(
  1839. GET_OR_DISTINCT(DIObjCProperty,
  1840. (Context, getMDString(Record[1]),
  1841. getMDOrNull(Record[2]), Record[3],
  1842. getMDString(Record[4]), getMDString(Record[5]),
  1843. Record[6], getDITypeRefOrNull(Record[7]))),
  1844. NextMetadataNo);
  1845. NextMetadataNo++;
  1846. break;
  1847. }
  1848. case bitc::METADATA_IMPORTED_ENTITY: {
  1849. if (Record.size() < 6 && Record.size() > 8)
  1850. return error("Invalid record");
  1851. IsDistinct = Record[0];
  1852. bool HasFile = (Record.size() >= 7);
  1853. bool HasElements = (Record.size() >= 8);
  1854. MetadataList.assignValue(
  1855. GET_OR_DISTINCT(DIImportedEntity,
  1856. (Context, Record[1], getMDOrNull(Record[2]),
  1857. getDITypeRefOrNull(Record[3]),
  1858. HasFile ? getMDOrNull(Record[6]) : nullptr,
  1859. HasFile ? Record[4] : 0, getMDString(Record[5]),
  1860. HasElements ? getMDOrNull(Record[7]) : nullptr)),
  1861. NextMetadataNo);
  1862. NextMetadataNo++;
  1863. break;
  1864. }
  1865. case bitc::METADATA_STRING_OLD: {
  1866. std::string String(Record.begin(), Record.end());
  1867. // Test for upgrading !llvm.loop.
  1868. HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
  1869. ++NumMDStringLoaded;
  1870. Metadata *MD = MDString::get(Context, String);
  1871. MetadataList.assignValue(MD, NextMetadataNo);
  1872. NextMetadataNo++;
  1873. break;
  1874. }
  1875. case bitc::METADATA_STRINGS: {
  1876. auto CreateNextMDString = [&](StringRef Str) {
  1877. ++NumMDStringLoaded;
  1878. MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
  1879. NextMetadataNo++;
  1880. };
  1881. if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
  1882. return Err;
  1883. break;
  1884. }
  1885. case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
  1886. if (Record.size() % 2 == 0)
  1887. return error("Invalid record");
  1888. unsigned ValueID = Record[0];
  1889. if (ValueID >= ValueList.size())
  1890. return error("Invalid record");
  1891. if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
  1892. if (Error Err = parseGlobalObjectAttachment(
  1893. *GO, ArrayRef<uint64_t>(Record).slice(1)))
  1894. return Err;
  1895. break;
  1896. }
  1897. case bitc::METADATA_KIND: {
  1898. // Support older bitcode files that had METADATA_KIND records in a
  1899. // block with METADATA_BLOCK_ID.
  1900. if (Error Err = parseMetadataKindRecord(Record))
  1901. return Err;
  1902. break;
  1903. }
  1904. case bitc::METADATA_ARG_LIST: {
  1905. SmallVector<ValueAsMetadata *, 4> Elts;
  1906. Elts.reserve(Record.size());
  1907. for (uint64_t Elt : Record) {
  1908. Metadata *MD = getMD(Elt);
  1909. if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
  1910. return error(
  1911. "Invalid record: DIArgList should not contain forward refs");
  1912. if (!isa<ValueAsMetadata>(MD))
  1913. return error("Invalid record");
  1914. Elts.push_back(cast<ValueAsMetadata>(MD));
  1915. }
  1916. MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
  1917. NextMetadataNo++;
  1918. break;
  1919. }
  1920. }
  1921. return Error::success();
  1922. #undef GET_OR_DISTINCT
  1923. }
  1924. Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
  1925. ArrayRef<uint64_t> Record, StringRef Blob,
  1926. function_ref<void(StringRef)> CallBack) {
  1927. // All the MDStrings in the block are emitted together in a single
  1928. // record. The strings are concatenated and stored in a blob along with
  1929. // their sizes.
  1930. if (Record.size() != 2)
  1931. return error("Invalid record: metadata strings layout");
  1932. unsigned NumStrings = Record[0];
  1933. unsigned StringsOffset = Record[1];
  1934. if (!NumStrings)
  1935. return error("Invalid record: metadata strings with no strings");
  1936. if (StringsOffset > Blob.size())
  1937. return error("Invalid record: metadata strings corrupt offset");
  1938. StringRef Lengths = Blob.slice(0, StringsOffset);
  1939. SimpleBitstreamCursor R(Lengths);
  1940. StringRef Strings = Blob.drop_front(StringsOffset);
  1941. do {
  1942. if (R.AtEndOfStream())
  1943. return error("Invalid record: metadata strings bad length");
  1944. uint32_t Size;
  1945. if (Error E = R.ReadVBR(6).moveInto(Size))
  1946. return E;
  1947. if (Strings.size() < Size)
  1948. return error("Invalid record: metadata strings truncated chars");
  1949. CallBack(Strings.slice(0, Size));
  1950. Strings = Strings.drop_front(Size);
  1951. } while (--NumStrings);
  1952. return Error::success();
  1953. }
  1954. Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
  1955. GlobalObject &GO, ArrayRef<uint64_t> Record) {
  1956. assert(Record.size() % 2 == 0);
  1957. for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
  1958. auto K = MDKindMap.find(Record[I]);
  1959. if (K == MDKindMap.end())
  1960. return error("Invalid ID");
  1961. MDNode *MD =
  1962. dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
  1963. if (!MD)
  1964. return error("Invalid metadata attachment: expect fwd ref to MDNode");
  1965. GO.addMetadata(K->second, *MD);
  1966. }
  1967. return Error::success();
  1968. }
  1969. /// Parse metadata attachments.
  1970. Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
  1971. Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
  1972. if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1973. return Err;
  1974. SmallVector<uint64_t, 64> Record;
  1975. PlaceholderQueue Placeholders;
  1976. while (true) {
  1977. BitstreamEntry Entry;
  1978. if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
  1979. return E;
  1980. switch (Entry.Kind) {
  1981. case BitstreamEntry::SubBlock: // Handled for us already.
  1982. case BitstreamEntry::Error:
  1983. return error("Malformed block");
  1984. case BitstreamEntry::EndBlock:
  1985. resolveForwardRefsAndPlaceholders(Placeholders);
  1986. return Error::success();
  1987. case BitstreamEntry::Record:
  1988. // The interesting case.
  1989. break;
  1990. }
  1991. // Read a metadata attachment record.
  1992. Record.clear();
  1993. ++NumMDRecordLoaded;
  1994. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  1995. if (!MaybeRecord)
  1996. return MaybeRecord.takeError();
  1997. switch (MaybeRecord.get()) {
  1998. default: // Default behavior: ignore.
  1999. break;
  2000. case bitc::METADATA_ATTACHMENT: {
  2001. unsigned RecordLength = Record.size();
  2002. if (Record.empty())
  2003. return error("Invalid record");
  2004. if (RecordLength % 2 == 0) {
  2005. // A function attachment.
  2006. if (Error Err = parseGlobalObjectAttachment(F, Record))
  2007. return Err;
  2008. continue;
  2009. }
  2010. // An instruction attachment.
  2011. Instruction *Inst = InstructionList[Record[0]];
  2012. for (unsigned i = 1; i != RecordLength; i = i + 2) {
  2013. unsigned Kind = Record[i];
  2014. DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
  2015. if (I == MDKindMap.end())
  2016. return error("Invalid ID");
  2017. if (I->second == LLVMContext::MD_tbaa && StripTBAA)
  2018. continue;
  2019. auto Idx = Record[i + 1];
  2020. if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
  2021. !MetadataList.lookup(Idx)) {
  2022. // Load the attachment if it is in the lazy-loadable range and hasn't
  2023. // been loaded yet.
  2024. lazyLoadOneMetadata(Idx, Placeholders);
  2025. resolveForwardRefsAndPlaceholders(Placeholders);
  2026. }
  2027. Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
  2028. if (isa<LocalAsMetadata>(Node))
  2029. // Drop the attachment. This used to be legal, but there's no
  2030. // upgrade path.
  2031. break;
  2032. MDNode *MD = dyn_cast_or_null<MDNode>(Node);
  2033. if (!MD)
  2034. return error("Invalid metadata attachment");
  2035. if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
  2036. MD = upgradeInstructionLoopAttachment(*MD);
  2037. if (I->second == LLVMContext::MD_tbaa) {
  2038. assert(!MD->isTemporary() && "should load MDs before attachments");
  2039. MD = UpgradeTBAANode(*MD);
  2040. }
  2041. Inst->setMetadata(I->second, MD);
  2042. }
  2043. break;
  2044. }
  2045. }
  2046. }
  2047. }
  2048. /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
  2049. Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
  2050. SmallVectorImpl<uint64_t> &Record) {
  2051. if (Record.size() < 2)
  2052. return error("Invalid record");
  2053. unsigned Kind = Record[0];
  2054. SmallString<8> Name(Record.begin() + 1, Record.end());
  2055. unsigned NewKind = TheModule.getMDKindID(Name.str());
  2056. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  2057. return error("Conflicting METADATA_KIND records");
  2058. return Error::success();
  2059. }
  2060. /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
  2061. Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
  2062. if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
  2063. return Err;
  2064. SmallVector<uint64_t, 64> Record;
  2065. // Read all the records.
  2066. while (true) {
  2067. BitstreamEntry Entry;
  2068. if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
  2069. return E;
  2070. switch (Entry.Kind) {
  2071. case BitstreamEntry::SubBlock: // Handled for us already.
  2072. case BitstreamEntry::Error:
  2073. return error("Malformed block");
  2074. case BitstreamEntry::EndBlock:
  2075. return Error::success();
  2076. case BitstreamEntry::Record:
  2077. // The interesting case.
  2078. break;
  2079. }
  2080. // Read a record.
  2081. Record.clear();
  2082. ++NumMDRecordLoaded;
  2083. Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
  2084. if (!MaybeCode)
  2085. return MaybeCode.takeError();
  2086. switch (MaybeCode.get()) {
  2087. default: // Default behavior: ignore.
  2088. break;
  2089. case bitc::METADATA_KIND: {
  2090. if (Error Err = parseMetadataKindRecord(Record))
  2091. return Err;
  2092. break;
  2093. }
  2094. }
  2095. }
  2096. }
  2097. MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
  2098. Pimpl = std::move(RHS.Pimpl);
  2099. return *this;
  2100. }
  2101. MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
  2102. : Pimpl(std::move(RHS.Pimpl)) {}
  2103. MetadataLoader::~MetadataLoader() = default;
  2104. MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
  2105. BitcodeReaderValueList &ValueList,
  2106. bool IsImporting,
  2107. std::function<Type *(unsigned)> getTypeByID)
  2108. : Pimpl(std::make_unique<MetadataLoaderImpl>(
  2109. Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
  2110. Error MetadataLoader::parseMetadata(bool ModuleLevel) {
  2111. return Pimpl->parseMetadata(ModuleLevel);
  2112. }
  2113. bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
  2114. /// Return the given metadata, creating a replaceable forward reference if
  2115. /// necessary.
  2116. Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
  2117. return Pimpl->getMetadataFwdRefOrLoad(Idx);
  2118. }
  2119. DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
  2120. return Pimpl->lookupSubprogramForFunction(F);
  2121. }
  2122. Error MetadataLoader::parseMetadataAttachment(
  2123. Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
  2124. return Pimpl->parseMetadataAttachment(F, InstructionList);
  2125. }
  2126. Error MetadataLoader::parseMetadataKinds() {
  2127. return Pimpl->parseMetadataKinds();
  2128. }
  2129. void MetadataLoader::setStripTBAA(bool StripTBAA) {
  2130. return Pimpl->setStripTBAA(StripTBAA);
  2131. }
  2132. bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
  2133. unsigned MetadataLoader::size() const { return Pimpl->size(); }
  2134. void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
  2135. void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
  2136. return Pimpl->upgradeDebugIntrinsics(F);
  2137. }