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 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; } 1177 1178 std::error_code BitcodeReader::ParseMetadata() { 1179 unsigned NextMDValueNo = MDValueList.size(); 1180 1181 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 1182 return Error("Invalid record"); 1183 1184 SmallVector<uint64_t, 64> Record; 1185 1186 auto getMDString = [&](unsigned ID) -> MDString *{ 1187 // This requires that the ID is not really a forward reference. In 1188 // particular, the MDString must already have been resolved. 1189 if (ID) 1190 return cast<MDString>(MDValueList.getValueFwdRef(ID - 1)); 1191 return nullptr; 1192 }; 1193 1194 #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \ 1195 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS) 1196 1197 // Read all the records. 1198 while (1) { 1199 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1200 1201 switch (Entry.Kind) { 1202 case BitstreamEntry::SubBlock: // Handled for us already. 1203 case BitstreamEntry::Error: 1204 return Error("Malformed block"); 1205 case BitstreamEntry::EndBlock: 1206 MDValueList.tryToResolveCycles(); 1207 return std::error_code(); 1208 case BitstreamEntry::Record: 1209 // The interesting case. 1210 break; 1211 } 1212 1213 // Read a record. 1214 Record.clear(); 1215 unsigned Code = Stream.readRecord(Entry.ID, Record); 1216 bool IsDistinct = false; 1217 switch (Code) { 1218 default: // Default behavior: ignore. 1219 break; 1220 case bitc::METADATA_NAME: { 1221 // Read name of the named metadata. 1222 SmallString<8> Name(Record.begin(), Record.end()); 1223 Record.clear(); 1224 Code = Stream.ReadCode(); 1225 1226 // METADATA_NAME is always followed by METADATA_NAMED_NODE. 1227 unsigned NextBitCode = Stream.readRecord(Code, Record); 1228 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode; 1229 1230 // Read named metadata elements. 1231 unsigned Size = Record.size(); 1232 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 1233 for (unsigned i = 0; i != Size; ++i) { 1234 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i])); 1235 if (!MD) 1236 return Error("Invalid record"); 1237 NMD->addOperand(MD); 1238 } 1239 break; 1240 } 1241 case bitc::METADATA_OLD_FN_NODE: { 1242 // FIXME: Remove in 4.0. 1243 // This is a LocalAsMetadata record, the only type of function-local 1244 // metadata. 1245 if (Record.size() % 2 == 1) 1246 return Error("Invalid record"); 1247 1248 // If this isn't a LocalAsMetadata record, we're dropping it. This used 1249 // to be legal, but there's no upgrade path. 1250 auto dropRecord = [&] { 1251 MDValueList.AssignValue(MDNode::get(Context, None), NextMDValueNo++); 1252 }; 1253 if (Record.size() != 2) { 1254 dropRecord(); 1255 break; 1256 } 1257 1258 Type *Ty = getTypeByID(Record[0]); 1259 if (Ty->isMetadataTy() || Ty->isVoidTy()) { 1260 dropRecord(); 1261 break; 1262 } 1263 1264 MDValueList.AssignValue( 1265 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 1266 NextMDValueNo++); 1267 break; 1268 } 1269 case bitc::METADATA_OLD_NODE: { 1270 // FIXME: Remove in 4.0. 1271 if (Record.size() % 2 == 1) 1272 return Error("Invalid record"); 1273 1274 unsigned Size = Record.size(); 1275 SmallVector<Metadata *, 8> Elts; 1276 for (unsigned i = 0; i != Size; i += 2) { 1277 Type *Ty = getTypeByID(Record[i]); 1278 if (!Ty) 1279 return Error("Invalid record"); 1280 if (Ty->isMetadataTy()) 1281 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 1282 else if (!Ty->isVoidTy()) { 1283 auto *MD = 1284 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 1285 assert(isa<ConstantAsMetadata>(MD) && 1286 "Expected non-function-local metadata"); 1287 Elts.push_back(MD); 1288 } else 1289 Elts.push_back(nullptr); 1290 } 1291 MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++); 1292 break; 1293 } 1294 case bitc::METADATA_VALUE: { 1295 if (Record.size() != 2) 1296 return Error("Invalid record"); 1297 1298 Type *Ty = getTypeByID(Record[0]); 1299 if (Ty->isMetadataTy() || Ty->isVoidTy()) 1300 return Error("Invalid record"); 1301 1302 MDValueList.AssignValue( 1303 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 1304 NextMDValueNo++); 1305 break; 1306 } 1307 case bitc::METADATA_DISTINCT_NODE: 1308 IsDistinct = true; 1309 // fallthrough... 1310 case bitc::METADATA_NODE: { 1311 SmallVector<Metadata *, 8> Elts; 1312 Elts.reserve(Record.size()); 1313 for (unsigned ID : Record) 1314 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr); 1315 MDValueList.AssignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 1316 : MDNode::get(Context, Elts), 1317 NextMDValueNo++); 1318 break; 1319 } 1320 case bitc::METADATA_LOCATION: { 1321 if (Record.size() != 5) 1322 return Error("Invalid record"); 1323 1324 auto get = Record[0] ? MDLocation::getDistinct : MDLocation::get; 1325 unsigned Line = Record[1]; 1326 unsigned Column = Record[2]; 1327 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3])); 1328 Metadata *InlinedAt = 1329 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr; 1330 MDValueList.AssignValue(get(Context, Line, Column, Scope, InlinedAt), 1331 NextMDValueNo++); 1332 break; 1333 } 1334 case bitc::METADATA_GENERIC_DEBUG: { 1335 if (Record.size() < 4) 1336 return Error("Invalid record"); 1337 1338 unsigned Tag = Record[1]; 1339 unsigned Version = Record[2]; 1340 1341 if (Tag >= 1u << 16 || Version != 0) 1342 return Error("Invalid record"); 1343 1344 auto *Header = getMDString(Record[3]); 1345 SmallVector<Metadata *, 8> DwarfOps; 1346 for (unsigned I = 4, E = Record.size(); I != E; ++I) 1347 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1) 1348 : nullptr); 1349 MDValueList.AssignValue(GET_OR_DISTINCT(GenericDebugNode, Record[0], 1350 (Context, Tag, Header, DwarfOps)), 1351 NextMDValueNo++); 1352 break; 1353 } 1354 case bitc::METADATA_SUBRANGE: { 1355 if (Record.size() != 3) 1356 return Error("Invalid record"); 1357 1358 MDValueList.AssignValue( 1359 GET_OR_DISTINCT(MDSubrange, Record[0], 1360 (Context, Record[1], unrotateSign(Record[2]))), 1361 NextMDValueNo++); 1362 break; 1363 } 1364 case bitc::METADATA_ENUMERATOR: { 1365 if (Record.size() != 3) 1366 return Error("Invalid record"); 1367 1368 MDValueList.AssignValue(GET_OR_DISTINCT(MDEnumerator, Record[0], 1369 (Context, unrotateSign(Record[1]), 1370 getMDString(Record[2]))), 1371 NextMDValueNo++); 1372 break; 1373 } 1374 case bitc::METADATA_STRING: { 1375 std::string String(Record.begin(), Record.end()); 1376 llvm::UpgradeMDStringConstant(String); 1377 Metadata *MD = MDString::get(Context, String); 1378 MDValueList.AssignValue(MD, NextMDValueNo++); 1379 break; 1380 } 1381 case bitc::METADATA_KIND: { 1382 if (Record.size() < 2) 1383 return Error("Invalid record"); 1384 1385 unsigned Kind = Record[0]; 1386 SmallString<8> Name(Record.begin()+1, Record.end()); 1387 1388 unsigned NewKind = TheModule->getMDKindID(Name.str()); 1389 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1390 return Error("Conflicting METADATA_KIND records"); 1391 break; 1392 } 1393 } 1394 } 1395 #undef GET_OR_DISTINCT 1396 } 1397 1398 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 1399 /// the LSB for dense VBR encoding. 1400 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 1401 if ((V & 1) == 0) 1402 return V >> 1; 1403 if (V != 1) 1404 return -(V >> 1); 1405 // There is no such thing as -0 with integers. "-0" really means MININT. 1406 return 1ULL << 63; 1407 } 1408 1409 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 1410 /// values and aliases that we can. 1411 std::error_code BitcodeReader::ResolveGlobalAndAliasInits() { 1412 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 1413 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 1414 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist; 1415 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist; 1416 1417 GlobalInitWorklist.swap(GlobalInits); 1418 AliasInitWorklist.swap(AliasInits); 1419 FunctionPrefixWorklist.swap(FunctionPrefixes); 1420 FunctionPrologueWorklist.swap(FunctionPrologues); 1421 1422 while (!GlobalInitWorklist.empty()) { 1423 unsigned ValID = GlobalInitWorklist.back().second; 1424 if (ValID >= ValueList.size()) { 1425 // Not ready to resolve this yet, it requires something later in the file. 1426 GlobalInits.push_back(GlobalInitWorklist.back()); 1427 } else { 1428 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1429 GlobalInitWorklist.back().first->setInitializer(C); 1430 else 1431 return Error("Expected a constant"); 1432 } 1433 GlobalInitWorklist.pop_back(); 1434 } 1435 1436 while (!AliasInitWorklist.empty()) { 1437 unsigned ValID = AliasInitWorklist.back().second; 1438 if (ValID >= ValueList.size()) { 1439 AliasInits.push_back(AliasInitWorklist.back()); 1440 } else { 1441 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1442 AliasInitWorklist.back().first->setAliasee(C); 1443 else 1444 return Error("Expected a constant"); 1445 } 1446 AliasInitWorklist.pop_back(); 1447 } 1448 1449 while (!FunctionPrefixWorklist.empty()) { 1450 unsigned ValID = FunctionPrefixWorklist.back().second; 1451 if (ValID >= ValueList.size()) { 1452 FunctionPrefixes.push_back(FunctionPrefixWorklist.back()); 1453 } else { 1454 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1455 FunctionPrefixWorklist.back().first->setPrefixData(C); 1456 else 1457 return Error("Expected a constant"); 1458 } 1459 FunctionPrefixWorklist.pop_back(); 1460 } 1461 1462 while (!FunctionPrologueWorklist.empty()) { 1463 unsigned ValID = FunctionPrologueWorklist.back().second; 1464 if (ValID >= ValueList.size()) { 1465 FunctionPrologues.push_back(FunctionPrologueWorklist.back()); 1466 } else { 1467 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID])) 1468 FunctionPrologueWorklist.back().first->setPrologueData(C); 1469 else 1470 return Error("Expected a constant"); 1471 } 1472 FunctionPrologueWorklist.pop_back(); 1473 } 1474 1475 return std::error_code(); 1476 } 1477 1478 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 1479 SmallVector<uint64_t, 8> Words(Vals.size()); 1480 std::transform(Vals.begin(), Vals.end(), Words.begin(), 1481 BitcodeReader::decodeSignRotatedValue); 1482 1483 return APInt(TypeBits, Words); 1484 } 1485 1486 std::error_code BitcodeReader::ParseConstants() { 1487 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 1488 return Error("Invalid record"); 1489 1490 SmallVector<uint64_t, 64> Record; 1491 1492 // Read all the records for this value table. 1493 Type *CurTy = Type::getInt32Ty(Context); 1494 unsigned NextCstNo = ValueList.size(); 1495 while (1) { 1496 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1497 1498 switch (Entry.Kind) { 1499 case BitstreamEntry::SubBlock: // Handled for us already. 1500 case BitstreamEntry::Error: 1501 return Error("Malformed block"); 1502 case BitstreamEntry::EndBlock: 1503 if (NextCstNo != ValueList.size()) 1504 return Error("Invalid ronstant reference"); 1505 1506 // Once all the constants have been read, go through and resolve forward 1507 // references. 1508 ValueList.ResolveConstantForwardRefs(); 1509 return std::error_code(); 1510 case BitstreamEntry::Record: 1511 // The interesting case. 1512 break; 1513 } 1514 1515 // Read a record. 1516 Record.clear(); 1517 Value *V = nullptr; 1518 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 1519 switch (BitCode) { 1520 default: // Default behavior: unknown constant 1521 case bitc::CST_CODE_UNDEF: // UNDEF 1522 V = UndefValue::get(CurTy); 1523 break; 1524 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 1525 if (Record.empty()) 1526 return Error("Invalid record"); 1527 if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) 1528 return Error("Invalid record"); 1529 CurTy = TypeList[Record[0]]; 1530 continue; // Skip the ValueList manipulation. 1531 case bitc::CST_CODE_NULL: // NULL 1532 V = Constant::getNullValue(CurTy); 1533 break; 1534 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 1535 if (!CurTy->isIntegerTy() || Record.empty()) 1536 return Error("Invalid record"); 1537 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 1538 break; 1539 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 1540 if (!CurTy->isIntegerTy() || Record.empty()) 1541 return Error("Invalid record"); 1542 1543 APInt VInt = ReadWideAPInt(Record, 1544 cast<IntegerType>(CurTy)->getBitWidth()); 1545 V = ConstantInt::get(Context, VInt); 1546 1547 break; 1548 } 1549 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 1550 if (Record.empty()) 1551 return Error("Invalid record"); 1552 if (CurTy->isHalfTy()) 1553 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 1554 APInt(16, (uint16_t)Record[0]))); 1555 else if (CurTy->isFloatTy()) 1556 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 1557 APInt(32, (uint32_t)Record[0]))); 1558 else if (CurTy->isDoubleTy()) 1559 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 1560 APInt(64, Record[0]))); 1561 else if (CurTy->isX86_FP80Ty()) { 1562 // Bits are not stored the same way as a normal i80 APInt, compensate. 1563 uint64_t Rearrange[2]; 1564 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 1565 Rearrange[1] = Record[0] >> 48; 1566 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 1567 APInt(80, Rearrange))); 1568 } else if (CurTy->isFP128Ty()) 1569 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 1570 APInt(128, Record))); 1571 else if (CurTy->isPPC_FP128Ty()) 1572 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 1573 APInt(128, Record))); 1574 else 1575 V = UndefValue::get(CurTy); 1576 break; 1577 } 1578 1579 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 1580 if (Record.empty()) 1581 return Error("Invalid record"); 1582 1583 unsigned Size = Record.size(); 1584 SmallVector<Constant*, 16> Elts; 1585 1586 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 1587 for (unsigned i = 0; i != Size; ++i) 1588 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 1589 STy->getElementType(i))); 1590 V = ConstantStruct::get(STy, Elts); 1591 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 1592 Type *EltTy = ATy->getElementType(); 1593 for (unsigned i = 0; i != Size; ++i) 1594 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1595 V = ConstantArray::get(ATy, Elts); 1596 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 1597 Type *EltTy = VTy->getElementType(); 1598 for (unsigned i = 0; i != Size; ++i) 1599 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 1600 V = ConstantVector::get(Elts); 1601 } else { 1602 V = UndefValue::get(CurTy); 1603 } 1604 break; 1605 } 1606 case bitc::CST_CODE_STRING: // STRING: [values] 1607 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 1608 if (Record.empty()) 1609 return Error("Invalid record"); 1610 1611 SmallString<16> Elts(Record.begin(), Record.end()); 1612 V = ConstantDataArray::getString(Context, Elts, 1613 BitCode == bitc::CST_CODE_CSTRING); 1614 break; 1615 } 1616 case bitc::CST_CODE_DATA: {// DATA: [n x value] 1617 if (Record.empty()) 1618 return Error("Invalid record"); 1619 1620 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 1621 unsigned Size = Record.size(); 1622 1623 if (EltTy->isIntegerTy(8)) { 1624 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 1625 if (isa<VectorType>(CurTy)) 1626 V = ConstantDataVector::get(Context, Elts); 1627 else 1628 V = ConstantDataArray::get(Context, Elts); 1629 } else if (EltTy->isIntegerTy(16)) { 1630 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 1631 if (isa<VectorType>(CurTy)) 1632 V = ConstantDataVector::get(Context, Elts); 1633 else 1634 V = ConstantDataArray::get(Context, Elts); 1635 } else if (EltTy->isIntegerTy(32)) { 1636 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 1637 if (isa<VectorType>(CurTy)) 1638 V = ConstantDataVector::get(Context, Elts); 1639 else 1640 V = ConstantDataArray::get(Context, Elts); 1641 } else if (EltTy->isIntegerTy(64)) { 1642 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 1643 if (isa<VectorType>(CurTy)) 1644 V = ConstantDataVector::get(Context, Elts); 1645 else 1646 V = ConstantDataArray::get(Context, Elts); 1647 } else if (EltTy->isFloatTy()) { 1648 SmallVector<float, 16> Elts(Size); 1649 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 1650 if (isa<VectorType>(CurTy)) 1651 V = ConstantDataVector::get(Context, Elts); 1652 else 1653 V = ConstantDataArray::get(Context, Elts); 1654 } else if (EltTy->isDoubleTy()) { 1655 SmallVector<double, 16> Elts(Size); 1656 std::transform(Record.begin(), Record.end(), Elts.begin(), 1657 BitsToDouble); 1658 if (isa<VectorType>(CurTy)) 1659 V = ConstantDataVector::get(Context, Elts); 1660 else 1661 V = ConstantDataArray::get(Context, Elts); 1662 } else { 1663 return Error("Invalid type for value"); 1664 } 1665 break; 1666 } 1667 1668 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 1669 if (Record.size() < 3) 1670 return Error("Invalid record"); 1671 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 1672 if (Opc < 0) { 1673 V = UndefValue::get(CurTy); // Unknown binop. 1674 } else { 1675 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 1676 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 1677 unsigned Flags = 0; 1678 if (Record.size() >= 4) { 1679 if (Opc == Instruction::Add || 1680 Opc == Instruction::Sub || 1681 Opc == Instruction::Mul || 1682 Opc == Instruction::Shl) { 1683 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 1684 Flags |= OverflowingBinaryOperator::NoSignedWrap; 1685 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 1686 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 1687 } else if (Opc == Instruction::SDiv || 1688 Opc == Instruction::UDiv || 1689 Opc == Instruction::LShr || 1690 Opc == Instruction::AShr) { 1691 if (Record[3] & (1 << bitc::PEO_EXACT)) 1692 Flags |= SDivOperator::IsExact; 1693 } 1694 } 1695 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 1696 } 1697 break; 1698 } 1699 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 1700 if (Record.size() < 3) 1701 return Error("Invalid record"); 1702 int Opc = GetDecodedCastOpcode(Record[0]); 1703 if (Opc < 0) { 1704 V = UndefValue::get(CurTy); // Unknown cast. 1705 } else { 1706 Type *OpTy = getTypeByID(Record[1]); 1707 if (!OpTy) 1708 return Error("Invalid record"); 1709 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 1710 V = UpgradeBitCastExpr(Opc, Op, CurTy); 1711 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); 1712 } 1713 break; 1714 } 1715 case bitc::CST_CODE_CE_INBOUNDS_GEP: 1716 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 1717 if (Record.size() & 1) 1718 return Error("Invalid record"); 1719 SmallVector<Constant*, 16> Elts; 1720 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 1721 Type *ElTy = getTypeByID(Record[i]); 1722 if (!ElTy) 1723 return Error("Invalid record"); 1724 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 1725 } 1726 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 1727 V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 1728 BitCode == 1729 bitc::CST_CODE_CE_INBOUNDS_GEP); 1730 break; 1731 } 1732 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] 1733 if (Record.size() < 3) 1734 return Error("Invalid record"); 1735 1736 Type *SelectorTy = Type::getInt1Ty(Context); 1737 1738 // If CurTy is a vector of length n, then Record[0] must be a <n x i1> 1739 // vector. Otherwise, it must be a single bit. 1740 if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) 1741 SelectorTy = VectorType::get(Type::getInt1Ty(Context), 1742 VTy->getNumElements()); 1743 1744 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], 1745 SelectorTy), 1746 ValueList.getConstantFwdRef(Record[1],CurTy), 1747 ValueList.getConstantFwdRef(Record[2],CurTy)); 1748 break; 1749 } 1750 case bitc::CST_CODE_CE_EXTRACTELT 1751 : { // CE_EXTRACTELT: [opty, opval, opty, opval] 1752 if (Record.size() < 3) 1753 return Error("Invalid record"); 1754 VectorType *OpTy = 1755 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1756 if (!OpTy) 1757 return Error("Invalid record"); 1758 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1759 Constant *Op1 = nullptr; 1760 if (Record.size() == 4) { 1761 Type *IdxTy = getTypeByID(Record[2]); 1762 if (!IdxTy) 1763 return Error("Invalid record"); 1764 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1765 } else // TODO: Remove with llvm 4.0 1766 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1767 if (!Op1) 1768 return Error("Invalid record"); 1769 V = ConstantExpr::getExtractElement(Op0, Op1); 1770 break; 1771 } 1772 case bitc::CST_CODE_CE_INSERTELT 1773 : { // CE_INSERTELT: [opval, opval, opty, opval] 1774 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1775 if (Record.size() < 3 || !OpTy) 1776 return Error("Invalid record"); 1777 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1778 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 1779 OpTy->getElementType()); 1780 Constant *Op2 = nullptr; 1781 if (Record.size() == 4) { 1782 Type *IdxTy = getTypeByID(Record[2]); 1783 if (!IdxTy) 1784 return Error("Invalid record"); 1785 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy); 1786 } else // TODO: Remove with llvm 4.0 1787 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context)); 1788 if (!Op2) 1789 return Error("Invalid record"); 1790 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 1791 break; 1792 } 1793 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 1794 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 1795 if (Record.size() < 3 || !OpTy) 1796 return Error("Invalid record"); 1797 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 1798 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 1799 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1800 OpTy->getNumElements()); 1801 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 1802 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1803 break; 1804 } 1805 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 1806 VectorType *RTy = dyn_cast<VectorType>(CurTy); 1807 VectorType *OpTy = 1808 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 1809 if (Record.size() < 4 || !RTy || !OpTy) 1810 return Error("Invalid record"); 1811 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1812 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1813 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 1814 RTy->getNumElements()); 1815 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 1816 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 1817 break; 1818 } 1819 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 1820 if (Record.size() < 4) 1821 return Error("Invalid record"); 1822 Type *OpTy = getTypeByID(Record[0]); 1823 if (!OpTy) 1824 return Error("Invalid record"); 1825 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 1826 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 1827 1828 if (OpTy->isFPOrFPVectorTy()) 1829 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 1830 else 1831 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 1832 break; 1833 } 1834 // This maintains backward compatibility, pre-asm dialect keywords. 1835 // FIXME: Remove with the 4.0 release. 1836 case bitc::CST_CODE_INLINEASM_OLD: { 1837 if (Record.size() < 2) 1838 return Error("Invalid record"); 1839 std::string AsmStr, ConstrStr; 1840 bool HasSideEffects = Record[0] & 1; 1841 bool IsAlignStack = Record[0] >> 1; 1842 unsigned AsmStrSize = Record[1]; 1843 if (2+AsmStrSize >= Record.size()) 1844 return Error("Invalid record"); 1845 unsigned ConstStrSize = Record[2+AsmStrSize]; 1846 if (3+AsmStrSize+ConstStrSize > Record.size()) 1847 return Error("Invalid record"); 1848 1849 for (unsigned i = 0; i != AsmStrSize; ++i) 1850 AsmStr += (char)Record[2+i]; 1851 for (unsigned i = 0; i != ConstStrSize; ++i) 1852 ConstrStr += (char)Record[3+AsmStrSize+i]; 1853 PointerType *PTy = cast<PointerType>(CurTy); 1854 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1855 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 1856 break; 1857 } 1858 // This version adds support for the asm dialect keywords (e.g., 1859 // inteldialect). 1860 case bitc::CST_CODE_INLINEASM: { 1861 if (Record.size() < 2) 1862 return Error("Invalid record"); 1863 std::string AsmStr, ConstrStr; 1864 bool HasSideEffects = Record[0] & 1; 1865 bool IsAlignStack = (Record[0] >> 1) & 1; 1866 unsigned AsmDialect = Record[0] >> 2; 1867 unsigned AsmStrSize = Record[1]; 1868 if (2+AsmStrSize >= Record.size()) 1869 return Error("Invalid record"); 1870 unsigned ConstStrSize = Record[2+AsmStrSize]; 1871 if (3+AsmStrSize+ConstStrSize > Record.size()) 1872 return Error("Invalid record"); 1873 1874 for (unsigned i = 0; i != AsmStrSize; ++i) 1875 AsmStr += (char)Record[2+i]; 1876 for (unsigned i = 0; i != ConstStrSize; ++i) 1877 ConstrStr += (char)Record[3+AsmStrSize+i]; 1878 PointerType *PTy = cast<PointerType>(CurTy); 1879 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 1880 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 1881 InlineAsm::AsmDialect(AsmDialect)); 1882 break; 1883 } 1884 case bitc::CST_CODE_BLOCKADDRESS:{ 1885 if (Record.size() < 3) 1886 return Error("Invalid record"); 1887 Type *FnTy = getTypeByID(Record[0]); 1888 if (!FnTy) 1889 return Error("Invalid record"); 1890 Function *Fn = 1891 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 1892 if (!Fn) 1893 return Error("Invalid record"); 1894 1895 // Don't let Fn get dematerialized. 1896 BlockAddressesTaken.insert(Fn); 1897 1898 // If the function is already parsed we can insert the block address right 1899 // away. 1900 BasicBlock *BB; 1901 unsigned BBID = Record[2]; 1902 if (!BBID) 1903 // Invalid reference to entry block. 1904 return Error("Invalid ID"); 1905 if (!Fn->empty()) { 1906 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 1907 for (size_t I = 0, E = BBID; I != E; ++I) { 1908 if (BBI == BBE) 1909 return Error("Invalid ID"); 1910 ++BBI; 1911 } 1912 BB = BBI; 1913 } else { 1914 // Otherwise insert a placeholder and remember it so it can be inserted 1915 // when the function is parsed. 1916 auto &FwdBBs = BasicBlockFwdRefs[Fn]; 1917 if (FwdBBs.empty()) 1918 BasicBlockFwdRefQueue.push_back(Fn); 1919 if (FwdBBs.size() < BBID + 1) 1920 FwdBBs.resize(BBID + 1); 1921 if (!FwdBBs[BBID]) 1922 FwdBBs[BBID] = BasicBlock::Create(Context); 1923 BB = FwdBBs[BBID]; 1924 } 1925 V = BlockAddress::get(Fn, BB); 1926 break; 1927 } 1928 } 1929 1930 ValueList.AssignValue(V, NextCstNo); 1931 ++NextCstNo; 1932 } 1933 } 1934 1935 std::error_code BitcodeReader::ParseUseLists() { 1936 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 1937 return Error("Invalid record"); 1938 1939 // Read all the records. 1940 SmallVector<uint64_t, 64> Record; 1941 while (1) { 1942 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1943 1944 switch (Entry.Kind) { 1945 case BitstreamEntry::SubBlock: // Handled for us already. 1946 case BitstreamEntry::Error: 1947 return Error("Malformed block"); 1948 case BitstreamEntry::EndBlock: 1949 return std::error_code(); 1950 case BitstreamEntry::Record: 1951 // The interesting case. 1952 break; 1953 } 1954 1955 // Read a use list record. 1956 Record.clear(); 1957 bool IsBB = false; 1958 switch (Stream.readRecord(Entry.ID, Record)) { 1959 default: // Default behavior: unknown type. 1960 break; 1961 case bitc::USELIST_CODE_BB: 1962 IsBB = true; 1963 // fallthrough 1964 case bitc::USELIST_CODE_DEFAULT: { 1965 unsigned RecordLength = Record.size(); 1966 if (RecordLength < 3) 1967 // Records should have at least an ID and two indexes. 1968 return Error("Invalid record"); 1969 unsigned ID = Record.back(); 1970 Record.pop_back(); 1971 1972 Value *V; 1973 if (IsBB) { 1974 assert(ID < FunctionBBs.size() && "Basic block not found"); 1975 V = FunctionBBs[ID]; 1976 } else 1977 V = ValueList[ID]; 1978 unsigned NumUses = 0; 1979 SmallDenseMap<const Use *, unsigned, 16> Order; 1980 for (const Use &U : V->uses()) { 1981 if (++NumUses > Record.size()) 1982 break; 1983 Order[&U] = Record[NumUses - 1]; 1984 } 1985 if (Order.size() != Record.size() || NumUses > Record.size()) 1986 // Mismatches can happen if the functions are being materialized lazily 1987 // (out-of-order), or a value has been upgraded. 1988 break; 1989 1990 V->sortUseList([&](const Use &L, const Use &R) { 1991 return Order.lookup(&L) < Order.lookup(&R); 1992 }); 1993 break; 1994 } 1995 } 1996 } 1997 } 1998 1999 /// RememberAndSkipFunctionBody - When we see the block for a function body, 2000 /// remember where it is and then skip it. This lets us lazily deserialize the 2001 /// functions. 2002 std::error_code BitcodeReader::RememberAndSkipFunctionBody() { 2003 // Get the function we are talking about. 2004 if (FunctionsWithBodies.empty()) 2005 return Error("Insufficient function protos"); 2006 2007 Function *Fn = FunctionsWithBodies.back(); 2008 FunctionsWithBodies.pop_back(); 2009 2010 // Save the current stream state. 2011 uint64_t CurBit = Stream.GetCurrentBitNo(); 2012 DeferredFunctionInfo[Fn] = CurBit; 2013 2014 // Skip over the function block for now. 2015 if (Stream.SkipBlock()) 2016 return Error("Invalid record"); 2017 return std::error_code(); 2018 } 2019 2020 std::error_code BitcodeReader::GlobalCleanup() { 2021 // Patch the initializers for globals and aliases up. 2022 ResolveGlobalAndAliasInits(); 2023 if (!GlobalInits.empty() || !AliasInits.empty()) 2024 return Error("Malformed global initializer set"); 2025 2026 // Look for intrinsic functions which need to be upgraded at some point 2027 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 2028 FI != FE; ++FI) { 2029 Function *NewFn; 2030 if (UpgradeIntrinsicFunction(FI, NewFn)) 2031 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 2032 } 2033 2034 // Look for global variables which need to be renamed. 2035 for (Module::global_iterator 2036 GI = TheModule->global_begin(), GE = TheModule->global_end(); 2037 GI != GE;) { 2038 GlobalVariable *GV = GI++; 2039 UpgradeGlobalVariable(GV); 2040 } 2041 2042 // Force deallocation of memory for these vectors to favor the client that 2043 // want lazy deserialization. 2044 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 2045 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 2046 return std::error_code(); 2047 } 2048 2049 std::error_code BitcodeReader::ParseModule(bool Resume) { 2050 if (Resume) 2051 Stream.JumpToBit(NextUnreadBit); 2052 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2053 return Error("Invalid record"); 2054 2055 SmallVector<uint64_t, 64> Record; 2056 std::vector<std::string> SectionTable; 2057 std::vector<std::string> GCTable; 2058 2059 // Read all the records for this module. 2060 while (1) { 2061 BitstreamEntry Entry = Stream.advance(); 2062 2063 switch (Entry.Kind) { 2064 case BitstreamEntry::Error: 2065 return Error("Malformed block"); 2066 case BitstreamEntry::EndBlock: 2067 return GlobalCleanup(); 2068 2069 case BitstreamEntry::SubBlock: 2070 switch (Entry.ID) { 2071 default: // Skip unknown content. 2072 if (Stream.SkipBlock()) 2073 return Error("Invalid record"); 2074 break; 2075 case bitc::BLOCKINFO_BLOCK_ID: 2076 if (Stream.ReadBlockInfoBlock()) 2077 return Error("Malformed block"); 2078 break; 2079 case bitc::PARAMATTR_BLOCK_ID: 2080 if (std::error_code EC = ParseAttributeBlock()) 2081 return EC; 2082 break; 2083 case bitc::PARAMATTR_GROUP_BLOCK_ID: 2084 if (std::error_code EC = ParseAttributeGroupBlock()) 2085 return EC; 2086 break; 2087 case bitc::TYPE_BLOCK_ID_NEW: 2088 if (std::error_code EC = ParseTypeTable()) 2089 return EC; 2090 break; 2091 case bitc::VALUE_SYMTAB_BLOCK_ID: 2092 if (std::error_code EC = ParseValueSymbolTable()) 2093 return EC; 2094 SeenValueSymbolTable = true; 2095 break; 2096 case bitc::CONSTANTS_BLOCK_ID: 2097 if (std::error_code EC = ParseConstants()) 2098 return EC; 2099 if (std::error_code EC = ResolveGlobalAndAliasInits()) 2100 return EC; 2101 break; 2102 case bitc::METADATA_BLOCK_ID: 2103 if (std::error_code EC = ParseMetadata()) 2104 return EC; 2105 break; 2106 case bitc::FUNCTION_BLOCK_ID: 2107 // If this is the first function body we've seen, reverse the 2108 // FunctionsWithBodies list. 2109 if (!SeenFirstFunctionBody) { 2110 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 2111 if (std::error_code EC = GlobalCleanup()) 2112 return EC; 2113 SeenFirstFunctionBody = true; 2114 } 2115 2116 if (std::error_code EC = RememberAndSkipFunctionBody()) 2117 return EC; 2118 // For streaming bitcode, suspend parsing when we reach the function 2119 // bodies. Subsequent materialization calls will resume it when 2120 // necessary. For streaming, the function bodies must be at the end of 2121 // the bitcode. If the bitcode file is old, the symbol table will be 2122 // at the end instead and will not have been seen yet. In this case, 2123 // just finish the parse now. 2124 if (LazyStreamer && SeenValueSymbolTable) { 2125 NextUnreadBit = Stream.GetCurrentBitNo(); 2126 return std::error_code(); 2127 } 2128 break; 2129 case bitc::USELIST_BLOCK_ID: 2130 if (std::error_code EC = ParseUseLists()) 2131 return EC; 2132 break; 2133 } 2134 continue; 2135 2136 case BitstreamEntry::Record: 2137 // The interesting case. 2138 break; 2139 } 2140 2141 2142 // Read a record. 2143 switch (Stream.readRecord(Entry.ID, Record)) { 2144 default: break; // Default behavior, ignore unknown content. 2145 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 2146 if (Record.size() < 1) 2147 return Error("Invalid record"); 2148 // Only version #0 and #1 are supported so far. 2149 unsigned module_version = Record[0]; 2150 switch (module_version) { 2151 default: 2152 return Error("Invalid value"); 2153 case 0: 2154 UseRelativeIDs = false; 2155 break; 2156 case 1: 2157 UseRelativeIDs = true; 2158 break; 2159 } 2160 break; 2161 } 2162 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2163 std::string S; 2164 if (ConvertToString(Record, 0, S)) 2165 return Error("Invalid record"); 2166 TheModule->setTargetTriple(S); 2167 break; 2168 } 2169 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 2170 std::string S; 2171 if (ConvertToString(Record, 0, S)) 2172 return Error("Invalid record"); 2173 TheModule->setDataLayout(S); 2174 break; 2175 } 2176 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 2177 std::string S; 2178 if (ConvertToString(Record, 0, S)) 2179 return Error("Invalid record"); 2180 TheModule->setModuleInlineAsm(S); 2181 break; 2182 } 2183 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 2184 // FIXME: Remove in 4.0. 2185 std::string S; 2186 if (ConvertToString(Record, 0, S)) 2187 return Error("Invalid record"); 2188 // Ignore value. 2189 break; 2190 } 2191 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 2192 std::string S; 2193 if (ConvertToString(Record, 0, S)) 2194 return Error("Invalid record"); 2195 SectionTable.push_back(S); 2196 break; 2197 } 2198 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 2199 std::string S; 2200 if (ConvertToString(Record, 0, S)) 2201 return Error("Invalid record"); 2202 GCTable.push_back(S); 2203 break; 2204 } 2205 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name] 2206 if (Record.size() < 2) 2207 return Error("Invalid record"); 2208 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]); 2209 unsigned ComdatNameSize = Record[1]; 2210 std::string ComdatName; 2211 ComdatName.reserve(ComdatNameSize); 2212 for (unsigned i = 0; i != ComdatNameSize; ++i) 2213 ComdatName += (char)Record[2 + i]; 2214 Comdat *C = TheModule->getOrInsertComdat(ComdatName); 2215 C->setSelectionKind(SK); 2216 ComdatList.push_back(C); 2217 break; 2218 } 2219 // GLOBALVAR: [pointer type, isconst, initid, 2220 // linkage, alignment, section, visibility, threadlocal, 2221 // unnamed_addr, externally_initialized, dllstorageclass, 2222 // comdat] 2223 case bitc::MODULE_CODE_GLOBALVAR: { 2224 if (Record.size() < 6) 2225 return Error("Invalid record"); 2226 Type *Ty = getTypeByID(Record[0]); 2227 if (!Ty) 2228 return Error("Invalid record"); 2229 if (!Ty->isPointerTy()) 2230 return Error("Invalid type for value"); 2231 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 2232 Ty = cast<PointerType>(Ty)->getElementType(); 2233 2234 bool isConstant = Record[1]; 2235 uint64_t RawLinkage = Record[3]; 2236 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); 2237 unsigned Alignment = (1 << Record[4]) >> 1; 2238 std::string Section; 2239 if (Record[5]) { 2240 if (Record[5]-1 >= SectionTable.size()) 2241 return Error("Invalid ID"); 2242 Section = SectionTable[Record[5]-1]; 2243 } 2244 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 2245 // Local linkage must have default visibility. 2246 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage)) 2247 // FIXME: Change to an error if non-default in 4.0. 2248 Visibility = GetDecodedVisibility(Record[6]); 2249 2250 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 2251 if (Record.size() > 7) 2252 TLM = GetDecodedThreadLocalMode(Record[7]); 2253 2254 bool UnnamedAddr = false; 2255 if (Record.size() > 8) 2256 UnnamedAddr = Record[8]; 2257 2258 bool ExternallyInitialized = false; 2259 if (Record.size() > 9) 2260 ExternallyInitialized = Record[9]; 2261 2262 GlobalVariable *NewGV = 2263 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr, 2264 TLM, AddressSpace, ExternallyInitialized); 2265 NewGV->setAlignment(Alignment); 2266 if (!Section.empty()) 2267 NewGV->setSection(Section); 2268 NewGV->setVisibility(Visibility); 2269 NewGV->setUnnamedAddr(UnnamedAddr); 2270 2271 if (Record.size() > 10) 2272 NewGV->setDLLStorageClass(GetDecodedDLLStorageClass(Record[10])); 2273 else 2274 UpgradeDLLImportExportLinkage(NewGV, RawLinkage); 2275 2276 ValueList.push_back(NewGV); 2277 2278 // Remember which value to use for the global initializer. 2279 if (unsigned InitID = Record[2]) 2280 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 2281 2282 if (Record.size() > 11) { 2283 if (unsigned ComdatID = Record[11]) { 2284 assert(ComdatID <= ComdatList.size()); 2285 NewGV->setComdat(ComdatList[ComdatID - 1]); 2286 } 2287 } else if (hasImplicitComdat(RawLinkage)) { 2288 NewGV->setComdat(reinterpret_cast<Comdat *>(1)); 2289 } 2290 break; 2291 } 2292 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 2293 // alignment, section, visibility, gc, unnamed_addr, 2294 // prologuedata, dllstorageclass, comdat, prefixdata] 2295 case bitc::MODULE_CODE_FUNCTION: { 2296 if (Record.size() < 8) 2297 return Error("Invalid record"); 2298 Type *Ty = getTypeByID(Record[0]); 2299 if (!Ty) 2300 return Error("Invalid record"); 2301 if (!Ty->isPointerTy()) 2302 return Error("Invalid type for value"); 2303 FunctionType *FTy = 2304 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 2305 if (!FTy) 2306 return Error("Invalid type for value"); 2307 2308 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 2309 "", TheModule); 2310 2311 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 2312 bool isProto = Record[2]; 2313 uint64_t RawLinkage = Record[3]; 2314 Func->setLinkage(getDecodedLinkage(RawLinkage)); 2315 Func->setAttributes(getAttributes(Record[4])); 2316 2317 Func->setAlignment((1 << Record[5]) >> 1); 2318 if (Record[6]) { 2319 if (Record[6]-1 >= SectionTable.size()) 2320 return Error("Invalid ID"); 2321 Func->setSection(SectionTable[Record[6]-1]); 2322 } 2323 // Local linkage must have default visibility. 2324 if (!Func->hasLocalLinkage()) 2325 // FIXME: Change to an error if non-default in 4.0. 2326 Func->setVisibility(GetDecodedVisibility(Record[7])); 2327 if (Record.size() > 8 && Record[8]) { 2328 if (Record[8]-1 > GCTable.size()) 2329 return Error("Invalid ID"); 2330 Func->setGC(GCTable[Record[8]-1].c_str()); 2331 } 2332 bool UnnamedAddr = false; 2333 if (Record.size() > 9) 2334 UnnamedAddr = Record[9]; 2335 Func->setUnnamedAddr(UnnamedAddr); 2336 if (Record.size() > 10 && Record[10] != 0) 2337 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1)); 2338 2339 if (Record.size() > 11) 2340 Func->setDLLStorageClass(GetDecodedDLLStorageClass(Record[11])); 2341 else 2342 UpgradeDLLImportExportLinkage(Func, RawLinkage); 2343 2344 if (Record.size() > 12) { 2345 if (unsigned ComdatID = Record[12]) { 2346 assert(ComdatID <= ComdatList.size()); 2347 Func->setComdat(ComdatList[ComdatID - 1]); 2348 } 2349 } else if (hasImplicitComdat(RawLinkage)) { 2350 Func->setComdat(reinterpret_cast<Comdat *>(1)); 2351 } 2352 2353 if (Record.size() > 13 && Record[13] != 0) 2354 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1)); 2355 2356 ValueList.push_back(Func); 2357 2358 // If this is a function with a body, remember the prototype we are 2359 // creating now, so that we can match up the body with them later. 2360 if (!isProto) { 2361 Func->setIsMaterializable(true); 2362 FunctionsWithBodies.push_back(Func); 2363 if (LazyStreamer) 2364 DeferredFunctionInfo[Func] = 0; 2365 } 2366 break; 2367 } 2368 // ALIAS: [alias type, aliasee val#, linkage] 2369 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass] 2370 case bitc::MODULE_CODE_ALIAS: { 2371 if (Record.size() < 3) 2372 return Error("Invalid record"); 2373 Type *Ty = getTypeByID(Record[0]); 2374 if (!Ty) 2375 return Error("Invalid record"); 2376 auto *PTy = dyn_cast<PointerType>(Ty); 2377 if (!PTy) 2378 return Error("Invalid type for value"); 2379 2380 auto *NewGA = 2381 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 2382 getDecodedLinkage(Record[2]), "", TheModule); 2383 // Old bitcode files didn't have visibility field. 2384 // Local linkage must have default visibility. 2385 if (Record.size() > 3 && !NewGA->hasLocalLinkage()) 2386 // FIXME: Change to an error if non-default in 4.0. 2387 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 2388 if (Record.size() > 4) 2389 NewGA->setDLLStorageClass(GetDecodedDLLStorageClass(Record[4])); 2390 else 2391 UpgradeDLLImportExportLinkage(NewGA, Record[2]); 2392 if (Record.size() > 5) 2393 NewGA->setThreadLocalMode(GetDecodedThreadLocalMode(Record[5])); 2394 if (Record.size() > 6) 2395 NewGA->setUnnamedAddr(Record[6]); 2396 ValueList.push_back(NewGA); 2397 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 2398 break; 2399 } 2400 /// MODULE_CODE_PURGEVALS: [numvals] 2401 case bitc::MODULE_CODE_PURGEVALS: 2402 // Trim down the value list to the specified size. 2403 if (Record.size() < 1 || Record[0] > ValueList.size()) 2404 return Error("Invalid record"); 2405 ValueList.shrinkTo(Record[0]); 2406 break; 2407 } 2408 Record.clear(); 2409 } 2410 } 2411 2412 std::error_code BitcodeReader::ParseBitcodeInto(Module *M) { 2413 TheModule = nullptr; 2414 2415 if (std::error_code EC = InitStream()) 2416 return EC; 2417 2418 // Sniff for the signature. 2419 if (Stream.Read(8) != 'B' || 2420 Stream.Read(8) != 'C' || 2421 Stream.Read(4) != 0x0 || 2422 Stream.Read(4) != 0xC || 2423 Stream.Read(4) != 0xE || 2424 Stream.Read(4) != 0xD) 2425 return Error("Invalid bitcode signature"); 2426 2427 // We expect a number of well-defined blocks, though we don't necessarily 2428 // need to understand them all. 2429 while (1) { 2430 if (Stream.AtEndOfStream()) 2431 return std::error_code(); 2432 2433 BitstreamEntry Entry = 2434 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 2435 2436 switch (Entry.Kind) { 2437 case BitstreamEntry::Error: 2438 return Error("Malformed block"); 2439 case BitstreamEntry::EndBlock: 2440 return std::error_code(); 2441 2442 case BitstreamEntry::SubBlock: 2443 switch (Entry.ID) { 2444 case bitc::BLOCKINFO_BLOCK_ID: 2445 if (Stream.ReadBlockInfoBlock()) 2446 return Error("Malformed block"); 2447 break; 2448 case bitc::MODULE_BLOCK_ID: 2449 // Reject multiple MODULE_BLOCK's in a single bitstream. 2450 if (TheModule) 2451 return Error("Invalid multiple blocks"); 2452 TheModule = M; 2453 if (std::error_code EC = ParseModule(false)) 2454 return EC; 2455 if (LazyStreamer) 2456 return std::error_code(); 2457 break; 2458 default: 2459 if (Stream.SkipBlock()) 2460 return Error("Invalid record"); 2461 break; 2462 } 2463 continue; 2464 case BitstreamEntry::Record: 2465 // There should be no records in the top-level of blocks. 2466 2467 // The ranlib in Xcode 4 will align archive members by appending newlines 2468 // to the end of them. If this file size is a multiple of 4 but not 8, we 2469 // have to read and ignore these final 4 bytes :-( 2470 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 && 2471 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 2472 Stream.AtEndOfStream()) 2473 return std::error_code(); 2474 2475 return Error("Invalid record"); 2476 } 2477 } 2478 } 2479 2480 ErrorOr<std::string> BitcodeReader::parseModuleTriple() { 2481 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 2482 return Error("Invalid record"); 2483 2484 SmallVector<uint64_t, 64> Record; 2485 2486 std::string Triple; 2487 // Read all the records for this module. 2488 while (1) { 2489 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2490 2491 switch (Entry.Kind) { 2492 case BitstreamEntry::SubBlock: // Handled for us already. 2493 case BitstreamEntry::Error: 2494 return Error("Malformed block"); 2495 case BitstreamEntry::EndBlock: 2496 return Triple; 2497 case BitstreamEntry::Record: 2498 // The interesting case. 2499 break; 2500 } 2501 2502 // Read a record. 2503 switch (Stream.readRecord(Entry.ID, Record)) { 2504 default: break; // Default behavior, ignore unknown content. 2505 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 2506 std::string S; 2507 if (ConvertToString(Record, 0, S)) 2508 return Error("Invalid record"); 2509 Triple = S; 2510 break; 2511 } 2512 } 2513 Record.clear(); 2514 } 2515 llvm_unreachable("Exit infinite loop"); 2516 } 2517 2518 ErrorOr<std::string> BitcodeReader::parseTriple() { 2519 if (std::error_code EC = InitStream()) 2520 return EC; 2521 2522 // Sniff for the signature. 2523 if (Stream.Read(8) != 'B' || 2524 Stream.Read(8) != 'C' || 2525 Stream.Read(4) != 0x0 || 2526 Stream.Read(4) != 0xC || 2527 Stream.Read(4) != 0xE || 2528 Stream.Read(4) != 0xD) 2529 return Error("Invalid bitcode signature"); 2530 2531 // We expect a number of well-defined blocks, though we don't necessarily 2532 // need to understand them all. 2533 while (1) { 2534 BitstreamEntry Entry = Stream.advance(); 2535 2536 switch (Entry.Kind) { 2537 case BitstreamEntry::Error: 2538 return Error("Malformed block"); 2539 case BitstreamEntry::EndBlock: 2540 return std::error_code(); 2541 2542 case BitstreamEntry::SubBlock: 2543 if (Entry.ID == bitc::MODULE_BLOCK_ID) 2544 return parseModuleTriple(); 2545 2546 // Ignore other sub-blocks. 2547 if (Stream.SkipBlock()) 2548 return Error("Malformed block"); 2549 continue; 2550 2551 case BitstreamEntry::Record: 2552 Stream.skipRecord(Entry.ID); 2553 continue; 2554 } 2555 } 2556 } 2557 2558 /// ParseMetadataAttachment - Parse metadata attachments. 2559 std::error_code BitcodeReader::ParseMetadataAttachment() { 2560 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 2561 return Error("Invalid record"); 2562 2563 SmallVector<uint64_t, 64> Record; 2564 while (1) { 2565 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 2566 2567 switch (Entry.Kind) { 2568 case BitstreamEntry::SubBlock: // Handled for us already. 2569 case BitstreamEntry::Error: 2570 return Error("Malformed block"); 2571 case BitstreamEntry::EndBlock: 2572 return std::error_code(); 2573 case BitstreamEntry::Record: 2574 // The interesting case. 2575 break; 2576 } 2577 2578 // Read a metadata attachment record. 2579 Record.clear(); 2580 switch (Stream.readRecord(Entry.ID, Record)) { 2581 default: // Default behavior: ignore. 2582 break; 2583 case bitc::METADATA_ATTACHMENT: { 2584 unsigned RecordLength = Record.size(); 2585 if (Record.empty() || (RecordLength - 1) % 2 == 1) 2586 return Error("Invalid record"); 2587 Instruction *Inst = InstructionList[Record[0]]; 2588 for (unsigned i = 1; i != RecordLength; i = i+2) { 2589 unsigned Kind = Record[i]; 2590 DenseMap<unsigned, unsigned>::iterator I = 2591 MDKindMap.find(Kind); 2592 if (I == MDKindMap.end()) 2593 return Error("Invalid ID"); 2594 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]); 2595 if (isa<LocalAsMetadata>(Node)) 2596 // Drop the attachment. This used to be legal, but there's no 2597 // upgrade path. 2598 break; 2599 Inst->setMetadata(I->second, cast<MDNode>(Node)); 2600 if (I->second == LLVMContext::MD_tbaa) 2601 InstsWithTBAATag.push_back(Inst); 2602 } 2603 break; 2604 } 2605 } 2606 } 2607 } 2608 2609 /// ParseFunctionBody - Lazily parse the specified function body block. 2610 std::error_code BitcodeReader::ParseFunctionBody(Function *F) { 2611 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 2612 return Error("Invalid record"); 2613 2614 InstructionList.clear(); 2615 unsigned ModuleValueListSize = ValueList.size(); 2616 unsigned ModuleMDValueListSize = MDValueList.size(); 2617 2618 // Add all the function arguments to the value table. 2619 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 2620 ValueList.push_back(I); 2621 2622 unsigned NextValueNo = ValueList.size(); 2623 BasicBlock *CurBB = nullptr; 2624 unsigned CurBBNo = 0; 2625 2626 DebugLoc LastLoc; 2627 auto getLastInstruction = [&]() -> Instruction * { 2628 if (CurBB && !CurBB->empty()) 2629 return &CurBB->back(); 2630 else if (CurBBNo && FunctionBBs[CurBBNo - 1] && 2631 !FunctionBBs[CurBBNo - 1]->empty()) 2632 return &FunctionBBs[CurBBNo - 1]->back(); 2633 return nullptr; 2634 }; 2635 2636 // Read all the records. 2637 SmallVector<uint64_t, 64> Record; 2638 while (1) { 2639 BitstreamEntry Entry = Stream.advance(); 2640 2641 switch (Entry.Kind) { 2642 case BitstreamEntry::Error: 2643 return Error("Malformed block"); 2644 case BitstreamEntry::EndBlock: 2645 goto OutOfRecordLoop; 2646 2647 case BitstreamEntry::SubBlock: 2648 switch (Entry.ID) { 2649 default: // Skip unknown content. 2650 if (Stream.SkipBlock()) 2651 return Error("Invalid record"); 2652 break; 2653 case bitc::CONSTANTS_BLOCK_ID: 2654 if (std::error_code EC = ParseConstants()) 2655 return EC; 2656 NextValueNo = ValueList.size(); 2657 break; 2658 case bitc::VALUE_SYMTAB_BLOCK_ID: 2659 if (std::error_code EC = ParseValueSymbolTable()) 2660 return EC; 2661 break; 2662 case bitc::METADATA_ATTACHMENT_ID: 2663 if (std::error_code EC = ParseMetadataAttachment()) 2664 return EC; 2665 break; 2666 case bitc::METADATA_BLOCK_ID: 2667 if (std::error_code EC = ParseMetadata()) 2668 return EC; 2669 break; 2670 case bitc::USELIST_BLOCK_ID: 2671 if (std::error_code EC = ParseUseLists()) 2672 return EC; 2673 break; 2674 } 2675 continue; 2676 2677 case BitstreamEntry::Record: 2678 // The interesting case. 2679 break; 2680 } 2681 2682 // Read a record. 2683 Record.clear(); 2684 Instruction *I = nullptr; 2685 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 2686 switch (BitCode) { 2687 default: // Default behavior: reject 2688 return Error("Invalid value"); 2689 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] 2690 if (Record.size() < 1 || Record[0] == 0) 2691 return Error("Invalid record"); 2692 // Create all the basic blocks for the function. 2693 FunctionBBs.resize(Record[0]); 2694 2695 // See if anything took the address of blocks in this function. 2696 auto BBFRI = BasicBlockFwdRefs.find(F); 2697 if (BBFRI == BasicBlockFwdRefs.end()) { 2698 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 2699 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 2700 } else { 2701 auto &BBRefs = BBFRI->second; 2702 // Check for invalid basic block references. 2703 if (BBRefs.size() > FunctionBBs.size()) 2704 return Error("Invalid ID"); 2705 assert(!BBRefs.empty() && "Unexpected empty array"); 2706 assert(!BBRefs.front() && "Invalid reference to entry block"); 2707 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E; 2708 ++I) 2709 if (I < RE && BBRefs[I]) { 2710 BBRefs[I]->insertInto(F); 2711 FunctionBBs[I] = BBRefs[I]; 2712 } else { 2713 FunctionBBs[I] = BasicBlock::Create(Context, "", F); 2714 } 2715 2716 // Erase from the table. 2717 BasicBlockFwdRefs.erase(BBFRI); 2718 } 2719 2720 CurBB = FunctionBBs[0]; 2721 continue; 2722 } 2723 2724 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 2725 // This record indicates that the last instruction is at the same 2726 // location as the previous instruction with a location. 2727 I = getLastInstruction(); 2728 2729 if (!I) 2730 return Error("Invalid record"); 2731 I->setDebugLoc(LastLoc); 2732 I = nullptr; 2733 continue; 2734 2735 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 2736 I = getLastInstruction(); 2737 if (!I || Record.size() < 4) 2738 return Error("Invalid record"); 2739 2740 unsigned Line = Record[0], Col = Record[1]; 2741 unsigned ScopeID = Record[2], IAID = Record[3]; 2742 2743 MDNode *Scope = nullptr, *IA = nullptr; 2744 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 2745 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 2746 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 2747 I->setDebugLoc(LastLoc); 2748 I = nullptr; 2749 continue; 2750 } 2751 2752 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 2753 unsigned OpNum = 0; 2754 Value *LHS, *RHS; 2755 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2756 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2757 OpNum+1 > Record.size()) 2758 return Error("Invalid record"); 2759 2760 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 2761 if (Opc == -1) 2762 return Error("Invalid record"); 2763 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 2764 InstructionList.push_back(I); 2765 if (OpNum < Record.size()) { 2766 if (Opc == Instruction::Add || 2767 Opc == Instruction::Sub || 2768 Opc == Instruction::Mul || 2769 Opc == Instruction::Shl) { 2770 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 2771 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 2772 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 2773 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 2774 } else if (Opc == Instruction::SDiv || 2775 Opc == Instruction::UDiv || 2776 Opc == Instruction::LShr || 2777 Opc == Instruction::AShr) { 2778 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 2779 cast<BinaryOperator>(I)->setIsExact(true); 2780 } else if (isa<FPMathOperator>(I)) { 2781 FastMathFlags FMF; 2782 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra)) 2783 FMF.setUnsafeAlgebra(); 2784 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs)) 2785 FMF.setNoNaNs(); 2786 if (0 != (Record[OpNum] & FastMathFlags::NoInfs)) 2787 FMF.setNoInfs(); 2788 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros)) 2789 FMF.setNoSignedZeros(); 2790 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal)) 2791 FMF.setAllowReciprocal(); 2792 if (FMF.any()) 2793 I->setFastMathFlags(FMF); 2794 } 2795 2796 } 2797 break; 2798 } 2799 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 2800 unsigned OpNum = 0; 2801 Value *Op; 2802 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 2803 OpNum+2 != Record.size()) 2804 return Error("Invalid record"); 2805 2806 Type *ResTy = getTypeByID(Record[OpNum]); 2807 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 2808 if (Opc == -1 || !ResTy) 2809 return Error("Invalid record"); 2810 Instruction *Temp = nullptr; 2811 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) { 2812 if (Temp) { 2813 InstructionList.push_back(Temp); 2814 CurBB->getInstList().push_back(Temp); 2815 } 2816 } else { 2817 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 2818 } 2819 InstructionList.push_back(I); 2820 break; 2821 } 2822 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 2823 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 2824 unsigned OpNum = 0; 2825 Value *BasePtr; 2826 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 2827 return Error("Invalid record"); 2828 2829 SmallVector<Value*, 16> GEPIdx; 2830 while (OpNum != Record.size()) { 2831 Value *Op; 2832 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 2833 return Error("Invalid record"); 2834 GEPIdx.push_back(Op); 2835 } 2836 2837 I = GetElementPtrInst::Create(BasePtr, GEPIdx); 2838 InstructionList.push_back(I); 2839 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 2840 cast<GetElementPtrInst>(I)->setIsInBounds(true); 2841 break; 2842 } 2843 2844 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 2845 // EXTRACTVAL: [opty, opval, n x indices] 2846 unsigned OpNum = 0; 2847 Value *Agg; 2848 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2849 return Error("Invalid record"); 2850 2851 SmallVector<unsigned, 4> EXTRACTVALIdx; 2852 for (unsigned RecSize = Record.size(); 2853 OpNum != RecSize; ++OpNum) { 2854 uint64_t Index = Record[OpNum]; 2855 if ((unsigned)Index != Index) 2856 return Error("Invalid value"); 2857 EXTRACTVALIdx.push_back((unsigned)Index); 2858 } 2859 2860 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 2861 InstructionList.push_back(I); 2862 break; 2863 } 2864 2865 case bitc::FUNC_CODE_INST_INSERTVAL: { 2866 // INSERTVAL: [opty, opval, opty, opval, n x indices] 2867 unsigned OpNum = 0; 2868 Value *Agg; 2869 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 2870 return Error("Invalid record"); 2871 Value *Val; 2872 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 2873 return Error("Invalid record"); 2874 2875 SmallVector<unsigned, 4> INSERTVALIdx; 2876 for (unsigned RecSize = Record.size(); 2877 OpNum != RecSize; ++OpNum) { 2878 uint64_t Index = Record[OpNum]; 2879 if ((unsigned)Index != Index) 2880 return Error("Invalid value"); 2881 INSERTVALIdx.push_back((unsigned)Index); 2882 } 2883 2884 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 2885 InstructionList.push_back(I); 2886 break; 2887 } 2888 2889 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 2890 // obsolete form of select 2891 // handles select i1 ... in old bitcode 2892 unsigned OpNum = 0; 2893 Value *TrueVal, *FalseVal, *Cond; 2894 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2895 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2896 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 2897 return Error("Invalid record"); 2898 2899 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2900 InstructionList.push_back(I); 2901 break; 2902 } 2903 2904 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 2905 // new form of select 2906 // handles select i1 or select [N x i1] 2907 unsigned OpNum = 0; 2908 Value *TrueVal, *FalseVal, *Cond; 2909 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 2910 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 2911 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 2912 return Error("Invalid record"); 2913 2914 // select condition can be either i1 or [N x i1] 2915 if (VectorType* vector_type = 2916 dyn_cast<VectorType>(Cond->getType())) { 2917 // expect <n x i1> 2918 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 2919 return Error("Invalid type for value"); 2920 } else { 2921 // expect i1 2922 if (Cond->getType() != Type::getInt1Ty(Context)) 2923 return Error("Invalid type for value"); 2924 } 2925 2926 I = SelectInst::Create(Cond, TrueVal, FalseVal); 2927 InstructionList.push_back(I); 2928 break; 2929 } 2930 2931 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 2932 unsigned OpNum = 0; 2933 Value *Vec, *Idx; 2934 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2935 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 2936 return Error("Invalid record"); 2937 I = ExtractElementInst::Create(Vec, Idx); 2938 InstructionList.push_back(I); 2939 break; 2940 } 2941 2942 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 2943 unsigned OpNum = 0; 2944 Value *Vec, *Elt, *Idx; 2945 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 2946 popValue(Record, OpNum, NextValueNo, 2947 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 2948 getValueTypePair(Record, OpNum, NextValueNo, Idx)) 2949 return Error("Invalid record"); 2950 I = InsertElementInst::Create(Vec, Elt, Idx); 2951 InstructionList.push_back(I); 2952 break; 2953 } 2954 2955 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 2956 unsigned OpNum = 0; 2957 Value *Vec1, *Vec2, *Mask; 2958 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 2959 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 2960 return Error("Invalid record"); 2961 2962 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 2963 return Error("Invalid record"); 2964 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 2965 InstructionList.push_back(I); 2966 break; 2967 } 2968 2969 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 2970 // Old form of ICmp/FCmp returning bool 2971 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 2972 // both legal on vectors but had different behaviour. 2973 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 2974 // FCmp/ICmp returning bool or vector of bool 2975 2976 unsigned OpNum = 0; 2977 Value *LHS, *RHS; 2978 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 2979 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 2980 OpNum+1 != Record.size()) 2981 return Error("Invalid record"); 2982 2983 if (LHS->getType()->isFPOrFPVectorTy()) 2984 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 2985 else 2986 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 2987 InstructionList.push_back(I); 2988 break; 2989 } 2990 2991 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 2992 { 2993 unsigned Size = Record.size(); 2994 if (Size == 0) { 2995 I = ReturnInst::Create(Context); 2996 InstructionList.push_back(I); 2997 break; 2998 } 2999 3000 unsigned OpNum = 0; 3001 Value *Op = nullptr; 3002 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3003 return Error("Invalid record"); 3004 if (OpNum != Record.size()) 3005 return Error("Invalid record"); 3006 3007 I = ReturnInst::Create(Context, Op); 3008 InstructionList.push_back(I); 3009 break; 3010 } 3011 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 3012 if (Record.size() != 1 && Record.size() != 3) 3013 return Error("Invalid record"); 3014 BasicBlock *TrueDest = getBasicBlock(Record[0]); 3015 if (!TrueDest) 3016 return Error("Invalid record"); 3017 3018 if (Record.size() == 1) { 3019 I = BranchInst::Create(TrueDest); 3020 InstructionList.push_back(I); 3021 } 3022 else { 3023 BasicBlock *FalseDest = getBasicBlock(Record[1]); 3024 Value *Cond = getValue(Record, 2, NextValueNo, 3025 Type::getInt1Ty(Context)); 3026 if (!FalseDest || !Cond) 3027 return Error("Invalid record"); 3028 I = BranchInst::Create(TrueDest, FalseDest, Cond); 3029 InstructionList.push_back(I); 3030 } 3031 break; 3032 } 3033 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 3034 // Check magic 3035 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 3036 // "New" SwitchInst format with case ranges. The changes to write this 3037 // format were reverted but we still recognize bitcode that uses it. 3038 // Hopefully someday we will have support for case ranges and can use 3039 // this format again. 3040 3041 Type *OpTy = getTypeByID(Record[1]); 3042 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 3043 3044 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 3045 BasicBlock *Default = getBasicBlock(Record[3]); 3046 if (!OpTy || !Cond || !Default) 3047 return Error("Invalid record"); 3048 3049 unsigned NumCases = Record[4]; 3050 3051 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 3052 InstructionList.push_back(SI); 3053 3054 unsigned CurIdx = 5; 3055 for (unsigned i = 0; i != NumCases; ++i) { 3056 SmallVector<ConstantInt*, 1> CaseVals; 3057 unsigned NumItems = Record[CurIdx++]; 3058 for (unsigned ci = 0; ci != NumItems; ++ci) { 3059 bool isSingleNumber = Record[CurIdx++]; 3060 3061 APInt Low; 3062 unsigned ActiveWords = 1; 3063 if (ValueBitWidth > 64) 3064 ActiveWords = Record[CurIdx++]; 3065 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 3066 ValueBitWidth); 3067 CurIdx += ActiveWords; 3068 3069 if (!isSingleNumber) { 3070 ActiveWords = 1; 3071 if (ValueBitWidth > 64) 3072 ActiveWords = Record[CurIdx++]; 3073 APInt High = 3074 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 3075 ValueBitWidth); 3076 CurIdx += ActiveWords; 3077 3078 // FIXME: It is not clear whether values in the range should be 3079 // compared as signed or unsigned values. The partially 3080 // implemented changes that used this format in the past used 3081 // unsigned comparisons. 3082 for ( ; Low.ule(High); ++Low) 3083 CaseVals.push_back(ConstantInt::get(Context, Low)); 3084 } else 3085 CaseVals.push_back(ConstantInt::get(Context, Low)); 3086 } 3087 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 3088 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(), 3089 cve = CaseVals.end(); cvi != cve; ++cvi) 3090 SI->addCase(*cvi, DestBB); 3091 } 3092 I = SI; 3093 break; 3094 } 3095 3096 // Old SwitchInst format without case ranges. 3097 3098 if (Record.size() < 3 || (Record.size() & 1) == 0) 3099 return Error("Invalid record"); 3100 Type *OpTy = getTypeByID(Record[0]); 3101 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 3102 BasicBlock *Default = getBasicBlock(Record[2]); 3103 if (!OpTy || !Cond || !Default) 3104 return Error("Invalid record"); 3105 unsigned NumCases = (Record.size()-3)/2; 3106 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 3107 InstructionList.push_back(SI); 3108 for (unsigned i = 0, e = NumCases; i != e; ++i) { 3109 ConstantInt *CaseVal = 3110 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 3111 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 3112 if (!CaseVal || !DestBB) { 3113 delete SI; 3114 return Error("Invalid record"); 3115 } 3116 SI->addCase(CaseVal, DestBB); 3117 } 3118 I = SI; 3119 break; 3120 } 3121 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 3122 if (Record.size() < 2) 3123 return Error("Invalid record"); 3124 Type *OpTy = getTypeByID(Record[0]); 3125 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 3126 if (!OpTy || !Address) 3127 return Error("Invalid record"); 3128 unsigned NumDests = Record.size()-2; 3129 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 3130 InstructionList.push_back(IBI); 3131 for (unsigned i = 0, e = NumDests; i != e; ++i) { 3132 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 3133 IBI->addDestination(DestBB); 3134 } else { 3135 delete IBI; 3136 return Error("Invalid record"); 3137 } 3138 } 3139 I = IBI; 3140 break; 3141 } 3142 3143 case bitc::FUNC_CODE_INST_INVOKE: { 3144 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 3145 if (Record.size() < 4) 3146 return Error("Invalid record"); 3147 AttributeSet PAL = getAttributes(Record[0]); 3148 unsigned CCInfo = Record[1]; 3149 BasicBlock *NormalBB = getBasicBlock(Record[2]); 3150 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 3151 3152 unsigned OpNum = 4; 3153 Value *Callee; 3154 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 3155 return Error("Invalid record"); 3156 3157 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 3158 FunctionType *FTy = !CalleeTy ? nullptr : 3159 dyn_cast<FunctionType>(CalleeTy->getElementType()); 3160 3161 // Check that the right number of fixed parameters are here. 3162 if (!FTy || !NormalBB || !UnwindBB || 3163 Record.size() < OpNum+FTy->getNumParams()) 3164 return Error("Invalid record"); 3165 3166 SmallVector<Value*, 16> Ops; 3167 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3168 Ops.push_back(getValue(Record, OpNum, NextValueNo, 3169 FTy->getParamType(i))); 3170 if (!Ops.back()) 3171 return Error("Invalid record"); 3172 } 3173 3174 if (!FTy->isVarArg()) { 3175 if (Record.size() != OpNum) 3176 return Error("Invalid record"); 3177 } else { 3178 // Read type/value pairs for varargs params. 3179 while (OpNum != Record.size()) { 3180 Value *Op; 3181 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3182 return Error("Invalid record"); 3183 Ops.push_back(Op); 3184 } 3185 } 3186 3187 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 3188 InstructionList.push_back(I); 3189 cast<InvokeInst>(I)->setCallingConv( 3190 static_cast<CallingConv::ID>(CCInfo)); 3191 cast<InvokeInst>(I)->setAttributes(PAL); 3192 break; 3193 } 3194 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 3195 unsigned Idx = 0; 3196 Value *Val = nullptr; 3197 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 3198 return Error("Invalid record"); 3199 I = ResumeInst::Create(Val); 3200 InstructionList.push_back(I); 3201 break; 3202 } 3203 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 3204 I = new UnreachableInst(Context); 3205 InstructionList.push_back(I); 3206 break; 3207 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 3208 if (Record.size() < 1 || ((Record.size()-1)&1)) 3209 return Error("Invalid record"); 3210 Type *Ty = getTypeByID(Record[0]); 3211 if (!Ty) 3212 return Error("Invalid record"); 3213 3214 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 3215 InstructionList.push_back(PN); 3216 3217 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 3218 Value *V; 3219 // With the new function encoding, it is possible that operands have 3220 // negative IDs (for forward references). Use a signed VBR 3221 // representation to keep the encoding small. 3222 if (UseRelativeIDs) 3223 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 3224 else 3225 V = getValue(Record, 1+i, NextValueNo, Ty); 3226 BasicBlock *BB = getBasicBlock(Record[2+i]); 3227 if (!V || !BB) 3228 return Error("Invalid record"); 3229 PN->addIncoming(V, BB); 3230 } 3231 I = PN; 3232 break; 3233 } 3234 3235 case bitc::FUNC_CODE_INST_LANDINGPAD: { 3236 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 3237 unsigned Idx = 0; 3238 if (Record.size() < 4) 3239 return Error("Invalid record"); 3240 Type *Ty = getTypeByID(Record[Idx++]); 3241 if (!Ty) 3242 return Error("Invalid record"); 3243 Value *PersFn = nullptr; 3244 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 3245 return Error("Invalid record"); 3246 3247 bool IsCleanup = !!Record[Idx++]; 3248 unsigned NumClauses = Record[Idx++]; 3249 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses); 3250 LP->setCleanup(IsCleanup); 3251 for (unsigned J = 0; J != NumClauses; ++J) { 3252 LandingPadInst::ClauseType CT = 3253 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 3254 Value *Val; 3255 3256 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 3257 delete LP; 3258 return Error("Invalid record"); 3259 } 3260 3261 assert((CT != LandingPadInst::Catch || 3262 !isa<ArrayType>(Val->getType())) && 3263 "Catch clause has a invalid type!"); 3264 assert((CT != LandingPadInst::Filter || 3265 isa<ArrayType>(Val->getType())) && 3266 "Filter clause has invalid type!"); 3267 LP->addClause(cast<Constant>(Val)); 3268 } 3269 3270 I = LP; 3271 InstructionList.push_back(I); 3272 break; 3273 } 3274 3275 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 3276 if (Record.size() != 4) 3277 return Error("Invalid record"); 3278 PointerType *Ty = 3279 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 3280 Type *OpTy = getTypeByID(Record[1]); 3281 Value *Size = getFnValueByID(Record[2], OpTy); 3282 unsigned AlignRecord = Record[3]; 3283 bool InAlloca = AlignRecord & (1 << 5); 3284 unsigned Align = AlignRecord & ((1 << 5) - 1); 3285 if (!Ty || !Size) 3286 return Error("Invalid record"); 3287 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 3288 AI->setUsedWithInAlloca(InAlloca); 3289 I = AI; 3290 InstructionList.push_back(I); 3291 break; 3292 } 3293 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 3294 unsigned OpNum = 0; 3295 Value *Op; 3296 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3297 OpNum+2 != Record.size()) 3298 return Error("Invalid record"); 3299 3300 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3301 InstructionList.push_back(I); 3302 break; 3303 } 3304 case bitc::FUNC_CODE_INST_LOADATOMIC: { 3305 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 3306 unsigned OpNum = 0; 3307 Value *Op; 3308 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 3309 OpNum+4 != Record.size()) 3310 return Error("Invalid record"); 3311 3312 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3313 if (Ordering == NotAtomic || Ordering == Release || 3314 Ordering == AcquireRelease) 3315 return Error("Invalid record"); 3316 if (Ordering != NotAtomic && Record[OpNum] == 0) 3317 return Error("Invalid record"); 3318 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3319 3320 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1, 3321 Ordering, SynchScope); 3322 InstructionList.push_back(I); 3323 break; 3324 } 3325 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol] 3326 unsigned OpNum = 0; 3327 Value *Val, *Ptr; 3328 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3329 popValue(Record, OpNum, NextValueNo, 3330 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3331 OpNum+2 != Record.size()) 3332 return Error("Invalid record"); 3333 3334 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 3335 InstructionList.push_back(I); 3336 break; 3337 } 3338 case bitc::FUNC_CODE_INST_STOREATOMIC: { 3339 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 3340 unsigned OpNum = 0; 3341 Value *Val, *Ptr; 3342 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3343 popValue(Record, OpNum, NextValueNo, 3344 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3345 OpNum+4 != Record.size()) 3346 return Error("Invalid record"); 3347 3348 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3349 if (Ordering == NotAtomic || Ordering == Acquire || 3350 Ordering == AcquireRelease) 3351 return Error("Invalid record"); 3352 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3353 if (Ordering != NotAtomic && Record[OpNum] == 0) 3354 return Error("Invalid record"); 3355 3356 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1, 3357 Ordering, SynchScope); 3358 InstructionList.push_back(I); 3359 break; 3360 } 3361 case bitc::FUNC_CODE_INST_CMPXCHG: { 3362 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope, 3363 // failureordering?, isweak?] 3364 unsigned OpNum = 0; 3365 Value *Ptr, *Cmp, *New; 3366 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3367 popValue(Record, OpNum, NextValueNo, 3368 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) || 3369 popValue(Record, OpNum, NextValueNo, 3370 cast<PointerType>(Ptr->getType())->getElementType(), New) || 3371 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5)) 3372 return Error("Invalid record"); 3373 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]); 3374 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered) 3375 return Error("Invalid record"); 3376 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]); 3377 3378 AtomicOrdering FailureOrdering; 3379 if (Record.size() < 7) 3380 FailureOrdering = 3381 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering); 3382 else 3383 FailureOrdering = GetDecodedOrdering(Record[OpNum+3]); 3384 3385 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering, 3386 SynchScope); 3387 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 3388 3389 if (Record.size() < 8) { 3390 // Before weak cmpxchgs existed, the instruction simply returned the 3391 // value loaded from memory, so bitcode files from that era will be 3392 // expecting the first component of a modern cmpxchg. 3393 CurBB->getInstList().push_back(I); 3394 I = ExtractValueInst::Create(I, 0); 3395 } else { 3396 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]); 3397 } 3398 3399 InstructionList.push_back(I); 3400 break; 3401 } 3402 case bitc::FUNC_CODE_INST_ATOMICRMW: { 3403 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 3404 unsigned OpNum = 0; 3405 Value *Ptr, *Val; 3406 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 3407 popValue(Record, OpNum, NextValueNo, 3408 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 3409 OpNum+4 != Record.size()) 3410 return Error("Invalid record"); 3411 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 3412 if (Operation < AtomicRMWInst::FIRST_BINOP || 3413 Operation > AtomicRMWInst::LAST_BINOP) 3414 return Error("Invalid record"); 3415 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 3416 if (Ordering == NotAtomic || Ordering == Unordered) 3417 return Error("Invalid record"); 3418 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 3419 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 3420 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 3421 InstructionList.push_back(I); 3422 break; 3423 } 3424 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 3425 if (2 != Record.size()) 3426 return Error("Invalid record"); 3427 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 3428 if (Ordering == NotAtomic || Ordering == Unordered || 3429 Ordering == Monotonic) 3430 return Error("Invalid record"); 3431 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 3432 I = new FenceInst(Context, Ordering, SynchScope); 3433 InstructionList.push_back(I); 3434 break; 3435 } 3436 case bitc::FUNC_CODE_INST_CALL: { 3437 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 3438 if (Record.size() < 3) 3439 return Error("Invalid record"); 3440 3441 AttributeSet PAL = getAttributes(Record[0]); 3442 unsigned CCInfo = Record[1]; 3443 3444 unsigned OpNum = 2; 3445 Value *Callee; 3446 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 3447 return Error("Invalid record"); 3448 3449 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 3450 FunctionType *FTy = nullptr; 3451 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 3452 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 3453 return Error("Invalid record"); 3454 3455 SmallVector<Value*, 16> Args; 3456 // Read the fixed params. 3457 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 3458 if (FTy->getParamType(i)->isLabelTy()) 3459 Args.push_back(getBasicBlock(Record[OpNum])); 3460 else 3461 Args.push_back(getValue(Record, OpNum, NextValueNo, 3462 FTy->getParamType(i))); 3463 if (!Args.back()) 3464 return Error("Invalid record"); 3465 } 3466 3467 // Read type/value pairs for varargs params. 3468 if (!FTy->isVarArg()) { 3469 if (OpNum != Record.size()) 3470 return Error("Invalid record"); 3471 } else { 3472 while (OpNum != Record.size()) { 3473 Value *Op; 3474 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 3475 return Error("Invalid record"); 3476 Args.push_back(Op); 3477 } 3478 } 3479 3480 I = CallInst::Create(Callee, Args); 3481 InstructionList.push_back(I); 3482 cast<CallInst>(I)->setCallingConv( 3483 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1)); 3484 CallInst::TailCallKind TCK = CallInst::TCK_None; 3485 if (CCInfo & 1) 3486 TCK = CallInst::TCK_Tail; 3487 if (CCInfo & (1 << 14)) 3488 TCK = CallInst::TCK_MustTail; 3489 cast<CallInst>(I)->setTailCallKind(TCK); 3490 cast<CallInst>(I)->setAttributes(PAL); 3491 break; 3492 } 3493 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 3494 if (Record.size() < 3) 3495 return Error("Invalid record"); 3496 Type *OpTy = getTypeByID(Record[0]); 3497 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 3498 Type *ResTy = getTypeByID(Record[2]); 3499 if (!OpTy || !Op || !ResTy) 3500 return Error("Invalid record"); 3501 I = new VAArgInst(Op, ResTy); 3502 InstructionList.push_back(I); 3503 break; 3504 } 3505 } 3506 3507 // Add instruction to end of current BB. If there is no current BB, reject 3508 // this file. 3509 if (!CurBB) { 3510 delete I; 3511 return Error("Invalid instruction with no BB"); 3512 } 3513 CurBB->getInstList().push_back(I); 3514 3515 // If this was a terminator instruction, move to the next block. 3516 if (isa<TerminatorInst>(I)) { 3517 ++CurBBNo; 3518 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr; 3519 } 3520 3521 // Non-void values get registered in the value table for future use. 3522 if (I && !I->getType()->isVoidTy()) 3523 ValueList.AssignValue(I, NextValueNo++); 3524 } 3525 3526 OutOfRecordLoop: 3527 3528 // Check the function list for unresolved values. 3529 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 3530 if (!A->getParent()) { 3531 // We found at least one unresolved value. Nuke them all to avoid leaks. 3532 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 3533 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) { 3534 A->replaceAllUsesWith(UndefValue::get(A->getType())); 3535 delete A; 3536 } 3537 } 3538 return Error("Never resolved value found in function"); 3539 } 3540 } 3541 3542 // FIXME: Check for unresolved forward-declared metadata references 3543 // and clean up leaks. 3544 3545 // Trim the value list down to the size it was before we parsed this function. 3546 ValueList.shrinkTo(ModuleValueListSize); 3547 MDValueList.shrinkTo(ModuleMDValueListSize); 3548 std::vector<BasicBlock*>().swap(FunctionBBs); 3549 return std::error_code(); 3550 } 3551 3552 /// Find the function body in the bitcode stream 3553 std::error_code BitcodeReader::FindFunctionInStream( 3554 Function *F, 3555 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) { 3556 while (DeferredFunctionInfoIterator->second == 0) { 3557 if (Stream.AtEndOfStream()) 3558 return Error("Could not find function in stream"); 3559 // ParseModule will parse the next body in the stream and set its 3560 // position in the DeferredFunctionInfo map. 3561 if (std::error_code EC = ParseModule(true)) 3562 return EC; 3563 } 3564 return std::error_code(); 3565 } 3566 3567 //===----------------------------------------------------------------------===// 3568 // GVMaterializer implementation 3569 //===----------------------------------------------------------------------===// 3570 3571 void BitcodeReader::releaseBuffer() { Buffer.release(); } 3572 3573 std::error_code BitcodeReader::materialize(GlobalValue *GV) { 3574 Function *F = dyn_cast<Function>(GV); 3575 // If it's not a function or is already material, ignore the request. 3576 if (!F || !F->isMaterializable()) 3577 return std::error_code(); 3578 3579 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 3580 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 3581 // If its position is recorded as 0, its body is somewhere in the stream 3582 // but we haven't seen it yet. 3583 if (DFII->second == 0 && LazyStreamer) 3584 if (std::error_code EC = FindFunctionInStream(F, DFII)) 3585 return EC; 3586 3587 // Move the bit stream to the saved position of the deferred function body. 3588 Stream.JumpToBit(DFII->second); 3589 3590 if (std::error_code EC = ParseFunctionBody(F)) 3591 return EC; 3592 F->setIsMaterializable(false); 3593 3594 // Upgrade any old intrinsic calls in the function. 3595 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 3596 E = UpgradedIntrinsics.end(); I != E; ++I) { 3597 if (I->first != I->second) { 3598 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3599 UI != UE;) { 3600 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3601 UpgradeIntrinsicCall(CI, I->second); 3602 } 3603 } 3604 } 3605 3606 // Bring in any functions that this function forward-referenced via 3607 // blockaddresses. 3608 return materializeForwardReferencedFunctions(); 3609 } 3610 3611 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 3612 const Function *F = dyn_cast<Function>(GV); 3613 if (!F || F->isDeclaration()) 3614 return false; 3615 3616 // Dematerializing F would leave dangling references that wouldn't be 3617 // reconnected on re-materialization. 3618 if (BlockAddressesTaken.count(F)) 3619 return false; 3620 3621 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 3622 } 3623 3624 void BitcodeReader::Dematerialize(GlobalValue *GV) { 3625 Function *F = dyn_cast<Function>(GV); 3626 // If this function isn't dematerializable, this is a noop. 3627 if (!F || !isDematerializable(F)) 3628 return; 3629 3630 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 3631 3632 // Just forget the function body, we can remat it later. 3633 F->dropAllReferences(); 3634 F->setIsMaterializable(true); 3635 } 3636 3637 std::error_code BitcodeReader::MaterializeModule(Module *M) { 3638 assert(M == TheModule && 3639 "Can only Materialize the Module this BitcodeReader is attached to."); 3640 3641 // Promise to materialize all forward references. 3642 WillMaterializeAllForwardRefs = true; 3643 3644 // Iterate over the module, deserializing any functions that are still on 3645 // disk. 3646 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 3647 F != E; ++F) { 3648 if (std::error_code EC = materialize(F)) 3649 return EC; 3650 } 3651 // At this point, if there are any function bodies, the current bit is 3652 // pointing to the END_BLOCK record after them. Now make sure the rest 3653 // of the bits in the module have been read. 3654 if (NextUnreadBit) 3655 ParseModule(true); 3656 3657 // Check that all block address forward references got resolved (as we 3658 // promised above). 3659 if (!BasicBlockFwdRefs.empty()) 3660 return Error("Never resolved function from blockaddress"); 3661 3662 // Upgrade any intrinsic calls that slipped through (should not happen!) and 3663 // delete the old functions to clean up. We can't do this unless the entire 3664 // module is materialized because there could always be another function body 3665 // with calls to the old function. 3666 for (std::vector<std::pair<Function*, Function*> >::iterator I = 3667 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 3668 if (I->first != I->second) { 3669 for (auto UI = I->first->user_begin(), UE = I->first->user_end(); 3670 UI != UE;) { 3671 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 3672 UpgradeIntrinsicCall(CI, I->second); 3673 } 3674 if (!I->first->use_empty()) 3675 I->first->replaceAllUsesWith(I->second); 3676 I->first->eraseFromParent(); 3677 } 3678 } 3679 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 3680 3681 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++) 3682 UpgradeInstWithTBAATag(InstsWithTBAATag[I]); 3683 3684 UpgradeDebugInfo(*M); 3685 return std::error_code(); 3686 } 3687 3688 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const { 3689 return IdentifiedStructTypes; 3690 } 3691 3692 std::error_code BitcodeReader::InitStream() { 3693 if (LazyStreamer) 3694 return InitLazyStream(); 3695 return InitStreamFromBuffer(); 3696 } 3697 3698 std::error_code BitcodeReader::InitStreamFromBuffer() { 3699 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 3700 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 3701 3702 if (Buffer->getBufferSize() & 3) 3703 return Error("Invalid bitcode signature"); 3704 3705 // If we have a wrapper header, parse it and ignore the non-bc file contents. 3706 // The magic number is 0x0B17C0DE stored in little endian. 3707 if (isBitcodeWrapper(BufPtr, BufEnd)) 3708 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 3709 return Error("Invalid bitcode wrapper header"); 3710 3711 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 3712 Stream.init(&*StreamFile); 3713 3714 return std::error_code(); 3715 } 3716 3717 std::error_code BitcodeReader::InitLazyStream() { 3718 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 3719 // see it. 3720 auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer); 3721 StreamingMemoryObject &Bytes = *OwnedBytes; 3722 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes)); 3723 Stream.init(&*StreamFile); 3724 3725 unsigned char buf[16]; 3726 if (Bytes.readBytes(buf, 16, 0) != 16) 3727 return Error("Invalid bitcode signature"); 3728 3729 if (!isBitcode(buf, buf + 16)) 3730 return Error("Invalid bitcode signature"); 3731 3732 if (isBitcodeWrapper(buf, buf + 4)) { 3733 const unsigned char *bitcodeStart = buf; 3734 const unsigned char *bitcodeEnd = buf + 16; 3735 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 3736 Bytes.dropLeadingBytes(bitcodeStart - buf); 3737 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart); 3738 } 3739 return std::error_code(); 3740 } 3741 3742 namespace { 3743 class BitcodeErrorCategoryType : public std::error_category { 3744 const char *name() const LLVM_NOEXCEPT override { 3745 return "llvm.bitcode"; 3746 } 3747 std::string message(int IE) const override { 3748 BitcodeError E = static_cast<BitcodeError>(IE); 3749 switch (E) { 3750 case BitcodeError::InvalidBitcodeSignature: 3751 return "Invalid bitcode signature"; 3752 case BitcodeError::CorruptedBitcode: 3753 return "Corrupted bitcode"; 3754 } 3755 llvm_unreachable("Unknown error type!"); 3756 } 3757 }; 3758 } 3759 3760 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory; 3761 3762 const std::error_category &llvm::BitcodeErrorCategory() { 3763 return *ErrorCategory; 3764 } 3765 3766 //===----------------------------------------------------------------------===// 3767 // External interface 3768 //===----------------------------------------------------------------------===// 3769 3770 /// \brief Get a lazy one-at-time loading module from bitcode. 3771 /// 3772 /// This isn't always used in a lazy context. In particular, it's also used by 3773 /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull 3774 /// in forward-referenced functions from block address references. 3775 /// 3776 /// \param[in] WillMaterializeAll Set to \c true if the caller promises to 3777 /// materialize everything -- in particular, if this isn't truly lazy. 3778 static ErrorOr<Module *> 3779 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer, 3780 LLVMContext &Context, bool WillMaterializeAll, 3781 DiagnosticHandlerFunction DiagnosticHandler) { 3782 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 3783 BitcodeReader *R = 3784 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler); 3785 M->setMaterializer(R); 3786 3787 auto cleanupOnError = [&](std::error_code EC) { 3788 R->releaseBuffer(); // Never take ownership on error. 3789 delete M; // Also deletes R. 3790 return EC; 3791 }; 3792 3793 if (std::error_code EC = R->ParseBitcodeInto(M)) 3794 return cleanupOnError(EC); 3795 3796 if (!WillMaterializeAll) 3797 // Resolve forward references from blockaddresses. 3798 if (std::error_code EC = R->materializeForwardReferencedFunctions()) 3799 return cleanupOnError(EC); 3800 3801 Buffer.release(); // The BitcodeReader owns it now. 3802 return M; 3803 } 3804 3805 ErrorOr<Module *> 3806 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer, 3807 LLVMContext &Context, 3808 DiagnosticHandlerFunction DiagnosticHandler) { 3809 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false, 3810 DiagnosticHandler); 3811 } 3812 3813 ErrorOr<std::unique_ptr<Module>> 3814 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer, 3815 LLVMContext &Context, 3816 DiagnosticHandlerFunction DiagnosticHandler) { 3817 std::unique_ptr<Module> M = make_unique<Module>(Name, Context); 3818 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler); 3819 M->setMaterializer(R); 3820 if (std::error_code EC = R->ParseBitcodeInto(M.get())) 3821 return EC; 3822 return std::move(M); 3823 } 3824 3825 ErrorOr<Module *> 3826 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, 3827 DiagnosticHandlerFunction DiagnosticHandler) { 3828 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 3829 ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl( 3830 std::move(Buf), Context, true, DiagnosticHandler); 3831 if (!ModuleOrErr) 3832 return ModuleOrErr; 3833 Module *M = ModuleOrErr.get(); 3834 // Read in the entire module, and destroy the BitcodeReader. 3835 if (std::error_code EC = M->materializeAllPermanently()) { 3836 delete M; 3837 return EC; 3838 } 3839 3840 // TODO: Restore the use-lists to the in-memory state when the bitcode was 3841 // written. We must defer until the Module has been fully materialized. 3842 3843 return M; 3844 } 3845 3846 std::string 3847 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context, 3848 DiagnosticHandlerFunction DiagnosticHandler) { 3849 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false); 3850 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context, 3851 DiagnosticHandler); 3852 ErrorOr<std::string> Triple = R->parseTriple(); 3853 if (Triple.getError()) 3854 return ""; 3855 return Triple.get(); 3856 } 3857