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