Implement constant pointers, and null specifically in the parser, bytecode writer...
[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 "llvm/Module.h"
12 #include "llvm/BasicBlock.h"
13 #include "llvm/ConstPoolVals.h"
14 #include "llvm/DerivedTypes.h"
15 #include "ReaderInternals.h"
16 #include <algorithm>
17
18
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::MethodTyID: {
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     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     Val = MethodType::get(RetType, Params);
48     break;
49   }
50   case Type::ArrayTyID: {
51     unsigned ElTyp;
52     if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
53     const Type *ElementType = getType(ElTyp);
54     if (ElementType == 0) return failure(Val);
55
56     int NumElements;
57     if (read_vbr(Buf, EndBuf, NumElements)) return failure(Val);
58     Val = ArrayType::get(ElementType, NumElements);
59     break;
60   }
61   case Type::StructTyID: {
62     unsigned Typ;
63     vector<const Type*> Elements;
64
65     if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
66     while (Typ) {         // List is terminated by void/0 typeid
67       const Type *Ty = getType(Typ);
68       if (Ty == 0) return failure(Val);
69       Elements.push_back(Ty);
70       
71       if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
72     }
73
74     Val = StructType::get(Elements);
75     break;
76   }
77   case Type::PointerTyID: {
78     unsigned ElTyp;
79     if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
80     const Type *ElementType = getType(ElTyp);
81     if (ElementType == 0) return failure(Val);
82     Val = PointerType::get(ElementType);
83     break;
84   }
85
86   default:
87     cerr << __FILE__ << ":" << __LINE__ << ": Don't know how to deserialize"
88          << " primitive Type " << PrimType << "\n";
89     return failure(Val);
90   }
91
92   return Val;
93 }
94
95 // refineAbstractType - The callback method is invoked when one of the
96 // elements of TypeValues becomes more concrete...
97 //
98 void BytecodeParser::refineAbstractType(const DerivedType *OldType, 
99                                         const Type *NewType) {
100   TypeValuesListTy::iterator I = find(MethodTypeValues.begin(), 
101                                       MethodTypeValues.end(), OldType);
102   if (I == MethodTypeValues.end()) {
103     I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
104     assert(I != ModuleTypeValues.end() && 
105            "Can't refine a type I don't know about!");
106   }
107
108   *I = NewType;  // Update to point to new, more refined type.
109 }
110
111
112
113 // parseTypeConstants - We have to use this wierd code to handle recursive
114 // types.  We know that recursive types will only reference the current slab of
115 // values in the type plane, but they can forward reference types before they
116 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
117 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
118 // this ugly problem, we pesimistically insert an opaque type for each type we
119 // are about to read.  This means that forward references will resolve to
120 // something and when we reread the type later, we can replace the opaque type
121 // with a new resolved concrete type.
122 //
123 bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
124                                         TypeValuesListTy &Tab,
125                                         unsigned NumEntries) {
126   assert(Tab.size() == 0 && "I think table should always be empty here!"
127          "This should simplify later code");
128
129   // Record the base, starting level that we will begin with.
130   unsigned BaseLevel = Tab.size();
131
132   // Insert a bunch of opaque types to be resolved later...
133   for (unsigned i = 0; i < NumEntries; i++)
134     Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));
135
136   // Loop through reading all of the types.  Forward types will make use of the
137   // opaque types just inserted.
138   //
139   for (unsigned i = 0; i < NumEntries; i++) {
140     const Type *NewTy = parseTypeConstant(Buf, EndBuf);
141     if (NewTy == 0) return failure(true);
142     BCR_TRACE(4, "Read Type Constant: '" << NewTy << "'\n");
143
144     // Don't insertValue the new type... instead we want to replace the opaque
145     // type with the new concrete value...
146     //
147
148     // Refine the abstract type to the new type.  This causes all uses of the
149     // abstract type to use the newty.  This also will cause the opaque type
150     // to be deleted...
151     //
152     // FIXME when types are not const
153     const_cast<DerivedType*>(Tab[i+BaseLevel]->castDerivedTypeAsserting())->refineAbstractTypeTo(NewTy);
154
155     // This should have replace the old opaque type with the new type in the
156     // value table...
157     assert(Tab[i+BaseLevel] == NewTy && "refineAbstractType didn't work!");
158   }
159
160   BCR_TRACE(5, "Resulting types:\n");
161   for (unsigned i = 0; i < NumEntries; i++) {
162     BCR_TRACE(5, Tab[i+BaseLevel]->castTypeAsserting() << "\n");
163   }
164   return false;
165 }
166
167
168 bool BytecodeParser::parseConstPoolValue(const uchar *&Buf, 
169                                          const uchar *EndBuf,
170                                          const Type *Ty, ConstPoolVal *&V) {
171   switch (Ty->getPrimitiveID()) {
172   case Type::BoolTyID: {
173     unsigned Val;
174     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
175     if (Val != 0 && Val != 1) return failure(true);
176     V = ConstPoolBool::get(Val == 1);
177     break;
178   }
179
180   case Type::UByteTyID:   // Unsigned integer types...
181   case Type::UShortTyID:
182   case Type::UIntTyID: {
183     unsigned Val;
184     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
185     if (!ConstPoolUInt::isValueValidForType(Ty, Val)) return failure(true);
186     V = ConstPoolUInt::get(Ty, Val);
187     break;
188   }
189
190   case Type::ULongTyID: {
191     uint64_t Val;
192     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
193     V = ConstPoolUInt::get(Ty, Val);
194     break;
195   }
196
197   case Type::SByteTyID:   // Unsigned integer types...
198   case Type::ShortTyID:
199   case Type::IntTyID: {
200     int Val;
201     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
202     if (!ConstPoolSInt::isValueValidForType(Ty, Val)) return failure(true);
203     V = ConstPoolSInt::get(Ty, Val);
204     break;
205   }
206
207   case Type::LongTyID: {
208     int64_t Val;
209     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
210     V = ConstPoolSInt::get(Ty, Val);
211     break;
212   }
213
214   case Type::FloatTyID: {
215     float F;
216     if (input_data(Buf, EndBuf, &F, &F+1)) return failure(true);
217     V = ConstPoolFP::get(Ty, F);
218     break;
219   }
220
221   case Type::DoubleTyID: {
222     double Val;
223     if (input_data(Buf, EndBuf, &Val, &Val+1)) return failure(true);
224     V = ConstPoolFP::get(Ty, Val);
225     break;
226   }
227
228   case Type::TypeTyID:
229     assert(0 && "Type constants should be handled seperately!!!");
230     abort();
231
232   case Type::ArrayTyID: {
233     const ArrayType *AT = (const ArrayType*)Ty;
234     unsigned NumElements;
235     if (AT->isSized())          // Sized array, # elements stored in type!
236       NumElements = (unsigned)AT->getNumElements();
237     else                        // Unsized array, # elements stored in stream!
238       if (read_vbr(Buf, EndBuf, NumElements)) return failure(true);
239
240     vector<ConstPoolVal *> Elements;
241     while (NumElements--) {   // Read all of the elements of the constant.
242       unsigned Slot;
243       if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
244       Value *V = getValue(AT->getElementType(), Slot, false);
245       if (!V || !V->isConstant()) return failure(true);
246       Elements.push_back((ConstPoolVal*)V);
247     }
248     V = ConstPoolArray::get(AT, Elements);
249     break;
250   }
251
252   case Type::StructTyID: {
253     const StructType *ST = Ty->castStructType();
254     const StructType::ElementTypes &ET = ST->getElementTypes();
255
256     vector<ConstPoolVal *> Elements;
257     for (unsigned i = 0; i < ET.size(); ++i) {
258       unsigned Slot;
259       if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
260       Value *V = getValue(ET[i], Slot, false);
261       if (!V || !V->isConstant())
262         return failure(true);
263       Elements.push_back((ConstPoolVal*)V);      
264     }
265
266     V = ConstPoolStruct::get(ST, Elements);
267     break;
268   }    
269
270   case Type::PointerTyID: {
271     const PointerType *PT = Ty->castPointerType();
272     unsigned SubClass;
273     if (read_vbr(Buf, EndBuf, SubClass)) return failure(true);
274     if (SubClass != 0) return failure(true);
275
276
277     V = ConstPoolPointer::getNullPointer(PT);
278     break;
279   }
280
281   default:
282     cerr << __FILE__ << ":" << __LINE__ 
283          << ": Don't know how to deserialize constant value of type '"
284          << Ty->getName() << "'\n";
285     return failure(true);
286   }
287
288   return false;
289 }
290
291 bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
292                                        ValueTable &Tab, 
293                                        TypeValuesListTy &TypeTab) {
294   while (Buf < EndBuf) {
295     unsigned NumEntries, Typ;
296
297     if (read_vbr(Buf, EndBuf, NumEntries) ||
298         read_vbr(Buf, EndBuf, Typ)) return failure(true);
299     const Type *Ty = getType(Typ);
300     if (Ty == 0) return failure(true);
301     BCR_TRACE(3, "Type: '" << Ty << "'  NumEntries: " << NumEntries << "\n");
302
303     if (Typ == Type::TypeTyID) {
304       if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
305     } else {
306       for (unsigned i = 0; i < NumEntries; i++) {
307         ConstPoolVal *I;
308         if (parseConstPoolValue(Buf, EndBuf, Ty, I)) return failure(true);
309         BCR_TRACE(4, "Read Constant: '" << I << "'\n");
310         insertValue(I, Tab);
311       }
312     }
313   }
314   
315   if (Buf > EndBuf) return failure(true);
316   return false;
317 }