1 //===- ReadConst.cpp - Code to constants and constant pools ---------------===//
3 // This file implements functionality to deserialize constants and entire
6 // Note that this library should be as fast as possible, reentrant, and
9 //===----------------------------------------------------------------------===//
11 #include "ReaderInternals.h"
12 #include "llvm/Module.h"
13 #include "llvm/Constants.h"
16 const Type *BytecodeParser::parseTypeConstant(const unsigned char *&Buf,
17 const unsigned char *EndBuf) {
19 if (read_vbr(Buf, EndBuf, PrimType)) throw Error_readvbr;
22 if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
26 case Type::FunctionTyID: {
28 if (read_vbr(Buf, EndBuf, Typ)) return Val;
29 const Type *RetType = getType(Typ);
30 if (RetType == 0) return Val;
33 if (read_vbr(Buf, EndBuf, NumParams)) return Val;
35 std::vector<const Type*> Params;
37 if (read_vbr(Buf, EndBuf, Typ)) return Val;
38 const Type *Ty = getType(Typ);
39 if (Ty == 0) return Val;
43 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
44 if (isVarArg) Params.pop_back();
46 return FunctionType::get(RetType, Params, isVarArg);
48 case Type::ArrayTyID: {
50 if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
51 const Type *ElementType = getType(ElTyp);
52 if (ElementType == 0) return Val;
55 if (read_vbr(Buf, EndBuf, NumElements)) return Val;
57 BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
58 << NumElements << "\n");
59 return ArrayType::get(ElementType, NumElements);
61 case Type::StructTyID: {
63 std::vector<const Type*> Elements;
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);
71 if (read_vbr(Buf, EndBuf, Typ)) return Val;
74 return StructType::get(Elements);
76 case Type::PointerTyID: {
78 if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
79 BCR_TRACE(5, "Pointer Type Constant #" << ElTyp << "\n");
80 const Type *ElementType = getType(ElTyp);
81 if (ElementType == 0) return Val;
82 return PointerType::get(ElementType);
85 case Type::OpaqueTyID: {
86 return OpaqueType::get();
90 std::cerr << __FILE__ << ":" << __LINE__
91 << ": Don't know how to deserialize"
92 << " primitive Type " << PrimType << "\n";
97 // parseTypeConstants - We have to use this weird code to handle recursive
98 // types. We know that recursive types will only reference the current slab of
99 // values in the type plane, but they can forward reference types before they
100 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
101 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
102 // this ugly problem, we pessimistically insert an opaque type for each type we
103 // are about to read. This means that forward references will resolve to
104 // something and when we reread the type later, we can replace the opaque type
105 // with a new resolved concrete type.
107 void debug_type_tables();
108 void BytecodeParser::parseTypeConstants(const unsigned char *&Buf,
109 const unsigned char *EndBuf,
110 TypeValuesListTy &Tab,
111 unsigned NumEntries) {
112 assert(Tab.size() == 0 && "should not have read type constants in before!");
114 // Insert a bunch of opaque types to be resolved later...
115 for (unsigned i = 0; i < NumEntries; ++i)
116 Tab.push_back(OpaqueType::get());
118 // Loop through reading all of the types. Forward types will make use of the
119 // opaque types just inserted.
121 for (unsigned i = 0; i < NumEntries; ++i) {
122 const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
123 if (NewTy == 0) throw std::string("Parsed invalid type.");
124 BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
125 "' Replacing: " << OldTy << "\n");
127 // Don't insertValue the new type... instead we want to replace the opaque
128 // type with the new concrete value...
131 // Refine the abstract type to the new type. This causes all uses of the
132 // abstract type to use the newty. This also will cause the opaque type
135 ((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
137 // This should have replace the old opaque type with the new type in the
138 // value table... or with a preexisting type that was already in the system
139 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
142 BCR_TRACE(5, "Resulting types:\n");
143 for (unsigned i = 0; i < NumEntries; ++i) {
144 BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
150 Constant *BytecodeParser::parseConstantValue(const unsigned char *&Buf,
151 const unsigned char *EndBuf,
154 // We must check for a ConstantExpr before switching by type because
155 // a ConstantExpr can be of any type, and has no explicit value.
157 unsigned isExprNumArgs; // 0 if not expr; numArgs if is expr
158 if (read_vbr(Buf, EndBuf, isExprNumArgs)) throw Error_readvbr;
160 // FIXME: Encoding of constant exprs could be much more compact!
162 std::vector<Constant*> ArgVec;
163 ArgVec.reserve(isExprNumArgs);
164 if (read_vbr(Buf, EndBuf, Opcode)) throw Error_readvbr;
166 // Read the slot number and types of each of the arguments
167 for (unsigned i = 0; i != isExprNumArgs; ++i) {
168 unsigned ArgValSlot, ArgTypeSlot;
169 if (read_vbr(Buf, EndBuf, ArgValSlot)) throw Error_readvbr;
170 if (read_vbr(Buf, EndBuf, ArgTypeSlot)) throw Error_readvbr;
171 const Type *ArgTy = getType(ArgTypeSlot);
172 if (ArgTy == 0) throw std::string("Argument type slot not found.");
174 BCR_TRACE(4, "CE Arg " << i << ": Type: '" << ArgTy << "' slot: "
175 << ArgValSlot << "\n");
177 // Get the arg value from its slot if it exists, otherwise a placeholder
178 Constant *C = getConstantValue(ArgTy, ArgValSlot);
179 if (C == 0) throw std::string("No arg value or placeholder found.");
183 // Construct a ConstantExpr of the appropriate kind
184 if (isExprNumArgs == 1) { // All one-operand expressions
185 assert(Opcode == Instruction::Cast);
186 return ConstantExpr::getCast(ArgVec[0], Ty);
187 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
188 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
189 return ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
190 } else { // All other 2-operand expressions
191 return ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
195 // Ok, not an ConstantExpr. We now know how to read the given type...
196 switch (Ty->getPrimitiveID()) {
197 case Type::BoolTyID: {
199 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
200 if (Val != 0 && Val != 1) throw std::string("Invalid boolean value read.");
201 return ConstantBool::get(Val == 1);
204 case Type::UByteTyID: // Unsigned integer types...
205 case Type::UShortTyID:
206 case Type::UIntTyID: {
208 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
209 if (!ConstantUInt::isValueValidForType(Ty, Val))
210 throw std::string("Invalid unsigned byte/short/int read.");
211 return ConstantUInt::get(Ty, Val);
214 case Type::ULongTyID: {
216 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
217 return ConstantUInt::get(Ty, Val);
220 case Type::SByteTyID: // Signed integer types...
221 case Type::ShortTyID:
222 case Type::IntTyID: {
225 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
226 if (!ConstantSInt::isValueValidForType(Ty, Val))
227 throw std::string("Invalid signed byte/short/int/long read.");
228 return ConstantSInt::get(Ty, Val);
231 case Type::FloatTyID: {
233 if (input_data(Buf, EndBuf, &F, &F+1)) throw Error_inputdata;
234 return ConstantFP::get(Ty, F);
237 case Type::DoubleTyID: {
239 if (input_data(Buf, EndBuf, &Val, &Val+1)) throw Error_inputdata;
240 return ConstantFP::get(Ty, Val);
244 throw std::string("Type constants shouldn't live in constant table!");
246 case Type::ArrayTyID: {
247 const ArrayType *AT = cast<ArrayType>(Ty);
248 unsigned NumElements = AT->getNumElements();
250 std::vector<Constant*> Elements;
251 while (NumElements--) { // Read all of the elements of the constant.
253 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
254 Constant *C = getConstantValue(AT->getElementType(), Slot);
255 if (!C) throw std::string("Unable to get const value of array slot.");
256 Elements.push_back(C);
258 return ConstantArray::get(AT, Elements);
261 case Type::StructTyID: {
262 const StructType *ST = cast<StructType>(Ty);
263 const StructType::ElementTypes &ET = ST->getElementTypes();
265 std::vector<Constant *> Elements;
266 for (unsigned i = 0; i < ET.size(); ++i) {
268 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
269 Constant *C = getConstantValue(ET[i], Slot);
270 if (!C) throw std::string("Could not read const value in struct slot.");
271 Elements.push_back(C);
274 return ConstantStruct::get(ST, Elements);
277 case Type::PointerTyID: {
278 const PointerType *PT = cast<PointerType>(Ty);
280 if (HasImplicitZeroInitializer)
283 if (read_vbr(Buf, EndBuf, SubClass)) throw Error_readvbr;
286 case 0: // ConstantPointerNull value...
287 return ConstantPointerNull::get(PT);
289 case 1: { // ConstantPointerRef value...
291 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
292 BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
294 // Check to see if we have already read this global variable...
295 Value *Val = getValue(PT, Slot, false);
298 if (!(GV = dyn_cast<GlobalValue>(Val)))
299 throw std::string("Value of ConstantPointerRef not in ValueTable!");
300 BCR_TRACE(5, "Value Found in ValueTable!\n");
301 } else if (RevisionNum > 0) {
302 // Revision #0 could have forward references to globals that were weird.
303 // We got rid of this in subsequent revs.
304 throw std::string("Forward references to globals not allowed.");
305 } else { // Nope... find or create a forward ref. for it
306 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
308 if (I != GlobalRefs.end()) {
309 BCR_TRACE(5, "Previous forward ref found!\n");
310 GV = cast<GlobalValue>(I->second);
312 BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
314 // Create a placeholder for the global variable reference...
315 GlobalVariable *GVar =
316 new GlobalVariable(PT->getElementType(), false,
317 GlobalValue::InternalLinkage);
319 // Keep track of the fact that we have a forward ref to recycle it
320 GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
322 // Must temporarily push this value into the module table...
323 TheModule->getGlobalList().push_back(GVar);
328 return ConstantPointerRef::get(GV);
332 BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
333 throw std::string("Unknown pointer constant type.");
338 throw std::string("Don't know how to deserialize constant value of type '"+
339 Ty->getDescription());
343 void BytecodeParser::ParseGlobalTypes(const unsigned char *&Buf,
344 const unsigned char *EndBuf) {
346 ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
349 void BytecodeParser::ParseConstantPool(const unsigned char *&Buf,
350 const unsigned char *EndBuf,
352 TypeValuesListTy &TypeTab) {
353 while (Buf < EndBuf) {
354 unsigned NumEntries, Typ;
356 if (read_vbr(Buf, EndBuf, NumEntries) ||
357 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
358 const Type *Ty = getType(Typ);
359 if (Ty == 0) throw std::string("Invalid type read.");
360 BCR_TRACE(3, "Type: '" << Ty << "' NumEntries: " << NumEntries << "\n");
362 if (Typ == Type::TypeTyID) {
363 parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries);
365 for (unsigned i = 0; i < NumEntries; ++i) {
366 Constant *C = parseConstantValue(Buf, EndBuf, Ty);
367 assert(C && "parseConstantValue returned NULL!");
368 BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
370 if ((Slot = insertValue(C, Tab)) == -1)
371 throw std::string("Could not insert value into ValueTable.");
373 // If we are reading a function constant table, make sure that we adjust
374 // the slot number to be the real global constant number.
376 if (&Tab != &ModuleValues && Typ < ModuleValues.size())
377 Slot += ModuleValues[Typ]->size();
378 ResolveReferencesToValue(C, (unsigned)Slot);
383 if (Buf > EndBuf) throw std::string("Read past end of buffer.");