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