blob: 4011af7b0499fd8b1aaa588defb858f0ab00c680 [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 Lattner8eb10ce2003-10-09 06:05:40 +0000131 std::pair<unsigned,unsigned> KeyValue(type, oNum);
132 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
133 ForwardReferences.lower_bound(KeyValue);
134 if (I != ForwardReferences.end() && I->first == KeyValue)
135 return I->second; // We have already created this placeholder
136
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000137 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000138 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000139 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000140}
141
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000142/// getBasicBlock - Get a particular numbered basic block, which might be a
143/// forward reference. This works together with ParseBasicBlock to handle these
144/// forward references in a clean manner.
145///
146BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
147 // Make sure there is room in the table...
148 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
149
150 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
151 // has already created this block, or if the forward reference has already
152 // been created.
153 if (ParsedBasicBlocks[ID])
154 return ParsedBasicBlocks[ID];
155
156 // Otherwise, the basic block has not yet been created. Do so and add it to
157 // the ParsedBasicBlocks list.
158 return ParsedBasicBlocks[ID] = new BasicBlock();
159}
160
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000161/// getConstantValue - Just like getValue, except that it returns a null pointer
162/// only on error. It always returns a constant (meaning that if the value is
163/// defined, but is not a constant, that is an error). If the specified
164/// constant hasn't been parsed yet, a placeholder is defined and used. Later,
165/// after the real value is parsed, the placeholder is eliminated.
166///
167Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
168 if (Value *V = getValue(Ty, Slot, false))
169 return dyn_cast<Constant>(V); // If we already have the value parsed...
170
Chris Lattner52e20b02003-03-19 20:54:26 +0000171 std::pair<const Type*, unsigned> Key(Ty, Slot);
172 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
173
174 if (I != GlobalRefs.end() && I->first == Key) {
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000175 BCR_TRACE(5, "Previous forward ref found!\n");
176 return cast<Constant>(I->second);
177 } else {
178 // Create a placeholder for the constant reference and
179 // keep track of the fact that we have a forward ref to recycle it
180 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
181 Constant *C = new ConstPHolder(Ty, Slot);
182
183 // Keep track of the fact that we have a forward ref to recycle it
Chris Lattner52e20b02003-03-19 20:54:26 +0000184 GlobalRefs.insert(I, std::make_pair(Key, C));
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000185 return C;
186 }
187}
188
189
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000190BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
191 const unsigned char *EndBuf,
192 unsigned BlockNo) {
193 BasicBlock *BB;
194 if (ParsedBasicBlocks.size() == BlockNo)
195 ParsedBasicBlocks.push_back(BB = new BasicBlock());
196 else if (ParsedBasicBlocks[BlockNo] == 0)
197 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
198 else
199 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000200
201 while (Buf < EndBuf) {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000202 Instruction *Inst;
Misha Brukman12c29d12003-09-22 23:38:23 +0000203 ParseInstruction(Buf, EndBuf, Inst);
204
205 if (Inst == 0) { throw std::string("Could not parse Instruction."); }
206 if (insertValue(Inst, Values) == -1) {
207 throw std::string("Could not insert value.");
Chris Lattner00950542001-06-06 20:29:01 +0000208 }
209
Chris Lattner1d670cc2001-09-07 16:37:43 +0000210 BB->getInstList().push_back(Inst);
Chris Lattner1d670cc2001-09-07 16:37:43 +0000211 BCR_TRACE(4, Inst);
Chris Lattner00950542001-06-06 20:29:01 +0000212 }
213
Misha Brukman12c29d12003-09-22 23:38:23 +0000214 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000215}
216
Misha Brukman12c29d12003-09-22 23:38:23 +0000217void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000218 const unsigned char *EndBuf,
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000219 SymbolTable *ST,
220 Function *CurrentFunction) {
Chris Lattner00950542001-06-06 20:29:01 +0000221 while (Buf < EndBuf) {
222 // Symtab block header: [num entries][type id number]
223 unsigned NumEntries, Typ;
224 if (read_vbr(Buf, EndBuf, NumEntries) ||
Misha Brukman12c29d12003-09-22 23:38:23 +0000225 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
Chris Lattner00950542001-06-06 20:29:01 +0000226 const Type *Ty = getType(Typ);
Misha Brukman12c29d12003-09-22 23:38:23 +0000227 if (Ty == 0) throw std::string("Invalid type read in symbol table.");
Chris Lattner00950542001-06-06 20:29:01 +0000228
Chris Lattner1d670cc2001-09-07 16:37:43 +0000229 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
Misha Brukman12c29d12003-09-22 23:38:23 +0000230 " entries\n");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000231
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000232 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000233 // Symtab entry: [def slot #][name]
234 unsigned slot;
Misha Brukman12c29d12003-09-22 23:38:23 +0000235 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
Chris Lattner697954c2002-01-20 22:54:45 +0000236 std::string Name;
Chris Lattner00950542001-06-06 20:29:01 +0000237 if (read(Buf, EndBuf, Name, false)) // Not aligned...
Misha Brukman12c29d12003-09-22 23:38:23 +0000238 throw std::string("Buffer not aligned.");
Chris Lattner00950542001-06-06 20:29:01 +0000239
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000240 Value *V = 0;
Chris Lattner36392bc2003-10-08 21:18:57 +0000241 if (Typ == Type::TypeTyID)
242 V = (Value*)getType(slot);
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000243 else if (Typ == Type::LabelTyID) {
244 if (CurrentFunction) {
245 // FIXME: THIS IS N^2!!!
246 Function::iterator BlockIterator = CurrentFunction->begin();
247 std::advance(BlockIterator, slot);
248 V = BlockIterator;
249 }
250 } else
Chris Lattner36392bc2003-10-08 21:18:57 +0000251 V = getValue(Typ, slot, false); // Find mapping...
252 if (V == 0) throw std::string("Failed value look-up.");
Chris Lattner52e20b02003-03-19 20:54:26 +0000253 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
Misha Brukman12c29d12003-09-22 23:38:23 +0000254 if (!isa<Instruction>(V)) std::cerr << "\n");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000255
Chris Lattner52e20b02003-03-19 20:54:26 +0000256 V->setName(Name, ST);
Chris Lattner00950542001-06-06 20:29:01 +0000257 }
258 }
259
Misha Brukman12c29d12003-09-22 23:38:23 +0000260 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
Chris Lattner00950542001-06-06 20:29:01 +0000261}
262
Chris Lattner74734132002-08-17 22:01:27 +0000263void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
Chris Lattner0d75d8d72003-03-06 16:32:25 +0000264 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
265 Slot));
Chris Lattner74734132002-08-17 22:01:27 +0000266 if (I == GlobalRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +0000267
Chris Lattner74734132002-08-17 22:01:27 +0000268 BCR_TRACE(3, "Mutating forward refs!\n");
269 Value *VPH = I->second; // Get the placeholder...
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000270
Chris Lattner52e20b02003-03-19 20:54:26 +0000271 VPH->replaceAllUsesWith(NewV);
272
273 // If this is a global variable being resolved, remove the placeholder from
274 // the module...
275 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
276 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000277
Chris Lattner74734132002-08-17 22:01:27 +0000278 delete VPH; // Delete the old placeholder
279 GlobalRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000280}
281
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000282void BytecodeParser::ParseFunction(const unsigned char *&Buf,
283 const unsigned char *EndBuf) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000284 if (FunctionSignatureList.empty())
285 throw std::string("FunctionSignatureList empty!");
Chris Lattner52e20b02003-03-19 20:54:26 +0000286
Misha Brukman12c29d12003-09-22 23:38:23 +0000287 Function *F = FunctionSignatureList.back().first;
288 unsigned FunctionSlot = FunctionSignatureList.back().second;
289 FunctionSignatureList.pop_back();
290
291 // Save the information for future reading of the function
292 LazyFunctionInfo *LFI = new LazyFunctionInfo();
293 LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
294 LazyFunctionLoadMap[F] = LFI;
295 // Pretend we've `parsed' this function
296 Buf = EndBuf;
297}
298
299void BytecodeParser::materializeFunction(Function* F) {
300 // Find {start, end} pointers and slot in the map. If not there, we're done.
301 std::map<Function*, LazyFunctionInfo*>::iterator Fi =
302 LazyFunctionLoadMap.find(F);
303 if (Fi == LazyFunctionLoadMap.end()) return;
304
305 LazyFunctionInfo *LFI = Fi->second;
306 const unsigned char *Buf = LFI->Buf;
307 const unsigned char *EndBuf = LFI->EndBuf;
308 unsigned FunctionSlot = LFI->FunctionSlot;
309 LazyFunctionLoadMap.erase(Fi);
310 delete LFI;
Chris Lattner00950542001-06-06 20:29:01 +0000311
Chris Lattnere3869c82003-04-16 21:16:05 +0000312 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
313
314 if (!hasInternalMarkerOnly) {
315 unsigned LinkageType;
Misha Brukman12c29d12003-09-22 23:38:23 +0000316 if (read_vbr(Buf, EndBuf, LinkageType))
317 throw std::string("ParseFunction: Error reading from buffer.");
318 if (LinkageType & ~0x3)
319 throw std::string("Invalid linkage type for Function.");
Chris Lattnere3869c82003-04-16 21:16:05 +0000320 Linkage = (GlobalValue::LinkageTypes)LinkageType;
321 } else {
322 // We used to only support two linkage models: internal and external
323 unsigned isInternal;
Misha Brukman12c29d12003-09-22 23:38:23 +0000324 if (read_vbr(Buf, EndBuf, isInternal))
325 throw std::string("ParseFunction: Error reading from buffer.");
Chris Lattnere3869c82003-04-16 21:16:05 +0000326 if (isInternal) Linkage = GlobalValue::InternalLinkage;
327 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000328
Chris Lattnere3869c82003-04-16 21:16:05 +0000329 F->setLinkage(Linkage);
Chris Lattner00950542001-06-06 20:29:01 +0000330
Chris Lattner52e20b02003-03-19 20:54:26 +0000331 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
332 Function::aiterator AI = F->abegin();
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000333 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
Chris Lattner69da5cf2002-10-13 20:57:00 +0000334 It != Params.end(); ++It, ++AI) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000335 if (insertValue(AI, Values) == -1)
336 throw std::string("Error reading function arguments!");
Chris Lattner00950542001-06-06 20:29:01 +0000337 }
338
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000339 // Keep track of how many basic blocks we have read in...
340 unsigned BlockNum = 0;
341
Chris Lattner00950542001-06-06 20:29:01 +0000342 while (Buf < EndBuf) {
343 unsigned Type, Size;
Chris Lattnerb6c46952003-03-06 17:03:28 +0000344 const unsigned char *OldBuf = Buf;
Misha Brukman12c29d12003-09-22 23:38:23 +0000345 readBlock(Buf, EndBuf, Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +0000346
347 switch (Type) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000348 case BytecodeFormat::ConstantPool: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000349 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000350 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
Chris Lattner00950542001-06-06 20:29:01 +0000351 break;
Misha Brukman12c29d12003-09-22 23:38:23 +0000352 }
Chris Lattner00950542001-06-06 20:29:01 +0000353
354 case BytecodeFormat::BasicBlock: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000355 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000356 BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
357 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +0000358 break;
359 }
360
Misha Brukman12c29d12003-09-22 23:38:23 +0000361 case BytecodeFormat::SymbolTable: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000362 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000363 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
Chris Lattner00950542001-06-06 20:29:01 +0000364 break;
Misha Brukman12c29d12003-09-22 23:38:23 +0000365 }
Chris Lattner00950542001-06-06 20:29:01 +0000366
367 default:
Chris Lattner1d670cc2001-09-07 16:37:43 +0000368 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
Chris Lattner00950542001-06-06 20:29:01 +0000369 Buf += Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000370 if (OldBuf > Buf)
371 throw std::string("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +0000372 break;
373 }
Chris Lattner1d670cc2001-09-07 16:37:43 +0000374 BCR_TRACE(2, "} end block\n");
375
Misha Brukman12c29d12003-09-22 23:38:23 +0000376 // Malformed bc file if read past end of block.
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000377 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000378 }
379
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000380 // Make sure there were no references to non-existant basic blocks.
381 if (BlockNum != ParsedBasicBlocks.size())
382 throw std::string("Illegal basic block operand reference");
383 ParsedBasicBlocks.clear();
384
385
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000386 // Resolve forward references
387 while (!ForwardReferences.empty()) {
388 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I = ForwardReferences.begin();
389 unsigned type = I->first.first;
390 unsigned Slot = I->first.second;
391 Value *PlaceHolder = I->second;
392 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +0000393
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000394 Value *NewVal = getValue(type, Slot, false);
395 if (NewVal == 0)
396 throw std::string("Unresolvable reference found: <" +
397 PlaceHolder->getType()->getDescription() + ">:" +
398 utostr(Slot) + ".");
Chris Lattner6e448022003-10-08 21:51:46 +0000399
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000400 // Fixup all of the uses of this placeholder def...
401 PlaceHolder->replaceAllUsesWith(NewVal);
Chris Lattner6e448022003-10-08 21:51:46 +0000402
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000403 // Now that all the uses are gone, delete the placeholder...
404 // If we couldn't find a def (error case), then leak a little
405 // memory, because otherwise we can't remove all uses!
406 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +0000407 }
Chris Lattner00950542001-06-06 20:29:01 +0000408
Misha Brukman12c29d12003-09-22 23:38:23 +0000409 // Clear out function-level types...
Chris Lattner6e5a0e42003-03-06 17:18:14 +0000410 FunctionTypeValues.clear();
Chris Lattnere4d71a12001-09-14 22:03:42 +0000411
Chris Lattner52e20b02003-03-19 20:54:26 +0000412 freeTable(Values);
Chris Lattner00950542001-06-06 20:29:01 +0000413}
414
Misha Brukman12c29d12003-09-22 23:38:23 +0000415void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
416 const unsigned char *End) {
417 if (!FunctionSignatureList.empty())
418 throw std::string("Two ModuleGlobalInfo packets found!");
Chris Lattner00950542001-06-06 20:29:01 +0000419
Chris Lattner70cc3392001-09-10 07:58:01 +0000420 // Read global variables...
421 unsigned VarType;
Misha Brukman12c29d12003-09-22 23:38:23 +0000422 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
Chris Lattner70cc3392001-09-10 07:58:01 +0000423 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattnere3869c82003-04-16 21:16:05 +0000424 unsigned SlotNo;
425 GlobalValue::LinkageTypes Linkage;
426
427 if (!hasInternalMarkerOnly) {
428 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
429 // bit2,3 = Linkage, bit4+ = slot#
430 SlotNo = VarType >> 4;
431 Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
432 } else {
433 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
434 // bit2 = isInternal, bit3+ = slot#
435 SlotNo = VarType >> 3;
436 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
437 GlobalValue::ExternalLinkage;
438 }
439
440 const Type *Ty = getType(SlotNo);
Misha Brukman12c29d12003-09-22 23:38:23 +0000441 if (!Ty || !isa<PointerType>(Ty))
442 throw std::string("Global not pointer type! Ty = " +
443 Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +0000444
Chris Lattner52e20b02003-03-19 20:54:26 +0000445 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +0000446
Chris Lattner70cc3392001-09-10 07:58:01 +0000447 // Create the global variable...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000448 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +0000449 0, "", TheModule);
Chris Lattner05950c32001-10-13 06:47:01 +0000450 int DestSlot = insertValue(GV, ModuleValues);
Misha Brukman12c29d12003-09-22 23:38:23 +0000451 if (DestSlot == -1) throw Error_DestSlot;
Chris Lattner52e20b02003-03-19 20:54:26 +0000452 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
Chris Lattner74734132002-08-17 22:01:27 +0000453 ResolveReferencesToValue(GV, (unsigned)DestSlot);
Chris Lattner05950c32001-10-13 06:47:01 +0000454
Misha Brukman37f92e22003-09-11 22:34:13 +0000455 if (VarType & 2) { // Does it have an initializer?
Chris Lattner52e20b02003-03-19 20:54:26 +0000456 unsigned InitSlot;
Misha Brukman12c29d12003-09-22 23:38:23 +0000457 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
Chris Lattner52e20b02003-03-19 20:54:26 +0000458 GlobalInits.push_back(std::make_pair(GV, InitSlot));
459 }
Misha Brukman12c29d12003-09-22 23:38:23 +0000460 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
Chris Lattner70cc3392001-09-10 07:58:01 +0000461 }
462
Chris Lattner52e20b02003-03-19 20:54:26 +0000463 // Read the function objects for all of the functions that are coming
Chris Lattner74734132002-08-17 22:01:27 +0000464 unsigned FnSignature;
Misha Brukman12c29d12003-09-22 23:38:23 +0000465 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
Chris Lattner74734132002-08-17 22:01:27 +0000466 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
467 const Type *Ty = getType(FnSignature);
Chris Lattneref9c23f2001-10-03 14:53:21 +0000468 if (!Ty || !isa<PointerType>(Ty) ||
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000469 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000470 throw std::string("Function not ptr to func type! Ty = " +
471 Ty->getDescription());
Chris Lattner00950542001-06-06 20:29:01 +0000472 }
Chris Lattner8cdc6b72002-10-23 00:51:54 +0000473
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000474 // We create functions by passing the underlying FunctionType to create...
Chris Lattner7a176752001-12-04 00:03:30 +0000475 Ty = cast<PointerType>(Ty)->getElementType();
Chris Lattner00950542001-06-06 20:29:01 +0000476
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000477 // When the ModuleGlobalInfo section is read, we load the type of each
478 // function and the 'ModuleValues' slot that it lands in. We then load a
479 // placeholder into its slot to reserve it. When the function is loaded,
480 // this placeholder is replaced.
Chris Lattner00950542001-06-06 20:29:01 +0000481
482 // Insert the placeholder...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000483 Function *Func = new Function(cast<FunctionType>(Ty),
484 GlobalValue::InternalLinkage, "", TheModule);
Chris Lattner52e20b02003-03-19 20:54:26 +0000485 int DestSlot = insertValue(Func, ModuleValues);
Misha Brukman12c29d12003-09-22 23:38:23 +0000486 if (DestSlot == -1) throw Error_DestSlot;
Chris Lattner52e20b02003-03-19 20:54:26 +0000487 ResolveReferencesToValue(Func, (unsigned)DestSlot);
Chris Lattner00950542001-06-06 20:29:01 +0000488
Chris Lattner52e20b02003-03-19 20:54:26 +0000489 // Keep track of this information in a list that is emptied as functions are
490 // loaded...
Chris Lattner00950542001-06-06 20:29:01 +0000491 //
Chris Lattner52e20b02003-03-19 20:54:26 +0000492 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
493
Misha Brukman12c29d12003-09-22 23:38:23 +0000494 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000495 BCR_TRACE(2, "Function of type: " << Ty << "\n");
Chris Lattner00950542001-06-06 20:29:01 +0000496 }
497
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000498 ALIGN32(Buf, End);
Chris Lattner74734132002-08-17 22:01:27 +0000499
500 // Now that the function signature list is set up, reverse it so that we can
501 // remove elements efficiently from the back of the vector.
502 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +0000503
504 // This is for future proofing... in the future extra fields may be added that
505 // we don't understand, so we transparently ignore them.
506 //
507 Buf = End;
Chris Lattner00950542001-06-06 20:29:01 +0000508}
509
Misha Brukman12c29d12003-09-22 23:38:23 +0000510void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000511 const unsigned char *EndBuf) {
Chris Lattner036b8aa2003-03-06 17:55:45 +0000512 unsigned Version;
Misha Brukman12c29d12003-09-22 23:38:23 +0000513 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000514
515 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000516 Module::Endianness Endianness;
517 Module::PointerSize PointerSize;
518 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
519 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
520
521 bool hasNoEndianness = Version & 4;
522 bool hasNoPointerSize = Version & 8;
523
524 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +0000525
526 // Default values for the current bytecode version
Chris Lattner036b8aa2003-03-06 17:55:45 +0000527 HasImplicitZeroInitializer = true;
Chris Lattnere3869c82003-04-16 21:16:05 +0000528 hasInternalMarkerOnly = false;
529 FirstDerivedTyID = 14;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000530
531 switch (RevisionNum) {
532 case 0: // Initial revision
Chris Lattner52e20b02003-03-19 20:54:26 +0000533 // Version #0 didn't have any of the flags stored correctly, and in fact as
534 // only valid with a 14 in the flags values. Also, it does not support
535 // encoding zero initializers for arrays compactly.
536 //
Misha Brukman12c29d12003-09-22 23:38:23 +0000537 if (Version != 14) throw std::string("Unknown revision 0 flags?");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000538 HasImplicitZeroInitializer = false;
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000539 Endianness = Module::BigEndian;
540 PointerSize = Module::Pointer64;
Chris Lattnere3869c82003-04-16 21:16:05 +0000541 hasInternalMarkerOnly = true;
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000542 hasNoEndianness = hasNoPointerSize = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000543 break;
544 case 1:
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000545 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
546 // hasNoEndianness, and hasNoPointerSize.
Chris Lattnere3869c82003-04-16 21:16:05 +0000547 hasInternalMarkerOnly = true;
548 break;
549 case 2:
550 // Version #2 added information about all 4 linkage types instead of just
551 // having internal and external.
Chris Lattner036b8aa2003-03-06 17:55:45 +0000552 break;
553 default:
Misha Brukman12c29d12003-09-22 23:38:23 +0000554 throw std::string("Unknown bytecode version number!");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000555 }
556
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000557 if (hasNoEndianness) Endianness = Module::AnyEndianness;
558 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +0000559
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000560 TheModule->setEndianness(Endianness);
561 TheModule->setPointerSize(PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +0000562 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000563 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
564 << PointerSize << "\n");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000565 BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000566}
567
Misha Brukman12c29d12003-09-22 23:38:23 +0000568void BytecodeParser::ParseModule(const unsigned char *Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000569 const unsigned char *EndBuf) {
Chris Lattner00950542001-06-06 20:29:01 +0000570 unsigned Type, Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000571 readBlock(Buf, EndBuf, Type, Size);
572 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
573 throw std::string("Expected Module packet! B: "+
574 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
575 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
Chris Lattner00950542001-06-06 20:29:01 +0000576
Chris Lattner1d670cc2001-09-07 16:37:43 +0000577 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
Chris Lattner74734132002-08-17 22:01:27 +0000578 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +0000579
580 // Read into instance variables...
Misha Brukman12c29d12003-09-22 23:38:23 +0000581 ParseVersionInfo(Buf, EndBuf);
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000582 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000583
Chris Lattner00950542001-06-06 20:29:01 +0000584 while (Buf < EndBuf) {
Chris Lattnerb6c46952003-03-06 17:03:28 +0000585 const unsigned char *OldBuf = Buf;
Misha Brukman12c29d12003-09-22 23:38:23 +0000586 readBlock(Buf, EndBuf, Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +0000587 switch (Type) {
Chris Lattner52e20b02003-03-19 20:54:26 +0000588 case BytecodeFormat::GlobalTypePlane:
589 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000590 ParseGlobalTypes(Buf, Buf+Size);
Chris Lattner52e20b02003-03-19 20:54:26 +0000591 break;
592
593 case BytecodeFormat::ModuleGlobalInfo:
594 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000595 ParseModuleGlobalInfo(Buf, Buf+Size);
Chris Lattner52e20b02003-03-19 20:54:26 +0000596 break;
597
Chris Lattner1d670cc2001-09-07 16:37:43 +0000598 case BytecodeFormat::ConstantPool:
599 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000600 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
Chris Lattner00950542001-06-06 20:29:01 +0000601 break;
602
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000603 case BytecodeFormat::Function: {
604 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000605 ParseFunction(Buf, Buf+Size);
Chris Lattner00950542001-06-06 20:29:01 +0000606 break;
607 }
608
609 case BytecodeFormat::SymbolTable:
Chris Lattner1d670cc2001-09-07 16:37:43 +0000610 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000611 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
Chris Lattner00950542001-06-06 20:29:01 +0000612 break;
613
614 default:
Chris Lattner00950542001-06-06 20:29:01 +0000615 Buf += Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000616 if (OldBuf > Buf) throw std::string("Expected Module Block!");
Chris Lattner00950542001-06-06 20:29:01 +0000617 break;
618 }
Chris Lattner1d670cc2001-09-07 16:37:43 +0000619 BCR_TRACE(1, "} end block\n");
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000620 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000621 }
622
Chris Lattner52e20b02003-03-19 20:54:26 +0000623 // After the module constant pool has been read, we can safely initialize
624 // global variables...
625 while (!GlobalInits.empty()) {
626 GlobalVariable *GV = GlobalInits.back().first;
627 unsigned Slot = GlobalInits.back().second;
628 GlobalInits.pop_back();
629
630 // Look up the initializer value...
631 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000632 if (GV->hasInitializer())
633 throw std::string("Global *already* has an initializer?!");
Chris Lattner52e20b02003-03-19 20:54:26 +0000634 GV->setInitializer(cast<Constant>(V));
635 } else
Misha Brukman12c29d12003-09-22 23:38:23 +0000636 throw std::string("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +0000637 }
638
Misha Brukman12c29d12003-09-22 23:38:23 +0000639 if (!FunctionSignatureList.empty())
640 throw std::string("Function expected, but bytecode stream ended!");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000641
642 BCR_TRACE(0, "} end block\n\n");
Chris Lattner00950542001-06-06 20:29:01 +0000643}
644
Misha Brukman12c29d12003-09-22 23:38:23 +0000645void
646BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
647 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000648
Misha Brukman12c29d12003-09-22 23:38:23 +0000649 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000650
Chris Lattner00950542001-06-06 20:29:01 +0000651 // Read and check signature...
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000652 unsigned Sig;
Chris Lattner00950542001-06-06 20:29:01 +0000653 if (read(Buf, EndBuf, Sig) ||
Misha Brukman12c29d12003-09-22 23:38:23 +0000654 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
655 throw std::string("Invalid bytecode signature!");
Chris Lattner00950542001-06-06 20:29:01 +0000656
Chris Lattner75f20532003-04-22 18:02:52 +0000657 TheModule = new Module(ModuleID);
Misha Brukman12c29d12003-09-22 23:38:23 +0000658 try {
659 ParseModule(Buf, EndBuf);
660 } catch (std::string &Error) {
Chris Lattnera2602f32003-05-22 18:26:48 +0000661 freeState(); // Must destroy handles before deleting module!
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000662 delete TheModule;
663 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +0000664 throw;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000665 }
Chris Lattner00950542001-06-06 20:29:01 +0000666}