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