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