blob: 66111dd93d0d187bc44afbdeb42a1905c798784a [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00002//
3// This library implements the functionality defined in llvm/Bytecode/Reader.h
4//
5// Note that this library should be as fast as possible, reentrant, and
6// threadsafe!!
7//
Chris Lattner74734132002-08-17 22:01:27 +00008// TODO: Return error messages to caller instead of printing them out directly.
Chris Lattner00950542001-06-06 20:29:01 +00009// TODO: Allow passing in an option to ignore the symbol table
10//
Chris Lattnerd6b65252001-10-24 01:15:12 +000011//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000012
Chris Lattner7061dc52001-12-03 18:02:31 +000013#include "ReaderInternals.h"
Chris Lattner00950542001-06-06 20:29:01 +000014#include "llvm/Bytecode/Reader.h"
15#include "llvm/Bytecode/Format.h"
Chris Lattner31bcdb82002-04-28 19:55:58 +000016#include "llvm/Constants.h"
Chris Lattner7061dc52001-12-03 18:02:31 +000017#include "llvm/iPHINode.h"
Chris Lattner00950542001-06-06 20:29:01 +000018#include "llvm/iOther.h"
Misha Brukman12c29d12003-09-22 23:38:23 +000019#include "llvm/Module.h"
20#include "Support/StringExtras.h"
John Criswell7a73b802003-06-30 21:59:07 +000021#include "Config/unistd.h"
Misha Brukman12c29d12003-09-22 23:38:23 +000022#include "Config/sys/mman.h"
23#include "Config/sys/stat.h"
24#include "Config/sys/types.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include <algorithm>
Misha Brukman12c29d12003-09-22 23:38:23 +000026#include <memory>
Chris Lattner00950542001-06-06 20:29:01 +000027
Misha Brukmane0dd0d42003-09-23 16:15:29 +000028static 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.");
32}
Misha Brukman12c29d12003-09-22 23:38:23 +000033
Chris Lattner9e460f22003-10-04 20:00:03 +000034unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
35 if (Ty->isPrimitiveType())
36 return Ty->getPrimitiveID();
37
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]);
44
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]);
Chris Lattner00950542001-06-06 20:29:01 +000049}
50
51const Type *BytecodeParser::getType(unsigned ID) {
Chris Lattner8cdc6b72002-10-23 00:51:54 +000052 if (ID < Type::NumPrimitiveIDs) {
53 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
54 if (T) return T;
55 }
Chris Lattner00950542001-06-06 20:29:01 +000056
Chris Lattner697954c2002-01-20 22:54:45 +000057 //cerr << "Looking up Type ID: " << ID << "\n";
Chris Lattner36392bc2003-10-08 21:18:57 +000058
59 if (ID < Type::NumPrimitiveIDs) {
60 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
61 if (T) return T; // Asked for a primitive type...
62 }
63
64 // Otherwise, derived types need offset...
65 ID -= FirstDerivedTyID;
66
67 // Is it a module-level type?
68 if (ID < ModuleTypeValues.size())
69 return ModuleTypeValues[ID].get();
70
71 // Nope, is it a function-level type?
72 ID -= ModuleTypeValues.size();
73 if (ID < FunctionTypeValues.size())
74 return FunctionTypeValues[ID].get();
75
76 return 0;
Chris Lattner00950542001-06-06 20:29:01 +000077}
78
Chris Lattner52e20b02003-03-19 20:54:26 +000079int 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!");
Chris Lattner9e460f22003-10-04 20:00:03 +000084 unsigned type = getTypeSlot(Val->getType());
Chris Lattner1d670cc2001-09-07 16:37:43 +000085 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
Chris Lattner00950542001-06-06 20:29:01 +000086
Chris Lattner52e20b02003-03-19 20:54:26 +000087 if (ValueTab.size() <= type) {
88 unsigned OldSize = ValueTab.size();
89 ValueTab.resize(type+1);
90 while (OldSize != type+1)
91 ValueTab[OldSize++] = new ValueList();
Chris Lattner036b8aa2003-03-06 17:55:45 +000092 }
Chris Lattner00950542001-06-06 20:29:01 +000093
94 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
Misha Brukman12c29d12003-09-22 23:38:23 +000095 // << "] = " << Val << "\n";
Chris Lattner52e20b02003-03-19 20:54:26 +000096 ValueTab[type]->push_back(Val);
Chris Lattner00950542001-06-06 20:29:01 +000097
Chris Lattner52e20b02003-03-19 20:54:26 +000098 bool HasOffset = HasImplicitZeroInitializer &&
Misha Brukman12c29d12003-09-22 23:38:23 +000099 !Val->getType()->isPrimitiveType();
Chris Lattner52e20b02003-03-19 20:54:26 +0000100
101 return ValueTab[type]->size()-1 + HasOffset;
102}
103
104
Chris Lattner00950542001-06-06 20:29:01 +0000105Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
Chris Lattner36392bc2003-10-08 21:18:57 +0000106 return getValue(getTypeSlot(Ty), oNum, Create);
107}
108
109Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
110 assert(type != Type::TypeTyID && "getValue() cannot get types!");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000111 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000112 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000113
Chris Lattner52e20b02003-03-19 20:54:26 +0000114 if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
115 if (Num == 0)
Chris Lattner36392bc2003-10-08 21:18:57 +0000116 return Constant::getNullValue(getType(type));
Chris Lattner52e20b02003-03-19 20:54:26 +0000117 --Num;
Chris Lattner00950542001-06-06 20:29:01 +0000118 }
119
Chris Lattner52e20b02003-03-19 20:54:26 +0000120 if (type < ModuleValues.size()) {
121 if (Num < ModuleValues[type]->size())
122 return ModuleValues[type]->getOperand(Num);
123 Num -= ModuleValues[type]->size();
124 }
125
126 if (Values.size() > type && Values[type]->size() > Num)
127 return Values[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000128
Chris Lattner74734132002-08-17 22:01:27 +0000129 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000130
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000131 Value *Val = new ValPHolder(getType(type), oNum);
Chris Lattner36392bc2003-10-08 21:18:57 +0000132 if (insertValue(Val, LateResolveValues) == -1) return 0;
133 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000134}
135
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000136/// 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.
139///
140BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
141 // Make sure there is room in the table...
142 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
143
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
146 // been created.
147 if (ParsedBasicBlocks[ID])
148 return ParsedBasicBlocks[ID];
149
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();
153}
154
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000155/// 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.
160///
161Constant *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...
164
Chris Lattner52e20b02003-03-19 20:54:26 +0000165 std::pair<const Type*, unsigned> Key(Ty, Slot);
166 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
167
168 if (I != GlobalRefs.end() && I->first == Key) {
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000169 BCR_TRACE(5, "Previous forward ref found!\n");
170 return cast<Constant>(I->second);
171 } else {
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);
176
177 // Keep track of the fact that we have a forward ref to recycle it
Chris Lattner52e20b02003-03-19 20:54:26 +0000178 GlobalRefs.insert(I, std::make_pair(Key, C));
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000179 return C;
180 }
181}
182
183
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000184BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
185 const unsigned char *EndBuf,
186 unsigned BlockNo) {
187 BasicBlock *BB;
188 if (ParsedBasicBlocks.size() == BlockNo)
189 ParsedBasicBlocks.push_back(BB = new BasicBlock());
190 else if (ParsedBasicBlocks[BlockNo] == 0)
191 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
192 else
193 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000194
195 while (Buf < EndBuf) {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000196 Instruction *Inst;
Misha Brukman12c29d12003-09-22 23:38:23 +0000197 ParseInstruction(Buf, EndBuf, Inst);
198
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.");
Chris Lattner00950542001-06-06 20:29:01 +0000202 }
203
Chris Lattner1d670cc2001-09-07 16:37:43 +0000204 BB->getInstList().push_back(Inst);
Chris Lattner1d670cc2001-09-07 16:37:43 +0000205 BCR_TRACE(4, Inst);
Chris Lattner00950542001-06-06 20:29:01 +0000206 }
207
Misha Brukman12c29d12003-09-22 23:38:23 +0000208 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000209}
210
Misha Brukman12c29d12003-09-22 23:38:23 +0000211void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000212 const unsigned char *EndBuf,
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000213 SymbolTable *ST,
214 Function *CurrentFunction) {
Chris Lattner00950542001-06-06 20:29:01 +0000215 while (Buf < EndBuf) {
216 // Symtab block header: [num entries][type id number]
217 unsigned NumEntries, Typ;
218 if (read_vbr(Buf, EndBuf, NumEntries) ||
Misha Brukman12c29d12003-09-22 23:38:23 +0000219 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
Chris Lattner00950542001-06-06 20:29:01 +0000220 const Type *Ty = getType(Typ);
Misha Brukman12c29d12003-09-22 23:38:23 +0000221 if (Ty == 0) throw std::string("Invalid type read in symbol table.");
Chris Lattner00950542001-06-06 20:29:01 +0000222
Chris Lattner1d670cc2001-09-07 16:37:43 +0000223 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
Misha Brukman12c29d12003-09-22 23:38:23 +0000224 " entries\n");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000225
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000226 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000227 // Symtab entry: [def slot #][name]
228 unsigned slot;
Misha Brukman12c29d12003-09-22 23:38:23 +0000229 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
Chris Lattner697954c2002-01-20 22:54:45 +0000230 std::string Name;
Chris Lattner00950542001-06-06 20:29:01 +0000231 if (read(Buf, EndBuf, Name, false)) // Not aligned...
Misha Brukman12c29d12003-09-22 23:38:23 +0000232 throw std::string("Buffer not aligned.");
Chris Lattner00950542001-06-06 20:29:01 +0000233
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000234 Value *V = 0;
Chris Lattner36392bc2003-10-08 21:18:57 +0000235 if (Typ == Type::TypeTyID)
236 V = (Value*)getType(slot);
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000237 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);
242 V = BlockIterator;
243 }
244 } else
Chris Lattner36392bc2003-10-08 21:18:57 +0000245 V = getValue(Typ, slot, false); // Find mapping...
246 if (V == 0) throw std::string("Failed value look-up.");
Chris Lattner52e20b02003-03-19 20:54:26 +0000247 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
Misha Brukman12c29d12003-09-22 23:38:23 +0000248 if (!isa<Instruction>(V)) std::cerr << "\n");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000249
Chris Lattner52e20b02003-03-19 20:54:26 +0000250 V->setName(Name, ST);
Chris Lattner00950542001-06-06 20:29:01 +0000251 }
252 }
253
Misha Brukman12c29d12003-09-22 23:38:23 +0000254 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
Chris Lattner00950542001-06-06 20:29:01 +0000255}
256
Chris Lattner74734132002-08-17 22:01:27 +0000257void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
Chris Lattner0d75d8d72003-03-06 16:32:25 +0000258 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
259 Slot));
Chris Lattner74734132002-08-17 22:01:27 +0000260 if (I == GlobalRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +0000261
Chris Lattner74734132002-08-17 22:01:27 +0000262 BCR_TRACE(3, "Mutating forward refs!\n");
263 Value *VPH = I->second; // Get the placeholder...
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000264
Chris Lattner52e20b02003-03-19 20:54:26 +0000265 VPH->replaceAllUsesWith(NewV);
266
267 // If this is a global variable being resolved, remove the placeholder from
268 // the module...
269 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
270 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000271
Chris Lattner74734132002-08-17 22:01:27 +0000272 delete VPH; // Delete the old placeholder
273 GlobalRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000274}
275
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000276void BytecodeParser::ParseFunction(const unsigned char *&Buf,
277 const unsigned char *EndBuf) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000278 if (FunctionSignatureList.empty())
279 throw std::string("FunctionSignatureList empty!");
Chris Lattner52e20b02003-03-19 20:54:26 +0000280
Misha Brukman12c29d12003-09-22 23:38:23 +0000281 Function *F = FunctionSignatureList.back().first;
282 unsigned FunctionSlot = FunctionSignatureList.back().second;
283 FunctionSignatureList.pop_back();
284
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
290 Buf = EndBuf;
291}
292
293void 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;
298
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);
304 delete LFI;
Chris Lattner00950542001-06-06 20:29:01 +0000305
Chris Lattnere3869c82003-04-16 21:16:05 +0000306 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
307
308 if (!hasInternalMarkerOnly) {
309 unsigned LinkageType;
Misha Brukman12c29d12003-09-22 23:38:23 +0000310 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.");
Chris Lattnere3869c82003-04-16 21:16:05 +0000314 Linkage = (GlobalValue::LinkageTypes)LinkageType;
315 } else {
316 // We used to only support two linkage models: internal and external
317 unsigned isInternal;
Misha Brukman12c29d12003-09-22 23:38:23 +0000318 if (read_vbr(Buf, EndBuf, isInternal))
319 throw std::string("ParseFunction: Error reading from buffer.");
Chris Lattnere3869c82003-04-16 21:16:05 +0000320 if (isInternal) Linkage = GlobalValue::InternalLinkage;
321 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000322
Chris Lattnere3869c82003-04-16 21:16:05 +0000323 F->setLinkage(Linkage);
Chris Lattner00950542001-06-06 20:29:01 +0000324
Chris Lattner52e20b02003-03-19 20:54:26 +0000325 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
326 Function::aiterator AI = F->abegin();
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000327 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000328 It != Params.end(); ++It, ++AI) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000329 if (insertValue(AI, Values) == -1)
330 throw std::string("Error reading function arguments!");
Chris Lattner00950542001-06-06 20:29:01 +0000331 }
332
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000333 // Keep track of how many basic blocks we have read in...
334 unsigned BlockNum = 0;
335
Chris Lattner00950542001-06-06 20:29:01 +0000336 while (Buf < EndBuf) {
337 unsigned Type, Size;
Chris Lattnerb6c46952003-03-06 17:03:28 +0000338 const unsigned char *OldBuf = Buf;
Misha Brukman12c29d12003-09-22 23:38:23 +0000339 readBlock(Buf, EndBuf, Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +0000340
341 switch (Type) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000342 case BytecodeFormat::ConstantPool: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000343 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000344 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
Chris Lattner00950542001-06-06 20:29:01 +0000345 break;
Misha Brukman12c29d12003-09-22 23:38:23 +0000346 }
Chris Lattner00950542001-06-06 20:29:01 +0000347
348 case BytecodeFormat::BasicBlock: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000349 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000350 BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
351 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +0000352 break;
353 }
354
Misha Brukman12c29d12003-09-22 23:38:23 +0000355 case BytecodeFormat::SymbolTable: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000356 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000357 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
Chris Lattner00950542001-06-06 20:29:01 +0000358 break;
Misha Brukman12c29d12003-09-22 23:38:23 +0000359 }
Chris Lattner00950542001-06-06 20:29:01 +0000360
361 default:
Chris Lattner1d670cc2001-09-07 16:37:43 +0000362 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
Chris Lattner00950542001-06-06 20:29:01 +0000363 Buf += Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000364 if (OldBuf > Buf)
365 throw std::string("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +0000366 break;
367 }
Chris Lattner1d670cc2001-09-07 16:37:43 +0000368 BCR_TRACE(2, "} end block\n");
369
Misha Brukman12c29d12003-09-22 23:38:23 +0000370 // Malformed bc file if read past end of block.
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000371 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000372 }
373
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000374 // 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();
378
379
Misha Brukman12c29d12003-09-22 23:38:23 +0000380 // Check for unresolvable references
Chris Lattner6e448022003-10-08 21:51:46 +0000381 while (!LateResolveValues.empty()) {
382 ValueList &VL = *LateResolveValues.back();
383 LateResolveValues.pop_back();
Chris Lattner00950542001-06-06 20:29:01 +0000384
Chris Lattner6e448022003-10-08 21:51:46 +0000385 while (!VL.empty()) {
386 Value *V = VL.back();
387 unsigned IDNumber = getValueIDNumberFromPlaceHolder(V);
388 VL.pop_back();
389
390 Value *NewVal = getValue(V->getType(), IDNumber, false);
391 if (NewVal == 0)
392 throw std::string("Unresolvable reference found: <" +
393 V->getType()->getDescription() + ">:" +
394 utostr(IDNumber) + ".");
395
396 // Fixup all of the uses of this placeholder def...
397 V->replaceAllUsesWith(NewVal);
398
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!
402 delete V;
403 }
404 delete &VL;
405 }
Chris Lattner00950542001-06-06 20:29:01 +0000406
Misha Brukman12c29d12003-09-22 23:38:23 +0000407 // Clear out function-level types...
Chris Lattner6e5a0e42003-03-06 17:18:14 +0000408 FunctionTypeValues.clear();
Chris Lattnere4d71a12001-09-14 22:03:42 +0000409
Chris Lattner52e20b02003-03-19 20:54:26 +0000410 freeTable(Values);
Chris Lattner00950542001-06-06 20:29:01 +0000411}
412
Misha Brukman12c29d12003-09-22 23:38:23 +0000413void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
414 const unsigned char *End) {
415 if (!FunctionSignatureList.empty())
416 throw std::string("Two ModuleGlobalInfo packets found!");
Chris Lattner00950542001-06-06 20:29:01 +0000417
Chris Lattner70cc3392001-09-10 07:58:01 +0000418 // Read global variables...
419 unsigned VarType;
Misha Brukman12c29d12003-09-22 23:38:23 +0000420 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
Chris Lattner70cc3392001-09-10 07:58:01 +0000421 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattnere3869c82003-04-16 21:16:05 +0000422 unsigned SlotNo;
423 GlobalValue::LinkageTypes Linkage;
424
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);
430 } else {
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;
436 }
437
438 const Type *Ty = getType(SlotNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000439 if (!Ty || !isa<PointerType>(Ty))
440 throw std::string("Global not pointer type! Ty = " +
441 Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +0000442
Chris Lattner52e20b02003-03-19 20:54:26 +0000443 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +0000444
Chris Lattner70cc3392001-09-10 07:58:01 +0000445 // Create the global variable...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000446 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +0000447 0, "", TheModule);
Chris Lattner05950c32001-10-13 06:47:01 +0000448 int DestSlot = insertValue(GV, ModuleValues);
Misha Brukman12c29d12003-09-22 23:38:23 +0000449 if (DestSlot == -1) throw Error_DestSlot;
Chris Lattner52e20b02003-03-19 20:54:26 +0000450 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
Chris Lattner74734132002-08-17 22:01:27 +0000451 ResolveReferencesToValue(GV, (unsigned)DestSlot);
Chris Lattner05950c32001-10-13 06:47:01 +0000452
Misha Brukman37f92e22003-09-11 22:34:13 +0000453 if (VarType & 2) { // Does it have an initializer?
Chris Lattner52e20b02003-03-19 20:54:26 +0000454 unsigned InitSlot;
Misha Brukman12c29d12003-09-22 23:38:23 +0000455 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
Chris Lattner52e20b02003-03-19 20:54:26 +0000456 GlobalInits.push_back(std::make_pair(GV, InitSlot));
457 }
Misha Brukman12c29d12003-09-22 23:38:23 +0000458 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
Chris Lattner70cc3392001-09-10 07:58:01 +0000459 }
460
Chris Lattner52e20b02003-03-19 20:54:26 +0000461 // Read the function objects for all of the functions that are coming
Chris Lattner74734132002-08-17 22:01:27 +0000462 unsigned FnSignature;
Misha Brukman12c29d12003-09-22 23:38:23 +0000463 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
Chris Lattner74734132002-08-17 22:01:27 +0000464 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
465 const Type *Ty = getType(FnSignature);
Chris Lattneref9c23f2001-10-03 14:53:21 +0000466 if (!Ty || !isa<PointerType>(Ty) ||
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000467 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000468 throw std::string("Function not ptr to func type! Ty = " +
469 Ty->getDescription());
Chris Lattner00950542001-06-06 20:29:01 +0000470 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +0000471
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000472 // We create functions by passing the underlying FunctionType to create...
Chris Lattner7a176752001-12-04 00:03:30 +0000473 Ty = cast<PointerType>(Ty)->getElementType();
Chris Lattner00950542001-06-06 20:29:01 +0000474
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000475 // 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.
Chris Lattner00950542001-06-06 20:29:01 +0000479
480 // Insert the placeholder...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000481 Function *Func = new Function(cast<FunctionType>(Ty),
482 GlobalValue::InternalLinkage, "", TheModule);
Chris Lattner52e20b02003-03-19 20:54:26 +0000483 int DestSlot = insertValue(Func, ModuleValues);
Misha Brukman12c29d12003-09-22 23:38:23 +0000484 if (DestSlot == -1) throw Error_DestSlot;
Chris Lattner52e20b02003-03-19 20:54:26 +0000485 ResolveReferencesToValue(Func, (unsigned)DestSlot);
Chris Lattner00950542001-06-06 20:29:01 +0000486
Chris Lattner52e20b02003-03-19 20:54:26 +0000487 // Keep track of this information in a list that is emptied as functions are
488 // loaded...
Chris Lattner00950542001-06-06 20:29:01 +0000489 //
Chris Lattner52e20b02003-03-19 20:54:26 +0000490 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
491
Misha Brukman12c29d12003-09-22 23:38:23 +0000492 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000493 BCR_TRACE(2, "Function of type: " << Ty << "\n");
Chris Lattner00950542001-06-06 20:29:01 +0000494 }
495
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000496 ALIGN32(Buf, End);
Chris Lattner74734132002-08-17 22:01:27 +0000497
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());
Chris Lattner00950542001-06-06 20:29:01 +0000501
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.
504 //
505 Buf = End;
Chris Lattner00950542001-06-06 20:29:01 +0000506}
507
Misha Brukman12c29d12003-09-22 23:38:23 +0000508void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000509 const unsigned char *EndBuf) {
Chris Lattner036b8aa2003-03-06 17:55:45 +0000510 unsigned Version;
Misha Brukman12c29d12003-09-22 23:38:23 +0000511 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000512
513 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000514 Module::Endianness Endianness;
515 Module::PointerSize PointerSize;
516 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
517 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
518
519 bool hasNoEndianness = Version & 4;
520 bool hasNoPointerSize = Version & 8;
521
522 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +0000523
524 // Default values for the current bytecode version
Chris Lattner036b8aa2003-03-06 17:55:45 +0000525 HasImplicitZeroInitializer = true;
Chris Lattnere3869c82003-04-16 21:16:05 +0000526 hasInternalMarkerOnly = false;
527 FirstDerivedTyID = 14;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000528
529 switch (RevisionNum) {
530 case 0: // Initial revision
Chris Lattner52e20b02003-03-19 20:54:26 +0000531 // 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.
534 //
Misha Brukman12c29d12003-09-22 23:38:23 +0000535 if (Version != 14) throw std::string("Unknown revision 0 flags?");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000536 HasImplicitZeroInitializer = false;
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000537 Endianness = Module::BigEndian;
538 PointerSize = Module::Pointer64;
Chris Lattnere3869c82003-04-16 21:16:05 +0000539 hasInternalMarkerOnly = true;
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000540 hasNoEndianness = hasNoPointerSize = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000541 break;
542 case 1:
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000543 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
544 // hasNoEndianness, and hasNoPointerSize.
Chris Lattnere3869c82003-04-16 21:16:05 +0000545 hasInternalMarkerOnly = true;
546 break;
547 case 2:
548 // Version #2 added information about all 4 linkage types instead of just
549 // having internal and external.
Chris Lattner036b8aa2003-03-06 17:55:45 +0000550 break;
551 default:
Misha Brukman12c29d12003-09-22 23:38:23 +0000552 throw std::string("Unknown bytecode version number!");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000553 }
554
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000555 if (hasNoEndianness) Endianness = Module::AnyEndianness;
556 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +0000557
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000558 TheModule->setEndianness(Endianness);
559 TheModule->setPointerSize(PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +0000560 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000561 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
562 << PointerSize << "\n");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000563 BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000564}
565
Misha Brukman12c29d12003-09-22 23:38:23 +0000566void BytecodeParser::ParseModule(const unsigned char *Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000567 const unsigned char *EndBuf) {
Chris Lattner00950542001-06-06 20:29:01 +0000568 unsigned Type, Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000569 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?
Chris Lattner00950542001-06-06 20:29:01 +0000574
Chris Lattner1d670cc2001-09-07 16:37:43 +0000575 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
Chris Lattner74734132002-08-17 22:01:27 +0000576 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +0000577
578 // Read into instance variables...
Misha Brukman12c29d12003-09-22 23:38:23 +0000579 ParseVersionInfo(Buf, EndBuf);
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000580 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000581
Chris Lattner00950542001-06-06 20:29:01 +0000582 while (Buf < EndBuf) {
Chris Lattnerb6c46952003-03-06 17:03:28 +0000583 const unsigned char *OldBuf = Buf;
Misha Brukman12c29d12003-09-22 23:38:23 +0000584 readBlock(Buf, EndBuf, Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +0000585 switch (Type) {
Chris Lattner52e20b02003-03-19 20:54:26 +0000586 case BytecodeFormat::GlobalTypePlane:
587 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000588 ParseGlobalTypes(Buf, Buf+Size);
Chris Lattner52e20b02003-03-19 20:54:26 +0000589 break;
590
591 case BytecodeFormat::ModuleGlobalInfo:
592 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000593 ParseModuleGlobalInfo(Buf, Buf+Size);
Chris Lattner52e20b02003-03-19 20:54:26 +0000594 break;
595
Chris Lattner1d670cc2001-09-07 16:37:43 +0000596 case BytecodeFormat::ConstantPool:
597 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000598 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
Chris Lattner00950542001-06-06 20:29:01 +0000599 break;
600
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000601 case BytecodeFormat::Function: {
602 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000603 ParseFunction(Buf, Buf+Size);
Chris Lattner00950542001-06-06 20:29:01 +0000604 break;
605 }
606
607 case BytecodeFormat::SymbolTable:
Chris Lattner1d670cc2001-09-07 16:37:43 +0000608 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000609 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
Chris Lattner00950542001-06-06 20:29:01 +0000610 break;
611
612 default:
Chris Lattner00950542001-06-06 20:29:01 +0000613 Buf += Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000614 if (OldBuf > Buf) throw std::string("Expected Module Block!");
Chris Lattner00950542001-06-06 20:29:01 +0000615 break;
616 }
Chris Lattner1d670cc2001-09-07 16:37:43 +0000617 BCR_TRACE(1, "} end block\n");
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000618 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000619 }
620
Chris Lattner52e20b02003-03-19 20:54:26 +0000621 // 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();
627
628 // Look up the initializer value...
629 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000630 if (GV->hasInitializer())
631 throw std::string("Global *already* has an initializer?!");
Chris Lattner52e20b02003-03-19 20:54:26 +0000632 GV->setInitializer(cast<Constant>(V));
633 } else
Misha Brukman12c29d12003-09-22 23:38:23 +0000634 throw std::string("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +0000635 }
636
Misha Brukman12c29d12003-09-22 23:38:23 +0000637 if (!FunctionSignatureList.empty())
638 throw std::string("Function expected, but bytecode stream ended!");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000639
640 BCR_TRACE(0, "} end block\n\n");
Chris Lattner00950542001-06-06 20:29:01 +0000641}
642
Misha Brukman12c29d12003-09-22 23:38:23 +0000643void
644BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
645 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000646
Misha Brukman12c29d12003-09-22 23:38:23 +0000647 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000648
Chris Lattner00950542001-06-06 20:29:01 +0000649 // Read and check signature...
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000650 unsigned Sig;
Chris Lattner00950542001-06-06 20:29:01 +0000651 if (read(Buf, EndBuf, Sig) ||
Misha Brukman12c29d12003-09-22 23:38:23 +0000652 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
653 throw std::string("Invalid bytecode signature!");
Chris Lattner00950542001-06-06 20:29:01 +0000654
Chris Lattner75f20532003-04-22 18:02:52 +0000655 TheModule = new Module(ModuleID);
Misha Brukman12c29d12003-09-22 23:38:23 +0000656 try {
657 ParseModule(Buf, EndBuf);
658 } catch (std::string &Error) {
Chris Lattnera2602f32003-05-22 18:26:48 +0000659 freeState(); // Must destroy handles before deleting module!
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000660 delete TheModule;
661 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +0000662 throw;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000663 }
Chris Lattner00950542001-06-06 20:29:01 +0000664}