Add support for reading ConstantExpr nodes.
[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
18 using std::make_pair;
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     std::cerr << __FILE__ << ":" << __LINE__
95               << ": Don't know how to deserialize"
96               << " primitive Type " << PrimType << "\n";
97     return failure(Val);
98   }
99 }
100
101 // refineAbstractType - The callback method is invoked when one of the
102 // elements of TypeValues becomes more concrete...
103 //
104 void BytecodeParser::refineAbstractType(const DerivedType *OldType, 
105                                         const Type *NewType) {
106   if (OldType == NewType &&
107       OldType->isAbstract()) return;  // Type is modified, but same
108
109   TypeValuesListTy::iterator I = find(MethodTypeValues.begin(), 
110                                       MethodTypeValues.end(), OldType);
111   if (I == MethodTypeValues.end()) {
112     I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
113     assert(I != ModuleTypeValues.end() && 
114            "Can't refine a type I don't know about!");
115   }
116
117   if (OldType == NewType) {
118     assert(!OldType->isAbstract());
119     I->removeUserFromConcrete();
120   } else {
121     *I = NewType;  // Update to point to new, more refined type.
122   }
123 }
124
125
126
127 // parseTypeConstants - We have to use this wierd code to handle recursive
128 // types.  We know that recursive types will only reference the current slab of
129 // values in the type plane, but they can forward reference types before they
130 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
131 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
132 // this ugly problem, we pesimistically insert an opaque type for each type we
133 // are about to read.  This means that forward references will resolve to
134 // something and when we reread the type later, we can replace the opaque type
135 // with a new resolved concrete type.
136 //
137 void debug_type_tables();
138 bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
139                                         TypeValuesListTy &Tab,
140                                         unsigned NumEntries) {
141   assert(Tab.size() == 0 && "should not have read type constants in before!");
142
143   // Insert a bunch of opaque types to be resolved later...
144   for (unsigned i = 0; i < NumEntries; ++i)
145     Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));
146
147   // Loop through reading all of the types.  Forward types will make use of the
148   // opaque types just inserted.
149   //
150   for (unsigned i = 0; i < NumEntries; ++i) {
151     const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
152     if (NewTy == 0) return failure(true);
153     BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
154               "' Replacing: " << OldTy << "\n");
155
156     // Don't insertValue the new type... instead we want to replace the opaque
157     // type with the new concrete value...
158     //
159
160     // Refine the abstract type to the new type.  This causes all uses of the
161     // abstract type to use the newty.  This also will cause the opaque type
162     // to be deleted...
163     //
164     ((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
165
166     // This should have replace the old opaque type with the new type in the
167     // value table... or with a preexisting type that was already in the system
168     assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
169   }
170
171   BCR_TRACE(5, "Resulting types:\n");
172   for (unsigned i = 0; i < NumEntries; ++i) {
173     BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
174   }
175   debug_type_tables();
176   return false;
177 }
178
179
180 bool BytecodeParser::parseConstantValue(const uchar *&Buf, const uchar *EndBuf,
181                                         const Type *Ty, Constant *&V) {
182
183   // We must check for a ConstantExpr before switching by type because
184   // a ConstantExpr can be of any type, and has no explicit value.
185   // 
186   unsigned isExprNumArgs;               // 0 if not expr; numArgs if is expr
187   if (read_vbr(Buf, EndBuf, isExprNumArgs)) return failure(true);
188   if (isExprNumArgs) {
189     unsigned opCode;
190     vector<Constant*> argVec;
191     argVec.reserve(isExprNumArgs);
192     
193     if (read_vbr(Buf, EndBuf, opCode)) return failure(true);
194     
195     // Read the slot number and types of each of the arguments
196     for (unsigned i=0; i < isExprNumArgs; ++i) {
197       unsigned argValSlot, argTypeSlot;
198       if (read_vbr(Buf, EndBuf, argValSlot)) return failure(true);
199       if (read_vbr(Buf, EndBuf, argTypeSlot)) return failure(true);
200       const Type *argTy = getType(argTypeSlot);
201       if (argTy == 0) return failure(true);
202       
203       BCR_TRACE(4, "CE Arg " << i << ": Type: '" << argTy << "'  slot: " << argValSlot << "\n");
204       
205       // Get the arg value from its slot if it exists, otherwise a placeholder
206       Value *Val = getValue(argTy, argValSlot, false);
207       Constant* C;
208       if (Val) {
209         if (!(C = dyn_cast<Constant>(Val))) return failure(true);
210         BCR_TRACE(5, "Constant Found in ValueTable!\n");
211       } else {         // Nope... find or create a forward ref. for it
212         C = fwdRefs.GetFwdRefToConstant(argTy, argValSlot);
213       }
214       argVec.push_back(C);
215     }
216     
217     // Construct a ConstantExpr of the appropriate kind
218     if (isExprNumArgs == 1) {           // All one-operand expressions
219       V = ConstantExpr::get(opCode, argVec[0], Ty);
220     } else if (opCode == Instruction::GetElementPtr) { // GetElementPtr
221       vector<Value*> IdxList(argVec.begin()+1, argVec.end());
222       V = ConstantExpr::get(opCode, argVec[0], IdxList, Ty);
223     } else {                            // All other 2-operand expressions
224       V = ConstantExpr::get(opCode, argVec[0], argVec[1], Ty);
225     }
226     return false;
227   }
228   
229   // Ok, not an ConstantExpr.  We now know how to read the given type...
230   switch (Ty->getPrimitiveID()) {
231   case Type::BoolTyID: {
232     unsigned Val;
233     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
234     if (Val != 0 && Val != 1) return failure(true);
235     V = ConstantBool::get(Val == 1);
236     break;
237   }
238
239   case Type::UByteTyID:   // Unsigned integer types...
240   case Type::UShortTyID:
241   case Type::UIntTyID: {
242     unsigned Val;
243     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
244     if (!ConstantUInt::isValueValidForType(Ty, Val)) return failure(true);
245     V = ConstantUInt::get(Ty, Val);
246     break;
247   }
248
249   case Type::ULongTyID: {
250     uint64_t Val;
251     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
252     V = ConstantUInt::get(Ty, Val);
253     break;
254   }
255
256   case Type::SByteTyID:   // Unsigned integer types...
257   case Type::ShortTyID:
258   case Type::IntTyID: {
259     int Val;
260     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
261     if (!ConstantSInt::isValueValidForType(Ty, Val)) return failure(true);
262     V = ConstantSInt::get(Ty, Val);
263     break;
264   }
265
266   case Type::LongTyID: {
267     int64_t Val;
268     if (read_vbr(Buf, EndBuf, Val)) return failure(true);
269     V = ConstantSInt::get(Ty, Val);
270     break;
271   }
272
273   case Type::FloatTyID: {
274     float F;
275     if (input_data(Buf, EndBuf, &F, &F+1)) return failure(true);
276     V = ConstantFP::get(Ty, F);
277     break;
278   }
279
280   case Type::DoubleTyID: {
281     double Val;
282     if (input_data(Buf, EndBuf, &Val, &Val+1)) return failure(true);
283     V = ConstantFP::get(Ty, Val);
284     break;
285   }
286
287   case Type::TypeTyID:
288     assert(0 && "Type constants should be handled seperately!!!");
289     abort();
290
291   case Type::ArrayTyID: {
292     const ArrayType *AT = cast<const ArrayType>(Ty);
293     unsigned NumElements = AT->getNumElements();
294
295     std::vector<Constant*> Elements;
296     while (NumElements--) {   // Read all of the elements of the constant.
297       unsigned Slot;
298       if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
299       Value *V = getValue(AT->getElementType(), Slot, false);
300       if (!V || !isa<Constant>(V)) return failure(true);
301       Elements.push_back(cast<Constant>(V));
302     }
303     V = ConstantArray::get(AT, Elements);
304     break;
305   }
306
307   case Type::StructTyID: {
308     const StructType *ST = cast<StructType>(Ty);
309     const StructType::ElementTypes &ET = ST->getElementTypes();
310
311     std::vector<Constant *> Elements;
312     for (unsigned i = 0; i < ET.size(); ++i) {
313       unsigned Slot;
314       if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
315       Value *V = getValue(ET[i], Slot, false);
316       if (!V || !isa<Constant>(V))
317         return failure(true);
318       Elements.push_back(cast<Constant>(V));      
319     }
320
321     V = ConstantStruct::get(ST, Elements);
322     break;
323   }    
324
325   case Type::PointerTyID: {
326     const PointerType *PT = cast<const PointerType>(Ty);
327     unsigned SubClass;
328     if (read_vbr(Buf, EndBuf, SubClass)) return failure(true);
329     switch (SubClass) {
330     case 0:    // ConstantPointerNull value...
331       V = ConstantPointerNull::get(PT);
332       break;
333
334     case 1: {  // ConstantPointerRef value...
335       unsigned Slot;
336       if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
337       BCR_TRACE(4, "CPR: Type: '" << Ty << "'  slot: " << Slot << "\n");
338
339       // Check to see if we have already read this global variable yet...
340       Value *Val = getValue(PT, Slot, false);
341       GlobalValue* GV;
342       if (Val) {
343         if (!(GV = dyn_cast<GlobalValue>(Val))) return failure(true);
344         BCR_TRACE(5, "Value Found in ValueTable!\n");
345       } else {         // Nope... find or create a forward ref. for it
346         GV = fwdRefs.GetFwdRefToGlobal(PT, Slot);
347       }
348       V = ConstantPointerRef::get(GV);
349       break;
350     }
351     
352     default:
353       BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
354       return failure(true);
355     }
356     break;
357   }
358
359   default:
360     std::cerr << __FILE__ << ":" << __LINE__ 
361               << ": Don't know how to deserialize constant value of type '"
362               << Ty->getName() << "'\n";
363     return failure(true);
364   }
365
366   return false;
367 }
368
369 bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
370                                        ValueTable &Tab, 
371                                        TypeValuesListTy &TypeTab) {
372   while (Buf < EndBuf) {
373     unsigned NumEntries, Typ;
374
375     if (read_vbr(Buf, EndBuf, NumEntries) ||
376         read_vbr(Buf, EndBuf, Typ)) return failure(true);
377     const Type *Ty = getType(Typ);
378     if (Ty == 0) return failure(true);
379     BCR_TRACE(3, "Type: '" << Ty << "'  NumEntries: " << NumEntries << "\n");
380
381     if (Typ == Type::TypeTyID) {
382       if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
383     } else {
384       for (unsigned i = 0; i < NumEntries; ++i) {
385         Constant *I;
386         int Slot;
387         if (parseConstantValue(Buf, EndBuf, Ty, I)) return failure(true);
388         assert(I && "parseConstantValue returned `!failure' and NULL result");
389         BCR_TRACE(4, "Read Constant: '" << I << "'\n");
390         if ((Slot = insertValue(I, Tab)) < 0) return failure(true);
391         resolveRefsToConstant(I, (unsigned) Slot);
392       }
393     }
394   }
395   
396   if (Buf > EndBuf) return failure(true);
397   return false;
398 }