blob: 1674786fb76f6b94481093d688d64babc8eba23e [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 Lattner927b1852003-10-09 20:22:47 +000052 if (ID < Type::NumPrimitiveIDs)
53 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
54 return T;
Chris Lattner00950542001-06-06 20:29:01 +000055
Chris Lattner697954c2002-01-20 22:54:45 +000056 //cerr << "Looking up Type ID: " << ID << "\n";
Chris Lattner36392bc2003-10-08 21:18:57 +000057
Chris Lattner927b1852003-10-09 20:22:47 +000058 if (ID < Type::NumPrimitiveIDs)
59 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
60 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +000061
62 // Otherwise, derived types need offset...
63 ID -= FirstDerivedTyID;
64
65 // Is it a module-level type?
66 if (ID < ModuleTypeValues.size())
67 return ModuleTypeValues[ID].get();
68
69 // Nope, is it a function-level type?
70 ID -= ModuleTypeValues.size();
71 if (ID < FunctionTypeValues.size())
72 return FunctionTypeValues[ID].get();
73
Chris Lattner927b1852003-10-09 20:22:47 +000074 throw std::string("Illegal type reference!");
Chris Lattner00950542001-06-06 20:29:01 +000075}
76
Chris Lattner927b1852003-10-09 20:22:47 +000077unsigned BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
Chris Lattnerf0d92732003-10-13 14:34:59 +000078 return insertValue(Val, getTypeSlot(Val->getType()), ValueTab);
79}
80
81unsigned BytecodeParser::insertValue(Value *Val, unsigned type,
82 ValueTable &ValueTab) {
Chris Lattnercb7e2e22003-10-18 05:54:18 +000083 assert((!isa<Constant>(Val) || Val->getType()->isPrimitiveType() ||
Chris Lattner52e20b02003-03-19 20:54:26 +000084 !cast<Constant>(Val)->isNullValue()) &&
85 "Cannot read null values from bytecode!");
Chris Lattner1d670cc2001-09-07 16:37:43 +000086 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
Chris Lattner00950542001-06-06 20:29:01 +000087
Chris Lattner52e20b02003-03-19 20:54:26 +000088 if (ValueTab.size() <= type) {
89 unsigned OldSize = ValueTab.size();
90 ValueTab.resize(type+1);
91 while (OldSize != type+1)
92 ValueTab[OldSize++] = new ValueList();
Chris Lattner036b8aa2003-03-06 17:55:45 +000093 }
Chris Lattner00950542001-06-06 20:29:01 +000094
95 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
Misha Brukman12c29d12003-09-22 23:38:23 +000096 // << "] = " << Val << "\n";
Chris Lattner52e20b02003-03-19 20:54:26 +000097 ValueTab[type]->push_back(Val);
Chris Lattner00950542001-06-06 20:29:01 +000098
Chris Lattnercb7e2e22003-10-18 05:54:18 +000099 bool HasOffset = !Val->getType()->isPrimitiveType();
Chris Lattner52e20b02003-03-19 20:54:26 +0000100 return ValueTab[type]->size()-1 + HasOffset;
101}
102
103
Chris Lattner00950542001-06-06 20:29:01 +0000104Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
Chris Lattner36392bc2003-10-08 21:18:57 +0000105 return getValue(getTypeSlot(Ty), oNum, Create);
106}
107
108Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
109 assert(type != Type::TypeTyID && "getValue() cannot get types!");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000110 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000111 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000112
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000113 if (type >= FirstDerivedTyID) {
Chris Lattner52e20b02003-03-19 20:54:26 +0000114 if (Num == 0)
Chris Lattner36392bc2003-10-08 21:18:57 +0000115 return Constant::getNullValue(getType(type));
Chris Lattner52e20b02003-03-19 20:54:26 +0000116 --Num;
Chris Lattner00950542001-06-06 20:29:01 +0000117 }
118
Chris Lattner52e20b02003-03-19 20:54:26 +0000119 if (type < ModuleValues.size()) {
120 if (Num < ModuleValues[type]->size())
121 return ModuleValues[type]->getOperand(Num);
122 Num -= ModuleValues[type]->size();
123 }
124
125 if (Values.size() > type && Values[type]->size() > Num)
126 return Values[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000127
Chris Lattner74734132002-08-17 22:01:27 +0000128 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000129
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000130 std::pair<unsigned,unsigned> KeyValue(type, oNum);
131 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
132 ForwardReferences.lower_bound(KeyValue);
133 if (I != ForwardReferences.end() && I->first == KeyValue)
134 return I->second; // We have already created this placeholder
135
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000136 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000137 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000138 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000139}
140
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000141/// getBasicBlock - Get a particular numbered basic block, which might be a
142/// forward reference. This works together with ParseBasicBlock to handle these
143/// forward references in a clean manner.
144///
145BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
146 // Make sure there is room in the table...
147 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
148
149 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
150 // has already created this block, or if the forward reference has already
151 // been created.
152 if (ParsedBasicBlocks[ID])
153 return ParsedBasicBlocks[ID];
154
155 // Otherwise, the basic block has not yet been created. Do so and add it to
156 // the ParsedBasicBlocks list.
157 return ParsedBasicBlocks[ID] = new BasicBlock();
158}
159
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000160/// getConstantValue - Just like getValue, except that it returns a null pointer
161/// only on error. It always returns a constant (meaning that if the value is
162/// defined, but is not a constant, that is an error). If the specified
163/// constant hasn't been parsed yet, a placeholder is defined and used. Later,
164/// after the real value is parsed, the placeholder is eliminated.
165///
166Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
167 if (Value *V = getValue(Ty, Slot, false))
Chris Lattnerc9456ca2003-10-09 20:41:16 +0000168 if (Constant *C = dyn_cast<Constant>(V))
169 return C; // If we already have the value parsed, just return it
170 else
171 throw std::string("Reference of a value is expected to be a constant!");
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000172
Chris Lattner52e20b02003-03-19 20:54:26 +0000173 std::pair<const Type*, unsigned> Key(Ty, Slot);
174 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
175
176 if (I != GlobalRefs.end() && I->first == Key) {
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000177 BCR_TRACE(5, "Previous forward ref found!\n");
178 return cast<Constant>(I->second);
179 } else {
180 // Create a placeholder for the constant reference and
181 // keep track of the fact that we have a forward ref to recycle it
182 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
183 Constant *C = new ConstPHolder(Ty, Slot);
184
185 // Keep track of the fact that we have a forward ref to recycle it
Chris Lattner52e20b02003-03-19 20:54:26 +0000186 GlobalRefs.insert(I, std::make_pair(Key, C));
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000187 return C;
188 }
189}
190
191
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000192BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
193 const unsigned char *EndBuf,
194 unsigned BlockNo) {
195 BasicBlock *BB;
196 if (ParsedBasicBlocks.size() == BlockNo)
197 ParsedBasicBlocks.push_back(BB = new BasicBlock());
198 else if (ParsedBasicBlocks[BlockNo] == 0)
199 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
200 else
201 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000202
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000203 std::vector<unsigned> Args;
204 while (Buf < EndBuf)
205 ParseInstruction(Buf, EndBuf, Args, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000206
Misha Brukman12c29d12003-09-22 23:38:23 +0000207 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000208}
209
Misha Brukman12c29d12003-09-22 23:38:23 +0000210void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000211 const unsigned char *EndBuf,
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000212 SymbolTable *ST,
213 Function *CurrentFunction) {
Chris Lattner39cacce2003-10-10 05:43:47 +0000214 // Allow efficient basic block lookup by number.
215 std::vector<BasicBlock*> BBMap;
216 if (CurrentFunction)
217 for (Function::iterator I = CurrentFunction->begin(),
218 E = CurrentFunction->end(); I != E; ++I)
219 BBMap.push_back(I);
220
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);
Chris Lattner927b1852003-10-09 20:22:47 +0000227 BCR_TRACE(3, "Plane Type: '" << *Ty << "' with " << NumEntries <<
Misha Brukman12c29d12003-09-22 23:38:23 +0000228 " entries\n");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000229
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000230 for (unsigned i = 0; i != NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000231 // Symtab entry: [def slot #][name]
232 unsigned slot;
Misha Brukman12c29d12003-09-22 23:38:23 +0000233 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
Chris Lattner697954c2002-01-20 22:54:45 +0000234 std::string Name;
Chris Lattner00950542001-06-06 20:29:01 +0000235 if (read(Buf, EndBuf, Name, false)) // Not aligned...
Chris Lattner7dc3a2e2003-10-13 14:57:53 +0000236 throw std::string("Failed reading symbol name.");
Chris Lattner00950542001-06-06 20:29:01 +0000237
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000238 Value *V = 0;
Chris Lattner36392bc2003-10-08 21:18:57 +0000239 if (Typ == Type::TypeTyID)
240 V = (Value*)getType(slot);
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000241 else if (Typ == Type::LabelTyID) {
Chris Lattner39cacce2003-10-10 05:43:47 +0000242 if (slot < BBMap.size())
243 V = BBMap[slot];
244 } else {
Chris Lattner36392bc2003-10-08 21:18:57 +0000245 V = getValue(Typ, slot, false); // Find mapping...
Chris Lattner39cacce2003-10-10 05:43:47 +0000246 }
Chris Lattner36392bc2003-10-08 21:18:57 +0000247 if (V == 0) throw std::string("Failed value look-up.");
Chris Lattner52e20b02003-03-19 20:54:26 +0000248 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
Misha Brukman12c29d12003-09-22 23:38:23 +0000249 if (!isa<Instruction>(V)) std::cerr << "\n");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000250
Chris Lattner52e20b02003-03-19 20:54:26 +0000251 V->setName(Name, ST);
Chris Lattner00950542001-06-06 20:29:01 +0000252 }
253 }
254
Misha Brukman12c29d12003-09-22 23:38:23 +0000255 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
Chris Lattner00950542001-06-06 20:29:01 +0000256}
257
Chris Lattner74734132002-08-17 22:01:27 +0000258void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
Chris Lattner0d75d8d72003-03-06 16:32:25 +0000259 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
260 Slot));
Chris Lattner74734132002-08-17 22:01:27 +0000261 if (I == GlobalRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +0000262
Chris Lattner74734132002-08-17 22:01:27 +0000263 BCR_TRACE(3, "Mutating forward refs!\n");
264 Value *VPH = I->second; // Get the placeholder...
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) {
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000309 // We didn't support weak linkage explicitly.
Chris Lattnere3869c82003-04-16 21:16:05 +0000310 unsigned LinkageType;
Misha Brukman12c29d12003-09-22 23:38:23 +0000311 if (read_vbr(Buf, EndBuf, LinkageType))
312 throw std::string("ParseFunction: Error reading from buffer.");
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000313 if ((!hasExtendedLinkageSpecs && LinkageType > 3) ||
314 ( hasExtendedLinkageSpecs && LinkageType > 4))
Misha Brukman12c29d12003-09-22 23:38:23 +0000315 throw std::string("Invalid linkage type for Function.");
Chris Lattner6b252422003-10-16 18:28:50 +0000316 switch (LinkageType) {
317 case 0: Linkage = GlobalValue::ExternalLinkage; break;
318 case 1: Linkage = GlobalValue::WeakLinkage; break;
319 case 2: Linkage = GlobalValue::AppendingLinkage; break;
320 case 3: Linkage = GlobalValue::InternalLinkage; break;
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000321 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
Chris Lattner6b252422003-10-16 18:28:50 +0000322 }
Chris Lattnere3869c82003-04-16 21:16:05 +0000323 } else {
324 // We used to only support two linkage models: internal and external
325 unsigned isInternal;
Misha Brukman12c29d12003-09-22 23:38:23 +0000326 if (read_vbr(Buf, EndBuf, isInternal))
327 throw std::string("ParseFunction: Error reading from buffer.");
Chris Lattnere3869c82003-04-16 21:16:05 +0000328 if (isInternal) Linkage = GlobalValue::InternalLinkage;
329 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000330
Chris Lattnere3869c82003-04-16 21:16:05 +0000331 F->setLinkage(Linkage);
Chris Lattner00950542001-06-06 20:29:01 +0000332
Chris Lattner52e20b02003-03-19 20:54:26 +0000333 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
334 Function::aiterator AI = F->abegin();
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000335 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
Chris Lattner927b1852003-10-09 20:22:47 +0000336 It != Params.end(); ++It, ++AI)
337 insertValue(AI, Values);
Chris Lattner00950542001-06-06 20:29:01 +0000338
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
Chris Lattner97330cf2003-10-09 23:10:14 +0000385 // Resolve forward references. Replace any uses of a forward reference value
386 // with the real value.
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000387
Chris Lattner97330cf2003-10-09 23:10:14 +0000388 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
389 // number of operands. PHI nodes often have forward references, and can also
390 // often have a very large number of operands.
391 std::map<Value*, Value*> ForwardRefMapping;
392 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
393 I = ForwardReferences.begin(), E = ForwardReferences.end();
394 I != E; ++I)
395 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
396 false);
397
398 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
399 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
400 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
401 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
402 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
403 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
404 }
405
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000406 while (!ForwardReferences.empty()) {
Chris Lattner35d2ca62003-10-09 22:39:30 +0000407 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
408 ForwardReferences.begin();
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000409 Value *PlaceHolder = I->second;
410 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +0000411
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000412 // Now that all the uses are gone, delete the placeholder...
413 // If we couldn't find a def (error case), then leak a little
414 // memory, because otherwise we can't remove all uses!
415 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +0000416 }
Chris Lattner00950542001-06-06 20:29:01 +0000417
Misha Brukman12c29d12003-09-22 23:38:23 +0000418 // Clear out function-level types...
Chris Lattner6e5a0e42003-03-06 17:18:14 +0000419 FunctionTypeValues.clear();
Chris Lattnere4d71a12001-09-14 22:03:42 +0000420
Chris Lattner52e20b02003-03-19 20:54:26 +0000421 freeTable(Values);
Chris Lattner00950542001-06-06 20:29:01 +0000422}
423
Misha Brukman12c29d12003-09-22 23:38:23 +0000424void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
425 const unsigned char *End) {
426 if (!FunctionSignatureList.empty())
427 throw std::string("Two ModuleGlobalInfo packets found!");
Chris Lattner00950542001-06-06 20:29:01 +0000428
Chris Lattner70cc3392001-09-10 07:58:01 +0000429 // Read global variables...
430 unsigned VarType;
Misha Brukman12c29d12003-09-22 23:38:23 +0000431 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
Chris Lattner70cc3392001-09-10 07:58:01 +0000432 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattnere3869c82003-04-16 21:16:05 +0000433 unsigned SlotNo;
434 GlobalValue::LinkageTypes Linkage;
435
436 if (!hasInternalMarkerOnly) {
437 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
438 // bit2,3 = Linkage, bit4+ = slot#
439 SlotNo = VarType >> 4;
Chris Lattner6b252422003-10-16 18:28:50 +0000440 switch ((VarType >> 2) & 3) {
441 case 0: Linkage = GlobalValue::ExternalLinkage; break;
442 case 1: Linkage = GlobalValue::WeakLinkage; break;
443 case 2: Linkage = GlobalValue::AppendingLinkage; break;
444 case 3: Linkage = GlobalValue::InternalLinkage; break;
445 }
Chris Lattnere3869c82003-04-16 21:16:05 +0000446 } else {
447 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
448 // bit2 = isInternal, bit3+ = slot#
449 SlotNo = VarType >> 3;
450 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
451 GlobalValue::ExternalLinkage;
452 }
453
454 const Type *Ty = getType(SlotNo);
Chris Lattner927b1852003-10-09 20:22:47 +0000455 if (!isa<PointerType>(Ty))
Misha Brukman12c29d12003-09-22 23:38:23 +0000456 throw std::string("Global not pointer type! Ty = " +
457 Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +0000458
Chris Lattner52e20b02003-03-19 20:54:26 +0000459 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +0000460
Chris Lattner70cc3392001-09-10 07:58:01 +0000461 // Create the global variable...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000462 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +0000463 0, "", TheModule);
Chris Lattner52e20b02003-03-19 20:54:26 +0000464 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
Chris Lattnerf0d92732003-10-13 14:34:59 +0000465 ResolveReferencesToValue(GV, insertValue(GV, SlotNo, ModuleValues));
Chris Lattner05950c32001-10-13 06:47:01 +0000466
Misha Brukman37f92e22003-09-11 22:34:13 +0000467 if (VarType & 2) { // Does it have an initializer?
Chris Lattner52e20b02003-03-19 20:54:26 +0000468 unsigned InitSlot;
Misha Brukman12c29d12003-09-22 23:38:23 +0000469 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
Chris Lattner52e20b02003-03-19 20:54:26 +0000470 GlobalInits.push_back(std::make_pair(GV, InitSlot));
471 }
Misha Brukman12c29d12003-09-22 23:38:23 +0000472 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
Chris Lattner70cc3392001-09-10 07:58:01 +0000473 }
474
Chris Lattner52e20b02003-03-19 20:54:26 +0000475 // Read the function objects for all of the functions that are coming
Chris Lattner74734132002-08-17 22:01:27 +0000476 unsigned FnSignature;
Misha Brukman12c29d12003-09-22 23:38:23 +0000477 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
Chris Lattner74734132002-08-17 22:01:27 +0000478 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
479 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +0000480 if (!isa<PointerType>(Ty) ||
481 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
Misha Brukman12c29d12003-09-22 23:38:23 +0000482 throw std::string("Function not ptr to func type! Ty = " +
483 Ty->getDescription());
Chris Lattner8cdc6b72002-10-23 00:51:54 +0000484
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000485 // We create functions by passing the underlying FunctionType to create...
Chris Lattner7a176752001-12-04 00:03:30 +0000486 Ty = cast<PointerType>(Ty)->getElementType();
Chris Lattner00950542001-06-06 20:29:01 +0000487
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000488 // When the ModuleGlobalInfo section is read, we load the type of each
489 // function and the 'ModuleValues' slot that it lands in. We then load a
490 // placeholder into its slot to reserve it. When the function is loaded,
491 // this placeholder is replaced.
Chris Lattner00950542001-06-06 20:29:01 +0000492
493 // Insert the placeholder...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000494 Function *Func = new Function(cast<FunctionType>(Ty),
495 GlobalValue::InternalLinkage, "", TheModule);
Chris Lattnerf0d92732003-10-13 14:34:59 +0000496 unsigned DestSlot = insertValue(Func, FnSignature, ModuleValues);
Chris Lattner927b1852003-10-09 20:22:47 +0000497 ResolveReferencesToValue(Func, DestSlot);
Chris Lattner00950542001-06-06 20:29:01 +0000498
Chris Lattner52e20b02003-03-19 20:54:26 +0000499 // Keep track of this information in a list that is emptied as functions are
500 // loaded...
Chris Lattner00950542001-06-06 20:29:01 +0000501 //
Chris Lattner52e20b02003-03-19 20:54:26 +0000502 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
503
Misha Brukman12c29d12003-09-22 23:38:23 +0000504 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000505 BCR_TRACE(2, "Function of type: " << Ty << "\n");
Chris Lattner00950542001-06-06 20:29:01 +0000506 }
507
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000508 ALIGN32(Buf, End);
Chris Lattner74734132002-08-17 22:01:27 +0000509
510 // Now that the function signature list is set up, reverse it so that we can
511 // remove elements efficiently from the back of the vector.
512 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +0000513
514 // This is for future proofing... in the future extra fields may be added that
515 // we don't understand, so we transparently ignore them.
516 //
517 Buf = End;
Chris Lattner00950542001-06-06 20:29:01 +0000518}
519
Misha Brukman12c29d12003-09-22 23:38:23 +0000520void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000521 const unsigned char *EndBuf) {
Chris Lattner036b8aa2003-03-06 17:55:45 +0000522 unsigned Version;
Misha Brukman12c29d12003-09-22 23:38:23 +0000523 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000524
525 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000526 Module::Endianness Endianness;
527 Module::PointerSize PointerSize;
528 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
529 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
530
531 bool hasNoEndianness = Version & 4;
532 bool hasNoPointerSize = Version & 8;
533
534 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +0000535
536 // Default values for the current bytecode version
Chris Lattnere3869c82003-04-16 21:16:05 +0000537 hasInternalMarkerOnly = false;
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000538 hasExtendedLinkageSpecs = true;
539 hasOldStyleVarargs = false;
540 hasVarArgCallPadding = false;
Chris Lattnere3869c82003-04-16 21:16:05 +0000541 FirstDerivedTyID = 14;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000542
543 switch (RevisionNum) {
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000544 case 1: // LLVM pre-1.0 release: will be deleted on the next rev
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;
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000548 hasExtendedLinkageSpecs = false;
549 hasOldStyleVarargs = true;
550 hasVarArgCallPadding = true;
Chris Lattnere3869c82003-04-16 21:16:05 +0000551 break;
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000552 case 2: // LLVM pre-1.0 release:
Chris Lattnere3869c82003-04-16 21:16:05 +0000553 // Version #2 added information about all 4 linkage types instead of just
554 // having internal and external.
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000555 hasExtendedLinkageSpecs = false;
556 hasOldStyleVarargs = true;
557 hasVarArgCallPadding = true;
558 break;
559 case 0: // LLVM 1.0 release version
560 // Compared to rev #2, we added support for weak linkage, a more dense
561 // encoding, and better varargs support.
562
563 // FIXME: densify the encoding!
Chris Lattner036b8aa2003-03-06 17:55:45 +0000564 break;
565 default:
Misha Brukman12c29d12003-09-22 23:38:23 +0000566 throw std::string("Unknown bytecode version number!");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000567 }
568
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000569 if (hasNoEndianness) Endianness = Module::AnyEndianness;
570 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +0000571
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000572 TheModule->setEndianness(Endianness);
573 TheModule->setPointerSize(PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +0000574 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000575 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
576 << PointerSize << "\n");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000577}
578
Misha Brukman12c29d12003-09-22 23:38:23 +0000579void BytecodeParser::ParseModule(const unsigned char *Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000580 const unsigned char *EndBuf) {
Chris Lattner00950542001-06-06 20:29:01 +0000581 unsigned Type, Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000582 readBlock(Buf, EndBuf, Type, Size);
583 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
584 throw std::string("Expected Module packet! B: "+
585 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
586 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
Chris Lattner00950542001-06-06 20:29:01 +0000587
Chris Lattner1d670cc2001-09-07 16:37:43 +0000588 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
Chris Lattner74734132002-08-17 22:01:27 +0000589 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +0000590
591 // Read into instance variables...
Misha Brukman12c29d12003-09-22 23:38:23 +0000592 ParseVersionInfo(Buf, EndBuf);
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000593 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000594
Chris Lattner00950542001-06-06 20:29:01 +0000595 while (Buf < EndBuf) {
Chris Lattnerb6c46952003-03-06 17:03:28 +0000596 const unsigned char *OldBuf = Buf;
Misha Brukman12c29d12003-09-22 23:38:23 +0000597 readBlock(Buf, EndBuf, Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +0000598 switch (Type) {
Chris Lattner52e20b02003-03-19 20:54:26 +0000599 case BytecodeFormat::GlobalTypePlane:
600 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000601 ParseGlobalTypes(Buf, Buf+Size);
Chris Lattner52e20b02003-03-19 20:54:26 +0000602 break;
603
604 case BytecodeFormat::ModuleGlobalInfo:
605 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000606 ParseModuleGlobalInfo(Buf, Buf+Size);
Chris Lattner52e20b02003-03-19 20:54:26 +0000607 break;
608
Chris Lattner1d670cc2001-09-07 16:37:43 +0000609 case BytecodeFormat::ConstantPool:
610 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000611 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
Chris Lattner00950542001-06-06 20:29:01 +0000612 break;
613
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000614 case BytecodeFormat::Function: {
615 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000616 ParseFunction(Buf, Buf+Size);
Chris Lattner00950542001-06-06 20:29:01 +0000617 break;
618 }
619
620 case BytecodeFormat::SymbolTable:
Chris Lattner1d670cc2001-09-07 16:37:43 +0000621 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000622 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
Chris Lattner00950542001-06-06 20:29:01 +0000623 break;
624
625 default:
Chris Lattner00950542001-06-06 20:29:01 +0000626 Buf += Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000627 if (OldBuf > Buf) throw std::string("Expected Module Block!");
Chris Lattner00950542001-06-06 20:29:01 +0000628 break;
629 }
Chris Lattner1d670cc2001-09-07 16:37:43 +0000630 BCR_TRACE(1, "} end block\n");
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000631 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000632 }
633
Chris Lattner52e20b02003-03-19 20:54:26 +0000634 // After the module constant pool has been read, we can safely initialize
635 // global variables...
636 while (!GlobalInits.empty()) {
637 GlobalVariable *GV = GlobalInits.back().first;
638 unsigned Slot = GlobalInits.back().second;
639 GlobalInits.pop_back();
640
641 // Look up the initializer value...
642 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000643 if (GV->hasInitializer())
644 throw std::string("Global *already* has an initializer?!");
Chris Lattner52e20b02003-03-19 20:54:26 +0000645 GV->setInitializer(cast<Constant>(V));
646 } else
Misha Brukman12c29d12003-09-22 23:38:23 +0000647 throw std::string("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +0000648 }
649
Misha Brukman12c29d12003-09-22 23:38:23 +0000650 if (!FunctionSignatureList.empty())
651 throw std::string("Function expected, but bytecode stream ended!");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000652
653 BCR_TRACE(0, "} end block\n\n");
Chris Lattner00950542001-06-06 20:29:01 +0000654}
655
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000656void BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
657 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000658
Misha Brukman12c29d12003-09-22 23:38:23 +0000659 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000660
Chris Lattner00950542001-06-06 20:29:01 +0000661 // Read and check signature...
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000662 unsigned Sig;
Chris Lattner00950542001-06-06 20:29:01 +0000663 if (read(Buf, EndBuf, Sig) ||
Misha Brukman12c29d12003-09-22 23:38:23 +0000664 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
665 throw std::string("Invalid bytecode signature!");
Chris Lattner00950542001-06-06 20:29:01 +0000666
Chris Lattner75f20532003-04-22 18:02:52 +0000667 TheModule = new Module(ModuleID);
Misha Brukman12c29d12003-09-22 23:38:23 +0000668 try {
Chris Lattnercb7e2e22003-10-18 05:54:18 +0000669 usesOldStyleVarargs = false;
Misha Brukman12c29d12003-09-22 23:38:23 +0000670 ParseModule(Buf, EndBuf);
671 } catch (std::string &Error) {
Chris Lattnera2602f32003-05-22 18:26:48 +0000672 freeState(); // Must destroy handles before deleting module!
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000673 delete TheModule;
674 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +0000675 throw;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000676 }
Chris Lattner00950542001-06-06 20:29:01 +0000677}