There is no need for BytecodeParser to be an AbstractTypeUser. Instead, it
[oota-llvm.git] / lib / Bytecode / Reader / ConstantReader.cpp
1 //===- ReadConst.cpp - Code to constants and constant pools ---------------===//
2 //
3 // This file implements functionality to deserialize constants and entire 
4 // constant pools.
5 // 
6 // Note that this library should be as fast as possible, reentrant, and 
7 // thread-safe!!
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "ReaderInternals.h"
12 #include "llvm/Module.h"
13 #include "llvm/Constants.h"
14 #include <algorithm>
15
16 const Type *BytecodeParser::parseTypeConstant(const unsigned char *&Buf,
17                                               const unsigned char *EndBuf) {
18   unsigned PrimType;
19   if (read_vbr(Buf, EndBuf, PrimType)) throw Error_readvbr;
20
21   const Type *Val = 0;
22   if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
23     return Val;
24   
25   switch (PrimType) {
26   case Type::FunctionTyID: {
27     unsigned Typ;
28     if (read_vbr(Buf, EndBuf, Typ)) return Val;
29     const Type *RetType = getType(Typ);
30     if (RetType == 0) return Val;
31
32     unsigned NumParams;
33     if (read_vbr(Buf, EndBuf, NumParams)) return Val;
34
35     std::vector<const Type*> Params;
36     while (NumParams--) {
37       if (read_vbr(Buf, EndBuf, Typ)) return Val;
38       const Type *Ty = getType(Typ);
39       if (Ty == 0) return Val;
40       Params.push_back(Ty);
41     }
42
43     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
44     if (isVarArg) Params.pop_back();
45
46     return FunctionType::get(RetType, Params, isVarArg);
47   }
48   case Type::ArrayTyID: {
49     unsigned ElTyp;
50     if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
51     const Type *ElementType = getType(ElTyp);
52     if (ElementType == 0) return Val;
53
54     unsigned NumElements;
55     if (read_vbr(Buf, EndBuf, NumElements)) return Val;
56
57     BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size=" 
58               << NumElements << "\n");
59     return ArrayType::get(ElementType, NumElements);
60   }
61   case Type::StructTyID: {
62     unsigned Typ;
63     std::vector<const Type*> Elements;
64
65     if (read_vbr(Buf, EndBuf, Typ)) return Val;
66     while (Typ) {         // List is terminated by void/0 typeid
67       const Type *Ty = getType(Typ);
68       if (Ty == 0) return Val;
69       Elements.push_back(Ty);
70       
71       if (read_vbr(Buf, EndBuf, Typ)) return Val;
72     }
73
74     return StructType::get(Elements);
75   }
76   case Type::PointerTyID: {
77     unsigned ElTyp;
78     if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
79     BCR_TRACE(5, "Pointer Type Constant #" << ElTyp << "\n");
80     const Type *ElementType = getType(ElTyp);
81     if (ElementType == 0) return Val;
82     return PointerType::get(ElementType);
83   }
84
85   case Type::OpaqueTyID: {
86     return OpaqueType::get();
87   }
88
89   default:
90     std::cerr << __FILE__ << ":" << __LINE__
91               << ": Don't know how to deserialize"
92               << " primitive Type " << PrimType << "\n";
93     return Val;
94   }
95 }
96
97 // parseTypeConstants - We have to use this weird code to handle recursive
98 // types.  We know that recursive types will only reference the current slab of
99 // values in the type plane, but they can forward reference types before they
100 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
101 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
102 // this ugly problem, we pessimistically insert an opaque type for each type we
103 // are about to read.  This means that forward references will resolve to
104 // something and when we reread the type later, we can replace the opaque type
105 // with a new resolved concrete type.
106 //
107 void debug_type_tables();
108 void BytecodeParser::parseTypeConstants(const unsigned char *&Buf,
109                                         const unsigned char *EndBuf,
110                                         TypeValuesListTy &Tab,
111                                         unsigned NumEntries) {
112   assert(Tab.size() == 0 && "should not have read type constants in before!");
113
114   // Insert a bunch of opaque types to be resolved later...
115   for (unsigned i = 0; i < NumEntries; ++i)
116     Tab.push_back(OpaqueType::get());
117
118   // Loop through reading all of the types.  Forward types will make use of the
119   // opaque types just inserted.
120   //
121   for (unsigned i = 0; i < NumEntries; ++i) {
122     const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
123     if (NewTy == 0) throw std::string("Parsed invalid type.");
124     BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
125               "' Replacing: " << OldTy << "\n");
126
127     // Don't insertValue the new type... instead we want to replace the opaque
128     // type with the new concrete value...
129     //
130
131     // Refine the abstract type to the new type.  This causes all uses of the
132     // abstract type to use the newty.  This also will cause the opaque type
133     // to be deleted...
134     //
135     ((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
136
137     // This should have replace the old opaque type with the new type in the
138     // value table... or with a preexisting type that was already in the system
139     assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
140   }
141
142   BCR_TRACE(5, "Resulting types:\n");
143   for (unsigned i = 0; i < NumEntries; ++i) {
144     BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
145   }
146   debug_type_tables();
147 }
148
149
150 void BytecodeParser::parseConstantValue(const unsigned char *&Buf,
151                                         const unsigned char *EndBuf,
152                                         const Type *Ty, Constant *&V) {
153
154   // We must check for a ConstantExpr before switching by type because
155   // a ConstantExpr can be of any type, and has no explicit value.
156   // 
157   unsigned isExprNumArgs;               // 0 if not expr; numArgs if is expr
158   if (read_vbr(Buf, EndBuf, isExprNumArgs)) throw Error_readvbr;
159   if (isExprNumArgs) {
160     // FIXME: Encoding of constant exprs could be much more compact!
161     unsigned Opcode;
162     std::vector<Constant*> ArgVec;
163     ArgVec.reserve(isExprNumArgs);
164     if (read_vbr(Buf, EndBuf, Opcode)) throw Error_readvbr;
165
166     // Read the slot number and types of each of the arguments
167     for (unsigned i = 0; i != isExprNumArgs; ++i) {
168       unsigned ArgValSlot, ArgTypeSlot;
169       if (read_vbr(Buf, EndBuf, ArgValSlot)) throw Error_readvbr;
170       if (read_vbr(Buf, EndBuf, ArgTypeSlot)) throw Error_readvbr;
171       const Type *ArgTy = getType(ArgTypeSlot);
172       if (ArgTy == 0) throw std::string("Argument type slot not found.");
173       
174       BCR_TRACE(4, "CE Arg " << i << ": Type: '" << ArgTy << "'  slot: "
175                 << ArgValSlot << "\n");
176       
177       // Get the arg value from its slot if it exists, otherwise a placeholder
178       Constant *C = getConstantValue(ArgTy, ArgValSlot);
179       if (C == 0) throw std::string("No arg value or placeholder found.");
180       ArgVec.push_back(C);
181     }
182     
183     // Construct a ConstantExpr of the appropriate kind
184     if (isExprNumArgs == 1) {           // All one-operand expressions
185       assert(Opcode == Instruction::Cast);
186       V = ConstantExpr::getCast(ArgVec[0], Ty);
187     } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
188       std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
189       V = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
190     } else {                            // All other 2-operand expressions
191       V = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
192     }
193     return;
194   }
195   
196   // Ok, not an ConstantExpr.  We now know how to read the given type...
197   switch (Ty->getPrimitiveID()) {
198   case Type::BoolTyID: {
199     unsigned Val;
200     if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
201     if (Val != 0 && Val != 1) throw std::string("Invalid boolean value read.");
202     V = ConstantBool::get(Val == 1);
203     break;
204   }
205
206   case Type::UByteTyID:   // Unsigned integer types...
207   case Type::UShortTyID:
208   case Type::UIntTyID: {
209     unsigned Val;
210     if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
211     if (!ConstantUInt::isValueValidForType(Ty, Val)) 
212       throw std::string("Invalid unsigned byte/short/int read.");
213     V = ConstantUInt::get(Ty, Val);
214     break;
215   }
216
217   case Type::ULongTyID: {
218     uint64_t Val;
219     if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
220     V = ConstantUInt::get(Ty, Val);
221     break;
222   }
223
224   case Type::SByteTyID:   // Signed integer types...
225   case Type::ShortTyID:
226   case Type::IntTyID: {
227   case Type::LongTyID:
228     int64_t Val;
229     if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
230     if (!ConstantSInt::isValueValidForType(Ty, Val)) 
231       throw std::string("Invalid signed byte/short/int/long read.");
232     V = ConstantSInt::get(Ty, Val);
233     break;
234   }
235
236   case Type::FloatTyID: {
237     float F;
238     if (input_data(Buf, EndBuf, &F, &F+1)) throw Error_inputdata;
239     V = ConstantFP::get(Ty, F);
240     break;
241   }
242
243   case Type::DoubleTyID: {
244     double Val;
245     if (input_data(Buf, EndBuf, &Val, &Val+1)) throw Error_inputdata;
246     V = ConstantFP::get(Ty, Val);
247     break;
248   }
249
250   case Type::TypeTyID:
251     assert(0 && "Type constants should be handled separately!!!");
252     abort();
253
254   case Type::ArrayTyID: {
255     const ArrayType *AT = cast<ArrayType>(Ty);
256     unsigned NumElements = AT->getNumElements();
257
258     std::vector<Constant*> Elements;
259     while (NumElements--) {   // Read all of the elements of the constant.
260       unsigned Slot;
261       if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
262       Constant *C = getConstantValue(AT->getElementType(), Slot);
263       if (!C) throw std::string("Unable to get const value of array slot.");
264       Elements.push_back(C);
265     }
266     V = ConstantArray::get(AT, Elements);
267     break;
268   }
269
270   case Type::StructTyID: {
271     const StructType *ST = cast<StructType>(Ty);
272     const StructType::ElementTypes &ET = ST->getElementTypes();
273
274     std::vector<Constant *> Elements;
275     for (unsigned i = 0; i < ET.size(); ++i) {
276       unsigned Slot;
277       if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
278       Constant *C = getConstantValue(ET[i], Slot);
279       if (!C) throw std::string("Could not read const value in struct slot.");
280       Elements.push_back(C);
281     }
282
283     V = ConstantStruct::get(ST, Elements);
284     break;
285   }    
286
287   case Type::PointerTyID: {
288     const PointerType *PT = cast<PointerType>(Ty);
289     unsigned SubClass;
290     if (HasImplicitZeroInitializer)
291       SubClass = 1;
292     else
293       if (read_vbr(Buf, EndBuf, SubClass)) throw Error_readvbr;
294
295     switch (SubClass) {
296     case 0:    // ConstantPointerNull value...
297       V = ConstantPointerNull::get(PT);
298       break;
299
300     case 1: {  // ConstantPointerRef value...
301       unsigned Slot;
302       if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
303       BCR_TRACE(4, "CPR: Type: '" << Ty << "'  slot: " << Slot << "\n");
304
305       // Check to see if we have already read this global variable...
306       Value *Val = getValue(PT, Slot, false);
307       GlobalValue *GV;
308       if (Val) {
309         if (!(GV = dyn_cast<GlobalValue>(Val))) 
310           throw std::string("Value of ConstantPointerRef not in ValueTable!");
311         BCR_TRACE(5, "Value Found in ValueTable!\n");
312       } else if (RevisionNum > 0) {
313         // Revision #0 could have forward references to globals that were weird.
314         // We got rid of this in subsequent revs.
315         throw std::string("Forward references to globals not allowed.");
316       } else {         // Nope... find or create a forward ref. for it
317         GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
318
319         if (I != GlobalRefs.end()) {
320           BCR_TRACE(5, "Previous forward ref found!\n");
321           GV = cast<GlobalValue>(I->second);
322         } else {
323           BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
324           
325           // Create a placeholder for the global variable reference...
326           GlobalVariable *GVar =
327             new GlobalVariable(PT->getElementType(), false,
328                                GlobalValue::InternalLinkage);
329           
330           // Keep track of the fact that we have a forward ref to recycle it
331           GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
332           
333           // Must temporarily push this value into the module table...
334           TheModule->getGlobalList().push_back(GVar);
335           GV = GVar;
336         }
337       }
338
339       V = ConstantPointerRef::get(GV);
340       break;
341     }
342     
343     default:
344       BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
345       throw std::string("Unknown pointer constant type.");
346     }
347     break;
348   }
349
350   default:
351     std::cerr << __FILE__ << ":" << __LINE__ 
352               << ": Don't know how to deserialize constant value of type '"
353               << Ty->getName() << "'\n";
354     throw std::string("Don't know how to deserialize constant value of type '"+
355                       Ty->getName());
356   }
357 }
358
359 void BytecodeParser::ParseGlobalTypes(const unsigned char *&Buf,
360                                       const unsigned char *EndBuf) {
361   ValueTable T;
362   ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
363 }
364
365 void BytecodeParser::ParseConstantPool(const unsigned char *&Buf,
366                                        const unsigned char *EndBuf,
367                                        ValueTable &Tab, 
368                                        TypeValuesListTy &TypeTab) {
369   while (Buf < EndBuf) {
370     unsigned NumEntries, Typ;
371
372     if (read_vbr(Buf, EndBuf, NumEntries) ||
373         read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
374     const Type *Ty = getType(Typ);
375     if (Ty == 0) throw std::string("Invalid type read.");
376     BCR_TRACE(3, "Type: '" << Ty << "'  NumEntries: " << NumEntries << "\n");
377
378     if (Typ == Type::TypeTyID) {
379       parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries);
380     } else {
381       for (unsigned i = 0; i < NumEntries; ++i) {
382         Constant *C;
383         int Slot;
384         parseConstantValue(Buf, EndBuf, Ty, C);
385         assert(C && "parseConstantValue returned NULL!");
386         BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
387         if ((Slot = insertValue(C, Tab)) == -1)
388           throw std::string("Could not insert value into ValueTable.");
389
390         // If we are reading a function constant table, make sure that we adjust
391         // the slot number to be the real global constant number.
392         //
393         if (&Tab != &ModuleValues && Typ < ModuleValues.size())
394           Slot += ModuleValues[Typ]->size();
395         ResolveReferencesToValue(C, (unsigned)Slot);
396       }
397     }
398   }
399   
400   if (Buf > EndBuf) throw std::string("Read past end of buffer.");
401 }