Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(26)

Side by Side Diff: src/PNaClTranslator.cpp

Issue 361733002: Update Subzero to start parsing PNaCl bitcode files. (Closed) Base URL: https://chromium.googlesource.com/native_client/pnacl-subzero.git@master
Patch Set: Fix more nits. Created 6 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 //===- subzero/src/PNaClTranslator.cpp - Builds ICE from PNaCl bitcode ----===//
2 //
3 // The Subzero Code Generator
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PNaCl bitcode file to Ice translator.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PNaClTranslator.h"
15 #include "llvm/Bitcode/NaCl/NaClBitcodeDecoders.h"
16 #include "llvm/Bitcode/NaCl/NaClBitcodeHeader.h"
17 #include "llvm/Bitcode/NaCl/NaClBitcodeParser.h"
18 #include "llvm/Bitcode/NaCl/NaClReaderWriter.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/ValueHandle.h"
26
27 #include <vector>
28 #include <cassert>
29
30 using namespace llvm;
31
32 namespace {
33
34 // Top-level class to read PNaCl bitcode files, and translate to ICE.
35 class TopLevelParser : public NaClBitcodeParser {
36 TopLevelParser(const TopLevelParser&) LLVM_DELETED_FUNCTION;
37 void operator=(const TopLevelParser&) LLVM_DELETED_FUNCTION;
jvoung (off chromium) 2014/07/01 17:32:52 I think for Subzero, Jim has been using: T &opera
Karl 2014/07/01 21:31:07 Done.
38
39 public:
40 TopLevelParser(Module *Mod,
jvoung (off chromium) 2014/07/01 17:32:52 It would be good to clarify what state the incomin
Karl 2014/07/01 21:31:07 I hadn't really worried about this because these c
41 NaClBitcodeHeader &Header,
42 NaClBitstreamCursor &Cursor)
43 : NaClBitcodeParser(Cursor),
44 Mod(Mod),
45 Header(Header),
46 NumErrors(),
jvoung (off chromium) 2014/07/01 17:32:53 initialize to 0?
Karl 2014/07/01 21:31:06 Definitely!
jvoung (off chromium) 2014/07/02 17:00:15 Okay, using () does initialize to zero, but it see
Karl 2014/07/02 18:09:54 Adding zero to be more clear.
47 NumFunctionIds(0),
48 GlobalVarPlaceHolderType(0) {}
49
50 virtual ~TopLevelParser() {} LLVM_OVERRIDE;
51
52 virtual bool Error(const std::string &Message) LLVM_OVERRIDE {
53 ++NumErrors;
54 return NaClBitcodeParser::Error(Message);
55 }
56
57 /// Returns the number of errors found while parsing the bitcode
58 /// file.
59 unsigned getNumErrors() const {
60 return NumErrors;
61 }
62
63 /// Returns the LLVM module associated with the translation.
64 Module *getModule() {
65 return Mod;
66 }
67
68 /// Returns the number of bytes in the bitcode header.
69 size_t getHeaderSize() {
jvoung (off chromium) 2014/07/01 17:32:53 Some of these other methods are const too?
Karl 2014/07/01 21:31:06 Done.
70 return Header.getHeaderSize();
71 }
72
73 /// Returns the llvm context to use.
74 LLVMContext &getLLVMContext() {
75 return Mod->getContext();
76 }
77
78 /// Changes the size of the type list to the given size.
79 void resizeTypeIDValues(unsigned NewSize) {
80 TypeIDValues.resize(NewSize);
81 }
82
83 /// Returns the type associated with the given index.
84 Type *getTypeByID(unsigned ID) {
85 Type *Ty = ID < TypeIDValues.size() ? TypeIDValues[ID] : 0;
jvoung (off chromium) 2014/07/01 17:32:53 Clarify that the array could really end up storing
Karl 2014/07/01 21:31:08 Done.
86 if (Ty) return Ty;
87 return reportTypeIDAsUndefined(ID);
88 }
89
90 /// Defines type for ID.
91 void setTypeID(unsigned ID, Type *Ty) {
92 if (ID < TypeIDValues.size() && TypeIDValues[ID] == 0) {
93 TypeIDValues[ID] = Ty;
94 return;
95 }
96 reportBadSetTypeID(ID, Ty);
97 }
98
99 /// Sets the next function ID to the given LLVM function.
100 void setNextFunctionID(Function *Fcn) {
101 ++NumFunctionIds;
102 ValueIDValues.push_back(Fcn);
103 }
104
105 /// Defines the next function ID as one that has an implementation
106 /// (i.e a corresponding function block in the bitcode).
107 void setNextValueIDAsImplementedFunction() {
108 DefiningFunctionsList.push_back(ValueIDValues.size());
109 }
110
111 /// Returns the LLVM IR value associatd with the global value ID.
112 Value *getGlobalValueByID(unsigned ID) {
113 if (ID >= ValueIDValues.size()) return 0;
114 return ValueIDValues[ID];
115 }
116
117 /// Returns the number of function addresses (i.e. ID's) defined in
118 /// the bitcode file.
119 unsigned getNumFunctionIDs() {
jvoung (off chromium) 2014/07/01 17:32:52 const
Karl 2014/07/01 21:31:08 Done.
120 return NumFunctionIds;
121 }
122
123 /// Returns the number of global values defined in the bitcode
124 /// file.
125 unsigned getNumGlobalValueIDs() {
126 return ValueIDValues.size();
127 }
128
129 /// Resizes the list of of value IDs to include Count global
130 /// variable IDs.
131 void resizeValueIDsForGlobalVarCount(unsigned Count) {
132 ValueIDValues.resize(ValueIDValues.size() + Count);
133 }
134
135 /// Returns the global variable address associated with the given
136 /// value ID. If the ID refers to a global variable address not yet
137 /// defined, a placeholder is created so that we can fix it up
138 /// later.
139 Constant *getOrCreateGlobalVarRef(unsigned ID) {
140 if (ID >= ValueIDValues.size()) return 0;
141 if (Value *C = ValueIDValues[ID])
142 return dyn_cast<Constant>(C);
143
144 if (GlobalVarPlaceHolderType == 0)
jvoung (off chromium) 2014/07/01 17:32:53 Why not just eagerly initialize it in the class's
Karl 2014/07/01 21:31:06 Done.
145 GlobalVarPlaceHolderType = Type::getInt8Ty(getLLVMContext());
146 Constant *C =
147 new GlobalVariable(*Mod, GlobalVarPlaceHolderType, false,
148 GlobalValue::ExternalLinkage, 0);
149 ValueIDValues[ID] = C;
150 return C;
151 }
152
153 /// Assigns the given global variable (address) to the given value
154 /// ID. Returns true if ID is a valid global variable ID. Otherwise
155 /// returns false.
156 bool assignGlobalVariable(GlobalVariable *GV, unsigned ID) {
157 if (ID < NumFunctionIds || ID >= ValueIDValues.size()) return false;
158 WeakVH &OldV = ValueIDValues[ID];
159 if (OldV == 0) {
160 ValueIDValues[ID] = GV;
161 return true;
162 }
163
164 // If reached, there was a forward reference to this value. Replace it.
165 Value *PrevVal = OldV;
166 GlobalVariable *Placeholder = cast<GlobalVariable>(PrevVal);
167 Placeholder->replaceAllUsesWith(
168 ConstantExpr::getBitCast(GV, Placeholder->getType()));
169 Placeholder->eraseFromParent();
170 ValueIDValues[ID] = GV;
171 return true;
172 }
173
174 private:
175 // The parsed module.
176 Module *Mod;
177 // The bitcode header.
178 NaClBitcodeHeader &Header;
179 // The number of errors reported.
180 unsigned NumErrors;
181 // The types associated with each type ID.
182 std::vector<Type*> TypeIDValues;
183 // The (global) value IDs.
184 std::vector<WeakVH> ValueIDValues;
185 // The number of function IDs.
186 unsigned NumFunctionIds;
187 // The list of value IDs (in the order found) of defining function
188 // addresses.
189 std::vector<unsigned> DefiningFunctionsList;
190 // Cached global variable placeholder type. Used for all forward
191 // references to global variable addresses.
192 Type *GlobalVarPlaceHolderType;
193
194 virtual bool ParseBlock(unsigned BlockID) LLVM_OVERRIDE;
195
196 /// Reports that type ID is undefined, and then returns
197 /// the void type.
198 Type *reportTypeIDAsUndefined(unsigned ID);
199
200 /// Reports error about bad call to setTypeID.
201 void reportBadSetTypeID(unsigned ID, Type *Ty);
202 };
203
204 Type *TopLevelParser::reportTypeIDAsUndefined(unsigned ID) {
205 std::string Buffer;
206 raw_string_ostream StrBuf(Buffer);
jvoung (off chromium) 2014/07/01 17:32:52 This probably doesn't count as "Subzero core" sinc
Karl 2014/07/01 21:31:06 First off, Jim's comment about not using it is inc
207 StrBuf << "Can't find type for type id: " << ID;
208 Error(StrBuf.str());
209 Type *Ty = Type::getVoidTy(getLLVMContext());
210 // To reduce error messages, update type list if possible.
211 if (ID < TypeIDValues.size()) TypeIDValues[ID] = Ty;
212 return Ty;
213 }
214
215 void TopLevelParser::reportBadSetTypeID(unsigned ID, Type *Ty) {
216 std::string Buffer;
217 raw_string_ostream StrBuf(Buffer);
218 if (ID >= TypeIDValues.size()) {
219 StrBuf << "Type index " << ID << " out of range: can't install.";
220 } else {
221 // Must be case that index already defined.
222 StrBuf << "Type index " << ID << " defined as " << *TypeIDValues[ID]
223 << " and " << *Ty << ".";
224 }
225 Error(StrBuf.str());
226 }
227
228 // class for parsing blocks within the TopLevelParser.
229 class BlockParser : public NaClBitcodeParser {
230 protected:
231
232 // Constructor for nested block parsers.
233 BlockParser(unsigned BlockID, BlockParser *EnclosingParser)
234 : NaClBitcodeParser(BlockID, EnclosingParser),
235 Context(EnclosingParser->Context) {}
236
237 // Returns a string describing the bit address of the current record
238 // being processed by the block parser.
239 std::string getRecordAddress() const {
jvoung (off chromium) 2014/07/01 17:32:52 could inline this into Error(), then you don't nee
Karl 2014/07/01 21:31:06 Ok. the other uses I had for it has since been rem
240 uint64_t Bit = Record.GetStartBit() + Context->getHeaderSize() * 8;
241 std::string Buffer;
242 raw_string_ostream StrBuf(Buffer);
243 StrBuf << format("%"PRIu64":%u",
244 (Bit / 8),
245 static_cast<unsigned>(Bit % 8));
246 return StrBuf.str();
247 }
248
249 virtual bool Error(const std::string &Message) LLVM_OVERRIDE {
250 std::string Buffer;
251 raw_string_ostream StrBuf(Buffer);
252 StrBuf << "(" << getRecordAddress() << ") " << Message;
253 return Context->Error(StrBuf.str());
254 }
255
256 public:
257 // Constructor for the top-level module block parser.
258 BlockParser(unsigned BlockID, TopLevelParser *Context)
jvoung (off chromium) 2014/07/01 17:32:52 Why not make this first, before the nested block c
Karl 2014/07/01 21:31:07 Done.
259 : NaClBitcodeParser(BlockID, Context),
260 Context(Context) {}
261
262 virtual ~BlockParser() LLVM_OVERRIDE {}
263
264 protected:
265 // Default implementation. Reports that block is unknown and skips
266 // its contents.
267 virtual bool ParseBlock(unsigned BlockID) LLVM_OVERRIDE;
268
269 // Default implementation. Reports that the record is not
270 // understood.
271 virtual void ProcessRecord() LLVM_OVERRIDE;
272
273 // The context parser that contains the decoded state.
jvoung (off chromium) 2014/07/01 17:32:53 Can we collect the fields in one place, and the me
Karl 2014/07/01 21:31:06 Done.
274 TopLevelParser *Context;
275
276 /// Checks if the size of the record is Size. If not, an error is
277 /// produced using the given RecordName. Return true if error was
278 /// reported. Otherwise false.
jvoung (off chromium) 2014/07/01 17:32:53 I feel like some of these comments about the error
Karl 2014/07/01 21:31:08 Done.
279 bool checkRecordSize(unsigned Size, const char *RecordName) {
280 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
281 if (Values.size() != Size) {
282 return RecordSizeError(Size, RecordName, 0);
283 }
284 return false;
285 }
286
287 /// Checks if the size of the record is at least as large as the
288 /// LowerLimit. If not, an error is produced using the given
289 /// RecordName. Return true if error was reported. Otherwise false.
290 bool checkRecordSizeAtLeast(unsigned LowerLimit, const char *RecordName) {
291 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
292 if (Values.size() < LowerLimit) {
293 return RecordSizeError(LowerLimit, RecordName, "at least");
294 }
295 return false;
296 }
297
298 /// Checks if the size of the record is no larger than the
299 /// UpperLimit. If not, an error is produced using the given
300 /// RecordName. Return true if error was reported. Otherwise false.
301 bool checkRecordSizeNoMoreThan(unsigned UpperLimit, const char *RecordName) {
302 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
303 if (Values.size() > UpperLimit) {
304 return RecordSizeError(UpperLimit, RecordName, "no more than");
305 }
306 return false;
307 }
308
309 /// Checks if the size of the record is at least as large as the
310 /// LowerLimit, and no larger than the UpperLimit. If not, an error
311 /// is produced using the given RecordName. Return true if error was
312 /// reported. Otherwise false.
313 bool checkRecordSizeInRange(unsigned LowerLimit, unsigned UpperLimit,
314 const char *RecordName) {
315 return checkRecordSizeAtLeast(LowerLimit, RecordName)
316 || checkRecordSizeNoMoreThan(UpperLimit, RecordName);
317 }
318
319 private:
320 /// Generates a record size error. ExpectedSize is the number
321 /// of elements expected. RecordName is the name of the kind of
322 /// record that has incorrect size. ContextMessage (if not 0)
323 /// is appended to "record expects" to describe how ExpectedSize
324 /// should be interpreted.
325 bool RecordSizeError(unsigned ExpectedSize,
326 const char *RecordName,
327 const char *ContextMessage) {
328 std::string Buffer;
329 raw_string_ostream StrBuf(Buffer);
330 StrBuf << RecordName << " record expects";
331 if (ContextMessage) StrBuf << " " << ContextMessage;
332 StrBuf << " " << ExpectedSize << " argument";
333 if(ExpectedSize > 1) StrBuf << "s";
334 StrBuf << ". Found: " << Record.GetValues().size();
335 return Error(StrBuf.str());
336 }
337 };
338
339 bool BlockParser::ParseBlock(unsigned BlockID) {
jvoung (off chromium) 2014/07/01 17:32:53 I wonder if this class should be called something
Karl 2014/07/01 21:31:07 Done.
340 // If called, derived class doesn't know how to handle block.
341 // Report error and skip.
342 std::string Buffer;
343 raw_string_ostream StrBuf(Buffer);
344 StrBuf << "Don't know how to parse block id: " << BlockID;
345 Error(StrBuf.str());
346 SkipBlock();
347 return false;
348 }
349
350 void BlockParser::ProcessRecord() {
351 // If called, derived class doesn't know how to handle.
352 std::string Buffer;
353 raw_string_ostream StrBuf(Buffer);
354 StrBuf << "Don't know how to process record: " << Record;
355 Error(StrBuf.str());
356 }
357
358 // Class to parse a types block.
359 class TypesParser : public BlockParser {
360 public:
361 TypesParser(unsigned BlockID, BlockParser *EnclosingParser)
362 : BlockParser(BlockID, EnclosingParser), NextTypeId(0) {}
363
364 ~TypesParser() LLVM_OVERRIDE {}
365
366 protected:
367 virtual void ProcessRecord() LLVM_OVERRIDE;
368 // The type ID that will be associated with the next type defining
369 // record in the types block.
370 unsigned NextTypeId;
371 };
372
373 void TypesParser::ProcessRecord() {
374 Type *Ty = 0;
375 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
376 switch (Record.GetCode()) {
377 case naclbitc::TYPE_CODE_NUMENTRY:
378 // NUMENTRY: [numentries]
379 if (checkRecordSize(1, "Type count")) return;
380 Context->resizeTypeIDValues(Values[0]);
381 return;
382 case naclbitc::TYPE_CODE_VOID:
383 // VOID
384 if (checkRecordSize(0, "Type void")) break;
385 Ty = Type::getVoidTy(Context->getLLVMContext());
386 break;
387 case naclbitc::TYPE_CODE_FLOAT:
388 // FLOAT
389 if (checkRecordSize(0, "Type float")) break;
390 Ty = Type::getFloatTy(Context->getLLVMContext());
391 break;
392 case naclbitc::TYPE_CODE_DOUBLE:
393 // DOUBLE
394 if (checkRecordSize(0, "Type double")) break;
395 Ty = Type::getDoubleTy(Context->getLLVMContext());
396 break;
397 case naclbitc::TYPE_CODE_INTEGER:
398 // INTEGER: [width]
399 if (checkRecordSize(1, "Type integer")) break;
400 Ty = IntegerType::get(Context->getLLVMContext(), Values[0]);
401 // TODO(kschimpf) Check if size is legal.
402 break;
403 case naclbitc::TYPE_CODE_VECTOR:
404 // VECTOR: [numelts, eltty]
405 if (checkRecordSize(2, "Type vector")) break;
406 Ty = VectorType::get(Context->getTypeByID(Values[1]), Values[0]);
407 break;
408 case naclbitc::TYPE_CODE_FUNCTION: {
409 // FUNCTION: [vararg, retty, paramty x N]
410 if (checkRecordSizeAtLeast(2, "Type signature")) break;
411 SmallVector<Type *, 8> ArgTys;
412 for (unsigned i = 2, e = Values.size(); i != e; ++i) {
413 ArgTys.push_back(Context->getTypeByID(Values[i]));
414 }
415 Ty = FunctionType::get(Context->getTypeByID(Values[1]),
416 ArgTys, Values[0]);
417 break;
418 }
419 default:
420 BlockParser::ProcessRecord();
421 break;
422 }
423 // If Ty not defined, assume error. Use void as filler.
424 if (Ty == 0)
425 Ty = Type::getVoidTy(Context->getLLVMContext());
426 Context->setTypeID(NextTypeId++, Ty);
427 }
428
429 /// Parses the globals block (i.e. global variables).
430 class GlobalsParser : public BlockParser {
431 public:
432 GlobalsParser(unsigned BlockID, BlockParser *EnclosingParser)
433 : BlockParser(BlockID, EnclosingParser),
434 InitializersNeeded(0),
435 Alignment(1),
436 IsConstant(false) {
437 NextGlobalID = Context->getNumFunctionIDs();
438 }
439
440 virtual ~GlobalsParser() LLVM_OVERRIDE {}
441
442 protected:
443 virtual void ExitBlock() LLVM_OVERRIDE {
444 verifyNoMissingInitializers();
445 unsigned NumIDs = Context->getNumGlobalValueIDs();
446 if (NextGlobalID < NumIDs) {
447 unsigned NumFcnIDs = Context->getNumFunctionIDs();
448 std::string Buffer;
449 raw_string_ostream StrBuf(Buffer);
450 StrBuf << "Globals block expects "
451 << (NumIDs - NumFcnIDs)
452 << " global definitions. Found: "
453 << (NextGlobalID - NumFcnIDs);
454 Error(StrBuf.str());
455 }
456 BlockParser::ExitBlock();
457 }
458
459 virtual void ProcessRecord() LLVM_OVERRIDE;
460
461 // Holds the sequence of initializers for the global.
462 SmallVector<Constant *, 10> Initializers;
jvoung (off chromium) 2014/07/01 17:32:53 Similar, can we put all the fields in one block, a
Karl 2014/07/01 21:31:07 Done.
463
464 // Keeps track of how many initializers are expected for
465 // the global variable being built.
466 unsigned InitializersNeeded;
467
468 // The alignment assumed for the global variable being built.
469 unsigned Alignment;
470
471 // True if the global variable being built is a constant.
472 bool IsConstant;
473
474 // The index of the next global variable.
475 unsigned NextGlobalID;
476
477 // Checks if the number of initializers needed is the same as the
478 // number found in the bitcode file. If different, and error message
479 // is generated, and the internal state of the parser is fixed so
480 // this condition is no longer violated.
481 void verifyNoMissingInitializers() {
482 if (InitializersNeeded != Initializers.size()) {
483 std::string Buffer;
484 raw_string_ostream StrBuf(Buffer);
485 StrBuf << "Global variable @g"
486 << (NextGlobalID - Context->getNumFunctionIDs())
487 << " expected " << InitializersNeeded << " initializer";
488 if (InitializersNeeded > 1) StrBuf << "s";
489 StrBuf << ". Found: " << Initializers.size();
490 Error(StrBuf.str());
491 // Fix up state so that we can continue.
492 InitializersNeeded = Initializers.size();
493 installGlobalVar();
494 }
495 }
496
497 // Reserves a slot in the list of initializers being built. If there
498 // isn't room for the slot, an error message is generated.
499 void reserveInitializer(const char *RecordName) {
500 if (InitializersNeeded == Initializers.size()) {
jvoung (off chromium) 2014/07/01 17:32:52 Would it be safer to check if >= ? Otherwise, it l
Karl 2014/07/01 21:31:07 I did this so that we wouldn't get cascading error
501 std::string Buffer;
502 raw_string_ostream StrBuf(Buffer);
503 StrBuf << RecordName << " record: Too many initializers, ignoring.";
jvoung (off chromium) 2014/07/01 17:32:52 Probably could have just std::string() + ... for t
Karl 2014/07/01 21:31:07 Done.
504 Error(StrBuf.str());
505 }
506 }
507
508 // Takes the initializers (and other parser state values) and
509 // installs a global variable (with the initializers) into the list
510 // of ValueIDs.
511 void installGlobalVar() {
512 Constant *Init = 0;
513 switch (Initializers.size()) {
514 case 0:
515 Error("No initializer for global variable in global vars block");
516 return;
517 case 1:
518 Init = Initializers[0];
519 break;
520 default:
521 Init = ConstantStruct::getAnon(Context->getLLVMContext(),
522 Initializers, true);
523 break;
524 }
525 GlobalVariable *GV = new GlobalVariable(
526 *Context->getModule(), Init->getType(), IsConstant,
527 GlobalValue::InternalLinkage, Init, "");
528 GV->setAlignment(Alignment);
529 if (!Context->assignGlobalVariable(GV, NextGlobalID)) {
530 std::string Buffer;
531 raw_string_ostream StrBuf(Buffer);
532 StrBuf << "Defining global V[" << NextGlobalID
533 << "] not allowed. Out of range.";
534 Error(StrBuf.str());
535 }
536 ++NextGlobalID;
537 Initializers.clear();
538 InitializersNeeded = 0;
539 Alignment = 1;
540 IsConstant = false;
541 }
542 };
543
544 void GlobalsParser::ProcessRecord() {
545 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
546 switch (Record.GetCode()) {
547 case naclbitc::GLOBALVAR_COUNT:
548 // COUNT: [n]
549 if (checkRecordSize(1, "Globals count")) return;
550 if (NextGlobalID > Context->getNumFunctionIDs()) {
jvoung (off chromium) 2014/07/01 17:32:52 I can't put my finger on it, but this checks seems
Karl 2014/07/01 21:31:07 The test is to verify it appears before any global
551 Error("Globals count record not first in block.");
552 return;
553 }
554 verifyNoMissingInitializers();
555 Context->resizeValueIDsForGlobalVarCount(Values[0]);
556 return;
557 case naclbitc::GLOBALVAR_VAR: {
558 // VAR: [align, isconst]
559 if (checkRecordSize(2, "Globals variable")) return;
560 verifyNoMissingInitializers();
561 InitializersNeeded = 1;
562 Initializers.clear();
563 Alignment = (1 << Values[0]) >> 1;
564 IsConstant = Values[0] != 0;
jvoung (off chromium) 2014/07/01 17:32:52 Values[1] != 0 Otherwise, the alignment could mak
Karl 2014/07/01 21:31:08 Done.
565 return;
566 }
567 case naclbitc::GLOBALVAR_COMPOUND:
568 // COMPOUND: [size]
569 if (checkRecordSize(1, "globals compound")) return;
570 if (Initializers.size() > 0 || InitializersNeeded != 1) {
571 Error("Globals compound record not first initializer");
572 return;
573 }
574 if (Values[0] < 2) {
575 std::string Buffer;
576 raw_string_ostream StrBuf(Buffer);
577 StrBuf << "Globals compound record size invalid. Found: "
578 << Values[0];
579 Error(StrBuf.str());
580 return;
581 }
582 InitializersNeeded = Values[0];
583 return;
584 case naclbitc::GLOBALVAR_ZEROFILL: {
585 // ZEROFILL: [size]
586 if (checkRecordSize(1, "Globals zerofill")) return;
587 reserveInitializer("Globals zerofill");
588 Type *Ty = ArrayType::get(Type::getInt8Ty(Context->getLLVMContext()),
589 Values[0]);
590 Constant *Zero = ConstantAggregateZero::get(Ty);
591 Initializers.push_back(Zero);
592 break;
593 }
594 case naclbitc::GLOBALVAR_DATA: {
595 // DATA: [b0, b1, ...]
596 if (checkRecordSizeAtLeast(1, "Globals data")) return;
597 reserveInitializer("Globals data");
598 unsigned Size = Values.size();
599 uint8_t *Buf = new uint8_t[Size];
600 assert(Buf);
601 for (unsigned i = 0; i < Size; ++i)
jvoung (off chromium) 2014/07/01 17:32:53 could memcpy this?
Karl 2014/07/01 21:31:07 Not really. We are doing a cast from uint64_t to u
602 Buf[i] = Values[i];
603 Constant *Init = ConstantDataArray::get(
604 Context->getLLVMContext(),
605 ArrayRef<uint8_t>(Buf, Buf + Size));
606 Initializers.push_back(Init);
607 delete[] Buf;
608 break;
609 }
610 case naclbitc::GLOBALVAR_RELOC: {
611 // RELOC: [val, [addend]]
612 if (checkRecordSizeInRange(1, 2, "Globals reloc")) return;
613 Constant *BaseVal =
614 Context->getOrCreateGlobalVarRef(Values[0]);
615 if (BaseVal == 0) {
616 std::string Buffer;
617 raw_string_ostream StrBuf(Buffer);
618 StrBuf << "Can't find global relocation value: " << Values[0];
619 Error(StrBuf.str());
620 return;
621 }
622 Type *IntPtrType = IntegerType::get(Context->getLLVMContext(), 32);
623 Constant *Val = ConstantExpr::getPtrToInt(BaseVal, IntPtrType);
624 if (Values.size() == 2) {
625 Val = ConstantExpr::getAdd(Val, ConstantInt::get(IntPtrType, Values[1]));
626 }
627 Initializers.push_back(Val);
628 break;
629 }
630 default:
631 BlockParser::ProcessRecord();
632 return;
633 }
634 // If reached, just processed another intializer. See if time
635 // to install global.
636 if (InitializersNeeded == Initializers.size()) installGlobalVar();
637 }
638
639 // Parses a valuesymtab block in the bitcode file.
640 class ValuesymtabParser : public BlockParser {
641 typedef SmallString<128> StringType;
642 public:
643 ValuesymtabParser(unsigned BlockID,
644 BlockParser *EnclosingParser,
jvoung (off chromium) 2014/07/01 17:32:53 indent to line up to after the ( ? There is "make
Karl 2014/07/01 21:31:06 Done.
Jim Stichnoth 2014/07/07 20:50:23 This (modifying unrelated files) is usually becaus
645 bool AllowBbEntries)
646 : BlockParser(BlockID, EnclosingParser),
647 AllowBbEntries(AllowBbEntries) {}
648
649 virtual ~ValuesymtabParser() LLVM_OVERRIDE {}
650
651 protected:
652 // True if entries to name basic blocks allowed.
653 bool AllowBbEntries;
654 // The last name converted to a string using convertToString.
655 StringType ConvertedName;
656
657 virtual void ProcessRecord() LLVM_OVERRIDE;
658
659 void ConvertToString() {
660 ConvertedName.clear();
661 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
662 for (size_t i = 1, e = Values.size(); i != e; ++i) {
663 ConvertedName += static_cast<char>(Values[i]);
664 }
665 }
666 };
667
668 void ValuesymtabParser::ProcessRecord() {
669 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
670 switch (Record.GetCode()) {
671 case naclbitc::VST_CODE_ENTRY: {
672 // VST_ENTRY: [valid, namechar x N]
jvoung (off chromium) 2014/07/01 17:32:53 valueID, or something instead of valid
Karl 2014/07/01 21:31:07 Done.
673 if (checkRecordSizeAtLeast(2, "Valuesymtab value entry")) return;
674 ConvertToString();
jvoung (off chromium) 2014/07/01 17:32:52 Feels a bit roundabout that ConvertedName is a fie
Karl 2014/07/01 21:31:07 I mainly did this to avoid allocations between cal
675 Value *V = Context->getGlobalValueByID(Values[0]);
676 if (V == 0) {
677 std::string Buffer;
678 raw_string_ostream StrBuf(Buffer);
679 StrBuf << "Invalid global address ID in valuesymtab: " << Values[0];
680 Error(StrBuf.str());
681 return;
682 }
683 V->setName(StringRef(ConvertedName.data(), ConvertedName.size()));
684 return;
685 }
686 case naclbitc::VST_CODE_BBENTRY: {
687 // VST_BBENTRY: [bbid, namechar x N]
688 // For now, since we aren't processing function blocks, don't handle.
689 if (AllowBbEntries) {
690 Error("Valuesymtab bb entry not implemented");
691 return;
692 }
693 break;
694 }
695 default:
696 break;
697 }
698 // If reached, don't know how to handle record.
699 BlockParser::ProcessRecord();
700 return;
701 }
702
703 /// Parses the module block in the bitcode file.
704 class ModuleParser : public BlockParser {
705 public:
706 ModuleParser(unsigned BlockID, TopLevelParser *Context)
707 : BlockParser(BlockID, Context) {}
708
709 virtual ~ModuleParser() LLVM_OVERRIDE {}
710
711 protected:
712 virtual bool ParseBlock(unsigned BlockID) LLVM_OVERRIDE;
713
714 virtual void ProcessRecord() LLVM_OVERRIDE;
715 };
716
717 bool ModuleParser::ParseBlock(unsigned BlockID) LLVM_OVERRIDE {
718 switch (BlockID) {
719 case naclbitc::BLOCKINFO_BLOCK_ID:
720 return NaClBitcodeParser::ParseBlock(BlockID);
721 case naclbitc::TYPE_BLOCK_ID_NEW: {
722 TypesParser Parser(BlockID, this);
723 return Parser.ParseThisBlock();
724 }
725 case naclbitc::GLOBALVAR_BLOCK_ID: {
726 GlobalsParser Parser(BlockID, this);
727 return Parser.ParseThisBlock();
728 }
729 case naclbitc::VALUE_SYMTAB_BLOCK_ID: {
730 ValuesymtabParser Parser(BlockID, this, false);
731 return Parser.ParseThisBlock();
732 }
733 case naclbitc::FUNCTION_BLOCK_ID: {
734 Error("Function block parser not yet implemented, skipping");
735 SkipBlock();
736 return false;
737 }
738 default:
739 return BlockParser::ParseBlock(BlockID);
740 }
741 }
742
743 void ModuleParser::ProcessRecord() {
744 const NaClBitcodeRecord::RecordVector &Values = Record.GetValues();
745 switch (Record.GetCode()) {
746 case naclbitc::MODULE_CODE_VERSION: {
747 // VERSION: [version#]
748 if (checkRecordSize(1, "Module version")) return;
749 unsigned Version = Values[0];
750 if (Version != 1) {
751 std::string Buffer;
752 raw_string_ostream StrBuf(Buffer);
753 StrBuf << "Unknown bitstream version: " << Version;
754 Error(StrBuf.str());
755 }
756 return;
757 }
758 case naclbitc::MODULE_CODE_FUNCTION: {
759 // FUNCTION: [type, callingconv, isproto, linkage]
760 if (checkRecordSize(4, "Function heading")) return;
761 Type *Ty = Context->getTypeByID(Values[0]);
762 FunctionType *FTy = dyn_cast<FunctionType>(Ty);
763 if (FTy == 0) {
764 std::string Buffer;
765 raw_string_ostream StrBuf(Buffer);
766 StrBuf << "Function heading expects function type. Found: "
767 << Ty;
768 Error(StrBuf.str());
769 return;
770 }
771 CallingConv::ID CallingConv;
772 if (!naclbitc::DecodeCallingConv(Values[1], CallingConv)) {
773 std::string Buffer;
774 raw_string_ostream StrBuf(Buffer);
775 StrBuf << "Function heading has unknown calling convention: "
776 << Values[1];
777 Error(StrBuf.str());
778 return;
779 }
780 GlobalValue::LinkageTypes Linkage;
781 if (!naclbitc::DecodeLinkage(Values[3], Linkage)) {
782 std::string Buffer;
783 raw_string_ostream StrBuf(Buffer);
784 StrBuf << "Function heading has unknown linkage. Found "
785 << Values[3];
786 Error(StrBuf.str());
787 return;
788 }
789 Function *Func = Function::Create(FTy, Linkage, "", Context->getModule());
790 Func->setCallingConv(CallingConv);
791 if (Values[2] == 0) Context->setNextValueIDAsImplementedFunction();
792 Context->setNextFunctionID(Func);
793 // TODO(kschimpf) verify if Func matches PNaCl ABI.
794 return;
795 }
796 default:
797 BlockParser::ProcessRecord();
798 return;
799 }
800 }
801
802 bool TopLevelParser::ParseBlock(unsigned BlockID) {
803 if (BlockID == naclbitc::MODULE_BLOCK_ID) {
804 ModuleParser Parser(BlockID, this);
805 bool Results = Parser.ParseThisBlock();
jvoung (off chromium) 2014/07/01 17:32:53 Singular Result? Otherwise it sounds like a collec
Karl 2014/07/01 21:31:06 Done.
806 // TODO(kschimpf): Remove once translating function blocks.
807 errs() << "Global addresses:\n";
808 for (size_t i = 0; i < ValueIDValues.size(); ++i) {
809 errs() << "[" << i << "]: " << *ValueIDValues[i] << "\n";
jvoung (off chromium) 2014/07/01 17:32:53 How will this eventually transition? This starts t
Karl 2014/07/01 21:31:08 I need to implement a FunctionParser. It will have
810 }
811 return Results;
812 }
813 // Generate error message by using default block implementation.
814 BlockParser Parser(BlockID, this);
815 return Parser.ParseThisBlock();
816 }
817
818 }
819
820 namespace Ice {
821
822 int PNaClTranslator::translate(std::string IRFilename) {
823 OwningPtr<MemoryBuffer> MemBuf;
824 if (error_code ec =
825 MemoryBuffer::getFileOrSTDIN(IRFilename.c_str(), MemBuf)) {
826 errs() << "Error reading '" << IRFilename << "': "
827 << ec.message() << "\n";
828 return ExitStatus = 1;
829 }
830
831 if (MemBuf->getBufferSize() % 4 != 0) {
832 errs() << IRFilename
833 << ": Bitcode stream should be a multiple of 4 bytes in length.\n";
834 return ExitStatus = 1;
835 }
836
837 const unsigned char *BufPtr = (const unsigned char *)MemBuf->getBufferStart();
838 const unsigned char *EndBufPtr = BufPtr+MemBuf->getBufferSize();
839
840 // Read header and verify it is good.
841 NaClBitcodeHeader Header;
842 if (Header.Read(BufPtr, EndBufPtr) || !Header.IsSupported()) {
843 errs() << "Invalid PNaCl bitcode header.\n";
844 return ExitStatus = 1;
845 }
846
847 // Create a bitstream reader to read the bitcode file.
848 NaClBitstreamReader InputStreamFile(BufPtr, EndBufPtr);
849 NaClBitstreamCursor InputStream(InputStreamFile);
850
851 OwningPtr<Module> Mod(
852 new Module(MemBuf->getBufferIdentifier(), getGlobalContext()));
853
854 Mod->setDataLayout(PNaClDataLayout);
855
856 TopLevelParser Parser(&*Mod, Header, InputStream);
jvoung (off chromium) 2014/07/01 17:32:52 Mod.get(), if you just want the raw pointer. Or m
Karl 2014/07/01 21:31:07 Moved into Parser constructor.
857 int TopLevelBlocks = 0;
858 while (!InputStream.AtEndOfStream()) {
859 if (Parser.Parse()) return 1;
860 ++TopLevelBlocks;
861 }
862
863 if (TopLevelBlocks != 1) {
864 errs() << IRFilename << ": Contains more than one module. Found: "
865 << TopLevelBlocks << "\n";
866 return ExitStatus = 1;
867 }
868
869 return ExitStatus = (Parser.getNumErrors() > 0);
870 }
871
872 }
OLDNEW
« src/PNaClTranslator.h ('K') | « src/PNaClTranslator.h ('k') | src/llvm2ice.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698