Bug Summary

File:llvm/include/llvm/Bitstream/BitstreamReader.h
Warning:line 220, column 39
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::SimpleBitstreamCursor::word_t'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name BitstreamReader.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Bitstream/Reader -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Bitstream/Reader -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp

1//===- BitstreamReader.cpp - BitstreamReader 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
9#include "llvm/Bitstream/BitstreamReader.h"
10#include "llvm/ADT/StringRef.h"
11#include <cassert>
12#include <string>
13
14using namespace llvm;
15
16//===----------------------------------------------------------------------===//
17// BitstreamCursor implementation
18//===----------------------------------------------------------------------===//
19
20/// Having read the ENTER_SUBBLOCK abbrevid, enter the block.
21Error BitstreamCursor::EnterSubBlock(unsigned BlockID, unsigned *NumWordsP) {
22 // Save the current block's state on BlockScope.
23 BlockScope.push_back(Block(CurCodeSize));
24 BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
25
26 // Add the abbrevs specific to this block to the CurAbbrevs list.
27 if (BlockInfo) {
28 if (const BitstreamBlockInfo::BlockInfo *Info =
29 BlockInfo->getBlockInfo(BlockID)) {
30 CurAbbrevs.insert(CurAbbrevs.end(), Info->Abbrevs.begin(),
31 Info->Abbrevs.end());
32 }
33 }
34
35 // Get the codesize of this block.
36 Expected<uint32_t> MaybeVBR = ReadVBR(bitc::CodeLenWidth);
37 if (!MaybeVBR)
38 return MaybeVBR.takeError();
39 CurCodeSize = MaybeVBR.get();
40
41 if (CurCodeSize > MaxChunkSize)
42 return llvm::createStringError(
43 std::errc::illegal_byte_sequence,
44 "can't read more than %zu at a time, trying to read %u", +MaxChunkSize,
45 CurCodeSize);
46
47 SkipToFourByteBoundary();
48 Expected<word_t> MaybeNum = Read(bitc::BlockSizeWidth);
49 if (!MaybeNum)
50 return MaybeNum.takeError();
51 word_t NumWords = MaybeNum.get();
52 if (NumWordsP)
53 *NumWordsP = NumWords;
54
55 if (CurCodeSize == 0)
56 return llvm::createStringError(
57 std::errc::illegal_byte_sequence,
58 "can't enter sub-block: current code size is 0");
59 if (AtEndOfStream())
60 return llvm::createStringError(
61 std::errc::illegal_byte_sequence,
62 "can't enter sub block: already at end of stream");
63
64 return Error::success();
65}
66
67static Expected<uint64_t> readAbbreviatedField(BitstreamCursor &Cursor,
68 const BitCodeAbbrevOp &Op) {
69 assert(!Op.isLiteral() && "Not to be used with literals!")((!Op.isLiteral() && "Not to be used with literals!")
? static_cast<void> (0) : __assert_fail ("!Op.isLiteral() && \"Not to be used with literals!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 69, __PRETTY_FUNCTION__))
;
70
71 // Decode the value as we are commanded.
72 switch (Op.getEncoding()) {
73 case BitCodeAbbrevOp::Array:
74 case BitCodeAbbrevOp::Blob:
75 llvm_unreachable("Should not reach here")::llvm::llvm_unreachable_internal("Should not reach here", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 75)
;
76 case BitCodeAbbrevOp::Fixed:
77 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize)(((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize) ?
static_cast<void> (0) : __assert_fail ("(unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 77, __PRETTY_FUNCTION__))
;
78 return Cursor.Read((unsigned)Op.getEncodingData());
79 case BitCodeAbbrevOp::VBR:
80 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize)(((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize) ?
static_cast<void> (0) : __assert_fail ("(unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 80, __PRETTY_FUNCTION__))
;
81 return Cursor.ReadVBR64((unsigned)Op.getEncodingData());
82 case BitCodeAbbrevOp::Char6:
83 if (Expected<unsigned> Res = Cursor.Read(6))
84 return BitCodeAbbrevOp::DecodeChar6(Res.get());
85 else
86 return Res.takeError();
87 }
88 llvm_unreachable("invalid abbreviation encoding")::llvm::llvm_unreachable_internal("invalid abbreviation encoding"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 88)
;
89}
90
91static Error skipAbbreviatedField(BitstreamCursor &Cursor,
92 const BitCodeAbbrevOp &Op) {
93 assert(!Op.isLiteral() && "Not to be used with literals!")((!Op.isLiteral() && "Not to be used with literals!")
? static_cast<void> (0) : __assert_fail ("!Op.isLiteral() && \"Not to be used with literals!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 93, __PRETTY_FUNCTION__))
;
94
95 // Decode the value as we are commanded.
96 switch (Op.getEncoding()) {
97 case BitCodeAbbrevOp::Array:
98 case BitCodeAbbrevOp::Blob:
99 llvm_unreachable("Should not reach here")::llvm::llvm_unreachable_internal("Should not reach here", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 99)
;
100 case BitCodeAbbrevOp::Fixed:
101 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize)(((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize) ?
static_cast<void> (0) : __assert_fail ("(unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 101, __PRETTY_FUNCTION__))
;
102 if (Expected<unsigned> Res = Cursor.Read((unsigned)Op.getEncodingData()))
103 break;
104 else
105 return Res.takeError();
106 case BitCodeAbbrevOp::VBR:
107 assert((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize)(((unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize) ?
static_cast<void> (0) : __assert_fail ("(unsigned)Op.getEncodingData() <= Cursor.MaxChunkSize"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 107, __PRETTY_FUNCTION__))
;
108 if (Expected<uint64_t> Res =
109 Cursor.ReadVBR64((unsigned)Op.getEncodingData()))
110 break;
111 else
112 return Res.takeError();
113 case BitCodeAbbrevOp::Char6:
114 if (Expected<unsigned> Res = Cursor.Read(6))
115 break;
116 else
117 return Res.takeError();
118 }
119 return ErrorSuccess();
120}
121
122/// skipRecord - Read the current record and discard it.
123Expected<unsigned> BitstreamCursor::skipRecord(unsigned AbbrevID) {
124 // Skip unabbreviated records by reading past their entries.
125 if (AbbrevID == bitc::UNABBREV_RECORD) {
126 Expected<uint32_t> MaybeCode = ReadVBR(6);
127 if (!MaybeCode)
128 return MaybeCode.takeError();
129 unsigned Code = MaybeCode.get();
130 Expected<uint32_t> MaybeVBR = ReadVBR(6);
131 if (!MaybeVBR)
132 return MaybeVBR.get();
133 unsigned NumElts = MaybeVBR.get();
134 for (unsigned i = 0; i != NumElts; ++i)
135 if (Expected<uint64_t> Res = ReadVBR64(6))
136 ; // Skip!
137 else
138 return Res.takeError();
139 return Code;
140 }
141
142 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
143 const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
144 unsigned Code;
145 if (CodeOp.isLiteral())
146 Code = CodeOp.getLiteralValue();
147 else {
148 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
149 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
150 return llvm::createStringError(
151 std::errc::illegal_byte_sequence,
152 "Abbreviation starts with an Array or a Blob");
153 Expected<uint64_t> MaybeCode = readAbbreviatedField(*this, CodeOp);
154 if (!MaybeCode)
155 return MaybeCode.takeError();
156 Code = MaybeCode.get();
157 }
158
159 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i < e; ++i) {
160 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
161 if (Op.isLiteral())
162 continue;
163
164 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
165 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
166 if (Error Err = skipAbbreviatedField(*this, Op))
167 return std::move(Err);
168 continue;
169 }
170
171 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
172 // Array case. Read the number of elements as a vbr6.
173 Expected<uint32_t> MaybeNum = ReadVBR(6);
174 if (!MaybeNum)
175 return MaybeNum.takeError();
176 unsigned NumElts = MaybeNum.get();
177
178 // Get the element encoding.
179 assert(i+2 == e && "array op not second to last?")((i+2 == e && "array op not second to last?") ? static_cast
<void> (0) : __assert_fail ("i+2 == e && \"array op not second to last?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 179, __PRETTY_FUNCTION__))
;
180 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
181
182 // Read all the elements.
183 // Decode the value as we are commanded.
184 switch (EltEnc.getEncoding()) {
185 default:
186 report_fatal_error("Array element type can't be an Array or a Blob");
187 case BitCodeAbbrevOp::Fixed:
188 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize)(((unsigned)EltEnc.getEncodingData() <= MaxChunkSize) ? static_cast
<void> (0) : __assert_fail ("(unsigned)EltEnc.getEncodingData() <= MaxChunkSize"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 188, __PRETTY_FUNCTION__))
;
189 if (Error Err = JumpToBit(GetCurrentBitNo() +
190 NumElts * EltEnc.getEncodingData()))
191 return std::move(Err);
192 break;
193 case BitCodeAbbrevOp::VBR:
194 assert((unsigned)EltEnc.getEncodingData() <= MaxChunkSize)(((unsigned)EltEnc.getEncodingData() <= MaxChunkSize) ? static_cast
<void> (0) : __assert_fail ("(unsigned)EltEnc.getEncodingData() <= MaxChunkSize"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 194, __PRETTY_FUNCTION__))
;
195 for (; NumElts; --NumElts)
196 if (Expected<uint64_t> Res =
197 ReadVBR64((unsigned)EltEnc.getEncodingData()))
198 ; // Skip!
199 else
200 return Res.takeError();
201 break;
202 case BitCodeAbbrevOp::Char6:
203 if (Error Err = JumpToBit(GetCurrentBitNo() + NumElts * 6))
204 return std::move(Err);
205 break;
206 }
207 continue;
208 }
209
210 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob)((Op.getEncoding() == BitCodeAbbrevOp::Blob) ? static_cast<
void> (0) : __assert_fail ("Op.getEncoding() == BitCodeAbbrevOp::Blob"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 210, __PRETTY_FUNCTION__))
;
211 // Blob case. Read the number of bytes as a vbr6.
212 Expected<uint32_t> MaybeNum = ReadVBR(6);
213 if (!MaybeNum)
214 return MaybeNum.takeError();
215 unsigned NumElts = MaybeNum.get();
216 SkipToFourByteBoundary(); // 32-bit alignment
217
218 // Figure out where the end of this blob will be including tail padding.
219 size_t NewEnd = GetCurrentBitNo()+((NumElts+3)&~3)*8;
220
221 // If this would read off the end of the bitcode file, just set the
222 // record to empty and return.
223 if (!canSkipToPos(NewEnd/8)) {
224 skipToEnd();
225 break;
226 }
227
228 // Skip over the blob.
229 if (Error Err = JumpToBit(NewEnd))
230 return std::move(Err);
231 }
232 return Code;
233}
234
235Expected<unsigned> BitstreamCursor::readRecord(unsigned AbbrevID,
236 SmallVectorImpl<uint64_t> &Vals,
237 StringRef *Blob) {
238 if (AbbrevID == bitc::UNABBREV_RECORD) {
239 Expected<uint32_t> MaybeCode = ReadVBR(6);
240 if (!MaybeCode)
241 return MaybeCode.takeError();
242 uint32_t Code = MaybeCode.get();
243 Expected<uint32_t> MaybeNumElts = ReadVBR(6);
244 if (!MaybeNumElts)
245 return MaybeNumElts.takeError();
246 uint32_t NumElts = MaybeNumElts.get();
247
248 for (unsigned i = 0; i != NumElts; ++i)
249 if (Expected<uint64_t> MaybeVal = ReadVBR64(6))
250 Vals.push_back(MaybeVal.get());
251 else
252 return MaybeVal.takeError();
253 return Code;
254 }
255
256 const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
257
258 // Read the record code first.
259 assert(Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?")((Abbv->getNumOperandInfos() != 0 && "no record code in abbreviation?"
) ? static_cast<void> (0) : __assert_fail ("Abbv->getNumOperandInfos() != 0 && \"no record code in abbreviation?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 259, __PRETTY_FUNCTION__))
;
260 const BitCodeAbbrevOp &CodeOp = Abbv->getOperandInfo(0);
261 unsigned Code;
262 if (CodeOp.isLiteral())
263 Code = CodeOp.getLiteralValue();
264 else {
265 if (CodeOp.getEncoding() == BitCodeAbbrevOp::Array ||
266 CodeOp.getEncoding() == BitCodeAbbrevOp::Blob)
267 report_fatal_error("Abbreviation starts with an Array or a Blob");
268 if (Expected<uint64_t> MaybeCode = readAbbreviatedField(*this, CodeOp))
269 Code = MaybeCode.get();
270 else
271 return MaybeCode.takeError();
272 }
273
274 for (unsigned i = 1, e = Abbv->getNumOperandInfos(); i != e; ++i) {
275 const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
276 if (Op.isLiteral()) {
277 Vals.push_back(Op.getLiteralValue());
278 continue;
279 }
280
281 if (Op.getEncoding() != BitCodeAbbrevOp::Array &&
282 Op.getEncoding() != BitCodeAbbrevOp::Blob) {
283 if (Expected<uint64_t> MaybeVal = readAbbreviatedField(*this, Op))
284 Vals.push_back(MaybeVal.get());
285 else
286 return MaybeVal.takeError();
287 continue;
288 }
289
290 if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
291 // Array case. Read the number of elements as a vbr6.
292 Expected<uint32_t> MaybeNumElts = ReadVBR(6);
293 if (!MaybeNumElts)
294 return MaybeNumElts.takeError();
295 uint32_t NumElts = MaybeNumElts.get();
296
297 // Get the element encoding.
298 if (i + 2 != e)
299 report_fatal_error("Array op not second to last");
300 const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
301 if (!EltEnc.isEncoding())
302 report_fatal_error(
303 "Array element type has to be an encoding of a type");
304
305 // Read all the elements.
306 switch (EltEnc.getEncoding()) {
307 default:
308 report_fatal_error("Array element type can't be an Array or a Blob");
309 case BitCodeAbbrevOp::Fixed:
310 for (; NumElts; --NumElts)
311 if (Expected<SimpleBitstreamCursor::word_t> MaybeVal =
312 Read((unsigned)EltEnc.getEncodingData()))
313 Vals.push_back(MaybeVal.get());
314 else
315 return MaybeVal.takeError();
316 break;
317 case BitCodeAbbrevOp::VBR:
318 for (; NumElts; --NumElts)
319 if (Expected<uint64_t> MaybeVal =
320 ReadVBR64((unsigned)EltEnc.getEncodingData()))
321 Vals.push_back(MaybeVal.get());
322 else
323 return MaybeVal.takeError();
324 break;
325 case BitCodeAbbrevOp::Char6:
326 for (; NumElts; --NumElts)
327 if (Expected<SimpleBitstreamCursor::word_t> MaybeVal = Read(6))
328 Vals.push_back(BitCodeAbbrevOp::DecodeChar6(MaybeVal.get()));
329 else
330 return MaybeVal.takeError();
331 }
332 continue;
333 }
334
335 assert(Op.getEncoding() == BitCodeAbbrevOp::Blob)((Op.getEncoding() == BitCodeAbbrevOp::Blob) ? static_cast<
void> (0) : __assert_fail ("Op.getEncoding() == BitCodeAbbrevOp::Blob"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Bitstream/Reader/BitstreamReader.cpp"
, 335, __PRETTY_FUNCTION__))
;
336 // Blob case. Read the number of bytes as a vbr6.
337 Expected<uint32_t> MaybeNumElts = ReadVBR(6);
338 if (!MaybeNumElts)
339 return MaybeNumElts.takeError();
340 uint32_t NumElts = MaybeNumElts.get();
341 SkipToFourByteBoundary(); // 32-bit alignment
342
343 // Figure out where the end of this blob will be including tail padding.
344 size_t CurBitPos = GetCurrentBitNo();
345 size_t NewEnd = CurBitPos+((NumElts+3)&~3)*8;
346
347 // If this would read off the end of the bitcode file, just set the
348 // record to empty and return.
349 if (!canSkipToPos(NewEnd/8)) {
350 Vals.append(NumElts, 0);
351 skipToEnd();
352 break;
353 }
354
355 // Otherwise, inform the streamer that we need these bytes in memory. Skip
356 // over tail padding first, in case jumping to NewEnd invalidates the Blob
357 // pointer.
358 if (Error Err = JumpToBit(NewEnd))
359 return std::move(Err);
360 const char *Ptr = (const char *)getPointerToBit(CurBitPos, NumElts);
361
362 // If we can return a reference to the data, do so to avoid copying it.
363 if (Blob) {
364 *Blob = StringRef(Ptr, NumElts);
365 } else {
366 // Otherwise, unpack into Vals with zero extension.
367 for (; NumElts; --NumElts)
368 Vals.push_back((unsigned char)*Ptr++);
369 }
370 }
371
372 return Code;
373}
374
375Error BitstreamCursor::ReadAbbrevRecord() {
376 auto Abbv = std::make_shared<BitCodeAbbrev>();
377 Expected<uint32_t> MaybeNumOpInfo = ReadVBR(5);
378 if (!MaybeNumOpInfo)
379 return MaybeNumOpInfo.takeError();
380 unsigned NumOpInfo = MaybeNumOpInfo.get();
381 for (unsigned i = 0; i != NumOpInfo; ++i) {
382 Expected<word_t> MaybeIsLiteral = Read(1);
383 if (!MaybeIsLiteral)
384 return MaybeIsLiteral.takeError();
385 bool IsLiteral = MaybeIsLiteral.get();
386 if (IsLiteral) {
387 Expected<uint64_t> MaybeOp = ReadVBR64(8);
388 if (!MaybeOp)
389 return MaybeOp.takeError();
390 Abbv->Add(BitCodeAbbrevOp(MaybeOp.get()));
391 continue;
392 }
393
394 Expected<word_t> MaybeEncoding = Read(3);
395 if (!MaybeEncoding)
396 return MaybeEncoding.takeError();
397 BitCodeAbbrevOp::Encoding E =
398 (BitCodeAbbrevOp::Encoding)MaybeEncoding.get();
399 if (BitCodeAbbrevOp::hasEncodingData(E)) {
400 Expected<uint64_t> MaybeData = ReadVBR64(5);
401 if (!MaybeData)
402 return MaybeData.takeError();
403 uint64_t Data = MaybeData.get();
404
405 // As a special case, handle fixed(0) (i.e., a fixed field with zero bits)
406 // and vbr(0) as a literal zero. This is decoded the same way, and avoids
407 // a slow path in Read() to have to handle reading zero bits.
408 if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
409 Data == 0) {
410 Abbv->Add(BitCodeAbbrevOp(0));
411 continue;
412 }
413
414 if ((E == BitCodeAbbrevOp::Fixed || E == BitCodeAbbrevOp::VBR) &&
415 Data > MaxChunkSize)
416 report_fatal_error(
417 "Fixed or VBR abbrev record with size > MaxChunkData");
418
419 Abbv->Add(BitCodeAbbrevOp(E, Data));
420 } else
421 Abbv->Add(BitCodeAbbrevOp(E));
422 }
423
424 if (Abbv->getNumOperandInfos() == 0)
425 report_fatal_error("Abbrev record with no operands");
426 CurAbbrevs.push_back(std::move(Abbv));
427
428 return Error::success();
429}
430
431Expected<Optional<BitstreamBlockInfo>>
432BitstreamCursor::ReadBlockInfoBlock(bool ReadBlockInfoNames) {
433 if (llvm::Error Err = EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID))
1
Assuming the condition is false
2
Taking false branch
434 return std::move(Err);
435
436 BitstreamBlockInfo NewBlockInfo;
437
438 SmallVector<uint64_t, 64> Record;
439 BitstreamBlockInfo::BlockInfo *CurBlockInfo = nullptr;
440
441 // Read all the records for this module.
442 while (true) {
3
Loop condition is true. Entering loop body
11
Loop condition is true. Entering loop body
443 Expected<BitstreamEntry> MaybeEntry =
444 advanceSkippingSubblocks(AF_DontAutoprocessAbbrevs);
12
Calling 'BitstreamCursor::advanceSkippingSubblocks'
445 if (!MaybeEntry)
4
Taking false branch
446 return MaybeEntry.takeError();
447 BitstreamEntry Entry = MaybeEntry.get();
448
449 switch (Entry.Kind) {
5
Control jumps to 'case Record:' at line 455
450 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
451 case llvm::BitstreamEntry::Error:
452 return None;
453 case llvm::BitstreamEntry::EndBlock:
454 return std::move(NewBlockInfo);
455 case llvm::BitstreamEntry::Record:
456 // The interesting case.
457 break;
6
Execution continues on line 461
458 }
459
460 // Read abbrev records, associate them with CurBID.
461 if (Entry.ID
6.1
Field 'ID' is not equal to DEFINE_ABBREV
6.1
Field 'ID' is not equal to DEFINE_ABBREV
== bitc::DEFINE_ABBREV) {
7
Taking false branch
462 if (!CurBlockInfo) return None;
463 if (Error Err = ReadAbbrevRecord())
464 return std::move(Err);
465
466 // ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
467 // appropriate BlockInfo.
468 CurBlockInfo->Abbrevs.push_back(std::move(CurAbbrevs.back()));
469 CurAbbrevs.pop_back();
470 continue;
471 }
472
473 // Read a record.
474 Record.clear();
475 Expected<unsigned> MaybeBlockInfo = readRecord(Entry.ID, Record);
476 if (!MaybeBlockInfo)
8
Taking false branch
477 return MaybeBlockInfo.takeError();
478 switch (MaybeBlockInfo.get()) {
9
Control jumps to the 'default' case at line 479
479 default:
480 break; // Default behavior, ignore unknown content.
10
Execution continues on line 516
481 case bitc::BLOCKINFO_CODE_SETBID:
482 if (Record.size() < 1)
483 return None;
484 CurBlockInfo = &NewBlockInfo.getOrCreateBlockInfo((unsigned)Record[0]);
485 break;
486 case bitc::BLOCKINFO_CODE_BLOCKNAME: {
487 if (!CurBlockInfo)
488 return None;
489 if (!ReadBlockInfoNames)
490 break; // Ignore name.
491 std::string Name;
492 for (unsigned i = 0, e = Record.size(); i != e; ++i)
493 Name += (char)Record[i];
494 CurBlockInfo->Name = Name;
495 break;
496 }
497 case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
498 if (!CurBlockInfo) return None;
499 if (!ReadBlockInfoNames)
500 break; // Ignore name.
501 std::string Name;
502 for (unsigned i = 1, e = Record.size(); i != e; ++i)
503 Name += (char)Record[i];
504 CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
505 Name));
506 break;
507 }
508 }
509 }
510}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Bitstream/BitstreamReader.h

1//===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This header defines the BitstreamReader class. This class can be used to
10// read an arbitrary bitstream, regardless of its contents.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_BITSTREAM_BITSTREAMREADER_H
15#define LLVM_BITSTREAM_BITSTREAMREADER_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/Bitstream/BitCodes.h"
20#include "llvm/Support/Endian.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/Support/MathExtras.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include <algorithm>
25#include <cassert>
26#include <climits>
27#include <cstddef>
28#include <cstdint>
29#include <memory>
30#include <string>
31#include <utility>
32#include <vector>
33
34namespace llvm {
35
36/// This class maintains the abbreviations read from a block info block.
37class BitstreamBlockInfo {
38public:
39 /// This contains information emitted to BLOCKINFO_BLOCK blocks. These
40 /// describe abbreviations that all blocks of the specified ID inherit.
41 struct BlockInfo {
42 unsigned BlockID = 0;
43 std::vector<std::shared_ptr<BitCodeAbbrev>> Abbrevs;
44 std::string Name;
45 std::vector<std::pair<unsigned, std::string>> RecordNames;
46 };
47
48private:
49 std::vector<BlockInfo> BlockInfoRecords;
50
51public:
52 /// If there is block info for the specified ID, return it, otherwise return
53 /// null.
54 const BlockInfo *getBlockInfo(unsigned BlockID) const {
55 // Common case, the most recent entry matches BlockID.
56 if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
57 return &BlockInfoRecords.back();
58
59 for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
60 i != e; ++i)
61 if (BlockInfoRecords[i].BlockID == BlockID)
62 return &BlockInfoRecords[i];
63 return nullptr;
64 }
65
66 BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
67 if (const BlockInfo *BI = getBlockInfo(BlockID))
68 return *const_cast<BlockInfo*>(BI);
69
70 // Otherwise, add a new record.
71 BlockInfoRecords.emplace_back();
72 BlockInfoRecords.back().BlockID = BlockID;
73 return BlockInfoRecords.back();
74 }
75};
76
77/// This represents a position within a bitstream. There may be multiple
78/// independent cursors reading within one bitstream, each maintaining their
79/// own local state.
80class SimpleBitstreamCursor {
81 ArrayRef<uint8_t> BitcodeBytes;
82 size_t NextChar = 0;
83
84public:
85 /// This is the current data we have pulled from the stream but have not
86 /// returned to the client. This is specifically and intentionally defined to
87 /// follow the word size of the host machine for efficiency. We use word_t in
88 /// places that are aware of this to make it perfectly explicit what is going
89 /// on.
90 using word_t = size_t;
91
92private:
93 word_t CurWord = 0;
94
95 /// This is the number of bits in CurWord that are valid. This is always from
96 /// [0...bits_of(size_t)-1] inclusive.
97 unsigned BitsInCurWord = 0;
98
99public:
100 static const constexpr size_t MaxChunkSize = sizeof(word_t) * 8;
101
102 SimpleBitstreamCursor() = default;
103 explicit SimpleBitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
104 : BitcodeBytes(BitcodeBytes) {}
105 explicit SimpleBitstreamCursor(StringRef BitcodeBytes)
106 : BitcodeBytes(arrayRefFromStringRef(BitcodeBytes)) {}
107 explicit SimpleBitstreamCursor(MemoryBufferRef BitcodeBytes)
108 : SimpleBitstreamCursor(BitcodeBytes.getBuffer()) {}
109
110 bool canSkipToPos(size_t pos) const {
111 // pos can be skipped to if it is a valid address or one byte past the end.
112 return pos <= BitcodeBytes.size();
113 }
114
115 bool AtEndOfStream() {
116 return BitsInCurWord == 0 && BitcodeBytes.size() <= NextChar;
117 }
118
119 /// Return the bit # of the bit we are reading.
120 uint64_t GetCurrentBitNo() const {
121 return NextChar*CHAR_BIT8 - BitsInCurWord;
122 }
123
124 // Return the byte # of the current bit.
125 uint64_t getCurrentByteNo() const { return GetCurrentBitNo() / 8; }
126
127 ArrayRef<uint8_t> getBitcodeBytes() const { return BitcodeBytes; }
128
129 /// Reset the stream to the specified bit number.
130 Error JumpToBit(uint64_t BitNo) {
131 size_t ByteNo = size_t(BitNo/8) & ~(sizeof(word_t)-1);
132 unsigned WordBitNo = unsigned(BitNo & (sizeof(word_t)*8-1));
133 assert(canSkipToPos(ByteNo) && "Invalid location")((canSkipToPos(ByteNo) && "Invalid location") ? static_cast
<void> (0) : __assert_fail ("canSkipToPos(ByteNo) && \"Invalid location\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Bitstream/BitstreamReader.h"
, 133, __PRETTY_FUNCTION__))
;
134
135 // Move the cursor to the right word.
136 NextChar = ByteNo;
137 BitsInCurWord = 0;
138
139 // Skip over any bits that are already consumed.
140 if (WordBitNo) {
141 if (Expected<word_t> Res = Read(WordBitNo))
142 return Error::success();
143 else
144 return Res.takeError();
145 }
146
147 return Error::success();
148 }
149
150 /// Get a pointer into the bitstream at the specified byte offset.
151 const uint8_t *getPointerToByte(uint64_t ByteNo, uint64_t NumBytes) {
152 return BitcodeBytes.data() + ByteNo;
153 }
154
155 /// Get a pointer into the bitstream at the specified bit offset.
156 ///
157 /// The bit offset must be on a byte boundary.
158 const uint8_t *getPointerToBit(uint64_t BitNo, uint64_t NumBytes) {
159 assert(!(BitNo % 8) && "Expected bit on byte boundary")((!(BitNo % 8) && "Expected bit on byte boundary") ? static_cast
<void> (0) : __assert_fail ("!(BitNo % 8) && \"Expected bit on byte boundary\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Bitstream/BitstreamReader.h"
, 159, __PRETTY_FUNCTION__))
;
160 return getPointerToByte(BitNo / 8, NumBytes);
161 }
162
163 Error fillCurWord() {
164 if (NextChar >= BitcodeBytes.size())
165 return createStringError(std::errc::io_error,
166 "Unexpected end of file reading %u of %u bytes",
167 NextChar, BitcodeBytes.size());
168
169 // Read the next word from the stream.
170 const uint8_t *NextCharPtr = BitcodeBytes.data() + NextChar;
171 unsigned BytesRead;
172 if (BitcodeBytes.size() >= NextChar + sizeof(word_t)) {
173 BytesRead = sizeof(word_t);
174 CurWord =
175 support::endian::read<word_t, support::little, support::unaligned>(
176 NextCharPtr);
177 } else {
178 // Short read.
179 BytesRead = BitcodeBytes.size() - NextChar;
180 CurWord = 0;
181 for (unsigned B = 0; B != BytesRead; ++B)
182 CurWord |= uint64_t(NextCharPtr[B]) << (B * 8);
183 }
184 NextChar += BytesRead;
185 BitsInCurWord = BytesRead * 8;
186 return Error::success();
187 }
188
189 Expected<word_t> Read(unsigned NumBits) {
190 static const unsigned BitsInWord = MaxChunkSize;
191
192 assert(NumBits && NumBits <= BitsInWord &&((NumBits && NumBits <= BitsInWord && "Cannot return zero or more than BitsInWord bits!"
) ? static_cast<void> (0) : __assert_fail ("NumBits && NumBits <= BitsInWord && \"Cannot return zero or more than BitsInWord bits!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Bitstream/BitstreamReader.h"
, 193, __PRETTY_FUNCTION__))
19
Assuming 'NumBits' is not equal to 0
20
Assuming 'NumBits' is <= 'BitsInWord'
21
'?' condition is true
193 "Cannot return zero or more than BitsInWord bits!")((NumBits && NumBits <= BitsInWord && "Cannot return zero or more than BitsInWord bits!"
) ? static_cast<void> (0) : __assert_fail ("NumBits && NumBits <= BitsInWord && \"Cannot return zero or more than BitsInWord bits!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/Bitstream/BitstreamReader.h"
, 193, __PRETTY_FUNCTION__))
;
194
195 static const unsigned Mask = sizeof(word_t) > 4 ? 0x3f : 0x1f;
196
197 // If the field is fully contained by CurWord, return it quickly.
198 if (BitsInCurWord >= NumBits) {
22
Assuming 'NumBits' is > field 'BitsInCurWord'
23
Taking false branch
199 word_t R = CurWord & (~word_t(0) >> (BitsInWord - NumBits));
200
201 // Use a mask to avoid undefined behavior.
202 CurWord >>= (NumBits & Mask);
203
204 BitsInCurWord -= NumBits;
205 return R;
206 }
207
208 word_t R = BitsInCurWord
23.1
Field 'BitsInCurWord' is not equal to 0
23.1
Field 'BitsInCurWord' is not equal to 0
? CurWord : 0;
24
'?' condition is true
209 unsigned BitsLeft = NumBits - BitsInCurWord;
210
211 if (Error fillResult = fillCurWord())
25
Assuming the condition is false
26
Taking false branch
212 return std::move(fillResult);
213
214 // If we run out of data, abort.
215 if (BitsLeft > BitsInCurWord)
27
Assuming 'BitsLeft' is <= field 'BitsInCurWord'
28
Taking false branch
216 return createStringError(std::errc::io_error,
217 "Unexpected end of file reading %u of %u bits",
218 BitsInCurWord, BitsLeft);
219
220 word_t R2 = CurWord & (~word_t(0) >> (BitsInWord - BitsLeft));
29
The result of the right shift is undefined due to shifting by '64', which is greater or equal to the width of type 'llvm::SimpleBitstreamCursor::word_t'
221
222 // Use a mask to avoid undefined behavior.
223 CurWord >>= (BitsLeft & Mask);
224
225 BitsInCurWord -= BitsLeft;
226
227 R |= R2 << (NumBits - BitsLeft);
228
229 return R;
230 }
231
232 Expected<uint32_t> ReadVBR(unsigned NumBits) {
233 Expected<unsigned> MaybeRead = Read(NumBits);
234 if (!MaybeRead)
235 return MaybeRead;
236 uint32_t Piece = MaybeRead.get();
237
238 if ((Piece & (1U << (NumBits-1))) == 0)
239 return Piece;
240
241 uint32_t Result = 0;
242 unsigned NextBit = 0;
243 while (true) {
244 Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
245
246 if ((Piece & (1U << (NumBits-1))) == 0)
247 return Result;
248
249 NextBit += NumBits-1;
250 MaybeRead = Read(NumBits);
251 if (!MaybeRead)
252 return MaybeRead;
253 Piece = MaybeRead.get();
254 }
255 }
256
257 // Read a VBR that may have a value up to 64-bits in size. The chunk size of
258 // the VBR must still be <= 32 bits though.
259 Expected<uint64_t> ReadVBR64(unsigned NumBits) {
260 Expected<uint64_t> MaybeRead = Read(NumBits);
261 if (!MaybeRead)
262 return MaybeRead;
263 uint32_t Piece = MaybeRead.get();
264
265 if ((Piece & (1U << (NumBits-1))) == 0)
266 return uint64_t(Piece);
267
268 uint64_t Result = 0;
269 unsigned NextBit = 0;
270 while (true) {
271 Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
272
273 if ((Piece & (1U << (NumBits-1))) == 0)
274 return Result;
275
276 NextBit += NumBits-1;
277 MaybeRead = Read(NumBits);
278 if (!MaybeRead)
279 return MaybeRead;
280 Piece = MaybeRead.get();
281 }
282 }
283
284 void SkipToFourByteBoundary() {
285 // If word_t is 64-bits and if we've read less than 32 bits, just dump
286 // the bits we have up to the next 32-bit boundary.
287 if (sizeof(word_t) > 4 &&
288 BitsInCurWord >= 32) {
289 CurWord >>= BitsInCurWord-32;
290 BitsInCurWord = 32;
291 return;
292 }
293
294 BitsInCurWord = 0;
295 }
296
297 /// Return the size of the stream in bytes.
298 size_t SizeInBytes() const { return BitcodeBytes.size(); }
299
300 /// Skip to the end of the file.
301 void skipToEnd() { NextChar = BitcodeBytes.size(); }
302};
303
304/// When advancing through a bitstream cursor, each advance can discover a few
305/// different kinds of entries:
306struct BitstreamEntry {
307 enum {
308 Error, // Malformed bitcode was found.
309 EndBlock, // We've reached the end of the current block, (or the end of the
310 // file, which is treated like a series of EndBlock records.
311 SubBlock, // This is the start of a new subblock of a specific ID.
312 Record // This is a record with a specific AbbrevID.
313 } Kind;
314
315 unsigned ID;
316
317 static BitstreamEntry getError() {
318 BitstreamEntry E; E.Kind = Error; return E;
319 }
320
321 static BitstreamEntry getEndBlock() {
322 BitstreamEntry E; E.Kind = EndBlock; return E;
323 }
324
325 static BitstreamEntry getSubBlock(unsigned ID) {
326 BitstreamEntry E; E.Kind = SubBlock; E.ID = ID; return E;
327 }
328
329 static BitstreamEntry getRecord(unsigned AbbrevID) {
330 BitstreamEntry E; E.Kind = Record; E.ID = AbbrevID; return E;
331 }
332};
333
334/// This represents a position within a bitcode file, implemented on top of a
335/// SimpleBitstreamCursor.
336///
337/// Unlike iterators, BitstreamCursors are heavy-weight objects that should not
338/// be passed by value.
339class BitstreamCursor : SimpleBitstreamCursor {
340 // This is the declared size of code values used for the current block, in
341 // bits.
342 unsigned CurCodeSize = 2;
343
344 /// Abbrevs installed at in this block.
345 std::vector<std::shared_ptr<BitCodeAbbrev>> CurAbbrevs;
346
347 struct Block {
348 unsigned PrevCodeSize;
349 std::vector<std::shared_ptr<BitCodeAbbrev>> PrevAbbrevs;
350
351 explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
352 };
353
354 /// This tracks the codesize of parent blocks.
355 SmallVector<Block, 8> BlockScope;
356
357 BitstreamBlockInfo *BlockInfo = nullptr;
358
359public:
360 static const size_t MaxChunkSize = sizeof(word_t) * 8;
361
362 BitstreamCursor() = default;
363 explicit BitstreamCursor(ArrayRef<uint8_t> BitcodeBytes)
364 : SimpleBitstreamCursor(BitcodeBytes) {}
365 explicit BitstreamCursor(StringRef BitcodeBytes)
366 : SimpleBitstreamCursor(BitcodeBytes) {}
367 explicit BitstreamCursor(MemoryBufferRef BitcodeBytes)
368 : SimpleBitstreamCursor(BitcodeBytes) {}
369
370 using SimpleBitstreamCursor::AtEndOfStream;
371 using SimpleBitstreamCursor::canSkipToPos;
372 using SimpleBitstreamCursor::fillCurWord;
373 using SimpleBitstreamCursor::getBitcodeBytes;
374 using SimpleBitstreamCursor::GetCurrentBitNo;
375 using SimpleBitstreamCursor::getCurrentByteNo;
376 using SimpleBitstreamCursor::getPointerToByte;
377 using SimpleBitstreamCursor::JumpToBit;
378 using SimpleBitstreamCursor::Read;
379 using SimpleBitstreamCursor::ReadVBR;
380 using SimpleBitstreamCursor::ReadVBR64;
381 using SimpleBitstreamCursor::SizeInBytes;
382 using SimpleBitstreamCursor::skipToEnd;
383
384 /// Return the number of bits used to encode an abbrev #.
385 unsigned getAbbrevIDWidth() const { return CurCodeSize; }
386
387 /// Flags that modify the behavior of advance().
388 enum {
389 /// If this flag is used, the advance() method does not automatically pop
390 /// the block scope when the end of a block is reached.
391 AF_DontPopBlockAtEnd = 1,
392
393 /// If this flag is used, abbrev entries are returned just like normal
394 /// records.
395 AF_DontAutoprocessAbbrevs = 2
396 };
397
398 /// Advance the current bitstream, returning the next entry in the stream.
399 Expected<BitstreamEntry> advance(unsigned Flags = 0) {
400 while (true) {
15
Loop condition is true. Entering loop body
401 if (AtEndOfStream())
16
Taking false branch
402 return BitstreamEntry::getError();
403
404 Expected<unsigned> MaybeCode = ReadCode();
17
Calling 'BitstreamCursor::ReadCode'
405 if (!MaybeCode)
406 return MaybeCode.takeError();
407 unsigned Code = MaybeCode.get();
408
409 if (Code == bitc::END_BLOCK) {
410 // Pop the end of the block unless Flags tells us not to.
411 if (!(Flags & AF_DontPopBlockAtEnd) && ReadBlockEnd())
412 return BitstreamEntry::getError();
413 return BitstreamEntry::getEndBlock();
414 }
415
416 if (Code == bitc::ENTER_SUBBLOCK) {
417 if (Expected<unsigned> MaybeSubBlock = ReadSubBlockID())
418 return BitstreamEntry::getSubBlock(MaybeSubBlock.get());
419 else
420 return MaybeSubBlock.takeError();
421 }
422
423 if (Code == bitc::DEFINE_ABBREV &&
424 !(Flags & AF_DontAutoprocessAbbrevs)) {
425 // We read and accumulate abbrev's, the client can't do anything with
426 // them anyway.
427 if (Error Err = ReadAbbrevRecord())
428 return std::move(Err);
429 continue;
430 }
431
432 return BitstreamEntry::getRecord(Code);
433 }
434 }
435
436 /// This is a convenience function for clients that don't expect any
437 /// subblocks. This just skips over them automatically.
438 Expected<BitstreamEntry> advanceSkippingSubblocks(unsigned Flags = 0) {
439 while (true) {
13
Loop condition is true. Entering loop body
440 // If we found a normal entry, return it.
441 Expected<BitstreamEntry> MaybeEntry = advance(Flags);
14
Calling 'BitstreamCursor::advance'
442 if (!MaybeEntry)
443 return MaybeEntry;
444 BitstreamEntry Entry = MaybeEntry.get();
445
446 if (Entry.Kind != BitstreamEntry::SubBlock)
447 return Entry;
448
449 // If we found a sub-block, just skip over it and check the next entry.
450 if (Error Err = SkipBlock())
451 return std::move(Err);
452 }
453 }
454
455 Expected<unsigned> ReadCode() { return Read(CurCodeSize); }
18
Calling 'SimpleBitstreamCursor::Read'
456
457 // Block header:
458 // [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
459
460 /// Having read the ENTER_SUBBLOCK code, read the BlockID for the block.
461 Expected<unsigned> ReadSubBlockID() { return ReadVBR(bitc::BlockIDWidth); }
462
463 /// Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body
464 /// of this block.
465 Error SkipBlock() {
466 // Read and ignore the codelen value.
467 if (Expected<uint32_t> Res = ReadVBR(bitc::CodeLenWidth))
468 ; // Since we are skipping this block, we don't care what code widths are
469 // used inside of it.
470 else
471 return Res.takeError();
472
473 SkipToFourByteBoundary();
474 Expected<unsigned> MaybeNum = Read(bitc::BlockSizeWidth);
475 if (!MaybeNum)
476 return MaybeNum.takeError();
477 size_t NumFourBytes = MaybeNum.get();
478
479 // Check that the block wasn't partially defined, and that the offset isn't
480 // bogus.
481 size_t SkipTo = GetCurrentBitNo() + NumFourBytes * 4 * 8;
482 if (AtEndOfStream())
483 return createStringError(std::errc::illegal_byte_sequence,
484 "can't skip block: already at end of stream");
485 if (!canSkipToPos(SkipTo / 8))
486 return createStringError(std::errc::illegal_byte_sequence,
487 "can't skip to bit %zu from %" PRIu64"l" "u", SkipTo,
488 GetCurrentBitNo());
489
490 if (Error Res = JumpToBit(SkipTo))
491 return Res;
492
493 return Error::success();
494 }
495
496 /// Having read the ENTER_SUBBLOCK abbrevid, and enter the block.
497 Error EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = nullptr);
498
499 bool ReadBlockEnd() {
500 if (BlockScope.empty()) return true;
501
502 // Block tail:
503 // [END_BLOCK, <align4bytes>]
504 SkipToFourByteBoundary();
505
506 popBlockScope();
507 return false;
508 }
509
510private:
511 void popBlockScope() {
512 CurCodeSize = BlockScope.back().PrevCodeSize;
513
514 CurAbbrevs = std::move(BlockScope.back().PrevAbbrevs);
515 BlockScope.pop_back();
516 }
517
518 //===--------------------------------------------------------------------===//
519 // Record Processing
520 //===--------------------------------------------------------------------===//
521
522public:
523 /// Return the abbreviation for the specified AbbrevId.
524 const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
525 unsigned AbbrevNo = AbbrevID - bitc::FIRST_APPLICATION_ABBREV;
526 if (AbbrevNo >= CurAbbrevs.size())
527 report_fatal_error("Invalid abbrev number");
528 return CurAbbrevs[AbbrevNo].get();
529 }
530
531 /// Read the current record and discard it, returning the code for the record.
532 Expected<unsigned> skipRecord(unsigned AbbrevID);
533
534 Expected<unsigned> readRecord(unsigned AbbrevID,
535 SmallVectorImpl<uint64_t> &Vals,
536 StringRef *Blob = nullptr);
537
538 //===--------------------------------------------------------------------===//
539 // Abbrev Processing
540 //===--------------------------------------------------------------------===//
541 Error ReadAbbrevRecord();
542
543 /// Read and return a block info block from the bitstream. If an error was
544 /// encountered, return None.
545 ///
546 /// \param ReadBlockInfoNames Whether to read block/record name information in
547 /// the BlockInfo block. Only llvm-bcanalyzer uses this.
548 Expected<Optional<BitstreamBlockInfo>>
549 ReadBlockInfoBlock(bool ReadBlockInfoNames = false);
550
551 /// Set the block info to be used by this BitstreamCursor to interpret
552 /// abbreviated records.
553 void setBlockInfo(BitstreamBlockInfo *BI) { BlockInfo = BI; }
554};
555
556} // end llvm namespace
557
558#endif // LLVM_BITSTREAM_BITSTREAMREADER_H