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