1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/Bitcode/ReaderWriter.h" 11 #include "BitcodeReader.h" 12 #include "llvm/ADT/SmallString.h" 13 #include "llvm/ADT/SmallVector.h" 14 #include "llvm/ADT/Triple.h" 15 #include "llvm/Bitcode/LLVMBitCodes.h" 16 #include "llvm/IR/AutoUpgrade.h" 17 #include "llvm/IR/Constants.h" 18 #include "llvm/IR/DebugInfoMetadata.h" 19 #include "llvm/IR/DerivedTypes.h" 20 #include "llvm/IR/DiagnosticPrinter.h" 21 #include "llvm/IR/InlineAsm.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/LLVMContext.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/ManagedStatic.h" 29 #include "llvm/Support/MathExtras.h" 30 #include "llvm/Support/MemoryBuffer.h" 31 #include "llvm/Support/raw_ostream.h" 32 33 using namespace llvm; 34 35 enum { 36 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 37 }; 38 39 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC, 40 DiagnosticSeverity Severity, 41 const Twine &Msg) 42 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {} 43 44 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 45 46 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler, 47 std::error_code EC, const Twine &Message) { 48 BitcodeDiagnosticInfo DI(EC, DS_Error, Message); 49 DiagnosticHandler(DI); 50 return EC; 51 } 52 53 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler, 54 std::error_code EC) { 55 return Error(DiagnosticHandler, EC, EC.message()); 56 } 57 58 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) { 59 return ::Error(DiagnosticHandler, make_error_code(E), Message); 60 } 61 62 std::error_code BitcodeReader::Error(const Twine &Message) { 63 return ::Error(DiagnosticHandler, 64 make_error_code(BitcodeError::CorruptedBitcode), Message); 65 } 66 67 std::error_code BitcodeReader::Error(BitcodeError E) { 68 return ::Error(DiagnosticHandler, make_error_code(E)); 69 } 70 71 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F, 72 LLVMContext &C) { 73 if (F) 74 return F; 75 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); }; 76 } 77 78 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C, 79 DiagnosticHandlerFunction DiagnosticHandler) 80 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)), 81 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr), 82 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C), 83 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false), 84 WillMaterializeAllForwardRefs(false) {} 85 86 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C, 87 DiagnosticHandlerFunction DiagnosticHandler) 88 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)), 89 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer), 90 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C), 91 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false), 92 WillMaterializeAllForwardRefs(false) {} 93 94 std::error_code BitcodeReader::materializeForwardReferencedFunctions() { 95 if (WillMaterializeAllForwardRefs) 96 return std::error_code(); 97 98 // Prevent recursion. 99 WillMaterializeAllForwardRefs = true; 100 101 while (!BasicBlockFwdRefQueue.empty()) { 102 Function *F = BasicBlockFwdRefQueue.front(); 103 BasicBlockFwdRefQueue.pop_front(); 104 assert(F && "Expected valid function"); 105 if (!BasicBlockFwdRefs.count(F)) 106 // Already materialized. 107 continue; 108 109 // Check for a function that isn't materializable to prevent an infinite 110 // loop. When parsing a blockaddress stored in a global variable, there 111 // isn't a trivial way to check if a function will have a body without a 112 // linear search through FunctionsWithBodies, so just check it here. 113 if (!F->isMaterializable()) 114 return Error("Never resolved function from blockaddress"); 115 116 // Try to materialize F. 117 if (std::error_code EC = materialize(F)) 118 return EC; 119 } 120 assert(BasicBlockFwdRefs.empty() && "Function missing from queue"); 121 122 // Reset state. 123 WillMaterializeAllForwardRefs = false; 124 return std::error_code(); 125 } 126 127 void BitcodeReader::FreeState() { 128 Buffer = nullptr; 129 std::vector<Type*>().swap(TypeList); 130 ValueList.clear(); 131 MDValueList.clear(); 132 std::vector<Comdat *>().swap(ComdatList); 133 134 std::vector<AttributeSet>().swap(MAttributes); 135 std::vector<BasicBlock*>().swap(FunctionBBs); 136 std::vector<Function*>().swap(FunctionsWithBodies); 137 DeferredFunctionInfo.clear(); 138 MDKindMap.clear(); 139 140 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references"); 141 BasicBlockFwdRefQueue.clear(); 142 } 143 144 //===----------------------------------------------------------------------===// 145 // Helper functions to implement forward reference resolution, etc. 146 //===----------------------------------------------------------------------===// 147 148 /// ConvertToString - Convert a string from a record into an std::string, return 149 /// true on failure. 150 template<typename StrTy> 151 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx, 152 StrTy &Result) { 153 if (Idx > Record.size()) 154 return true; 155 156 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 157 Result += (char)Record[i]; 158 return false; 159 } 160 161 static bool hasImplicitComdat(size_t Val) { 162 switch (Val) { 163 default: 164 return false; 165 case 1: // Old WeakAnyLinkage 166 case 4: // Old LinkOnceAnyLinkage 167 case 10: // Old WeakODRLinkage 168 case 11: // Old LinkOnceODRLinkage 169 return true; 170 } 171 } 172 173 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) { 174 switch (Val) { 175 default: // Map unknown/new linkages to external 176 case 0: 177 return GlobalValue::ExternalLinkage; 178 case 2: 179 return GlobalValue::AppendingLinkage; 180 case 3: 181 return GlobalValue::InternalLinkage; 182 case 5: 183 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage 184 case 6: 185 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage 186 case 7: 187 return GlobalValue::ExternalWeakLinkage; 188 case 8: 189 return GlobalValue::CommonLinkage; 190 case 9: 191 return GlobalValue::PrivateLinkage; 192 case 12: 193 return GlobalValue::AvailableExternallyLinkage; 194 case 13: 195 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage 196 case 14: 197 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage 198 case 15: 199 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage 200 case 1: // Old value with implicit comdat. 201 case 16: 202 return GlobalValue::WeakAnyLinkage; 203 case 10: // Old value with implicit comdat. 204 case 17: 205 return GlobalValue::WeakODRLinkage; 206 case 4: // Old value with implicit comdat. 207 case 18: 208 return GlobalValue::LinkOnceAnyLinkage; 209 case 11: // Old value with implicit comdat. 210 case 19: 211 return GlobalValue::LinkOnceODRLinkage; 212 } 213 } 214 215 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 216 switch (Val) { 217 default: // Map unknown visibilities to default. 218 case 0: return GlobalValue::DefaultVisibility; 219 case 1: return GlobalValue::HiddenVisibility; 220 case 2: return GlobalValue::ProtectedVisibility; 221 } 222 } 223 224 static GlobalValue::DLLStorageClassTypes 225 GetDecodedDLLStorageClass(unsigned Val) { 226 switch (Val) { 227 default: // Map unknown values to default. 228 case 0: return GlobalValue::DefaultStorageClass; 229 case 1: return GlobalValue::DLLImportStorageClass; 230 case 2: return GlobalValue::DLLExportStorageClass; 231 } 232 } 233 234 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) { 235 switch (Val) { 236 case 0: return GlobalVariable::NotThreadLocal; 237 default: // Map unknown non-zero value to general dynamic. 238 case 1: return GlobalVariable::GeneralDynamicTLSModel; 239 case 2: return GlobalVariable::LocalDynamicTLSModel; 240 case 3: return GlobalVariable::InitialExecTLSModel; 241 case 4: return GlobalVariable::LocalExecTLSModel; 242 } 243 } 244 245 static int GetDecodedCastOpcode(unsigned Val) { 246 switch (Val) { 247 default: return -1; 248 case bitc::CAST_TRUNC : return Instruction::Trunc; 249 case bitc::CAST_ZEXT : return Instruction::ZExt; 250 case bitc::CAST_SEXT : return Instruction::SExt; 251 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 252 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 253 case bitc::CAST_UITOFP : return Instruction::UIToFP; 254 case bitc::CAST_SITOFP : return Instruction::SIToFP; 255 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 256 case bitc::CAST_FPEXT : return Instruction::FPExt; 257 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 258 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 259 case bitc::CAST_BITCAST : return Instruction::BitCast; 260 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; 261 } 262 } 263 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) { 264 switch (Val) { 265 default: return -1; 266 case bitc::BINOP_ADD: 267 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add; 268 case bitc::BINOP_SUB: 269 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub; 270 case bitc::BINOP_MUL: 271 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul; 272 case bitc::BINOP_UDIV: return Instruction::UDiv; 273 case bitc::BINOP_SDIV: 274 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv; 275 case bitc::BINOP_UREM: return Instruction::URem; 276 case bitc::BINOP_SREM: 277 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem; 278 case bitc::BINOP_SHL: return Instruction::Shl; 279 case bitc::BINOP_LSHR: return Instruction::LShr; 280 case bitc::BINOP_ASHR: return Instruction::AShr; 281 case bitc::BINOP_AND: return Instruction::And; 282 case bitc::BINOP_OR: return Instruction::Or; 283 case bitc::BINOP_XOR: return Instruction::Xor; 284 } 285 } 286 287 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) { 288 switch (Val) { 289 default: return AtomicRMWInst::BAD_BINOP; 290 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 291 case bitc::RMW_ADD: return AtomicRMWInst::Add; 292 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 293 case bitc::RMW_AND: return AtomicRMWInst::And; 294 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 295 case bitc::RMW_OR: return AtomicRMWInst::Or; 296 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 297 case bitc::RMW_MAX: return AtomicRMWInst::Max; 298 case bitc::RMW_MIN: return AtomicRMWInst::Min; 299 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 300 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 301 } 302 } 303 304 static AtomicOrdering GetDecodedOrdering(unsigned Val) { 305 switch (Val) { 306 case bitc::ORDERING_NOTATOMIC: return NotAtomic; 307 case bitc::ORDERING_UNORDERED: return Unordered; 308 case bitc::ORDERING_MONOTONIC: return Monotonic; 309 case bitc::ORDERING_ACQUIRE: return Acquire; 310 case bitc::ORDERING_RELEASE: return Release; 311 case bitc::ORDERING_ACQREL: return AcquireRelease; 312 default: // Map unknown orderings to sequentially-consistent. 313 case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 314 } 315 } 316 317 static SynchronizationScope GetDecodedSynchScope(unsigned Val) { 318 switch (Val) { 319 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 320 default: // Map unknown scopes to cross-thread. 321 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 322 } 323 } 324 325 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) { 326 switch (Val) { 327 default: // Map unknown selection kinds to any. 328 case bitc::COMDAT_SELECTION_KIND_ANY: 329 return Comdat::Any; 330 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH: 331 return Comdat::ExactMatch; 332 case bitc::COMDAT_SELECTION_KIND_LARGEST: 333 return Comdat::Largest; 334 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES: 335 return Comdat::NoDuplicates; 336 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE: 337 return Comdat::SameSize; 338 } 339 } 340 341 static void UpgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) { 342 switch (Val) { 343 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; 344 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; 345 } 346 } 347 348 namespace llvm { 349 namespace { 350 /// @brief A class for maintaining the slot number definition 351 /// as a placeholder for the actual definition for forward constants defs. 352 class ConstantPlaceHolder : public ConstantExpr { 353 void operator=(const ConstantPlaceHolder &) = delete; 354 public: 355 // allocate space for exactly one operand 356 void *operator new(size_t s) { 357 return User::operator new(s, 1); 358 } 359 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context) 360 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 361 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 362 } 363 364 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 365 static bool classof(const Value *V) { 366 return isa<ConstantExpr>(V) && 367 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 368 } 369 370 371 /// Provide fast operand accessors 372 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 373 }; 374 } 375 376 // FIXME: can we inherit this from ConstantExpr? 377 template <> 378 struct OperandTraits<ConstantPlaceHolder> : 379 public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 380 }; 381 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value) 382 } 383 384 385 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 386 if (Idx == size()) { 387 push_back(V); 388 return; 389 } 390 391 if (Idx >= size()) 392 resize(Idx+1); 393 394 WeakVH &OldV = ValuePtrs[Idx]; 395 if (!OldV) { 396 OldV = V; 397 return; 398 } 399 400 // Handle constants and non-constants (e.g. instrs) differently for 401 // efficiency. 402 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 403 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 404 OldV = V; 405 } else { 406 // If there was a forward reference to this value, replace it. 407 Value *PrevVal = OldV; 408 OldV->replaceAllUsesWith(V); 409 delete PrevVal; 410 } 411 } 412 413 414 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 415 Type *Ty) { 416 if (Idx >= size()) 417 resize(Idx + 1); 418 419 if (Value *V = ValuePtrs[Idx]) { 420 assert(Ty == V->getType() && "Type mismatch in constant table!"); 421 return cast<Constant>(V); 422 } 423 424 // Create and return a placeholder, which will later be RAUW'd. 425 Constant *C = new ConstantPlaceHolder(Ty, Context); 426 ValuePtrs[Idx] = C; 427 return C; 428 } 429 430 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 431 if (Idx >= size()) 432 resize(Idx + 1); 433 434 if (Value *V = ValuePtrs[Idx]) { 435 assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!"); 436 return V; 437 } 438 439 // No type specified, must be invalid reference. 440 if (!Ty) return nullptr; 441 442 // Create and return a placeholder, which will later be RAUW'd. 443 Value *V = new Argument(Ty); 444 ValuePtrs[Idx] = V; 445 return V; 446 } 447 448 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk 449 /// resolves any forward references. The idea behind this is that we sometimes 450 /// get constants (such as large arrays) which reference *many* forward ref 451 /// constants. Replacing each of these causes a lot of thrashing when 452 /// building/reuniquing the constant. Instead of doing this, we look at all the 453 /// uses and rewrite all the place holders at once for any constant that uses 454 /// a placeholder. 455 void BitcodeReaderValueList::ResolveConstantForwardRefs() { 456 // Sort the values by-pointer so that they are efficient to look up with a 457 // binary search. 458 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 459 460 SmallVector<Constant*, 64> NewOps; 461 462 while (!ResolveConstants.empty()) { 463 Value *RealVal = operator[](ResolveConstants.back().second); 464 Constant *Placeholder = ResolveConstants.back().first; 465 ResolveConstants.pop_back(); 466 467 // Loop over all users of the placeholder, updating them to reference the 468 // new value. If they reference more than one placeholder, update them all 469 // at once. 470 while (!Placeholder->use_empty()) { 471 auto UI = Placeholder->user_begin(); 472 User *U = *UI; 473 474 // If the using object isn't uniqued, just update the operands. This 475 // handles instructions and initializers for global variables. 476 if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 477 UI.getUse().set(RealVal); 478 continue; 479 } 480 481 // Otherwise, we have a constant that uses the placeholder. Replace that 482 // constant with a new constant that has *all* placeholder uses updated. 483 Constant *UserC = cast<Constant>(U); 484 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 485 I != E; ++I) { 486 Value *NewOp; 487 if (!isa<ConstantPlaceHolder>(*I)) { 488 // Not a placeholder reference. 489 NewOp = *I; 490 } else if (*I == Placeholder) { 491 // Common case is that it just references this one placeholder. 492 NewOp = RealVal; 493 } else { 494 // Otherwise, look up the placeholder in ResolveConstants. 495 ResolveConstantsTy::iterator It = 496 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 497 std::pair<Constant*, unsigned>(cast<Constant>(*I), 498 0)); 499 assert(It != ResolveConstants.end() && It->first == *I); 500 NewOp = operator[](It->second); 501 } 502 503 NewOps.push_back(cast<Constant>(NewOp)); 504 } 505 506 // Make the new constant. 507 Constant *NewC; 508 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 509 NewC = ConstantArray::get(UserCA->getType(), NewOps); 510 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 511 NewC = ConstantStruct::get(UserCS->getType(), NewOps); 512 } else if (isa<ConstantVector>(UserC)) { 513 NewC = ConstantVector::get(NewOps); 514 } else { 515 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 516 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 517 } 518 519 UserC->replaceAllUsesWith(NewC); 520 UserC->destroyConstant(); 521 NewOps.clear(); 522 } 523 524 // Update all ValueHandles, they should be the only users at this point. 525 Placeholder->replaceAllUsesWith(RealVal); 526 delete Placeholder; 527 } 528 } 529 530 void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) { 531 if (Idx == size()) { 532 push_back(MD); 533 return; 534 } 535 536 if (Idx >= size()) 537 resize(Idx+1); 538 539 TrackingMDRef &OldMD = MDValuePtrs[Idx]; 540 if (!OldMD) { 541 OldMD.reset(MD); 542 return; 543 } 544 545 // If there was a forward reference to this value, replace it. 546 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get())); 547 PrevMD->replaceAllUsesWith(MD); 548 --NumFwdRefs; 549 } 550 551 Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { 552 if (Idx >= size()) 553 resize(Idx + 1); 554 555 if (Metadata *MD = MDValuePtrs[Idx]) 556 return MD; 557 558 // Track forward refs to be resolved later. 559 if (AnyFwdRefs) { 560 MinFwdRef = std::min(MinFwdRef, Idx); 561 MaxFwdRef = std::max(MaxFwdRef, Idx); 562 } else { 563 AnyFwdRefs = true; 564 MinFwdRef = MaxFwdRef = Idx; 565 } 566 ++NumFwdRefs; 567 568 // Create and return a placeholder, which will later be RAUW'd. 569 Metadata *MD = MDNode::getTemporary(Context, None).release(); 570 MDValuePtrs[Idx].reset(MD); 571 return MD; 572 } 573 574 void BitcodeReaderMDValueList::tryToResolveCycles() { 575 if (!AnyFwdRefs) 576 // Nothing to do. 577 return; 578 579 if (NumFwdRefs) 580 // Still forward references... can't resolve cycles. 581 return; 582 583 // Resolve any cycles. 584 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) { 585 auto &MD = MDValuePtrs[I]; 586 auto *N = dyn_cast_or_null<MDNode>(MD); 587 if (!N) 588 continue; 589 590 assert(!N->isTemporary() && "Unexpected forward reference"); 591 N->resolveCycles(); 592 } 593 594 // Make sure we return early again until there's another forward ref. 595 AnyFwdRefs = false; 596 } 597 598 Type *BitcodeReader::getTypeByID(unsigned ID) { 599 // The type table size is always specified correctly. 600 if (ID >= TypeList.size()) 601 return nullptr; 602 603 if (Type *Ty = TypeList[ID]) 604 return Ty; 605 606 // If we have a forward reference, the only possible case is when it is to a 607 // named struct. Just create a placeholder for now. 608 return TypeList[ID] = createIdentifiedStructType(Context); 609 } 610 611 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, 612 StringRef Name) { 613 auto *Ret = StructType::create(Context, Name); 614 IdentifiedStructTypes.push_back(Ret); 615 return Ret; 616 } 617 618 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { 619 auto *Ret = StructType::create(Context); 620 IdentifiedStructTypes.push_back(Ret); 621 return Ret; 622 } 623 624 625 //===----------------------------------------------------------------------===// 626 // Functions for parsing blocks from the bitcode file 627 //===----------------------------------------------------------------------===// 628 629 630 /// \brief This fills an AttrBuilder object with the LLVM attributes that have 631 /// been decoded from the given integer. This function must stay in sync with 632 /// 'encodeLLVMAttributesForBitcode'. 633 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 634 uint64_t EncodedAttrs) { 635 // FIXME: Remove in 4.0. 636 637 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 638 // the bits above 31 down by 11 bits. 639 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 640 assert((!Alignment || isPowerOf2_32(Alignment)) && 641 "Alignment must be a power of two."); 642 643 if (Alignment) 644 B.addAlignmentAttr(Alignment); 645 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 646 (EncodedAttrs & 0xffff)); 647 } 648 649 std::error_code BitcodeReader::ParseAttributeBlock() { 650 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 651 return Error("Invalid record"); 652 653 if (!MAttributes.empty()) 654 return Error("Invalid multiple blocks"); 655 656 SmallVector<uint64_t, 64> Record; 657 658 SmallVector<AttributeSet, 8> Attrs; 659 660 // Read all the records. 661 while (1) { 662 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 663 664 switch (Entry.Kind) { 665 case BitstreamEntry::SubBlock: // Handled for us already. 666 case BitstreamEntry::Error: 667 return Error("Malformed block"); 668 case BitstreamEntry::EndBlock: 669 return std::error_code(); 670 case BitstreamEntry::Record: 671 // The interesting case. 672 break; 673 } 674 675 // Read a record. 676 Record.clear(); 677 switch (Stream.readRecord(Entry.ID, Record)) { 678 default: // Default behavior: ignore. 679 break; 680 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 681 // FIXME: Remove in 4.0. 682 if (Record.size() & 1) 683 return Error("Invalid record"); 684 685 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 686 AttrBuilder B; 687 decodeLLVMAttributesForBitcode(B, Record[i+1]); 688 Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 689 } 690 691 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 692 Attrs.clear(); 693 break; 694 } 695 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 696 for (unsigned i = 0, e = Record.size(); i != e; ++i) 697 Attrs.push_back(MAttributeGroups[Record[i]]); 698 699 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 700 Attrs.clear(); 701 break; 702 } 703 } 704 } 705 } 706 707 // Returns Attribute::None on unrecognized codes. 708 static Attribute::AttrKind GetAttrFromCode(uint64_t Code) { 709 switch (Code) { 710 default: 711 return Attribute::None; 712 case bitc::ATTR_KIND_ALIGNMENT: 713 return Attribute::Alignment; 714 case bitc::ATTR_KIND_ALWAYS_INLINE: 715 return Attribute::AlwaysInline; 716 case bitc::ATTR_KIND_BUILTIN: 717 return Attribute::Builtin; 718 case bitc::ATTR_KIND_BY_VAL: 719 return Attribute::ByVal; 720 case bitc::ATTR_KIND_IN_ALLOCA: 721 return Attribute::InAlloca; 722 case bitc::ATTR_KIND_COLD: 723 return Attribute::Cold; 724 case bitc::ATTR_KIND_INLINE_HINT: 725 return Attribute::InlineHint; 726 case bitc::ATTR_KIND_IN_REG: 727 return Attribute::InReg; 728 case bitc::ATTR_KIND_JUMP_TABLE: 729 return Attribute::JumpTable; 730 case bitc::ATTR_KIND_MIN_SIZE: 731 return Attribute::MinSize; 732 case bitc::ATTR_KIND_NAKED: 733 return Attribute::Naked; 734 case bitc::ATTR_KIND_NEST: 735 return Attribute::Nest; 736 case bitc::ATTR_KIND_NO_ALIAS: 737 return Attribute::NoAlias; 738 case bitc::ATTR_KIND_NO_BUILTIN: 739 return Attribute::NoBuiltin; 740 case bitc::ATTR_KIND_NO_CAPTURE: 741 return Attribute::NoCapture; 742 case bitc::ATTR_KIND_NO_DUPLICATE: 743 return Attribute::NoDuplicate; 744 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT: 745 return Attribute::NoImplicitFloat; 746 case bitc::ATTR_KIND_NO_INLINE: 747 return Attribute::NoInline; 748 case bitc::ATTR_KIND_NON_LAZY_BIND: 749 return Attribute::NonLazyBind; 750 case bitc::ATTR_KIND_NON_NULL: 751 return Attribute::NonNull; 752 case bitc::ATTR_KIND_DEREFERENCEABLE: 753 return Attribute::Dereferenceable; 754 case bitc::ATTR_KIND_NO_RED_ZONE: 755 return Attribute::NoRedZone; 756 case bitc::ATTR_KIND_NO_RETURN: 757 return Attribute::NoReturn; 758 case bitc::ATTR_KIND_NO_UNWIND: 759 return Attribute::NoUnwind; 760 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE: 761 return Attribute::OptimizeForSize; 762 case bitc::ATTR_KIND_OPTIMIZE_NONE: 763 return Attribute::OptimizeNone; 764 case bitc::ATTR_KIND_READ_NONE: 765 return Attribute::ReadNone; 766 case bitc::ATTR_KIND_READ_ONLY: 767 return Attribute::ReadOnly; 768 case bitc::ATTR_KIND_RETURNED: 769 return Attribute::Returned; 770 case bitc::ATTR_KIND_RETURNS_TWICE: 771 return Attribute::ReturnsTwice; 772 case bitc::ATTR_KIND_S_EXT: 773 return Attribute::SExt; 774 case bitc::ATTR_KIND_STACK_ALIGNMENT: 775 return Attribute::StackAlignment; 776 case bitc::ATTR_KIND_STACK_PROTECT: 777 return Attribute::StackProtect; 778 case bitc::ATTR_KIND_STACK_PROTECT_REQ: 779 return Attribute::StackProtectReq; 780 case bitc::ATTR_KIND_STACK_PROTECT_STRONG: 781 return Attribute::StackProtectStrong; 782 case bitc::ATTR_KIND_STRUCT_RET: 783 return Attribute::StructRet; 784 case bitc::ATTR_KIND_SANITIZE_ADDRESS: 785 return Attribute::SanitizeAddress; 786 case bitc::ATTR_KIND_SANITIZE_THREAD: 787 return Attribute::SanitizeThread; 788 case bitc::ATTR_KIND_SANITIZE_MEMORY: 789 return Attribute::SanitizeMemory; 790 case bitc::ATTR_KIND_UW_TABLE: 791 return Attribute::UWTable; 792 case bitc::ATTR_KIND_Z_EXT: 793 return Attribute::ZExt; 794 } 795 } 796 797 std::error_code BitcodeReader::ParseAttrKind(uint64_t Code, 798 Attribute::AttrKind *Kind) { 799 *Kind = GetAttrFromCode(Code); 800 if (*Kind == Attribute::None) 801 return Error(BitcodeError::CorruptedBitcode, 802 "Unknown attribute kind (" + Twine(Code) + ")"); 803 return std::error_code(); 804 } 805 806 std::error_code BitcodeReader::ParseAttributeGroupBlock() { 807 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 808 return Error("Invalid record"); 809 810 if (!MAttributeGroups.empty()) 811 return Error("Invalid multiple blocks"); 812 813 SmallVector<uint64_t, 64> Record; 814 815 // Read all the records. 816 while (1) { 817 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 818 819 switch (Entry.Kind) { 820 case BitstreamEntry::SubBlock: // Handled for us already. 821 case BitstreamEntry::Error: 822 return Error("Malformed block"); 823 case BitstreamEntry::EndBlock: 824 return std::error_code(); 825 case BitstreamEntry::Record: 826 // The interesting case. 827 break; 828 } 829 830 // Read a record. 831 Record.clear(); 832 switch (Stream.readRecord(Entry.ID, Record)) { 833 default: // Default behavior: ignore. 834 break; 835 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 836 if (Record.size() < 3) 837 return Error("Invalid record"); 838 839 uint64_t GrpID = Record[0]; 840 uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 841 842 AttrBuilder B; 843 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 844 if (Record[i] == 0) { // Enum attribute 845 Attribute::AttrKind Kind; 846 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind)) 847 return EC; 848 849 B.addAttribute(Kind); 850 } else if (Record[i] == 1) { // Integer attribute 851 Attribute::AttrKind Kind; 852 if (std::error_code EC = ParseAttrKind(Record[++i], &Kind)) 853 return EC; 854 if (Kind == Attribute::Alignment) 855 B.addAlignmentAttr(Record[++i]); 856 else if (Kind == Attribute::StackAlignment) 857 B.addStackAlignmentAttr(Record[++i]); 858 else if (Kind == Attribute::Dereferenceable) 859 B.addDereferenceableAttr(Record[++i]); 860 } else { // String attribute 861 assert((Record[i] == 3 || Record[i] == 4) && 862 "Invalid attribute group entry"); 863 bool HasValue = (Record[i++] == 4); 864 SmallString<64> KindStr; 865 SmallString<64> ValStr; 866 867 while (Record[i] != 0 && i != e) 868 KindStr += Record[i++]; 869 assert(Record[i] == 0 && "Kind string not null terminated"); 870 871 if (HasValue) { 872 // Has a value associated with it. 873 ++i; // Skip the '0' that terminates the "kind" string. 874 while (Record[i] != 0 && i != e) 875 ValStr += Record[i++]; 876 assert(Record[i] == 0 && "Value string not null terminated"); 877 } 878 879 B.addAttribute(KindStr.str(), ValStr.str()); 880 } 881 } 882 883 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 884 break; 885 } 886 } 887 } 888 } 889 890 std::error_code BitcodeReader::ParseTypeTable() { 891 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 892 return Error("Invalid record"); 893 894 return ParseTypeTableBody(); 895 } 896 897 std::error_code BitcodeReader::ParseTypeTableBody() { 898 if (!TypeList.empty()) 899 return Error("Invalid multiple blocks"); 900 901 SmallVector<uint64_t, 64> Record; 902 unsigned NumRecords = 0; 903 904 SmallString<64> TypeName; 905 906 // Read all the records for this type table. 907 while (1) { 908 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 909 910 switch (Entry.Kind) { 911 case BitstreamEntry::SubBlock: // Handled for us already. 912 case BitstreamEntry::Error: 913 return Error("Malformed block"); 914 case BitstreamEntry::EndBlock: 915 if (NumRecords != TypeList.size()) 916 return Error("Malformed block"); 917 return std::error_code(); 918 case BitstreamEntry::Record: 919 // The interesting case. 920 break; 921 } 922 923 // Read a record. 924 Record.clear(); 925 Type *ResultTy = nullptr; 926 switch (Stream.readRecord(Entry.ID, Record)) { 927 default: 928 return Error("Invalid value"); 929 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 930 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 931 // type list. This allows us to reserve space. 932 if (Record.size() < 1) 933 return Error("Invalid record"); 934 TypeList.resize(Record[0]); 935 continue; 936 case bitc::TYPE_CODE_VOID: // VOID 937 ResultTy = Type::getVoidTy(Context); 938 break; 939 case bitc::TYPE_CODE_HALF: // HALF 940 ResultTy = Type::getHalfTy(Context); 941 break; 942 case bitc::TYPE_CODE_FLOAT: // FLOAT 943 ResultTy = Type::getFloatTy(Context); 944 break; 945 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 946 ResultTy = Type::getDoubleTy(Context); 947 break; 948 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 949 ResultTy = Type::getX86_FP80Ty(Context); 950 break; 951 case bitc::TYPE_CODE_FP128: // FP128 952 ResultTy = Type::getFP128Ty(Context); 953 break; 954 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 955 ResultTy = Type::getPPC_FP128Ty(Context); 956 break; 957 case bitc::TYPE_CODE_LABEL: // LABEL 958 ResultTy = Type::getLabelTy(Context); 959 break; 960 case bitc::TYPE_CODE_METADATA: // METADATA 961 ResultTy = Type::getMetadataTy(Context); 962 break; 963 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 964 ResultTy = Type::getX86_MMXTy(Context); 965 break; 966 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] 967 if (Record.size() < 1) 968 return Error("Invalid record"); 969 970 uint64_t NumBits = Record[0]; 971 if (NumBits < IntegerType::MIN_INT_BITS || 972 NumBits > IntegerType::MAX_INT_BITS) 973 return Error("Bitwidth for integer type out of range"); 974 ResultTy = IntegerType::get(Context, NumBits); 975 break; 976 } 977 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 978 // [pointee type, address space] 979 if (Record.size() < 1) 980 return Error("Invalid record"); 981 unsigned AddressSpace = 0; 982 if (Record.size() == 2) 983 AddressSpace = Record[1]; 984 ResultTy = getTypeByID(Record[0]); 985 if (!ResultTy) 986 return Error("Invalid type"); 987 ResultTy = PointerType::get(ResultTy, AddressSpace); 988 break; 989 } 990 case bitc::TYPE_CODE_FUNCTION_OLD: { 991 // FIXME: attrid is dead, remove it in LLVM 4.0 992 // FUNCTION: [vararg, attrid, retty, paramty x N] 993 if (Record.size() < 3) 994 return Error("Invalid record"); 995 SmallVector<Type*, 8> ArgTys; 996 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 997 if (Type *T = getTypeByID(Record[i])) 998 ArgTys.push_back(T); 999 else 1000 break; 1001 } 1002 1003 ResultTy = getTypeByID(Record[2]); 1004 if (!ResultTy || ArgTys.size() < Record.size()-3) 1005 return Error("Invalid type"); 1006 1007 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1008 break; 1009 } 1010 case bitc::TYPE_CODE_FUNCTION: { 1011 // FUNCTION: [vararg, retty, paramty x N] 1012 if (Record.size() < 2) 1013 return Error("Invalid record"); 1014 SmallVector<Type*, 8> ArgTys; 1015 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 1016 if (Type *T = getTypeByID(Record[i])) 1017 ArgTys.push_back(T); 1018 else 1019 break; 1020 } 1021 1022 ResultTy = getTypeByID(Record[1]); 1023 if (!ResultTy || ArgTys.size() < Record.size()-2) 1024 return Error("Invalid type"); 1025 1026 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 1027 break; 1028 } 1029 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 1030 if (Record.size() < 1) 1031 return Error("Invalid record"); 1032 SmallVector<Type*, 8> EltTys; 1033 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 1034 if (Type *T = getTypeByID(Record[i])) 1035 EltTys.push_back(T); 1036 else 1037 break; 1038 } 1039 if (EltTys.size() != Record.size()-1) 1040 return Error("Invalid type"); 1041 ResultTy = StructType::get(Context, EltTys, Record[0]); 1042 break; 1043 } 1044 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 1045 if (ConvertToString(Record, 0, TypeName)) 1046 return Error("Invalid record"); 1047 continue; 1048 1049 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 1050 if (Record.size() < 1) 1051 return Error("Invalid record"); 1052 1053 if (NumRecords >= TypeList.size()) 1054 return Error("Invalid TYPE table"); 1055 1056 // Check to see if this was forward referenced, if so fill in the temp. 1057 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 1058 if (Res) { 1059 Res->setName(TypeName); 1060 TypeList[NumRecords] = nullptr; 1061 } else // Otherwise, create a new struct. 1062 Res = createIdentifiedStructType(Context, TypeName); 1063 TypeName.clear(); 1064 1065 SmallVector<Type*, 8> EltTys; 1066 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 1067 if (Type *T = getTypeByID(Record[i])) 1068 EltTys.push_back(T); 1069 else 1070 break; 1071 } 1072 if (EltTys.size() != Record.size()-1) 1073 return Error("Invalid record"); 1074 Res->setBody(EltTys, Record[0]); 1075 ResultTy = Res; 1076 break; 1077 } 1078 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 1079 if (Record.size() != 1) 1080 return Error("Invalid record"); 1081 1082 if (NumRecords >= TypeList.size()) 1083 return Error("Invalid TYPE table"); 1084 1085 // Check to see if this was forward referenced, if so fill in the temp. 1086 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 1087 if (Res) { 1088 Res->setName(TypeName); 1089 TypeList[NumRecords] = nullptr; 1090 } else // Otherwise, create a new struct with no body. 1091 Res = createIdentifiedStructType(Context, TypeName); 1092 TypeName.clear(); 1093 ResultTy = Res; 1094 break; 1095 } 1096 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 1097 if (Record.size() < 2) 1098 return Error("Invalid record"); 1099 if ((ResultTy = getTypeByID(Record[1]))) 1100 ResultTy = ArrayType::get(ResultTy, Record[0]); 1101 else 1102 return Error("Invalid type"); 1103 break; 1104 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 1105 if (Record.size() < 2) 1106 return Error("Invalid record"); 1107 if ((ResultTy = getTypeByID(Record[1]))) 1108 ResultTy = VectorType::get(ResultTy, Record[0]); 1109 else 1110 return Error("Invalid type"); 1111 break; 1112 } 1113 1114 if (NumRecords >= TypeList.size()) 1115 return Error("Invalid TYPE table"); 1116 if (TypeList[NumRecords]) 1117 return Error( 1118 "Invalid TYPE table: Only named structs can be forward referenced"); 1119 assert(ResultTy && "Didn't read a type?"); 1120 TypeList[NumRecords++] = ResultTy; 1121 } 1122 } 1123 1124 std::error_code BitcodeReader::ParseValueSymbolTable() { 1125 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 1126 return Error("Invalid record"); 1127 1128 SmallVector<uint64_t, 64> Record; 1129 1130 Triple TT(TheModule->getTargetTriple()); 1131 1132 // Read all the records for this value table. 1133 SmallString<128> ValueName; 1134 while (1) { 1135 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1136 1137 switch (Entry.Kind) { 1138 case BitstreamEntry::SubBlock: // Handled for us already. 1139 case BitstreamEntry::Error: 1140 return Error("Malformed block"); 1141 case BitstreamEntry::EndBlock: 1142 return std::error_code(); 1143 case BitstreamEntry::Record: 1144 // The interesting case. 1145 break; 1146 } 1147 1148 // Read a record. 1149 Record.clear(); 1150 switch (Stream.readRecord(Entry.ID, Record)) { 1151 default: // Default behavior: unknown type. 1152 break; 1153 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 1154 if (ConvertToString(Record, 1, ValueName)) 1155 return Error("Invalid record"); 1156 unsigned ValueID = Record[0]; 1157 if (ValueID >= ValueList.size() || !ValueList[ValueID]) 1158 return Error("Invalid record"); 1159 Value *V = ValueList[ValueID]; 1160 1161 V->setName(StringRef(ValueName.data(), ValueName.size())); 1162 if (auto *GO = dyn_cast<GlobalObject>(V)) { 1163 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) { 1164 if (TT.isOSBinFormatMachO()) 1165 GO->setComdat(nullptr); 1166 else 1167 GO->setComdat(TheModule->getOrInsertComdat(V->getName())); 1168 } 1169 } 1170 ValueName.clear(); 1171 break; 1172 } 1173 case bitc::VST_CODE_BBENTRY: { 1174 if (ConvertToString(Record, 1, ValueName)) 1175 return Error("Invalid record"); 1176 BasicBlock *BB = getBasicBlock(Record[0]); 1177 if (!BB) 1178 return Error("Invalid record"); 1179 1180 BB->setName(StringRef(ValueName.data(), ValueName.size())); 1181 ValueName.clear(); 1182 break; 1183 } 1184 } 1185 } 1186 } 1187 1188 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; } 1189 1190 std::error_code BitcodeReader::ParseMetadata() { 1191 unsigned NextMDValueNo = MDValueList.size(); 1192 1193 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 1194 return Error("Invalid record"); 1195 1196 SmallVector<uint64_t, 64> Record; 1197 1198 auto getMD = 1199 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); }; 1200 auto getMDOrNull = [&](unsigned ID) -> Metadata *{ 1201 if (ID) 1202 return getMD(ID - 1); 1203 return nullptr; 1204 }; 1205 auto getMDString = [&](unsigned ID) -> MDString *{ 1206 // This requires that the ID is not really a forward reference. In 1207 // particular, the MDString must already have been resolved. 1208 return cast_or_null<MDString>(getMDOrNull(ID)); 1209 }; 1210 1211 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \ 1212 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS) 1213 1214 // Read all the records. 1215 while (1) { 1216 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1217 1218 switch (Entry.Kind) { 1219 case BitstreamEntry::SubBlock: // Handled for us already. 1220 case BitstreamEntry::Error: 1221 return Error("Malformed block"); 1222 case BitstreamEntry::EndBlock: 1223 MDValueList.tryToResolveCycles(); 1224 return std::error_code(); 1225 case BitstreamEntry::Record: 1226 // The interesting case. 1227 break; 1228 } 1229 1230 // Read a record. 1231 Record.clear(); 1232 unsigned Code = Stream.readRecord(Entry.ID, Record); 1233 bool IsDistinct = false; 1234 switch (Code) { 1235 default: // Default behavior: ignore. 1236 break; 1237 case bitc::METADATA_NAME: { 1238 // Read name of the named metadata. 1239 SmallString<8> Name(Record.begin(), Record.end()); 1240 Record.clear(); 1241 Code = Stream.ReadCode(); 1242 1243 // METADATA_NAME is always followed by METADATA_NAMED_NODE. 1244 unsigned NextBitCode = Stream.readRecord(Code, Record); 1245 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode; 1246 1247 // Read named metadata elements. 1248 unsigned Size = Record.size(); 1249 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 1250 for (unsigned i = 0; i != Size; ++i) { 1251 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i])); 1252 if (!MD) 1253 return Error("Invalid record"); 1254 NMD->addOperand(MD); 1255 } 1256 break; 1257 } 1258 case bitc::METADATA_OLD_FN_NODE: { 1259 // FIXME: Remove in 4.0. 1260 // This is a LocalAsMetadata record, the only type of function-local 1261 // metadata. 1262 if (Record.size() % 2 == 1) 1263 return Error("Invalid record"); 1264 1265 // If this isn't a LocalAsMetadata record, we're dropping it. This used 1266 // to be legal, but there's no upgrade path. 1267 auto dropRecord = [&] { 1268 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++); 1269 }; 1270 if (Record.size() != 2) { 1271 dropRecord(); 1272 break; 1273 } 1274 1275 Type *Ty = getTypeByID(Record[0]); 1276 if (Ty->isMetadataTy() || Ty->isVoidTy()) { 1277 dropRecord(); 1278 break; 1279 } 1280 1281 MDValueList.AssignValue( 1282 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 1283 NextMDValueNo++); 1284 break; 1285 } 1286 case bitc::METADATA_OLD_NODE: { 1287 // FIXME: Remove in 4.0. 1288 if (Record.size() % 2 == 1) 1289 return Error("Invalid record"); 1290 1291 unsigned Size = Record.size(); 1292 SmallVector<Metadata *, 8> Elts; 1293 for (unsigned i = 0; i != Size; i += 2) { 1294 Type *Ty = getTypeByID(Record[i]); 1295 if (!Ty) 1296 return Error("Invalid record"); 1297 if (Ty->isMetadataTy()) 1298 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 1299 else if (!Ty->isVoidTy()) { 1300 auto *MD = 1301 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 1302 assert(isa<ConstantAsMetadata>(MD) && 1303 "Expected non-function-local metadata"); 1304 Elts.push_back(MD); 1305 } else 1306 Elts.push_back(nullptr); 1307 } 1308 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++); 1309 break; 1310 } 1311 case bitc::METADATA_VALUE: { 1312 if (Record.size() != 2) 1313 return Error("Invalid record"); 1314 1315 Type *Ty = getTypeByID(Record[0]); 1316 if (Ty->isMetadataTy() || Ty->isVoidTy()) 1317 return Error("Invalid record"); 1318 1319 MDValueList.AssignValue( 1320 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 1321 NextMDValueNo++); 1322 break; 1323 } 1324 case bitc::METADATA_DISTINCT_NODE: 1325 IsDistinct = true; 1326 // fallthrough... 1327 case bitc::METADATA_NODE: { 1328 SmallVector<Metadata *, 8> Elts; 1329 Elts.reserve(Record.size()); 1330 for (unsigned ID : Record) 1331 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr); 1332 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 1333 : MDNode::get(Context, Elts), 1334 NextMDValueNo++); 1335 break; 1336 } 1337 case bitc::METADATA_LOCATION: { 1338 if (Record.size() != 5) 1339 return Error("Invalid record"); 1340 1341 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get; 1342 unsigned Line = Record[1]; 1343 unsigned Column = Record[2]; 1344 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3])); 1345 Metadata *InlinedAt = 1346 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr; 1347 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt), 1348 NextMDValueNo++); 1349 break; 1350 } 1351 case bitc::METADATA_GENERIC_DEBUG: { 1352 if (Record.size() < 4) 1353 return Error("Invalid record"); 1354 1355 unsigned Tag = Record[1]; 1356 unsigned Version = Record[2]; 1357 1358 if (Tag >= 1u << 16 || Version != 0) 1359 return Error("Invalid record"); 1360 1361 auto *Header = getMDString(Record[3]); 1362 SmallVector<Metadata *, 8> DwarfOps; 1363 for (unsigned I = 4, E = Record.size(); I != E; ++I) 1364 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1) 1365 : nullptr); 1366 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0], 1367 (Context, Tag, Header, DwarfOps)), 1368 NextMDValueNo++); 1369 break; 1370 } 1371 case bitc::METADATA_SUBRANGE: { 1372 if (Record.size() != 3) 1373 return Error("Invalid record"); 1374 1375 MDValueList.AssignValue( 1376 GET_OR_DISTINCT(MDSubrange, Record[0], 1377 (Context, Record[1], unrotateSign(Record[2]))), 1378 NextMDValueNo++); 1379 break; 1380 } 1381 case bitc::METADATA_ENUMERATOR: { 1382 if (Record.size() != 3) 1383 return Error("Invalid record"); 1384 1385 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0], 1386 (Context, unrotateSign(Record[1]), 1387 getMDString(Record[2]))), 1388 NextMDValueNo++); 1389 break; 1390 } 1391 case bitc::METADATA_BASIC_TYPE: { 1392 if (Record.size() != 6) 1393 return Error("Invalid record"); 1394 1395 MDValueList.AssignValue( 1396 GET_OR_DISTINCT(MDBasicType, Record[0], 1397 (Context, Record[1], getMDString(Record[2]), 1398 Record[3], Record[4], Record[5])), 1399 NextMDValueNo++); 1400 break; 1401 } 1402 case bitc::METADATA_DERIVED_TYPE: { 1403 if (Record.size() != 12) 1404 return Error("Invalid record"); 1405 1406 MDValueList.AssignValue( 1407 GET_OR_DISTINCT(MDDerivedType, Record[0], 1408 (Context, Record[1], getMDString(Record[2]), 1409 getMDOrNull(Record[3]), Record[4], 1410 getMDOrNull(Record[5]), getMD(Record[6]), Record[7], 1411 Record[8], Record[9], Record[10], 1412 getMDOrNull(Record[11]))), 1413 NextMDValueNo++); 1414 break; 1415 } 1416 case bitc::METADATA_COMPOSITE_TYPE: { 1417 if (Record.size() != 16) 1418 return Error("Invalid record"); 1419 1420 MDValueList.AssignValue( 1421 GET_OR_DISTINCT(MDCompositeType, Record[0], 1422 (Context, Record[1], getMDString(Record[2]), 1423 getMDOrNull(Record[3]), Record[4], 1424 getMDOrNull(Record[5]), getMDOrNull(Record[6]), 1425 Record[7], Record[8], Record[9], Record[10], 1426 getMDOrNull(Record[11]), Record[12], 1427 getMDOrNull(Record[13]), getMDOrNull(Record[14]), 1428 getMDString(Record[15]))), 1429 NextMDValueNo++); 1430 break; 1431 } 1432 case bitc::METADATA_SUBROUTINE_TYPE: { 1433 if (Record.size() != 3) 1434 return Error("Invalid record"); 1435 1436 MDValueList.AssignValue( 1437 GET_OR_DISTINCT(MDSubroutineType, Record[0], 1438 (Context, Record[1], getMDOrNull(Record[2]))), 1439 NextMDValueNo++); 1440 break; 1441 } 1442 case bitc::METADATA_FILE: { 1443 if (Record.size() != 3) 1444 return Error("Invalid record"); 1445 1446 MDValueList.AssignValue( 1447 GET_OR_DISTINCT(MDFile, Record[0], (Context, getMDString(Record[1]), 1448 getMDString(Record[2]))), 1449 NextMDValueNo++); 1450 break; 1451 } 1452 case bitc::METADATA_COMPILE_UNIT: { 1453 if (Record.size() != 14) 1454 return Error("Invalid record"); 1455 1456 MDValueList.AssignValue( 1457 GET_OR_DISTINCT( 1458 MDCompileUnit, Record[0], 1459 (Context, Record[1], getMD(Record[2]), getMDString(Record[3]), 1460 Record[4], getMDString(Record[5]), Record[6], 1461 getMDString(Record[7]), Record[8], getMDOrNull(Record[9]), 1462 getMDOrNull(Record[10]), getMDOrNull(Record[11]), 1463 getMDOrNull(Record[12]), getMDOrNull(Record[13]))), 1464 NextMDValueNo++); 1465 break; 1466 } 1467 case bitc::METADATA_SUBPROGRAM: { 1468 if (Record.size() != 19) 1469 return Error("Invalid record"); 1470 1471 MDValueList.AssignValue( 1472 GET_OR_DISTINCT( 1473 MDSubprogram, Record[0], 1474 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 1475 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 1476 getMDOrNull(Record[6]), Record[7], Record[8], Record[9], 1477 getMDOrNull(Record[10]), Record[11], Record[12], Record[13], 1478 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]), 1479 getMDOrNull(Record[17]), getMDOrNull(Record[18]))), 1480 NextMDValueNo++); 1481 break; 1482 } 1483 case bitc::METADATA_LEXICAL_BLOCK: { 1484 if (Record.size() != 5) 1485 return Error("Invalid record"); 1486 1487 MDValueList.AssignValue( 1488 GET_OR_DISTINCT(MDLexicalBlock, Record[0], 1489 (Context, getMDOrNull(Record[1]), 1490 getMDOrNull(Record[2]), Record[3], Record[4])), 1491 NextMDValueNo++); 1492 break; 1493 } 1494 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 1495 if (Record.size() != 4) 1496 return Error("Invalid record"); 1497 1498 MDValueList.AssignValue( 1499 GET_OR_DISTINCT(MDLexicalBlockFile, Record[0], 1500 (Context, getMDOrNull(Record[1]), 1501 getMDOrNull(Record[2]), Record[3])), 1502 NextMDValueNo++); 1503 break; 1504 } 1505 case bitc::METADATA_NAMESPACE: { 1506 if (Record.size() != 5) 1507 return Error("Invalid record"); 1508 1509 MDValueList.AssignValue( 1510 GET_OR_DISTINCT(MDNamespace, Record[0], 1511 (Context, getMDOrNull(Record[1]), 1512 getMDOrNull(Record[2]), getMDString(Record[3]), 1513 Record[4])), 1514 NextMDValueNo++); 1515 break; 1516 } 1517 case bitc::METADATA_TEMPLATE_TYPE: { 1518 if (Record.size() != 3) 1519 return Error("Invalid record"); 1520 1521 MDValueList.AssignValue(GET_OR_DISTINCT(MDTemplateTypeParameter, 1522 Record[0], 1523 (Context, getMDString(Record[1]), 1524 getMDOrNull(Record[2]))), 1525 NextMDValueNo++); 1526 break; 1527 } 1528 case bitc::METADATA_TEMPLATE_VALUE: { 1529 if (Record.size() != 5) 1530 return Error("Invalid record"); 1531 1532 MDValueList.AssignValue( 1533 GET_OR_DISTINCT(MDTemplateValueParameter, Record[0], 1534 (Context, Record[1], getMDString(Record[2]), 1535 getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 1536 NextMDValueNo++); 1537 break; 1538 } 1539 case bitc::METADATA_GLOBAL_VAR: { 1540 if (Record.size() != 11) 1541 return Error("Invalid record"); 1542 1543 MDValueList.AssignValue( 1544 GET_OR_DISTINCT(MDGlobalVariable, Record[0], 1545 (Context, getMDOrNull(Record[1]), 1546 getMDString(Record[2]), getMDString(Record[3]), 1547 getMDOrNull(Record[4]), Record[5], 1548 getMDOrNull(Record[6]), Record[7], Record[8], 1549 getMDOrNull(Record[9]), getMDOrNull(Record[10]))), 1550 NextMDValueNo++); 1551 break; 1552 } 1553 case bitc::METADATA_LOCAL_VAR: { 1554 if (Record.size() != 10) 1555 return Error("Invalid record"); 1556 1557 MDValueList.AssignValue( 1558 GET_OR_DISTINCT(MDLocalVariable, Record[0], 1559 (Context, Record[1], getMDOrNull(Record[2]), 1560 getMDString(Record[3]), getMDOrNull(Record[4]), 1561 Record[5], getMDOrNull(Record[6]), Record[7], 1562 Record[8], getMDOrNull(Record[9]))), 1563 NextMDValueNo++); 1564 break; 1565 } 1566 case bitc::METADATA_EXPRESSION: { 1567 if (Record.size() < 1) 1568 return Error("Invalid record"); 1569 1570 MDValueList.AssignValue( 1571 GET_OR_DISTINCT(MDExpression, Record[0], 1572 (Context, makeArrayRef(Record).slice(1))), 1573 NextMDValueNo++); 1574 break; 1575 } 1576 case bitc::METADATA_OBJC_PROPERTY: { 1577 if (Record.size() != 8) 1578 return Error("Invalid record"); 1579 1580 MDValueList.AssignValue( 1581 GET_OR_DISTINCT(MDObjCProperty, Record[0], 1582 (Context, getMDString(Record[1]), 1583 getMDOrNull(Record[2]), Record[3], 1584 getMDString(Record[4]), getMDString(Record[5]), 1585 Record[6], getMDOrNull(Record[7]))), 1586 NextMDValueNo++); 1587 break; 1588 } 1589 case bitc::METADATA_IMPORTED_ENTITY: { 1590 if (Record.size() != 6) 1591 return Error("Invalid record"); 1592 1593 MDValueList.AssignValue( 1594 GET_OR_DISTINCT(MDImportedEntity, Record[0], 1595 (Context, Record[1], getMDOrNull(Record[2]), 1596 getMDOrNull(Record[3]), Record[4], 1597 getMDString(Record[5]))), 1598 NextMDValueNo++); 1599 break; 1600 } 1601 case bitc::METADATA_STRING: { 1602 std::string String(Record.begin(), Record.end()); 1603 llvm::UpgradeMDStringConstant(String); 1604 Metadata *MD = MDString::get(Context, String); 1605 MDValueList.AssignValue(MD, NextMDValueNo++); 1606 break; 1607 } 1608 case bitc::METADATA_KIND: { 1609 if (Record.size() < 2) 1610 return Error("Invalid record"); 1611 1612 unsigned Kind = Record[0]; 1613 SmallString<8> Name(Record.begin()+1, Record.end()); 1614 1615 unsigned NewKind = TheModule->getMDKindID(Name.str()); 1616 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1617 return Error("Conflicting METADATA_KIND records"); 1618 break; 1619 } 1620 } 1621 } 1622 #undef GET_OR_DISTINCT 1623 } 1624 1625 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 1626 /// the LSB for dense VBR encoding. 1627 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 1628 if ((V & 1) == 0) 1629 return V >> 1; 1630 if (V != 1) 1631 return -(V >> 1); 1632 // There is no such thing as -0 with integers. "-0" really means MININT. 1633 return 1ULL << 63; 1634 } 1635 1636 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 1637 /// values and aliases that we can. 1638 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() { 1639 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 1640 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 1641 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 1642 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 1643 1644 GlobalInitWorklist.swap(GlobalInits); 1645 AliasInitWorklist.swap(AliasInits); 1646 FunctionPrefixWorklist.swap(FunctionPrefixes); 1647 FunctionPrologueWorklist.swap(FunctionPrologues); 1648 1649 while (!GlobalInitWorklist.empty()) { 1650 unsigned ValID = GlobalInitWorklist.back().second; 1651 if (ValID >= ValueList.size()) { 1652 // Not ready to resolve this yet, it requires something later in the file. 1653 GlobalInits.push_back(GlobalInitWorklist.back()); 1654 } else { 1655 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1656 GlobalInitWorklist.back().first->setInitializer(C); 1657 else 1658 return Error("Expected a constant"); 1659 } 1660 GlobalInitWorklist.pop_back(); 1661 } 1662 1663 while (!AliasInitWorklist.empty()) { 1664 unsigned ValID = AliasInitWorklist.back().second; 1665 if (ValID >= ValueList.size()) { 1666 AliasInits.push_back(AliasInitWorklist.back()); 1667 } else { 1668 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1669 AliasInitWorklist.back().first->setAliasee(C); 1670 else 1671 return Error("Expected a constant"); 1672 } 1673 AliasInitWorklist.pop_back(); 1674 } 1675 1676 while (!FunctionPrefixWorklist.empty()) { 1677 unsigned ValID = FunctionPrefixWorklist.back().second; 1678 if (ValID >= ValueList.size()) { 1679 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 1680 } else { 1681 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1682 FunctionPrefixWorklist.back().first->setPrefixData(C); 1683 else 1684 return Error("Expected a constant"); 1685 } 1686 FunctionPrefixWorklist.pop_back(); 1687 } 1688 1689 while (!FunctionPrologueWorklist.empty()) { 1690 unsigned ValID = FunctionPrologueWorklist.back().second; 1691 if (ValID >= ValueList.size()) { 1692 FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 1693 } else { 1694 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1695 FunctionPrologueWorklist.back().first->setPrologueData(C); 1696 else 1697 return Error("Expected a constant"); 1698 } 1699 FunctionPrologueWorklist.pop_back(); 1700 } 1701 1702 return std::error_code(); 1703 } 1704 1705 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 1706 SmallVector<uint64_t, 8> Words(Vals.size()); 1707 std::transform(Vals.begin(), Vals.end(), Words.begin(), 1708 BitcodeReader::decodeSignRotatedValue); 1709 1710 return APInt(TypeBits, Words); 1711 } 1712 1713 std::error_code BitcodeReader::ParseConstants() { 1714 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 1715 return Error("Invalid record"); 1716 1717 SmallVector<uint64_t, 64> Record; 1718 1719 // Read all the records for this value table. 1720 Type *CurTy = Type::getInt32Ty(Context); 1721 unsigned NextCstNo = ValueList.size(); 1722 while (1) { 1723 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1724 1725 switch (Entry.Kind) { 1726 case BitstreamEntry::SubBlock: // Handled for us already. 1727 case BitstreamEntry::Error: 1728 return Error("Malformed block"); 1729 case BitstreamEntry::EndBlock: 1730 if (NextCstNo != ValueList.size()) 1731 return Error("Invalid ronstant reference"); 1732 1733 // Once all the constants have been read, go through and resolve forward 1734 // references. 1735 ValueList.ResolveConstantForwardRefs(); 1736 return std::error_code(); 1737 case BitstreamEntry::Record: 1738 // The interesting case. 1739 break; 1740 } 1741 1742 // Read a record. 1743 Record.clear(); 1744 Value *V = nullptr; 1745 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1746 switch (BitCode) { 1747 default: // Default behavior: unknown constant 1748 case bitc::CST_CODE_UNDEF: // UNDEF 1749 V = UndefValue::get(CurTy); 1750 break; 1751 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 1752 if (Record.empty()) 1753 return Error("Invalid record"); 1754 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 1755 return Error("Invalid record"); 1756 CurTy = TypeList[Record[0]]; 1757 continue; // Skip the ValueList manipulation. 1758 case bitc::CST_CODE_NULL: // NULL 1759 V = Constant::getNullValue(CurTy); 1760 break; 1761 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 1762 if (!CurTy->isIntegerTy() || Record.empty()) 1763 return Error("Invalid record"); 1764 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 1765 break; 1766 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 1767 if (!CurTy->isIntegerTy() || Record.empty()) 1768 return Error("Invalid record"); 1769 1770 APInt VInt = ReadWideAPInt(Record, 1771 cast<IntegerType>(CurTy)->getBitWidth()); 1772 V = ConstantInt::get(Context, VInt); 1773 1774 break; 1775 } 1776 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1777 if (Record.empty()) 1778 return Error("Invalid record"); 1779 if (CurTy->isHalfTy()) 1780 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 1781 APInt(16, (uint16_t)Record[0]))); 1782 else if (CurTy->isFloatTy()) 1783 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 1784 APInt(32, (uint32_t)Record[0]))); 1785 else if (CurTy->isDoubleTy()) 1786 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 1787 APInt(64, Record[0]))); 1788 else if (CurTy->isX86_FP80Ty()) { 1789 // Bits are not stored the same way as a normal i80 APInt, compensate. 1790 uint64_t Rearrange[2]; 1791 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1792 Rearrange[1] = Record[0] >> 48; 1793 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 1794 APInt(80, Rearrange))); 1795 } else if (CurTy->isFP128Ty()) 1796 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 1797 APInt(128, Record))); 1798 else if (CurTy->isPPC_FP128Ty()) 1799 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 1800 APInt(128, Record))); 1801 else 1802 V = UndefValue::get(CurTy); 1803 break; 1804 } 1805 1806 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1807 if (Record.empty()) 1808 return Error("Invalid record"); 1809 1810 unsigned Size = Record.size(); 1811 SmallVector<Constant*, 16> Elts; 1812 1813 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1814 for (unsigned i = 0; i != Size; ++i) 1815 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1816 STy->getElementType(i))); 1817 V = ConstantStruct::get(STy, Elts); 1818 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1819 Type *EltTy = ATy->getElementType(); 1820 for (unsigned i = 0; i != Size; ++i) 1821 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1822 V = ConstantArray::get(ATy, Elts); 1823 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1824 Type *EltTy = VTy->getElementType(); 1825 for (unsigned i = 0; i != Size; ++i) 1826 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1827 V = ConstantVector::get(Elts); 1828 } else { 1829 V = UndefValue::get(CurTy); 1830 } 1831 break; 1832 } 1833 case bitc::CST_CODE_STRING: // STRING: [values] 1834 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1835 if (Record.empty()) 1836 return Error("Invalid record"); 1837 1838 SmallString<16> Elts(Record.begin(), Record.end()); 1839 V = ConstantDataArray::getString(Context, Elts, 1840 BitCode == bitc::CST_CODE_CSTRING); 1841 break; 1842 } 1843 case bitc::CST_CODE_DATA: {// DATA: [n x value] 1844 if (Record.empty()) 1845 return Error("Invalid record"); 1846 1847 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 1848 unsigned Size = Record.size(); 1849 1850 if (EltTy->isIntegerTy(8)) { 1851 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 1852 if (isa<VectorType>(CurTy)) 1853 V = ConstantDataVector::get(Context, Elts); 1854 else 1855 V = ConstantDataArray::get(Context, Elts); 1856 } else if (EltTy->isIntegerTy(16)) { 1857 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 1858 if (isa<VectorType>(CurTy)) 1859 V = ConstantDataVector::get(Context, Elts); 1860 else 1861 V = ConstantDataArray::get(Context, Elts); 1862 } else if (EltTy->isIntegerTy(32)) { 1863 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 1864 if (isa<VectorType>(CurTy)) 1865 V = ConstantDataVector::get(Context, Elts); 1866 else 1867 V = ConstantDataArray::get(Context, Elts); 1868 } else if (EltTy->isIntegerTy(64)) { 1869 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 1870 if (isa<VectorType>(CurTy)) 1871 V = ConstantDataVector::get(Context, Elts); 1872 else 1873 V = ConstantDataArray::get(Context, Elts); 1874 } else if (EltTy->isFloatTy()) { 1875 SmallVector<float, 16> Elts(Size); 1876 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 1877 if (isa<VectorType>(CurTy)) 1878 V = ConstantDataVector::get(Context, Elts); 1879 else 1880 V = ConstantDataArray::get(Context, Elts); 1881 } else if (EltTy->isDoubleTy()) { 1882 SmallVector<double, 16> Elts(Size); 1883 std::transform(Record.begin(), Record.end(), Elts.begin(), 1884 BitsToDouble); 1885 if (isa<VectorType>(CurTy)) 1886 V = ConstantDataVector::get(Context, Elts); 1887 else 1888 V = ConstantDataArray::get(Context, Elts); 1889 } else { 1890 return Error("Invalid type for value"); 1891 } 1892 break; 1893 } 1894 1895 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1896 if (Record.size() < 3) 1897 return Error("Invalid record"); 1898 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1899 if (Opc < 0) { 1900 V = UndefValue::get(CurTy); // Unknown binop. 1901 } else { 1902 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1903 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1904 unsigned Flags = 0; 1905 if (Record.size() >= 4) { 1906 if (Opc == Instruction::Add || 1907 Opc == Instruction::Sub || 1908 Opc == Instruction::Mul || 1909 Opc == Instruction::Shl) { 1910 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1911 Flags |= OverflowingBinaryOperator::NoSignedWrap; 1912 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1913 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1914 } else if (Opc == Instruction::SDiv || 1915 Opc == Instruction::UDiv || 1916 Opc == Instruction::LShr || 1917 Opc == Instruction::AShr) { 1918 if (Record[3] & (1 << bitc::PEO_EXACT)) 1919 Flags |= SDivOperator::IsExact; 1920 } 1921 } 1922 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1923 } 1924 break; 1925 } 1926 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1927 if (Record.size() < 3) 1928 return Error("Invalid record"); 1929 int Opc = GetDecodedCastOpcode(Record[0]); 1930 if (Opc < 0) { 1931 V = UndefValue::get(CurTy); // Unknown cast. 1932 } else { 1933 Type *OpTy = getTypeByID(Record[1]); 1934 if (!OpTy) 1935 return Error("Invalid record"); 1936 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1937 V = UpgradeBitCastExpr(Opc, Op, CurTy); 1938 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 1939 } 1940 break; 1941 } 1942 case bitc::CST_CODE_CE_INBOUNDS_GEP: 1943 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1944 if (Record.size() & 1) 1945 return Error("Invalid record"); 1946 SmallVector<Constant*, 16> Elts; 1947 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1948 Type *ElTy = getTypeByID(Record[i]); 1949 if (!ElTy) 1950 return Error("Invalid record"); 1951 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1952 } 1953 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1954 V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 1955 BitCode == 1956 bitc::CST_CODE_CE_INBOUNDS_GEP); 1957 break; 1958 } 1959 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 1960 if (Record.size() < 3) 1961 return Error("Invalid record"); 1962 1963 Type *SelectorTy = Type::getInt1Ty(Context); 1964 1965 // If CurTy is a vector of length n, then Record[0] must be a <n x i1> 1966 // vector. Otherwise, it must be a single bit. 1967 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 1968 SelectorTy = VectorType::get(Type::getInt1Ty(Context), 1969 VTy->getNumElements()); 1970 1971 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 1972 SelectorTy), 1973 ValueList.getConstantFwdRef(Record[1],CurTy), 1974 ValueList.getConstantFwdRef(Record[2],CurTy)); 1975 break; 1976 } 1977 case bitc::CST_CODE_CE_EXTRACTELT 1978 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 1979 if (Record.size() < 3) 1980 return Error("Invalid record"); 1981 VectorType *OpTy = 1982 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1983 if (!OpTy) 1984 return Error("Invalid record"); 1985 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1986 Constant *Op1 = nullptr; 1987 if (Record.size() == 4) { 1988 Type *IdxTy = getTypeByID(Record[2]); 1989 if (!IdxTy) 1990 return Error("Invalid record"); 1991 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1992 } else // TODO: Remove with llvm 4.0 1993 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1994 if (!Op1) 1995 return Error("Invalid record"); 1996 V = ConstantExpr::getExtractElement(Op0, Op1); 1997 break; 1998 } 1999 case bitc::CST_CODE_CE_INSERTELT 2000 : { // CE_INSERTELT: [opval, opval, opty, opval] 2001 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 2002 if (Record.size() < 3 || !OpTy) 2003 return Error("Invalid record"); 2004 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2005 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 2006 OpTy->getElementType()); 2007 Constant *Op2 = nullptr; 2008 if (Record.size() == 4) { 2009 Type *IdxTy = getTypeByID(Record[2]); 2010 if (!IdxTy) 2011 return Error("Invalid record"); 2012 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 2013 } else // TODO: Remove with llvm 4.0 2014 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 2015 if (!Op2) 2016 return Error("Invalid record"); 2017 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 2018 break; 2019 } 2020 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 2021 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 2022 if (Record.size() < 3 || !OpTy) 2023 return Error("Invalid record"); 2024 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 2025 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 2026 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2027 OpTy->getNumElements()); 2028 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 2029 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2030 break; 2031 } 2032 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 2033 VectorType *RTy = dyn_cast<VectorType>(CurTy); 2034 VectorType *OpTy = 2035 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 2036 if (Record.size() < 4 || !RTy || !OpTy) 2037 return Error("Invalid record"); 2038 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2039 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2040 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 2041 RTy->getNumElements()); 2042 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 2043 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 2044 break; 2045 } 2046 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 2047 if (Record.size() < 4) 2048 return Error("Invalid record"); 2049 Type *OpTy = getTypeByID(Record[0]); 2050 if (!OpTy) 2051 return Error("Invalid record"); 2052 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 2053 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 2054 2055 if (OpTy->isFPOrFPVectorTy()) 2056 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 2057 else 2058 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 2059 break; 2060 } 2061 // This maintains backward compatibility, pre-asm dialect keywords. 2062 // FIXME: Remove with the 4.0 release. 2063 case bitc::CST_CODE_INLINEASM_OLD: { 2064 if (Record.size() < 2) 2065 return Error("Invalid record"); 2066 std::string AsmStr, ConstrStr; 2067 bool HasSideEffects = Record[0] & 1; 2068 bool IsAlignStack = Record[0] >> 1; 2069 unsigned AsmStrSize = Record[1]; 2070 if (2+AsmStrSize >= Record.size()) 2071 return Error("Invalid record"); 2072 unsigned ConstStrSize = Record[2+AsmStrSize]; 2073 if (3+AsmStrSize+ConstStrSize > Record.size()) 2074 return Error("Invalid record"); 2075 2076 for (unsigned i = 0; i != AsmStrSize; ++i) 2077 AsmStr += (char)Record[2+i]; 2078 for (unsigned i = 0; i != ConstStrSize; ++i) 2079 ConstrStr += (char)Record[3+AsmStrSize+i]; 2080 PointerType *PTy = cast<PointerType>(CurTy); 2081 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2082 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 2083 break; 2084 } 2085 // This version adds support for the asm dialect keywords (e.g., 2086 // inteldialect). 2087 case bitc::CST_CODE_INLINEASM: { 2088 if (Record.size() < 2) 2089 return Error("Invalid record"); 2090 std::string AsmStr, ConstrStr; 2091 bool HasSideEffects = Record[0] & 1; 2092 bool IsAlignStack = (Record[0] >> 1) & 1; 2093 unsigned AsmDialect = Record[0] >> 2; 2094 unsigned AsmStrSize = Record[1]; 2095 if (2+AsmStrSize >= Record.size()) 2096 return Error("Invalid record"); 2097 unsigned ConstStrSize = Record[2+AsmStrSize]; 2098 if (3+AsmStrSize+ConstStrSize > Record.size()) 2099 return Error("Invalid record"); 2100 2101 for (unsigned i = 0; i != AsmStrSize; ++i) 2102 AsmStr += (char)Record[2+i]; 2103 for (unsigned i = 0; i != ConstStrSize; ++i) 2104 ConstrStr += (char)Record[3+AsmStrSize+i]; 2105 PointerType *PTy = cast<PointerType>(CurTy); 2106 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 2107 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 2108 InlineAsm::AsmDialect(AsmDialect)); 2109 break; 2110 } 2111 case bitc::CST_CODE_BLOCKADDRESS:{ 2112 if (Record.size() < 3) 2113 return Error("Invalid record"); 2114 Type *FnTy = getTypeByID(Record[0]); 2115 if (!FnTy) 2116 return Error("Invalid record"); 2117 Function *Fn = 2118 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 2119 if (!Fn) 2120 return Error("Invalid record"); 2121 2122 // Don't let Fn get dematerialized. 2123 BlockAddressesTaken.insert(Fn); 2124 2125 // If the function is already parsed we can insert the block address right 2126 // away. 2127 BasicBlock *BB; 2128 unsigned BBID = Record[2]; 2129 if (!BBID) 2130 // Invalid reference to entry block. 2131 return Error("Invalid ID"); 2132 if (!Fn->empty()) { 2133 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 2134 for (size_t I = 0, E = BBID; I != E; ++I) { 2135 if (BBI == BBE) 2136 return Error("Invalid ID"); 2137 ++BBI; 2138 } 2139 BB = BBI; 2140 } else { 2141 // Otherwise insert a placeholder and remember it so it can be inserted 2142 // when the function is parsed. 2143 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 2144 if (FwdBBs.empty()) 2145 BasicBlockFwdRefQueue.push_back(Fn); 2146 if (FwdBBs.size() < BBID + 1) 2147 FwdBBs.resize(BBID + 1); 2148 if (!FwdBBs[BBID]) 2149 FwdBBs[BBID] = BasicBlock::Create(Context); 2150 BB = FwdBBs[BBID]; 2151 } 2152 V = BlockAddress::get(Fn, BB); 2153 break; 2154 } 2155 } 2156 2157 ValueList.AssignValue(V, NextCstNo); 2158 ++NextCstNo; 2159 } 2160 } 2161 2162 std::error_code BitcodeReader::ParseUseLists() { 2163 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 2164 return Error("Invalid record"); 2165 2166 // Read all the records. 2167 SmallVector<uint64_t, 64> Record; 2168 while (1) { 2169 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2170 2171 switch (Entry.Kind) { 2172 case BitstreamEntry::SubBlock: // Handled for us already. 2173 case BitstreamEntry::Error: 2174 return Error("Malformed block"); 2175 case BitstreamEntry::EndBlock: 2176 return std::error_code(); 2177 case BitstreamEntry::Record: 2178 // The interesting case. 2179 break; 2180 } 2181 2182 // Read a use list record. 2183 Record.clear(); 2184 bool IsBB = false; 2185 switch (Stream.readRecord(Entry.ID, Record)) { 2186 default: // Default behavior: unknown type. 2187 break; 2188 case bitc::USELIST_CODE_BB: 2189 IsBB = true; 2190 // fallthrough 2191 case bitc::USELIST_CODE_DEFAULT: { 2192 unsigned RecordLength = Record.size(); 2193 if (RecordLength < 3) 2194 // Records should have at least an ID and two indexes. 2195 return Error("Invalid record"); 2196 unsigned ID = Record.back(); 2197 Record.pop_back(); 2198 2199 Value *V; 2200 if (IsBB) { 2201 assert(ID < FunctionBBs.size() && "Basic block not found"); 2202 V = FunctionBBs[ID]; 2203 } else 2204 V = ValueList[ID]; 2205 unsigned NumUses = 0; 2206 SmallDenseMap<const Use *, unsigned, 16> Order; 2207 for (const Use &U : V->uses()) { 2208 if (++NumUses > Record.size()) 2209 break; 2210 Order[&U] = Record[NumUses - 1]; 2211 } 2212 if (Order.size() != Record.size() || NumUses > Record.size()) 2213 // Mismatches can happen if the functions are being materialized lazily 2214 // (out-of-order), or a value has been upgraded. 2215 break; 2216 2217 V->sortUseList([&](const Use &L, const Use &R) { 2218 return Order.lookup(&L) < Order.lookup(&R); 2219 }); 2220 break; 2221 } 2222 } 2223 } 2224 } 2225 2226 /// RememberAndSkipFunctionBody - When we see the block for a function body, 2227 /// remember where it is and then skip it. This lets us lazily deserialize the 2228 /// functions. 2229 std::error_code BitcodeReader::RememberAndSkipFunctionBody() { 2230 // Get the function we are talking about. 2231 if (FunctionsWithBodies.empty()) 2232 return Error("Insufficient function protos"); 2233 2234 Function *Fn = FunctionsWithBodies.back(); 2235 FunctionsWithBodies.pop_back(); 2236 2237 // Save the current stream state. 2238 uint64_t CurBit = Stream.GetCurrentBitNo(); 2239 DeferredFunctionInfo[Fn] = CurBit; 2240 2241 // Skip over the function block for now. 2242 if (Stream.SkipBlock()) 2243 return Error("Invalid record"); 2244 return std::error_code(); 2245 } 2246 2247 std::error_code BitcodeReader::GlobalCleanup() { 2248 // Patch the initializers for globals and aliases up. 2249 ResolveGlobalAndAliasInits(); 2250 if (!GlobalInits.empty() || !AliasInits.empty()) 2251 return Error("Malformed global initializer set"); 2252 2253 // Look for intrinsic functions which need to be upgraded at some point 2254 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 2255 FI != FE; ++FI) { 2256 Function *NewFn; 2257 if (UpgradeIntrinsicFunction(FI, NewFn)) 2258 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 2259 } 2260 2261 // Look for global variables which need to be renamed. 2262 for (Module::global_iterator 2263 GI = TheModule->global_begin(), GE = TheModule->global_end(); 2264 GI != GE;) { 2265 GlobalVariable *GV = GI++; 2266 UpgradeGlobalVariable(GV); 2267 } 2268 2269 // Force deallocation of memory for these vectors to favor the client that 2270 // want lazy deserialization. 2271 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 2272 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 2273 return std::error_code(); 2274 } 2275 2276 std::error_code BitcodeReader::ParseModule(bool Resume) { 2277 if (Resume) 2278 Stream.JumpToBit(NextUnreadBit); 2279 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2280 return Error("Invalid record"); 2281 2282 SmallVector<uint64_t, 64> Record; 2283 std::vector<std::string> SectionTable; 2284 std::vector<std::string> GCTable; 2285 2286 // Read all the records for this module. 2287 while (1) { 2288 BitstreamEntry Entry = Stream.advance(); 2289 2290 switch (Entry.Kind) { 2291 case BitstreamEntry::Error: 2292 return Error("Malformed block"); 2293 case BitstreamEntry::EndBlock: 2294 return GlobalCleanup(); 2295 2296 case BitstreamEntry::SubBlock: 2297 switch (Entry.ID) { 2298 default: // Skip unknown content. 2299 if (Stream.SkipBlock()) 2300 return Error("Invalid record"); 2301 break; 2302 case bitc::BLOCKINFO_BLOCK_ID: 2303 if (Stream.ReadBlockInfoBlock()) 2304 return Error("Malformed block"); 2305 break; 2306 case bitc::PARAMATTR_BLOCK_ID: 2307 if (std::error_code EC = ParseAttributeBlock()) 2308 return EC; 2309 break; 2310 case bitc::PARAMATTR_GROUP_BLOCK_ID: 2311 if (std::error_code EC = ParseAttributeGroupBlock()) 2312 return EC; 2313 break; 2314 case bitc::TYPE_BLOCK_ID_NEW: 2315 if (std::error_code EC = ParseTypeTable()) 2316 return EC; 2317 break; 2318 case bitc::VALUE_SYMTAB_BLOCK_ID: 2319 if (std::error_code EC = ParseValueSymbolTable()) 2320 return EC; 2321 SeenValueSymbolTable = true; 2322 break; 2323 case bitc::CONSTANTS_BLOCK_ID: 2324 if (std::error_code EC = ParseConstants()) 2325 return EC; 2326 if (std::error_code EC = ResolveGlobalAndAliasInits()) 2327 return EC; 2328 break; 2329 case bitc::METADATA_BLOCK_ID: 2330 if (std::error_code EC = ParseMetadata()) 2331 return EC; 2332 break; 2333 case bitc::FUNCTION_BLOCK_ID: 2334 // If this is the first function body we've seen, reverse the 2335 // FunctionsWithBodies list. 2336 if (!SeenFirstFunctionBody) { 2337 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 2338 if (std::error_code EC = GlobalCleanup()) 2339 return EC; 2340 SeenFirstFunctionBody = true; 2341 } 2342 2343 if (std::error_code EC = RememberAndSkipFunctionBody()) 2344 return EC; 2345 // For streaming bitcode, suspend parsing when we reach the function 2346 // bodies. Subsequent materialization calls will resume it when 2347 // necessary. For streaming, the function bodies must be at the end of 2348 // the bitcode. If the bitcode file is old, the symbol table will be 2349 // at the end instead and will not have been seen yet. In this case, 2350 // just finish the parse now. 2351 if (LazyStreamer && SeenValueSymbolTable) { 2352 NextUnreadBit = Stream.GetCurrentBitNo(); 2353 return std::error_code(); 2354 } 2355 break; 2356 case bitc::USELIST_BLOCK_ID: 2357 if (std::error_code EC = ParseUseLists()) 2358 return EC; 2359 break; 2360 } 2361 continue; 2362 2363 case BitstreamEntry::Record: 2364 // The interesting case. 2365 break; 2366 } 2367 2368 2369 // Read a record. 2370 switch (Stream.readRecord(Entry.ID, Record)) { 2371 default: break; // Default behavior, ignore unknown content. 2372 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 2373 if (Record.size() < 1) 2374 return Error("Invalid record"); 2375 // Only version #0 and #1 are supported so far. 2376 unsigned module_version = Record[0]; 2377 switch (module_version) { 2378 default: 2379 return Error("Invalid value"); 2380 case 0: 2381 UseRelativeIDs = false; 2382 break; 2383 case 1: 2384 UseRelativeIDs = true; 2385 break; 2386 } 2387 break; 2388 } 2389 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2390 std::string S; 2391 if (ConvertToString(Record, 0, S)) 2392 return Error("Invalid record"); 2393 TheModule->setTargetTriple(S); 2394 break; 2395 } 2396 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 2397 std::string S; 2398 if (ConvertToString(Record, 0, S)) 2399 return Error("Invalid record"); 2400 TheModule->setDataLayout(S); 2401 break; 2402 } 2403 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 2404 std::string S; 2405 if (ConvertToString(Record, 0, S)) 2406 return Error("Invalid record"); 2407 TheModule->setModuleInlineAsm(S); 2408 break; 2409 } 2410 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 2411 // FIXME: Remove in 4.0. 2412 std::string S; 2413 if (ConvertToString(Record, 0, S)) 2414 return Error("Invalid record"); 2415 // Ignore value. 2416 break; 2417 } 2418 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 2419 std::string S; 2420 if (ConvertToString(Record, 0, S)) 2421 return Error("Invalid record"); 2422 SectionTable.push_back(S); 2423 break; 2424 } 2425 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 2426 std::string S; 2427 if (ConvertToString(Record, 0, S)) 2428 return Error("Invalid record"); 2429 GCTable.push_back(S); 2430 break; 2431 } 2432 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 2433 if (Record.size() < 2) 2434 return Error("Invalid record"); 2435 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 2436 unsigned ComdatNameSize = Record[1]; 2437 std::string ComdatName; 2438 ComdatName.reserve(ComdatNameSize); 2439 for (unsigned i = 0; i != ComdatNameSize; ++i) 2440 ComdatName += (char)Record[2 + i]; 2441 Comdat *C = TheModule->getOrInsertComdat(ComdatName); 2442 C->setSelectionKind(SK); 2443 ComdatList.push_back(C); 2444 break; 2445 } 2446 // GLOBALVAR: [pointer type, isconst, initid, 2447 // linkage, alignment, section, visibility, threadlocal, 2448 // unnamed_addr, externally_initialized, dllstorageclass, 2449 // comdat] 2450 case bitc::MODULE_CODE_GLOBALVAR: { 2451 if (Record.size() < 6) 2452 return Error("Invalid record"); 2453 Type *Ty = getTypeByID(Record[0]); 2454 if (!Ty) 2455 return Error("Invalid record"); 2456 if (!Ty->isPointerTy()) 2457 return Error("Invalid type for value"); 2458 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 2459 Ty = cast<PointerType>(Ty)->getElementType(); 2460 2461 bool isConstant = Record[1]; 2462 uint64_t RawLinkage = Record[3]; 2463 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 2464 unsigned Alignment = (1 << Record[4]) >> 1; 2465 std::string Section; 2466 if (Record[5]) { 2467 if (Record[5]-1 >= SectionTable.size()) 2468 return Error("Invalid ID"); 2469 Section = SectionTable[Record[5]-1]; 2470 } 2471 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 2472 // Local linkage must have default visibility. 2473 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 2474 // FIXME: Change to an error if non-default in 4.0. 2475 Visibility = GetDecodedVisibility(Record[6]); 2476 2477 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 2478 if (Record.size() > 7) 2479 TLM = GetDecodedThreadLocalMode(Record[7]); 2480 2481 bool UnnamedAddr = false; 2482 if (Record.size() > 8) 2483 UnnamedAddr = Record[8]; 2484 2485 bool ExternallyInitialized = false; 2486 if (Record.size() > 9) 2487 ExternallyInitialized = Record[9]; 2488 2489 GlobalVariable *NewGV = 2490 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 2491 TLM, AddressSpace, ExternallyInitialized); 2492 NewGV->setAlignment(Alignment); 2493 if (!Section.empty()) 2494 NewGV->setSection(Section); 2495 NewGV->setVisibility(Visibility); 2496 NewGV->setUnnamedAddr(UnnamedAddr); 2497 2498 if (Record.size() > 10) 2499 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10])); 2500 else 2501 UpgradeDLLImportExportLinkage(NewGV, RawLinkage); 2502 2503 ValueList.push_back(NewGV); 2504 2505 // Remember which value to use for the global initializer. 2506 if (unsigned InitID = Record[2]) 2507 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 2508 2509 if (Record.size() > 11) { 2510 if (unsigned ComdatID = Record[11]) { 2511 assert(ComdatID <= ComdatList.size()); 2512 NewGV->setComdat(ComdatList[ComdatID - 1]); 2513 } 2514 } else if (hasImplicitComdat(RawLinkage)) { 2515 NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 2516 } 2517 break; 2518 } 2519 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 2520 // alignment, section, visibility, gc, unnamed_addr, 2521 // prologuedata, dllstorageclass, comdat, prefixdata] 2522 case bitc::MODULE_CODE_FUNCTION: { 2523 if (Record.size() < 8) 2524 return Error("Invalid record"); 2525 Type *Ty = getTypeByID(Record[0]); 2526 if (!Ty) 2527 return Error("Invalid record"); 2528 if (!Ty->isPointerTy()) 2529 return Error("Invalid type for value"); 2530 FunctionType *FTy = 2531 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 2532 if (!FTy) 2533 return Error("Invalid type for value"); 2534 2535 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 2536 "", TheModule); 2537 2538 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 2539 bool isProto = Record[2]; 2540 uint64_t RawLinkage = Record[3]; 2541 Func->setLinkage(getDecodedLinkage(RawLinkage)); 2542 Func->setAttributes(getAttributes(Record[4])); 2543 2544 Func->setAlignment((1 << Record[5]) >> 1); 2545 if (Record[6]) { 2546 if (Record[6]-1 >= SectionTable.size()) 2547 return Error("Invalid ID"); 2548 Func->setSection(SectionTable[Record[6]-1]); 2549 } 2550 // Local linkage must have default visibility. 2551 if (!Func->hasLocalLinkage()) 2552 // FIXME: Change to an error if non-default in 4.0. 2553 Func->setVisibility(GetDecodedVisibility(Record[7])); 2554 if (Record.size() > 8 && Record[8]) { 2555 if (Record[8]-1 > GCTable.size()) 2556 return Error("Invalid ID"); 2557 Func->setGC(GCTable[Record[8]-1].c_str()); 2558 } 2559 bool UnnamedAddr = false; 2560 if (Record.size() > 9) 2561 UnnamedAddr = Record[9]; 2562 Func->setUnnamedAddr(UnnamedAddr); 2563 if (Record.size() > 10 && Record[10] != 0) 2564 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 2565 2566 if (Record.size() > 11) 2567 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11])); 2568 else 2569 UpgradeDLLImportExportLinkage(Func, RawLinkage); 2570 2571 if (Record.size() > 12) { 2572 if (unsigned ComdatID = Record[12]) { 2573 assert(ComdatID <= ComdatList.size()); 2574 Func->setComdat(ComdatList[ComdatID - 1]); 2575 } 2576 } else if (hasImplicitComdat(RawLinkage)) { 2577 Func->setComdat(reinterpret_cast<Comdat *>(1)); 2578 } 2579 2580 if (Record.size() > 13 && Record[13] != 0) 2581 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 2582 2583 ValueList.push_back(Func); 2584 2585 // If this is a function with a body, remember the prototype we are 2586 // creating now, so that we can match up the body with them later. 2587 if (!isProto) { 2588 Func->setIsMaterializable(true); 2589 FunctionsWithBodies.push_back(Func); 2590 if (LazyStreamer) 2591 DeferredFunctionInfo[Func] = 0; 2592 } 2593 break; 2594 } 2595 // ALIAS: [alias type, aliasee val#, linkage] 2596 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass] 2597 case bitc::MODULE_CODE_ALIAS: { 2598 if (Record.size() < 3) 2599 return Error("Invalid record"); 2600 Type *Ty = getTypeByID(Record[0]); 2601 if (!Ty) 2602 return Error("Invalid record"); 2603 auto *PTy = dyn_cast<PointerType>(Ty); 2604 if (!PTy) 2605 return Error("Invalid type for value"); 2606 2607 auto *NewGA = 2608 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 2609 getDecodedLinkage(Record[2]), "", TheModule); 2610 // Old bitcode files didn't have visibility field. 2611 // Local linkage must have default visibility. 2612 if (Record.size() > 3 && !NewGA->hasLocalLinkage()) 2613 // FIXME: Change to an error if non-default in 4.0. 2614 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 2615 if (Record.size() > 4) 2616 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4])); 2617 else 2618 UpgradeDLLImportExportLinkage(NewGA, Record[2]); 2619 if (Record.size() > 5) 2620 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5])); 2621 if (Record.size() > 6) 2622 NewGA->setUnnamedAddr(Record[6]); 2623 ValueList.push_back(NewGA); 2624 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 2625 break; 2626 } 2627 /// MODULE_CODE_PURGEVALS: [numvals] 2628 case bitc::MODULE_CODE_PURGEVALS: 2629 // Trim down the value list to the specified size. 2630 if (Record.size() < 1 || Record[0] > ValueList.size()) 2631 return Error("Invalid record"); 2632 ValueList.shrinkTo(Record[0]); 2633 break; 2634 } 2635 Record.clear(); 2636 } 2637 } 2638 2639 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) { 2640 TheModule = nullptr; 2641 2642 if (std::error_code EC = InitStream()) 2643 return EC; 2644 2645 // Sniff for the signature. 2646 if (Stream.Read(8) != 'B' || 2647 Stream.Read(8) != 'C' || 2648 Stream.Read(4) != 0x0 || 2649 Stream.Read(4) != 0xC || 2650 Stream.Read(4) != 0xE || 2651 Stream.Read(4) != 0xD) 2652 return Error("Invalid bitcode signature"); 2653 2654 // We expect a number of well-defined blocks, though we don't necessarily 2655 // need to understand them all. 2656 while (1) { 2657 if (Stream.AtEndOfStream()) 2658 return std::error_code(); 2659 2660 BitstreamEntry Entry = 2661 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 2662 2663 switch (Entry.Kind) { 2664 case BitstreamEntry::Error: 2665 return Error("Malformed block"); 2666 case BitstreamEntry::EndBlock: 2667 return std::error_code(); 2668 2669 case BitstreamEntry::SubBlock: 2670 switch (Entry.ID) { 2671 case bitc::BLOCKINFO_BLOCK_ID: 2672 if (Stream.ReadBlockInfoBlock()) 2673 return Error("Malformed block"); 2674 break; 2675 case bitc::MODULE_BLOCK_ID: 2676 // Reject multiple MODULE_BLOCK's in a single bitstream. 2677 if (TheModule) 2678 return Error("Invalid multiple blocks"); 2679 TheModule = M; 2680 if (std::error_code EC = ParseModule(false)) 2681 return EC; 2682 if (LazyStreamer) 2683 return std::error_code(); 2684 break; 2685 default: 2686 if (Stream.SkipBlock()) 2687 return Error("Invalid record"); 2688 break; 2689 } 2690 continue; 2691 case BitstreamEntry::Record: 2692 // There should be no records in the top-level of blocks. 2693 2694 // The ranlib in Xcode 4 will align archive members by appending newlines 2695 // to the end of them. If this file size is a multiple of 4 but not 8, we 2696 // have to read and ignore these final 4 bytes :-( 2697 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 && 2698 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 2699 Stream.AtEndOfStream()) 2700 return std::error_code(); 2701 2702 return Error("Invalid record"); 2703 } 2704 } 2705 } 2706 2707 ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 2708 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2709 return Error("Invalid record"); 2710 2711 SmallVector<uint64_t, 64> Record; 2712 2713 std::string Triple; 2714 // Read all the records for this module. 2715 while (1) { 2716 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2717 2718 switch (Entry.Kind) { 2719 case BitstreamEntry::SubBlock: // Handled for us already. 2720 case BitstreamEntry::Error: 2721 return Error("Malformed block"); 2722 case BitstreamEntry::EndBlock: 2723 return Triple; 2724 case BitstreamEntry::Record: 2725 // The interesting case. 2726 break; 2727 } 2728 2729 // Read a record. 2730 switch (Stream.readRecord(Entry.ID, Record)) { 2731 default: break; // Default behavior, ignore unknown content. 2732 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2733 std::string S; 2734 if (ConvertToString(Record, 0, S)) 2735 return Error("Invalid record"); 2736 Triple = S; 2737 break; 2738 } 2739 } 2740 Record.clear(); 2741 } 2742 llvm_unreachable("Exit infinite loop"); 2743 } 2744 2745 ErrorOr<std::string> BitcodeReader::parseTriple() { 2746 if (std::error_code EC = InitStream()) 2747 return EC; 2748 2749 // Sniff for the signature. 2750 if (Stream.Read(8) != 'B' || 2751 Stream.Read(8) != 'C' || 2752 Stream.Read(4) != 0x0 || 2753 Stream.Read(4) != 0xC || 2754 Stream.Read(4) != 0xE || 2755 Stream.Read(4) != 0xD) 2756 return Error("Invalid bitcode signature"); 2757 2758 // We expect a number of well-defined blocks, though we don't necessarily 2759 // need to understand them all. 2760 while (1) { 2761 BitstreamEntry Entry = Stream.advance(); 2762 2763 switch (Entry.Kind) { 2764 case BitstreamEntry::Error: 2765 return Error("Malformed block"); 2766 case BitstreamEntry::EndBlock: 2767 return std::error_code(); 2768 2769 case BitstreamEntry::SubBlock: 2770 if (Entry.ID == bitc::MODULE_BLOCK_ID) 2771 return parseModuleTriple(); 2772 2773 // Ignore other sub-blocks. 2774 if (Stream.SkipBlock()) 2775 return Error("Malformed block"); 2776 continue; 2777 2778 case BitstreamEntry::Record: 2779 Stream.skipRecord(Entry.ID); 2780 continue; 2781 } 2782 } 2783 } 2784 2785 /// ParseMetadataAttachment - Parse metadata attachments. 2786 std::error_code BitcodeReader::ParseMetadataAttachment() { 2787 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 2788 return Error("Invalid record"); 2789 2790 SmallVector<uint64_t, 64> Record; 2791 while (1) { 2792 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2793 2794 switch (Entry.Kind) { 2795 case BitstreamEntry::SubBlock: // Handled for us already. 2796 case BitstreamEntry::Error: 2797 return Error("Malformed block"); 2798 case BitstreamEntry::EndBlock: 2799 return std::error_code(); 2800 case BitstreamEntry::Record: 2801 // The interesting case. 2802 break; 2803 } 2804 2805 // Read a metadata attachment record. 2806 Record.clear(); 2807 switch (Stream.readRecord(Entry.ID, Record)) { 2808 default: // Default behavior: ignore. 2809 break; 2810 case bitc::METADATA_ATTACHMENT: { 2811 unsigned RecordLength = Record.size(); 2812 if (Record.empty() || (RecordLength - 1) % 2 == 1) 2813 return Error("Invalid record"); 2814 Instruction *Inst = InstructionList[Record[0]]; 2815 for (unsigned i = 1; i != RecordLength; i = i+2) { 2816 unsigned Kind = Record[i]; 2817 DenseMap<unsigned, unsigned>::iterator I = 2818 MDKindMap.find(Kind); 2819 if (I == MDKindMap.end()) 2820 return Error("Invalid ID"); 2821 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]); 2822 if (isa<LocalAsMetadata>(Node)) 2823 // Drop the attachment. This used to be legal, but there's no 2824 // upgrade path. 2825 break; 2826 Inst->setMetadata(I->second, cast<MDNode>(Node)); 2827 if (I->second == LLVMContext::MD_tbaa) 2828 InstsWithTBAATag.push_back(Inst); 2829 } 2830 break; 2831 } 2832 } 2833 } 2834 } 2835 2836 /// ParseFunctionBody - Lazily parse the specified function body block. 2837 std::error_code BitcodeReader::ParseFunctionBody(Function *F) { 2838 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 2839 return Error("Invalid record"); 2840 2841 InstructionList.clear(); 2842 unsigned ModuleValueListSize = ValueList.size(); 2843 unsigned ModuleMDValueListSize = MDValueList.size(); 2844 2845 // Add all the function arguments to the value table. 2846 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 2847 ValueList.push_back(I); 2848 2849 unsigned NextValueNo = ValueList.size(); 2850 BasicBlock *CurBB = nullptr; 2851 unsigned CurBBNo = 0; 2852 2853 DebugLoc LastLoc; 2854 auto getLastInstruction = [&]() -> Instruction * { 2855 if (CurBB && !CurBB->empty()) 2856 return &CurBB->back(); 2857 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 2858 !FunctionBBs[CurBBNo - 1]->empty()) 2859 return &FunctionBBs[CurBBNo - 1]->back(); 2860 return nullptr; 2861 }; 2862 2863 // Read all the records. 2864 SmallVector<uint64_t, 64> Record; 2865 while (1) { 2866 BitstreamEntry Entry = Stream.advance(); 2867 2868 switch (Entry.Kind) { 2869 case BitstreamEntry::Error: 2870 return Error("Malformed block"); 2871 case BitstreamEntry::EndBlock: 2872 goto OutOfRecordLoop; 2873 2874 case BitstreamEntry::SubBlock: 2875 switch (Entry.ID) { 2876 default: // Skip unknown content. 2877 if (Stream.SkipBlock()) 2878 return Error("Invalid record"); 2879 break; 2880 case bitc::CONSTANTS_BLOCK_ID: 2881 if (std::error_code EC = ParseConstants()) 2882 return EC; 2883 NextValueNo = ValueList.size(); 2884 break; 2885 case bitc::VALUE_SYMTAB_BLOCK_ID: 2886 if (std::error_code EC = ParseValueSymbolTable()) 2887 return EC; 2888 break; 2889 case bitc::METADATA_ATTACHMENT_ID: 2890 if (std::error_code EC = ParseMetadataAttachment()) 2891 return EC; 2892 break; 2893 case bitc::METADATA_BLOCK_ID: 2894 if (std::error_code EC = ParseMetadata()) 2895 return EC; 2896 break; 2897 case bitc::USELIST_BLOCK_ID: 2898 if (std::error_code EC = ParseUseLists()) 2899 return EC; 2900 break; 2901 } 2902 continue; 2903 2904 case BitstreamEntry::Record: 2905 // The interesting case. 2906 break; 2907 } 2908 2909 // Read a record. 2910 Record.clear(); 2911 Instruction *I = nullptr; 2912 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2913 switch (BitCode) { 2914 default: // Default behavior: reject 2915 return Error("Invalid value"); 2916 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 2917 if (Record.size() < 1 || Record[0] == 0) 2918 return Error("Invalid record"); 2919 // Create all the basic blocks for the function. 2920 FunctionBBs.resize(Record[0]); 2921 2922 // See if anything took the address of blocks in this function. 2923 auto BBFRI = BasicBlockFwdRefs.find(F); 2924 if (BBFRI == BasicBlockFwdRefs.end()) { 2925 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 2926 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 2927 } else { 2928 auto &BBRefs = BBFRI->second; 2929 // Check for invalid basic block references. 2930 if (BBRefs.size() > FunctionBBs.size()) 2931 return Error("Invalid ID"); 2932 assert(!BBRefs.empty() && "Unexpected empty array"); 2933 assert(!BBRefs.front() && "Invalid reference to entry block"); 2934 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 2935 ++I) 2936 if (I < RE && BBRefs[I]) { 2937 BBRefs[I]->insertInto(F); 2938 FunctionBBs[I] = BBRefs[I]; 2939 } else { 2940 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 2941 } 2942 2943 // Erase from the table. 2944 BasicBlockFwdRefs.erase(BBFRI); 2945 } 2946 2947 CurBB = FunctionBBs[0]; 2948 continue; 2949 } 2950 2951 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 2952 // This record indicates that the last instruction is at the same 2953 // location as the previous instruction with a location. 2954 I = getLastInstruction(); 2955 2956 if (!I) 2957 return Error("Invalid record"); 2958 I->setDebugLoc(LastLoc); 2959 I = nullptr; 2960 continue; 2961 2962 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 2963 I = getLastInstruction(); 2964 if (!I || Record.size() < 4) 2965 return Error("Invalid record"); 2966 2967 unsigned Line = Record[0], Col = Record[1]; 2968 unsigned ScopeID = Record[2], IAID = Record[3]; 2969 2970 MDNode *Scope = nullptr, *IA = nullptr; 2971 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 2972 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 2973 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 2974 I->setDebugLoc(LastLoc); 2975 I = nullptr; 2976 continue; 2977 } 2978 2979 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 2980 unsigned OpNum = 0; 2981 Value *LHS, *RHS; 2982 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2983 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2984 OpNum+1 > Record.size()) 2985 return Error("Invalid record"); 2986 2987 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 2988 if (Opc == -1) 2989 return Error("Invalid record"); 2990 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2991 InstructionList.push_back(I); 2992 if (OpNum < Record.size()) { 2993 if (Opc == Instruction::Add || 2994 Opc == Instruction::Sub || 2995 Opc == Instruction::Mul || 2996 Opc == Instruction::Shl) { 2997 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2998 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 2999 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 3000 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 3001 } else if (Opc == Instruction::SDiv || 3002 Opc == Instruction::UDiv || 3003 Opc == Instruction::LShr || 3004 Opc == Instruction::AShr) { 3005 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 3006 cast<BinaryOperator>(I)->setIsExact(true); 3007 } else if (isa<FPMathOperator>(I)) { 3008 FastMathFlags FMF; 3009 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra)) 3010 FMF.setUnsafeAlgebra(); 3011 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs)) 3012 FMF.setNoNaNs(); 3013 if (0 != (Record[OpNum] & FastMathFlags::NoInfs)) 3014 FMF.setNoInfs(); 3015 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros)) 3016 FMF.setNoSignedZeros(); 3017 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal)) 3018 FMF.setAllowReciprocal(); 3019 if (FMF.any()) 3020 I->setFastMathFlags(FMF); 3021 } 3022 3023 } 3024 break; 3025 } 3026 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 3027 unsigned OpNum = 0; 3028 Value *Op; 3029 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3030 OpNum+2 != Record.size()) 3031 return Error("Invalid record"); 3032 3033 Type *ResTy = getTypeByID(Record[OpNum]); 3034 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 3035 if (Opc == -1 || !ResTy) 3036 return Error("Invalid record"); 3037 Instruction *Temp = nullptr; 3038 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 3039 if (Temp) { 3040 InstructionList.push_back(Temp); 3041 CurBB->getInstList().push_back(Temp); 3042 } 3043 } else { 3044 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 3045 } 3046 InstructionList.push_back(I); 3047 break; 3048 } 3049 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 3050 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 3051 unsigned OpNum = 0; 3052 Value *BasePtr; 3053 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 3054 return Error("Invalid record"); 3055 3056 SmallVector<Value*, 16> GEPIdx; 3057 while (OpNum != Record.size()) { 3058 Value *Op; 3059 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3060 return Error("Invalid record"); 3061 GEPIdx.push_back(Op); 3062 } 3063 3064 I = GetElementPtrInst::Create(BasePtr, GEPIdx); 3065 InstructionList.push_back(I); 3066 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 3067 cast<GetElementPtrInst>(I)->setIsInBounds(true); 3068 break; 3069 } 3070 3071 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 3072 // EXTRACTVAL: [opty, opval, n x indices] 3073 unsigned OpNum = 0; 3074 Value *Agg; 3075 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 3076 return Error("Invalid record"); 3077 3078 SmallVector<unsigned, 4> EXTRACTVALIdx; 3079 Type *CurTy = Agg->getType(); 3080 for (unsigned RecSize = Record.size(); 3081 OpNum != RecSize; ++OpNum) { 3082 bool IsArray = CurTy->isArrayTy(); 3083 bool IsStruct = CurTy->isStructTy(); 3084 uint64_t Index = Record[OpNum]; 3085 3086 if (!IsStruct && !IsArray) 3087 return Error("EXTRACTVAL: Invalid type"); 3088 if ((unsigned)Index != Index) 3089 return Error("Invalid value"); 3090 if (IsStruct && Index >= CurTy->subtypes().size()) 3091 return Error("EXTRACTVAL: Invalid struct index"); 3092 if (IsArray && Index >= CurTy->getArrayNumElements()) 3093 return Error("EXTRACTVAL: Invalid array index"); 3094 EXTRACTVALIdx.push_back((unsigned)Index); 3095 3096 if (IsStruct) 3097 CurTy = CurTy->subtypes()[Index]; 3098 else 3099 CurTy = CurTy->subtypes()[0]; 3100 } 3101 3102 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 3103 InstructionList.push_back(I); 3104 break; 3105 } 3106 3107 case bitc::FUNC_CODE_INST_INSERTVAL: { 3108 // INSERTVAL: [opty, opval, opty, opval, n x indices] 3109 unsigned OpNum = 0; 3110 Value *Agg; 3111 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 3112 return Error("Invalid record"); 3113 Value *Val; 3114 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 3115 return Error("Invalid record"); 3116 3117 SmallVector<unsigned, 4> INSERTVALIdx; 3118 Type *CurTy = Agg->getType(); 3119 for (unsigned RecSize = Record.size(); 3120 OpNum != RecSize; ++OpNum) { 3121 bool IsArray = CurTy->isArrayTy(); 3122 bool IsStruct = CurTy->isStructTy(); 3123 uint64_t Index = Record[OpNum]; 3124 3125 if (!IsStruct && !IsArray) 3126 return Error("INSERTVAL: Invalid type"); 3127 if (!CurTy->isStructTy() && !CurTy->isArrayTy()) 3128 return Error("Invalid type"); 3129 if ((unsigned)Index != Index) 3130 return Error("Invalid value"); 3131 if (IsStruct && Index >= CurTy->subtypes().size()) 3132 return Error("INSERTVAL: Invalid struct index"); 3133 if (IsArray && Index >= CurTy->getArrayNumElements()) 3134 return Error("INSERTVAL: Invalid array index"); 3135 3136 INSERTVALIdx.push_back((unsigned)Index); 3137 if (IsStruct) 3138 CurTy = CurTy->subtypes()[Index]; 3139 else 3140 CurTy = CurTy->subtypes()[0]; 3141 } 3142 3143 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 3144 InstructionList.push_back(I); 3145 break; 3146 } 3147 3148 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 3149 // obsolete form of select 3150 // handles select i1 ... in old bitcode 3151 unsigned OpNum = 0; 3152 Value *TrueVal, *FalseVal, *Cond; 3153 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 3154 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3155 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 3156 return Error("Invalid record"); 3157 3158 I = SelectInst::Create(Cond, TrueVal, FalseVal); 3159 InstructionList.push_back(I); 3160 break; 3161 } 3162 3163 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 3164 // new form of select 3165 // handles select i1 or select [N x i1] 3166 unsigned OpNum = 0; 3167 Value *TrueVal, *FalseVal, *Cond; 3168 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 3169 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 3170 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 3171 return Error("Invalid record"); 3172 3173 // select condition can be either i1 or [N x i1] 3174 if (VectorType* vector_type = 3175 dyn_cast<VectorType>(Cond->getType())) { 3176 // expect <n x i1> 3177 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 3178 return Error("Invalid type for value"); 3179 } else { 3180 // expect i1 3181 if (Cond->getType() != Type::getInt1Ty(Context)) 3182 return Error("Invalid type for value"); 3183 } 3184 3185 I = SelectInst::Create(Cond, TrueVal, FalseVal); 3186 InstructionList.push_back(I); 3187 break; 3188 } 3189 3190 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 3191 unsigned OpNum = 0; 3192 Value *Vec, *Idx; 3193 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 3194 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 3195 return Error("Invalid record"); 3196 I = ExtractElementInst::Create(Vec, Idx); 3197 InstructionList.push_back(I); 3198 break; 3199 } 3200 3201 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 3202 unsigned OpNum = 0; 3203 Value *Vec, *Elt, *Idx; 3204 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 3205 popValue(Record, OpNum, NextValueNo, 3206 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 3207 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 3208 return Error("Invalid record"); 3209 I = InsertElementInst::Create(Vec, Elt, Idx); 3210 InstructionList.push_back(I); 3211 break; 3212 } 3213 3214 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 3215 unsigned OpNum = 0; 3216 Value *Vec1, *Vec2, *Mask; 3217 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 3218 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 3219 return Error("Invalid record"); 3220 3221 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 3222 return Error("Invalid record"); 3223 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 3224 InstructionList.push_back(I); 3225 break; 3226 } 3227 3228 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 3229 // Old form of ICmp/FCmp returning bool 3230 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 3231 // both legal on vectors but had different behaviour. 3232 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 3233 // FCmp/ICmp returning bool or vector of bool 3234 3235 unsigned OpNum = 0; 3236 Value *LHS, *RHS; 3237 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 3238 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 3239 OpNum+1 != Record.size()) 3240 return Error("Invalid record"); 3241 3242 if (LHS->getType()->isFPOrFPVectorTy()) 3243 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 3244 else 3245 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 3246 InstructionList.push_back(I); 3247 break; 3248 } 3249 3250 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 3251 { 3252 unsigned Size = Record.size(); 3253 if (Size == 0) { 3254 I = ReturnInst::Create(Context); 3255 InstructionList.push_back(I); 3256 break; 3257 } 3258 3259 unsigned OpNum = 0; 3260 Value *Op = nullptr; 3261 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3262 return Error("Invalid record"); 3263 if (OpNum != Record.size()) 3264 return Error("Invalid record"); 3265 3266 I = ReturnInst::Create(Context, Op); 3267 InstructionList.push_back(I); 3268 break; 3269 } 3270 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 3271 if (Record.size() != 1 && Record.size() != 3) 3272 return Error("Invalid record"); 3273 BasicBlock *TrueDest = getBasicBlock(Record[0]); 3274 if (!TrueDest) 3275 return Error("Invalid record"); 3276 3277 if (Record.size() == 1) { 3278 I = BranchInst::Create(TrueDest); 3279 InstructionList.push_back(I); 3280 } 3281 else { 3282 BasicBlock *FalseDest = getBasicBlock(Record[1]); 3283 Value *Cond = getValue(Record, 2, NextValueNo, 3284 Type::getInt1Ty(Context)); 3285 if (!FalseDest || !Cond) 3286 return Error("Invalid record"); 3287 I = BranchInst::Create(TrueDest, FalseDest, Cond); 3288 InstructionList.push_back(I); 3289 } 3290 break; 3291 } 3292 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 3293 // Check magic 3294 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 3295 // "New" SwitchInst format with case ranges. The changes to write this 3296 // format were reverted but we still recognize bitcode that uses it. 3297 // Hopefully someday we will have support for case ranges and can use 3298 // this format again. 3299 3300 Type *OpTy = getTypeByID(Record[1]); 3301 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 3302 3303 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 3304 BasicBlock *Default = getBasicBlock(Record[3]); 3305 if (!OpTy || !Cond || !Default) 3306 return Error("Invalid record"); 3307 3308 unsigned NumCases = Record[4]; 3309 3310 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 3311 InstructionList.push_back(SI); 3312 3313 unsigned CurIdx = 5; 3314 for (unsigned i = 0; i != NumCases; ++i) { 3315 SmallVector<ConstantInt*, 1> CaseVals; 3316 unsigned NumItems = Record[CurIdx++]; 3317 for (unsigned ci = 0; ci != NumItems; ++ci) { 3318 bool isSingleNumber = Record[CurIdx++]; 3319 3320 APInt Low; 3321 unsigned ActiveWords = 1; 3322 if (ValueBitWidth > 64) 3323 ActiveWords = Record[CurIdx++]; 3324 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 3325 ValueBitWidth); 3326 CurIdx += ActiveWords; 3327 3328 if (!isSingleNumber) { 3329 ActiveWords = 1; 3330 if (ValueBitWidth > 64) 3331 ActiveWords = Record[CurIdx++]; 3332 APInt High = 3333 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 3334 ValueBitWidth); 3335 CurIdx += ActiveWords; 3336 3337 // FIXME: It is not clear whether values in the range should be 3338 // compared as signed or unsigned values. The partially 3339 // implemented changes that used this format in the past used 3340 // unsigned comparisons. 3341 for ( ; Low.ule(High); ++Low) 3342 CaseVals.push_back(ConstantInt::get(Context, Low)); 3343 } else 3344 CaseVals.push_back(ConstantInt::get(Context, Low)); 3345 } 3346 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 3347 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 3348 cve = CaseVals.end(); cvi != cve; ++cvi) 3349 SI->addCase(*cvi, DestBB); 3350 } 3351 I = SI; 3352 break; 3353 } 3354 3355 // Old SwitchInst format without case ranges. 3356 3357 if (Record.size() < 3 || (Record.size() & 1) == 0) 3358 return Error("Invalid record"); 3359 Type *OpTy = getTypeByID(Record[0]); 3360 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 3361 BasicBlock *Default = getBasicBlock(Record[2]); 3362 if (!OpTy || !Cond || !Default) 3363 return Error("Invalid record"); 3364 unsigned NumCases = (Record.size()-3)/2; 3365 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 3366 InstructionList.push_back(SI); 3367 for (unsigned i = 0, e = NumCases; i != e; ++i) { 3368 ConstantInt *CaseVal = 3369 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 3370 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 3371 if (!CaseVal || !DestBB) { 3372 delete SI; 3373 return Error("Invalid record"); 3374 } 3375 SI->addCase(CaseVal, DestBB); 3376 } 3377 I = SI; 3378 break; 3379 } 3380 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 3381 if (Record.size() < 2) 3382 return Error("Invalid record"); 3383 Type *OpTy = getTypeByID(Record[0]); 3384 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 3385 if (!OpTy || !Address) 3386 return Error("Invalid record"); 3387 unsigned NumDests = Record.size()-2; 3388 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 3389 InstructionList.push_back(IBI); 3390 for (unsigned i = 0, e = NumDests; i != e; ++i) { 3391 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 3392 IBI->addDestination(DestBB); 3393 } else { 3394 delete IBI; 3395 return Error("Invalid record"); 3396 } 3397 } 3398 I = IBI; 3399 break; 3400 } 3401 3402 case bitc::FUNC_CODE_INST_INVOKE: { 3403 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 3404 if (Record.size() < 4) 3405 return Error("Invalid record"); 3406 AttributeSet PAL = getAttributes(Record[0]); 3407 unsigned CCInfo = Record[1]; 3408 BasicBlock *NormalBB = getBasicBlock(Record[2]); 3409 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 3410 3411 unsigned OpNum = 4; 3412 Value *Callee; 3413 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 3414 return Error("Invalid record"); 3415 3416 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 3417 FunctionType *FTy = !CalleeTy ? nullptr : 3418 dyn_cast<FunctionType>(CalleeTy->getElementType()); 3419 3420 // Check that the right number of fixed parameters are here. 3421 if (!FTy || !NormalBB || !UnwindBB || 3422 Record.size() < OpNum+FTy->getNumParams()) 3423 return Error("Invalid record"); 3424 3425 SmallVector<Value*, 16> Ops; 3426 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3427 Ops.push_back(getValue(Record, OpNum, NextValueNo, 3428 FTy->getParamType(i))); 3429 if (!Ops.back()) 3430 return Error("Invalid record"); 3431 } 3432 3433 if (!FTy->isVarArg()) { 3434 if (Record.size() != OpNum) 3435 return Error("Invalid record"); 3436 } else { 3437 // Read type/value pairs for varargs params. 3438 while (OpNum != Record.size()) { 3439 Value *Op; 3440 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3441 return Error("Invalid record"); 3442 Ops.push_back(Op); 3443 } 3444 } 3445 3446 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 3447 InstructionList.push_back(I); 3448 cast<InvokeInst>(I)->setCallingConv( 3449 static_cast<CallingConv::ID>(CCInfo)); 3450 cast<InvokeInst>(I)->setAttributes(PAL); 3451 break; 3452 } 3453 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 3454 unsigned Idx = 0; 3455 Value *Val = nullptr; 3456 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 3457 return Error("Invalid record"); 3458 I = ResumeInst::Create(Val); 3459 InstructionList.push_back(I); 3460 break; 3461 } 3462 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 3463 I = new UnreachableInst(Context); 3464 InstructionList.push_back(I); 3465 break; 3466 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 3467 if (Record.size() < 1 || ((Record.size()-1)&1)) 3468 return Error("Invalid record"); 3469 Type *Ty = getTypeByID(Record[0]); 3470 if (!Ty) 3471 return Error("Invalid record"); 3472 3473 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 3474 InstructionList.push_back(PN); 3475 3476 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 3477 Value *V; 3478 // With the new function encoding, it is possible that operands have 3479 // negative IDs (for forward references). Use a signed VBR 3480 // representation to keep the encoding small. 3481 if (UseRelativeIDs) 3482 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 3483 else 3484 V = getValue(Record, 1+i, NextValueNo, Ty); 3485 BasicBlock *BB = getBasicBlock(Record[2+i]); 3486 if (!V || !BB) 3487 return Error("Invalid record"); 3488 PN->addIncoming(V, BB); 3489 } 3490 I = PN; 3491 break; 3492 } 3493 3494 case bitc::FUNC_CODE_INST_LANDINGPAD: { 3495 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 3496 unsigned Idx = 0; 3497 if (Record.size() < 4) 3498 return Error("Invalid record"); 3499 Type *Ty = getTypeByID(Record[Idx++]); 3500 if (!Ty) 3501 return Error("Invalid record"); 3502 Value *PersFn = nullptr; 3503 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 3504 return Error("Invalid record"); 3505 3506 bool IsCleanup = !!Record[Idx++]; 3507 unsigned NumClauses = Record[Idx++]; 3508 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses); 3509 LP->setCleanup(IsCleanup); 3510 for (unsigned J = 0; J != NumClauses; ++J) { 3511 LandingPadInst::ClauseType CT = 3512 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 3513 Value *Val; 3514 3515 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 3516 delete LP; 3517 return Error("Invalid record"); 3518 } 3519 3520 assert((CT != LandingPadInst::Catch || 3521 !isa<ArrayType>(Val->getType())) && 3522 "Catch clause has a invalid type!"); 3523 assert((CT != LandingPadInst::Filter || 3524 isa<ArrayType>(Val->getType())) && 3525 "Filter clause has invalid type!"); 3526 LP->addClause(cast<Constant>(Val)); 3527 } 3528 3529 I = LP; 3530 InstructionList.push_back(I); 3531 break; 3532 } 3533 3534 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 3535 if (Record.size() != 4) 3536 return Error("Invalid record"); 3537 PointerType *Ty = 3538 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 3539 Type *OpTy = getTypeByID(Record[1]); 3540 Value *Size = getFnValueByID(Record[2], OpTy); 3541 unsigned AlignRecord = Record[3]; 3542 bool InAlloca = AlignRecord & (1 << 5); 3543 unsigned Align = AlignRecord & ((1 << 5) - 1); 3544 if (!Ty || !Size) 3545 return Error("Invalid record"); 3546 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 3547 AI->setUsedWithInAlloca(InAlloca); 3548 I = AI; 3549 InstructionList.push_back(I); 3550 break; 3551 } 3552 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 3553 unsigned OpNum = 0; 3554 Value *Op; 3555 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3556 OpNum+2 != Record.size()) 3557 return Error("Invalid record"); 3558 3559 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3560 InstructionList.push_back(I); 3561 break; 3562 } 3563 case bitc::FUNC_CODE_INST_LOADATOMIC: { 3564 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 3565 unsigned OpNum = 0; 3566 Value *Op; 3567 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3568 OpNum+4 != Record.size()) 3569 return Error("Invalid record"); 3570 3571 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3572 if (Ordering == NotAtomic || Ordering == Release || 3573 Ordering == AcquireRelease) 3574 return Error("Invalid record"); 3575 if (Ordering != NotAtomic && Record[OpNum] == 0) 3576 return Error("Invalid record"); 3577 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3578 3579 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1, 3580 Ordering, SynchScope); 3581 InstructionList.push_back(I); 3582 break; 3583 } 3584 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol] 3585 unsigned OpNum = 0; 3586 Value *Val, *Ptr; 3587 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3588 popValue(Record, OpNum, NextValueNo, 3589 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3590 OpNum+2 != Record.size()) 3591 return Error("Invalid record"); 3592 3593 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3594 InstructionList.push_back(I); 3595 break; 3596 } 3597 case bitc::FUNC_CODE_INST_STOREATOMIC: { 3598 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 3599 unsigned OpNum = 0; 3600 Value *Val, *Ptr; 3601 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3602 popValue(Record, OpNum, NextValueNo, 3603 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3604 OpNum+4 != Record.size()) 3605 return Error("Invalid record"); 3606 3607 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3608 if (Ordering == NotAtomic || Ordering == Acquire || 3609 Ordering == AcquireRelease) 3610 return Error("Invalid record"); 3611 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3612 if (Ordering != NotAtomic && Record[OpNum] == 0) 3613 return Error("Invalid record"); 3614 3615 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1, 3616 Ordering, SynchScope); 3617 InstructionList.push_back(I); 3618 break; 3619 } 3620 case bitc::FUNC_CODE_INST_CMPXCHG: { 3621 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 3622 // failureordering?, isweak?] 3623 unsigned OpNum = 0; 3624 Value *Ptr, *Cmp, *New; 3625 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3626 popValue(Record, OpNum, NextValueNo, 3627 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) || 3628 popValue(Record, OpNum, NextValueNo, 3629 cast<PointerType>(Ptr->getType())->getElementType(), New) || 3630 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5)) 3631 return Error("Invalid record"); 3632 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]); 3633 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 3634 return Error("Invalid record"); 3635 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]); 3636 3637 AtomicOrdering FailureOrdering; 3638 if (Record.size() < 7) 3639 FailureOrdering = 3640 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 3641 else 3642 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]); 3643 3644 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 3645 SynchScope); 3646 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 3647 3648 if (Record.size() < 8) { 3649 // Before weak cmpxchgs existed, the instruction simply returned the 3650 // value loaded from memory, so bitcode files from that era will be 3651 // expecting the first component of a modern cmpxchg. 3652 CurBB->getInstList().push_back(I); 3653 I = ExtractValueInst::Create(I, 0); 3654 } else { 3655 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 3656 } 3657 3658 InstructionList.push_back(I); 3659 break; 3660 } 3661 case bitc::FUNC_CODE_INST_ATOMICRMW: { 3662 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 3663 unsigned OpNum = 0; 3664 Value *Ptr, *Val; 3665 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3666 popValue(Record, OpNum, NextValueNo, 3667 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3668 OpNum+4 != Record.size()) 3669 return Error("Invalid record"); 3670 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 3671 if (Operation < AtomicRMWInst::FIRST_BINOP || 3672 Operation > AtomicRMWInst::LAST_BINOP) 3673 return Error("Invalid record"); 3674 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3675 if (Ordering == NotAtomic || Ordering == Unordered) 3676 return Error("Invalid record"); 3677 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3678 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 3679 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 3680 InstructionList.push_back(I); 3681 break; 3682 } 3683 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 3684 if (2 != Record.size()) 3685 return Error("Invalid record"); 3686 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 3687 if (Ordering == NotAtomic || Ordering == Unordered || 3688 Ordering == Monotonic) 3689 return Error("Invalid record"); 3690 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 3691 I = new FenceInst(Context, Ordering, SynchScope); 3692 InstructionList.push_back(I); 3693 break; 3694 } 3695 case bitc::FUNC_CODE_INST_CALL: { 3696 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 3697 if (Record.size() < 3) 3698 return Error("Invalid record"); 3699 3700 AttributeSet PAL = getAttributes(Record[0]); 3701 unsigned CCInfo = Record[1]; 3702 3703 unsigned OpNum = 2; 3704 Value *Callee; 3705 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 3706 return Error("Invalid record"); 3707 3708 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 3709 FunctionType *FTy = nullptr; 3710 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 3711 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 3712 return Error("Invalid record"); 3713 3714 SmallVector<Value*, 16> Args; 3715 // Read the fixed params. 3716 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3717 if (FTy->getParamType(i)->isLabelTy()) 3718 Args.push_back(getBasicBlock(Record[OpNum])); 3719 else 3720 Args.push_back(getValue(Record, OpNum, NextValueNo, 3721 FTy->getParamType(i))); 3722 if (!Args.back()) 3723 return Error("Invalid record"); 3724 } 3725 3726 // Read type/value pairs for varargs params. 3727 if (!FTy->isVarArg()) { 3728 if (OpNum != Record.size()) 3729 return Error("Invalid record"); 3730 } else { 3731 while (OpNum != Record.size()) { 3732 Value *Op; 3733 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3734 return Error("Invalid record"); 3735 Args.push_back(Op); 3736 } 3737 } 3738 3739 I = CallInst::Create(Callee, Args); 3740 InstructionList.push_back(I); 3741 cast<CallInst>(I)->setCallingConv( 3742 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1)); 3743 CallInst::TailCallKind TCK = CallInst::TCK_None; 3744 if (CCInfo & 1) 3745 TCK = CallInst::TCK_Tail; 3746 if (CCInfo & (1 << 14)) 3747 TCK = CallInst::TCK_MustTail; 3748 cast<CallInst>(I)->setTailCallKind(TCK); 3749 cast<CallInst>(I)->setAttributes(PAL); 3750 break; 3751 } 3752 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 3753 if (Record.size() < 3) 3754 return Error("Invalid record"); 3755 Type *OpTy = getTypeByID(Record[0]); 3756 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 3757 Type *ResTy = getTypeByID(Record[2]); 3758 if (!OpTy || !Op || !ResTy) 3759 return Error("Invalid record"); 3760 I = new VAArgInst(Op, ResTy); 3761 InstructionList.push_back(I); 3762 break; 3763 } 3764 } 3765 3766 // Add instruction to end of current BB. If there is no current BB, reject 3767 // this file. 3768 if (!CurBB) { 3769 delete I; 3770 return Error("Invalid instruction with no BB"); 3771 } 3772 CurBB->getInstList().push_back(I); 3773 3774 // If this was a terminator instruction, move to the next block. 3775 if (isa<TerminatorInst>(I)) { 3776 ++CurBBNo; 3777 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 3778 } 3779 3780 // Non-void values get registered in the value table for future use. 3781 if (I && !I->getType()->isVoidTy()) 3782 ValueList.AssignValue(I, NextValueNo++); 3783 } 3784 3785 OutOfRecordLoop: 3786 3787 // Check the function list for unresolved values. 3788 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 3789 if (!A->getParent()) { 3790 // We found at least one unresolved value. Nuke them all to avoid leaks. 3791 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 3792 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 3793 A->replaceAllUsesWith(UndefValue::get(A->getType())); 3794 delete A; 3795 } 3796 } 3797 return Error("Never resolved value found in function"); 3798 } 3799 } 3800 3801 // FIXME: Check for unresolved forward-declared metadata references 3802 // and clean up leaks. 3803 3804 // Trim the value list down to the size it was before we parsed this function. 3805 ValueList.shrinkTo(ModuleValueListSize); 3806 MDValueList.shrinkTo(ModuleMDValueListSize); 3807 std::vector<BasicBlock*>().swap(FunctionBBs); 3808 return std::error_code(); 3809 } 3810 3811 /// Find the function body in the bitcode stream 3812 std::error_code BitcodeReader::FindFunctionInStream( 3813 Function *F, 3814 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 3815 while (DeferredFunctionInfoIterator->second == 0) { 3816 if (Stream.AtEndOfStream()) 3817 return Error("Could not find function in stream"); 3818 // ParseModule will parse the next body in the stream and set its 3819 // position in the DeferredFunctionInfo map. 3820 if (std::error_code EC = ParseModule(true)) 3821 return EC; 3822 } 3823 return std::error_code(); 3824 } 3825 3826 //===----------------------------------------------------------------------===// 3827 // GVMaterializer implementation 3828 //===----------------------------------------------------------------------===// 3829 3830 void BitcodeReader::releaseBuffer() { Buffer.release(); } 3831 3832 std::error_code BitcodeReader::materialize(GlobalValue *GV) { 3833 Function *F = dyn_cast<Function>(GV); 3834 // If it's not a function or is already material, ignore the request. 3835 if (!F || !F->isMaterializable()) 3836 return std::error_code(); 3837 3838 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 3839 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 3840 // If its position is recorded as 0, its body is somewhere in the stream 3841 // but we haven't seen it yet. 3842 if (DFII->second == 0 && LazyStreamer) 3843 if (std::error_code EC = FindFunctionInStream(F, DFII)) 3844 return EC; 3845 3846 // Move the bit stream to the saved position of the deferred function body. 3847 Stream.JumpToBit(DFII->second); 3848 3849 if (std::error_code EC = ParseFunctionBody(F)) 3850 return EC; 3851 F->setIsMaterializable(false); 3852 3853 // Upgrade any old intrinsic calls in the function. 3854 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 3855 E = UpgradedIntrinsics.end(); I != E; ++I) { 3856 if (I->first != I->second) { 3857 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3858 UI != UE;) { 3859 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3860 UpgradeIntrinsicCall(CI, I->second); 3861 } 3862 } 3863 } 3864 3865 // Bring in any functions that this function forward-referenced via 3866 // blockaddresses. 3867 return materializeForwardReferencedFunctions(); 3868 } 3869 3870 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 3871 const Function *F = dyn_cast<Function>(GV); 3872 if (!F || F->isDeclaration()) 3873 return false; 3874 3875 // Dematerializing F would leave dangling references that wouldn't be 3876 // reconnected on re-materialization. 3877 if (BlockAddressesTaken.count(F)) 3878 return false; 3879 3880 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 3881 } 3882 3883 void BitcodeReader::Dematerialize(GlobalValue *GV) { 3884 Function *F = dyn_cast<Function>(GV); 3885 // If this function isn't dematerializable, this is a noop. 3886 if (!F || !isDematerializable(F)) 3887 return; 3888 3889 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 3890 3891 // Just forget the function body, we can remat it later. 3892 F->dropAllReferences(); 3893 F->setIsMaterializable(true); 3894 } 3895 3896 std::error_code BitcodeReader::MaterializeModule(Module *M) { 3897 assert(M == TheModule && 3898 "Can only Materialize the Module this BitcodeReader is attached to."); 3899 3900 // Promise to materialize all forward references. 3901 WillMaterializeAllForwardRefs = true; 3902 3903 // Iterate over the module, deserializing any functions that are still on 3904 // disk. 3905 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 3906 F != E; ++F) { 3907 if (std::error_code EC = materialize(F)) 3908 return EC; 3909 } 3910 // At this point, if there are any function bodies, the current bit is 3911 // pointing to the END_BLOCK record after them. Now make sure the rest 3912 // of the bits in the module have been read. 3913 if (NextUnreadBit) 3914 ParseModule(true); 3915 3916 // Check that all block address forward references got resolved (as we 3917 // promised above). 3918 if (!BasicBlockFwdRefs.empty()) 3919 return Error("Never resolved function from blockaddress"); 3920 3921 // Upgrade any intrinsic calls that slipped through (should not happen!) and 3922 // delete the old functions to clean up. We can't do this unless the entire 3923 // module is materialized because there could always be another function body 3924 // with calls to the old function. 3925 for (std::vector<std::pair<Function*, Function*> >::iterator I = 3926 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 3927 if (I->first != I->second) { 3928 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3929 UI != UE;) { 3930 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3931 UpgradeIntrinsicCall(CI, I->second); 3932 } 3933 if (!I->first->use_empty()) 3934 I->first->replaceAllUsesWith(I->second); 3935 I->first->eraseFromParent(); 3936 } 3937 } 3938 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 3939 3940 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 3941 UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 3942 3943 UpgradeDebugInfo(*M); 3944 return std::error_code(); 3945 } 3946 3947 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 3948 return IdentifiedStructTypes; 3949 } 3950 3951 std::error_code BitcodeReader::InitStream() { 3952 if (LazyStreamer) 3953 return InitLazyStream(); 3954 return InitStreamFromBuffer(); 3955 } 3956 3957 std::error_code BitcodeReader::InitStreamFromBuffer() { 3958 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 3959 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 3960 3961 if (Buffer->getBufferSize() & 3) 3962 return Error("Invalid bitcode signature"); 3963 3964 // If we have a wrapper header, parse it and ignore the non-bc file contents. 3965 // The magic number is 0x0B17C0DE stored in little endian. 3966 if (isBitcodeWrapper(BufPtr, BufEnd)) 3967 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 3968 return Error("Invalid bitcode wrapper header"); 3969 3970 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 3971 Stream.init(&*StreamFile); 3972 3973 return std::error_code(); 3974 } 3975 3976 std::error_code BitcodeReader::InitLazyStream() { 3977 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 3978 // see it. 3979 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer); 3980 StreamingMemoryObject &Bytes = *OwnedBytes; 3981 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 3982 Stream.init(&*StreamFile); 3983 3984 unsigned char buf[16]; 3985 if (Bytes.readBytes(buf, 16, 0) != 16) 3986 return Error("Invalid bitcode signature"); 3987 3988 if (!isBitcode(buf, buf + 16)) 3989 return Error("Invalid bitcode signature"); 3990 3991 if (isBitcodeWrapper(buf, buf + 4)) { 3992 const unsigned char *bitcodeStart = buf; 3993 const unsigned char *bitcodeEnd = buf + 16; 3994 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 3995 Bytes.dropLeadingBytes(bitcodeStart - buf); 3996 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 3997 } 3998 return std::error_code(); 3999 } 4000 4001 namespace { 4002 class BitcodeErrorCategoryType : public std::error_category { 4003 const char *name() const LLVM_NOEXCEPT override { 4004 return "llvm.bitcode"; 4005 } 4006 std::string message(int IE) const override { 4007 BitcodeError E = static_cast<BitcodeError>(IE); 4008 switch (E) { 4009 case BitcodeError::InvalidBitcodeSignature: 4010 return "Invalid bitcode signature"; 4011 case BitcodeError::CorruptedBitcode: 4012 return "Corrupted bitcode"; 4013 } 4014 llvm_unreachable("Unknown error type!"); 4015 } 4016 }; 4017 } 4018 4019 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 4020 4021 const std::error_category &llvm::BitcodeErrorCategory() { 4022 return *ErrorCategory; 4023 } 4024 4025 //===----------------------------------------------------------------------===// 4026 // External interface 4027 //===----------------------------------------------------------------------===// 4028 4029 /// \brief Get a lazy one-at-time loading module from bitcode. 4030 /// 4031 /// This isn't always used in a lazy context. In particular, it's also used by 4032 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 4033 /// in forward-referenced functions from block address references. 4034 /// 4035 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to 4036 /// materialize everything -- in particular, if this isn't truly lazy. 4037 static ErrorOr<Module *> 4038 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 4039 LLVMContext &Context, bool WillMaterializeAll, 4040 DiagnosticHandlerFunction DiagnosticHandler) { 4041 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 4042 BitcodeReader *R = 4043 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler); 4044 M->setMaterializer(R); 4045 4046 auto cleanupOnError = [&](std::error_code EC) { 4047 R->releaseBuffer(); // Never take ownership on error. 4048 delete M; // Also deletes R. 4049 return EC; 4050 }; 4051 4052 if (std::error_code EC = R->ParseBitcodeInto(M)) 4053 return cleanupOnError(EC); 4054 4055 if (!WillMaterializeAll) 4056 // Resolve forward references from blockaddresses. 4057 if (std::error_code EC = R->materializeForwardReferencedFunctions()) 4058 return cleanupOnError(EC); 4059 4060 Buffer.release(); // The BitcodeReader owns it now. 4061 return M; 4062 } 4063 4064 ErrorOr<Module *> 4065 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 4066 LLVMContext &Context, 4067 DiagnosticHandlerFunction DiagnosticHandler) { 4068 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 4069 DiagnosticHandler); 4070 } 4071 4072 ErrorOr<std::unique_ptr<Module>> 4073 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer, 4074 LLVMContext &Context, 4075 DiagnosticHandlerFunction DiagnosticHandler) { 4076 std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 4077 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler); 4078 M->setMaterializer(R); 4079 if (std::error_code EC = R->ParseBitcodeInto(M.get())) 4080 return EC; 4081 return std::move(M); 4082 } 4083 4084 ErrorOr<Module *> 4085 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 4086 DiagnosticHandlerFunction DiagnosticHandler) { 4087 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 4088 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl( 4089 std::move(Buf), Context, true, DiagnosticHandler); 4090 if (!ModuleOrErr) 4091 return ModuleOrErr; 4092 Module *M = ModuleOrErr.get(); 4093 // Read in the entire module, and destroy the BitcodeReader. 4094 if (std::error_code EC = M->materializeAllPermanently()) { 4095 delete M; 4096 return EC; 4097 } 4098 4099 // TODO: Restore the use-lists to the in-memory state when the bitcode was 4100 // written. We must defer until the Module has been fully materialized. 4101 4102 return M; 4103 } 4104 4105 std::string 4106 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context, 4107 DiagnosticHandlerFunction DiagnosticHandler) { 4108 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 4109 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context, 4110 DiagnosticHandler); 4111 ErrorOr<std::string> Triple = R->parseTriple(); 4112 if (Triple.getError()) 4113 return ""; 4114 return Triple.get(); 4115 } 4116