This debugging hook is no longer needed.
[oota-llvm.git] / lib / Bytecode / Reader / ConstantReader.cpp
1 //===- ConstantReader.cpp - Code to constants and types ====---------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements functionality to deserialize constants and types from
11 // bytecode files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ReaderInternals.h"
16 #include "llvm/Module.h"
17 #include "llvm/Constants.h"
18 #include <algorithm>
19 using namespace llvm;
20
21 const Type *BytecodeParser::parseTypeConstant(const unsigned char *&Buf,
22                                               const unsigned char *EndBuf) {
23   unsigned PrimType = read_vbr_uint(Buf, EndBuf);
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     const Type *RetType = getType(read_vbr_uint(Buf, EndBuf));
32
33     unsigned NumParams = read_vbr_uint(Buf, EndBuf);
34
35     std::vector<const Type*> Params;
36     while (NumParams--)
37       Params.push_back(getType(read_vbr_uint(Buf, EndBuf)));
38
39     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
40     if (isVarArg) Params.pop_back();
41
42     return FunctionType::get(RetType, Params, isVarArg);
43   }
44   case Type::ArrayTyID: {
45     unsigned ElTyp = read_vbr_uint(Buf, EndBuf);
46     const Type *ElementType = getType(ElTyp);
47
48     unsigned NumElements = read_vbr_uint(Buf, EndBuf);
49
50     BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size=" 
51               << NumElements << "\n");
52     return ArrayType::get(ElementType, NumElements);
53   }
54   case Type::StructTyID: {
55     std::vector<const Type*> Elements;
56     unsigned Typ = read_vbr_uint(Buf, EndBuf);
57     while (Typ) {         // List is terminated by void/0 typeid
58       Elements.push_back(getType(Typ));
59       Typ = read_vbr_uint(Buf, EndBuf);
60     }
61
62     return StructType::get(Elements);
63   }
64   case Type::PointerTyID: {
65     unsigned ElTyp = read_vbr_uint(Buf, EndBuf);
66     BCR_TRACE(5, "Pointer Type Constant #" << ElTyp << "\n");
67     return PointerType::get(getType(ElTyp));
68   }
69
70   case Type::OpaqueTyID: {
71     return OpaqueType::get();
72   }
73
74   default:
75     std::cerr << __FILE__ << ":" << __LINE__
76               << ": Don't know how to deserialize"
77               << " primitive Type " << PrimType << "\n";
78     return Val;
79   }
80 }
81
82 // parseTypeConstants - We have to use this weird code to handle recursive
83 // types.  We know that recursive types will only reference the current slab of
84 // values in the type plane, but they can forward reference types before they
85 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
86 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
87 // this ugly problem, we pessimistically insert an opaque type for each type we
88 // are about to read.  This means that forward references will resolve to
89 // something and when we reread the type later, we can replace the opaque type
90 // with a new resolved concrete type.
91 //
92 void BytecodeParser::parseTypeConstants(const unsigned char *&Buf,
93                                         const unsigned char *EndBuf,
94                                         TypeValuesListTy &Tab,
95                                         unsigned NumEntries) {
96   assert(Tab.size() == 0 && "should not have read type constants in before!");
97
98   // Insert a bunch of opaque types to be resolved later...
99   Tab.reserve(NumEntries);
100   for (unsigned i = 0; i != NumEntries; ++i)
101     Tab.push_back(OpaqueType::get());
102
103   // Loop through reading all of the types.  Forward types will make use of the
104   // opaque types just inserted.
105   //
106   for (unsigned i = 0; i != NumEntries; ++i) {
107     const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
108     if (NewTy == 0) throw std::string("Couldn't parse type!");
109     BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
110               "' Replacing: " << OldTy << "\n");
111
112     // Don't insertValue the new type... instead we want to replace the opaque
113     // type with the new concrete value...
114     //
115
116     // Refine the abstract type to the new type.  This causes all uses of the
117     // abstract type to use NewTy.  This also will cause the opaque type to be
118     // deleted...
119     //
120     cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
121
122     // This should have replace the old opaque type with the new type in the
123     // value table... or with a preexisting type that was already in the system
124     assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
125   }
126
127   BCR_TRACE(5, "Resulting types:\n");
128   for (unsigned i = 0; i < NumEntries; ++i) {
129     BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
130   }
131 }
132
133
134 Constant *BytecodeParser::parseConstantValue(const unsigned char *&Buf,
135                                              const unsigned char *EndBuf,
136                                              unsigned TypeID) {
137
138   // We must check for a ConstantExpr before switching by type because
139   // a ConstantExpr can be of any type, and has no explicit value.
140   // 
141   // 0 if not expr; numArgs if is expr
142   unsigned isExprNumArgs = read_vbr_uint(Buf, EndBuf);
143   
144   if (isExprNumArgs) {
145     // FIXME: Encoding of constant exprs could be much more compact!
146     std::vector<Constant*> ArgVec;
147     ArgVec.reserve(isExprNumArgs);
148     unsigned Opcode = read_vbr_uint(Buf, EndBuf);
149     
150     // Read the slot number and types of each of the arguments
151     for (unsigned i = 0; i != isExprNumArgs; ++i) {
152       unsigned ArgValSlot = read_vbr_uint(Buf, EndBuf);
153       unsigned ArgTypeSlot = read_vbr_uint(Buf, EndBuf);
154       BCR_TRACE(4, "CE Arg " << i << ": Type: '" << *getType(ArgTypeSlot)
155                 << "'  slot: " << ArgValSlot << "\n");
156       
157       // Get the arg value from its slot if it exists, otherwise a placeholder
158       ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
159     }
160     
161     // Construct a ConstantExpr of the appropriate kind
162     if (isExprNumArgs == 1) {           // All one-operand expressions
163       assert(Opcode == Instruction::Cast);
164       return ConstantExpr::getCast(ArgVec[0], getType(TypeID));
165     } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
166       std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
167       return ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
168     } else {                            // All other 2-operand expressions
169       return ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
170     }
171   }
172   
173   // Ok, not an ConstantExpr.  We now know how to read the given type...
174   const Type *Ty = getType(TypeID);
175   switch (Ty->getPrimitiveID()) {
176   case Type::BoolTyID: {
177     unsigned Val = read_vbr_uint(Buf, EndBuf);
178     if (Val != 0 && Val != 1) throw std::string("Invalid boolean value read.");
179     return ConstantBool::get(Val == 1);
180   }
181
182   case Type::UByteTyID:   // Unsigned integer types...
183   case Type::UShortTyID:
184   case Type::UIntTyID: {
185     unsigned Val = read_vbr_uint(Buf, EndBuf);
186     if (!ConstantUInt::isValueValidForType(Ty, Val)) 
187       throw std::string("Invalid unsigned byte/short/int read.");
188     return ConstantUInt::get(Ty, Val);
189   }
190
191   case Type::ULongTyID: {
192     return ConstantUInt::get(Ty, read_vbr_uint64(Buf, EndBuf));
193   }
194
195   case Type::SByteTyID:   // Signed integer types...
196   case Type::ShortTyID:
197   case Type::IntTyID: {
198   case Type::LongTyID:
199     int64_t Val = read_vbr_int64(Buf, EndBuf);
200     if (!ConstantSInt::isValueValidForType(Ty, Val)) 
201       throw std::string("Invalid signed byte/short/int/long read.");
202     return ConstantSInt::get(Ty, Val);
203   }
204
205   case Type::FloatTyID: {
206     float F;
207     input_data(Buf, EndBuf, &F, &F+1);
208     return ConstantFP::get(Ty, F);
209   }
210
211   case Type::DoubleTyID: {
212     double Val;
213     input_data(Buf, EndBuf, &Val, &Val+1);
214     return ConstantFP::get(Ty, Val);
215   }
216
217   case Type::TypeTyID:
218     throw std::string("Type constants shouldn't live in constant table!");
219
220   case Type::ArrayTyID: {
221     const ArrayType *AT = cast<ArrayType>(Ty);
222     unsigned NumElements = AT->getNumElements();
223     unsigned TypeSlot = getTypeSlot(AT->getElementType());
224     std::vector<Constant*> Elements;
225     Elements.reserve(NumElements);
226     while (NumElements--)     // Read all of the elements of the constant.
227       Elements.push_back(getConstantValue(TypeSlot,
228                                           read_vbr_uint(Buf, EndBuf)));
229     return ConstantArray::get(AT, Elements);
230   }
231
232   case Type::StructTyID: {
233     const StructType *ST = cast<StructType>(Ty);
234
235     std::vector<Constant *> Elements;
236     Elements.reserve(ST->getNumElements());
237     for (unsigned i = 0; i != ST->getNumElements(); ++i)
238       Elements.push_back(getConstantValue(ST->getElementType(i),
239                                           read_vbr_uint(Buf, EndBuf)));
240
241     return ConstantStruct::get(ST, Elements);
242   }    
243
244   case Type::PointerTyID: {  // ConstantPointerRef value...
245     const PointerType *PT = cast<PointerType>(Ty);
246     unsigned Slot = read_vbr_uint(Buf, EndBuf);
247     BCR_TRACE(4, "CPR: Type: '" << Ty << "'  slot: " << Slot << "\n");
248     
249     // Check to see if we have already read this global variable...
250     Value *Val = getValue(TypeID, Slot, false);
251     GlobalValue *GV;
252     if (Val) {
253       if (!(GV = dyn_cast<GlobalValue>(Val))) 
254         throw std::string("Value of ConstantPointerRef not in ValueTable!");
255       BCR_TRACE(5, "Value Found in ValueTable!\n");
256     } else {
257       throw std::string("Forward references are not allowed here.");
258     }
259     
260     return ConstantPointerRef::get(GV);
261   }
262
263   default:
264     throw std::string("Don't know how to deserialize constant value of type '"+
265                       Ty->getDescription());
266   }
267 }
268
269 void BytecodeParser::ParseGlobalTypes(const unsigned char *&Buf,
270                                       const unsigned char *EndBuf) {
271   ValueTable T;
272   ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
273 }
274
275 void BytecodeParser::parseStringConstants(const unsigned char *&Buf,
276                                           const unsigned char *EndBuf,
277                                           unsigned NumEntries, ValueTable &Tab){
278   for (; NumEntries; --NumEntries) {
279     unsigned Typ = read_vbr_uint(Buf, EndBuf);
280     const Type *Ty = getType(Typ);
281     if (!isa<ArrayType>(Ty))
282       throw std::string("String constant data invalid!");
283     
284     const ArrayType *ATy = cast<ArrayType>(Ty);
285     if (ATy->getElementType() != Type::SByteTy &&
286         ATy->getElementType() != Type::UByteTy)
287       throw std::string("String constant data invalid!");
288     
289     // Read character data.  The type tells us how long the string is.
290     char Data[ATy->getNumElements()];
291     input_data(Buf, EndBuf, Data, Data+ATy->getNumElements());
292
293     std::vector<Constant*> Elements(ATy->getNumElements());
294     if (ATy->getElementType() == Type::SByteTy)
295       for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
296         Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
297     else
298       for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
299         Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
300
301     // Create the constant, inserting it as needed.
302     Constant *C = ConstantArray::get(ATy, Elements);
303     unsigned Slot = insertValue(C, Typ, Tab);
304     ResolveReferencesToConstant(C, Slot);
305   }
306 }
307
308
309 void BytecodeParser::ParseConstantPool(const unsigned char *&Buf,
310                                        const unsigned char *EndBuf,
311                                        ValueTable &Tab, 
312                                        TypeValuesListTy &TypeTab) {
313   while (Buf < EndBuf) {
314     unsigned NumEntries = read_vbr_uint(Buf, EndBuf);
315     unsigned Typ = read_vbr_uint(Buf, EndBuf);
316     if (Typ == Type::TypeTyID) {
317       BCR_TRACE(3, "Type: 'type'  NumEntries: " << NumEntries << "\n");
318       parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries);
319     } else if (Typ == Type::VoidTyID) {
320       assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
321       parseStringConstants(Buf, EndBuf, NumEntries, Tab);
322     } else {
323       BCR_TRACE(3, "Type: '" << *getType(Typ) << "'  NumEntries: "
324                 << NumEntries << "\n");
325
326       for (unsigned i = 0; i < NumEntries; ++i) {
327         Constant *C = parseConstantValue(Buf, EndBuf, Typ);
328         assert(C && "parseConstantValue returned NULL!");
329         BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
330         unsigned Slot = insertValue(C, Typ, Tab);
331
332         // If we are reading a function constant table, make sure that we adjust
333         // the slot number to be the real global constant number.
334         //
335         if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
336             ModuleValues[Typ])
337           Slot += ModuleValues[Typ]->size();
338         ResolveReferencesToConstant(C, Slot);
339       }
340     }
341   }
342   
343   if (Buf > EndBuf) throw std::string("Read past end of buffer.");
344 }