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