blob: 2d16230bb9138a9dd7792bd6b2a3694546f17daa [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnercaee0dc2007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Chris Lattnera7c49aa2007-05-01 07:01:57 +000019#include "llvm/Instructions.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Chris Lattner48c85b82007-05-04 03:30:17 +000021#include "llvm/ParameterAttributes.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000025#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000026using namespace llvm;
27
Chris Lattnerb348bb82007-05-18 04:02:46 +000028void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000029 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000030 Buffer = 0;
31 std::vector<PATypeHolder>().swap(TypeList);
32 ValueList.clear();
33 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
34 std::vector<BasicBlock*>().swap(FunctionBBs);
35 std::vector<Function*>().swap(FunctionsWithBodies);
36 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000037}
38
Chris Lattner48c85b82007-05-04 03:30:17 +000039//===----------------------------------------------------------------------===//
40// Helper functions to implement forward reference resolution, etc.
41//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000042
Chris Lattnercaee0dc2007-04-22 06:23:29 +000043/// ConvertToString - Convert a string from a record into an std::string, return
44/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000045template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000046static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000047 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000048 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000049 return true;
50
Chris Lattner15e6d172007-05-04 19:11:41 +000051 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
52 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000053 return false;
54}
55
56static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
57 switch (Val) {
58 default: // Map unknown/new linkages to external
59 case 0: return GlobalValue::ExternalLinkage;
60 case 1: return GlobalValue::WeakLinkage;
61 case 2: return GlobalValue::AppendingLinkage;
62 case 3: return GlobalValue::InternalLinkage;
63 case 4: return GlobalValue::LinkOnceLinkage;
64 case 5: return GlobalValue::DLLImportLinkage;
65 case 6: return GlobalValue::DLLExportLinkage;
66 case 7: return GlobalValue::ExternalWeakLinkage;
67 }
68}
69
70static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
71 switch (Val) {
72 default: // Map unknown visibilities to default.
73 case 0: return GlobalValue::DefaultVisibility;
74 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000075 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000076 }
77}
78
Chris Lattnerf581c3b2007-04-24 07:07:11 +000079static int GetDecodedCastOpcode(unsigned Val) {
80 switch (Val) {
81 default: return -1;
82 case bitc::CAST_TRUNC : return Instruction::Trunc;
83 case bitc::CAST_ZEXT : return Instruction::ZExt;
84 case bitc::CAST_SEXT : return Instruction::SExt;
85 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
86 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
87 case bitc::CAST_UITOFP : return Instruction::UIToFP;
88 case bitc::CAST_SITOFP : return Instruction::SIToFP;
89 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
90 case bitc::CAST_FPEXT : return Instruction::FPExt;
91 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
92 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
93 case bitc::CAST_BITCAST : return Instruction::BitCast;
94 }
95}
96static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
97 switch (Val) {
98 default: return -1;
99 case bitc::BINOP_ADD: return Instruction::Add;
100 case bitc::BINOP_SUB: return Instruction::Sub;
101 case bitc::BINOP_MUL: return Instruction::Mul;
102 case bitc::BINOP_UDIV: return Instruction::UDiv;
103 case bitc::BINOP_SDIV:
104 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
105 case bitc::BINOP_UREM: return Instruction::URem;
106 case bitc::BINOP_SREM:
107 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
108 case bitc::BINOP_SHL: return Instruction::Shl;
109 case bitc::BINOP_LSHR: return Instruction::LShr;
110 case bitc::BINOP_ASHR: return Instruction::AShr;
111 case bitc::BINOP_AND: return Instruction::And;
112 case bitc::BINOP_OR: return Instruction::Or;
113 case bitc::BINOP_XOR: return Instruction::Xor;
114 }
115}
116
117
Chris Lattner522b7b12007-04-24 05:48:56 +0000118namespace {
119 /// @brief A class for maintaining the slot number definition
120 /// as a placeholder for the actual definition for forward constants defs.
121 class ConstantPlaceHolder : public ConstantExpr {
122 ConstantPlaceHolder(); // DO NOT IMPLEMENT
123 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000124 public:
125 Use Op;
Dan Gohmanadf3eab2007-11-19 15:30:20 +0000126 explicit ConstantPlaceHolder(const Type *Ty)
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000127 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
128 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000129 }
130 };
131}
132
133Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
134 const Type *Ty) {
135 if (Idx >= size()) {
136 // Insert a bunch of null values.
137 Uses.resize(Idx+1);
138 OperandList = &Uses[0];
139 NumOperands = Idx+1;
140 }
141
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000142 if (Value *V = Uses[Idx]) {
143 assert(Ty == V->getType() && "Type mismatch in constant table!");
144 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000145 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000146
147 // Create and return a placeholder, which will later be RAUW'd.
148 Constant *C = new ConstantPlaceHolder(Ty);
149 Uses[Idx].init(C, this);
150 return C;
151}
152
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000153Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
154 if (Idx >= size()) {
155 // Insert a bunch of null values.
156 Uses.resize(Idx+1);
157 OperandList = &Uses[0];
158 NumOperands = Idx+1;
159 }
160
161 if (Value *V = Uses[Idx]) {
162 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
163 return V;
164 }
165
Chris Lattner01ff65f2007-05-02 05:16:49 +0000166 // No type specified, must be invalid reference.
167 if (Ty == 0) return 0;
168
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000169 // Create and return a placeholder, which will later be RAUW'd.
170 Value *V = new Argument(Ty);
171 Uses[Idx].init(V, this);
172 return V;
173}
174
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000175
176const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
177 // If the TypeID is in range, return it.
178 if (ID < TypeList.size())
179 return TypeList[ID].get();
180 if (!isTypeTable) return 0;
181
182 // The type table allows forward references. Push as many Opaque types as
183 // needed to get up to ID.
184 while (TypeList.size() <= ID)
185 TypeList.push_back(OpaqueType::get());
186 return TypeList.back().get();
187}
188
Chris Lattner48c85b82007-05-04 03:30:17 +0000189//===----------------------------------------------------------------------===//
190// Functions for parsing blocks from the bitcode file
191//===----------------------------------------------------------------------===//
192
193bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000194 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000195 return Error("Malformed block record");
196
197 if (!ParamAttrs.empty())
198 return Error("Multiple PARAMATTR blocks found!");
199
200 SmallVector<uint64_t, 64> Record;
201
202 ParamAttrsVector Attrs;
203
204 // Read all the records.
205 while (1) {
206 unsigned Code = Stream.ReadCode();
207 if (Code == bitc::END_BLOCK) {
208 if (Stream.ReadBlockEnd())
209 return Error("Error at end of PARAMATTR block");
210 return false;
211 }
212
213 if (Code == bitc::ENTER_SUBBLOCK) {
214 // No known subblocks, always skip them.
215 Stream.ReadSubBlockID();
216 if (Stream.SkipBlock())
217 return Error("Malformed block record");
218 continue;
219 }
220
221 if (Code == bitc::DEFINE_ABBREV) {
222 Stream.ReadAbbrevRecord();
223 continue;
224 }
225
226 // Read a record.
227 Record.clear();
228 switch (Stream.ReadRecord(Code, Record)) {
229 default: // Default behavior: ignore.
230 break;
231 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
232 if (Record.size() & 1)
233 return Error("Invalid ENTRY record");
234
Chris Lattner48c85b82007-05-04 03:30:17 +0000235 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Duncan Sands5e41f652007-11-20 14:09:29 +0000236 if (Record[i+1] != ParamAttr::None)
237 Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
Chris Lattner48c85b82007-05-04 03:30:17 +0000238 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000239 ParamAttrs.push_back(Attrs.empty() ? NULL : ParamAttrsList::get(Attrs));
Chris Lattner48c85b82007-05-04 03:30:17 +0000240 Attrs.clear();
241 break;
242 }
Duncan Sands5e41f652007-11-20 14:09:29 +0000243 }
Chris Lattner48c85b82007-05-04 03:30:17 +0000244 }
245}
246
247
Chris Lattner86697142007-05-01 05:01:34 +0000248bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000249 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000250 return Error("Malformed block record");
251
252 if (!TypeList.empty())
253 return Error("Multiple TYPE_BLOCKs found!");
254
255 SmallVector<uint64_t, 64> Record;
256 unsigned NumRecords = 0;
257
258 // Read all the records for this type table.
259 while (1) {
260 unsigned Code = Stream.ReadCode();
261 if (Code == bitc::END_BLOCK) {
262 if (NumRecords != TypeList.size())
263 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000264 if (Stream.ReadBlockEnd())
265 return Error("Error at end of type table block");
266 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000267 }
268
269 if (Code == bitc::ENTER_SUBBLOCK) {
270 // No known subblocks, always skip them.
271 Stream.ReadSubBlockID();
272 if (Stream.SkipBlock())
273 return Error("Malformed block record");
274 continue;
275 }
276
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000277 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000278 Stream.ReadAbbrevRecord();
279 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000280 }
281
282 // Read a record.
283 Record.clear();
284 const Type *ResultTy = 0;
285 switch (Stream.ReadRecord(Code, Record)) {
286 default: // Default behavior: unknown type.
287 ResultTy = 0;
288 break;
289 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
290 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
291 // type list. This allows us to reserve space.
292 if (Record.size() < 1)
293 return Error("Invalid TYPE_CODE_NUMENTRY record");
294 TypeList.reserve(Record[0]);
295 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000296 case bitc::TYPE_CODE_VOID: // VOID
297 ResultTy = Type::VoidTy;
298 break;
299 case bitc::TYPE_CODE_FLOAT: // FLOAT
300 ResultTy = Type::FloatTy;
301 break;
302 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
303 ResultTy = Type::DoubleTy;
304 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000305 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
306 ResultTy = Type::X86_FP80Ty;
307 break;
308 case bitc::TYPE_CODE_FP128: // FP128
309 ResultTy = Type::FP128Ty;
310 break;
311 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
312 ResultTy = Type::PPC_FP128Ty;
313 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000314 case bitc::TYPE_CODE_LABEL: // LABEL
315 ResultTy = Type::LabelTy;
316 break;
317 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
318 ResultTy = 0;
319 break;
320 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
321 if (Record.size() < 1)
322 return Error("Invalid Integer type record");
323
324 ResultTy = IntegerType::get(Record[0]);
325 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000326 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
327 // [pointee type, address space]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000328 if (Record.size() < 1)
329 return Error("Invalid POINTER type record");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000330 unsigned AddressSpace = 0;
331 if (Record.size() == 2)
332 AddressSpace = Record[1];
333 ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000334 break;
Christopher Lambfe63fb92007-12-11 08:59:05 +0000335 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000336 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattnera1afde72007-11-27 17:48:06 +0000337 // FIXME: attrid is dead, remove it in LLVM 3.0
338 // FUNCTION: [vararg, attrid, retty, paramty x N]
339 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000340 return Error("Invalid FUNCTION type record");
341 std::vector<const Type*> ArgTys;
Chris Lattnera1afde72007-11-27 17:48:06 +0000342 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000343 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000344
Chris Lattnera1afde72007-11-27 17:48:06 +0000345 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsdc024672007-11-27 13:23:08 +0000346 Record[0]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000347 break;
348 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000349 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000350 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000351 return Error("Invalid STRUCT type record");
352 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000353 for (unsigned i = 1, e = Record.size(); i != e; ++i)
354 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000355 ResultTy = StructType::get(EltTys, Record[0]);
356 break;
357 }
358 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
359 if (Record.size() < 2)
360 return Error("Invalid ARRAY type record");
361 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
362 break;
363 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
364 if (Record.size() < 2)
365 return Error("Invalid VECTOR type record");
366 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
367 break;
368 }
369
370 if (NumRecords == TypeList.size()) {
371 // If this is a new type slot, just append it.
372 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
373 ++NumRecords;
374 } else if (ResultTy == 0) {
375 // Otherwise, this was forward referenced, so an opaque type was created,
376 // but the result type is actually just an opaque. Leave the one we
377 // created previously.
378 ++NumRecords;
379 } else {
380 // Otherwise, this was forward referenced, so an opaque type was created.
381 // Resolve the opaque type to the real type now.
382 assert(NumRecords < TypeList.size() && "Typelist imbalance");
383 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
384
385 // Don't directly push the new type on the Tab. Instead we want to replace
386 // the opaque type we previously inserted with the new concrete value. The
387 // refinement from the abstract (opaque) type to the new type causes all
388 // uses of the abstract type to use the concrete type (NewTy). This will
389 // also cause the opaque type to be deleted.
390 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
391
392 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000393 // value table... or with a preexisting type that was already in the
394 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000395 assert(TypeList[NumRecords-1].get() != OldTy &&
396 "refineAbstractType didn't work!");
397 }
398 }
399}
400
401
Chris Lattner86697142007-05-01 05:01:34 +0000402bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000403 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000404 return Error("Malformed block record");
405
406 SmallVector<uint64_t, 64> Record;
407
408 // Read all the records for this type table.
409 std::string TypeName;
410 while (1) {
411 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000412 if (Code == bitc::END_BLOCK) {
413 if (Stream.ReadBlockEnd())
414 return Error("Error at end of type symbol table block");
415 return false;
416 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000417
418 if (Code == bitc::ENTER_SUBBLOCK) {
419 // No known subblocks, always skip them.
420 Stream.ReadSubBlockID();
421 if (Stream.SkipBlock())
422 return Error("Malformed block record");
423 continue;
424 }
425
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000426 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000427 Stream.ReadAbbrevRecord();
428 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000429 }
430
431 // Read a record.
432 Record.clear();
433 switch (Stream.ReadRecord(Code, Record)) {
434 default: // Default behavior: unknown type.
435 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000436 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000437 if (ConvertToString(Record, 1, TypeName))
438 return Error("Invalid TST_ENTRY record");
439 unsigned TypeID = Record[0];
440 if (TypeID >= TypeList.size())
441 return Error("Invalid Type ID in TST_ENTRY record");
442
443 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
444 TypeName.clear();
445 break;
446 }
447 }
448}
449
Chris Lattner86697142007-05-01 05:01:34 +0000450bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000451 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000452 return Error("Malformed block record");
453
454 SmallVector<uint64_t, 64> Record;
455
456 // Read all the records for this value table.
457 SmallString<128> ValueName;
458 while (1) {
459 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000460 if (Code == bitc::END_BLOCK) {
461 if (Stream.ReadBlockEnd())
462 return Error("Error at end of value symbol table block");
463 return false;
464 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000465 if (Code == bitc::ENTER_SUBBLOCK) {
466 // No known subblocks, always skip them.
467 Stream.ReadSubBlockID();
468 if (Stream.SkipBlock())
469 return Error("Malformed block record");
470 continue;
471 }
472
473 if (Code == bitc::DEFINE_ABBREV) {
474 Stream.ReadAbbrevRecord();
475 continue;
476 }
477
478 // Read a record.
479 Record.clear();
480 switch (Stream.ReadRecord(Code, Record)) {
481 default: // Default behavior: unknown type.
482 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000483 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000484 if (ConvertToString(Record, 1, ValueName))
485 return Error("Invalid TST_ENTRY record");
486 unsigned ValueID = Record[0];
487 if (ValueID >= ValueList.size())
488 return Error("Invalid Value ID in VST_ENTRY record");
489 Value *V = ValueList[ValueID];
490
491 V->setName(&ValueName[0], ValueName.size());
492 ValueName.clear();
493 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000494 }
495 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000496 if (ConvertToString(Record, 1, ValueName))
497 return Error("Invalid VST_BBENTRY record");
498 BasicBlock *BB = getBasicBlock(Record[0]);
499 if (BB == 0)
500 return Error("Invalid BB ID in VST_BBENTRY record");
501
502 BB->setName(&ValueName[0], ValueName.size());
503 ValueName.clear();
504 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000505 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000506 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000507 }
508}
509
Chris Lattner0eef0802007-04-24 04:04:35 +0000510/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
511/// the LSB for dense VBR encoding.
512static uint64_t DecodeSignRotatedValue(uint64_t V) {
513 if ((V & 1) == 0)
514 return V >> 1;
515 if (V != 1)
516 return -(V >> 1);
517 // There is no such thing as -0 with integers. "-0" really means MININT.
518 return 1ULL << 63;
519}
520
Chris Lattner07d98b42007-04-26 02:46:40 +0000521/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
522/// values and aliases that we can.
523bool BitcodeReader::ResolveGlobalAndAliasInits() {
524 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
525 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
526
527 GlobalInitWorklist.swap(GlobalInits);
528 AliasInitWorklist.swap(AliasInits);
529
530 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000531 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000532 if (ValID >= ValueList.size()) {
533 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000534 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000535 } else {
536 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
537 GlobalInitWorklist.back().first->setInitializer(C);
538 else
539 return Error("Global variable initializer is not a constant!");
540 }
541 GlobalInitWorklist.pop_back();
542 }
543
544 while (!AliasInitWorklist.empty()) {
545 unsigned ValID = AliasInitWorklist.back().second;
546 if (ValID >= ValueList.size()) {
547 AliasInits.push_back(AliasInitWorklist.back());
548 } else {
549 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000550 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000551 else
552 return Error("Alias initializer is not a constant!");
553 }
554 AliasInitWorklist.pop_back();
555 }
556 return false;
557}
558
559
Chris Lattner86697142007-05-01 05:01:34 +0000560bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000561 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000562 return Error("Malformed block record");
563
564 SmallVector<uint64_t, 64> Record;
565
566 // Read all the records for this value table.
567 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000568 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000569 while (1) {
570 unsigned Code = Stream.ReadCode();
571 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000572 if (NextCstNo != ValueList.size())
573 return Error("Invalid constant reference!");
574
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000575 if (Stream.ReadBlockEnd())
576 return Error("Error at end of constants block");
577 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000578 }
579
580 if (Code == bitc::ENTER_SUBBLOCK) {
581 // No known subblocks, always skip them.
582 Stream.ReadSubBlockID();
583 if (Stream.SkipBlock())
584 return Error("Malformed block record");
585 continue;
586 }
587
588 if (Code == bitc::DEFINE_ABBREV) {
589 Stream.ReadAbbrevRecord();
590 continue;
591 }
592
593 // Read a record.
594 Record.clear();
595 Value *V = 0;
596 switch (Stream.ReadRecord(Code, Record)) {
597 default: // Default behavior: unknown constant
598 case bitc::CST_CODE_UNDEF: // UNDEF
599 V = UndefValue::get(CurTy);
600 break;
601 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
602 if (Record.empty())
603 return Error("Malformed CST_SETTYPE record");
604 if (Record[0] >= TypeList.size())
605 return Error("Invalid Type ID in CST_SETTYPE record");
606 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000607 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000608 case bitc::CST_CODE_NULL: // NULL
609 V = Constant::getNullValue(CurTy);
610 break;
611 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000612 if (!isa<IntegerType>(CurTy) || Record.empty())
613 return Error("Invalid CST_INTEGER record");
614 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
615 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000616 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
617 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000618 return Error("Invalid WIDE_INTEGER record");
619
Chris Lattner15e6d172007-05-04 19:11:41 +0000620 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000621 SmallVector<uint64_t, 8> Words;
622 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000623 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000624 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000625 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000626 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000627 break;
628 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000629 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000630 if (Record.empty())
631 return Error("Invalid FLOAT record");
632 if (CurTy == Type::FloatTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000633 V = ConstantFP::get(CurTy, APFloat(APInt(32, (uint32_t)Record[0])));
Chris Lattner0eef0802007-04-24 04:04:35 +0000634 else if (CurTy == Type::DoubleTy)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000635 V = ConstantFP::get(CurTy, APFloat(APInt(64, Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000636 else if (CurTy == Type::X86_FP80Ty)
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000637 V = ConstantFP::get(CurTy, APFloat(APInt(80, 2, &Record[0])));
Dale Johannesen43421b32007-09-06 18:13:44 +0000638 else if (CurTy == Type::FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000639 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesen43421b32007-09-06 18:13:44 +0000640 else if (CurTy == Type::PPC_FP128Ty)
Dale Johannesena471c2e2007-10-11 18:07:22 +0000641 V = ConstantFP::get(CurTy, APFloat(APInt(128, 2, &Record[0])));
Chris Lattnere16504e2007-04-24 03:30:34 +0000642 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000643 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000644 break;
Dale Johannesen3f6eb742007-09-11 18:32:33 +0000645 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000646
Chris Lattner15e6d172007-05-04 19:11:41 +0000647 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
648 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000649 return Error("Invalid CST_AGGREGATE record");
650
Chris Lattner15e6d172007-05-04 19:11:41 +0000651 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000652 std::vector<Constant*> Elts;
653
654 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
655 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000656 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000657 STy->getElementType(i)));
658 V = ConstantStruct::get(STy, Elts);
659 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
660 const Type *EltTy = ATy->getElementType();
661 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000662 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000663 V = ConstantArray::get(ATy, Elts);
664 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
665 const Type *EltTy = VTy->getElementType();
666 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000667 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000668 V = ConstantVector::get(Elts);
669 } else {
670 V = UndefValue::get(CurTy);
671 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000672 break;
673 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000674 case bitc::CST_CODE_STRING: { // STRING: [values]
675 if (Record.empty())
676 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000677
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000678 const ArrayType *ATy = cast<ArrayType>(CurTy);
679 const Type *EltTy = ATy->getElementType();
680
681 unsigned Size = Record.size();
682 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000683 for (unsigned i = 0; i != Size; ++i)
684 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
685 V = ConstantArray::get(ATy, Elts);
686 break;
687 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000688 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
689 if (Record.empty())
690 return Error("Invalid CST_AGGREGATE record");
691
692 const ArrayType *ATy = cast<ArrayType>(CurTy);
693 const Type *EltTy = ATy->getElementType();
694
695 unsigned Size = Record.size();
696 std::vector<Constant*> Elts;
697 for (unsigned i = 0; i != Size; ++i)
698 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
699 Elts.push_back(Constant::getNullValue(EltTy));
700 V = ConstantArray::get(ATy, Elts);
701 break;
702 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000703 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
704 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
705 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000706 if (Opc < 0) {
707 V = UndefValue::get(CurTy); // Unknown binop.
708 } else {
709 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
710 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
711 V = ConstantExpr::get(Opc, LHS, RHS);
712 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000713 break;
714 }
715 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
716 if (Record.size() < 3) return Error("Invalid CE_CAST record");
717 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000718 if (Opc < 0) {
719 V = UndefValue::get(CurTy); // Unknown cast.
720 } else {
721 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000722 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000723 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
724 V = ConstantExpr::getCast(Opc, Op, CurTy);
725 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000726 break;
727 }
728 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000729 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000730 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000731 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000732 const Type *ElTy = getTypeByID(Record[i]);
733 if (!ElTy) return Error("Invalid CE_GEP record");
734 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
735 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000736 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
737 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000738 }
739 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
740 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
741 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
742 Type::Int1Ty),
743 ValueList.getConstantFwdRef(Record[1],CurTy),
744 ValueList.getConstantFwdRef(Record[2],CurTy));
745 break;
746 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
747 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
748 const VectorType *OpTy =
749 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
750 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
751 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
752 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
753 OpTy->getElementType());
754 V = ConstantExpr::getExtractElement(Op0, Op1);
755 break;
756 }
757 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
758 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
759 if (Record.size() < 3 || OpTy == 0)
760 return Error("Invalid CE_INSERTELT record");
761 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
762 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
763 OpTy->getElementType());
764 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
765 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
766 break;
767 }
768 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
769 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
770 if (Record.size() < 3 || OpTy == 0)
771 return Error("Invalid CE_INSERTELT record");
772 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
773 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
774 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
775 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
776 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
777 break;
778 }
779 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
780 if (Record.size() < 4) return Error("Invalid CE_CMP record");
781 const Type *OpTy = getTypeByID(Record[0]);
782 if (OpTy == 0) return Error("Invalid CE_CMP record");
783 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
784 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
785
786 if (OpTy->isFloatingPoint())
787 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
788 else
789 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
790 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000791 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000792 case bitc::CST_CODE_INLINEASM: {
793 if (Record.size() < 2) return Error("Invalid INLINEASM record");
794 std::string AsmStr, ConstrStr;
795 bool HasSideEffects = Record[0];
796 unsigned AsmStrSize = Record[1];
797 if (2+AsmStrSize >= Record.size())
798 return Error("Invalid INLINEASM record");
799 unsigned ConstStrSize = Record[2+AsmStrSize];
800 if (3+AsmStrSize+ConstStrSize > Record.size())
801 return Error("Invalid INLINEASM record");
802
803 for (unsigned i = 0; i != AsmStrSize; ++i)
804 AsmStr += (char)Record[2+i];
805 for (unsigned i = 0; i != ConstStrSize; ++i)
806 ConstrStr += (char)Record[3+AsmStrSize+i];
807 const PointerType *PTy = cast<PointerType>(CurTy);
808 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
809 AsmStr, ConstrStr, HasSideEffects);
810 break;
811 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000812 }
813
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000814 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000815 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000816 }
817}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000818
Chris Lattner980e5aa2007-05-01 05:52:21 +0000819/// RememberAndSkipFunctionBody - When we see the block for a function body,
820/// remember where it is and then skip it. This lets us lazily deserialize the
821/// functions.
822bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000823 // Get the function we are talking about.
824 if (FunctionsWithBodies.empty())
825 return Error("Insufficient function protos");
826
827 Function *Fn = FunctionsWithBodies.back();
828 FunctionsWithBodies.pop_back();
829
830 // Save the current stream state.
831 uint64_t CurBit = Stream.GetCurrentBitNo();
832 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
833
834 // Set the functions linkage to GhostLinkage so we know it is lazily
835 // deserialized.
836 Fn->setLinkage(GlobalValue::GhostLinkage);
837
838 // Skip over the function block for now.
839 if (Stream.SkipBlock())
840 return Error("Malformed block record");
841 return false;
842}
843
Chris Lattner86697142007-05-01 05:01:34 +0000844bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000845 // Reject multiple MODULE_BLOCK's in a single bitstream.
846 if (TheModule)
847 return Error("Multiple MODULE_BLOCKs in same stream");
848
Chris Lattnere17b6582007-05-05 00:17:00 +0000849 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000850 return Error("Malformed block record");
851
852 // Otherwise, create the module.
853 TheModule = new Module(ModuleID);
854
855 SmallVector<uint64_t, 64> Record;
856 std::vector<std::string> SectionTable;
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000857 std::vector<std::string> CollectorTable;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000858
859 // Read all the records for this module.
860 while (!Stream.AtEndOfStream()) {
861 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000862 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000863 if (Stream.ReadBlockEnd())
864 return Error("Error at end of module block");
865
866 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000867 ResolveGlobalAndAliasInits();
868 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000869 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000870 if (!FunctionsWithBodies.empty())
871 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000872
Chandler Carruth69940402007-08-04 01:51:18 +0000873 // Look for intrinsic functions which need to be upgraded at some point
874 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
875 FI != FE; ++FI) {
Evan Chengf9b83fc2007-12-17 22:33:23 +0000876 Function* NewFn;
877 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carruth69940402007-08-04 01:51:18 +0000878 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
879 }
880
Chris Lattner980e5aa2007-05-01 05:52:21 +0000881 // Force deallocation of memory for these vectors to favor the client that
882 // want lazy deserialization.
883 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
884 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
885 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000886 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000887 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000888
889 if (Code == bitc::ENTER_SUBBLOCK) {
890 switch (Stream.ReadSubBlockID()) {
891 default: // Skip unknown content.
892 if (Stream.SkipBlock())
893 return Error("Malformed block record");
894 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000895 case bitc::BLOCKINFO_BLOCK_ID:
896 if (Stream.ReadBlockInfoBlock())
897 return Error("Malformed BlockInfoBlock");
898 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000899 case bitc::PARAMATTR_BLOCK_ID:
900 if (ParseParamAttrBlock())
901 return true;
902 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000903 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000904 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000905 return true;
906 break;
907 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000908 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000909 return true;
910 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000911 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000912 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000913 return true;
914 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000915 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000916 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000917 return true;
918 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000919 case bitc::FUNCTION_BLOCK_ID:
920 // If this is the first function body we've seen, reverse the
921 // FunctionsWithBodies list.
922 if (!HasReversedFunctionsWithBodies) {
923 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
924 HasReversedFunctionsWithBodies = true;
925 }
926
Chris Lattner980e5aa2007-05-01 05:52:21 +0000927 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000928 return true;
929 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000930 }
931 continue;
932 }
933
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000934 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000935 Stream.ReadAbbrevRecord();
936 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000937 }
938
939 // Read a record.
940 switch (Stream.ReadRecord(Code, Record)) {
941 default: break; // Default behavior, ignore unknown content.
942 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
943 if (Record.size() < 1)
944 return Error("Malformed MODULE_CODE_VERSION");
945 // Only version #0 is supported so far.
946 if (Record[0] != 0)
947 return Error("Unknown bitstream version!");
948 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000949 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000950 std::string S;
951 if (ConvertToString(Record, 0, S))
952 return Error("Invalid MODULE_CODE_TRIPLE record");
953 TheModule->setTargetTriple(S);
954 break;
955 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000956 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000957 std::string S;
958 if (ConvertToString(Record, 0, S))
959 return Error("Invalid MODULE_CODE_DATALAYOUT record");
960 TheModule->setDataLayout(S);
961 break;
962 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000963 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000964 std::string S;
965 if (ConvertToString(Record, 0, S))
966 return Error("Invalid MODULE_CODE_ASM record");
967 TheModule->setModuleInlineAsm(S);
968 break;
969 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000970 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000971 std::string S;
972 if (ConvertToString(Record, 0, S))
973 return Error("Invalid MODULE_CODE_DEPLIB record");
974 TheModule->addLibrary(S);
975 break;
976 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000977 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000978 std::string S;
979 if (ConvertToString(Record, 0, S))
980 return Error("Invalid MODULE_CODE_SECTIONNAME record");
981 SectionTable.push_back(S);
982 break;
983 }
Gordon Henriksen80a75bf2007-12-10 03:18:06 +0000984 case bitc::MODULE_CODE_COLLECTORNAME: { // SECTIONNAME: [strchr x N]
985 std::string S;
986 if (ConvertToString(Record, 0, S))
987 return Error("Invalid MODULE_CODE_COLLECTORNAME record");
988 CollectorTable.push_back(S);
989 break;
990 }
Christopher Lambfe63fb92007-12-11 08:59:05 +0000991 // GLOBALVAR: [pointer type, isconst, initid,
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000992 // linkage, alignment, section, visibility, threadlocal]
993 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000994 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000995 return Error("Invalid MODULE_CODE_GLOBALVAR record");
996 const Type *Ty = getTypeByID(Record[0]);
997 if (!isa<PointerType>(Ty))
998 return Error("Global not a pointer type!");
Christopher Lambfe63fb92007-12-11 08:59:05 +0000999 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001000 Ty = cast<PointerType>(Ty)->getElementType();
1001
1002 bool isConstant = Record[1];
1003 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1004 unsigned Alignment = (1 << Record[4]) >> 1;
1005 std::string Section;
1006 if (Record[5]) {
1007 if (Record[5]-1 >= SectionTable.size())
1008 return Error("Invalid section ID");
1009 Section = SectionTable[Record[5]-1];
1010 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001011 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +00001012 if (Record.size() > 6)
1013 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +00001014 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +00001015 if (Record.size() > 7)
1016 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001017
1018 GlobalVariable *NewGV =
Christopher Lambfe63fb92007-12-11 08:59:05 +00001019 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1020 isThreadLocal, AddressSpace);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001021 NewGV->setAlignment(Alignment);
1022 if (!Section.empty())
1023 NewGV->setSection(Section);
1024 NewGV->setVisibility(Visibility);
1025 NewGV->setThreadLocal(isThreadLocal);
1026
Chris Lattner0b2482a2007-04-23 21:26:05 +00001027 ValueList.push_back(NewGV);
1028
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001029 // Remember which value to use for the global initializer.
1030 if (unsigned InitID = Record[2])
1031 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001032 break;
1033 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001034 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001035 // alignment, section, visibility, collector]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001036 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001037 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001038 return Error("Invalid MODULE_CODE_FUNCTION record");
1039 const Type *Ty = getTypeByID(Record[0]);
1040 if (!isa<PointerType>(Ty))
1041 return Error("Function not a pointer type!");
1042 const FunctionType *FTy =
1043 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1044 if (!FTy)
1045 return Error("Function not a pointer to function type!");
1046
1047 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1048 "", TheModule);
1049
1050 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001051 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001052 Func->setLinkage(GetDecodedLinkage(Record[3]));
Duncan Sandsdc024672007-11-27 13:23:08 +00001053 const ParamAttrsList *PAL = getParamAttrs(Record[4]);
1054 Func->setParamAttrs(PAL);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001055
1056 Func->setAlignment((1 << Record[5]) >> 1);
1057 if (Record[6]) {
1058 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001059 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001060 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001061 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001062 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen80a75bf2007-12-10 03:18:06 +00001063 if (Record.size() > 8 && Record[8]) {
1064 if (Record[8]-1 > CollectorTable.size())
1065 return Error("Invalid collector ID");
1066 Func->setCollector(CollectorTable[Record[8]-1].c_str());
1067 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001068
Chris Lattner0b2482a2007-04-23 21:26:05 +00001069 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001070
1071 // If this is a function with a body, remember the prototype we are
1072 // creating now, so that we can match up the body with them later.
1073 if (!isProto)
1074 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001075 break;
1076 }
Chris Lattner07d98b42007-04-26 02:46:40 +00001077 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +00001078 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001079 if (Record.size() < 3)
1080 return Error("Invalid MODULE_ALIAS record");
1081 const Type *Ty = getTypeByID(Record[0]);
1082 if (!isa<PointerType>(Ty))
1083 return Error("Function not a pointer type!");
1084
1085 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1086 "", 0, TheModule);
1087 ValueList.push_back(NewGA);
1088 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1089 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001090 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001091 /// MODULE_CODE_PURGEVALS: [numvals]
1092 case bitc::MODULE_CODE_PURGEVALS:
1093 // Trim down the value list to the specified size.
1094 if (Record.size() < 1 || Record[0] > ValueList.size())
1095 return Error("Invalid MODULE_PURGEVALS record");
1096 ValueList.shrinkTo(Record[0]);
1097 break;
1098 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001099 Record.clear();
1100 }
1101
1102 return Error("Premature end of bitstream");
1103}
1104
1105
Chris Lattnerc453f762007-04-29 07:54:31 +00001106bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001107 TheModule = 0;
1108
Chris Lattnerc453f762007-04-29 07:54:31 +00001109 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001110 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1111
Chris Lattnerc453f762007-04-29 07:54:31 +00001112 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001113 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001114
1115 // Sniff for the signature.
1116 if (Stream.Read(8) != 'B' ||
1117 Stream.Read(8) != 'C' ||
1118 Stream.Read(4) != 0x0 ||
1119 Stream.Read(4) != 0xC ||
1120 Stream.Read(4) != 0xE ||
1121 Stream.Read(4) != 0xD)
1122 return Error("Invalid bitcode signature");
1123
1124 // We expect a number of well-defined blocks, though we don't necessarily
1125 // need to understand them all.
1126 while (!Stream.AtEndOfStream()) {
1127 unsigned Code = Stream.ReadCode();
1128
1129 if (Code != bitc::ENTER_SUBBLOCK)
1130 return Error("Invalid record at top-level");
1131
1132 unsigned BlockID = Stream.ReadSubBlockID();
1133
1134 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001135 switch (BlockID) {
1136 case bitc::BLOCKINFO_BLOCK_ID:
1137 if (Stream.ReadBlockInfoBlock())
1138 return Error("Malformed BlockInfoBlock");
1139 break;
1140 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001141 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001142 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001143 break;
1144 default:
1145 if (Stream.SkipBlock())
1146 return Error("Malformed block record");
1147 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001148 }
1149 }
1150
1151 return false;
1152}
Chris Lattnerc453f762007-04-29 07:54:31 +00001153
Chris Lattner48f84872007-05-01 04:59:48 +00001154
Chris Lattner980e5aa2007-05-01 05:52:21 +00001155/// ParseFunctionBody - Lazily parse the specified function body block.
1156bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001157 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001158 return Error("Malformed block record");
1159
1160 unsigned ModuleValueListSize = ValueList.size();
1161
1162 // Add all the function arguments to the value table.
1163 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1164 ValueList.push_back(I);
1165
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001166 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001167 BasicBlock *CurBB = 0;
1168 unsigned CurBBNo = 0;
1169
Chris Lattner980e5aa2007-05-01 05:52:21 +00001170 // Read all the records.
1171 SmallVector<uint64_t, 64> Record;
1172 while (1) {
1173 unsigned Code = Stream.ReadCode();
1174 if (Code == bitc::END_BLOCK) {
1175 if (Stream.ReadBlockEnd())
1176 return Error("Error at end of function block");
1177 break;
1178 }
1179
1180 if (Code == bitc::ENTER_SUBBLOCK) {
1181 switch (Stream.ReadSubBlockID()) {
1182 default: // Skip unknown content.
1183 if (Stream.SkipBlock())
1184 return Error("Malformed block record");
1185 break;
1186 case bitc::CONSTANTS_BLOCK_ID:
1187 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001188 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001189 break;
1190 case bitc::VALUE_SYMTAB_BLOCK_ID:
1191 if (ParseValueSymbolTable()) return true;
1192 break;
1193 }
1194 continue;
1195 }
1196
1197 if (Code == bitc::DEFINE_ABBREV) {
1198 Stream.ReadAbbrevRecord();
1199 continue;
1200 }
1201
1202 // Read a record.
1203 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001204 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001205 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001206 default: // Default behavior: reject
1207 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001208 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001209 if (Record.size() < 1 || Record[0] == 0)
1210 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001211 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001212 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001213 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1214 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001215 CurBB = FunctionBBs[0];
1216 continue;
1217
Chris Lattnerabfbf852007-05-06 00:21:25 +00001218 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1219 unsigned OpNum = 0;
1220 Value *LHS, *RHS;
1221 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1222 getValue(Record, OpNum, LHS->getType(), RHS) ||
1223 OpNum+1 != Record.size())
1224 return Error("Invalid BINOP record");
1225
1226 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1227 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001228 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001229 break;
1230 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001231 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1232 unsigned OpNum = 0;
1233 Value *Op;
1234 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1235 OpNum+2 != Record.size())
1236 return Error("Invalid CAST record");
1237
1238 const Type *ResTy = getTypeByID(Record[OpNum]);
1239 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1240 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001241 return Error("Invalid CAST record");
1242 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1243 break;
1244 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001245 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001246 unsigned OpNum = 0;
1247 Value *BasePtr;
1248 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001249 return Error("Invalid GEP record");
1250
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001251 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001252 while (OpNum != Record.size()) {
1253 Value *Op;
1254 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001255 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001256 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001257 }
1258
David Greeneb8f74792007-09-04 15:46:09 +00001259 I = new GetElementPtrInst(BasePtr, GEPIdx.begin(), GEPIdx.end());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001260 break;
1261 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001262
Chris Lattnerabfbf852007-05-06 00:21:25 +00001263 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1264 unsigned OpNum = 0;
1265 Value *TrueVal, *FalseVal, *Cond;
1266 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1267 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1268 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001269 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001270
1271 I = new SelectInst(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001272 break;
1273 }
1274
1275 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001276 unsigned OpNum = 0;
1277 Value *Vec, *Idx;
1278 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1279 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001280 return Error("Invalid EXTRACTELT record");
1281 I = new ExtractElementInst(Vec, Idx);
1282 break;
1283 }
1284
1285 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001286 unsigned OpNum = 0;
1287 Value *Vec, *Elt, *Idx;
1288 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1289 getValue(Record, OpNum,
1290 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1291 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001292 return Error("Invalid INSERTELT record");
1293 I = new InsertElementInst(Vec, Elt, Idx);
1294 break;
1295 }
1296
Chris Lattnerabfbf852007-05-06 00:21:25 +00001297 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1298 unsigned OpNum = 0;
1299 Value *Vec1, *Vec2, *Mask;
1300 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1301 getValue(Record, OpNum, Vec1->getType(), Vec2))
1302 return Error("Invalid SHUFFLEVEC record");
1303
1304 const Type *MaskTy =
1305 VectorType::get(Type::Int32Ty,
1306 cast<VectorType>(Vec1->getType())->getNumElements());
1307
1308 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001309 return Error("Invalid SHUFFLEVEC record");
1310 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1311 break;
1312 }
1313
1314 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001315 unsigned OpNum = 0;
1316 Value *LHS, *RHS;
1317 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1318 getValue(Record, OpNum, LHS->getType(), RHS) ||
1319 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001320 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001321
1322 if (LHS->getType()->isFPOrFPVector())
1323 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001324 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001325 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001326 break;
1327 }
1328
Chris Lattner231cbcb2007-05-02 04:27:25 +00001329 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1330 if (Record.size() == 0) {
1331 I = new ReturnInst();
1332 break;
Chris Lattner7337ab92007-05-06 00:00:00 +00001333 } else {
1334 unsigned OpNum = 0;
1335 Value *Op;
1336 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1337 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001338 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001339 I = new ReturnInst(Op);
1340 break;
1341 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001342 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001343 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001344 return Error("Invalid BR record");
1345 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1346 if (TrueDest == 0)
1347 return Error("Invalid BR record");
1348
1349 if (Record.size() == 1)
1350 I = new BranchInst(TrueDest);
1351 else {
1352 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1353 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1354 if (FalseDest == 0 || Cond == 0)
1355 return Error("Invalid BR record");
1356 I = new BranchInst(TrueDest, FalseDest, Cond);
1357 }
1358 break;
1359 }
1360 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1361 if (Record.size() < 3 || (Record.size() & 1) == 0)
1362 return Error("Invalid SWITCH record");
1363 const Type *OpTy = getTypeByID(Record[0]);
1364 Value *Cond = getFnValueByID(Record[1], OpTy);
1365 BasicBlock *Default = getBasicBlock(Record[2]);
1366 if (OpTy == 0 || Cond == 0 || Default == 0)
1367 return Error("Invalid SWITCH record");
1368 unsigned NumCases = (Record.size()-3)/2;
1369 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1370 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1371 ConstantInt *CaseVal =
1372 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1373 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1374 if (CaseVal == 0 || DestBB == 0) {
1375 delete SI;
1376 return Error("Invalid SWITCH record!");
1377 }
1378 SI->addCase(CaseVal, DestBB);
1379 }
1380 I = SI;
1381 break;
1382 }
1383
Duncan Sandsdc024672007-11-27 13:23:08 +00001384 case bitc::FUNC_CODE_INST_INVOKE: {
1385 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001386 if (Record.size() < 4) return Error("Invalid INVOKE record");
Duncan Sandsdc024672007-11-27 13:23:08 +00001387 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001388 unsigned CCInfo = Record[1];
1389 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1390 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001391
Chris Lattnera9bb7132007-05-08 05:38:01 +00001392 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001393 Value *Callee;
1394 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001395 return Error("Invalid INVOKE record");
1396
Chris Lattner7337ab92007-05-06 00:00:00 +00001397 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1398 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001399 dyn_cast<FunctionType>(CalleeTy->getElementType());
1400
1401 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001402 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1403 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001404 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001405
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001406 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001407 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1408 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1409 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001410 }
1411
Chris Lattner7337ab92007-05-06 00:00:00 +00001412 if (!FTy->isVarArg()) {
1413 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001414 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001415 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001416 // Read type/value pairs for varargs params.
1417 while (OpNum != Record.size()) {
1418 Value *Op;
1419 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1420 return Error("Invalid INVOKE record");
1421 Ops.push_back(Op);
1422 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001423 }
1424
David Greenef1355a52007-08-27 19:04:21 +00001425 I = new InvokeInst(Callee, NormalBB, UnwindBB, Ops.begin(), Ops.end());
Chris Lattner76520192007-05-03 22:34:03 +00001426 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Duncan Sandsdc024672007-11-27 13:23:08 +00001427 cast<InvokeInst>(I)->setParamAttrs(PAL);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001428 break;
1429 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001430 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1431 I = new UnwindInst();
1432 break;
1433 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1434 I = new UnreachableInst();
1435 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001436 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001437 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001438 return Error("Invalid PHI record");
1439 const Type *Ty = getTypeByID(Record[0]);
1440 if (!Ty) return Error("Invalid PHI record");
1441
1442 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001443 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001444
Chris Lattner15e6d172007-05-04 19:11:41 +00001445 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1446 Value *V = getFnValueByID(Record[1+i], Ty);
1447 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001448 if (!V || !BB) return Error("Invalid PHI record");
1449 PN->addIncoming(V, BB);
1450 }
1451 I = PN;
1452 break;
1453 }
1454
1455 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1456 if (Record.size() < 3)
1457 return Error("Invalid MALLOC record");
1458 const PointerType *Ty =
1459 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1460 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1461 unsigned Align = Record[2];
1462 if (!Ty || !Size) return Error("Invalid MALLOC record");
1463 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1464 break;
1465 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001466 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1467 unsigned OpNum = 0;
1468 Value *Op;
1469 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1470 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001471 return Error("Invalid FREE record");
1472 I = new FreeInst(Op);
1473 break;
1474 }
1475 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1476 if (Record.size() < 3)
1477 return Error("Invalid ALLOCA record");
1478 const PointerType *Ty =
1479 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1480 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1481 unsigned Align = Record[2];
1482 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1483 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1484 break;
1485 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001486 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001487 unsigned OpNum = 0;
1488 Value *Op;
1489 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1490 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001491 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001492
1493 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001494 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001495 }
Christopher Lambfe63fb92007-12-11 08:59:05 +00001496 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1497 unsigned OpNum = 0;
1498 Value *Val, *Ptr;
1499 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1500 getValue(Record, OpNum,
1501 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1502 OpNum+2 != Record.size())
1503 return Error("Invalid STORE record");
1504
1505 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1506 break;
1507 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001508 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lambfe63fb92007-12-11 08:59:05 +00001509 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Chris Lattnerabfbf852007-05-06 00:21:25 +00001510 unsigned OpNum = 0;
1511 Value *Val, *Ptr;
1512 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Christopher Lamb43ad6b32007-12-17 01:12:55 +00001513 getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
Chris Lattnerabfbf852007-05-06 00:21:25 +00001514 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001515 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001516
1517 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001518 break;
1519 }
Duncan Sandsdc024672007-11-27 13:23:08 +00001520 case bitc::FUNC_CODE_INST_CALL: {
1521 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1522 if (Record.size() < 3)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001523 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001524
Duncan Sandsdc024672007-11-27 13:23:08 +00001525 const ParamAttrsList *PAL = getParamAttrs(Record[0]);
Chris Lattnera9bb7132007-05-08 05:38:01 +00001526 unsigned CCInfo = Record[1];
1527
1528 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001529 Value *Callee;
1530 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1531 return Error("Invalid CALL record");
1532
1533 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001534 const FunctionType *FTy = 0;
1535 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001536 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001537 return Error("Invalid CALL record");
1538
1539 SmallVector<Value*, 16> Args;
1540 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001541 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00001542 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1543 Args.push_back(getBasicBlock(Record[OpNum]));
1544 else
1545 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001546 if (Args.back() == 0) return Error("Invalid CALL record");
1547 }
1548
Chris Lattner0579f7f2007-05-03 22:04:19 +00001549 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001550 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001551 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001552 return Error("Invalid CALL record");
1553 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001554 while (OpNum != Record.size()) {
1555 Value *Op;
1556 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1557 return Error("Invalid CALL record");
1558 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001559 }
1560 }
1561
David Greene52eec542007-08-01 03:43:44 +00001562 I = new CallInst(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001563 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1564 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Duncan Sandsdc024672007-11-27 13:23:08 +00001565 cast<CallInst>(I)->setParamAttrs(PAL);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001566 break;
1567 }
1568 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1569 if (Record.size() < 3)
1570 return Error("Invalid VAARG record");
1571 const Type *OpTy = getTypeByID(Record[0]);
1572 Value *Op = getFnValueByID(Record[1], OpTy);
1573 const Type *ResTy = getTypeByID(Record[2]);
1574 if (!OpTy || !Op || !ResTy)
1575 return Error("Invalid VAARG record");
1576 I = new VAArgInst(Op, ResTy);
1577 break;
1578 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001579 }
1580
1581 // Add instruction to end of current BB. If there is no current BB, reject
1582 // this file.
1583 if (CurBB == 0) {
1584 delete I;
1585 return Error("Invalid instruction with no BB");
1586 }
1587 CurBB->getInstList().push_back(I);
1588
1589 // If this was a terminator instruction, move to the next block.
1590 if (isa<TerminatorInst>(I)) {
1591 ++CurBBNo;
1592 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1593 }
1594
1595 // Non-void values get registered in the value table for future use.
1596 if (I && I->getType() != Type::VoidTy)
1597 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001598 }
1599
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001600 // Check the function list for unresolved values.
1601 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1602 if (A->getParent() == 0) {
1603 // We found at least one unresolved value. Nuke them all to avoid leaks.
1604 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1605 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1606 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1607 delete A;
1608 }
1609 }
Chris Lattner35a04702007-05-04 03:50:29 +00001610 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001611 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001612 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001613
1614 // Trim the value list down to the size it was before we parsed this function.
1615 ValueList.shrinkTo(ModuleValueListSize);
1616 std::vector<BasicBlock*>().swap(FunctionBBs);
1617
Chris Lattner48f84872007-05-01 04:59:48 +00001618 return false;
1619}
1620
Chris Lattnerb348bb82007-05-18 04:02:46 +00001621//===----------------------------------------------------------------------===//
1622// ModuleProvider implementation
1623//===----------------------------------------------------------------------===//
1624
1625
1626bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1627 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001628 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001629
1630 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1631 DeferredFunctionInfo.find(F);
1632 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1633
1634 // Move the bit stream to the saved position of the deferred function body and
1635 // restore the real linkage type for the function.
1636 Stream.JumpToBit(DFII->second.first);
1637 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1638
1639 if (ParseFunctionBody(F)) {
1640 if (ErrInfo) *ErrInfo = ErrorString;
1641 return true;
1642 }
Chandler Carruth69940402007-08-04 01:51:18 +00001643
1644 // Upgrade any old intrinsic calls in the function.
1645 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1646 E = UpgradedIntrinsics.end(); I != E; ++I) {
1647 if (I->first != I->second) {
1648 for (Value::use_iterator UI = I->first->use_begin(),
1649 UE = I->first->use_end(); UI != UE; ) {
1650 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1651 UpgradeIntrinsicCall(CI, I->second);
1652 }
1653 }
1654 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001655
1656 return false;
1657}
1658
1659void BitcodeReader::dematerializeFunction(Function *F) {
1660 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001661 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001662 return;
1663
1664 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1665
1666 // Just forget the function body, we can remat it later.
1667 F->deleteBody();
1668 F->setLinkage(GlobalValue::GhostLinkage);
1669}
1670
1671
1672Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1673 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1674 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1675 ++I) {
1676 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001677 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001678 materializeFunction(F, ErrInfo))
1679 return 0;
1680 }
Chandler Carruth69940402007-08-04 01:51:18 +00001681
1682 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1683 // delete the old functions to clean up. We can't do this unless the entire
1684 // module is materialized because there could always be another function body
1685 // with calls to the old function.
1686 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1687 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1688 if (I->first != I->second) {
1689 for (Value::use_iterator UI = I->first->use_begin(),
1690 UE = I->first->use_end(); UI != UE; ) {
1691 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1692 UpgradeIntrinsicCall(CI, I->second);
1693 }
1694 ValueList.replaceUsesOfWith(I->first, I->second);
1695 I->first->eraseFromParent();
1696 }
1697 }
1698 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1699
Chris Lattnerb348bb82007-05-18 04:02:46 +00001700 return TheModule;
1701}
1702
1703
1704/// This method is provided by the parent ModuleProvde class and overriden
1705/// here. It simply releases the module from its provided and frees up our
1706/// state.
1707/// @brief Release our hold on the generated module
1708Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1709 // Since we're losing control of this Module, we must hand it back complete
1710 Module *M = ModuleProvider::releaseModule(ErrInfo);
1711 FreeState();
1712 return M;
1713}
1714
Chris Lattner48f84872007-05-01 04:59:48 +00001715
Chris Lattnerc453f762007-04-29 07:54:31 +00001716//===----------------------------------------------------------------------===//
1717// External interface
1718//===----------------------------------------------------------------------===//
1719
1720/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1721///
1722ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1723 std::string *ErrMsg) {
1724 BitcodeReader *R = new BitcodeReader(Buffer);
1725 if (R->ParseBitcode()) {
1726 if (ErrMsg)
1727 *ErrMsg = R->getErrorString();
1728
1729 // Don't let the BitcodeReader dtor delete 'Buffer'.
1730 R->releaseMemoryBuffer();
1731 delete R;
1732 return 0;
1733 }
1734 return R;
1735}
1736
1737/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1738/// If an error occurs, return null and fill in *ErrMsg if non-null.
1739Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1740 BitcodeReader *R;
1741 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1742 if (!R) return 0;
1743
Chris Lattnerb348bb82007-05-18 04:02:46 +00001744 // Read in the entire module.
1745 Module *M = R->materializeModule(ErrMsg);
1746
1747 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1748 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001749 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001750
1751 // If there was no error, tell ModuleProvider not to delete it when its dtor
1752 // is run.
1753 if (M)
1754 M = R->releaseModule(ErrMsg);
1755
Chris Lattnerc453f762007-04-29 07:54:31 +00001756 delete R;
1757 return M;
1758}