Eliminate duplicate or unneccesary #include's
[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 // threadsafe!!
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "ReaderInternals.h"
12 #include "llvm/Module.h"
13 #include "llvm/Constants.h"
14 #include "llvm/GlobalVariable.h"
15 #include <algorithm>
16 #include <iostream>
17 using std::make_pair;
18 using std::cerr;
19
20 const Type *BytecodeParser::parseTypeConstant(const uchar *&Buf,
21                                               const uchar *EndBuf) {
22   unsigned PrimType;
23   if (read_vbr(Buf, EndBuf, PrimType)) return failure<const Type*>(0);
24
25   const Type *Val = 0;
26   if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
27     return Val;
28   
29   switch (PrimType) {
30   case Type::FunctionTyID: {
31     unsigned Typ;
32     if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
33     const Type *RetType = getType(Typ);
34     if (RetType == 0) return failure(Val);
35
36     unsigned NumParams;
37     if (read_vbr(Buf, EndBuf, NumParams)) return failure(Val);
38
39     std::vector<const Type*> Params;
40     while (NumParams--) {
41       if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
42       const Type *Ty = getType(Typ);
43       if (Ty == 0) return failure(Val);
44       Params.push_back(Ty);
45     }
46
47     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
48     if (isVarArg) Params.pop_back();
49
50     return FunctionType::get(RetType, Params, isVarArg);
51   }
52   case Type::ArrayTyID: {
53     unsigned ElTyp;
54     if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
55     const Type *ElementType = getType(ElTyp);
56     if (ElementType == 0) return failure(Val);
57
58     unsigned NumElements;
59     if (read_vbr(Buf, EndBuf, NumElements)) return failure(Val);
60
61     BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size=" 
62               << NumElements << "\n");
63     return ArrayType::get(ElementType, NumElements);
64   }
65   case Type::StructTyID: {
66     unsigned Typ;
67     std::vector<const Type*> Elements;
68
69     if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
70     while (Typ) {         // List is terminated by void/0 typeid
71       const Type *Ty = getType(Typ);
72       if (Ty == 0) return failure(Val);
73       Elements.push_back(Ty);
74       
75       if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
76     }
77
78     return StructType::get(Elements);
79   }
80   case Type::PointerTyID: {
81     unsigned ElTyp;
82     if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
83     BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << "\n");
84     const Type *ElementType = getType(ElTyp);
85     if (ElementType == 0) return failure(Val);
86     return PointerType::get(ElementType);
87   }
88
89   case Type::OpaqueTyID: {
90     return OpaqueType::get();
91   }
92
93   default:
94     cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to deserialize"
95          << " primitive Type " << PrimType << "\n";
96     return failure(Val);
97   }
98 }
99
100 // refineAbstractType - The callback method is invoked when one of the
101 // elements of TypeValues becomes more concrete...
102 //
103 void BytecodeParser::refineAbstractType(const DerivedType *OldType, 
104                                         const Type *NewType) {
105   if (OldType == NewType &&
106       OldType->isAbstract()) return;  // Type is modified, but same
107
108   TypeValuesListTy::iterator I = find(MethodTypeValues.begin(), 
109                                       MethodTypeValues.end(), OldType);
110   if (I == MethodTypeValues.end()) {
111     I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
112     assert(I != ModuleTypeValues.end() && 
113            "Can't refine a type I don't know about!");
114   }
115
116   if (OldType == NewType) {
117     assert(!OldType->isAbstract());
118     I->removeUserFromConcrete();
119   } else {
120     *I = NewType;  // Update to point to new, more refined type.
121   }
122 }
123
124
125
126 // parseTypeConstants - We have to use this wierd code to handle recursive
127 // types.  We know that recursive types will only reference the current slab of
128 // values in the type plane, but they can forward reference types before they
129 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
130 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
131 // this ugly problem, we pesimistically insert an opaque type for each type we
132 // are about to read.  This means that forward references will resolve to
133 // something and when we reread the type later, we can replace the opaque type
134 // with a new resolved concrete type.
135 //
136 void debug_type_tables();
137 bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
138                                         TypeValuesListTy &Tab,
139                                         unsigned NumEntries) {
140   assert(Tab.size() == 0 && "should not have read type constants in before!");
141
142   // Insert a bunch of opaque types to be resolved later...
143   for (unsigned i = 0; i < NumEntries; ++i)
144     Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));
145
146   // Loop through reading all of the types.  Forward types will make use of the
147   // opaque types just inserted.
148   //
149   for (unsigned i = 0; i < NumEntries; ++i) {
150     const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
151     if (NewTy == 0) return failure(true);
152     BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
153               "' Replacing: " << OldTy << "\n");
154
155     // Don't insertValue the new type... instead we want to replace the opaque
156     // type with the new concrete value...
157     //
158
159     // Refine the abstract type to the new type.  This causes all uses of the
160     // abstract type to use the newty.  This also will cause the opaque type
161     // to be deleted...
162     //
163     cast<DerivedType>(Tab[i].get())->refineAbstractTypeTo(NewTy);
164
165     // This should have replace the old opaque type with the new type in the
166     // value table... or with a preexisting type that was already in the system
167     assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
168   }
169
170   BCR_TRACE(5, "Resulting types:\n");
171   for (unsigned i = 0; i < NumEntries; ++i) {
172     BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
173   }
174   debug_type_tables();
175   return false;
176 }
177
178
179 bool BytecodeParser::parseConstantValue(const uchar *&Buf, const uchar *EndBuf,
180                                         const Type *Ty, Constant *&V) {
181   switch (Ty->getPrimitiveID()) {
182   case Type::BoolTyID: {
183     unsigned Val;
184     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
185     if (Val != 0 && Val != 1) return failure(true);
186     V = ConstantBool::get(Val == 1);
187     break;
188   }
189
190   case Type::UByteTyID:   // Unsigned integer types...
191   case Type::UShortTyID:
192   case Type::UIntTyID: {
193     unsigned Val;
194     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
195     if (!ConstantUInt::isValueValidForType(Ty, Val)) return failure(true);
196     V = ConstantUInt::get(Ty, Val);
197     break;
198   }
199
200   case Type::ULongTyID: {
201     uint64_t Val;
202     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
203     V = ConstantUInt::get(Ty, Val);
204     break;
205   }
206
207   case Type::SByteTyID:   // Unsigned integer types...
208   case Type::ShortTyID:
209   case Type::IntTyID: {
210     int Val;
211     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
212     if (!ConstantSInt::isValueValidForType(Ty, Val)) return failure(true);
213     V = ConstantSInt::get(Ty, Val);
214     break;
215   }
216
217   case Type::LongTyID: {
218     int64_t Val;
219     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
220     V = ConstantSInt::get(Ty, Val);
221     break;
222   }
223
224   case Type::FloatTyID: {
225     float F;
226     if (input_data(Buf, EndBuf, &F, &F+1)) return failure(true);
227     V = ConstantFP::get(Ty, F);
228     break;
229   }
230
231   case Type::DoubleTyID: {
232     double Val;
233     if (input_data(Buf, EndBuf, &Val, &Val+1)) return failure(true);
234     V = ConstantFP::get(Ty, Val);
235     break;
236   }
237
238   case Type::TypeTyID:
239     assert(0 && "Type constants should be handled seperately!!!");
240     abort();
241
242   case Type::ArrayTyID: {
243     const ArrayType *AT = cast<const ArrayType>(Ty);
244     unsigned NumElements = AT->getNumElements();
245
246     std::vector<Constant*> Elements;
247     while (NumElements--) {   // Read all of the elements of the constant.
248       unsigned Slot;
249       if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
250       Value *V = getValue(AT->getElementType(), Slot, false);
251       if (!V || !isa<Constant>(V)) return failure(true);
252       Elements.push_back(cast<Constant>(V));
253     }
254     V = ConstantArray::get(AT, Elements);
255     break;
256   }
257
258   case Type::StructTyID: {
259     const StructType *ST = cast<StructType>(Ty);
260     const StructType::ElementTypes &ET = ST->getElementTypes();
261
262     std::vector<Constant *> Elements;
263     for (unsigned i = 0; i < ET.size(); ++i) {
264       unsigned Slot;
265       if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
266       Value *V = getValue(ET[i], Slot, false);
267       if (!V || !isa<Constant>(V))
268         return failure(true);
269       Elements.push_back(cast<Constant>(V));      
270     }
271
272     V = ConstantStruct::get(ST, Elements);
273     break;
274   }    
275
276   case Type::PointerTyID: {
277     const PointerType *PT = cast<const PointerType>(Ty);
278     unsigned SubClass;
279     if (read_vbr(Buf, EndBuf, SubClass)) return failure(true);
280     switch (SubClass) {
281     case 0:    // ConstantPointerNull value...
282       V = ConstantPointerNull::get(PT);
283       break;
284
285     case 1: {  // ConstantPointerRef value...
286       unsigned Slot;
287       if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
288       BCR_TRACE(4, "CPPR: Type: '" << Ty << "'  slot: " << Slot << "\n");
289
290       // Check to see if we have already read this global variable yet...
291       Value *Val = getValue(PT, Slot, false);
292       GlobalValue *GV;
293       if (Val) {
294         if (!(GV = dyn_cast<GlobalValue>(Val))) return failure(true);
295         BCR_TRACE(5, "Value Found in ValueTable!\n");
296       } else {         // Nope... see if we have previously forward ref'd it
297         GlobalRefsType::iterator I = GlobalRefs.find(make_pair(PT, Slot));
298         if (I != GlobalRefs.end()) {
299           BCR_TRACE(5, "Previous forward ref found!\n");
300           GV = I->second;
301         } else {
302           BCR_TRACE(5, "Creating new forward ref variable!\n");
303
304           // Create a placeholder for the global variable reference...
305           GlobalVariable *GVar =
306             new GlobalVariable(PT->getElementType(), false, true);
307
308           // Keep track of the fact that we have a forward ref to recycle it
309           GlobalRefs.insert(make_pair(make_pair(PT, Slot), GVar));
310
311           // Must temporarily push this value into the module table...
312           TheModule->getGlobalList().push_back(GVar);
313           GV = GVar;
314         }
315       }
316       
317       V = ConstantPointerRef::get(GV);
318       break;
319     }
320     default:
321       BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
322       return failure(true);
323     }
324     break;
325   }
326
327   default:
328     cerr << __FILE__ << ":" << __LINE__ 
329          << ": Don't know how to deserialize constant value of type '"
330          << Ty->getName() << "'\n";
331     return failure(true);
332   }
333
334   return false;
335 }
336
337 bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
338                                        ValueTable &Tab, 
339                                        TypeValuesListTy &TypeTab) {
340   while (Buf < EndBuf) {
341     unsigned NumEntries, Typ;
342
343     if (read_vbr(Buf, EndBuf, NumEntries) ||
344         read_vbr(Buf, EndBuf, Typ)) return failure(true);
345     const Type *Ty = getType(Typ);
346     if (Ty == 0) return failure(true);
347     BCR_TRACE(3, "Type: '" << Ty << "'  NumEntries: " << NumEntries << "\n");
348
349     if (Typ == Type::TypeTyID) {
350       if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
351     } else {
352       for (unsigned i = 0; i < NumEntries; ++i) {
353         Constant *I;
354         if (parseConstantValue(Buf, EndBuf, Ty, I)) return failure(true);
355         BCR_TRACE(4, "Read Constant: '" << I << "'\n");
356         if (insertValue(I, Tab) == -1) return failure(true);
357       }
358     }
359   }
360   
361   if (Buf > EndBuf) return failure(true);
362   return false;
363 }