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

Side by Side Diff: lib/Bitcode/NaCl/Reader/NaClBitcodeReader.cpp

Issue 770853002: Fix error reporting in the PNaCl bitcode reader. (Closed) Base URL: https://chromium.googlesource.com/native_client/pnacl-llvm.git@master
Patch Set: Fix typo. Created 6 years 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
1 //===- NaClBitcodeReader.cpp ----------------------------------------------===// 1 //===- NaClBitcodeReader.cpp ----------------------------------------------===//
2 // Internal NaClBitcodeReader implementation 2 // Internal NaClBitcodeReader implementation
3 // 3 //
4 // The LLVM Compiler Infrastructure 4 // The LLVM Compiler Infrastructure
5 // 5 //
6 // This file is distributed under the University of Illinois Open Source 6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details. 7 // License. See LICENSE.TXT for details.
8 // 8 //
9 //===----------------------------------------------------------------------===// 9 //===----------------------------------------------------------------------===//
10 10
(...skipping 98 matching lines...) Expand 10 before | Expand all | Expand 10 after
109 109
110 // No type specified, must be invalid reference. 110 // No type specified, must be invalid reference.
111 if (Ty == 0) 111 if (Ty == 0)
112 return true; 112 return true;
113 113
114 // Create a placeholder, which will later be RAUW'd. 114 // Create a placeholder, which will later be RAUW'd.
115 ValuePtrs[Idx] = new Argument(Ty); 115 ValuePtrs[Idx] = new Argument(Ty);
116 return false; 116 return false;
117 } 117 }
118 118
119 namespace {
120 class NaClBitcodeErrorCategoryType : public std::error_category {
121 const char *name() const LLVM_NOEXCEPT override {
122 return "pnacl.bitcode";
123 }
124 std::string message(int IndexError) const override {
125 switch(static_cast<NaClBitcodeReader::ErrorType>(IndexError)) {
126 case NaClBitcodeReader::CouldNotFindFunctionInStream:
127 return "Unable to find function in bitcode stream.";
128 case NaClBitcodeReader::InsufficientFunctionProtos:
129 return "Insufficient function protos";
130 case NaClBitcodeReader::InvalidBitstream:
131 return "Error in bitstream format";
132 case NaClBitcodeReader::InvalidConstantReference:
133 return "Bad constant reference";
134 case NaClBitcodeReader::InvalidInstructionWithNoBB:
135 return "No basic block for instruction";
136 case NaClBitcodeReader::InvalidMultipleBlocks:
137 return "Multiple blocks for a kind of block that should have only one";
138 case NaClBitcodeReader::InvalidRecord:
139 return "Record doesn't have expected size or structure";
140 case NaClBitcodeReader::InvalidSkippedBlock:
141 return "Unable to skip unknown block in bitcode file";
142 case NaClBitcodeReader::InvalidType:
143 return "Invalid type in record";
144 case NaClBitcodeReader::InvalidTypeForValue:
145 return "Type of value in record incorrect";
146 case NaClBitcodeReader::InvalidValue:
147 return "Invalid value in record";
148 case NaClBitcodeReader::MalformedBlock:
149 return "Malformed block. Unable to advance over block";
150 }
151 llvm_unreachable("Unknown error type!");
152 }
153 };
154 } // end of anonomous namespace.
155
156 const std::error_category &NaClBitcodeReader::BitcodeErrorCategory() {
157 static NaClBitcodeErrorCategoryType ErrCat;
158 return ErrCat;
159 }
160
119 Type *NaClBitcodeReader::getTypeByID(unsigned ID) { 161 Type *NaClBitcodeReader::getTypeByID(unsigned ID) {
120 // The type table size is always specified correctly. 162 // The type table size is always specified correctly.
121 if (ID >= TypeList.size()) 163 if (ID >= TypeList.size())
122 return 0; 164 return 0;
123 165
124 if (Type *Ty = TypeList[ID]) 166 if (Type *Ty = TypeList[ID])
125 return Ty; 167 return Ty;
126 168
127 // If we have a forward reference, the only possible case is when it is to a 169 // If we have a forward reference, the only possible case is when it is to a
128 // named struct. Just create a placeholder for now. 170 // named struct. Just create a placeholder for now.
129 return TypeList[ID] = StructType::create(Context); 171 return TypeList[ID] = StructType::create(Context);
130 } 172 }
131 173
132 174
133 //===----------------------------------------------------------------------===// 175 //===----------------------------------------------------------------------===//
134 // Functions for parsing blocks from the bitcode file 176 // Functions for parsing blocks from the bitcode file
135 //===----------------------------------------------------------------------===// 177 //===----------------------------------------------------------------------===//
136 178
137 179
138 bool NaClBitcodeReader::ParseTypeTable() { 180 std::error_code NaClBitcodeReader::Error(ErrorType E,
181 const std::string &Message) const {
182 if (Verbose)
183 *Verbose << "Error: " << Message << "\n";
184 return Error(E);
185 }
186
187 std::error_code NaClBitcodeReader::ParseTypeTable() {
139 DEBUG(dbgs() << "-> ParseTypeTable\n"); 188 DEBUG(dbgs() << "-> ParseTypeTable\n");
140 if (Stream.EnterSubBlock(naclbitc::TYPE_BLOCK_ID_NEW)) 189 if (Stream.EnterSubBlock(naclbitc::TYPE_BLOCK_ID_NEW))
141 return Error("Malformed block record"); 190 return Error(InvalidRecord, "Malformed block record");
142 191
143 bool result = ParseTypeTableBody(); 192 std::error_code result = ParseTypeTableBody();
144 if (!result) 193 if (!result)
145 DEBUG(dbgs() << "<- ParseTypeTable\n"); 194 DEBUG(dbgs() << "<- ParseTypeTable\n");
146 return result; 195 return result;
147 } 196 }
148 197
149 bool NaClBitcodeReader::ParseTypeTableBody() { 198 std::error_code NaClBitcodeReader::ParseTypeTableBody() {
150 if (!TypeList.empty()) 199 if (!TypeList.empty())
151 return Error("Multiple TYPE_BLOCKs found!"); 200 return Error(InvalidMultipleBlocks, "Multiple TYPE_BLOCKs found!");
152 201
153 SmallVector<uint64_t, 64> Record; 202 SmallVector<uint64_t, 64> Record;
154 unsigned NumRecords = 0; 203 unsigned NumRecords = 0;
155 204
156 // Read all the records for this type table. 205 // Read all the records for this type table.
157 while (1) { 206 while (1) {
158 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 207 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks();
159 208
160 switch (Entry.Kind) { 209 switch (Entry.Kind) {
161 case NaClBitstreamEntry::SubBlock: // Handled for us already. 210 case NaClBitstreamEntry::SubBlock: // Handled for us already.
162 case NaClBitstreamEntry::Error: 211 case NaClBitstreamEntry::Error:
163 Error("Error in the type table block"); 212 return Error(MalformedBlock, "Error in the type table block");
164 return true;
165 case NaClBitstreamEntry::EndBlock: 213 case NaClBitstreamEntry::EndBlock:
166 if (NumRecords != TypeList.size()) 214 if (NumRecords != TypeList.size())
167 return Error("Invalid type forward reference in TYPE_BLOCK"); 215 return Error(MalformedBlock,
168 return false; 216 "Invalid type forward reference in TYPE_BLOCK");
217 return std::error_code();
169 case NaClBitstreamEntry::Record: 218 case NaClBitstreamEntry::Record:
170 // The interesting case. 219 // The interesting case.
171 break; 220 break;
172 } 221 }
173 222
174 // Read a record. 223 // Read a record.
175 Record.clear(); 224 Record.clear();
176 Type *ResultTy = 0; 225 Type *ResultTy = 0;
177 unsigned TypeCode = Stream.readRecord(Entry.ID, Record); 226 unsigned TypeCode = Stream.readRecord(Entry.ID, Record);
178 switch (TypeCode) { 227 switch (TypeCode) {
179 default: { 228 default: {
180 std::string Message; 229 std::string Message;
181 raw_string_ostream StrM(Message); 230 raw_string_ostream StrM(Message);
182 StrM << "Unknown type code in type table: " << TypeCode; 231 StrM << "Unknown type code in type table: " << TypeCode;
183 StrM.flush(); 232 StrM.flush();
184 return Error(Message); 233 return Error(InvalidValue, Message);
185 } 234 }
186 235
187 case naclbitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 236 case naclbitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
188 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 237 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
189 // type list. This allows us to reserve space. 238 // type list. This allows us to reserve space.
190 if (Record.size() != 1) 239 if (Record.size() != 1)
191 return Error("Invalid TYPE_CODE_NUMENTRY record"); 240 return Error(InvalidRecord, "Invalid TYPE_CODE_NUMENTRY record");
192 TypeList.resize(Record[0]); 241 TypeList.resize(Record[0]);
193 // No type was defined, skip the checks that follow the switch. 242 // No type was defined, skip the checks that follow the switch.
194 continue; 243 continue;
195 244
196 case naclbitc::TYPE_CODE_VOID: // VOID 245 case naclbitc::TYPE_CODE_VOID: // VOID
197 if (Record.size() != 0) 246 if (Record.size() != 0)
198 return Error("Invalid TYPE_CODE_VOID record"); 247 return Error(InvalidRecord, "Invalid TYPE_CODE_VOID record");
199 ResultTy = Type::getVoidTy(Context); 248 ResultTy = Type::getVoidTy(Context);
200 break; 249 break;
201 250
202 case naclbitc::TYPE_CODE_FLOAT: // FLOAT 251 case naclbitc::TYPE_CODE_FLOAT: // FLOAT
203 if (Record.size() != 0) 252 if (Record.size() != 0)
204 return Error("Invalid TYPE_CODE_FLOAT record"); 253 return Error(InvalidRecord, "Invalid TYPE_CODE_FLOAT record");
205 ResultTy = Type::getFloatTy(Context); 254 ResultTy = Type::getFloatTy(Context);
206 break; 255 break;
207 256
208 case naclbitc::TYPE_CODE_DOUBLE: // DOUBLE 257 case naclbitc::TYPE_CODE_DOUBLE: // DOUBLE
209 if (Record.size() != 0) 258 if (Record.size() != 0)
210 return Error("Invalid TYPE_CODE_DOUBLE record"); 259 return Error(InvalidRecord, "Invalid TYPE_CODE_DOUBLE record");
211 ResultTy = Type::getDoubleTy(Context); 260 ResultTy = Type::getDoubleTy(Context);
212 break; 261 break;
213 262
214 case naclbitc::TYPE_CODE_INTEGER: // INTEGER: [width] 263 case naclbitc::TYPE_CODE_INTEGER: // INTEGER: [width]
215 if (Record.size() != 1) 264 if (Record.size() != 1)
216 return Error("Invalid TYPE_CODE_INTEGER record"); 265 return Error(InvalidRecord, "Invalid TYPE_CODE_INTEGER record");
217 ResultTy = IntegerType::get(Context, Record[0]); 266 ResultTy = IntegerType::get(Context, Record[0]);
218 break; 267 break;
219 268
220 case naclbitc::TYPE_CODE_FUNCTION: { 269 case naclbitc::TYPE_CODE_FUNCTION: {
221 // FUNCTION: [vararg, retty, paramty x N] 270 // FUNCTION: [vararg, retty, paramty x N]
222 if (Record.size() < 2) 271 if (Record.size() < 2)
223 return Error("Invalid TYPE_CODE_FUNCTION record"); 272 return Error(InvalidRecord, "Invalid TYPE_CODE_FUNCTION record");
224 SmallVector<Type *, 8> ArgTys; 273 SmallVector<Type *, 8> ArgTys;
225 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 274 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
226 if (Type *T = getTypeByID(Record[i])) 275 if (Type *T = getTypeByID(Record[i]))
227 ArgTys.push_back(T); 276 ArgTys.push_back(T);
228 else 277 else
229 break; 278 break;
230 } 279 }
231 280
232 ResultTy = getTypeByID(Record[1]); 281 ResultTy = getTypeByID(Record[1]);
233 if (ResultTy == 0 || ArgTys.size() < Record.size() - 2) 282 if (ResultTy == 0 || ArgTys.size() < Record.size() - 2)
234 return Error("invalid type in function type"); 283 return Error(InvalidType, "invalid type in function type");
235 284
236 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 285 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
237 break; 286 break;
238 } 287 }
239 case naclbitc::TYPE_CODE_VECTOR: { // VECTOR: [numelts, eltty] 288 case naclbitc::TYPE_CODE_VECTOR: { // VECTOR: [numelts, eltty]
240 if (Record.size() != 2) 289 if (Record.size() != 2)
241 return Error("Invalid VECTOR type record"); 290 return Error(InvalidRecord, "Invalid VECTOR type record");
242 if ((ResultTy = getTypeByID(Record[1]))) 291 if ((ResultTy = getTypeByID(Record[1])))
243 ResultTy = VectorType::get(ResultTy, Record[0]); 292 ResultTy = VectorType::get(ResultTy, Record[0]);
244 else 293 else
245 return Error("invalid type in vector type"); 294 return Error(InvalidType, "invalid type in vector type");
246 break; 295 break;
247 } 296 }
248 } 297 }
249 298
250 if (NumRecords >= TypeList.size()) 299 if (NumRecords >= TypeList.size())
251 return Error("invalid TYPE table"); 300 return Error(MalformedBlock, "invalid TYPE table");
252 assert(ResultTy && "Didn't read a type?"); 301 assert(ResultTy && "Didn't read a type?");
253 assert(TypeList[NumRecords] == 0 && "Already read type?"); 302 assert(TypeList[NumRecords] == 0 && "Already read type?");
254 TypeList[NumRecords++] = ResultTy; 303 TypeList[NumRecords++] = ResultTy;
255 } 304 }
305 return std::error_code();
256 } 306 }
257 307
258 namespace { 308 namespace {
259 309
260 // Class to process globals in two passes. In the first pass, build 310 // Class to process globals in two passes. In the first pass, build
261 // the corresponding global variables with no initializers. In the 311 // the corresponding global variables with no initializers. In the
262 // second pass, add initializers. The purpose of putting off 312 // second pass, add initializers. The purpose of putting off
263 // initializers is to make sure that we don't need to generate 313 // initializers is to make sure that we don't need to generate
264 // placeholders for relocation records, and the corresponding cost 314 // placeholders for relocation records, and the corresponding cost
265 // of duplicating initializers when these placeholders are replaced. 315 // of duplicating initializers when these placeholders are replaced.
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after
303 Module *TheModule) 353 Module *TheModule)
304 : Reader(Reader), 354 : Reader(Reader),
305 ValueList(ValueList), 355 ValueList(ValueList),
306 Stream(Stream), 356 Stream(Stream),
307 Context(Context), 357 Context(Context),
308 TheModule(TheModule), 358 TheModule(TheModule),
309 FirstValueNo(ValueList.size()), 359 FirstValueNo(ValueList.size()),
310 NumGlobals(0), 360 NumGlobals(0),
311 StartBit(Stream.GetCurrentBitNo()) {} 361 StartBit(Stream.GetCurrentBitNo()) {}
312 362
313 bool GenerateGlobalVarsPass() { 363 std::error_code GenerateGlobalVarsPass() {
314 InitPass(); 364 InitPass();
315 365
316 // The type for the initializer of the global variable. 366 // The type for the initializer of the global variable.
317 SmallVector<Type*, 10> VarType; 367 SmallVector<Type*, 10> VarType;
318 // The alignment value defined for the global variable. 368 // The alignment value defined for the global variable.
319 unsigned VarAlignment = 0; 369 unsigned VarAlignment = 0;
320 // True if the variable is read-only. 370 // True if the variable is read-only.
321 bool VarIsConstant = false; 371 bool VarIsConstant = false;
322 372
323 // Read all records to build global variables without initializers. 373 // Read all records to build global variables without initializers.
324 while (1) { 374 while (1) {
325 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks( 375 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(
326 NaClBitstreamCursor::AF_DontPopBlockAtEnd); 376 NaClBitstreamCursor::AF_DontPopBlockAtEnd);
327 switch (Entry.Kind) { 377 switch (Entry.Kind) {
328 case NaClBitstreamEntry::SubBlock: 378 case NaClBitstreamEntry::SubBlock:
329 case NaClBitstreamEntry::Error: 379 case NaClBitstreamEntry::Error:
330 return Reader.Error("Error in the global vars block"); 380 return Reader.Error(NaClBitcodeReader::MalformedBlock,
381 "Error in the global vars block");
331 case NaClBitstreamEntry::EndBlock: 382 case NaClBitstreamEntry::EndBlock:
332 if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo)) 383 if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo))
333 return Reader.Error("Error in the global vars block"); 384 return Reader.Error(NaClBitcodeReader::MalformedBlock,
334 return false; 385 "Error in the global vars block");
386 return std::error_code();
335 case NaClBitstreamEntry::Record: 387 case NaClBitstreamEntry::Record:
336 // The interesting case. 388 // The interesting case.
337 break; 389 break;
338 } 390 }
339 391
340 // Read a record. 392 // Read a record.
341 Record.clear(); 393 Record.clear();
342 unsigned Bitcode = Stream.readRecord(Entry.ID, Record); 394 unsigned Bitcode = Stream.readRecord(Entry.ID, Record);
343 switch (Bitcode) { 395 switch (Bitcode) {
344 default: return Reader.Error("Unknown global variable entry"); 396 default:
397 return Reader.Error(NaClBitcodeReader::InvalidValue,
398 "Unknown global variable entry");
345 case naclbitc::GLOBALVAR_VAR: 399 case naclbitc::GLOBALVAR_VAR:
346 // Start the definition of a global variable. 400 // Start the definition of a global variable.
347 if (ProcessingGlobal || Record.size() != 2) 401 if (ProcessingGlobal || Record.size() != 2)
348 return Reader.Error("Bad GLOBALVAR_VAR record"); 402 return Reader.Error(NaClBitcodeReader::InvalidRecord,
403 "Bad GLOBALVAR_VAR record");
349 ProcessingGlobal = true; 404 ProcessingGlobal = true;
350 VarAlignment = (1 << Record[0]) >> 1; 405 VarAlignment = (1 << Record[0]) >> 1;
351 VarIsConstant = Record[1] != 0; 406 VarIsConstant = Record[1] != 0;
352 // Assume (by default) there is a single initializer. 407 // Assume (by default) there is a single initializer.
353 VarInitializersNeeded = 1; 408 VarInitializersNeeded = 1;
354 break; 409 break;
355 case naclbitc::GLOBALVAR_COMPOUND: 410 case naclbitc::GLOBALVAR_COMPOUND:
356 // Global variable has multiple initializers. Changes the 411 // Global variable has multiple initializers. Changes the
357 // default number of initializers to the given value in 412 // default number of initializers to the given value in
358 // Record[0]. 413 // Record[0].
359 if (!ProcessingGlobal || !VarType.empty() || 414 if (!ProcessingGlobal || !VarType.empty() ||
360 VarInitializersNeeded != 1 || Record.size() != 1) 415 VarInitializersNeeded != 1 || Record.size() != 1)
361 return Reader.Error("Bad GLOBALVAR_COMPOUND record"); 416 return Reader.Error(NaClBitcodeReader::InvalidRecord,
417 "Bad GLOBALVAR_COMPOUND record");
362 VarInitializersNeeded = Record[0]; 418 VarInitializersNeeded = Record[0];
363 break; 419 break;
364 case naclbitc::GLOBALVAR_ZEROFILL: { 420 case naclbitc::GLOBALVAR_ZEROFILL: {
365 // Define a type that defines a sequence of zero-filled bytes. 421 // Define a type that defines a sequence of zero-filled bytes.
366 if (!ProcessingGlobal || Record.size() != 1) 422 if (!ProcessingGlobal || Record.size() != 1)
367 return Reader.Error("Bad GLOBALVAR_ZEROFILL record"); 423 return Reader.Error(NaClBitcodeReader::InvalidRecord,
424 "Bad GLOBALVAR_ZEROFILL record");
368 VarType.push_back(ArrayType::get( 425 VarType.push_back(ArrayType::get(
369 Type::getInt8Ty(Context), Record[0])); 426 Type::getInt8Ty(Context), Record[0]));
370 break; 427 break;
371 } 428 }
372 case naclbitc::GLOBALVAR_DATA: { 429 case naclbitc::GLOBALVAR_DATA: {
373 // Defines a type defined by a sequence of byte values. 430 // Defines a type defined by a sequence of byte values.
374 if (!ProcessingGlobal || Record.size() < 1) 431 if (!ProcessingGlobal || Record.size() < 1)
375 return Reader.Error("Bad GLOBALVAR_DATA record"); 432 return Reader.Error(NaClBitcodeReader::InvalidRecord,
433 "Bad GLOBALVAR_DATA record");
376 VarType.push_back(ArrayType::get( 434 VarType.push_back(ArrayType::get(
377 Type::getInt8Ty(Context), Record.size())); 435 Type::getInt8Ty(Context), Record.size()));
378 break; 436 break;
379 } 437 }
380 case naclbitc::GLOBALVAR_RELOC: { 438 case naclbitc::GLOBALVAR_RELOC: {
381 // Define a relocation initializer type. 439 // Define a relocation initializer type.
382 if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2) 440 if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2)
383 return Reader.Error("Bad GLOBALVAR_RELOC record"); 441 return Reader.Error(NaClBitcodeReader::InvalidRecord,
442 "Bad GLOBALVAR_RELOC record");
384 VarType.push_back(IntegerType::get(Context, 32)); 443 VarType.push_back(IntegerType::get(Context, 32));
385 break; 444 break;
386 } 445 }
387 case naclbitc::GLOBALVAR_COUNT: 446 case naclbitc::GLOBALVAR_COUNT:
388 if (Record.size() != 1 || NumGlobals != 0) 447 if (Record.size() != 1 || NumGlobals != 0)
389 return Reader.Error("Invalid global count record"); 448 return Reader.Error(NaClBitcodeReader::InvalidRecord,
449 "Invalid global count record");
390 NumGlobals = Record[0]; 450 NumGlobals = Record[0];
391 break; 451 break;
392 } 452 }
393 453
394 // If more initializers needed for global variable, continue processing. 454 // If more initializers needed for global variable, continue processing.
395 if (!ProcessingGlobal || VarType.size() < VarInitializersNeeded) 455 if (!ProcessingGlobal || VarType.size() < VarInitializersNeeded)
396 continue; 456 continue;
397 457
398 Type *Ty = 0; 458 Type *Ty = 0;
399 switch (VarType.size()) { 459 switch (VarType.size()) {
400 case 0: 460 case 0:
401 return Reader.Error( 461 return Reader.Error(
462 NaClBitcodeReader::InvalidRecord,
402 "No initializer for global variable in global vars block"); 463 "No initializer for global variable in global vars block");
403 case 1: 464 case 1:
404 Ty = VarType[0]; 465 Ty = VarType[0];
405 break; 466 break;
406 default: 467 default:
407 Ty = StructType::get(Context, VarType, true); 468 Ty = StructType::get(Context, VarType, true);
408 break; 469 break;
409 } 470 }
410 GlobalVariable *GV = new GlobalVariable( 471 GlobalVariable *GV = new GlobalVariable(
411 *TheModule, Ty, VarIsConstant, 472 *TheModule, Ty, VarIsConstant,
412 GlobalValue::InternalLinkage, NULL, ""); 473 GlobalValue::InternalLinkage, NULL, "");
413 GV->setAlignment(VarAlignment); 474 GV->setAlignment(VarAlignment);
414 ValueList.AssignValue(GV, NextValueNo); 475 ValueList.AssignValue(GV, NextValueNo);
415 ++NextValueNo; 476 ++NextValueNo;
416 ProcessingGlobal = false; 477 ProcessingGlobal = false;
417 VarAlignment = 0; 478 VarAlignment = 0;
418 VarIsConstant = false; 479 VarIsConstant = false;
419 VarInitializersNeeded = 0; 480 VarInitializersNeeded = 0;
420 VarType.clear(); 481 VarType.clear();
421 } 482 }
483 return std::error_code();
422 } 484 }
423 485
424 bool GenerateGlobalVarInitsPass() { 486 std::error_code GenerateGlobalVarInitsPass() {
425 InitPass(); 487 InitPass();
426 // The initializer for the global variable. 488 // The initializer for the global variable.
427 SmallVector<Constant *, 10> VarInit; 489 SmallVector<Constant *, 10> VarInit;
428 490
429 while (1) { 491 while (1) {
430 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks( 492 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(
431 NaClBitstreamCursor::AF_DontAutoprocessAbbrevs); 493 NaClBitstreamCursor::AF_DontAutoprocessAbbrevs);
432 switch (Entry.Kind) { 494 switch (Entry.Kind) {
433 case NaClBitstreamEntry::SubBlock: 495 case NaClBitstreamEntry::SubBlock:
434 case NaClBitstreamEntry::Error: 496 case NaClBitstreamEntry::Error:
435 return Reader.Error("Error in the global vars block"); 497 return Reader.Error(NaClBitcodeReader::MalformedBlock,
498 "Error in the global vars block");
436 case NaClBitstreamEntry::EndBlock: 499 case NaClBitstreamEntry::EndBlock:
437 if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo)) 500 if (ProcessingGlobal || NumGlobals != (NextValueNo - FirstValueNo))
438 return Reader.Error("Error in the global vars block"); 501 return Reader.Error(NaClBitcodeReader::MalformedBlock,
439 return false; 502 "Error in the global vars block");
503 return std::error_code();
440 case NaClBitstreamEntry::Record: 504 case NaClBitstreamEntry::Record:
441 if (Entry.ID == naclbitc::DEFINE_ABBREV) { 505 if (Entry.ID == naclbitc::DEFINE_ABBREV) {
442 Stream.SkipAbbrevRecord(); 506 Stream.SkipAbbrevRecord();
443 continue; 507 continue;
444 } 508 }
445 // The interesting case. 509 // The interesting case.
446 break; 510 break;
447 default: 511 default:
448 return Reader.Error("Unexpected record"); 512 return Reader.Error(NaClBitcodeReader::InvalidRecord,
513 "Unexpected record");
449 } 514 }
450 515
451 // Read a record. 516 // Read a record.
452 Record.clear(); 517 Record.clear();
453 unsigned Bitcode = Stream.readRecord(Entry.ID, Record); 518 unsigned Bitcode = Stream.readRecord(Entry.ID, Record);
454 switch (Bitcode) { 519 switch (Bitcode) {
455 default: return Reader.Error("Unknown global variable entry 2"); 520 default:
521 return Reader.Error(NaClBitcodeReader::InvalidValue,
522 "Unknown global variable entry 2");
456 case naclbitc::GLOBALVAR_VAR: 523 case naclbitc::GLOBALVAR_VAR:
457 // Start the definition of a global variable. 524 // Start the definition of a global variable.
458 ProcessingGlobal = true; 525 ProcessingGlobal = true;
459 // Assume (by default) there is a single initializer. 526 // Assume (by default) there is a single initializer.
460 VarInitializersNeeded = 1; 527 VarInitializersNeeded = 1;
461 break; 528 break;
462 case naclbitc::GLOBALVAR_COMPOUND: 529 case naclbitc::GLOBALVAR_COMPOUND:
463 // Global variable has multiple initializers. Changes the 530 // Global variable has multiple initializers. Changes the
464 // default number of initializers to the given value in 531 // default number of initializers to the given value in
465 // Record[0]. 532 // Record[0].
466 if (!ProcessingGlobal || !VarInit.empty() || 533 if (!ProcessingGlobal || !VarInit.empty() ||
467 VarInitializersNeeded != 1 || Record.size() != 1) 534 VarInitializersNeeded != 1 || Record.size() != 1)
468 return Reader.Error("Bad GLOBALVAR_COMPOUND record"); 535 return Reader.Error(NaClBitcodeReader::InvalidRecord,
536 "Bad GLOBALVAR_COMPOUND record");
469 VarInitializersNeeded = Record[0]; 537 VarInitializersNeeded = Record[0];
470 break; 538 break;
471 case naclbitc::GLOBALVAR_ZEROFILL: { 539 case naclbitc::GLOBALVAR_ZEROFILL: {
472 // Define an initializer that defines a sequence of zero-filled bytes. 540 // Define an initializer that defines a sequence of zero-filled bytes.
473 if (!ProcessingGlobal || Record.size() != 1) 541 if (!ProcessingGlobal || Record.size() != 1)
474 return Reader.Error("Bad GLOBALVAR_ZEROFILL record"); 542 return Reader.Error(NaClBitcodeReader::InvalidRecord,
543 "Bad GLOBALVAR_ZEROFILL record");
475 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), 544 Type *Ty = ArrayType::get(Type::getInt8Ty(Context),
476 Record[0]); 545 Record[0]);
477 Constant *Zero = ConstantAggregateZero::get(Ty); 546 Constant *Zero = ConstantAggregateZero::get(Ty);
478 VarInit.push_back(Zero); 547 VarInit.push_back(Zero);
479 break; 548 break;
480 } 549 }
481 case naclbitc::GLOBALVAR_DATA: { 550 case naclbitc::GLOBALVAR_DATA: {
482 // Defines an initializer defined by a sequence of byte values. 551 // Defines an initializer defined by a sequence of byte values.
483 if (!ProcessingGlobal || Record.size() < 1) 552 if (!ProcessingGlobal || Record.size() < 1)
484 return Reader.Error("Bad GLOBALVAR_DATA record"); 553 return Reader.Error(NaClBitcodeReader::InvalidRecord,
554 "Bad GLOBALVAR_DATA record");
485 unsigned Size = Record.size(); 555 unsigned Size = Record.size();
486 uint8_t *Buf = new uint8_t[Size]; 556 uint8_t *Buf = new uint8_t[Size];
487 assert(Buf); 557 assert(Buf);
488 for (unsigned i = 0; i < Size; ++i) 558 for (unsigned i = 0; i < Size; ++i)
489 Buf[i] = Record[i]; 559 Buf[i] = Record[i];
490 Constant *Init = ConstantDataArray::get( 560 Constant *Init = ConstantDataArray::get(
491 Context, ArrayRef<uint8_t>(Buf, Buf + Size)); 561 Context, ArrayRef<uint8_t>(Buf, Buf + Size));
492 VarInit.push_back(Init); 562 VarInit.push_back(Init);
493 delete[] Buf; 563 delete[] Buf;
494 break; 564 break;
495 } 565 }
496 case naclbitc::GLOBALVAR_RELOC: { 566 case naclbitc::GLOBALVAR_RELOC: {
497 // Define a relocation initializer. 567 // Define a relocation initializer.
498 if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2) 568 if (!ProcessingGlobal || Record.size() < 1 || Record.size() > 2)
499 return Reader.Error("Bad GLOBALVAR_RELOC record"); 569 return Reader.Error(NaClBitcodeReader::InvalidRecord,
570 "Bad GLOBALVAR_RELOC record");
500 Constant *BaseVal = cast<Constant>(ValueList[Record[0]]); 571 Constant *BaseVal = cast<Constant>(ValueList[Record[0]]);
501 Type *IntPtrType = IntegerType::get(Context, 32); 572 Type *IntPtrType = IntegerType::get(Context, 32);
502 Constant *Val = ConstantExpr::getPtrToInt(BaseVal, IntPtrType); 573 Constant *Val = ConstantExpr::getPtrToInt(BaseVal, IntPtrType);
503 if (Record.size() == 2) { 574 if (Record.size() == 2) {
504 uint32_t Addend = Record[1]; 575 uint32_t Addend = Record[1];
505 Val = ConstantExpr::getAdd(Val, ConstantInt::get(IntPtrType, 576 Val = ConstantExpr::getAdd(Val, ConstantInt::get(IntPtrType,
506 Addend)); 577 Addend));
507 } 578 }
508 VarInit.push_back(Val); 579 VarInit.push_back(Val);
509 break; 580 break;
510 } 581 }
511 case naclbitc::GLOBALVAR_COUNT: 582 case naclbitc::GLOBALVAR_COUNT:
512 if (Record.size() != 1) 583 if (Record.size() != 1)
513 return Reader.Error("Invalid global count record"); 584 return Reader.Error(NaClBitcodeReader::InvalidRecord,
585 "Invalid global count record");
514 // Note: NumGlobals should have been set in GenerateGlobalVarsPass. 586 // Note: NumGlobals should have been set in GenerateGlobalVarsPass.
515 // Fail if methods are called in wrong order. 587 // Fail if methods are called in wrong order.
516 assert(NumGlobals == Record[0]); 588 assert(NumGlobals == Record[0]);
517 break; 589 break;
518 } 590 }
519 591
520 // If more initializers needed for global variable, continue processing. 592 // If more initializers needed for global variable, continue processing.
521 if (!ProcessingGlobal || VarInit.size() < VarInitializersNeeded) 593 if (!ProcessingGlobal || VarInit.size() < VarInitializersNeeded)
522 continue; 594 continue;
523 595
524 Constant *Init = 0; 596 Constant *Init = 0;
525 switch (VarInit.size()) { 597 switch (VarInit.size()) {
526 case 0: 598 case 0:
527 return Reader.Error( 599 return Reader.Error(NaClBitcodeReader::InvalidRecord,
528 "No initializer for global variable in global vars block"); 600 "No initializer for global variable in global vars block");
529 case 1: 601 case 1:
530 Init = VarInit[0]; 602 Init = VarInit[0];
531 break; 603 break;
532 default: 604 default:
533 Init = ConstantStruct::getAnon(Context, VarInit, true); 605 Init = ConstantStruct::getAnon(Context, VarInit, true);
534 break; 606 break;
535 } 607 }
536 cast<GlobalVariable>(ValueList[NextValueNo])->setInitializer(Init); 608 cast<GlobalVariable>(ValueList[NextValueNo])->setInitializer(Init);
537 ++NextValueNo; 609 ++NextValueNo;
538 ProcessingGlobal = false; 610 ProcessingGlobal = false;
539 VarInitializersNeeded = 0; 611 VarInitializersNeeded = 0;
540 VarInit.clear(); 612 VarInit.clear();
541 } 613 }
614 return std::error_code();
542 } 615 }
543 }; 616 };
544 617
545 } // End anonymous namespace. 618 } // End anonymous namespace.
546 619
547 bool NaClBitcodeReader::ParseGlobalVars() { 620 std::error_code NaClBitcodeReader::ParseGlobalVars() {
548 if (Stream.EnterSubBlock(naclbitc::GLOBALVAR_BLOCK_ID)) 621 if (Stream.EnterSubBlock(naclbitc::GLOBALVAR_BLOCK_ID))
549 return Error("Malformed block record"); 622 return Error(InvalidRecord, "Malformed block record");
550 623
551 ParseGlobalsHandler PassHandler(*this, ValueList, Stream, Context, TheModule); 624 ParseGlobalsHandler PassHandler(*this, ValueList, Stream, Context, TheModule);
552 if (PassHandler.GenerateGlobalVarsPass()) return true; 625 if (std::error_code EC = PassHandler.GenerateGlobalVarsPass())
626 return EC;
553 return PassHandler.GenerateGlobalVarInitsPass(); 627 return PassHandler.GenerateGlobalVarInitsPass();
554 } 628 }
555 629
556 bool NaClBitcodeReader::ParseValueSymbolTable() { 630 std::error_code NaClBitcodeReader::ParseValueSymbolTable() {
557 DEBUG(dbgs() << "-> ParseValueSymbolTable\n"); 631 DEBUG(dbgs() << "-> ParseValueSymbolTable\n");
558 if (Stream.EnterSubBlock(naclbitc::VALUE_SYMTAB_BLOCK_ID)) 632 if (Stream.EnterSubBlock(naclbitc::VALUE_SYMTAB_BLOCK_ID))
559 return Error("Malformed block record"); 633 return Error(InvalidRecord, "Malformed block record");
560 634
561 SmallVector<uint64_t, 64> Record; 635 SmallVector<uint64_t, 64> Record;
562 636
563 // Read all the records for this value table. 637 // Read all the records for this value table.
564 SmallString<128> ValueName; 638 SmallString<128> ValueName;
565 while (1) { 639 while (1) {
566 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 640 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks();
567 641
568 switch (Entry.Kind) { 642 switch (Entry.Kind) {
569 case NaClBitstreamEntry::SubBlock: // Handled for us already. 643 case NaClBitstreamEntry::SubBlock: // Handled for us already.
570 case NaClBitstreamEntry::Error: 644 case NaClBitstreamEntry::Error:
571 return Error("malformed value symbol table block"); 645 return Error(MalformedBlock, "malformed value symbol table block");
572 case NaClBitstreamEntry::EndBlock: 646 case NaClBitstreamEntry::EndBlock:
573 DEBUG(dbgs() << "<- ParseValueSymbolTable\n"); 647 DEBUG(dbgs() << "<- ParseValueSymbolTable\n");
574 return false; 648 return std::error_code();
575 case NaClBitstreamEntry::Record: 649 case NaClBitstreamEntry::Record:
576 // The interesting case. 650 // The interesting case.
577 break; 651 break;
578 } 652 }
579 653
580 // Read a record. 654 // Read a record.
581 Record.clear(); 655 Record.clear();
582 switch (Stream.readRecord(Entry.ID, Record)) { 656 switch (Stream.readRecord(Entry.ID, Record)) {
583 default: // Default behavior: unknown type. 657 default: // Default behavior: unknown type.
584 break; 658 break;
585 case naclbitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 659 case naclbitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
586 if (ConvertToString(Record, 1, ValueName)) 660 if (ConvertToString(Record, 1, ValueName))
587 return Error("Invalid VST_ENTRY record"); 661 return Error(InvalidRecord, "Invalid VST_ENTRY record");
588 unsigned ValueID = Record[0]; 662 unsigned ValueID = Record[0];
589 if (ValueID >= ValueList.size()) 663 if (ValueID >= ValueList.size())
590 return Error("Invalid Value ID in VST_ENTRY record"); 664 return Error(InvalidValue, "Invalid Value ID in VST_ENTRY record");
591 Value *V = ValueList[ValueID]; 665 Value *V = ValueList[ValueID];
592 666
593 V->setName(StringRef(ValueName.data(), ValueName.size())); 667 V->setName(StringRef(ValueName.data(), ValueName.size()));
594 ValueName.clear(); 668 ValueName.clear();
595 break; 669 break;
596 } 670 }
597 case naclbitc::VST_CODE_BBENTRY: { 671 case naclbitc::VST_CODE_BBENTRY: {
598 if (ConvertToString(Record, 1, ValueName)) 672 if (ConvertToString(Record, 1, ValueName))
599 return Error("Invalid VST_BBENTRY record"); 673 return Error(InvalidRecord, "Invalid VST_BBENTRY record");
600 BasicBlock *BB = getBasicBlock(Record[0]); 674 BasicBlock *BB = getBasicBlock(Record[0]);
601 if (BB == 0) 675 if (BB == 0)
602 return Error("Invalid BB ID in VST_BBENTRY record"); 676 return Error(InvalidValue, "Invalid BB ID in VST_BBENTRY record");
603 677
604 BB->setName(StringRef(ValueName.data(), ValueName.size())); 678 BB->setName(StringRef(ValueName.data(), ValueName.size()));
605 ValueName.clear(); 679 ValueName.clear();
606 break; 680 break;
607 } 681 }
608 } 682 }
609 } 683 }
610 } 684 }
611 685
612 bool NaClBitcodeReader::ParseConstants() { 686 std::error_code NaClBitcodeReader::ParseConstants() {
613 DEBUG(dbgs() << "-> ParseConstants\n"); 687 DEBUG(dbgs() << "-> ParseConstants\n");
614 if (Stream.EnterSubBlock(naclbitc::CONSTANTS_BLOCK_ID)) 688 if (Stream.EnterSubBlock(naclbitc::CONSTANTS_BLOCK_ID))
615 return Error("Malformed block record"); 689 return Error(InvalidRecord, "Malformed block record");
616 690
617 SmallVector<uint64_t, 64> Record; 691 SmallVector<uint64_t, 64> Record;
618 692
619 // Read all the records for this value table. 693 // Read all the records for this value table.
620 Type *CurTy = Type::getInt32Ty(Context); 694 Type *CurTy = Type::getInt32Ty(Context);
621 unsigned NextCstNo = ValueList.size(); 695 unsigned NextCstNo = ValueList.size();
622 while (1) { 696 while (1) {
623 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 697 NaClBitstreamEntry Entry = Stream.advanceSkippingSubblocks();
624 698
625 switch (Entry.Kind) { 699 switch (Entry.Kind) {
626 case NaClBitstreamEntry::SubBlock: // Handled for us already. 700 case NaClBitstreamEntry::SubBlock: // Handled for us already.
627 case NaClBitstreamEntry::Error: 701 case NaClBitstreamEntry::Error:
628 return Error("malformed block record in AST file"); 702 return Error(MalformedBlock, "malformed block record in AST file");
629 case NaClBitstreamEntry::EndBlock: 703 case NaClBitstreamEntry::EndBlock:
630 if (NextCstNo != ValueList.size()) 704 if (NextCstNo != ValueList.size())
631 return Error("Invalid constant reference!"); 705 return Error(InvalidConstantReference,
706 "Invalid constant reference!");
632 DEBUG(dbgs() << "<- ParseConstants\n"); 707 DEBUG(dbgs() << "<- ParseConstants\n");
633 return false; 708 return std::error_code();
634 case NaClBitstreamEntry::Record: 709 case NaClBitstreamEntry::Record:
635 // The interesting case. 710 // The interesting case.
636 break; 711 break;
637 } 712 }
638 713
639 // Read a record. 714 // Read a record.
640 Record.clear(); 715 Record.clear();
641 Value *V = 0; 716 Value *V = 0;
642 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 717 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
643 switch (BitCode) { 718 switch (BitCode) {
644 default: { 719 default: {
645 std::string Message; 720 std::string Message;
646 raw_string_ostream StrM(Message); 721 raw_string_ostream StrM(Message);
647 StrM << "Invalid Constant code: " << BitCode; 722 StrM << "Invalid Constant code: " << BitCode;
648 StrM.flush(); 723 StrM.flush();
649 return Error(Message); 724 return Error(InvalidValue, Message);
650 } 725 }
651 case naclbitc::CST_CODE_UNDEF: // UNDEF 726 case naclbitc::CST_CODE_UNDEF: // UNDEF
652 V = UndefValue::get(CurTy); 727 V = UndefValue::get(CurTy);
653 break; 728 break;
654 case naclbitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 729 case naclbitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
655 if (Record.empty()) 730 if (Record.empty())
656 return Error("Malformed CST_SETTYPE record"); 731 return Error(NaClBitcodeReader::InvalidRecord,
732 "Malformed CST_SETTYPE record");
657 if (Record[0] >= TypeList.size()) 733 if (Record[0] >= TypeList.size())
658 return Error("Invalid Type ID in CST_SETTYPE record"); 734 return Error(NaClBitcodeReader::InvalidType,
735 "Invalid Type ID in CST_SETTYPE record");
659 CurTy = TypeList[Record[0]]; 736 CurTy = TypeList[Record[0]];
660 continue; // Skip the ValueList manipulation. 737 continue; // Skip the ValueList manipulation.
661 case naclbitc::CST_CODE_INTEGER: // INTEGER: [intval] 738 case naclbitc::CST_CODE_INTEGER: // INTEGER: [intval]
662 if (!CurTy->isIntegerTy() || Record.empty()) 739 if (!CurTy->isIntegerTy() || Record.empty())
663 return Error("Invalid CST_INTEGER record"); 740 return Error(InvalidRecord, "Invalid CST_INTEGER record");
664 V = ConstantInt::get(CurTy, NaClDecodeSignRotatedValue(Record[0])); 741 V = ConstantInt::get(CurTy, NaClDecodeSignRotatedValue(Record[0]));
665 break; 742 break;
666 case naclbitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 743 case naclbitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
667 if (Record.empty()) 744 if (Record.empty())
668 return Error("Invalid FLOAT record"); 745 return Error(NaClBitcodeReader::InvalidRecord, "Invalid FLOAT record");
669 if (CurTy->isFloatTy()) 746 if (CurTy->isFloatTy())
670 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 747 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
671 APInt(32, (uint32_t)Record[0]))); 748 APInt(32, (uint32_t)Record[0])));
672 else if (CurTy->isDoubleTy()) 749 else if (CurTy->isDoubleTy())
673 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 750 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
674 APInt(64, Record[0]))); 751 APInt(64, Record[0])));
675 else 752 else
676 return Error("Unknown type for FLOAT record"); 753 return Error(NaClBitcodeReader::InvalidRecord,
754 "Unknown type for FLOAT record");
677 break; 755 break;
678 } 756 }
679 } 757 }
680 758
681 ValueList.AssignValue(V, NextCstNo); 759 ValueList.AssignValue(V, NextCstNo);
682 ++NextCstNo; 760 ++NextCstNo;
683 } 761 }
762 return std::error_code();
684 } 763 }
685 764
686 /// RememberAndSkipFunctionBody - When we see the block for a function body, 765 /// RememberAndSkipFunctionBody - When we see the block for a function body,
687 /// remember where it is and then skip it. This lets us lazily deserialize the 766 /// remember where it is and then skip it. This lets us lazily deserialize the
688 /// functions. 767 /// functions.
689 bool NaClBitcodeReader::RememberAndSkipFunctionBody() { 768 std::error_code NaClBitcodeReader::RememberAndSkipFunctionBody() {
690 DEBUG(dbgs() << "-> RememberAndSkipFunctionBody\n"); 769 DEBUG(dbgs() << "-> RememberAndSkipFunctionBody\n");
691 // Get the function we are talking about. 770 // Get the function we are talking about.
692 if (FunctionsWithBodies.empty()) 771 if (FunctionsWithBodies.empty())
693 return Error("Insufficient function protos"); 772 return Error(InsufficientFunctionProtos,
773 "Insufficient function protos");
694 774
695 Function *Fn = FunctionsWithBodies.back(); 775 Function *Fn = FunctionsWithBodies.back();
696 FunctionsWithBodies.pop_back(); 776 FunctionsWithBodies.pop_back();
697 777
698 // Save the current stream state. 778 // Save the current stream state.
699 uint64_t CurBit = Stream.GetCurrentBitNo(); 779 uint64_t CurBit = Stream.GetCurrentBitNo();
700 DeferredFunctionInfo[Fn] = CurBit; 780 DeferredFunctionInfo[Fn] = CurBit;
701 781
702 // Skip over the function block for now. 782 // Skip over the function block for now.
703 if (Stream.SkipBlock()) 783 if (Stream.SkipBlock())
704 return Error("Malformed block record"); 784 return Error(InvalidSkippedBlock, "Unable to skip function block.");
705 DEBUG(dbgs() << "<- RememberAndSkipFunctionBody\n"); 785 DEBUG(dbgs() << "<- RememberAndSkipFunctionBody\n");
706 return false; 786 return std::error_code();
707 } 787 }
708 788
709 bool NaClBitcodeReader::GlobalCleanup() { 789 std::error_code NaClBitcodeReader::GlobalCleanup() {
710 // Look for intrinsic functions which need to be upgraded at some point 790 // Look for intrinsic functions which need to be upgraded at some point
711 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 791 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
712 FI != FE; ++FI) { 792 FI != FE; ++FI) {
713 Function *NewFn; 793 Function *NewFn;
714 if (UpgradeIntrinsicFunction(FI, NewFn)) 794 if (UpgradeIntrinsicFunction(FI, NewFn))
715 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 795 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
716 } 796 }
717 797
718 // Look for global variables which need to be renamed. 798 // Look for global variables which need to be renamed.
719 for (Module::global_iterator 799 for (Module::global_iterator
720 GI = TheModule->global_begin(), GE = TheModule->global_end(); 800 GI = TheModule->global_begin(), GE = TheModule->global_end();
721 GI != GE; ++GI) 801 GI != GE; ++GI)
722 UpgradeGlobalVariable(GI); 802 UpgradeGlobalVariable(GI);
723 return false; 803 return std::error_code();
724 } 804 }
725 805
726 FunctionType *NaClBitcodeReader::AddPointerTypesToIntrinsicType( 806 FunctionType *NaClBitcodeReader::AddPointerTypesToIntrinsicType(
727 StringRef Name, FunctionType *FTy) { 807 StringRef Name, FunctionType *FTy) {
728 FunctionType *IntrinsicTy = AllowedIntrinsics.getIntrinsicType(Name); 808 FunctionType *IntrinsicTy = AllowedIntrinsics.getIntrinsicType(Name);
729 if (IntrinsicTy == 0) return FTy; 809 if (IntrinsicTy == 0) return FTy;
730 810
731 Type *IReturnTy = IntrinsicTy->getReturnType(); 811 Type *IReturnTy = IntrinsicTy->getReturnType();
732 Type *FReturnTy = FTy->getReturnType(); 812 Type *FReturnTy = FTy->getReturnType();
733 813
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
770 Function *NewIntrinsic = Function::Create( 850 Function *NewIntrinsic = Function::Create(
771 ITy, GlobalValue::ExternalLinkage, "", TheModule); 851 ITy, GlobalValue::ExternalLinkage, "", TheModule);
772 NewIntrinsic->takeName(Func); 852 NewIntrinsic->takeName(Func);
773 ValueList.OverwriteValue(NewIntrinsic, Index); 853 ValueList.OverwriteValue(NewIntrinsic, Index);
774 Func->eraseFromParent(); 854 Func->eraseFromParent();
775 } 855 }
776 } 856 }
777 } 857 }
778 } 858 }
779 859
780 bool NaClBitcodeReader::ParseModule(bool Resume) { 860 std::error_code NaClBitcodeReader::ParseModule(bool Resume) {
781 DEBUG(dbgs() << "-> ParseModule\n"); 861 DEBUG(dbgs() << "-> ParseModule\n");
782 if (Resume) 862 if (Resume)
783 Stream.JumpToBit(NextUnreadBit); 863 Stream.JumpToBit(NextUnreadBit);
784 else if (Stream.EnterSubBlock(naclbitc::MODULE_BLOCK_ID)) 864 else if (Stream.EnterSubBlock(naclbitc::MODULE_BLOCK_ID))
785 return Error("Malformed block record"); 865 return Error(InvalidRecord, "Malformed block record");
786 866
787 SmallVector<uint64_t, 64> Record; 867 SmallVector<uint64_t, 64> Record;
788 868
789 // Read all the records for this module. 869 // Read all the records for this module.
790 while (1) { 870 while (1) {
791 NaClBitstreamEntry Entry = Stream.advance(0, 0); 871 NaClBitstreamEntry Entry = Stream.advance(0, 0);
792 872
793 switch (Entry.Kind) { 873 switch (Entry.Kind) {
794 case NaClBitstreamEntry::Error: 874 case NaClBitstreamEntry::Error:
795 Error("malformed module block"); 875 return Error(MalformedBlock, "malformed module block");
796 return true;
797 case NaClBitstreamEntry::EndBlock: 876 case NaClBitstreamEntry::EndBlock:
798 DEBUG(dbgs() << "<- ParseModule\n"); 877 DEBUG(dbgs() << "<- ParseModule\n");
799 return GlobalCleanup(); 878 return GlobalCleanup();
800 879
801 case NaClBitstreamEntry::SubBlock: 880 case NaClBitstreamEntry::SubBlock:
802 switch (Entry.ID) { 881 switch (Entry.ID) {
803 default: { 882 default: {
804 std::string Message; 883 std::string Message;
805 raw_string_ostream StrM(Message); 884 raw_string_ostream StrM(Message);
806 StrM << "Unknown block ID: " << Entry.ID; 885 StrM << "Unknown block ID: " << Entry.ID;
807 return Error(StrM.str()); 886 return Error(InvalidRecord, StrM.str());
808 } 887 }
809 case naclbitc::BLOCKINFO_BLOCK_ID: 888 case naclbitc::BLOCKINFO_BLOCK_ID:
810 if (Stream.ReadBlockInfoBlock(0)) 889 if (Stream.ReadBlockInfoBlock(0))
811 return Error("Malformed BlockInfoBlock"); 890 return Error(MalformedBlock, "Malformed BlockInfoBlock");
812 break; 891 break;
813 case naclbitc::TYPE_BLOCK_ID_NEW: 892 case naclbitc::TYPE_BLOCK_ID_NEW:
814 if (ParseTypeTable()) 893 if (std::error_code EC = ParseTypeTable())
815 return true; 894 return EC;
816 break; 895 break;
817 case naclbitc::GLOBALVAR_BLOCK_ID: 896 case naclbitc::GLOBALVAR_BLOCK_ID:
818 if (ParseGlobalVars()) 897 if (std::error_code EC = ParseGlobalVars())
819 return true; 898 return EC;
820 break; 899 break;
821 case naclbitc::VALUE_SYMTAB_BLOCK_ID: 900 case naclbitc::VALUE_SYMTAB_BLOCK_ID:
822 if (ParseValueSymbolTable()) 901 if (std::error_code EC = ParseValueSymbolTable())
823 return true; 902 return EC;
824 SeenValueSymbolTable = true; 903 SeenValueSymbolTable = true;
825 // Now that we know the names of the intrinsics, we can add 904 // Now that we know the names of the intrinsics, we can add
826 // pointer types to the intrinsic declarations' types. 905 // pointer types to the intrinsic declarations' types.
827 AddPointerTypesToIntrinsicParams(); 906 AddPointerTypesToIntrinsicParams();
828 break; 907 break;
829 case naclbitc::FUNCTION_BLOCK_ID: 908 case naclbitc::FUNCTION_BLOCK_ID:
830 // If this is the first function body we've seen, reverse the 909 // If this is the first function body we've seen, reverse the
831 // FunctionsWithBodies list. 910 // FunctionsWithBodies list.
832 if (!SeenFirstFunctionBody) { 911 if (!SeenFirstFunctionBody) {
833 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 912 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
834 if (GlobalCleanup()) 913 if (std::error_code EC = GlobalCleanup())
835 return true; 914 return EC;
836 SeenFirstFunctionBody = true; 915 SeenFirstFunctionBody = true;
837 } 916 }
838 917
839 if (RememberAndSkipFunctionBody()) 918 if (std::error_code EC = RememberAndSkipFunctionBody())
840 return true; 919 return EC;
841 920
842 // For streaming bitcode, suspend parsing when we reach the function 921 // For streaming bitcode, suspend parsing when we reach the function
843 // bodies. Subsequent materialization calls will resume it when 922 // bodies. Subsequent materialization calls will resume it when
844 // necessary. For streaming, the function bodies must be at the end of 923 // necessary. For streaming, the function bodies must be at the end of
845 // the bitcode. If the bitcode file is old, the symbol table will be 924 // the bitcode. If the bitcode file is old, the symbol table will be
846 // at the end instead and will not have been seen yet. In this case, 925 // at the end instead and will not have been seen yet. In this case,
847 // just finish the parse now. 926 // just finish the parse now.
848 if (LazyStreamer && SeenValueSymbolTable) { 927 if (LazyStreamer && SeenValueSymbolTable) {
849 NextUnreadBit = Stream.GetCurrentBitNo(); 928 NextUnreadBit = Stream.GetCurrentBitNo();
850 DEBUG(dbgs() << "<- ParseModule\n"); 929 DEBUG(dbgs() << "<- ParseModule\n");
851 return false; 930 return std::error_code();
852 } 931 }
853 break; 932 break;
854 } 933 }
855 continue; 934 continue;
856 935
857 case NaClBitstreamEntry::Record: 936 case NaClBitstreamEntry::Record:
858 // The interesting case. 937 // The interesting case.
859 break; 938 break;
860 } 939 }
861 940
862 // Read a record. 941 // Read a record.
863 unsigned Selector = Stream.readRecord(Entry.ID, Record); 942 unsigned Selector = Stream.readRecord(Entry.ID, Record);
864 switch (Selector) { 943 switch (Selector) {
865 default: { 944 default: {
866 std::string Message; 945 std::string Message;
867 raw_string_ostream StrM(Message); 946 raw_string_ostream StrM(Message);
868 StrM << "Invalid MODULE_CODE: " << Selector; 947 StrM << "Invalid MODULE_CODE: " << Selector;
869 StrM.flush(); 948 StrM.flush();
870 return Error(Message); 949 return Error(InvalidValue, Message);
871 } 950 }
872 case naclbitc::MODULE_CODE_VERSION: { // VERSION: [version#] 951 case naclbitc::MODULE_CODE_VERSION: { // VERSION: [version#]
873 if (Record.size() < 1) 952 if (Record.size() < 1)
874 return Error("Malformed MODULE_CODE_VERSION"); 953 return Error(InvalidRecord, "Malformed MODULE_CODE_VERSION");
875 // Only version #1 is supported for PNaCl. Version #0 is not supported. 954 // Only version #1 is supported for PNaCl. Version #0 is not supported.
876 unsigned module_version = Record[0]; 955 unsigned module_version = Record[0];
877 if (module_version != 1) 956 if (module_version != 1)
878 return Error("Unknown bitstream version!"); 957 return Error(InvalidValue, "Unknown bitstream version!");
879 break; 958 break;
880 } 959 }
881 // FUNCTION: [type, callingconv, isproto, linkage] 960 // FUNCTION: [type, callingconv, isproto, linkage]
882 case naclbitc::MODULE_CODE_FUNCTION: { 961 case naclbitc::MODULE_CODE_FUNCTION: {
883 if (Record.size() < 4) 962 if (Record.size() < 4)
884 return Error("Invalid MODULE_CODE_FUNCTION record"); 963 return Error(InvalidRecord, "Invalid MODULE_CODE_FUNCTION record");
885 Type *Ty = getTypeByID(Record[0]); 964 Type *Ty = getTypeByID(Record[0]);
886 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record"); 965 if (!Ty)
966 return Error(InvalidType, "Invalid MODULE_CODE_FUNCTION record");
887 FunctionType *FTy = dyn_cast<FunctionType>(Ty); 967 FunctionType *FTy = dyn_cast<FunctionType>(Ty);
888 if (!FTy) 968 if (!FTy)
889 return Error("Function not declared with a function type!"); 969 return Error(InvalidType,
970 "Function not declared with a function type!");
890 971
891 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 972 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
892 "", TheModule); 973 "", TheModule);
893 974
894 CallingConv::ID CallingConv; 975 CallingConv::ID CallingConv;
895 if (!naclbitc::DecodeCallingConv(Record[1], CallingConv)) 976 if (!naclbitc::DecodeCallingConv(Record[1], CallingConv))
896 return Error("PNaCl bitcode contains invalid calling conventions."); 977 return Error(InvalidValue,
978 "PNaCl bitcode contains invalid calling conventions.");
897 Func->setCallingConv(CallingConv); 979 Func->setCallingConv(CallingConv);
898 bool isProto = Record[2]; 980 bool isProto = Record[2];
899 GlobalValue::LinkageTypes Linkage; 981 GlobalValue::LinkageTypes Linkage;
900 if (!naclbitc::DecodeLinkage(Record[3], Linkage)) 982 if (!naclbitc::DecodeLinkage(Record[3], Linkage))
901 return Error("Unknown linkage type"); 983 return Error(InvalidValue, "Unknown linkage type");
902 Func->setLinkage(Linkage); 984 Func->setLinkage(Linkage);
903 ValueList.push_back(Func); 985 ValueList.push_back(Func);
904 986
905 // If this is a function with a body, remember the prototype we are 987 // If this is a function with a body, remember the prototype we are
906 // creating now, so that we can match up the body with them later. 988 // creating now, so that we can match up the body with them later.
907 if (!isProto) { 989 if (!isProto) {
908 FunctionsWithBodies.push_back(Func); 990 FunctionsWithBodies.push_back(Func);
909 if (LazyStreamer) DeferredFunctionInfo[Func] = 0; 991 if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
910 } 992 }
911 break; 993 break;
912 } 994 }
913 } 995 }
914 Record.clear(); 996 Record.clear();
915 } 997 }
998 return std::error_code();
916 } 999 }
917 1000
918 const char *llvm::PNaClDataLayout = 1001 const char *llvm::PNaClDataLayout =
919 "e-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-" 1002 "e-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"
920 "f32:32:32-f64:64:64-p:32:32:32-v128:32:32"; 1003 "f32:32:32-f64:64:64-p:32:32:32-v128:32:32";
921 1004
922 bool NaClBitcodeReader::ParseBitcodeInto(Module *M) { 1005 std::error_code NaClBitcodeReader::ParseBitcodeInto(Module *M) {
923 TheModule = 0; 1006 TheModule = 0;
924 1007
925 // PNaCl does not support different DataLayouts in pexes, so we 1008 // PNaCl does not support different DataLayouts in pexes, so we
926 // implicitly set the DataLayout to the following default. 1009 // implicitly set the DataLayout to the following default.
927 // 1010 //
928 // This is not usually needed by the backend, but it might be used 1011 // This is not usually needed by the backend, but it might be used
929 // by IR passes that the PNaCl translator runs. We set this in the 1012 // by IR passes that the PNaCl translator runs. We set this in the
930 // reader rather than in pnacl-llc so that 'opt' will also use the 1013 // reader rather than in pnacl-llc so that 'opt' will also use the
931 // correct DataLayout if it is run on a pexe. 1014 // correct DataLayout if it is run on a pexe.
932 M->setDataLayout(PNaClDataLayout); 1015 M->setDataLayout(PNaClDataLayout);
933 1016
934 if (InitStream()) return true; // InitSream will set the error string. 1017 if (std::error_code EC = InitStream())
1018 return EC;
935 1019
936 // We expect a number of well-defined blocks, though we don't necessarily 1020 // We expect a number of well-defined blocks, though we don't necessarily
937 // need to understand them all. 1021 // need to understand them all.
938 while (1) { 1022 while (1) {
939 if (Stream.AtEndOfStream()) 1023 if (Stream.AtEndOfStream())
940 return false; 1024 return std::error_code();
941 1025
942 NaClBitstreamEntry Entry = 1026 NaClBitstreamEntry Entry =
943 Stream.advance(NaClBitstreamCursor::AF_DontAutoprocessAbbrevs, 0); 1027 Stream.advance(NaClBitstreamCursor::AF_DontAutoprocessAbbrevs, 0);
944 1028
945 switch (Entry.Kind) { 1029 switch (Entry.Kind) {
946 case NaClBitstreamEntry::Error: 1030 case NaClBitstreamEntry::Error:
947 Error("malformed module file"); 1031 return Error(MalformedBlock, "malformed module file");
948 return true;
949 case NaClBitstreamEntry::EndBlock: 1032 case NaClBitstreamEntry::EndBlock:
950 return false; 1033 return std::error_code();
951 1034
952 case NaClBitstreamEntry::SubBlock: 1035 case NaClBitstreamEntry::SubBlock:
953 switch (Entry.ID) { 1036 switch (Entry.ID) {
954 case naclbitc::BLOCKINFO_BLOCK_ID: 1037 case naclbitc::BLOCKINFO_BLOCK_ID:
955 if (Stream.ReadBlockInfoBlock(0)) 1038 if (Stream.ReadBlockInfoBlock(0))
956 return Error("Malformed BlockInfoBlock"); 1039 return Error(MalformedBlock, "Malformed BlockInfoBlock");
957 break; 1040 break;
958 case naclbitc::MODULE_BLOCK_ID: 1041 case naclbitc::MODULE_BLOCK_ID:
959 // Reject multiple MODULE_BLOCK's in a single bitstream. 1042 // Reject multiple MODULE_BLOCK's in a single bitstream.
960 if (TheModule) 1043 if (TheModule)
961 return Error("Multiple MODULE_BLOCKs in same stream"); 1044 return Error(InvalidMultipleBlocks,
1045 "Multiple MODULE_BLOCKs in same stream");
962 TheModule = M; 1046 TheModule = M;
963 if (ParseModule(false)) 1047 if (std::error_code EC = ParseModule(false))
964 return true; 1048 return EC;
965 if (LazyStreamer) return false; 1049 if (LazyStreamer)
1050 return std::error_code();
966 break; 1051 break;
967 default: 1052 default:
968 if (Stream.SkipBlock()) 1053 if (Stream.SkipBlock())
969 return Error("Malformed block record"); 1054 return Error(InvalidSkippedBlock,
1055 "Unable to skip unknown top-level block");
970 break; 1056 break;
971 } 1057 }
972 continue; 1058 continue;
973 case NaClBitstreamEntry::Record: 1059 case NaClBitstreamEntry::Record:
974 // There should be no records in the top-level of blocks. 1060 // There should be no records in the top-level of blocks.
975 return Error("Invalid record at top-level"); 1061 return Error(InvalidRecord, "Invalid record at top-level");
976 } 1062 }
977 } 1063 }
978 } 1064 }
979 1065
980 // Returns true if error occured installing I into BB. 1066 // Returns true if error occured installing I into BB.
981 bool NaClBitcodeReader::InstallInstruction( 1067 std::error_code NaClBitcodeReader::InstallInstruction(
982 BasicBlock *BB, Instruction *I) { 1068 BasicBlock *BB, Instruction *I) {
983 // Add instruction to end of current BB. If there is no current BB, reject 1069 // Add instruction to end of current BB. If there is no current BB, reject
984 // this file. 1070 // this file.
985 if (BB == 0) { 1071 if (BB == 0) {
986 delete I; 1072 delete I;
987 return Error("Invalid instruction with no BB"); 1073 return Error(InvalidInstructionWithNoBB,
1074 "Instruction with no BB, can't install");
988 } 1075 }
989 BB->getInstList().push_back(I); 1076 BB->getInstList().push_back(I);
990 return false; 1077 return std::error_code();
991 } 1078 }
992 1079
993 CastInst * 1080 CastInst *
994 NaClBitcodeReader::CreateCast(unsigned BBIndex, Instruction::CastOps Op, 1081 NaClBitcodeReader::CreateCast(unsigned BBIndex, Instruction::CastOps Op,
995 Type *CT, Value *V, bool DeferInsertion) { 1082 Type *CT, Value *V, bool DeferInsertion) {
996 if (BBIndex >= FunctionBBs.size()) 1083 if (BBIndex >= FunctionBBs.size())
997 report_fatal_error("CreateCast on unknown basic block"); 1084 report_fatal_error("CreateCast on unknown basic block");
998 BasicBlockInfo &BBInfo = FunctionBBs[BBIndex]; 1085 BasicBlockInfo &BBInfo = FunctionBBs[BBIndex];
999 NaClBitcodeReaderCast ModeledCast(Op, CT, V); 1086 NaClBitcodeReaderCast ModeledCast(Op, CT, V);
1000 CastInst *Cast = BBInfo.CastMap[ModeledCast]; 1087 CastInst *Cast = BBInfo.CastMap[ModeledCast];
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
1035 return CreateCast(BBIndex, Instruction::IntToPtr, T, Op); 1122 return CreateCast(BBIndex, Instruction::IntToPtr, T, Op);
1036 } 1123 }
1037 1124
1038 std::string Message; 1125 std::string Message;
1039 raw_string_ostream StrM(Message); 1126 raw_string_ostream StrM(Message);
1040 StrM << "Can't convert " << *Op << " to type " << *T << "\n"; 1127 StrM << "Can't convert " << *Op << " to type " << *T << "\n";
1041 report_fatal_error(StrM.str()); 1128 report_fatal_error(StrM.str());
1042 } 1129 }
1043 1130
1044 /// ParseFunctionBody - Lazily parse the specified function body block. 1131 /// ParseFunctionBody - Lazily parse the specified function body block.
1045 bool NaClBitcodeReader::ParseFunctionBody(Function *F) { 1132 std::error_code NaClBitcodeReader::ParseFunctionBody(Function *F) {
1046 DEBUG(dbgs() << "-> ParseFunctionBody\n"); 1133 DEBUG(dbgs() << "-> ParseFunctionBody\n");
1047 if (Stream.EnterSubBlock(naclbitc::FUNCTION_BLOCK_ID)) 1134 if (Stream.EnterSubBlock(naclbitc::FUNCTION_BLOCK_ID))
1048 return Error("Malformed block record"); 1135 return Error(InvalidRecord, "Malformed block record");
1049 1136
1050 unsigned ModuleValueListSize = ValueList.size(); 1137 unsigned ModuleValueListSize = ValueList.size();
1051 1138
1052 // Add all the function arguments to the value table. 1139 // Add all the function arguments to the value table.
1053 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 1140 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1054 ValueList.push_back(I); 1141 ValueList.push_back(I);
1055 1142
1056 unsigned NextValueNo = ValueList.size(); 1143 unsigned NextValueNo = ValueList.size();
1057 BasicBlock *CurBB = 0; 1144 BasicBlock *CurBB = 0;
1058 unsigned CurBBNo = 0; 1145 unsigned CurBBNo = 0;
1059 1146
1060 // Read all the records. 1147 // Read all the records.
1061 SmallVector<uint64_t, 64> Record; 1148 SmallVector<uint64_t, 64> Record;
1062 while (1) { 1149 while (1) {
1063 NaClBitstreamEntry Entry = Stream.advance(0, 0); 1150 NaClBitstreamEntry Entry = Stream.advance(0, 0);
1064 1151
1065 switch (Entry.Kind) { 1152 switch (Entry.Kind) {
1066 case NaClBitstreamEntry::Error: 1153 case NaClBitstreamEntry::Error:
1067 return Error("Bitcode error in function block"); 1154 return Error(MalformedBlock, "Bitcode error in function block");
1068 case NaClBitstreamEntry::EndBlock: 1155 case NaClBitstreamEntry::EndBlock:
1069 goto OutOfRecordLoop; 1156 goto OutOfRecordLoop;
1070 1157
1071 case NaClBitstreamEntry::SubBlock: 1158 case NaClBitstreamEntry::SubBlock:
1072 switch (Entry.ID) { 1159 switch (Entry.ID) {
1073 default: // Skip unknown content. 1160 default: // Skip unknown content.
1074 dbgs() << "default skip block\n";
1075 if (Stream.SkipBlock()) 1161 if (Stream.SkipBlock())
1076 return Error("Malformed block record"); 1162 return Error(InvalidSkippedBlock,
1163 "Unable to skip unknown block in function block");
1077 break; 1164 break;
1078 case naclbitc::CONSTANTS_BLOCK_ID: 1165 case naclbitc::CONSTANTS_BLOCK_ID:
1079 if (ParseConstants()) 1166 if (std::error_code EC = ParseConstants())
1080 return true; 1167 return EC;
1081 NextValueNo = ValueList.size(); 1168 NextValueNo = ValueList.size();
1082 break; 1169 break;
1083 case naclbitc::VALUE_SYMTAB_BLOCK_ID: 1170 case naclbitc::VALUE_SYMTAB_BLOCK_ID:
1084 if (PNaClAllowLocalSymbolTables) { 1171 if (PNaClAllowLocalSymbolTables) {
1085 if (ParseValueSymbolTable()) 1172 if (std::error_code EC = ParseValueSymbolTable())
1086 return true; 1173 return EC;
1087 } else { 1174 } else {
1088 return Error("Local value symbol tables not allowed"); 1175 return Error(InvalidRecord, "Local value symbol tables not allowed");
1089 } 1176 }
1090 break; 1177 break;
1091 } 1178 }
1092 continue; 1179 continue;
1093 1180
1094 case NaClBitstreamEntry::Record: 1181 case NaClBitstreamEntry::Record:
1095 // The interesting case. 1182 // The interesting case.
1096 break; 1183 break;
1097 } 1184 }
1098 1185
1099 // Read a record. 1186 // Read a record.
1100 Record.clear(); 1187 Record.clear();
1101 Instruction *I = 0; 1188 Instruction *I = 0;
1102 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1189 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1103 switch (BitCode) { 1190 switch (BitCode) {
1104 default: {// Default behavior: reject 1191 default: {// Default behavior: reject
1105 std::string Message; 1192 std::string Message;
1106 raw_string_ostream StrM(Message); 1193 raw_string_ostream StrM(Message);
1107 StrM << "Unknown instruction record: <" << BitCode; 1194 StrM << "Unknown instruction record: <" << BitCode;
1108 for (unsigned I = 0, E = Record.size(); I != E; ++I) { 1195 for (unsigned I = 0, E = Record.size(); I != E; ++I) {
1109 StrM << " " << Record[I]; 1196 StrM << " " << Record[I];
1110 } 1197 }
1111 StrM << ">"; 1198 StrM << ">";
1112 return Error(StrM.str()); 1199 return Error(InvalidRecord, StrM.str());
1113 } 1200 }
1114 1201
1115 case naclbitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 1202 case naclbitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1116 if (Record.size() != 1 || Record[0] == 0) 1203 if (Record.size() != 1 || Record[0] == 0)
1117 return Error("Invalid DECLAREBLOCKS record"); 1204 return Error(InvalidRecord, "Invalid DECLAREBLOCKS record");
1118 // Create all the basic blocks for the function. 1205 // Create all the basic blocks for the function.
1119 FunctionBBs.resize(Record[0]); 1206 FunctionBBs.resize(Record[0]);
1120 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) { 1207 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) {
1121 BasicBlockInfo &BBInfo = FunctionBBs[i]; 1208 BasicBlockInfo &BBInfo = FunctionBBs[i];
1122 BBInfo.BB = BasicBlock::Create(Context, "", F); 1209 BBInfo.BB = BasicBlock::Create(Context, "", F);
1123 } 1210 }
1124 CurBB = FunctionBBs.at(0).BB; 1211 CurBB = FunctionBBs.at(0).BB;
1125 continue; 1212 continue;
1126 1213
1127 case naclbitc::FUNC_CODE_INST_BINOP: { 1214 case naclbitc::FUNC_CODE_INST_BINOP: {
1128 // BINOP: [opval, opval, opcode[, flags]] 1215 // BINOP: [opval, opval, opcode[, flags]]
1129 // Note: Only old PNaCl bitcode files may contain flags. If 1216 // Note: Only old PNaCl bitcode files may contain flags. If
1130 // they are found, we ignore them. 1217 // they are found, we ignore them.
1131 unsigned OpNum = 0; 1218 unsigned OpNum = 0;
1132 Value *LHS, *RHS; 1219 Value *LHS, *RHS;
1133 if (popValue(Record, &OpNum, NextValueNo, &LHS) || 1220 if (popValue(Record, &OpNum, NextValueNo, &LHS) ||
1134 popValue(Record, &OpNum, NextValueNo, &RHS) || 1221 popValue(Record, &OpNum, NextValueNo, &RHS) ||
1135 OpNum+1 > Record.size()) 1222 OpNum+1 > Record.size())
1136 return Error("Invalid BINOP record"); 1223 return Error(InvalidRecord, "Invalid BINOP record");
1137 1224
1138 LHS = ConvertOpToScalar(LHS, CurBBNo); 1225 LHS = ConvertOpToScalar(LHS, CurBBNo);
1139 RHS = ConvertOpToScalar(RHS, CurBBNo); 1226 RHS = ConvertOpToScalar(RHS, CurBBNo);
1140 1227
1141 Instruction::BinaryOps Opc; 1228 Instruction::BinaryOps Opc;
1142 if (!naclbitc::DecodeBinaryOpcode(Record[OpNum++], LHS->getType(), Opc)) 1229 if (!naclbitc::DecodeBinaryOpcode(Record[OpNum++], LHS->getType(), Opc))
1143 return Error("Invalid binary opcode in BINOP record"); 1230 return Error(InvalidValue, "Invalid binary opcode in BINOP record");
1144 I = BinaryOperator::Create(Opc, LHS, RHS); 1231 I = BinaryOperator::Create(Opc, LHS, RHS);
1145 break; 1232 break;
1146 } 1233 }
1147 case naclbitc::FUNC_CODE_INST_CAST: { // CAST: [opval, destty, castopc] 1234 case naclbitc::FUNC_CODE_INST_CAST: { // CAST: [opval, destty, castopc]
1148 unsigned OpNum = 0; 1235 unsigned OpNum = 0;
1149 Value *Op; 1236 Value *Op;
1150 if (popValue(Record, &OpNum, NextValueNo, &Op) || 1237 if (popValue(Record, &OpNum, NextValueNo, &Op) ||
1151 OpNum+2 != Record.size()) 1238 OpNum+2 != Record.size())
1152 return Error("Invalid CAST record: bad record size"); 1239 return Error(InvalidRecord, "Invalid CAST record: bad record size");
1153 1240
1154 Type *ResTy = getTypeByID(Record[OpNum]); 1241 Type *ResTy = getTypeByID(Record[OpNum]);
1155 if (ResTy == 0) 1242 if (ResTy == 0)
1156 return Error("Invalid CAST record: bad type ID"); 1243 return Error(InvalidType, "Invalid CAST record: bad type ID");
1157 Instruction::CastOps Opc; 1244 Instruction::CastOps Opc;
1158 if (!naclbitc::DecodeCastOpcode(Record[OpNum+1], Opc)) { 1245 if (!naclbitc::DecodeCastOpcode(Record[OpNum+1], Opc)) {
1159 return Error("Invalid CAST record: bad opcode"); 1246 return Error(InvalidValue, "Invalid CAST record: bad opcode");
1160 } 1247 }
1161 1248
1162 // If a ptrtoint cast was elided on the argument of the cast, 1249 // If a ptrtoint cast was elided on the argument of the cast,
1163 // add it back. Note: The casts allowed here should match the 1250 // add it back. Note: The casts allowed here should match the
1164 // casts in NaClValueEnumerator::ExpectsScalarValue. 1251 // casts in NaClValueEnumerator::ExpectsScalarValue.
1165 switch (Opc) { 1252 switch (Opc) {
1166 case Instruction::Trunc: 1253 case Instruction::Trunc:
1167 case Instruction::ZExt: 1254 case Instruction::ZExt:
1168 case Instruction::SExt: 1255 case Instruction::SExt:
1169 case Instruction::UIToFP: 1256 case Instruction::UIToFP:
(...skipping 10 matching lines...) Expand all
1180 1267
1181 case naclbitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [opval, opval, pred] 1268 case naclbitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [opval, opval, pred]
1182 // new form of select 1269 // new form of select
1183 // handles select i1 or select [N x i1] 1270 // handles select i1 or select [N x i1]
1184 unsigned OpNum = 0; 1271 unsigned OpNum = 0;
1185 Value *TrueVal, *FalseVal, *Cond; 1272 Value *TrueVal, *FalseVal, *Cond;
1186 if (popValue(Record, &OpNum, NextValueNo, &TrueVal) || 1273 if (popValue(Record, &OpNum, NextValueNo, &TrueVal) ||
1187 popValue(Record, &OpNum, NextValueNo, &FalseVal) || 1274 popValue(Record, &OpNum, NextValueNo, &FalseVal) ||
1188 popValue(Record, &OpNum, NextValueNo, &Cond) || 1275 popValue(Record, &OpNum, NextValueNo, &Cond) ||
1189 OpNum != Record.size()) 1276 OpNum != Record.size())
1190 return Error("Invalid SELECT record"); 1277 return Error(InvalidRecord, "Invalid SELECT record");
1191 1278
1192 TrueVal = ConvertOpToScalar(TrueVal, CurBBNo); 1279 TrueVal = ConvertOpToScalar(TrueVal, CurBBNo);
1193 FalseVal = ConvertOpToScalar(FalseVal, CurBBNo); 1280 FalseVal = ConvertOpToScalar(FalseVal, CurBBNo);
1194 1281
1195 // select condition can be either i1 or [N x i1] 1282 // select condition can be either i1 or [N x i1]
1196 if (VectorType* vector_type = 1283 if (VectorType* vector_type =
1197 dyn_cast<VectorType>(Cond->getType())) { 1284 dyn_cast<VectorType>(Cond->getType())) {
1198 // expect <n x i1> 1285 // expect <n x i1>
1199 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 1286 if (vector_type->getElementType() != Type::getInt1Ty(Context))
1200 return Error("Invalid SELECT vector condition type"); 1287 return Error(InvalidTypeForValue,
1288 "Invalid SELECT vector condition type");
1201 } else { 1289 } else {
1202 // expect i1 1290 // expect i1
1203 if (Cond->getType() != Type::getInt1Ty(Context)) 1291 if (Cond->getType() != Type::getInt1Ty(Context))
1204 return Error("Invalid SELECT condition type"); 1292 return Error(InvalidTypeForValue, "Invalid SELECT condition type");
1205 } 1293 }
1206 1294
1207 I = SelectInst::Create(Cond, TrueVal, FalseVal); 1295 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1208 break; 1296 break;
1209 } 1297 }
1210 1298
1211 case naclbitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opval, opval] 1299 case naclbitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opval, opval]
1212 unsigned OpNum = 0; 1300 unsigned OpNum = 0;
1213 Value *Vec, *Idx; 1301 Value *Vec, *Idx;
1214 if (popValue(Record, &OpNum, NextValueNo, &Vec) || 1302 if (popValue(Record, &OpNum, NextValueNo, &Vec) ||
1215 popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size()) 1303 popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size())
1216 return Error("Invalid EXTRACTELEMENT record"); 1304 return Error(InvalidRecord, "Invalid EXTRACTELEMENT record");
1217 1305
1218 // expect i32 1306 // expect i32
1219 if (Idx->getType() != Type::getInt32Ty(Context)) 1307 if (Idx->getType() != Type::getInt32Ty(Context))
1220 return Error("Invalid EXTRACTELEMENT index type"); 1308 return Error(InvalidTypeForValue, "Invalid EXTRACTELEMENT index type");
1221 1309
1222 I = ExtractElementInst::Create(Vec, Idx); 1310 I = ExtractElementInst::Create(Vec, Idx);
1223 break; 1311 break;
1224 } 1312 }
1225 1313
1226 case naclbitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [opval,opval,opval] 1314 case naclbitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [opval,opval,opval]
1227 unsigned OpNum = 0; 1315 unsigned OpNum = 0;
1228 Value *Vec, *Elt, *Idx; 1316 Value *Vec, *Elt, *Idx;
1229 if (popValue(Record, &OpNum, NextValueNo, &Vec) || 1317 if (popValue(Record, &OpNum, NextValueNo, &Vec) ||
1230 popValue(Record, &OpNum, NextValueNo, &Elt) || 1318 popValue(Record, &OpNum, NextValueNo, &Elt) ||
1231 popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size()) 1319 popValue(Record, &OpNum, NextValueNo, &Idx) || OpNum != Record.size())
1232 return Error("Invalid INSERTELEMENT record"); 1320 return Error(InvalidRecord, "Invalid INSERTELEMENT record");
1233 1321
1234 // expect vector type 1322 // expect vector type
1235 if (!isa<VectorType>(Vec->getType())) 1323 if (!isa<VectorType>(Vec->getType()))
1236 return Error("Invalid INSERTELEMENT vector type"); 1324 return Error(InvalidTypeForValue, "Invalid INSERTELEMENT vector type");
1237 // match vector and element types 1325 // match vector and element types
1238 if (cast<VectorType>(Vec->getType())->getElementType() != Elt->getType()) 1326 if (cast<VectorType>(Vec->getType())->getElementType() != Elt->getType())
1239 return Error("Mismatched INSERTELEMENT vector and element type"); 1327 return Error(InvalidTypeForValue,
1328 "Mismatched INSERTELEMENT vector and element type");
1240 // expect i32 1329 // expect i32
1241 if (Idx->getType() != Type::getInt32Ty(Context)) 1330 if (Idx->getType() != Type::getInt32Ty(Context))
1242 return Error("Invalid INSERTELEMENT index type"); 1331 return Error(InvalidTypeForValue, "Invalid INSERTELEMENT index type");
1243 1332
1244 I = InsertElementInst::Create(Vec, Elt, Idx); 1333 I = InsertElementInst::Create(Vec, Elt, Idx);
1245 break; 1334 break;
1246 } 1335 }
1247 1336
1248 case naclbitc::FUNC_CODE_INST_CMP2: { // CMP2: [opval, opval, pred] 1337 case naclbitc::FUNC_CODE_INST_CMP2: { // CMP2: [opval, opval, pred]
1249 // FCmp/ICmp returning bool or vector of bool 1338 // FCmp/ICmp returning bool or vector of bool
1250 1339
1251 unsigned OpNum = 0; 1340 unsigned OpNum = 0;
1252 Value *LHS, *RHS; 1341 Value *LHS, *RHS;
1253 if (popValue(Record, &OpNum, NextValueNo, &LHS) || 1342 if (popValue(Record, &OpNum, NextValueNo, &LHS) ||
1254 popValue(Record, &OpNum, NextValueNo, &RHS) || 1343 popValue(Record, &OpNum, NextValueNo, &RHS) ||
1255 OpNum+1 != Record.size()) 1344 OpNum+1 != Record.size())
1256 return Error("Invalid CMP record"); 1345 return Error(InvalidRecord, "Invalid CMP record");
1257 1346
1258 LHS = ConvertOpToScalar(LHS, CurBBNo); 1347 LHS = ConvertOpToScalar(LHS, CurBBNo);
1259 RHS = ConvertOpToScalar(RHS, CurBBNo); 1348 RHS = ConvertOpToScalar(RHS, CurBBNo);
1260 1349
1261 CmpInst::Predicate Predicate; 1350 CmpInst::Predicate Predicate;
1262 if (LHS->getType()->isFPOrFPVectorTy()) { 1351 if (LHS->getType()->isFPOrFPVectorTy()) {
1263 if (!naclbitc::DecodeFcmpPredicate(Record[OpNum], Predicate)) 1352 if (!naclbitc::DecodeFcmpPredicate(Record[OpNum], Predicate))
1264 return Error( 1353 return Error(
1354 InvalidValue,
1265 "PNaCl bitcode contains invalid floating comparison predicate"); 1355 "PNaCl bitcode contains invalid floating comparison predicate");
1266 I = new FCmpInst(Predicate, LHS, RHS); 1356 I = new FCmpInst(Predicate, LHS, RHS);
1267 } else { 1357 } else {
1268 if (!naclbitc::DecodeIcmpPredicate(Record[OpNum], Predicate)) 1358 if (!naclbitc::DecodeIcmpPredicate(Record[OpNum], Predicate))
1269 return Error( 1359 return Error(
1360 InvalidValue,
1270 "PNaCl bitcode contains invalid integer comparison predicate"); 1361 "PNaCl bitcode contains invalid integer comparison predicate");
1271 I = new ICmpInst(Predicate, LHS, RHS); 1362 I = new ICmpInst(Predicate, LHS, RHS);
1272 } 1363 }
1273 break; 1364 break;
1274 } 1365 }
1275 1366
1276 case naclbitc::FUNC_CODE_INST_RET: // RET: [opval<optional>] 1367 case naclbitc::FUNC_CODE_INST_RET: // RET: [opval<optional>]
1277 { 1368 {
1278 unsigned Size = Record.size(); 1369 unsigned Size = Record.size();
1279 if (Size == 0) { 1370 if (Size == 0) {
1280 I = ReturnInst::Create(Context); 1371 I = ReturnInst::Create(Context);
1281 break; 1372 break;
1282 } 1373 }
1283 1374
1284 unsigned OpNum = 0; 1375 unsigned OpNum = 0;
1285 Value *Op = NULL; 1376 Value *Op = NULL;
1286 if (popValue(Record, &OpNum, NextValueNo, &Op)) 1377 if (popValue(Record, &OpNum, NextValueNo, &Op))
1287 return Error("Invalid RET record"); 1378 return Error(InvalidRecord, "Invalid RET record");
1288 if (OpNum != Record.size()) 1379 if (OpNum != Record.size())
1289 return Error("Invalid RET record"); 1380 return Error(InvalidRecord, "Invalid RET record");
1290 1381
1291 I = ReturnInst::Create(Context, ConvertOpToScalar(Op, CurBBNo)); 1382 I = ReturnInst::Create(Context, ConvertOpToScalar(Op, CurBBNo));
1292 break; 1383 break;
1293 } 1384 }
1294 case naclbitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 1385 case naclbitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1295 if (Record.size() != 1 && Record.size() != 3) 1386 if (Record.size() != 1 && Record.size() != 3)
1296 return Error("Invalid BR record"); 1387 return Error(InvalidRecord, "Invalid BR record");
1297 BasicBlock *TrueDest = getBasicBlock(Record[0]); 1388 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1298 if (TrueDest == 0) 1389 if (TrueDest == 0)
1299 return Error("Invalid BR record"); 1390 return Error(InvalidRecord, "Invalid BR record");
1300 1391
1301 if (Record.size() == 1) { 1392 if (Record.size() == 1) {
1302 I = BranchInst::Create(TrueDest); 1393 I = BranchInst::Create(TrueDest);
1303 } 1394 }
1304 else { 1395 else {
1305 BasicBlock *FalseDest = getBasicBlock(Record[1]); 1396 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1306 Value *Cond = getValue(Record, 2, NextValueNo); 1397 Value *Cond = getValue(Record, 2, NextValueNo);
1307 if (FalseDest == 0 || Cond == 0) 1398 if (FalseDest == 0 || Cond == 0)
1308 return Error("Invalid BR record"); 1399 return Error(InvalidValue, "Invalid BR record");
1309 I = BranchInst::Create(TrueDest, FalseDest, Cond); 1400 I = BranchInst::Create(TrueDest, FalseDest, Cond);
1310 } 1401 }
1311 break; 1402 break;
1312 } 1403 }
1313 case naclbitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 1404 case naclbitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
1314 if (Record.size() < 4) 1405 if (Record.size() < 4)
1315 return Error("Invalid SWITCH record"); 1406 return Error(InvalidRecord, "Invalid SWITCH record");
1316 Type *OpTy = getTypeByID(Record[0]); 1407 Type *OpTy = getTypeByID(Record[0]);
1317 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 1408 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
1318 if (ValueBitWidth > 64) 1409 if (ValueBitWidth > 64)
1319 return Error("Wide integers are not supported in PNaCl bitcode"); 1410 return Error(InvalidValue,
1411 "Wide integers are not supported in PNaCl bitcode");
1320 1412
1321 Value *Cond = getValue(Record, 1, NextValueNo); 1413 Value *Cond = getValue(Record, 1, NextValueNo);
1322 BasicBlock *Default = getBasicBlock(Record[2]); 1414 BasicBlock *Default = getBasicBlock(Record[2]);
1323 if (OpTy == 0 || Cond == 0 || Default == 0) 1415 if (OpTy == 0 || Cond == 0 || Default == 0)
1324 return Error("Invalid SWITCH record"); 1416 return Error(InvalidRecord, "Invalid SWITCH record");
1325 1417
1326 unsigned NumCases = Record[3]; 1418 unsigned NumCases = Record[3];
1327 1419
1328 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 1420 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1329 1421
1330 unsigned CurIdx = 4; 1422 unsigned CurIdx = 4;
1331 for (unsigned i = 0; i != NumCases; ++i) { 1423 for (unsigned i = 0; i != NumCases; ++i) {
1332 // The PNaCl bitcode format has vestigial support for case 1424 // The PNaCl bitcode format has vestigial support for case
1333 // ranges, but we no longer support reading them because 1425 // ranges, but we no longer support reading them because
1334 // no-one produced them. 1426 // no-one produced them.
1335 // See https://code.google.com/p/nativeclient/issues/detail?id=3758 1427 // See https://code.google.com/p/nativeclient/issues/detail?id=3758
1336 unsigned NumItems = Record[CurIdx++]; 1428 unsigned NumItems = Record[CurIdx++];
1337 bool isSingleNumber = Record[CurIdx++]; 1429 bool isSingleNumber = Record[CurIdx++];
1338 if (NumItems != 1 || !isSingleNumber) 1430 if (NumItems != 1 || !isSingleNumber)
1339 return Error("Case ranges are not supported in PNaCl bitcode"); 1431 return Error(InvalidRecord,
1432 "Case ranges are not supported in PNaCl bitcode");
1340 1433
1341 APInt CaseValue(ValueBitWidth, 1434 APInt CaseValue(ValueBitWidth,
1342 NaClDecodeSignRotatedValue(Record[CurIdx++])); 1435 NaClDecodeSignRotatedValue(Record[CurIdx++]));
1343 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 1436 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
1344 SI->addCase(ConstantInt::get(Context, CaseValue), DestBB); 1437 SI->addCase(ConstantInt::get(Context, CaseValue), DestBB);
1345 } 1438 }
1346 I = SI; 1439 I = SI;
1347 break; 1440 break;
1348 } 1441 }
1349 case naclbitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 1442 case naclbitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1350 I = new UnreachableInst(Context); 1443 I = new UnreachableInst(Context);
1351 break; 1444 break;
1352 case naclbitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 1445 case naclbitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1353 if (Record.size() < 1 || ((Record.size()-1)&1)) 1446 if (Record.size() < 1 || ((Record.size()-1)&1))
1354 return Error("Invalid PHI record"); 1447 return Error(InvalidRecord, "Invalid PHI record");
1355 Type *Ty = getTypeByID(Record[0]); 1448 Type *Ty = getTypeByID(Record[0]);
1356 if (!Ty) return Error("Invalid PHI record"); 1449 if (!Ty) return Error(InvalidType, "Invalid PHI record");
1357 1450
1358 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 1451 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
1359 1452
1360 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 1453 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1361 Value *V; 1454 Value *V;
1362 // With relative value IDs, it is possible that operands have 1455 // With relative value IDs, it is possible that operands have
1363 // negative IDs (for forward references). Use a signed VBR 1456 // negative IDs (for forward references). Use a signed VBR
1364 // representation to keep the encoding small. 1457 // representation to keep the encoding small.
1365 V = getValueSigned(Record, 1+i, NextValueNo); 1458 V = getValueSigned(Record, 1+i, NextValueNo);
1366 unsigned BBIndex = Record[2+i]; 1459 unsigned BBIndex = Record[2+i];
1367 BasicBlock *BB = getBasicBlock(BBIndex); 1460 BasicBlock *BB = getBasicBlock(BBIndex);
1368 if (!V || !BB) return Error("Invalid PHI record"); 1461 if (!V || !BB)
1462 return Error(InvalidValue, "Invalid PHI record");
1369 if (Ty == IntPtrType) { 1463 if (Ty == IntPtrType) {
1370 // Delay installing scalar casts until all instructions of 1464 // Delay installing scalar casts until all instructions of
1371 // the function are rendered. This guarantees that we insert 1465 // the function are rendered. This guarantees that we insert
1372 // the conversion just before the incoming edge (or use an 1466 // the conversion just before the incoming edge (or use an
1373 // existing conversion if already installed). 1467 // existing conversion if already installed).
1374 V = ConvertOpToScalar(V, BBIndex, /* DeferInsertion = */ true); 1468 V = ConvertOpToScalar(V, BBIndex, /* DeferInsertion = */ true);
1375 } 1469 }
1376 PN->addIncoming(V, BB); 1470 PN->addIncoming(V, BB);
1377 } 1471 }
1378 I = PN; 1472 I = PN;
1379 break; 1473 break;
1380 } 1474 }
1381 1475
1382 case naclbitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [op, align] 1476 case naclbitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [op, align]
1383 if (Record.size() != 2) 1477 if (Record.size() != 2)
1384 return Error("Invalid ALLOCA record"); 1478 return Error(InvalidRecord, "Invalid ALLOCA record");
1385 Value *Size; 1479 Value *Size;
1386 unsigned OpNum = 0; 1480 unsigned OpNum = 0;
1387 if (popValue(Record, &OpNum, NextValueNo, &Size)) 1481 if (popValue(Record, &OpNum, NextValueNo, &Size))
1388 return Error("Invalid ALLOCA record"); 1482 return Error(InvalidRecord, "Invalid ALLOCA record");
1389 unsigned Align = Record[1]; 1483 unsigned Align = Record[1];
1390 I = new AllocaInst(Type::getInt8Ty(Context), Size, (1 << Align) >> 1); 1484 I = new AllocaInst(Type::getInt8Ty(Context), Size, (1 << Align) >> 1);
1391 break; 1485 break;
1392 } 1486 }
1393 case naclbitc::FUNC_CODE_INST_LOAD: { 1487 case naclbitc::FUNC_CODE_INST_LOAD: {
1394 // LOAD: [op, align, ty] 1488 // LOAD: [op, align, ty]
1395 unsigned OpNum = 0; 1489 unsigned OpNum = 0;
1396 Value *Op; 1490 Value *Op;
1397 if (popValue(Record, &OpNum, NextValueNo, &Op) || 1491 if (popValue(Record, &OpNum, NextValueNo, &Op) ||
1398 Record.size() != 3) 1492 Record.size() != 3)
1399 return Error("Invalid LOAD record"); 1493 return Error(InvalidRecord, "Invalid LOAD record");
1400 1494
1401 // Add pointer cast to op. 1495 // Add pointer cast to op.
1402 Type *T = getTypeByID(Record[2]); 1496 Type *T = getTypeByID(Record[2]);
1403 if (T == 0) 1497 if (T == nullptr)
1404 return Error("Invalid type for load instruction"); 1498 return Error(InvalidType, "Invalid type for load instruction");
1405 Op = ConvertOpToType(Op, T->getPointerTo(), CurBBNo); 1499 Op = ConvertOpToType(Op, T->getPointerTo(), CurBBNo);
1406 if (Op == 0) return true; 1500 if (Op == nullptr)
1501 return Error(InvalidTypeForValue, "Can't convert cast to type");
1407 I = new LoadInst(Op, "", false, (1 << Record[OpNum]) >> 1); 1502 I = new LoadInst(Op, "", false, (1 << Record[OpNum]) >> 1);
1408 break; 1503 break;
1409 } 1504 }
1410 case naclbitc::FUNC_CODE_INST_STORE: { 1505 case naclbitc::FUNC_CODE_INST_STORE: {
1411 // STORE: [ptr, val, align] 1506 // STORE: [ptr, val, align]
1412 unsigned OpNum = 0; 1507 unsigned OpNum = 0;
1413 Value *Val, *Ptr; 1508 Value *Val, *Ptr;
1414 if (popValue(Record, &OpNum, NextValueNo, &Ptr) || 1509 if (popValue(Record, &OpNum, NextValueNo, &Ptr) ||
1415 popValue(Record, &OpNum, NextValueNo, &Val) || 1510 popValue(Record, &OpNum, NextValueNo, &Val) ||
1416 OpNum+1 != Record.size()) 1511 OpNum+1 != Record.size())
1417 return Error("Invalid STORE record"); 1512 return Error(InvalidRecord, "Invalid STORE record");
1418 Val = ConvertOpToScalar(Val, CurBBNo); 1513 Val = ConvertOpToScalar(Val, CurBBNo);
1419 Ptr = ConvertOpToType(Ptr, Val->getType()->getPointerTo(), CurBBNo); 1514 Ptr = ConvertOpToType(Ptr, Val->getType()->getPointerTo(), CurBBNo);
1515 if (Ptr == nullptr)
1516 return Error(InvalidTypeForValue, "Can't convert cast to type");
1420 I = new StoreInst(Val, Ptr, false, (1 << Record[OpNum]) >> 1); 1517 I = new StoreInst(Val, Ptr, false, (1 << Record[OpNum]) >> 1);
1421 break; 1518 break;
1422 } 1519 }
1423 case naclbitc::FUNC_CODE_INST_CALL: 1520 case naclbitc::FUNC_CODE_INST_CALL:
1424 case naclbitc::FUNC_CODE_INST_CALL_INDIRECT: { 1521 case naclbitc::FUNC_CODE_INST_CALL_INDIRECT: {
1425 // CALL: [cc, fnid, arg0, arg1...] 1522 // CALL: [cc, fnid, arg0, arg1...]
1426 // CALL_INDIRECT: [cc, fnid, returnty, args...] 1523 // CALL_INDIRECT: [cc, fnid, returnty, args...]
1427 if ((Record.size() < 2) || 1524 if ((Record.size() < 2) ||
1428 (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT && 1525 (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT &&
1429 Record.size() < 3)) 1526 Record.size() < 3))
1430 return Error("Invalid CALL record"); 1527 return Error(InvalidRecord, "Invalid CALL record");
1431 1528
1432 unsigned CCInfo = Record[0]; 1529 unsigned CCInfo = Record[0];
1433 1530
1434 unsigned OpNum = 1; 1531 unsigned OpNum = 1;
1435 Value *Callee; 1532 Value *Callee;
1436 if (popValue(Record, &OpNum, NextValueNo, &Callee)) 1533 if (popValue(Record, &OpNum, NextValueNo, &Callee))
1437 return Error("Invalid CALL record"); 1534 return Error(InvalidRecord, "Invalid CALL record");
1438 1535
1439 // Build function type for call. 1536 // Build function type for call.
1440 FunctionType *FTy = 0; 1537 FunctionType *FTy = 0;
1441 Type *ReturnType = 0; 1538 Type *ReturnType = 0;
1442 if (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT) { 1539 if (BitCode == naclbitc::FUNC_CODE_INST_CALL_INDIRECT) {
1443 // Callee type has been elided, add back in. 1540 // Callee type has been elided, add back in.
1444 ReturnType = getTypeByID(Record[2]); 1541 ReturnType = getTypeByID(Record[2]);
1445 ++OpNum; 1542 ++OpNum;
1446 } else { 1543 } else {
1447 // Get type signature from callee. 1544 // Get type signature from callee.
1448 if (PointerType *OpTy = dyn_cast<PointerType>(Callee->getType())) { 1545 if (PointerType *OpTy = dyn_cast<PointerType>(Callee->getType())) {
1449 FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 1546 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1450 } 1547 }
1451 if (FTy == 0) 1548 if (FTy == 0)
1452 return Error("Invalid type for CALL record"); 1549 return Error(InvalidType, "Invalid type for CALL record");
1453 } 1550 }
1454 1551
1455 unsigned NumParams = Record.size() - OpNum; 1552 unsigned NumParams = Record.size() - OpNum;
1456 if (FTy && NumParams != FTy->getNumParams()) 1553 if (FTy && NumParams != FTy->getNumParams())
1457 return Error("Invalid CALL record"); 1554 return Error(InvalidRecord, "Invalid CALL record");
1458 1555
1459 // Process call arguments. 1556 // Process call arguments.
1460 SmallVector<Value*, 6> Args; 1557 SmallVector<Value*, 6> Args;
1461 for (unsigned Index = 0; Index < NumParams; ++Index) { 1558 for (unsigned Index = 0; Index < NumParams; ++Index) {
1462 Value *Arg; 1559 Value *Arg;
1463 if (popValue(Record, &OpNum, NextValueNo, &Arg)) 1560 if (popValue(Record, &OpNum, NextValueNo, &Arg))
1464 Error("Invalid argument in CALL record"); 1561 Error(InvalidValue, "Invalid argument in CALL record");
1465 if (FTy) { 1562 if (FTy) {
1466 // Add a cast, to a pointer type if necessary, in case this 1563 // Add a cast, to a pointer type if necessary, in case this
1467 // is an intrinsic call that takes a pointer argument. 1564 // is an intrinsic call that takes a pointer argument.
1468 Arg = ConvertOpToType(Arg, FTy->getParamType(Index), CurBBNo); 1565 Arg = ConvertOpToType(Arg, FTy->getParamType(Index), CurBBNo);
1469 } else { 1566 } else {
1470 Arg = ConvertOpToScalar(Arg, CurBBNo); 1567 Arg = ConvertOpToScalar(Arg, CurBBNo);
1471 } 1568 }
1472 Args.push_back(Arg); 1569 Args.push_back(Arg);
1473 } 1570 }
1474 1571
1475 if (FTy == 0) { 1572 if (FTy == 0) {
1476 // Reconstruct the function type and cast the function pointer 1573 // Reconstruct the function type and cast the function pointer
1477 // to it. 1574 // to it.
1478 SmallVector<Type*, 6> ArgTypes; 1575 SmallVector<Type*, 6> ArgTypes;
1479 for (unsigned Index = 0; Index < NumParams; ++Index) 1576 for (unsigned Index = 0; Index < NumParams; ++Index)
1480 ArgTypes.push_back(Args[Index]->getType()); 1577 ArgTypes.push_back(Args[Index]->getType());
1481 FTy = FunctionType::get(ReturnType, ArgTypes, false); 1578 FTy = FunctionType::get(ReturnType, ArgTypes, false);
1482 Callee = ConvertOpToType(Callee, FTy->getPointerTo(), CurBBNo); 1579 Callee = ConvertOpToType(Callee, FTy->getPointerTo(), CurBBNo);
1483 } 1580 }
1484 1581
1485 // Construct call. 1582 // Construct call.
1486 I = CallInst::Create(Callee, Args); 1583 I = CallInst::Create(Callee, Args);
1487 CallingConv::ID CallingConv; 1584 CallingConv::ID CallingConv;
1488 if (!naclbitc::DecodeCallingConv(CCInfo>>1, CallingConv)) 1585 if (!naclbitc::DecodeCallingConv(CCInfo>>1, CallingConv))
1489 return Error("PNaCl bitcode contains invalid calling conventions."); 1586 return Error(InvalidValue,
1587 "PNaCl bitcode contains invalid calling conventions.");
1490 cast<CallInst>(I)->setCallingConv(CallingConv); 1588 cast<CallInst>(I)->setCallingConv(CallingConv);
1491 cast<CallInst>(I)->setTailCall(CCInfo & 1); 1589 cast<CallInst>(I)->setTailCall(CCInfo & 1);
1492 break; 1590 break;
1493 } 1591 }
1494 case naclbitc::FUNC_CODE_INST_FORWARDTYPEREF: 1592 case naclbitc::FUNC_CODE_INST_FORWARDTYPEREF:
1495 // Build corresponding forward reference. 1593 // Build corresponding forward reference.
1496 if (Record.size() != 2 || 1594 if (Record.size() != 2 ||
1497 ValueList.createValueFwdRef(Record[0], getTypeByID(Record[1]))) 1595 ValueList.createValueFwdRef(Record[0], getTypeByID(Record[1])))
1498 return Error("Invalid FORWARDTYPEREF record"); 1596 return Error(InvalidRecord, "Invalid FORWARDTYPEREF record");
1499 continue; 1597 continue;
1500 } 1598 }
1501 1599
1502 if (InstallInstruction(CurBB, I)) 1600 if (std::error_code EC = InstallInstruction(CurBB, I))
1503 return true; 1601 return EC;
1504 1602
1505 // If this was a terminator instruction, move to the next block. 1603 // If this was a terminator instruction, move to the next block.
1506 if (isa<TerminatorInst>(I)) { 1604 if (isa<TerminatorInst>(I)) {
1507 ++CurBBNo; 1605 ++CurBBNo;
1508 CurBB = getBasicBlock(CurBBNo); 1606 CurBB = getBasicBlock(CurBBNo);
1509 } 1607 }
1510 1608
1511 // Non-void values get registered in the value table for future use. 1609 // Non-void values get registered in the value table for future use.
1512 if (I && !I->getType()->isVoidTy()) { 1610 if (I && !I->getType()->isVoidTy()) {
1513 Value *NewVal = I; 1611 Value *NewVal = I;
(...skipping 29 matching lines...) Expand all
1543 // Check the function list for unresolved values. 1641 // Check the function list for unresolved values.
1544 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 1642 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1545 if (A->getParent() == 0) { 1643 if (A->getParent() == 0) {
1546 // We found at least one unresolved value. Nuke them all to avoid leaks. 1644 // We found at least one unresolved value. Nuke them all to avoid leaks.
1547 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 1645 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1548 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) { 1646 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
1549 A->replaceAllUsesWith(UndefValue::get(A->getType())); 1647 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1550 delete A; 1648 delete A;
1551 } 1649 }
1552 } 1650 }
1553 return Error("Never resolved value found in function!"); 1651 return Error(InvalidValue, "Never resolved value found in function!");
1554 } 1652 }
1555 } 1653 }
1556 1654
1557 // Trim the value list down to the size it was before we parsed this function. 1655 // Trim the value list down to the size it was before we parsed this function.
1558 ValueList.shrinkTo(ModuleValueListSize); 1656 ValueList.shrinkTo(ModuleValueListSize);
1559 FunctionBBs.clear(); 1657 FunctionBBs.clear();
1560 DEBUG(dbgs() << "-> ParseFunctionBody\n"); 1658 DEBUG(dbgs() << "-> ParseFunctionBody\n");
1561 return false; 1659 return std::error_code();
1562 } 1660 }
1563 1661
1564 /// FindFunctionInStream - Find the function body in the bitcode stream 1662 /// FindFunctionInStream - Find the function body in the bitcode stream
1565 bool NaClBitcodeReader::FindFunctionInStream(Function *F, 1663 std::error_code NaClBitcodeReader::FindFunctionInStream(
1566 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) { 1664 Function *F,
1665 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
1567 while (DeferredFunctionInfoIterator->second == 0) { 1666 while (DeferredFunctionInfoIterator->second == 0) {
1568 if (Stream.AtEndOfStream()) 1667 if (Stream.AtEndOfStream())
1569 return Error("Could not find Function in stream"); 1668 return Error(CouldNotFindFunctionInStream,
1669 "Could not find Function in stream");
1570 // ParseModule will parse the next body in the stream and set its 1670 // ParseModule will parse the next body in the stream and set its
1571 // position in the DeferredFunctionInfo map. 1671 // position in the DeferredFunctionInfo map.
1572 if (ParseModule(true)) return true; 1672 if (std::error_code EC = ParseModule(true))
1673 return EC;
1573 } 1674 }
1574 return false; 1675 return std::error_code();
1575 } 1676 }
1576 1677
1577 //===----------------------------------------------------------------------===// 1678 //===----------------------------------------------------------------------===//
1578 // GVMaterializer implementation 1679 // GVMaterializer implementation
1579 //===----------------------------------------------------------------------===// 1680 //===----------------------------------------------------------------------===//
1580 1681
1581 void NaClBitcodeReader::releaseBuffer() { Buffer.release(); } 1682 void NaClBitcodeReader::releaseBuffer() { Buffer.release(); }
1582 1683
1583 bool NaClBitcodeReader::isMaterializable(const GlobalValue *GV) const { 1684 bool NaClBitcodeReader::isMaterializable(const GlobalValue *GV) const {
1584 if (const Function *F = dyn_cast<Function>(GV)) { 1685 if (const Function *F = dyn_cast<Function>(GV)) {
(...skipping 102 matching lines...) Expand 10 before | Expand all | Expand 10 after
1687 if (!I->first->use_empty()) 1788 if (!I->first->use_empty())
1688 I->first->replaceAllUsesWith(I->second); 1789 I->first->replaceAllUsesWith(I->second);
1689 I->first->eraseFromParent(); 1790 I->first->eraseFromParent();
1690 } 1791 }
1691 } 1792 }
1692 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 1793 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1693 1794
1694 return std::error_code(); 1795 return std::error_code();
1695 } 1796 }
1696 1797
1697 bool NaClBitcodeReader::InitStream() { 1798 std::error_code NaClBitcodeReader::InitStream() {
1698 if (LazyStreamer) return InitLazyStream(); 1799 if (LazyStreamer)
1800 return InitLazyStream();
1699 return InitStreamFromBuffer(); 1801 return InitStreamFromBuffer();
1700 } 1802 }
1701 1803
1702 bool NaClBitcodeReader::InitStreamFromBuffer() { 1804 std::error_code NaClBitcodeReader::InitStreamFromBuffer() {
1703 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 1805 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
1704 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 1806 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1705 1807
1706 if (Buffer->getBufferSize() & 3) 1808 if (Buffer->getBufferSize() & 3)
1707 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 1809 return Error(InvalidBitstream,
1810 "Bitcode stream should be a multiple of 4 bytes in length");
1708 1811
1709 if (Header.Read(BufPtr, BufEnd)) 1812 if (Header.Read(BufPtr, BufEnd))
1710 return Error(Header.Unsupported()); 1813 return Error(InvalidBitstream, Header.Unsupported());
1711 1814
1712 StreamFile.reset(new NaClBitstreamReader(BufPtr, BufEnd)); 1815 StreamFile.reset(new NaClBitstreamReader(BufPtr, BufEnd));
1713 Stream.init(*StreamFile); 1816 Stream.init(*StreamFile);
1714 1817
1715 if (AcceptHeader()) 1818 if (AcceptHeader())
1716 return Error(Header.Unsupported()); 1819 return Error(InvalidBitstream, Header.Unsupported());
1717 return false; 1820 return std::error_code();
1718 } 1821 }
1719 1822
1720 bool NaClBitcodeReader::InitLazyStream() { 1823 std::error_code NaClBitcodeReader::InitLazyStream() {
1721 if (Header.Read(LazyStreamer)) 1824 if (Header.Read(LazyStreamer))
1722 return Error(Header.Unsupported()); 1825 return Error(InvalidBitstream, Header.Unsupported());
1723 1826
1724 StreamFile.reset(new NaClBitstreamReader(LazyStreamer, 1827 StreamFile.reset(new NaClBitstreamReader(LazyStreamer,
1725 Header.getHeaderSize())); 1828 Header.getHeaderSize()));
1726 Stream.init(*StreamFile); 1829 Stream.init(*StreamFile);
1727 if (AcceptHeader()) 1830 if (AcceptHeader())
1728 return Error(Header.Unsupported()); 1831 return Error(InvalidBitstream, Header.Unsupported());
1729 return false; 1832 return std::error_code();
1730 } 1833 }
1731 1834
1732 //===----------------------------------------------------------------------===// 1835 //===----------------------------------------------------------------------===//
1733 // External interface 1836 // External interface
1734 //===----------------------------------------------------------------------===// 1837 //===----------------------------------------------------------------------===//
1735 1838
1736 /// getNaClLazyBitcodeModule - lazy function-at-a-time loading from a file. 1839 /// getNaClLazyBitcodeModule - lazy function-at-a-time loading from a file.
1737 /// 1840 ///
1738 Module *llvm::getNaClLazyBitcodeModule(MemoryBuffer *Buffer, 1841 ErrorOr<Module *> llvm::getNaClLazyBitcodeModule(
1739 LLVMContext& Context, 1842 MemoryBuffer *Buffer, LLVMContext& Context, raw_ostream *Verbose,
1740 std::string *ErrMsg, 1843 bool AcceptSupportedOnly) {
1741 bool AcceptSupportedOnly) {
1742 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 1844 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
1743 NaClBitcodeReader *R = 1845 NaClBitcodeReader *R =
1744 new NaClBitcodeReader(Buffer, Context, AcceptSupportedOnly); 1846 new NaClBitcodeReader(Buffer, Context, Verbose, AcceptSupportedOnly);
1745 M->setMaterializer(R); 1847 M->setMaterializer(R);
1746 if (R->ParseBitcodeInto(M)) { 1848 if (std::error_code EC = R->ParseBitcodeInto(M)) {
1747 if (ErrMsg) 1849 R->releaseBuffer(); // Never take ownership on error.
1748 *ErrMsg = R->getErrorString();
1749
1750 delete M; // Also deletes R. 1850 delete M; // Also deletes R.
1751 return 0; 1851 return EC;
1752 } 1852 }
1753 1853
1754 return M; 1854 return M;
1755 } 1855 }
1756 1856
1757 1857
1758 Module *llvm::getNaClStreamedBitcodeModule(const std::string &name, 1858 Module *llvm::getNaClStreamedBitcodeModule(const std::string &name,
1759 StreamingMemoryObject *Streamer, 1859 StreamingMemoryObject *Streamer,
1760 LLVMContext &Context, 1860 LLVMContext &Context,
1861 raw_ostream *Verbose,
1761 std::string *ErrMsg, 1862 std::string *ErrMsg,
1762 bool AcceptSupportedOnly) { 1863 bool AcceptSupportedOnly) {
1763 Module *M = new Module(name, Context); 1864 Module *M = new Module(name, Context);
1764 NaClBitcodeReader *R = 1865 NaClBitcodeReader *R =
1765 new NaClBitcodeReader(Streamer, Context, AcceptSupportedOnly); 1866 new NaClBitcodeReader(Streamer, Context, Verbose,
1867 AcceptSupportedOnly);
1766 M->setMaterializer(R); 1868 M->setMaterializer(R);
1767 if (R->ParseBitcodeInto(M)) { 1869 if (std::error_code EC = R->ParseBitcodeInto(M)) {
1768 if (ErrMsg) 1870 if (ErrMsg)
1769 *ErrMsg = R->getErrorString(); 1871 *ErrMsg = EC.message();
1770 delete M; // Also deletes R. 1872 delete M; // Also deletes R.
1771 return 0; 1873 return nullptr;
1772 } 1874 }
1773 1875
1774 return M; 1876 return M;
1775 } 1877 }
1776 1878
1777 /// NaClParseBitcodeFile - Read the specified bitcode file, returning the module . 1879 /// NaClParseBitcodeFile - Read the specified bitcode file, returning the module .
1778 /// If an error occurs, return null and fill in *ErrMsg if non-null. 1880 /// If an error occurs, return null and fill in *ErrMsg if non-null.
1779 Module *llvm::NaClParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 1881 ErrorOr<Module *> llvm::NaClParseBitcodeFile(
1780 std::string *ErrMsg, 1882 MemoryBuffer *Buffer, LLVMContext& Context, raw_ostream *Verbose,
1781 bool AcceptSupportedOnly){ 1883 bool AcceptSupportedOnly){
1782 Module *M = getNaClLazyBitcodeModule(Buffer, Context, ErrMsg, 1884 ErrorOr<Module *> ModuleOrErr =
1783 AcceptSupportedOnly); 1885 getNaClLazyBitcodeModule(Buffer, Context, Verbose, AcceptSupportedOnly);
1784 if (!M) return 0; 1886 if (!ModuleOrErr)
1785 1887 return ModuleOrErr;
1888 Module *M = ModuleOrErr.get();
1786 // Read in the entire module, and destroy the NaClBitcodeReader. 1889 // Read in the entire module, and destroy the NaClBitcodeReader.
1787 if (std::error_code EC = M->materializeAllPermanently()) { 1890 if (std::error_code EC = M->materializeAllPermanently()) {
1788 *ErrMsg = EC.message();
1789 delete M; 1891 delete M;
1790 return 0; 1892 return EC;
1791 } 1893 }
1792 1894
1793 // TODO: Restore the use-lists to the in-memory state when the bitcode was 1895 // TODO: Restore the use-lists to the in-memory state when the bitcode was
1794 // written. We must defer until the Module has been fully materialized. 1896 // written. We must defer until the Module has been fully materialized.
1795 1897
1796 return M; 1898 return M;
1797 } 1899 }
OLDNEW
« no previous file with comments | « lib/Bitcode/NaCl/Reader/NaClBitcodeReader.h ('k') | lib/Bitcode/NaCl/TestUtils/NaClBitcodeMunge.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698