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