BitstreamReader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. //===- BitstreamReader.cpp - BitstreamReader 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 "llvm/Bitcode/BitstreamReader.h"
  10. using namespace llvm;
  11. //===----------------------------------------------------------------------===//
  12. // BitstreamCursor implementation
  13. //===----------------------------------------------------------------------===//
  14. void BitstreamCursor::freeState() {
  15. // Free all the Abbrevs.
  16. CurAbbrevs.clear();
  17. // Free all the Abbrevs in the block scope.
  18. BlockScope.clear();
  19. }
  20. /// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
  21. /// the block, and return true if the block has an error.
  22. bool BitstreamCursor::EnterSubBlock(unsigned BlockID, unsigned *NumWordsP) {
  23. // Save the current block's state on BlockScope.
  24. BlockScope.push_back(Block(CurCodeSize));
  25. BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
  26. // Add the abbrevs specific to this block to the CurAbbrevs list.
  27. if (const BitstreamReader::BlockInfo *Info =
  28. BitStream->getBlockInfo(BlockID)) {
  29. CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
  30. Info->Abbrevs.end());
  31. }
  32. // Get the codesize of this block.
  33. CurCodeSize = ReadVBR(bitc::CodeLenWidth);
  34. // We can't read more than MaxChunkSize at a time
  35. if (CurCodeSize > MaxChunkSize)
  36. return true;
  37. SkipToFourByteBoundary();
  38. unsigned NumWords = Read(bitc::BlockSizeWidth);
  39. if (NumWordsP) *NumWordsP = NumWords;
  40. // Validate that this block is sane.
  41. return CurCodeSize == 0 || AtEndOfStream();
  42. }
  43. static uint64_t readAbbreviatedField(BitstreamCursor &Cursor,
  44. const BitCodeAbbrevOp &Op) {
  45. assert(!Op.isLiteral() && "Not to be used with literals!");
  46. // Decode the value as we are commanded.
  47. switch (Op.getEncoding()) {
  48. case BitCodeAbbrevOp::Array:
  49. case BitCodeAbbrevOp::Blob:
  50. llvm_unreachable("Should not reach here");
  51. case BitCodeAbbrevOp::Fixed:
  52. assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
  53. return Cursor.Read((unsigned)Op.getEncodingData());
  54. case BitCodeAbbrevOp::VBR:
  55. assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
  56. return Cursor.ReadVBR64((unsigned)Op.getEncodingData());
  57. case BitCodeAbbrevOp::Char6:
  58. return BitCodeAbbrevOp::DecodeChar6(Cursor.Read(6));
  59. }
  60. llvm_unreachable("invalid abbreviation encoding");
  61. }
  62. static void skipAbbreviatedField(BitstreamCursor &Cursor,
  63. const BitCodeAbbrevOp &Op) {
  64. assert(!Op.isLiteral() && "Not to be used with literals!");
  65. // Decode the value as we are commanded.
  66. switch (Op.getEncoding()) {
  67. case BitCodeAbbrevOp::Array:
  68. case BitCodeAbbrevOp::Blob:
  69. llvm_unreachable("Should not reach here");
  70. case BitCodeAbbrevOp::Fixed:
  71. assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
  72. Cursor.Read((unsigned)Op.getEncodingData());
  73. break;
  74. case BitCodeAbbrevOp::VBR:
  75. assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize);
  76. Cursor.ReadVBR64((unsigned)Op.getEncodingData());
  77. break;
  78. case BitCodeAbbrevOp::Char6:
  79. Cursor.Read(6);
  80. break;
  81. }
  82. }
  83. /// skipRecord - Read the current record and discard it.
  84. void BitstreamCursor::skipRecord(unsigned AbbrevID) {
  85. // Skip unabbreviated records by reading past their entries.
  86. if (AbbrevID == bitc::UNABBREV_RECORD) {
  87. unsigned Code = ReadVBR(6);
  88. (void)Code;
  89. unsigned NumElts = ReadVBR(6);
  90. for (unsigned i = 0; i != NumElts; ++i)
  91. (void)ReadVBR64(6);
  92. return;
  93. }
  94. const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
  95. for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
  96. const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
  97. if (Op.isLiteral())
  98. continue;
  99. if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
  100. Op.getEncoding() != BitCodeAbbrevOp::Blob) {
  101. skipAbbreviatedField(*this, Op);
  102. continue;
  103. }
  104. if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
  105. // Array case. Read the number of elements as a vbr6.
  106. unsigned NumElts = ReadVBR(6);
  107. // Get the element encoding.
  108. assert(i+2 == e && "array op not second to last?");
  109. const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
  110. // Read all the elements.
  111. for (; NumElts; --NumElts)
  112. skipAbbreviatedField(*this, EltEnc);
  113. continue;
  114. }
  115. assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
  116. // Blob case. Read the number of bytes as a vbr6.
  117. unsigned NumElts = ReadVBR(6);
  118. SkipToFourByteBoundary(); // 32-bit alignment
  119. // Figure out where the end of this blob will be including tail padding.
  120. size_t NewEnd = GetCurrentBitNo()+((NumElts+3)&~3)*8;
  121. // If this would read off the end of the bitcode file, just set the
  122. // record to empty and return.
  123. if (!canSkipToPos(NewEnd/8)) {
  124. NextChar = BitStream->getBitcodeBytes().getExtent();
  125. break;
  126. }
  127. // Skip over the blob.
  128. JumpToBit(NewEnd);
  129. }
  130. }
  131. unsigned BitstreamCursor::readRecord(unsigned AbbrevID,
  132. SmallVectorImpl<uint64_t> &Vals,
  133. StringRef *Blob) {
  134. if (AbbrevID == bitc::UNABBREV_RECORD) {
  135. unsigned Code = ReadVBR(6);
  136. unsigned NumElts = ReadVBR(6);
  137. for (unsigned i = 0; i != NumElts; ++i)
  138. Vals.push_back(ReadVBR64(6));
  139. return Code;
  140. }
  141. const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
  142. // Read the record code first.
  143. assert(Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?");
  144. const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
  145. unsigned Code;
  146. if (CodeOp.isLiteral())
  147. Code = CodeOp.getLiteralValue();
  148. else {
  149. if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
  150. CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
  151. report_fatal_error("Abbreviation starts with an Array or a Blob");
  152. Code = readAbbreviatedField(*this, CodeOp);
  153. }
  154. for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
  155. const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
  156. if (Op.isLiteral()) {
  157. Vals.push_back(Op.getLiteralValue());
  158. continue;
  159. }
  160. if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
  161. Op.getEncoding() != BitCodeAbbrevOp::Blob) {
  162. Vals.push_back(readAbbreviatedField(*this, Op));
  163. continue;
  164. }
  165. if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
  166. // Array case. Read the number of elements as a vbr6.
  167. unsigned NumElts = ReadVBR(6);
  168. // Get the element encoding.
  169. if (i + 2 != e)
  170. report_fatal_error("Array op not second to last");
  171. const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
  172. if (!EltEnc.isEncoding())
  173. report_fatal_error(
  174. "Array element type has to be an encoding of a type");
  175. if (EltEnc.getEncoding() == BitCodeAbbrevOp::Array ||
  176. EltEnc.getEncoding() == BitCodeAbbrevOp::Blob)
  177. report_fatal_error("Array element type can't be an Array or a Blob");
  178. // Read all the elements.
  179. for (; NumElts; --NumElts)
  180. Vals.push_back(readAbbreviatedField(*this, EltEnc));
  181. continue;
  182. }
  183. assert(Op.getEncoding() == BitCodeAbbrevOp::Blob);
  184. // Blob case. Read the number of bytes as a vbr6.
  185. unsigned NumElts = ReadVBR(6);
  186. SkipToFourByteBoundary(); // 32-bit alignment
  187. // Figure out where the end of this blob will be including tail padding.
  188. size_t CurBitPos = GetCurrentBitNo();
  189. size_t NewEnd = CurBitPos+((NumElts+3)&~3)*8;
  190. // If this would read off the end of the bitcode file, just set the
  191. // record to empty and return.
  192. if (!canSkipToPos(NewEnd/8)) {
  193. Vals.append(NumElts, 0);
  194. NextChar = BitStream->getBitcodeBytes().getExtent();
  195. break;
  196. }
  197. // Otherwise, inform the streamer that we need these bytes in memory.
  198. const char *Ptr = (const char*)
  199. BitStream->getBitcodeBytes().getPointer(CurBitPos/8, NumElts);
  200. // If we can return a reference to the data, do so to avoid copying it.
  201. if (Blob) {
  202. *Blob = StringRef(Ptr, NumElts);
  203. } else {
  204. // Otherwise, unpack into Vals with zero extension.
  205. for (; NumElts; --NumElts)
  206. Vals.push_back((unsigned char)*Ptr++);
  207. }
  208. // Skip over tail padding.
  209. JumpToBit(NewEnd);
  210. }
  211. return Code;
  212. }
  213. void BitstreamCursor::ReadAbbrevRecord() {
  214. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  215. unsigned NumOpInfo = ReadVBR(5);
  216. for (unsigned i = 0; i != NumOpInfo; ++i) {
  217. bool IsLiteral = Read(1);
  218. if (IsLiteral) {
  219. Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
  220. continue;
  221. }
  222. BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
  223. if (BitCodeAbbrevOp::hasEncodingData(E)) {
  224. uint64_t Data = ReadVBR64(5);
  225. // As a special case, handle fixed(0) (i.e., a fixed field with zero bits)
  226. // and vbr(0) as a literal zero. This is decoded the same way, and avoids
  227. // a slow path in Read() to have to handle reading zero bits.
  228. if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
  229. Data == 0) {
  230. Abbv->Add(BitCodeAbbrevOp(0));
  231. continue;
  232. }
  233. if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
  234. Data > MaxChunkSize)
  235. report_fatal_error(
  236. "Fixed or VBR abbrev record with size > MaxChunkData");
  237. Abbv->Add(BitCodeAbbrevOp(E, Data));
  238. } else
  239. Abbv->Add(BitCodeAbbrevOp(E));
  240. }
  241. if (Abbv->getNumOperandInfos() == 0)
  242. report_fatal_error("Abbrev record with no operands");
  243. CurAbbrevs.push_back(Abbv);
  244. }
  245. bool BitstreamCursor::ReadBlockInfoBlock(unsigned *pCount) {
  246. // If this is the second stream to get to the block info block, skip it.
  247. if (BitStream->hasBlockInfoRecords())
  248. return SkipBlock();
  249. if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
  250. SmallVector<uint64_t, 64> Record;
  251. BitstreamReader::BlockInfo *CurBlockInfo = nullptr;
  252. // Read all the records for this module.
  253. while (1) {
  254. BitstreamEntry Entry = advanceSkippingSubblocks(AF_DontAutoprocessAbbrevs, pCount);
  255. switch (Entry.Kind) {
  256. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  257. case llvm::BitstreamEntry::Error:
  258. return true;
  259. case llvm::BitstreamEntry::EndBlock:
  260. return false;
  261. case llvm::BitstreamEntry::Record:
  262. // The interesting case.
  263. break;
  264. }
  265. // Read abbrev records, associate them with CurBID.
  266. if (Entry.ID == bitc::DEFINE_ABBREV) {
  267. if (!CurBlockInfo) return true;
  268. ReadAbbrevRecord();
  269. // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
  270. // appropriate BlockInfo.
  271. CurBlockInfo->Abbrevs.push_back(std::move(CurAbbrevs.back()));
  272. CurAbbrevs.pop_back();
  273. continue;
  274. }
  275. // Read a record.
  276. Record.clear();
  277. switch (readRecord(Entry.ID, Record)) {
  278. default: break; // Default behavior, ignore unknown content.
  279. case bitc::BLOCKINFO_CODE_SETBID:
  280. if (Record.size() < 1) return true;
  281. CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
  282. break;
  283. case bitc::BLOCKINFO_CODE_BLOCKNAME: {
  284. if (!CurBlockInfo) return true;
  285. if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
  286. std::string Name;
  287. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  288. Name += (char)Record[i];
  289. CurBlockInfo->Name = Name;
  290. break;
  291. }
  292. case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
  293. if (!CurBlockInfo) return true;
  294. if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
  295. std::string Name;
  296. for (unsigned i = 1, e = Record.size(); i != e; ++i)
  297. Name += (char)Record[i];
  298. CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
  299. Name));
  300. break;
  301. }
  302. }
  303. }
  304. }
  305. // HLSL Change Starts
  306. void BitstreamUseTracker::track(BitstreamUseTracker *BT, uint64_t begin,
  307. uint64_t end) {
  308. if (BT)
  309. BT->insert(begin, end);
  310. }
  311. BitstreamUseTracker::ExtendResult
  312. BitstreamUseTracker::extendRange(UseRange &Curr, UseRange &NewRange) {
  313. // Most likely case first.
  314. if (Curr.first <= NewRange.first && Curr.second < NewRange.second) {
  315. Curr.second = NewRange.second;
  316. return ExtendedEnd;
  317. }
  318. if (Curr.first <= NewRange.first && NewRange.second <= Curr.second) {
  319. return Included; // already included.
  320. }
  321. if (NewRange.first < Curr.first && NewRange.second <= Curr.second) {
  322. return ExtendedBegin;
  323. }
  324. if (NewRange.first < Curr.first && Curr.second < NewRange.second) {
  325. return ExtendedBoth;
  326. }
  327. return Exclusive;
  328. }
  329. bool BitstreamUseTracker::isDense(uint64_t endBitoffset) const {
  330. return Ranges.size() == 1 && Ranges[0].first == 0 &&
  331. Ranges[0].second == endBitoffset;
  332. }
  333. bool BitstreamUseTracker::considerMergeRight(size_t idx) {
  334. bool changed = false;
  335. while (idx < Ranges.size() - 1) {
  336. if (Ranges[idx].second >= Ranges[idx + 1].first) {
  337. Ranges[idx].second = Ranges[idx + 1].second;
  338. Ranges.erase(&Ranges[idx + 1]);
  339. changed = true;
  340. }
  341. }
  342. return changed;
  343. }
  344. void BitstreamUseTracker::insert(uint64_t begin, uint64_t end) {
  345. UseRange IR(begin, end);
  346. for (size_t i = 0; i < Ranges.size(); ++i) {
  347. ExtendResult ER = extendRange(Ranges[i], IR);
  348. switch (ER) {
  349. case Included:
  350. return;
  351. case ExtendedEnd:
  352. considerMergeRight(i);
  353. return;
  354. case ExtendedBegin:
  355. if (i > 0)
  356. considerMergeRight(i - 1);
  357. return;
  358. case ExtendedBoth:
  359. if (i > 0) {
  360. if (!considerMergeRight(i - 1))
  361. considerMergeRight(i);
  362. } else
  363. considerMergeRight(i);
  364. return;
  365. case Exclusive:
  366. // If completely to the left, then insert there; otherwise,
  367. // keep traversing in order.
  368. if (end <= Ranges[i].first) {
  369. Ranges.insert(&Ranges[i], IR);
  370. return;
  371. }
  372. }
  373. }
  374. // This range goes at the end.
  375. Ranges.push_back(IR);
  376. }
  377. BitstreamUseTracker::ScopeTrack::~ScopeTrack() {
  378. if (BC->getBitStreamReader()->Tracker != nullptr)
  379. BC->getBitStreamReader()->Tracker->insert(begin, BC->GetCurrentBitNo());
  380. }
  381. BitstreamUseTracker::ScopeTrack
  382. BitstreamUseTracker::scope_track(BitstreamCursor *BC) {
  383. ScopeTrack Result;
  384. Result.BC = BC;
  385. Result.begin = BC->GetCurrentBitNo();
  386. return Result;
  387. }
  388. // HLSL Change Ends