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