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.");
34 unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
35 if (Ty->isPrimitiveType())
36 return Ty->getPrimitiveID();
38 // Check the function level types first...
39 TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
40 FunctionTypeValues.end(), Ty);
41 if (I != FunctionTypeValues.end())
42 return FirstDerivedTyID + ModuleTypeValues.size() +
43 (&*I - &FunctionTypeValues[0]);
45 I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
46 if (I == ModuleTypeValues.end())
47 throw std::string("Didn't find type in ModuleTypeValues.");
48 return FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
51 const Type *BytecodeParser::getType(unsigned ID) {
52 if (ID < Type::NumPrimitiveIDs) {
53 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
57 //cerr << "Looking up Type ID: " << ID << "\n";
59 if (ID < Type::NumPrimitiveIDs) {
60 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
61 if (T) return T; // Asked for a primitive type...
64 // Otherwise, derived types need offset...
65 ID -= FirstDerivedTyID;
67 // Is it a module-level type?
68 if (ID < ModuleTypeValues.size())
69 return ModuleTypeValues[ID].get();
71 // Nope, is it a function-level type?
72 ID -= ModuleTypeValues.size();
73 if (ID < FunctionTypeValues.size())
74 return FunctionTypeValues[ID].get();
79 int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
80 assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
81 Val->getType()->isPrimitiveType() ||
82 !cast<Constant>(Val)->isNullValue()) &&
83 "Cannot read null values from bytecode!");
84 unsigned type = getTypeSlot(Val->getType());
85 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
87 if (ValueTab.size() <= type) {
88 unsigned OldSize = ValueTab.size();
89 ValueTab.resize(type+1);
90 while (OldSize != type+1)
91 ValueTab[OldSize++] = new ValueList();
94 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
95 // << "] = " << Val << "\n";
96 ValueTab[type]->push_back(Val);
98 bool HasOffset = HasImplicitZeroInitializer &&
99 !Val->getType()->isPrimitiveType();
101 return ValueTab[type]->size()-1 + HasOffset;
105 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
106 return getValue(getTypeSlot(Ty), oNum, Create);
109 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
110 assert(type != Type::TypeTyID && "getValue() cannot get types!");
111 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
114 if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
116 return Constant::getNullValue(getType(type));
120 if (type < ModuleValues.size()) {
121 if (Num < ModuleValues[type]->size())
122 return ModuleValues[type]->getOperand(Num);
123 Num -= ModuleValues[type]->size();
126 if (Values.size() > type && Values[type]->size() > Num)
127 return Values[type]->getOperand(Num);
129 if (!Create) return 0; // Do not create a placeholder?
131 Value *Val = new ValPHolder(getType(type), oNum);
132 if (insertValue(Val, LateResolveValues) == -1) return 0;
136 /// getBasicBlock - Get a particular numbered basic block, which might be a
137 /// forward reference. This works together with ParseBasicBlock to handle these
138 /// forward references in a clean manner.
140 BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
141 // Make sure there is room in the table...
142 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
144 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
145 // has already created this block, or if the forward reference has already
147 if (ParsedBasicBlocks[ID])
148 return ParsedBasicBlocks[ID];
150 // Otherwise, the basic block has not yet been created. Do so and add it to
151 // the ParsedBasicBlocks list.
152 return ParsedBasicBlocks[ID] = new BasicBlock();
155 /// getConstantValue - Just like getValue, except that it returns a null pointer
156 /// only on error. It always returns a constant (meaning that if the value is
157 /// defined, but is not a constant, that is an error). If the specified
158 /// constant hasn't been parsed yet, a placeholder is defined and used. Later,
159 /// after the real value is parsed, the placeholder is eliminated.
161 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
162 if (Value *V = getValue(Ty, Slot, false))
163 return dyn_cast<Constant>(V); // If we already have the value parsed...
165 std::pair<const Type*, unsigned> Key(Ty, Slot);
166 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
168 if (I != GlobalRefs.end() && I->first == Key) {
169 BCR_TRACE(5, "Previous forward ref found!\n");
170 return cast<Constant>(I->second);
172 // Create a placeholder for the constant reference and
173 // keep track of the fact that we have a forward ref to recycle it
174 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
175 Constant *C = new ConstPHolder(Ty, Slot);
177 // Keep track of the fact that we have a forward ref to recycle it
178 GlobalRefs.insert(I, std::make_pair(Key, C));
184 BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
185 const unsigned char *EndBuf,
188 if (ParsedBasicBlocks.size() == BlockNo)
189 ParsedBasicBlocks.push_back(BB = new BasicBlock());
190 else if (ParsedBasicBlocks[BlockNo] == 0)
191 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
193 BB = ParsedBasicBlocks[BlockNo];
195 while (Buf < EndBuf) {
197 ParseInstruction(Buf, EndBuf, Inst);
199 if (Inst == 0) { throw std::string("Could not parse Instruction."); }
200 if (insertValue(Inst, Values) == -1) {
201 throw std::string("Could not insert value.");
204 BB->getInstList().push_back(Inst);
211 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
212 const unsigned char *EndBuf,
214 Function *CurrentFunction) {
215 while (Buf < EndBuf) {
216 // Symtab block header: [num entries][type id number]
217 unsigned NumEntries, Typ;
218 if (read_vbr(Buf, EndBuf, NumEntries) ||
219 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
220 const Type *Ty = getType(Typ);
221 if (Ty == 0) throw std::string("Invalid type read in symbol table.");
223 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
226 for (unsigned i = 0; i < NumEntries; ++i) {
227 // Symtab entry: [def slot #][name]
229 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
231 if (read(Buf, EndBuf, Name, false)) // Not aligned...
232 throw std::string("Buffer not aligned.");
235 if (Typ == Type::TypeTyID)
236 V = (Value*)getType(slot);
237 else if (Typ == Type::LabelTyID) {
238 if (CurrentFunction) {
239 // FIXME: THIS IS N^2!!!
240 Function::iterator BlockIterator = CurrentFunction->begin();
241 std::advance(BlockIterator, slot);
245 V = getValue(Typ, slot, false); // Find mapping...
246 if (V == 0) throw std::string("Failed value look-up.");
247 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
248 if (!isa<Instruction>(V)) std::cerr << "\n");
250 V->setName(Name, ST);
254 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
257 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
258 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
260 if (I == GlobalRefs.end()) return; // Never forward referenced?
262 BCR_TRACE(3, "Mutating forward refs!\n");
263 Value *VPH = I->second; // Get the placeholder...
265 VPH->replaceAllUsesWith(NewV);
267 // If this is a global variable being resolved, remove the placeholder from
269 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
270 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
272 delete VPH; // Delete the old placeholder
273 GlobalRefs.erase(I); // Remove the map entry for it
276 void BytecodeParser::ParseFunction(const unsigned char *&Buf,
277 const unsigned char *EndBuf) {
278 if (FunctionSignatureList.empty())
279 throw std::string("FunctionSignatureList empty!");
281 Function *F = FunctionSignatureList.back().first;
282 unsigned FunctionSlot = FunctionSignatureList.back().second;
283 FunctionSignatureList.pop_back();
285 // Save the information for future reading of the function
286 LazyFunctionInfo *LFI = new LazyFunctionInfo();
287 LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
288 LazyFunctionLoadMap[F] = LFI;
289 // Pretend we've `parsed' this function
293 void BytecodeParser::materializeFunction(Function* F) {
294 // Find {start, end} pointers and slot in the map. If not there, we're done.
295 std::map<Function*, LazyFunctionInfo*>::iterator Fi =
296 LazyFunctionLoadMap.find(F);
297 if (Fi == LazyFunctionLoadMap.end()) return;
299 LazyFunctionInfo *LFI = Fi->second;
300 const unsigned char *Buf = LFI->Buf;
301 const unsigned char *EndBuf = LFI->EndBuf;
302 unsigned FunctionSlot = LFI->FunctionSlot;
303 LazyFunctionLoadMap.erase(Fi);
306 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
308 if (!hasInternalMarkerOnly) {
309 unsigned LinkageType;
310 if (read_vbr(Buf, EndBuf, LinkageType))
311 throw std::string("ParseFunction: Error reading from buffer.");
312 if (LinkageType & ~0x3)
313 throw std::string("Invalid linkage type for Function.");
314 Linkage = (GlobalValue::LinkageTypes)LinkageType;
316 // We used to only support two linkage models: internal and external
318 if (read_vbr(Buf, EndBuf, isInternal))
319 throw std::string("ParseFunction: Error reading from buffer.");
320 if (isInternal) Linkage = GlobalValue::InternalLinkage;
323 F->setLinkage(Linkage);
325 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
326 Function::aiterator AI = F->abegin();
327 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
328 It != Params.end(); ++It, ++AI) {
329 if (insertValue(AI, Values) == -1)
330 throw std::string("Error reading function arguments!");
333 // Keep track of how many basic blocks we have read in...
334 unsigned BlockNum = 0;
336 while (Buf < EndBuf) {
338 const unsigned char *OldBuf = Buf;
339 readBlock(Buf, EndBuf, Type, Size);
342 case BytecodeFormat::ConstantPool: {
343 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
344 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
348 case BytecodeFormat::BasicBlock: {
349 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
350 BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
351 F->getBasicBlockList().push_back(BB);
355 case BytecodeFormat::SymbolTable: {
356 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
357 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
362 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
365 throw std::string("Wrapped around reading bytecode.");
368 BCR_TRACE(2, "} end block\n");
370 // Malformed bc file if read past end of block.
371 ALIGN32(Buf, EndBuf);
374 // Make sure there were no references to non-existant basic blocks.
375 if (BlockNum != ParsedBasicBlocks.size())
376 throw std::string("Illegal basic block operand reference");
377 ParsedBasicBlocks.clear();
380 // Check for unresolvable references
381 while (!LateResolveValues.empty()) {
382 ValueList &VL = *LateResolveValues.back();
383 LateResolveValues.pop_back();
385 while (!VL.empty()) {
386 Value *V = VL.back();
387 unsigned IDNumber = getValueIDNumberFromPlaceHolder(V);
390 Value *NewVal = getValue(V->getType(), IDNumber, false);
392 throw std::string("Unresolvable reference found: <" +
393 V->getType()->getDescription() + ">:" +
394 utostr(IDNumber) + ".");
396 // Fixup all of the uses of this placeholder def...
397 V->replaceAllUsesWith(NewVal);
399 // Now that all the uses are gone, delete the placeholder...
400 // If we couldn't find a def (error case), then leak a little
401 // memory, because otherwise we can't remove all uses!
407 // Clear out function-level types...
408 FunctionTypeValues.clear();
413 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
414 const unsigned char *End) {
415 if (!FunctionSignatureList.empty())
416 throw std::string("Two ModuleGlobalInfo packets found!");
418 // Read global variables...
420 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
421 while (VarType != Type::VoidTyID) { // List is terminated by Void
423 GlobalValue::LinkageTypes Linkage;
425 if (!hasInternalMarkerOnly) {
426 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
427 // bit2,3 = Linkage, bit4+ = slot#
428 SlotNo = VarType >> 4;
429 Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
431 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
432 // bit2 = isInternal, bit3+ = slot#
433 SlotNo = VarType >> 3;
434 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
435 GlobalValue::ExternalLinkage;
438 const Type *Ty = getType(SlotNo);
439 if (!Ty || !isa<PointerType>(Ty))
440 throw std::string("Global not pointer type! Ty = " +
441 Ty->getDescription());
443 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
445 // Create the global variable...
446 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
448 int DestSlot = insertValue(GV, ModuleValues);
449 if (DestSlot == -1) throw Error_DestSlot;
450 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
451 ResolveReferencesToValue(GV, (unsigned)DestSlot);
453 if (VarType & 2) { // Does it have an initializer?
455 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
456 GlobalInits.push_back(std::make_pair(GV, InitSlot));
458 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
461 // Read the function objects for all of the functions that are coming
462 unsigned FnSignature;
463 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
464 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
465 const Type *Ty = getType(FnSignature);
466 if (!Ty || !isa<PointerType>(Ty) ||
467 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
468 throw std::string("Function not ptr to func type! Ty = " +
469 Ty->getDescription());
472 // We create functions by passing the underlying FunctionType to create...
473 Ty = cast<PointerType>(Ty)->getElementType();
475 // When the ModuleGlobalInfo section is read, we load the type of each
476 // function and the 'ModuleValues' slot that it lands in. We then load a
477 // placeholder into its slot to reserve it. When the function is loaded,
478 // this placeholder is replaced.
480 // Insert the placeholder...
481 Function *Func = new Function(cast<FunctionType>(Ty),
482 GlobalValue::InternalLinkage, "", TheModule);
483 int DestSlot = insertValue(Func, ModuleValues);
484 if (DestSlot == -1) throw Error_DestSlot;
485 ResolveReferencesToValue(Func, (unsigned)DestSlot);
487 // Keep track of this information in a list that is emptied as functions are
490 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
492 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
493 BCR_TRACE(2, "Function of type: " << Ty << "\n");
498 // Now that the function signature list is set up, reverse it so that we can
499 // remove elements efficiently from the back of the vector.
500 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
502 // This is for future proofing... in the future extra fields may be added that
503 // we don't understand, so we transparently ignore them.
508 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
509 const unsigned char *EndBuf) {
511 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
513 // Unpack version number: low four bits are for flags, top bits = version
514 Module::Endianness Endianness;
515 Module::PointerSize PointerSize;
516 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
517 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
519 bool hasNoEndianness = Version & 4;
520 bool hasNoPointerSize = Version & 8;
522 RevisionNum = Version >> 4;
524 // Default values for the current bytecode version
525 HasImplicitZeroInitializer = true;
526 hasInternalMarkerOnly = false;
527 FirstDerivedTyID = 14;
529 switch (RevisionNum) {
530 case 0: // Initial revision
531 // Version #0 didn't have any of the flags stored correctly, and in fact as
532 // only valid with a 14 in the flags values. Also, it does not support
533 // encoding zero initializers for arrays compactly.
535 if (Version != 14) throw std::string("Unknown revision 0 flags?");
536 HasImplicitZeroInitializer = false;
537 Endianness = Module::BigEndian;
538 PointerSize = Module::Pointer64;
539 hasInternalMarkerOnly = true;
540 hasNoEndianness = hasNoPointerSize = false;
543 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
544 // hasNoEndianness, and hasNoPointerSize.
545 hasInternalMarkerOnly = true;
548 // Version #2 added information about all 4 linkage types instead of just
549 // having internal and external.
552 throw std::string("Unknown bytecode version number!");
555 if (hasNoEndianness) Endianness = Module::AnyEndianness;
556 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
558 TheModule->setEndianness(Endianness);
559 TheModule->setPointerSize(PointerSize);
560 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
561 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
562 << PointerSize << "\n");
563 BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
566 void BytecodeParser::ParseModule(const unsigned char *Buf,
567 const unsigned char *EndBuf) {
569 readBlock(Buf, EndBuf, Type, Size);
570 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
571 throw std::string("Expected Module packet! B: "+
572 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
573 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
575 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
576 FunctionSignatureList.clear(); // Just in case...
578 // Read into instance variables...
579 ParseVersionInfo(Buf, EndBuf);
580 ALIGN32(Buf, EndBuf);
582 while (Buf < EndBuf) {
583 const unsigned char *OldBuf = Buf;
584 readBlock(Buf, EndBuf, Type, Size);
586 case BytecodeFormat::GlobalTypePlane:
587 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
588 ParseGlobalTypes(Buf, Buf+Size);
591 case BytecodeFormat::ModuleGlobalInfo:
592 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
593 ParseModuleGlobalInfo(Buf, Buf+Size);
596 case BytecodeFormat::ConstantPool:
597 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
598 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
601 case BytecodeFormat::Function: {
602 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
603 ParseFunction(Buf, Buf+Size);
607 case BytecodeFormat::SymbolTable:
608 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
609 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
614 if (OldBuf > Buf) throw std::string("Expected Module Block!");
617 BCR_TRACE(1, "} end block\n");
618 ALIGN32(Buf, EndBuf);
621 // After the module constant pool has been read, we can safely initialize
622 // global variables...
623 while (!GlobalInits.empty()) {
624 GlobalVariable *GV = GlobalInits.back().first;
625 unsigned Slot = GlobalInits.back().second;
626 GlobalInits.pop_back();
628 // Look up the initializer value...
629 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
630 if (GV->hasInitializer())
631 throw std::string("Global *already* has an initializer?!");
632 GV->setInitializer(cast<Constant>(V));
634 throw std::string("Cannot find initializer value.");
637 if (!FunctionSignatureList.empty())
638 throw std::string("Function expected, but bytecode stream ended!");
640 BCR_TRACE(0, "} end block\n\n");
644 BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
645 const std::string &ModuleID) {
647 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
649 // Read and check signature...
651 if (read(Buf, EndBuf, Sig) ||
652 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
653 throw std::string("Invalid bytecode signature!");
655 TheModule = new Module(ModuleID);
657 ParseModule(Buf, EndBuf);
658 } catch (std::string &Error) {
659 freeState(); // Must destroy handles before deleting module!