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"
24 const Type *BytecodeParser::parseTypeConstant(const unsigned char *&Buf,
25 const unsigned char *EndBuf) {
26 unsigned PrimType = read_vbr_uint(Buf, EndBuf);
29 if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
33 case Type::FunctionTyID: {
34 const Type *RetType = getType(read_vbr_uint(Buf, EndBuf));
36 unsigned NumParams = read_vbr_uint(Buf, EndBuf);
38 std::vector<const Type*> Params;
40 Params.push_back(getType(read_vbr_uint(Buf, EndBuf)));
42 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
43 if (isVarArg) Params.pop_back();
45 return FunctionType::get(RetType, Params, isVarArg);
47 case Type::ArrayTyID: {
48 unsigned ElTyp = read_vbr_uint(Buf, EndBuf);
49 const Type *ElementType = getType(ElTyp);
51 unsigned NumElements = read_vbr_uint(Buf, EndBuf);
53 BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
54 << NumElements << "\n");
55 return ArrayType::get(ElementType, NumElements);
57 case Type::StructTyID: {
58 std::vector<const Type*> Elements;
59 unsigned Typ = read_vbr_uint(Buf, EndBuf);
60 while (Typ) { // List is terminated by void/0 typeid
61 Elements.push_back(getType(Typ));
62 Typ = read_vbr_uint(Buf, EndBuf);
65 return StructType::get(Elements);
67 case Type::PointerTyID: {
68 unsigned ElTyp = read_vbr_uint(Buf, EndBuf);
69 BCR_TRACE(5, "Pointer Type Constant #" << ElTyp << "\n");
70 return PointerType::get(getType(ElTyp));
73 case Type::OpaqueTyID: {
74 return OpaqueType::get();
78 std::cerr << __FILE__ << ":" << __LINE__
79 << ": Don't know how to deserialize"
80 << " primitive Type " << PrimType << "\n";
85 // parseTypeConstants - We have to use this weird code to handle recursive
86 // types. We know that recursive types will only reference the current slab of
87 // values in the type plane, but they can forward reference types before they
88 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
89 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
90 // this ugly problem, we pessimistically insert an opaque type for each type we
91 // are about to read. This means that forward references will resolve to
92 // something and when we reread the type later, we can replace the opaque type
93 // with a new resolved concrete type.
95 namespace llvm { void debug_type_tables(); }
96 void BytecodeParser::parseTypeConstants(const unsigned char *&Buf,
97 const unsigned char *EndBuf,
98 TypeValuesListTy &Tab,
99 unsigned NumEntries) {
100 assert(Tab.size() == 0 && "should not have read type constants in before!");
102 // Insert a bunch of opaque types to be resolved later...
103 Tab.reserve(NumEntries);
104 for (unsigned i = 0; i != NumEntries; ++i)
105 Tab.push_back(OpaqueType::get());
107 // Loop through reading all of the types. Forward types will make use of the
108 // opaque types just inserted.
110 for (unsigned i = 0; i != NumEntries; ++i) {
111 const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
112 if (NewTy == 0) throw std::string("Couldn't parse type!");
113 BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
114 "' Replacing: " << OldTy << "\n");
116 // Don't insertValue the new type... instead we want to replace the opaque
117 // type with the new concrete value...
120 // Refine the abstract type to the new type. This causes all uses of the
121 // abstract type to use NewTy. This also will cause the opaque type to be
124 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
126 // This should have replace the old opaque type with the new type in the
127 // value table... or with a preexisting type that was already in the system
128 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
131 BCR_TRACE(5, "Resulting types:\n");
132 for (unsigned i = 0; i < NumEntries; ++i) {
133 BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
139 Constant *BytecodeParser::parseConstantValue(const unsigned char *&Buf,
140 const unsigned char *EndBuf,
143 // We must check for a ConstantExpr before switching by type because
144 // a ConstantExpr can be of any type, and has no explicit value.
146 // 0 if not expr; numArgs if is expr
147 unsigned isExprNumArgs = read_vbr_uint(Buf, EndBuf);
150 // FIXME: Encoding of constant exprs could be much more compact!
151 std::vector<Constant*> ArgVec;
152 ArgVec.reserve(isExprNumArgs);
153 unsigned Opcode = read_vbr_uint(Buf, EndBuf);
155 // Read the slot number and types of each of the arguments
156 for (unsigned i = 0; i != isExprNumArgs; ++i) {
157 unsigned ArgValSlot = read_vbr_uint(Buf, EndBuf);
158 unsigned ArgTypeSlot = read_vbr_uint(Buf, EndBuf);
159 BCR_TRACE(4, "CE Arg " << i << ": Type: '" << *getType(ArgTypeSlot)
160 << "' slot: " << ArgValSlot << "\n");
162 // Get the arg value from its slot if it exists, otherwise a placeholder
163 ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
166 // Construct a ConstantExpr of the appropriate kind
167 if (isExprNumArgs == 1) { // All one-operand expressions
168 assert(Opcode == Instruction::Cast);
169 return ConstantExpr::getCast(ArgVec[0], getType(TypeID));
170 } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
171 std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
172 return ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
173 } else { // All other 2-operand expressions
174 return ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
178 // Ok, not an ConstantExpr. We now know how to read the given type...
179 const Type *Ty = getType(TypeID);
180 switch (Ty->getPrimitiveID()) {
181 case Type::BoolTyID: {
182 unsigned Val = read_vbr_uint(Buf, EndBuf);
183 if (Val != 0 && Val != 1) throw std::string("Invalid boolean value read.");
184 return ConstantBool::get(Val == 1);
187 case Type::UByteTyID: // Unsigned integer types...
188 case Type::UShortTyID:
189 case Type::UIntTyID: {
190 unsigned Val = read_vbr_uint(Buf, EndBuf);
191 if (!ConstantUInt::isValueValidForType(Ty, Val))
192 throw std::string("Invalid unsigned byte/short/int read.");
193 return ConstantUInt::get(Ty, Val);
196 case Type::ULongTyID: {
197 return ConstantUInt::get(Ty, read_vbr_uint64(Buf, EndBuf));
200 case Type::SByteTyID: // Signed integer types...
201 case Type::ShortTyID:
202 case Type::IntTyID: {
204 int64_t Val = read_vbr_int64(Buf, EndBuf);
205 if (!ConstantSInt::isValueValidForType(Ty, Val))
206 throw std::string("Invalid signed byte/short/int/long read.");
207 return ConstantSInt::get(Ty, Val);
210 case Type::FloatTyID: {
212 input_data(Buf, EndBuf, &F, &F+1);
213 return ConstantFP::get(Ty, F);
216 case Type::DoubleTyID: {
218 input_data(Buf, EndBuf, &Val, &Val+1);
219 return ConstantFP::get(Ty, Val);
223 throw std::string("Type constants shouldn't live in constant table!");
225 case Type::ArrayTyID: {
226 const ArrayType *AT = cast<ArrayType>(Ty);
227 unsigned NumElements = AT->getNumElements();
228 unsigned TypeSlot = getTypeSlot(AT->getElementType());
229 std::vector<Constant*> Elements;
230 Elements.reserve(NumElements);
231 while (NumElements--) // Read all of the elements of the constant.
232 Elements.push_back(getConstantValue(TypeSlot,
233 read_vbr_uint(Buf, EndBuf)));
234 return ConstantArray::get(AT, Elements);
237 case Type::StructTyID: {
238 const StructType *ST = cast<StructType>(Ty);
239 const StructType::ElementTypes &ET = ST->getElementTypes();
241 std::vector<Constant *> Elements;
242 Elements.reserve(ET.size());
243 for (unsigned i = 0; i != ET.size(); ++i)
244 Elements.push_back(getConstantValue(ET[i], read_vbr_uint(Buf, EndBuf)));
246 return ConstantStruct::get(ST, Elements);
249 case Type::PointerTyID: { // ConstantPointerRef value...
250 const PointerType *PT = cast<PointerType>(Ty);
251 unsigned Slot = read_vbr_uint(Buf, EndBuf);
252 BCR_TRACE(4, "CPR: Type: '" << Ty << "' slot: " << Slot << "\n");
254 // Check to see if we have already read this global variable...
255 Value *Val = getValue(TypeID, Slot, false);
258 if (!(GV = dyn_cast<GlobalValue>(Val)))
259 throw std::string("Value of ConstantPointerRef not in ValueTable!");
260 BCR_TRACE(5, "Value Found in ValueTable!\n");
262 throw std::string("Forward references are not allowed here.");
265 return ConstantPointerRef::get(GV);
269 throw std::string("Don't know how to deserialize constant value of type '"+
270 Ty->getDescription());
274 void BytecodeParser::ParseGlobalTypes(const unsigned char *&Buf,
275 const unsigned char *EndBuf) {
277 ParseConstantPool(Buf, EndBuf, T, ModuleTypeValues);
280 void BytecodeParser::parseStringConstants(const unsigned char *&Buf,
281 const unsigned char *EndBuf,
282 unsigned NumEntries, ValueTable &Tab){
283 for (; NumEntries; --NumEntries) {
284 unsigned Typ = read_vbr_uint(Buf, EndBuf);
285 const Type *Ty = getType(Typ);
286 if (!isa<ArrayType>(Ty))
287 throw std::string("String constant data invalid!");
289 const ArrayType *ATy = cast<ArrayType>(Ty);
290 if (ATy->getElementType() != Type::SByteTy &&
291 ATy->getElementType() != Type::UByteTy)
292 throw std::string("String constant data invalid!");
294 // Read character data. The type tells us how long the string is.
295 char Data[ATy->getNumElements()];
296 input_data(Buf, EndBuf, Data, Data+ATy->getNumElements());
298 std::vector<Constant*> Elements(ATy->getNumElements());
299 if (ATy->getElementType() == Type::SByteTy)
300 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
301 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
303 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
304 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
306 // Create the constant, inserting it as needed.
307 Constant *C = ConstantArray::get(ATy, Elements);
308 unsigned Slot = insertValue(C, Typ, Tab);
309 ResolveReferencesToConstant(C, Slot);
314 void BytecodeParser::ParseConstantPool(const unsigned char *&Buf,
315 const unsigned char *EndBuf,
317 TypeValuesListTy &TypeTab) {
318 while (Buf < EndBuf) {
319 unsigned NumEntries = read_vbr_uint(Buf, EndBuf);
320 unsigned Typ = read_vbr_uint(Buf, EndBuf);
321 if (Typ == Type::TypeTyID) {
322 BCR_TRACE(3, "Type: 'type' NumEntries: " << NumEntries << "\n");
323 parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries);
324 } else if (Typ == Type::VoidTyID) {
325 assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
326 parseStringConstants(Buf, EndBuf, NumEntries, Tab);
328 BCR_TRACE(3, "Type: '" << *getType(Typ) << "' NumEntries: "
329 << NumEntries << "\n");
331 for (unsigned i = 0; i < NumEntries; ++i) {
332 Constant *C = parseConstantValue(Buf, EndBuf, Typ);
333 assert(C && "parseConstantValue returned NULL!");
334 BCR_TRACE(4, "Read Constant: '" << *C << "'\n");
335 unsigned Slot = insertValue(C, Typ, Tab);
337 // If we are reading a function constant table, make sure that we adjust
338 // the slot number to be the real global constant number.
340 if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
342 Slot += ModuleValues[Typ]->size();
343 ResolveReferencesToConstant(C, Slot);
348 if (Buf > EndBuf) throw std::string("Read past end of buffer.");