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