1 //===- ReadConst.cpp - Code to constants and constant pools ---------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements functionality to deserialize constants and entire
13 // Note that this library should be as fast as possible, reentrant, and
16 //===----------------------------------------------------------------------===//
18 #include "ReaderInternals.h"
19 #include "llvm/Module.h"
20 #include "llvm/Constants.h"
23 const Type *BytecodeParser::parseTypeConstant(const unsigned char *&Buf,
24 const unsigned char *EndBuf) {
26 if (read_vbr(Buf, EndBuf, PrimType)) throw Error_readvbr;
29 if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
33 case Type::FunctionTyID: {
35 if (read_vbr(Buf, EndBuf, Typ)) return Val;
36 const Type *RetType = getType(Typ);
39 if (read_vbr(Buf, EndBuf, NumParams)) return Val;
41 std::vector<const Type*> Params;
43 if (read_vbr(Buf, EndBuf, Typ)) return Val;
44 Params.push_back(getType(Typ));
47 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
48 if (isVarArg) Params.pop_back();
50 return FunctionType::get(RetType, Params, isVarArg);
52 case Type::ArrayTyID: {
54 if (read_vbr(Buf, EndBuf, ElTyp)) return Val;
55 const Type *ElementType = getType(ElTyp);
58 if (read_vbr(Buf, EndBuf, NumElements)) return Val;
60 BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
61 << NumElements << "\n");
62 return ArrayType::get(ElementType, NumElements);
64 case Type::StructTyID: {
66 std::vector<const Type*> Elements;
68 if (read_vbr(Buf, EndBuf, Typ)) return Val;
69 while (Typ) { // List is terminated by void/0 typeid
70 Elements.push_back(getType(Typ));
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 return PointerType::get(getType(ElTyp));
83 case Type::OpaqueTyID: {
84 return OpaqueType::get();
88 std::cerr << __FILE__ << ":" << __LINE__
89 << ": Don't know how to deserialize"
90 << " primitive Type " << PrimType << "\n";
95 // parseTypeConstants - We have to use this weird code to handle recursive
96 // types. We know that recursive types will only reference the current slab of
97 // values in the type plane, but they can forward reference types before they
98 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
99 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
100 // this ugly problem, we pessimistically insert an opaque type for each type we
101 // are about to read. This means that forward references will resolve to
102 // something and when we reread the type later, we can replace the opaque type
103 // with a new resolved concrete type.
105 void debug_type_tables();
106 void BytecodeParser::parseTypeConstants(const unsigned char *&Buf,
107 const unsigned char *EndBuf,
108 TypeValuesListTy &Tab,
109 unsigned NumEntries) {
110 assert(Tab.size() == 0 && "should not have read type constants in before!");
112 // Insert a bunch of opaque types to be resolved later...
113 for (unsigned i = 0; i < NumEntries; ++i)
114 Tab.push_back(OpaqueType::get());
116 // Loop through reading all of the types. Forward types will make use of the
117 // opaque types just inserted.
119 for (unsigned i = 0; i < NumEntries; ++i) {
120 const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
121 if (NewTy == 0) throw std::string("Parsed invalid type.");
122 BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
123 "' Replacing: " << OldTy << "\n");
125 // Don't insertValue the new type... instead we want to replace the opaque
126 // type with the new concrete value...
129 // Refine the abstract type to the new type. This causes all uses of the
130 // abstract type to use the newty. This also will cause the opaque type
133 ((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);
135 // This should have replace the old opaque type with the new type in the
136 // value table... or with a preexisting type that was already in the system
137 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
140 BCR_TRACE(5, "Resulting types:\n");
141 for (unsigned i = 0; i < NumEntries; ++i) {
142 BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
148 Constant *BytecodeParser::parseConstantValue(const unsigned char *&Buf,
149 const unsigned char *EndBuf,
152 // We must check for a ConstantExpr before switching by type because
153 // a ConstantExpr can be of any type, and has no explicit value.
155 unsigned isExprNumArgs; // 0 if not expr; numArgs if is expr
156 if (read_vbr(Buf, EndBuf, isExprNumArgs)) throw Error_readvbr;
158 // FIXME: Encoding of constant exprs could be much more compact!
160 std::vector<Constant*> ArgVec;
161 ArgVec.reserve(isExprNumArgs);
162 if (read_vbr(Buf, EndBuf, Opcode)) throw Error_readvbr;
164 // Read the slot number and types of each of the arguments
165 for (unsigned i = 0; i != isExprNumArgs; ++i) {
166 unsigned ArgValSlot, ArgTypeSlot;
167 if (read_vbr(Buf, EndBuf, ArgValSlot)) throw Error_readvbr;
168 if (read_vbr(Buf, EndBuf, ArgTypeSlot)) throw Error_readvbr;
169 const Type *ArgTy = getType(ArgTypeSlot);
171 BCR_TRACE(4, "CE Arg " << i << ": Type: '" << *ArgTy << "' slot: "
172 << ArgValSlot << "\n");
174 // Get the arg value from its slot if it exists, otherwise a placeholder
175 ArgVec.push_back(getConstantValue(ArgTy, ArgValSlot));
178 // Construct a ConstantExpr of the appropriate kind
179 if (isExprNumArgs == 1) { // All one-operand expressions
180 assert(Opcode == Instruction::Cast);
181 return ConstantExpr::getCast(ArgVec[0], Ty);
182 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
183 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
184 return ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
185 } else { // All other 2-operand expressions
186 return ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
190 // Ok, not an ConstantExpr. We now know how to read the given type...
191 switch (Ty->getPrimitiveID()) {
192 case Type::BoolTyID: {
194 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
195 if (Val != 0 && Val != 1) throw std::string("Invalid boolean value read.");
196 return ConstantBool::get(Val == 1);
199 case Type::UByteTyID: // Unsigned integer types...
200 case Type::UShortTyID:
201 case Type::UIntTyID: {
203 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
204 if (!ConstantUInt::isValueValidForType(Ty, Val))
205 throw std::string("Invalid unsigned byte/short/int read.");
206 return ConstantUInt::get(Ty, Val);
209 case Type::ULongTyID: {
211 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
212 return ConstantUInt::get(Ty, Val);
215 case Type::SByteTyID: // Signed integer types...
216 case Type::ShortTyID:
217 case Type::IntTyID: {
220 if (read_vbr(Buf, EndBuf, Val)) throw Error_readvbr;
221 if (!ConstantSInt::isValueValidForType(Ty, Val))
222 throw std::string("Invalid signed byte/short/int/long read.");
223 return ConstantSInt::get(Ty, Val);
226 case Type::FloatTyID: {
228 if (input_data(Buf, EndBuf, &F, &F+1)) throw Error_inputdata;
229 return ConstantFP::get(Ty, F);
232 case Type::DoubleTyID: {
234 if (input_data(Buf, EndBuf, &Val, &Val+1)) throw Error_inputdata;
235 return ConstantFP::get(Ty, Val);
239 throw std::string("Type constants shouldn't live in constant table!");
241 case Type::ArrayTyID: {
242 const ArrayType *AT = cast<ArrayType>(Ty);
243 unsigned NumElements = AT->getNumElements();
245 std::vector<Constant*> Elements;
246 while (NumElements--) { // Read all of the elements of the constant.
248 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
249 Elements.push_back(getConstantValue(AT->getElementType(), Slot));
251 return ConstantArray::get(AT, Elements);
254 case Type::StructTyID: {
255 const StructType *ST = cast<StructType>(Ty);
256 const StructType::ElementTypes &ET = ST->getElementTypes();
258 std::vector<Constant *> Elements;
259 for (unsigned i = 0; i < ET.size(); ++i) {
261 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
262 Elements.push_back(getConstantValue(ET[i], Slot));
265 return ConstantStruct::get(ST, Elements);
268 case Type::PointerTyID: { // ConstantPointerRef value...
269 const PointerType *PT = cast<PointerType>(Ty);
271 if (read_vbr(Buf, EndBuf, Slot)) throw Error_readvbr;
272 BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
274 // Check to see if we have already read this global variable...
275 Value *Val = getValue(PT, Slot, false);
278 if (!(GV = dyn_cast<GlobalValue>(Val)))
279 throw std::string("Value of ConstantPointerRef not in ValueTable!");
280 BCR_TRACE(5, "Value Found in ValueTable!\n");
281 } else if (RevisionNum > 0) {
282 // Revision #0 could have forward references to globals that were weird.
283 // We got rid of this in subsequent revs.
284 throw std::string("Forward references to globals not allowed.");
285 } else { // Nope... find or create a forward ref. for it
286 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PT, Slot));
288 if (I != GlobalRefs.end()) {
289 BCR_TRACE(5, "Previous forward ref found!\n");
290 GV = cast<GlobalValue>(I->second);
292 BCR_TRACE(5, "Creating new forward ref to a global variable!\n");
294 // Create a placeholder for the global variable reference...
295 GlobalVariable *GVar =
296 new GlobalVariable(PT->getElementType(), false,
297 GlobalValue::InternalLinkage);
299 // Keep track of the fact that we have a forward ref to recycle it
300 GlobalRefs.insert(std::make_pair(std::make_pair(PT, Slot), GVar));
302 // Must temporarily push this value into the module table...
303 TheModule->getGlobalList().push_back(GVar);
308 return ConstantPointerRef::get(GV);
312 throw std::string("Don't know how to deserialize constant value of type '"+
313 Ty->getDescription());
317 void BytecodeParser::ParseGlobalTypes(const unsigned char *&Buf,
318 const unsigned char *EndBuf) {
320 ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
323 void BytecodeParser::ParseConstantPool(const unsigned char *&Buf,
324 const unsigned char *EndBuf,
326 TypeValuesListTy &TypeTab) {
327 while (Buf < EndBuf) {
328 unsigned NumEntries, Typ;
330 if (read_vbr(Buf, EndBuf, NumEntries) ||
331 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
332 if (Typ == Type::TypeTyID) {
333 BCR_TRACE(3, "Type: 'type' NumEntries: " << NumEntries << "\n");
334 parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries);
336 const Type *Ty = getType(Typ);
337 BCR_TRACE(3, "Type: '" << *Ty << "' NumEntries: " << NumEntries << "\n");
339 for (unsigned i = 0; i < NumEntries; ++i) {
340 Constant *C = parseConstantValue(Buf, EndBuf, Ty);
341 assert(C && "parseConstantValue returned NULL!");
342 BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
343 unsigned Slot = insertValue(C, Typ, Tab);
345 // If we are reading a function constant table, make sure that we adjust
346 // the slot number to be the real global constant number.
348 if (&Tab != &ModuleValues && Typ < ModuleValues.size())
349 Slot += ModuleValues[Typ]->size();
350 ResolveReferencesToValue(C, Slot);
355 if (Buf > EndBuf) throw std::string("Read past end of buffer.");