MetadataLoader.cpp 62 KB

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