1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
3 // This library implements the functionality defined in llvm/Bytecode/Reader.h
5 // Note that this library should be as fast as possible, reentrant, and
8 // TODO: Return error messages to caller instead of printing them out directly.
9 // TODO: Allow passing in an option to ignore the symbol table
11 //===----------------------------------------------------------------------===//
13 #include "ReaderInternals.h"
14 #include "llvm/Bytecode/Reader.h"
15 #include "llvm/Bytecode/Format.h"
16 #include "llvm/Constants.h"
17 #include "llvm/iPHINode.h"
18 #include "llvm/iOther.h"
19 #include "llvm/Module.h"
20 #include "Support/StringExtras.h"
21 #include "Config/unistd.h"
22 #include "Config/sys/mman.h"
23 #include "Config/sys/stat.h"
24 #include "Config/sys/types.h"
28 static inline void ALIGN32(const unsigned char *&begin,
29 const unsigned char *end) {
30 if (align32(begin, end))
31 throw std::string("Alignment error in buffer: read past end of block.");
35 BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
36 if (Ty->isPrimitiveType()) {
37 Slot = Ty->getPrimitiveID();
39 // Check the function level types first...
40 TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
41 FunctionTypeValues.end(), Ty);
42 if (I != FunctionTypeValues.end()) {
43 Slot = FirstDerivedTyID + ModuleTypeValues.size() +
44 (&*I - &FunctionTypeValues[0]);
46 I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
47 if (I == ModuleTypeValues.end())
48 throw std::string("Didn't find type in ModuleTypeValues.");
49 Slot = FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
52 //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << "\n";
55 const Type *BytecodeParser::getType(unsigned ID) {
56 if (ID < Type::NumPrimitiveIDs) {
57 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
61 //cerr << "Looking up Type ID: " << ID << "\n";
62 const Value *V = getValue(Type::TypeTy, ID, false);
63 return cast_or_null<Type>(V);
66 int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
67 assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
68 Val->getType()->isPrimitiveType() ||
69 !cast<Constant>(Val)->isNullValue()) &&
70 "Cannot read null values from bytecode!");
72 getTypeSlot(Val->getType(), type);
73 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
75 if (ValueTab.size() <= type) {
76 unsigned OldSize = ValueTab.size();
77 ValueTab.resize(type+1);
78 while (OldSize != type+1)
79 ValueTab[OldSize++] = new ValueList();
82 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
83 // << "] = " << Val << "\n";
84 ValueTab[type]->push_back(Val);
86 bool HasOffset = HasImplicitZeroInitializer &&
87 !Val->getType()->isPrimitiveType();
89 return ValueTab[type]->size()-1 + HasOffset;
93 void BytecodeParser::setValueTo(ValueTable &ValueTab, unsigned Slot,
95 assert(&ValueTab == &ModuleValues && "Can only setValueTo on Module values!");
97 getTypeSlot(Val->getType(), type);
99 assert((!HasImplicitZeroInitializer || Slot != 0) &&
100 "Cannot change zero init");
101 assert(type < ValueTab.size() && Slot <= ValueTab[type]->size());
102 ValueTab[type]->setOperand(Slot-HasImplicitZeroInitializer, Val);
105 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
107 unsigned type; // The type plane it lives in...
108 getTypeSlot(Ty, type);
110 if (type == Type::TypeTyID) { // The 'type' plane has implicit values
111 assert(Create == false);
112 if (Num < Type::NumPrimitiveIDs) {
113 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
114 if (T) return (Value*)T; // Asked for a primitive type...
117 // Otherwise, derived types need offset...
118 Num -= FirstDerivedTyID;
120 // Is it a module-level type?
121 if (Num < ModuleTypeValues.size())
122 return (Value*)ModuleTypeValues[Num].get();
124 // Nope, is it a function-level type?
125 Num -= ModuleTypeValues.size();
126 if (Num < FunctionTypeValues.size())
127 return (Value*)FunctionTypeValues[Num].get();
132 if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
134 return Constant::getNullValue(Ty);
138 if (type < ModuleValues.size()) {
139 if (Num < ModuleValues[type]->size())
140 return ModuleValues[type]->getOperand(Num);
141 Num -= ModuleValues[type]->size();
144 if (Values.size() > type && Values[type]->size() > Num)
145 return Values[type]->getOperand(Num);
147 if (!Create) return 0; // Do not create a placeholder?
150 switch (Ty->getPrimitiveID()) {
151 case Type::LabelTyID:
152 d = new BBPHolder(Ty, oNum);
155 d = new ValPHolder(Ty, oNum);
159 assert(d != 0 && "How did we not make something?");
160 if (insertValue(d, LateResolveValues) == -1) return 0;
164 /// getConstantValue - Just like getValue, except that it returns a null pointer
165 /// only on error. It always returns a constant (meaning that if the value is
166 /// defined, but is not a constant, that is an error). If the specified
167 /// constant hasn't been parsed yet, a placeholder is defined and used. Later,
168 /// after the real value is parsed, the placeholder is eliminated.
170 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
171 if (Value *V = getValue(Ty, Slot, false))
172 return dyn_cast<Constant>(V); // If we already have the value parsed...
174 std::pair<const Type*, unsigned> Key(Ty, Slot);
175 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
177 if (I != GlobalRefs.end() && I->first == Key) {
178 BCR_TRACE(5, "Previous forward ref found!\n");
179 return cast<Constant>(I->second);
181 // Create a placeholder for the constant reference and
182 // keep track of the fact that we have a forward ref to recycle it
183 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
184 Constant *C = new ConstPHolder(Ty, Slot);
186 // Keep track of the fact that we have a forward ref to recycle it
187 GlobalRefs.insert(I, std::make_pair(Key, C));
193 void BytecodeParser::postResolveValues(ValueTable &ValTab) {
194 while (!ValTab.empty()) {
195 ValueList &DL = *ValTab.back();
198 while (!DL.empty()) {
199 Value *D = DL.back();
200 unsigned IDNumber = getValueIDNumberFromPlaceHolder(D);
203 Value *NewDef = getValue(D->getType(), IDNumber, false);
205 throw std::string("Unresolvable reference found: <" +
206 D->getType()->getDescription() + ">:" +
207 utostr(IDNumber) + ".");
209 // Fixup all of the uses of this placeholder def...
210 D->replaceAllUsesWith(NewDef);
212 // Now that all the uses are gone, delete the placeholder...
213 // If we couldn't find a def (error case), then leak a little
214 delete D; // memory, 'cause otherwise we can't remove all uses!
221 std::auto_ptr<BasicBlock>
222 BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
223 const unsigned char *EndBuf) {
224 std::auto_ptr<BasicBlock> BB(new BasicBlock());
226 while (Buf < EndBuf) {
228 ParseInstruction(Buf, EndBuf, Inst);
230 if (Inst == 0) { throw std::string("Could not parse Instruction."); }
231 if (insertValue(Inst, Values) == -1) {
232 throw std::string("Could not insert value.");
235 BB->getInstList().push_back(Inst);
242 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
243 const unsigned char *EndBuf,
245 while (Buf < EndBuf) {
246 // Symtab block header: [num entries][type id number]
247 unsigned NumEntries, Typ;
248 if (read_vbr(Buf, EndBuf, NumEntries) ||
249 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
250 const Type *Ty = getType(Typ);
251 if (Ty == 0) throw std::string("Invalid type read in symbol table.");
253 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
256 for (unsigned i = 0; i < NumEntries; ++i) {
257 // Symtab entry: [def slot #][name]
259 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
261 if (read(Buf, EndBuf, Name, false)) // Not aligned...
262 throw std::string("Buffer not aligned.");
264 Value *V = getValue(Ty, slot, false); // Find mapping...
266 BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << "\n");
267 throw std::string("Failed value look-up.");
269 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
270 if (!isa<Instruction>(V)) std::cerr << "\n");
272 V->setName(Name, ST);
276 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
279 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
280 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
282 if (I == GlobalRefs.end()) return; // Never forward referenced?
284 BCR_TRACE(3, "Mutating forward refs!\n");
285 Value *VPH = I->second; // Get the placeholder...
287 VPH->replaceAllUsesWith(NewV);
289 // If this is a global variable being resolved, remove the placeholder from
291 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
292 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
294 delete VPH; // Delete the old placeholder
295 GlobalRefs.erase(I); // Remove the map entry for it
299 BytecodeParser::ParseFunction(const unsigned char *&Buf,
300 const unsigned char *EndBuf) {
301 if (FunctionSignatureList.empty())
302 throw std::string("FunctionSignatureList empty!");
304 Function *F = FunctionSignatureList.back().first;
305 unsigned FunctionSlot = FunctionSignatureList.back().second;
306 FunctionSignatureList.pop_back();
308 // Save the information for future reading of the function
309 LazyFunctionInfo *LFI = new LazyFunctionInfo();
310 LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
311 LazyFunctionLoadMap[F] = LFI;
312 // Pretend we've `parsed' this function
316 void BytecodeParser::materializeFunction(Function* F) {
317 // Find {start, end} pointers and slot in the map. If not there, we're done.
318 std::map<Function*, LazyFunctionInfo*>::iterator Fi =
319 LazyFunctionLoadMap.find(F);
320 if (Fi == LazyFunctionLoadMap.end()) return;
322 LazyFunctionInfo *LFI = Fi->second;
323 const unsigned char *Buf = LFI->Buf;
324 const unsigned char *EndBuf = LFI->EndBuf;
325 unsigned FunctionSlot = LFI->FunctionSlot;
326 LazyFunctionLoadMap.erase(Fi);
329 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
331 if (!hasInternalMarkerOnly) {
332 unsigned LinkageType;
333 if (read_vbr(Buf, EndBuf, LinkageType))
334 throw std::string("ParseFunction: Error reading from buffer.");
335 if (LinkageType & ~0x3)
336 throw std::string("Invalid linkage type for Function.");
337 Linkage = (GlobalValue::LinkageTypes)LinkageType;
339 // We used to only support two linkage models: internal and external
341 if (read_vbr(Buf, EndBuf, isInternal))
342 throw std::string("ParseFunction: Error reading from buffer.");
343 if (isInternal) Linkage = GlobalValue::InternalLinkage;
346 F->setLinkage(Linkage);
348 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
349 Function::aiterator AI = F->abegin();
350 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
351 It != Params.end(); ++It, ++AI) {
352 if (insertValue(AI, Values) == -1)
353 throw std::string("Error reading function arguments!");
356 while (Buf < EndBuf) {
358 const unsigned char *OldBuf = Buf;
359 readBlock(Buf, EndBuf, Type, Size);
362 case BytecodeFormat::ConstantPool: {
363 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
364 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
368 case BytecodeFormat::BasicBlock: {
369 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
370 std::auto_ptr<BasicBlock> BB = ParseBasicBlock(Buf, Buf+Size);
371 if (!BB.get() || insertValue(BB.get(), Values) == -1)
372 throw std::string("Parse error: BasicBlock");
374 F->getBasicBlockList().push_back(BB.release());
378 case BytecodeFormat::SymbolTable: {
379 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
380 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable());
385 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
388 throw std::string("Wrapped around reading bytecode.");
391 BCR_TRACE(2, "} end block\n");
393 // Malformed bc file if read past end of block.
394 ALIGN32(Buf, EndBuf);
397 // Check for unresolvable references
398 postResolveValues(LateResolveValues);
400 //ResolveReferencesToValue(F, FunctionSlot);
402 // Clear out function-level types...
403 FunctionTypeValues.clear();
408 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
409 const unsigned char *End) {
410 if (!FunctionSignatureList.empty())
411 throw std::string("Two ModuleGlobalInfo packets found!");
413 // Read global variables...
415 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
416 while (VarType != Type::VoidTyID) { // List is terminated by Void
418 GlobalValue::LinkageTypes Linkage;
420 if (!hasInternalMarkerOnly) {
421 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
422 // bit2,3 = Linkage, bit4+ = slot#
423 SlotNo = VarType >> 4;
424 Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
426 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
427 // bit2 = isInternal, bit3+ = slot#
428 SlotNo = VarType >> 3;
429 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
430 GlobalValue::ExternalLinkage;
433 const Type *Ty = getType(SlotNo);
434 if (!Ty || !isa<PointerType>(Ty))
435 throw std::string("Global not pointer type! Ty = " +
436 Ty->getDescription());
438 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
440 // Create the global variable...
441 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
443 int DestSlot = insertValue(GV, ModuleValues);
444 if (DestSlot == -1) throw Error_DestSlot;
445 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
446 ResolveReferencesToValue(GV, (unsigned)DestSlot);
448 if (VarType & 2) { // Does it have an initializer?
450 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
451 GlobalInits.push_back(std::make_pair(GV, InitSlot));
453 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
456 // Read the function objects for all of the functions that are coming
457 unsigned FnSignature;
458 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
459 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
460 const Type *Ty = getType(FnSignature);
461 if (!Ty || !isa<PointerType>(Ty) ||
462 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
463 throw std::string("Function not ptr to func type! Ty = " +
464 Ty->getDescription());
467 // We create functions by passing the underlying FunctionType to create...
468 Ty = cast<PointerType>(Ty)->getElementType();
470 // When the ModuleGlobalInfo section is read, we load the type of each
471 // function and the 'ModuleValues' slot that it lands in. We then load a
472 // placeholder into its slot to reserve it. When the function is loaded,
473 // this placeholder is replaced.
475 // Insert the placeholder...
476 Function *Func = new Function(cast<FunctionType>(Ty),
477 GlobalValue::InternalLinkage, "", TheModule);
478 int DestSlot = insertValue(Func, ModuleValues);
479 if (DestSlot == -1) throw Error_DestSlot;
480 ResolveReferencesToValue(Func, (unsigned)DestSlot);
482 // Keep track of this information in a list that is emptied as functions are
485 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
487 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
488 BCR_TRACE(2, "Function of type: " << Ty << "\n");
493 // Now that the function signature list is set up, reverse it so that we can
494 // remove elements efficiently from the back of the vector.
495 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
497 // This is for future proofing... in the future extra fields may be added that
498 // we don't understand, so we transparently ignore them.
503 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
504 const unsigned char *EndBuf) {
506 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
508 // Unpack version number: low four bits are for flags, top bits = version
509 Module::Endianness Endianness;
510 Module::PointerSize PointerSize;
511 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
512 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
514 bool hasNoEndianness = Version & 4;
515 bool hasNoPointerSize = Version & 8;
517 RevisionNum = Version >> 4;
519 // Default values for the current bytecode version
520 HasImplicitZeroInitializer = true;
521 hasInternalMarkerOnly = false;
522 FirstDerivedTyID = 14;
524 switch (RevisionNum) {
525 case 0: // Initial revision
526 // Version #0 didn't have any of the flags stored correctly, and in fact as
527 // only valid with a 14 in the flags values. Also, it does not support
528 // encoding zero initializers for arrays compactly.
530 if (Version != 14) throw std::string("Unknown revision 0 flags?");
531 HasImplicitZeroInitializer = false;
532 Endianness = Module::BigEndian;
533 PointerSize = Module::Pointer64;
534 hasInternalMarkerOnly = true;
535 hasNoEndianness = hasNoPointerSize = false;
538 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
539 // hasNoEndianness, and hasNoPointerSize.
540 hasInternalMarkerOnly = true;
543 // Version #2 added information about all 4 linkage types instead of just
544 // having internal and external.
547 throw std::string("Unknown bytecode version number!");
550 if (hasNoEndianness) Endianness = Module::AnyEndianness;
551 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
553 TheModule->setEndianness(Endianness);
554 TheModule->setPointerSize(PointerSize);
555 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
556 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
557 << PointerSize << "\n");
558 BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
561 void BytecodeParser::ParseModule(const unsigned char *Buf,
562 const unsigned char *EndBuf) {
564 readBlock(Buf, EndBuf, Type, Size);
565 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
566 throw std::string("Expected Module packet! B: "+
567 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
568 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
570 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
571 FunctionSignatureList.clear(); // Just in case...
573 // Read into instance variables...
574 ParseVersionInfo(Buf, EndBuf);
575 ALIGN32(Buf, EndBuf);
577 while (Buf < EndBuf) {
578 const unsigned char *OldBuf = Buf;
579 readBlock(Buf, EndBuf, Type, Size);
581 case BytecodeFormat::GlobalTypePlane:
582 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
583 ParseGlobalTypes(Buf, Buf+Size);
586 case BytecodeFormat::ModuleGlobalInfo:
587 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
588 ParseModuleGlobalInfo(Buf, Buf+Size);
591 case BytecodeFormat::ConstantPool:
592 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
593 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
596 case BytecodeFormat::Function: {
597 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
598 ParseFunction(Buf, Buf+Size);
602 case BytecodeFormat::SymbolTable:
603 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
604 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable());
609 if (OldBuf > Buf) throw std::string("Expected Module Block!");
612 BCR_TRACE(1, "} end block\n");
613 ALIGN32(Buf, EndBuf);
616 // After the module constant pool has been read, we can safely initialize
617 // global variables...
618 while (!GlobalInits.empty()) {
619 GlobalVariable *GV = GlobalInits.back().first;
620 unsigned Slot = GlobalInits.back().second;
621 GlobalInits.pop_back();
623 // Look up the initializer value...
624 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
625 if (GV->hasInitializer())
626 throw std::string("Global *already* has an initializer?!");
627 GV->setInitializer(cast<Constant>(V));
629 throw std::string("Cannot find initializer value.");
632 if (!FunctionSignatureList.empty())
633 throw std::string("Function expected, but bytecode stream ended!");
635 BCR_TRACE(0, "} end block\n\n");
639 BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
640 const std::string &ModuleID) {
642 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
644 // Read and check signature...
646 if (read(Buf, EndBuf, Sig) ||
647 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
648 throw std::string("Invalid bytecode signature!");
650 TheModule = new Module(ModuleID);
652 ParseModule(Buf, EndBuf);
653 } catch (std::string &Error) {
654 freeState(); // Must destroy handles before deleting module!