blob: bc1eba01e2d398876266d6ef9cda1cb43bbe76c2 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Bitcode/ReaderWriter.h"
15#include "BitcodeReader.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/InlineAsm.h"
19#include "llvm/Instructions.h"
Owen Anderson4956cde2009-07-07 20:18:58 +000020#include "llvm/LLVMContext.h"
Nick Lewycky117f4382009-05-10 20:57:05 +000021#include "llvm/MDNode.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Module.h"
Chandler Carrutha228e392007-08-04 01:51:18 +000023#include "llvm/AutoUpgrade.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/ADT/SmallString.h"
Devang Patel57652392008-02-26 19:38:17 +000025#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/MemoryBuffer.h"
Gabor Greif25bc3222008-05-10 08:32:32 +000028#include "llvm/OperandTraits.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029using namespace llvm;
30
31void BitcodeReader::FreeState() {
32 delete Buffer;
33 Buffer = 0;
34 std::vector<PATypeHolder>().swap(TypeList);
35 ValueList.clear();
Chris Lattner2ee85532008-03-12 02:25:52 +000036
Devang Patelf2a4a922008-09-26 22:53:05 +000037 std::vector<AttrListPtr>().swap(MAttributes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038 std::vector<BasicBlock*>().swap(FunctionBBs);
39 std::vector<Function*>().swap(FunctionsWithBodies);
40 DeferredFunctionInfo.clear();
41}
42
43//===----------------------------------------------------------------------===//
44// Helper functions to implement forward reference resolution, etc.
45//===----------------------------------------------------------------------===//
46
47/// ConvertToString - Convert a string from a record into an std::string, return
48/// true on failure.
49template<typename StrTy>
50static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
51 StrTy &Result) {
52 if (Idx > Record.size())
53 return true;
54
55 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
56 Result += (char)Record[i];
57 return false;
58}
59
60static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
61 switch (Val) {
62 default: // Map unknown/new linkages to external
Bill Wendling41a07852009-07-20 01:03:30 +000063 case 0: return GlobalValue::ExternalLinkage;
64 case 1: return GlobalValue::WeakAnyLinkage;
65 case 2: return GlobalValue::AppendingLinkage;
66 case 3: return GlobalValue::InternalLinkage;
67 case 4: return GlobalValue::LinkOnceAnyLinkage;
68 case 5: return GlobalValue::DLLImportLinkage;
69 case 6: return GlobalValue::DLLExportLinkage;
70 case 7: return GlobalValue::ExternalWeakLinkage;
71 case 8: return GlobalValue::CommonLinkage;
72 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands19d161f2009-03-07 15:45:40 +000073 case 10: return GlobalValue::WeakODRLinkage;
74 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner68433442009-04-13 05:44:34 +000075 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling41a07852009-07-20 01:03:30 +000076 case 13: return GlobalValue::LinkerPrivateLinkage;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077 }
78}
79
80static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
81 switch (Val) {
82 default: // Map unknown visibilities to default.
83 case 0: return GlobalValue::DefaultVisibility;
84 case 1: return GlobalValue::HiddenVisibility;
85 case 2: return GlobalValue::ProtectedVisibility;
86 }
87}
88
89static int GetDecodedCastOpcode(unsigned Val) {
90 switch (Val) {
91 default: return -1;
92 case bitc::CAST_TRUNC : return Instruction::Trunc;
93 case bitc::CAST_ZEXT : return Instruction::ZExt;
94 case bitc::CAST_SEXT : return Instruction::SExt;
95 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
96 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
97 case bitc::CAST_UITOFP : return Instruction::UIToFP;
98 case bitc::CAST_SITOFP : return Instruction::SIToFP;
99 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
100 case bitc::CAST_FPEXT : return Instruction::FPExt;
101 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
102 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
103 case bitc::CAST_BITCAST : return Instruction::BitCast;
104 }
105}
106static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
107 switch (Val) {
108 default: return -1;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000109 case bitc::BINOP_ADD:
110 return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
111 case bitc::BINOP_SUB:
112 return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
113 case bitc::BINOP_MUL:
114 return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115 case bitc::BINOP_UDIV: return Instruction::UDiv;
116 case bitc::BINOP_SDIV:
117 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
118 case bitc::BINOP_UREM: return Instruction::URem;
119 case bitc::BINOP_SREM:
120 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
121 case bitc::BINOP_SHL: return Instruction::Shl;
122 case bitc::BINOP_LSHR: return Instruction::LShr;
123 case bitc::BINOP_ASHR: return Instruction::AShr;
124 case bitc::BINOP_AND: return Instruction::And;
125 case bitc::BINOP_OR: return Instruction::Or;
126 case bitc::BINOP_XOR: return Instruction::Xor;
127 }
128}
129
Gabor Greif25bc3222008-05-10 08:32:32 +0000130namespace llvm {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131namespace {
132 /// @brief A class for maintaining the slot number definition
133 /// as a placeholder for the actual definition for forward constants defs.
134 class ConstantPlaceHolder : public ConstantExpr {
135 ConstantPlaceHolder(); // DO NOT IMPLEMENT
136 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greifd6da1d02008-04-06 20:25:17 +0000137 public:
138 // allocate space for exactly one operand
139 void *operator new(size_t s) {
140 return User::operator new(s, 1);
141 }
Owen Anderson4956cde2009-07-07 20:18:58 +0000142 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
Gabor Greif25bc3222008-05-10 08:32:32 +0000143 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000144 Op<0>() = Context.getUndef(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 }
Chris Lattner345bbb72008-08-21 02:34:16 +0000146
147 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
148 static inline bool classof(const ConstantPlaceHolder *) { return true; }
149 static bool classof(const Value *V) {
150 return isa<ConstantExpr>(V) &&
151 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
152 }
153
154
Gabor Greif25bc3222008-05-10 08:32:32 +0000155 /// Provide fast operand accessors
Chris Lattnered490d12009-03-31 22:55:09 +0000156 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 };
158}
159
Chris Lattnered490d12009-03-31 22:55:09 +0000160// FIXME: can we inherit this from ConstantExpr?
Gabor Greif25bc3222008-05-10 08:32:32 +0000161template <>
162struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
163};
Gabor Greif25bc3222008-05-10 08:32:32 +0000164}
165
Chris Lattnered490d12009-03-31 22:55:09 +0000166
167void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
168 if (Idx == size()) {
169 push_back(V);
170 return;
171 }
172
173 if (Idx >= size())
174 resize(Idx+1);
175
176 WeakVH &OldV = ValuePtrs[Idx];
177 if (OldV == 0) {
178 OldV = V;
179 return;
180 }
181
182 // Handle constants and non-constants (e.g. instrs) differently for
183 // efficiency.
184 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
185 ResolveConstants.push_back(std::make_pair(PHC, Idx));
186 OldV = V;
187 } else {
188 // If there was a forward reference to this value, replace it.
189 Value *PrevVal = OldV;
190 OldV->replaceAllUsesWith(V);
191 delete PrevVal;
Gabor Greif25bc3222008-05-10 08:32:32 +0000192 }
193}
Chris Lattnered490d12009-03-31 22:55:09 +0000194
Gabor Greif25bc3222008-05-10 08:32:32 +0000195
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
197 const Type *Ty) {
Chris Lattnered490d12009-03-31 22:55:09 +0000198 if (Idx >= size())
Gabor Greif25bc3222008-05-10 08:32:32 +0000199 resize(Idx + 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200
Chris Lattnered490d12009-03-31 22:55:09 +0000201 if (Value *V = ValuePtrs[Idx]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 assert(Ty == V->getType() && "Type mismatch in constant table!");
203 return cast<Constant>(V);
204 }
205
206 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson4956cde2009-07-07 20:18:58 +0000207 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattnered490d12009-03-31 22:55:09 +0000208 ValuePtrs[Idx] = C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 return C;
210}
211
212Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
Chris Lattnered490d12009-03-31 22:55:09 +0000213 if (Idx >= size())
Gabor Greif25bc3222008-05-10 08:32:32 +0000214 resize(Idx + 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215
Chris Lattnered490d12009-03-31 22:55:09 +0000216 if (Value *V = ValuePtrs[Idx]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
218 return V;
219 }
220
221 // No type specified, must be invalid reference.
222 if (Ty == 0) return 0;
223
224 // Create and return a placeholder, which will later be RAUW'd.
225 Value *V = new Argument(Ty);
Chris Lattnered490d12009-03-31 22:55:09 +0000226 ValuePtrs[Idx] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 return V;
228}
229
Chris Lattner345bbb72008-08-21 02:34:16 +0000230/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
231/// resolves any forward references. The idea behind this is that we sometimes
232/// get constants (such as large arrays) which reference *many* forward ref
233/// constants. Replacing each of these causes a lot of thrashing when
234/// building/reuniquing the constant. Instead of doing this, we look at all the
235/// uses and rewrite all the place holders at once for any constant that uses
236/// a placeholder.
237void BitcodeReaderValueList::ResolveConstantForwardRefs() {
238 // Sort the values by-pointer so that they are efficient to look up with a
239 // binary search.
240 std::sort(ResolveConstants.begin(), ResolveConstants.end());
241
242 SmallVector<Constant*, 64> NewOps;
243
244 while (!ResolveConstants.empty()) {
Chris Lattnered490d12009-03-31 22:55:09 +0000245 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner345bbb72008-08-21 02:34:16 +0000246 Constant *Placeholder = ResolveConstants.back().first;
247 ResolveConstants.pop_back();
248
249 // Loop over all users of the placeholder, updating them to reference the
250 // new value. If they reference more than one placeholder, update them all
251 // at once.
252 while (!Placeholder->use_empty()) {
Chris Lattner8ae2e252008-08-21 17:31:45 +0000253 Value::use_iterator UI = Placeholder->use_begin();
254
Chris Lattner345bbb72008-08-21 02:34:16 +0000255 // If the using object isn't uniqued, just update the operands. This
256 // handles instructions and initializers for global variables.
Chris Lattner8ae2e252008-08-21 17:31:45 +0000257 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
258 UI.getUse().set(RealVal);
Chris Lattner345bbb72008-08-21 02:34:16 +0000259 continue;
260 }
261
262 // Otherwise, we have a constant that uses the placeholder. Replace that
263 // constant with a new constant that has *all* placeholder uses updated.
Chris Lattner8ae2e252008-08-21 17:31:45 +0000264 Constant *UserC = cast<Constant>(*UI);
Chris Lattner345bbb72008-08-21 02:34:16 +0000265 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
266 I != E; ++I) {
267 Value *NewOp;
268 if (!isa<ConstantPlaceHolder>(*I)) {
269 // Not a placeholder reference.
270 NewOp = *I;
271 } else if (*I == Placeholder) {
272 // Common case is that it just references this one placeholder.
273 NewOp = RealVal;
274 } else {
275 // Otherwise, look up the placeholder in ResolveConstants.
276 ResolveConstantsTy::iterator It =
277 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
278 std::pair<Constant*, unsigned>(cast<Constant>(*I),
279 0));
280 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattnered490d12009-03-31 22:55:09 +0000281 NewOp = operator[](It->second);
Chris Lattner345bbb72008-08-21 02:34:16 +0000282 }
283
284 NewOps.push_back(cast<Constant>(NewOp));
285 }
286
287 // Make the new constant.
288 Constant *NewC;
289 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000290 NewC = Context.getConstantArray(UserCA->getType(), &NewOps[0],
291 NewOps.size());
Chris Lattner345bbb72008-08-21 02:34:16 +0000292 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000293 NewC = Context.getConstantStruct(&NewOps[0], NewOps.size(),
294 UserCS->getType()->isPacked());
Chris Lattner345bbb72008-08-21 02:34:16 +0000295 } else if (isa<ConstantVector>(UserC)) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000296 NewC = Context.getConstantVector(&NewOps[0], NewOps.size());
Nick Lewycky117f4382009-05-10 20:57:05 +0000297 } else {
298 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Chris Lattner345bbb72008-08-21 02:34:16 +0000299 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
300 NewOps.size());
301 }
302
303 UserC->replaceAllUsesWith(NewC);
304 UserC->destroyConstant();
305 NewOps.clear();
306 }
307
Nick Lewycky117f4382009-05-10 20:57:05 +0000308 // Update all ValueHandles, they should be the only users at this point.
309 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner345bbb72008-08-21 02:34:16 +0000310 delete Placeholder;
311 }
312}
313
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314
315const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
316 // If the TypeID is in range, return it.
317 if (ID < TypeList.size())
318 return TypeList[ID].get();
319 if (!isTypeTable) return 0;
320
321 // The type table allows forward references. Push as many Opaque types as
322 // needed to get up to ID.
323 while (TypeList.size() <= ID)
Owen Anderson4956cde2009-07-07 20:18:58 +0000324 TypeList.push_back(Context.getOpaqueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 return TypeList.back().get();
326}
327
328//===----------------------------------------------------------------------===//
329// Functions for parsing blocks from the bitcode file
330//===----------------------------------------------------------------------===//
331
Devang Pateld222f862008-09-25 21:00:45 +0000332bool BitcodeReader::ParseAttributeBlock() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
334 return Error("Malformed block record");
335
Devang Patelf2a4a922008-09-26 22:53:05 +0000336 if (!MAttributes.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 return Error("Multiple PARAMATTR blocks found!");
338
339 SmallVector<uint64_t, 64> Record;
340
Devang Pateld222f862008-09-25 21:00:45 +0000341 SmallVector<AttributeWithIndex, 8> Attrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342
343 // Read all the records.
344 while (1) {
345 unsigned Code = Stream.ReadCode();
346 if (Code == bitc::END_BLOCK) {
347 if (Stream.ReadBlockEnd())
348 return Error("Error at end of PARAMATTR block");
349 return false;
350 }
351
352 if (Code == bitc::ENTER_SUBBLOCK) {
353 // No known subblocks, always skip them.
354 Stream.ReadSubBlockID();
355 if (Stream.SkipBlock())
356 return Error("Malformed block record");
357 continue;
358 }
359
360 if (Code == bitc::DEFINE_ABBREV) {
361 Stream.ReadAbbrevRecord();
362 continue;
363 }
364
365 // Read a record.
366 Record.clear();
367 switch (Stream.ReadRecord(Code, Record)) {
368 default: // Default behavior: ignore.
369 break;
370 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
371 if (Record.size() & 1)
372 return Error("Invalid ENTRY record");
373
Chris Lattner58601542008-10-05 18:22:09 +0000374 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patelf2a4a922008-09-26 22:53:05 +0000375 // If Function attributes are using index 0 then transfer them
Chris Lattner58601542008-10-05 18:22:09 +0000376 // to index ~0. Index 0 is used for return value attributes but used to be
377 // used for function attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +0000378 Attributes RetAttribute = Attribute::None;
379 Attributes FnAttribute = Attribute::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky4029a942008-12-19 09:38:31 +0000381 // FIXME: remove in LLVM 3.0
382 // The alignment is stored as a 16-bit raw value from bits 31--16.
383 // We shift the bits above 31 down by 11 bits.
384
385 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
386 if (Alignment && !isPowerOf2_32(Alignment))
387 return Error("Alignment is not a power of two.");
388
389 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
390 if (Alignment)
391 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
392 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
393 Record[i+1] = ReconstitutedAttr;
394
Devang Patelf2a4a922008-09-26 22:53:05 +0000395 if (Record[i] == 0)
396 RetAttribute = Record[i+1];
397 else if (Record[i] == ~0U)
398 FnAttribute = Record[i+1];
399 }
Chris Lattner58601542008-10-05 18:22:09 +0000400
401 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
402 Attribute::ReadOnly|Attribute::ReadNone);
403
404 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
405 (RetAttribute & OldRetAttrs) != 0) {
406 if (FnAttribute == Attribute::None) { // add a slot so they get added.
407 Record.push_back(~0U);
408 Record.push_back(0);
Devang Patelf2a4a922008-09-26 22:53:05 +0000409 }
Chris Lattner58601542008-10-05 18:22:09 +0000410
411 FnAttribute |= RetAttribute & OldRetAttrs;
412 RetAttribute &= ~OldRetAttrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000413 }
Chris Lattner2ee85532008-03-12 02:25:52 +0000414
Devang Patelf2a4a922008-09-26 22:53:05 +0000415 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner58601542008-10-05 18:22:09 +0000416 if (Record[i] == 0) {
417 if (RetAttribute != Attribute::None)
418 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
419 } else if (Record[i] == ~0U) {
420 if (FnAttribute != Attribute::None)
421 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
422 } else if (Record[i+1] != Attribute::None)
Devang Patelf2a4a922008-09-26 22:53:05 +0000423 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
424 }
Devang Patelf2a4a922008-09-26 22:53:05 +0000425
426 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427 Attrs.clear();
428 break;
429 }
Duncan Sandse2898f02007-11-20 14:09:29 +0000430 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431 }
432}
433
434
435bool BitcodeReader::ParseTypeTable() {
436 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
437 return Error("Malformed block record");
438
439 if (!TypeList.empty())
440 return Error("Multiple TYPE_BLOCKs found!");
441
442 SmallVector<uint64_t, 64> Record;
443 unsigned NumRecords = 0;
444
445 // Read all the records for this type table.
446 while (1) {
447 unsigned Code = Stream.ReadCode();
448 if (Code == bitc::END_BLOCK) {
449 if (NumRecords != TypeList.size())
450 return Error("Invalid type forward reference in TYPE_BLOCK");
451 if (Stream.ReadBlockEnd())
452 return Error("Error at end of type table block");
453 return false;
454 }
455
456 if (Code == bitc::ENTER_SUBBLOCK) {
457 // No known subblocks, always skip them.
458 Stream.ReadSubBlockID();
459 if (Stream.SkipBlock())
460 return Error("Malformed block record");
461 continue;
462 }
463
464 if (Code == bitc::DEFINE_ABBREV) {
465 Stream.ReadAbbrevRecord();
466 continue;
467 }
468
469 // Read a record.
470 Record.clear();
471 const Type *ResultTy = 0;
472 switch (Stream.ReadRecord(Code, Record)) {
473 default: // Default behavior: unknown type.
474 ResultTy = 0;
475 break;
476 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
477 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
478 // type list. This allows us to reserve space.
479 if (Record.size() < 1)
480 return Error("Invalid TYPE_CODE_NUMENTRY record");
481 TypeList.reserve(Record[0]);
482 continue;
483 case bitc::TYPE_CODE_VOID: // VOID
484 ResultTy = Type::VoidTy;
485 break;
486 case bitc::TYPE_CODE_FLOAT: // FLOAT
487 ResultTy = Type::FloatTy;
488 break;
489 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
490 ResultTy = Type::DoubleTy;
491 break;
Dale Johannesenf325d9f2007-08-03 01:03:46 +0000492 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
493 ResultTy = Type::X86_FP80Ty;
494 break;
495 case bitc::TYPE_CODE_FP128: // FP128
496 ResultTy = Type::FP128Ty;
497 break;
498 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
499 ResultTy = Type::PPC_FP128Ty;
500 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 case bitc::TYPE_CODE_LABEL: // LABEL
502 ResultTy = Type::LabelTy;
503 break;
504 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
505 ResultTy = 0;
506 break;
Nick Lewycky29aaef82009-05-30 05:06:04 +0000507 case bitc::TYPE_CODE_METADATA: // METADATA
508 ResultTy = Type::MetadataTy;
509 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
511 if (Record.size() < 1)
512 return Error("Invalid Integer type record");
513
Owen Anderson4956cde2009-07-07 20:18:58 +0000514 ResultTy = Context.getIntegerType(Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000515 break;
Christopher Lamb44d62f62007-12-11 08:59:05 +0000516 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
517 // [pointee type, address space]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 if (Record.size() < 1)
519 return Error("Invalid POINTER type record");
Christopher Lamb44d62f62007-12-11 08:59:05 +0000520 unsigned AddressSpace = 0;
521 if (Record.size() == 2)
522 AddressSpace = Record[1];
Owen Anderson4956cde2009-07-07 20:18:58 +0000523 ResultTy = Context.getPointerType(getTypeByID(Record[0], true),
524 AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000525 break;
Christopher Lamb44d62f62007-12-11 08:59:05 +0000526 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattner70b644d2007-11-27 17:48:06 +0000528 // FIXME: attrid is dead, remove it in LLVM 3.0
529 // FUNCTION: [vararg, attrid, retty, paramty x N]
530 if (Record.size() < 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000531 return Error("Invalid FUNCTION type record");
532 std::vector<const Type*> ArgTys;
Chris Lattner70b644d2007-11-27 17:48:06 +0000533 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 ArgTys.push_back(getTypeByID(Record[i], true));
535
Owen Anderson4956cde2009-07-07 20:18:58 +0000536 ResultTy = Context.getFunctionType(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000537 Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 break;
539 }
540 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
541 if (Record.size() < 1)
542 return Error("Invalid STRUCT type record");
543 std::vector<const Type*> EltTys;
544 for (unsigned i = 1, e = Record.size(); i != e; ++i)
545 EltTys.push_back(getTypeByID(Record[i], true));
Owen Anderson4956cde2009-07-07 20:18:58 +0000546 ResultTy = Context.getStructType(EltTys, Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 break;
548 }
549 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
550 if (Record.size() < 2)
551 return Error("Invalid ARRAY type record");
Owen Anderson4956cde2009-07-07 20:18:58 +0000552 ResultTy = Context.getArrayType(getTypeByID(Record[1], true), Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553 break;
554 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
555 if (Record.size() < 2)
556 return Error("Invalid VECTOR type record");
Owen Anderson4956cde2009-07-07 20:18:58 +0000557 ResultTy = Context.getVectorType(getTypeByID(Record[1], true), Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000558 break;
559 }
560
561 if (NumRecords == TypeList.size()) {
562 // If this is a new type slot, just append it.
Owen Anderson4956cde2009-07-07 20:18:58 +0000563 TypeList.push_back(ResultTy ? ResultTy : Context.getOpaqueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 ++NumRecords;
565 } else if (ResultTy == 0) {
566 // Otherwise, this was forward referenced, so an opaque type was created,
567 // but the result type is actually just an opaque. Leave the one we
568 // created previously.
569 ++NumRecords;
570 } else {
571 // Otherwise, this was forward referenced, so an opaque type was created.
572 // Resolve the opaque type to the real type now.
573 assert(NumRecords < TypeList.size() && "Typelist imbalance");
574 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
575
576 // Don't directly push the new type on the Tab. Instead we want to replace
577 // the opaque type we previously inserted with the new concrete value. The
578 // refinement from the abstract (opaque) type to the new type causes all
579 // uses of the abstract type to use the concrete type (NewTy). This will
580 // also cause the opaque type to be deleted.
581 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
582
583 // This should have replaced the old opaque type with the new type in the
584 // value table... or with a preexisting type that was already in the
585 // system. Let's just make sure it did.
586 assert(TypeList[NumRecords-1].get() != OldTy &&
587 "refineAbstractType didn't work!");
588 }
589 }
590}
591
592
593bool BitcodeReader::ParseTypeSymbolTable() {
594 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
595 return Error("Malformed block record");
596
597 SmallVector<uint64_t, 64> Record;
598
599 // Read all the records for this type table.
600 std::string TypeName;
601 while (1) {
602 unsigned Code = Stream.ReadCode();
603 if (Code == bitc::END_BLOCK) {
604 if (Stream.ReadBlockEnd())
605 return Error("Error at end of type symbol table block");
606 return false;
607 }
608
609 if (Code == bitc::ENTER_SUBBLOCK) {
610 // No known subblocks, always skip them.
611 Stream.ReadSubBlockID();
612 if (Stream.SkipBlock())
613 return Error("Malformed block record");
614 continue;
615 }
616
617 if (Code == bitc::DEFINE_ABBREV) {
618 Stream.ReadAbbrevRecord();
619 continue;
620 }
621
622 // Read a record.
623 Record.clear();
624 switch (Stream.ReadRecord(Code, Record)) {
625 default: // Default behavior: unknown type.
626 break;
627 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
628 if (ConvertToString(Record, 1, TypeName))
629 return Error("Invalid TST_ENTRY record");
630 unsigned TypeID = Record[0];
631 if (TypeID >= TypeList.size())
632 return Error("Invalid Type ID in TST_ENTRY record");
633
634 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
635 TypeName.clear();
636 break;
637 }
638 }
639}
640
641bool BitcodeReader::ParseValueSymbolTable() {
642 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
643 return Error("Malformed block record");
644
645 SmallVector<uint64_t, 64> Record;
646
647 // Read all the records for this value table.
648 SmallString<128> ValueName;
649 while (1) {
650 unsigned Code = Stream.ReadCode();
651 if (Code == bitc::END_BLOCK) {
652 if (Stream.ReadBlockEnd())
653 return Error("Error at end of value symbol table block");
654 return false;
655 }
656 if (Code == bitc::ENTER_SUBBLOCK) {
657 // No known subblocks, always skip them.
658 Stream.ReadSubBlockID();
659 if (Stream.SkipBlock())
660 return Error("Malformed block record");
661 continue;
662 }
663
664 if (Code == bitc::DEFINE_ABBREV) {
665 Stream.ReadAbbrevRecord();
666 continue;
667 }
668
669 // Read a record.
670 Record.clear();
671 switch (Stream.ReadRecord(Code, Record)) {
672 default: // Default behavior: unknown type.
673 break;
674 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
675 if (ConvertToString(Record, 1, ValueName))
Nick Lewyckydc9b1b52009-05-31 06:07:28 +0000676 return Error("Invalid VST_ENTRY record");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 unsigned ValueID = Record[0];
678 if (ValueID >= ValueList.size())
679 return Error("Invalid Value ID in VST_ENTRY record");
680 Value *V = ValueList[ValueID];
681
682 V->setName(&ValueName[0], ValueName.size());
683 ValueName.clear();
684 break;
685 }
686 case bitc::VST_CODE_BBENTRY: {
687 if (ConvertToString(Record, 1, ValueName))
688 return Error("Invalid VST_BBENTRY record");
689 BasicBlock *BB = getBasicBlock(Record[0]);
690 if (BB == 0)
691 return Error("Invalid BB ID in VST_BBENTRY record");
692
693 BB->setName(&ValueName[0], ValueName.size());
694 ValueName.clear();
695 break;
696 }
697 }
698 }
699}
700
701/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
702/// the LSB for dense VBR encoding.
703static uint64_t DecodeSignRotatedValue(uint64_t V) {
704 if ((V & 1) == 0)
705 return V >> 1;
706 if (V != 1)
707 return -(V >> 1);
708 // There is no such thing as -0 with integers. "-0" really means MININT.
709 return 1ULL << 63;
710}
711
712/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
713/// values and aliases that we can.
714bool BitcodeReader::ResolveGlobalAndAliasInits() {
715 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
716 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
717
718 GlobalInitWorklist.swap(GlobalInits);
719 AliasInitWorklist.swap(AliasInits);
720
721 while (!GlobalInitWorklist.empty()) {
722 unsigned ValID = GlobalInitWorklist.back().second;
723 if (ValID >= ValueList.size()) {
724 // Not ready to resolve this yet, it requires something later in the file.
725 GlobalInits.push_back(GlobalInitWorklist.back());
726 } else {
727 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
728 GlobalInitWorklist.back().first->setInitializer(C);
729 else
730 return Error("Global variable initializer is not a constant!");
731 }
732 GlobalInitWorklist.pop_back();
733 }
734
735 while (!AliasInitWorklist.empty()) {
736 unsigned ValID = AliasInitWorklist.back().second;
737 if (ValID >= ValueList.size()) {
738 AliasInits.push_back(AliasInitWorklist.back());
739 } else {
740 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
741 AliasInitWorklist.back().first->setAliasee(C);
742 else
743 return Error("Alias initializer is not a constant!");
744 }
745 AliasInitWorklist.pop_back();
746 }
747 return false;
748}
749
750
751bool BitcodeReader::ParseConstants() {
752 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
753 return Error("Malformed block record");
754
755 SmallVector<uint64_t, 64> Record;
756
757 // Read all the records for this value table.
758 const Type *CurTy = Type::Int32Ty;
759 unsigned NextCstNo = ValueList.size();
760 while (1) {
761 unsigned Code = Stream.ReadCode();
Chris Lattner345bbb72008-08-21 02:34:16 +0000762 if (Code == bitc::END_BLOCK)
763 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764
765 if (Code == bitc::ENTER_SUBBLOCK) {
766 // No known subblocks, always skip them.
767 Stream.ReadSubBlockID();
768 if (Stream.SkipBlock())
769 return Error("Malformed block record");
770 continue;
771 }
772
773 if (Code == bitc::DEFINE_ABBREV) {
774 Stream.ReadAbbrevRecord();
775 continue;
776 }
777
778 // Read a record.
779 Record.clear();
780 Value *V = 0;
781 switch (Stream.ReadRecord(Code, Record)) {
782 default: // Default behavior: unknown constant
783 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson4956cde2009-07-07 20:18:58 +0000784 V = Context.getUndef(CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 break;
786 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
787 if (Record.empty())
788 return Error("Malformed CST_SETTYPE record");
789 if (Record[0] >= TypeList.size())
790 return Error("Invalid Type ID in CST_SETTYPE record");
791 CurTy = TypeList[Record[0]];
792 continue; // Skip the ValueList manipulation.
793 case bitc::CST_CODE_NULL: // NULL
Owen Anderson4956cde2009-07-07 20:18:58 +0000794 V = Context.getNullValue(CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795 break;
796 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
797 if (!isa<IntegerType>(CurTy) || Record.empty())
798 return Error("Invalid CST_INTEGER record");
Owen Anderson4956cde2009-07-07 20:18:58 +0000799 V = Context.getConstantInt(CurTy, DecodeSignRotatedValue(Record[0]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 break;
801 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
802 if (!isa<IntegerType>(CurTy) || Record.empty())
803 return Error("Invalid WIDE_INTEGER record");
804
805 unsigned NumWords = Record.size();
806 SmallVector<uint64_t, 8> Words;
807 Words.resize(NumWords);
808 for (unsigned i = 0; i != NumWords; ++i)
809 Words[i] = DecodeSignRotatedValue(Record[i]);
Owen Anderson4956cde2009-07-07 20:18:58 +0000810 V = Context.getConstantInt(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 NumWords, &Words[0]));
812 break;
813 }
Dale Johannesen1616e902007-09-11 18:32:33 +0000814 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 if (Record.empty())
816 return Error("Invalid FLOAT record");
817 if (CurTy == Type::FloatTy)
Owen Anderson4956cde2009-07-07 20:18:58 +0000818 V = Context.getConstantFP(APFloat(APInt(32, (uint32_t)Record[0])));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819 else if (CurTy == Type::DoubleTy)
Owen Anderson4956cde2009-07-07 20:18:58 +0000820 V = Context.getConstantFP(APFloat(APInt(64, Record[0])));
Dale Johannesen0a92eac2009-03-23 21:16:53 +0000821 else if (CurTy == Type::X86_FP80Ty) {
822 // Bits are not stored the same way as a normal i80 APInt, compensate.
823 uint64_t Rearrange[2];
824 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
825 Rearrange[1] = Record[0] >> 48;
Owen Anderson4956cde2009-07-07 20:18:58 +0000826 V = Context.getConstantFP(APFloat(APInt(80, 2, Rearrange)));
Dale Johannesen0a92eac2009-03-23 21:16:53 +0000827 } else if (CurTy == Type::FP128Ty)
Owen Anderson4956cde2009-07-07 20:18:58 +0000828 V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000829 else if (CurTy == Type::PPC_FP128Ty)
Owen Anderson4956cde2009-07-07 20:18:58 +0000830 V = Context.getConstantFP(APFloat(APInt(128, 2, &Record[0])));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 else
Owen Anderson4956cde2009-07-07 20:18:58 +0000832 V = Context.getUndef(CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000833 break;
Dale Johannesen1616e902007-09-11 18:32:33 +0000834 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835
836 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
837 if (Record.empty())
838 return Error("Invalid CST_AGGREGATE record");
839
840 unsigned Size = Record.size();
841 std::vector<Constant*> Elts;
842
843 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
844 for (unsigned i = 0; i != Size; ++i)
845 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
846 STy->getElementType(i)));
Owen Anderson4956cde2009-07-07 20:18:58 +0000847 V = Context.getConstantStruct(STy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
849 const Type *EltTy = ATy->getElementType();
850 for (unsigned i = 0; i != Size; ++i)
851 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4956cde2009-07-07 20:18:58 +0000852 V = Context.getConstantArray(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
854 const Type *EltTy = VTy->getElementType();
855 for (unsigned i = 0; i != Size; ++i)
856 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4956cde2009-07-07 20:18:58 +0000857 V = Context.getConstantVector(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 } else {
Owen Anderson4956cde2009-07-07 20:18:58 +0000859 V = Context.getUndef(CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860 }
861 break;
862 }
863 case bitc::CST_CODE_STRING: { // STRING: [values]
864 if (Record.empty())
865 return Error("Invalid CST_AGGREGATE record");
866
867 const ArrayType *ATy = cast<ArrayType>(CurTy);
868 const Type *EltTy = ATy->getElementType();
869
870 unsigned Size = Record.size();
871 std::vector<Constant*> Elts;
872 for (unsigned i = 0; i != Size; ++i)
Owen Anderson4956cde2009-07-07 20:18:58 +0000873 Elts.push_back(Context.getConstantInt(EltTy, Record[i]));
874 V = Context.getConstantArray(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 break;
876 }
877 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
878 if (Record.empty())
879 return Error("Invalid CST_AGGREGATE record");
880
881 const ArrayType *ATy = cast<ArrayType>(CurTy);
882 const Type *EltTy = ATy->getElementType();
883
884 unsigned Size = Record.size();
885 std::vector<Constant*> Elts;
886 for (unsigned i = 0; i != Size; ++i)
Owen Anderson4956cde2009-07-07 20:18:58 +0000887 Elts.push_back(Context.getConstantInt(EltTy, Record[i]));
888 Elts.push_back(Context.getNullValue(EltTy));
889 V = Context.getConstantArray(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 break;
891 }
892 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
893 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
894 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
895 if (Opc < 0) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000896 V = Context.getUndef(CurTy); // Unknown binop.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 } else {
898 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
899 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Owen Anderson4956cde2009-07-07 20:18:58 +0000900 V = Context.getConstantExpr(Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 }
902 break;
903 }
904 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
905 if (Record.size() < 3) return Error("Invalid CE_CAST record");
906 int Opc = GetDecodedCastOpcode(Record[0]);
907 if (Opc < 0) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000908 V = Context.getUndef(CurTy); // Unknown cast.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909 } else {
910 const Type *OpTy = getTypeByID(Record[1]);
911 if (!OpTy) return Error("Invalid CE_CAST record");
912 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Anderson4956cde2009-07-07 20:18:58 +0000913 V = Context.getConstantExprCast(Opc, Op, CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 }
915 break;
916 }
917 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
918 if (Record.size() & 1) return Error("Invalid CE_GEP record");
919 SmallVector<Constant*, 16> Elts;
920 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
921 const Type *ElTy = getTypeByID(Record[i]);
922 if (!ElTy) return Error("Invalid CE_GEP record");
923 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
924 }
Owen Anderson4956cde2009-07-07 20:18:58 +0000925 V = Context.getConstantExprGetElementPtr(Elts[0], &Elts[1],
926 Elts.size()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 break;
928 }
929 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
930 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Anderson4956cde2009-07-07 20:18:58 +0000931 V = Context.getConstantExprSelect(ValueList.getConstantFwdRef(Record[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932 Type::Int1Ty),
933 ValueList.getConstantFwdRef(Record[1],CurTy),
934 ValueList.getConstantFwdRef(Record[2],CurTy));
935 break;
936 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
937 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
938 const VectorType *OpTy =
939 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
940 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
941 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner12b4aee2009-02-03 02:11:28 +0000942 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Owen Anderson4956cde2009-07-07 20:18:58 +0000943 V = Context.getConstantExprExtractElement(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 break;
945 }
946 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
947 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
948 if (Record.size() < 3 || OpTy == 0)
949 return Error("Invalid CE_INSERTELT record");
950 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
951 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
952 OpTy->getElementType());
953 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Owen Anderson4956cde2009-07-07 20:18:58 +0000954 V = Context.getConstantExprInsertElement(Op0, Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955 break;
956 }
957 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
958 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
959 if (Record.size() < 3 || OpTy == 0)
Nate Begemand6d715b2009-02-12 21:28:33 +0000960 return Error("Invalid CE_SHUFFLEVEC record");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
962 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson4956cde2009-07-07 20:18:58 +0000963 const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
964 OpTy->getNumElements());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson4956cde2009-07-07 20:18:58 +0000966 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 break;
968 }
Nate Begemand6d715b2009-02-12 21:28:33 +0000969 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
970 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
971 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
972 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
973 return Error("Invalid CE_SHUFVEC_EX record");
974 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
975 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Anderson4956cde2009-07-07 20:18:58 +0000976 const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
977 RTy->getNumElements());
Nate Begemand6d715b2009-02-12 21:28:33 +0000978 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson4956cde2009-07-07 20:18:58 +0000979 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
Nate Begemand6d715b2009-02-12 21:28:33 +0000980 break;
981 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
983 if (Record.size() < 4) return Error("Invalid CE_CMP record");
984 const Type *OpTy = getTypeByID(Record[0]);
985 if (OpTy == 0) return Error("Invalid CE_CMP record");
986 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
987 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
988
989 if (OpTy->isFloatingPoint())
Owen Anderson4956cde2009-07-07 20:18:58 +0000990 V = Context.getConstantExprFCmp(Record[3], Op0, Op1);
Nate Begeman646fa482008-05-12 19:01:56 +0000991 else
Nick Lewycky8f5253b2009-07-08 03:04:38 +0000992 V = Context.getConstantExprICmp(Record[3], Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 break;
994 }
995 case bitc::CST_CODE_INLINEASM: {
996 if (Record.size() < 2) return Error("Invalid INLINEASM record");
997 std::string AsmStr, ConstrStr;
998 bool HasSideEffects = Record[0];
999 unsigned AsmStrSize = Record[1];
1000 if (2+AsmStrSize >= Record.size())
1001 return Error("Invalid INLINEASM record");
1002 unsigned ConstStrSize = Record[2+AsmStrSize];
1003 if (3+AsmStrSize+ConstStrSize > Record.size())
1004 return Error("Invalid INLINEASM record");
1005
1006 for (unsigned i = 0; i != AsmStrSize; ++i)
1007 AsmStr += (char)Record[2+i];
1008 for (unsigned i = 0; i != ConstStrSize; ++i)
1009 ConstrStr += (char)Record[3+AsmStrSize+i];
1010 const PointerType *PTy = cast<PointerType>(CurTy);
1011 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1012 AsmStr, ConstrStr, HasSideEffects);
1013 break;
1014 }
Nick Lewycky4dcf8102009-04-04 07:22:01 +00001015 case bitc::CST_CODE_MDSTRING: {
Nick Lewycky4dcf8102009-04-04 07:22:01 +00001016 unsigned MDStringLength = Record.size();
1017 SmallString<8> String;
1018 String.resize(MDStringLength);
1019 for (unsigned i = 0; i != MDStringLength; ++i)
1020 String[i] = Record[i];
Owen Anderson4956cde2009-07-07 20:18:58 +00001021 V = Context.getMDString(String.c_str(), String.c_str() + MDStringLength);
Nick Lewycky4dcf8102009-04-04 07:22:01 +00001022 break;
1023 }
1024 case bitc::CST_CODE_MDNODE: {
1025 if (Record.empty() || Record.size() % 2 == 1)
1026 return Error("Invalid CST_MDNODE record");
1027
1028 unsigned Size = Record.size();
Nick Lewycky117f4382009-05-10 20:57:05 +00001029 SmallVector<Value*, 8> Elts;
Nick Lewycky4dcf8102009-04-04 07:22:01 +00001030 for (unsigned i = 0; i != Size; i += 2) {
1031 const Type *Ty = getTypeByID(Record[i], false);
Nick Lewycky117f4382009-05-10 20:57:05 +00001032 if (Ty != Type::VoidTy)
Nick Lewyckycd36a362009-06-01 04:42:10 +00001033 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
Nick Lewycky117f4382009-05-10 20:57:05 +00001034 else
1035 Elts.push_back(NULL);
Nick Lewycky4dcf8102009-04-04 07:22:01 +00001036 }
Owen Anderson4956cde2009-07-07 20:18:58 +00001037 V = Context.getMDNode(&Elts[0], Elts.size());
Nick Lewycky4dcf8102009-04-04 07:22:01 +00001038 break;
1039 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 }
1041
1042 ValueList.AssignValue(V, NextCstNo);
1043 ++NextCstNo;
1044 }
Chris Lattner345bbb72008-08-21 02:34:16 +00001045
1046 if (NextCstNo != ValueList.size())
1047 return Error("Invalid constant reference!");
1048
1049 if (Stream.ReadBlockEnd())
1050 return Error("Error at end of constants block");
1051
1052 // Once all the constants have been read, go through and resolve forward
1053 // references.
1054 ValueList.ResolveConstantForwardRefs();
1055 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056}
1057
1058/// RememberAndSkipFunctionBody - When we see the block for a function body,
1059/// remember where it is and then skip it. This lets us lazily deserialize the
1060/// functions.
1061bool BitcodeReader::RememberAndSkipFunctionBody() {
1062 // Get the function we are talking about.
1063 if (FunctionsWithBodies.empty())
1064 return Error("Insufficient function protos");
1065
1066 Function *Fn = FunctionsWithBodies.back();
1067 FunctionsWithBodies.pop_back();
1068
1069 // Save the current stream state.
1070 uint64_t CurBit = Stream.GetCurrentBitNo();
1071 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1072
1073 // Set the functions linkage to GhostLinkage so we know it is lazily
1074 // deserialized.
1075 Fn->setLinkage(GlobalValue::GhostLinkage);
1076
1077 // Skip over the function block for now.
1078 if (Stream.SkipBlock())
1079 return Error("Malformed block record");
1080 return false;
1081}
1082
1083bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1084 // Reject multiple MODULE_BLOCK's in a single bitstream.
1085 if (TheModule)
1086 return Error("Multiple MODULE_BLOCKs in same stream");
1087
1088 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1089 return Error("Malformed block record");
1090
1091 // Otherwise, create the module.
Owen Anderson25209b42009-07-01 16:58:40 +00001092 TheModule = new Module(ModuleID, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093
1094 SmallVector<uint64_t, 64> Record;
1095 std::vector<std::string> SectionTable;
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001096 std::vector<std::string> GCTable;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097
1098 // Read all the records for this module.
1099 while (!Stream.AtEndOfStream()) {
1100 unsigned Code = Stream.ReadCode();
1101 if (Code == bitc::END_BLOCK) {
1102 if (Stream.ReadBlockEnd())
1103 return Error("Error at end of module block");
1104
1105 // Patch the initializers for globals and aliases up.
1106 ResolveGlobalAndAliasInits();
1107 if (!GlobalInits.empty() || !AliasInits.empty())
1108 return Error("Malformed global initializer set");
1109 if (!FunctionsWithBodies.empty())
1110 return Error("Too few function bodies found");
1111
Chandler Carrutha228e392007-08-04 01:51:18 +00001112 // Look for intrinsic functions which need to be upgraded at some point
1113 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1114 FI != FE; ++FI) {
Evan Cheng7f05d852007-12-17 22:33:23 +00001115 Function* NewFn;
1116 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carrutha228e392007-08-04 01:51:18 +00001117 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1118 }
1119
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 // Force deallocation of memory for these vectors to favor the client that
1121 // want lazy deserialization.
1122 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1123 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1124 std::vector<Function*>().swap(FunctionsWithBodies);
1125 return false;
1126 }
1127
1128 if (Code == bitc::ENTER_SUBBLOCK) {
1129 switch (Stream.ReadSubBlockID()) {
1130 default: // Skip unknown content.
1131 if (Stream.SkipBlock())
1132 return Error("Malformed block record");
1133 break;
1134 case bitc::BLOCKINFO_BLOCK_ID:
1135 if (Stream.ReadBlockInfoBlock())
1136 return Error("Malformed BlockInfoBlock");
1137 break;
1138 case bitc::PARAMATTR_BLOCK_ID:
Devang Pateld222f862008-09-25 21:00:45 +00001139 if (ParseAttributeBlock())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 return true;
1141 break;
1142 case bitc::TYPE_BLOCK_ID:
1143 if (ParseTypeTable())
1144 return true;
1145 break;
1146 case bitc::TYPE_SYMTAB_BLOCK_ID:
1147 if (ParseTypeSymbolTable())
1148 return true;
1149 break;
1150 case bitc::VALUE_SYMTAB_BLOCK_ID:
1151 if (ParseValueSymbolTable())
1152 return true;
1153 break;
1154 case bitc::CONSTANTS_BLOCK_ID:
1155 if (ParseConstants() || ResolveGlobalAndAliasInits())
1156 return true;
1157 break;
1158 case bitc::FUNCTION_BLOCK_ID:
1159 // If this is the first function body we've seen, reverse the
1160 // FunctionsWithBodies list.
1161 if (!HasReversedFunctionsWithBodies) {
1162 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1163 HasReversedFunctionsWithBodies = true;
1164 }
1165
1166 if (RememberAndSkipFunctionBody())
1167 return true;
1168 break;
1169 }
1170 continue;
1171 }
1172
1173 if (Code == bitc::DEFINE_ABBREV) {
1174 Stream.ReadAbbrevRecord();
1175 continue;
1176 }
1177
1178 // Read a record.
1179 switch (Stream.ReadRecord(Code, Record)) {
1180 default: break; // Default behavior, ignore unknown content.
1181 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1182 if (Record.size() < 1)
1183 return Error("Malformed MODULE_CODE_VERSION");
1184 // Only version #0 is supported so far.
1185 if (Record[0] != 0)
1186 return Error("Unknown bitstream version!");
1187 break;
1188 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1189 std::string S;
1190 if (ConvertToString(Record, 0, S))
1191 return Error("Invalid MODULE_CODE_TRIPLE record");
1192 TheModule->setTargetTriple(S);
1193 break;
1194 }
1195 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1196 std::string S;
1197 if (ConvertToString(Record, 0, S))
1198 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1199 TheModule->setDataLayout(S);
1200 break;
1201 }
1202 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1203 std::string S;
1204 if (ConvertToString(Record, 0, S))
1205 return Error("Invalid MODULE_CODE_ASM record");
1206 TheModule->setModuleInlineAsm(S);
1207 break;
1208 }
1209 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1210 std::string S;
1211 if (ConvertToString(Record, 0, S))
1212 return Error("Invalid MODULE_CODE_DEPLIB record");
1213 TheModule->addLibrary(S);
1214 break;
1215 }
1216 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1217 std::string S;
1218 if (ConvertToString(Record, 0, S))
1219 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1220 SectionTable.push_back(S);
1221 break;
1222 }
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001223 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001224 std::string S;
1225 if (ConvertToString(Record, 0, S))
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001226 return Error("Invalid MODULE_CODE_GCNAME record");
1227 GCTable.push_back(S);
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001228 break;
1229 }
Christopher Lamb44d62f62007-12-11 08:59:05 +00001230 // GLOBALVAR: [pointer type, isconst, initid,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 // linkage, alignment, section, visibility, threadlocal]
1232 case bitc::MODULE_CODE_GLOBALVAR: {
1233 if (Record.size() < 6)
1234 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1235 const Type *Ty = getTypeByID(Record[0]);
1236 if (!isa<PointerType>(Ty))
1237 return Error("Global not a pointer type!");
Christopher Lamb44d62f62007-12-11 08:59:05 +00001238 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 Ty = cast<PointerType>(Ty)->getElementType();
1240
1241 bool isConstant = Record[1];
1242 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1243 unsigned Alignment = (1 << Record[4]) >> 1;
1244 std::string Section;
1245 if (Record[5]) {
1246 if (Record[5]-1 >= SectionTable.size())
1247 return Error("Invalid section ID");
1248 Section = SectionTable[Record[5]-1];
1249 }
1250 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1251 if (Record.size() > 6)
1252 Visibility = GetDecodedVisibility(Record[6]);
1253 bool isThreadLocal = false;
1254 if (Record.size() > 7)
1255 isThreadLocal = Record[7];
1256
1257 GlobalVariable *NewGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +00001258 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lamb44d62f62007-12-11 08:59:05 +00001259 isThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 NewGV->setAlignment(Alignment);
1261 if (!Section.empty())
1262 NewGV->setSection(Section);
1263 NewGV->setVisibility(Visibility);
1264 NewGV->setThreadLocal(isThreadLocal);
1265
1266 ValueList.push_back(NewGV);
1267
1268 // Remember which value to use for the global initializer.
1269 if (unsigned InitID = Record[2])
1270 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1271 break;
1272 }
1273 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001274 // alignment, section, visibility, gc]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001275 case bitc::MODULE_CODE_FUNCTION: {
1276 if (Record.size() < 8)
1277 return Error("Invalid MODULE_CODE_FUNCTION record");
1278 const Type *Ty = getTypeByID(Record[0]);
1279 if (!isa<PointerType>(Ty))
1280 return Error("Function not a pointer type!");
1281 const FunctionType *FTy =
1282 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1283 if (!FTy)
1284 return Error("Function not a pointer to function type!");
1285
Gabor Greifd6da1d02008-04-06 20:25:17 +00001286 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1287 "", TheModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288
1289 Func->setCallingConv(Record[1]);
1290 bool isProto = Record[2];
1291 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Pateld222f862008-09-25 21:00:45 +00001292 Func->setAttributes(getAttributes(Record[4]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293
1294 Func->setAlignment((1 << Record[5]) >> 1);
1295 if (Record[6]) {
1296 if (Record[6]-1 >= SectionTable.size())
1297 return Error("Invalid section ID");
1298 Func->setSection(SectionTable[Record[6]-1]);
1299 }
1300 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001301 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001302 if (Record[8]-1 > GCTable.size())
1303 return Error("Invalid GC ID");
1304 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001305 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001306 ValueList.push_back(Func);
1307
1308 // If this is a function with a body, remember the prototype we are
1309 // creating now, so that we can match up the body with them later.
1310 if (!isProto)
1311 FunctionsWithBodies.push_back(Func);
1312 break;
1313 }
Anton Korobeynikov5789f8d2008-03-12 00:49:19 +00001314 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikov902a0112008-03-11 21:40:17 +00001315 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316 case bitc::MODULE_CODE_ALIAS: {
1317 if (Record.size() < 3)
1318 return Error("Invalid MODULE_ALIAS record");
1319 const Type *Ty = getTypeByID(Record[0]);
1320 if (!isa<PointerType>(Ty))
1321 return Error("Function not a pointer type!");
1322
1323 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1324 "", 0, TheModule);
Anton Korobeynikov5789f8d2008-03-12 00:49:19 +00001325 // Old bitcode files didn't have visibility field.
1326 if (Record.size() > 3)
1327 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 ValueList.push_back(NewGA);
1329 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1330 break;
1331 }
1332 /// MODULE_CODE_PURGEVALS: [numvals]
1333 case bitc::MODULE_CODE_PURGEVALS:
1334 // Trim down the value list to the specified size.
1335 if (Record.size() < 1 || Record[0] > ValueList.size())
1336 return Error("Invalid MODULE_PURGEVALS record");
1337 ValueList.shrinkTo(Record[0]);
1338 break;
1339 }
1340 Record.clear();
1341 }
1342
1343 return Error("Premature end of bitstream");
1344}
1345
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346bool BitcodeReader::ParseBitcode() {
1347 TheModule = 0;
1348
1349 if (Buffer->getBufferSize() & 3)
1350 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1351
1352 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner65b13ff2008-07-09 05:14:23 +00001353 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1354
1355 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1356 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnerabd0e442009-04-06 20:54:32 +00001357 if (isBitcodeWrapper(BufPtr, BufEnd))
1358 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner65b13ff2008-07-09 05:14:23 +00001359 return Error("Invalid bitcode wrapper header");
1360
Chris Lattner25a6abf2009-04-26 20:59:02 +00001361 StreamFile.init(BufPtr, BufEnd);
1362 Stream.init(StreamFile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363
1364 // Sniff for the signature.
1365 if (Stream.Read(8) != 'B' ||
1366 Stream.Read(8) != 'C' ||
1367 Stream.Read(4) != 0x0 ||
1368 Stream.Read(4) != 0xC ||
1369 Stream.Read(4) != 0xE ||
1370 Stream.Read(4) != 0xD)
1371 return Error("Invalid bitcode signature");
1372
1373 // We expect a number of well-defined blocks, though we don't necessarily
1374 // need to understand them all.
1375 while (!Stream.AtEndOfStream()) {
1376 unsigned Code = Stream.ReadCode();
1377
1378 if (Code != bitc::ENTER_SUBBLOCK)
1379 return Error("Invalid record at top-level");
1380
1381 unsigned BlockID = Stream.ReadSubBlockID();
1382
1383 // We only know the MODULE subblock ID.
1384 switch (BlockID) {
1385 case bitc::BLOCKINFO_BLOCK_ID:
1386 if (Stream.ReadBlockInfoBlock())
1387 return Error("Malformed BlockInfoBlock");
1388 break;
1389 case bitc::MODULE_BLOCK_ID:
1390 if (ParseModule(Buffer->getBufferIdentifier()))
1391 return true;
1392 break;
1393 default:
1394 if (Stream.SkipBlock())
1395 return Error("Malformed block record");
1396 break;
1397 }
1398 }
1399
1400 return false;
1401}
1402
1403
1404/// ParseFunctionBody - Lazily parse the specified function body block.
1405bool BitcodeReader::ParseFunctionBody(Function *F) {
1406 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1407 return Error("Malformed block record");
1408
1409 unsigned ModuleValueListSize = ValueList.size();
1410
1411 // Add all the function arguments to the value table.
1412 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1413 ValueList.push_back(I);
1414
1415 unsigned NextValueNo = ValueList.size();
1416 BasicBlock *CurBB = 0;
1417 unsigned CurBBNo = 0;
1418
1419 // Read all the records.
1420 SmallVector<uint64_t, 64> Record;
1421 while (1) {
1422 unsigned Code = Stream.ReadCode();
1423 if (Code == bitc::END_BLOCK) {
1424 if (Stream.ReadBlockEnd())
1425 return Error("Error at end of function block");
1426 break;
1427 }
1428
1429 if (Code == bitc::ENTER_SUBBLOCK) {
1430 switch (Stream.ReadSubBlockID()) {
1431 default: // Skip unknown content.
1432 if (Stream.SkipBlock())
1433 return Error("Malformed block record");
1434 break;
1435 case bitc::CONSTANTS_BLOCK_ID:
1436 if (ParseConstants()) return true;
1437 NextValueNo = ValueList.size();
1438 break;
1439 case bitc::VALUE_SYMTAB_BLOCK_ID:
1440 if (ParseValueSymbolTable()) return true;
1441 break;
1442 }
1443 continue;
1444 }
1445
1446 if (Code == bitc::DEFINE_ABBREV) {
1447 Stream.ReadAbbrevRecord();
1448 continue;
1449 }
1450
1451 // Read a record.
1452 Record.clear();
1453 Instruction *I = 0;
1454 switch (Stream.ReadRecord(Code, Record)) {
1455 default: // Default behavior: reject
1456 return Error("Unknown instruction");
1457 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1458 if (Record.size() < 1 || Record[0] == 0)
1459 return Error("Invalid DECLAREBLOCKS record");
1460 // Create all the basic blocks for the function.
1461 FunctionBBs.resize(Record[0]);
1462 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greifd6da1d02008-04-06 20:25:17 +00001463 FunctionBBs[i] = BasicBlock::Create("", F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 CurBB = FunctionBBs[0];
1465 continue;
1466
1467 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1468 unsigned OpNum = 0;
1469 Value *LHS, *RHS;
1470 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1471 getValue(Record, OpNum, LHS->getType(), RHS) ||
1472 OpNum+1 != Record.size())
1473 return Error("Invalid BINOP record");
1474
1475 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1476 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greifa645dd32008-05-16 19:29:10 +00001477 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001478 break;
1479 }
1480 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1481 unsigned OpNum = 0;
1482 Value *Op;
1483 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1484 OpNum+2 != Record.size())
1485 return Error("Invalid CAST record");
1486
1487 const Type *ResTy = getTypeByID(Record[OpNum]);
1488 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1489 if (Opc == -1 || ResTy == 0)
1490 return Error("Invalid CAST record");
Gabor Greifa645dd32008-05-16 19:29:10 +00001491 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 break;
1493 }
1494 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1495 unsigned OpNum = 0;
1496 Value *BasePtr;
1497 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1498 return Error("Invalid GEP record");
1499
1500 SmallVector<Value*, 16> GEPIdx;
1501 while (OpNum != Record.size()) {
1502 Value *Op;
1503 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1504 return Error("Invalid GEP record");
1505 GEPIdx.push_back(Op);
1506 }
1507
Gabor Greifd6da1d02008-04-06 20:25:17 +00001508 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001509 break;
1510 }
1511
Dan Gohmane5febe42008-05-31 00:58:22 +00001512 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1513 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001514 unsigned OpNum = 0;
1515 Value *Agg;
1516 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1517 return Error("Invalid EXTRACTVAL record");
1518
Dan Gohmane5febe42008-05-31 00:58:22 +00001519 SmallVector<unsigned, 4> EXTRACTVALIdx;
1520 for (unsigned RecSize = Record.size();
1521 OpNum != RecSize; ++OpNum) {
1522 uint64_t Index = Record[OpNum];
1523 if ((unsigned)Index != Index)
1524 return Error("Invalid EXTRACTVAL index");
1525 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001526 }
1527
1528 I = ExtractValueInst::Create(Agg,
1529 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1530 break;
1531 }
1532
Dan Gohmane5febe42008-05-31 00:58:22 +00001533 case bitc::FUNC_CODE_INST_INSERTVAL: {
1534 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001535 unsigned OpNum = 0;
1536 Value *Agg;
1537 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1538 return Error("Invalid INSERTVAL record");
1539 Value *Val;
1540 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1541 return Error("Invalid INSERTVAL record");
1542
Dan Gohmane5febe42008-05-31 00:58:22 +00001543 SmallVector<unsigned, 4> INSERTVALIdx;
1544 for (unsigned RecSize = Record.size();
1545 OpNum != RecSize; ++OpNum) {
1546 uint64_t Index = Record[OpNum];
1547 if ((unsigned)Index != Index)
1548 return Error("Invalid INSERTVAL index");
1549 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001550 }
1551
1552 I = InsertValueInst::Create(Agg, Val,
1553 INSERTVALIdx.begin(), INSERTVALIdx.end());
1554 break;
1555 }
1556
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohman6fa5bce2008-09-16 01:01:33 +00001558 // obsolete form of select
1559 // handles select i1 ... in old bitcode
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 unsigned OpNum = 0;
1561 Value *TrueVal, *FalseVal, *Cond;
1562 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1563 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Dan Gohman607ddb92008-09-09 02:08:49 +00001564 getValue(Record, OpNum, Type::Int1Ty, Cond))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001565 return Error("Invalid SELECT record");
Dan Gohman6fa5bce2008-09-16 01:01:33 +00001566
1567 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1568 break;
1569 }
1570
1571 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1572 // new form of select
1573 // handles select i1 or select [N x i1]
1574 unsigned OpNum = 0;
1575 Value *TrueVal, *FalseVal, *Cond;
1576 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1577 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1578 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1579 return Error("Invalid SELECT record");
Dan Gohmanb60ca3c2008-09-09 01:02:47 +00001580
1581 // select condition can be either i1 or [N x i1]
Dan Gohman6fa5bce2008-09-16 01:01:33 +00001582 if (const VectorType* vector_type =
1583 dyn_cast<const VectorType>(Cond->getType())) {
Dan Gohmanb60ca3c2008-09-09 01:02:47 +00001584 // expect <n x i1>
1585 if (vector_type->getElementType() != Type::Int1Ty)
1586 return Error("Invalid SELECT condition type");
1587 } else {
1588 // expect i1
1589 if (Cond->getType() != Type::Int1Ty)
1590 return Error("Invalid SELECT condition type");
1591 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592
Gabor Greifd6da1d02008-04-06 20:25:17 +00001593 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001594 break;
1595 }
1596
1597 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1598 unsigned OpNum = 0;
1599 Value *Vec, *Idx;
1600 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1601 getValue(Record, OpNum, Type::Int32Ty, Idx))
1602 return Error("Invalid EXTRACTELT record");
1603 I = new ExtractElementInst(Vec, Idx);
1604 break;
1605 }
1606
1607 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1608 unsigned OpNum = 0;
1609 Value *Vec, *Elt, *Idx;
1610 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1611 getValue(Record, OpNum,
1612 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1613 getValue(Record, OpNum, Type::Int32Ty, Idx))
1614 return Error("Invalid INSERTELT record");
Gabor Greifd6da1d02008-04-06 20:25:17 +00001615 I = InsertElementInst::Create(Vec, Elt, Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001616 break;
1617 }
1618
1619 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1620 unsigned OpNum = 0;
1621 Value *Vec1, *Vec2, *Mask;
1622 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1623 getValue(Record, OpNum, Vec1->getType(), Vec2))
1624 return Error("Invalid SHUFFLEVEC record");
1625
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001626 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001627 return Error("Invalid SHUFFLEVEC record");
1628 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1629 break;
1630 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001631
Nick Lewycky8f5253b2009-07-08 03:04:38 +00001632 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1633 // Old form of ICmp/FCmp returning bool
1634 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1635 // both legal on vectors but had different behaviour.
1636 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1637 // FCmp/ICmp returning bool or vector of bool
1638
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001639 unsigned OpNum = 0;
1640 Value *LHS, *RHS;
1641 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1642 getValue(Record, OpNum, LHS->getType(), RHS) ||
1643 OpNum+1 != Record.size())
1644 return Error("Invalid CMP record");
1645
Dan Gohmanb60ca3c2008-09-09 01:02:47 +00001646 if (LHS->getType()->isFPOrFPVector())
Owen Anderson6601fcd2009-07-09 23:48:35 +00001647 I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky8f5253b2009-07-08 03:04:38 +00001648 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00001649 I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Dan Gohmanb60ca3c2008-09-09 01:02:47 +00001650 break;
1651 }
Nick Lewycky8f5253b2009-07-08 03:04:38 +00001652
Devang Patel774ee9e2008-02-22 02:49:49 +00001653 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1654 if (Record.size() != 2)
1655 return Error("Invalid GETRESULT record");
1656 unsigned OpNum = 0;
1657 Value *Op;
1658 getValueTypePair(Record, OpNum, NextValueNo, Op);
1659 unsigned Index = Record[1];
Dan Gohman29474e92008-07-23 00:34:11 +00001660 I = ExtractValueInst::Create(Op, Index);
Devang Patel774ee9e2008-02-22 02:49:49 +00001661 break;
1662 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663
1664 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelb7fbc8b2008-02-26 01:29:32 +00001665 {
1666 unsigned Size = Record.size();
1667 if (Size == 0) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00001668 I = ReturnInst::Create();
Devang Patelb7fbc8b2008-02-26 01:29:32 +00001669 break;
Dan Gohman29474e92008-07-23 00:34:11 +00001670 }
Devang Patelb7fbc8b2008-02-26 01:29:32 +00001671
Dan Gohman29474e92008-07-23 00:34:11 +00001672 unsigned OpNum = 0;
1673 SmallVector<Value *,4> Vs;
1674 do {
1675 Value *Op = NULL;
1676 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1677 return Error("Invalid RET record");
1678 Vs.push_back(Op);
1679 } while(OpNum != Record.size());
1680
1681 const Type *ReturnType = F->getReturnType();
1682 if (Vs.size() > 1 ||
1683 (isa<StructType>(ReturnType) &&
1684 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
Owen Anderson4956cde2009-07-07 20:18:58 +00001685 Value *RV = Context.getUndef(ReturnType);
Dan Gohman29474e92008-07-23 00:34:11 +00001686 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1687 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1688 CurBB->getInstList().push_back(I);
1689 ValueList.AssignValue(I, NextValueNo++);
1690 RV = I;
1691 }
1692 I = ReturnInst::Create(RV);
Devang Patelb7fbc8b2008-02-26 01:29:32 +00001693 break;
1694 }
Dan Gohman29474e92008-07-23 00:34:11 +00001695
1696 I = ReturnInst::Create(Vs[0]);
1697 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698 }
1699 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1700 if (Record.size() != 1 && Record.size() != 3)
1701 return Error("Invalid BR record");
1702 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1703 if (TrueDest == 0)
1704 return Error("Invalid BR record");
1705
1706 if (Record.size() == 1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00001707 I = BranchInst::Create(TrueDest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708 else {
1709 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1710 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1711 if (FalseDest == 0 || Cond == 0)
1712 return Error("Invalid BR record");
Gabor Greifd6da1d02008-04-06 20:25:17 +00001713 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714 }
1715 break;
1716 }
1717 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1718 if (Record.size() < 3 || (Record.size() & 1) == 0)
1719 return Error("Invalid SWITCH record");
1720 const Type *OpTy = getTypeByID(Record[0]);
1721 Value *Cond = getFnValueByID(Record[1], OpTy);
1722 BasicBlock *Default = getBasicBlock(Record[2]);
1723 if (OpTy == 0 || Cond == 0 || Default == 0)
1724 return Error("Invalid SWITCH record");
1725 unsigned NumCases = (Record.size()-3)/2;
Gabor Greifd6da1d02008-04-06 20:25:17 +00001726 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1728 ConstantInt *CaseVal =
1729 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1730 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1731 if (CaseVal == 0 || DestBB == 0) {
1732 delete SI;
1733 return Error("Invalid SWITCH record!");
1734 }
1735 SI->addCase(CaseVal, DestBB);
1736 }
1737 I = SI;
1738 break;
1739 }
1740
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001741 case bitc::FUNC_CODE_INST_INVOKE: {
1742 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001743 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Pateld222f862008-09-25 21:00:45 +00001744 AttrListPtr PAL = getAttributes(Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001745 unsigned CCInfo = Record[1];
1746 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1747 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1748
1749 unsigned OpNum = 4;
1750 Value *Callee;
1751 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1752 return Error("Invalid INVOKE record");
1753
1754 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1755 const FunctionType *FTy = !CalleeTy ? 0 :
1756 dyn_cast<FunctionType>(CalleeTy->getElementType());
1757
1758 // Check that the right number of fixed parameters are here.
1759 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1760 Record.size() < OpNum+FTy->getNumParams())
1761 return Error("Invalid INVOKE record");
1762
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763 SmallVector<Value*, 16> Ops;
1764 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1765 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1766 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1767 }
1768
1769 if (!FTy->isVarArg()) {
1770 if (Record.size() != OpNum)
1771 return Error("Invalid INVOKE record");
1772 } else {
1773 // Read type/value pairs for varargs params.
1774 while (OpNum != Record.size()) {
1775 Value *Op;
1776 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1777 return Error("Invalid INVOKE record");
1778 Ops.push_back(Op);
1779 }
1780 }
1781
Gabor Greifb91ea9d2008-05-15 10:04:30 +00001782 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1783 Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001784 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Devang Pateld222f862008-09-25 21:00:45 +00001785 cast<InvokeInst>(I)->setAttributes(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001786 break;
1787 }
1788 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1789 I = new UnwindInst();
1790 break;
1791 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1792 I = new UnreachableInst();
1793 break;
1794 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1795 if (Record.size() < 1 || ((Record.size()-1)&1))
1796 return Error("Invalid PHI record");
1797 const Type *Ty = getTypeByID(Record[0]);
1798 if (!Ty) return Error("Invalid PHI record");
1799
Gabor Greifd6da1d02008-04-06 20:25:17 +00001800 PHINode *PN = PHINode::Create(Ty);
Chris Lattner20e7f1a2008-04-13 00:14:42 +00001801 PN->reserveOperandSpace((Record.size()-1)/2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802
1803 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1804 Value *V = getFnValueByID(Record[1+i], Ty);
1805 BasicBlock *BB = getBasicBlock(Record[2+i]);
1806 if (!V || !BB) return Error("Invalid PHI record");
1807 PN->addIncoming(V, BB);
1808 }
1809 I = PN;
1810 break;
1811 }
1812
1813 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1814 if (Record.size() < 3)
1815 return Error("Invalid MALLOC record");
1816 const PointerType *Ty =
1817 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1818 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1819 unsigned Align = Record[2];
1820 if (!Ty || !Size) return Error("Invalid MALLOC record");
Owen Anderson140166d2009-07-15 23:53:25 +00001821 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001822 break;
1823 }
1824 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1825 unsigned OpNum = 0;
1826 Value *Op;
1827 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1828 OpNum != Record.size())
1829 return Error("Invalid FREE record");
1830 I = new FreeInst(Op);
1831 break;
1832 }
1833 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1834 if (Record.size() < 3)
1835 return Error("Invalid ALLOCA record");
1836 const PointerType *Ty =
1837 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1838 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1839 unsigned Align = Record[2];
1840 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson140166d2009-07-15 23:53:25 +00001841 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842 break;
1843 }
1844 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1845 unsigned OpNum = 0;
1846 Value *Op;
1847 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1848 OpNum+2 != Record.size())
1849 return Error("Invalid LOAD record");
1850
1851 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1852 break;
1853 }
Christopher Lamb44d62f62007-12-11 08:59:05 +00001854 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1855 unsigned OpNum = 0;
1856 Value *Val, *Ptr;
1857 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1858 getValue(Record, OpNum,
1859 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1860 OpNum+2 != Record.size())
1861 return Error("Invalid STORE record");
1862
1863 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1864 break;
1865 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001866 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lamb44d62f62007-12-11 08:59:05 +00001867 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001868 unsigned OpNum = 0;
1869 Value *Val, *Ptr;
1870 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Owen Anderson4956cde2009-07-07 20:18:58 +00001871 getValue(Record, OpNum,
1872 Context.getPointerTypeUnqual(Val->getType()), Ptr)||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001873 OpNum+2 != Record.size())
1874 return Error("Invalid STORE record");
1875
1876 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1877 break;
1878 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001879 case bitc::FUNC_CODE_INST_CALL: {
1880 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1881 if (Record.size() < 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 return Error("Invalid CALL record");
1883
Devang Pateld222f862008-09-25 21:00:45 +00001884 AttrListPtr PAL = getAttributes(Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001885 unsigned CCInfo = Record[1];
1886
1887 unsigned OpNum = 2;
1888 Value *Callee;
1889 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1890 return Error("Invalid CALL record");
1891
1892 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1893 const FunctionType *FTy = 0;
1894 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1895 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1896 return Error("Invalid CALL record");
1897
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898 SmallVector<Value*, 16> Args;
1899 // Read the fixed params.
1900 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johannesencfb19e62007-11-05 21:20:28 +00001901 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1902 Args.push_back(getBasicBlock(Record[OpNum]));
1903 else
1904 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001905 if (Args.back() == 0) return Error("Invalid CALL record");
1906 }
1907
1908 // Read type/value pairs for varargs params.
1909 if (!FTy->isVarArg()) {
1910 if (OpNum != Record.size())
1911 return Error("Invalid CALL record");
1912 } else {
1913 while (OpNum != Record.size()) {
1914 Value *Op;
1915 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1916 return Error("Invalid CALL record");
1917 Args.push_back(Op);
1918 }
1919 }
1920
Gabor Greifd6da1d02008-04-06 20:25:17 +00001921 I = CallInst::Create(Callee, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001922 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1923 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Pateld222f862008-09-25 21:00:45 +00001924 cast<CallInst>(I)->setAttributes(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001925 break;
1926 }
1927 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1928 if (Record.size() < 3)
1929 return Error("Invalid VAARG record");
1930 const Type *OpTy = getTypeByID(Record[0]);
1931 Value *Op = getFnValueByID(Record[1], OpTy);
1932 const Type *ResTy = getTypeByID(Record[2]);
1933 if (!OpTy || !Op || !ResTy)
1934 return Error("Invalid VAARG record");
1935 I = new VAArgInst(Op, ResTy);
1936 break;
1937 }
1938 }
1939
1940 // Add instruction to end of current BB. If there is no current BB, reject
1941 // this file.
1942 if (CurBB == 0) {
1943 delete I;
1944 return Error("Invalid instruction with no BB");
1945 }
1946 CurBB->getInstList().push_back(I);
1947
1948 // If this was a terminator instruction, move to the next block.
1949 if (isa<TerminatorInst>(I)) {
1950 ++CurBBNo;
1951 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1952 }
1953
1954 // Non-void values get registered in the value table for future use.
1955 if (I && I->getType() != Type::VoidTy)
1956 ValueList.AssignValue(I, NextValueNo++);
1957 }
1958
1959 // Check the function list for unresolved values.
1960 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1961 if (A->getParent() == 0) {
1962 // We found at least one unresolved value. Nuke them all to avoid leaks.
1963 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1964 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
Owen Anderson4956cde2009-07-07 20:18:58 +00001965 A->replaceAllUsesWith(Context.getUndef(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001966 delete A;
1967 }
1968 }
1969 return Error("Never resolved value found in function!");
1970 }
1971 }
1972
1973 // Trim the value list down to the size it was before we parsed this function.
1974 ValueList.shrinkTo(ModuleValueListSize);
1975 std::vector<BasicBlock*>().swap(FunctionBBs);
1976
1977 return false;
1978}
1979
1980//===----------------------------------------------------------------------===//
1981// ModuleProvider implementation
1982//===----------------------------------------------------------------------===//
1983
1984
1985bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1986 // If it already is material, ignore the request.
1987 if (!F->hasNotBeenReadFromBitcode()) return false;
1988
1989 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1990 DeferredFunctionInfo.find(F);
1991 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1992
1993 // Move the bit stream to the saved position of the deferred function body and
1994 // restore the real linkage type for the function.
1995 Stream.JumpToBit(DFII->second.first);
1996 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1997
1998 if (ParseFunctionBody(F)) {
1999 if (ErrInfo) *ErrInfo = ErrorString;
2000 return true;
2001 }
Chandler Carrutha228e392007-08-04 01:51:18 +00002002
2003 // Upgrade any old intrinsic calls in the function.
2004 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2005 E = UpgradedIntrinsics.end(); I != E; ++I) {
2006 if (I->first != I->second) {
2007 for (Value::use_iterator UI = I->first->use_begin(),
2008 UE = I->first->use_end(); UI != UE; ) {
2009 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2010 UpgradeIntrinsicCall(CI, I->second);
2011 }
2012 }
2013 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002014
2015 return false;
2016}
2017
2018void BitcodeReader::dematerializeFunction(Function *F) {
2019 // If this function isn't materialized, or if it is a proto, this is a noop.
2020 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2021 return;
2022
2023 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2024
2025 // Just forget the function body, we can remat it later.
2026 F->deleteBody();
2027 F->setLinkage(GlobalValue::GhostLinkage);
2028}
2029
2030
2031Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
Chris Lattner6b69fff2009-06-16 05:15:21 +00002032 // Iterate over the module, deserializing any functions that are still on
2033 // disk.
2034 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2035 F != E; ++F)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002036 if (F->hasNotBeenReadFromBitcode() &&
2037 materializeFunction(F, ErrInfo))
2038 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00002039
2040 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2041 // delete the old functions to clean up. We can't do this unless the entire
2042 // module is materialized because there could always be another function body
2043 // with calls to the old function.
2044 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2045 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2046 if (I->first != I->second) {
2047 for (Value::use_iterator UI = I->first->use_begin(),
2048 UE = I->first->use_end(); UI != UE; ) {
2049 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2050 UpgradeIntrinsicCall(CI, I->second);
2051 }
Chris Lattnerda486ce2009-04-01 01:43:03 +00002052 if (!I->first->use_empty())
2053 I->first->replaceAllUsesWith(I->second);
Chandler Carrutha228e392007-08-04 01:51:18 +00002054 I->first->eraseFromParent();
2055 }
2056 }
2057 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2058
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002059 return TheModule;
2060}
2061
2062
2063/// This method is provided by the parent ModuleProvde class and overriden
2064/// here. It simply releases the module from its provided and frees up our
2065/// state.
2066/// @brief Release our hold on the generated module
2067Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2068 // Since we're losing control of this Module, we must hand it back complete
2069 Module *M = ModuleProvider::releaseModule(ErrInfo);
2070 FreeState();
2071 return M;
2072}
2073
2074
2075//===----------------------------------------------------------------------===//
2076// External interface
2077//===----------------------------------------------------------------------===//
2078
2079/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2080///
2081ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
Owen Anderson92adb182009-07-01 23:13:44 +00002082 LLVMContext& Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002083 std::string *ErrMsg) {
Owen Anderson25209b42009-07-01 16:58:40 +00002084 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 if (R->ParseBitcode()) {
2086 if (ErrMsg)
2087 *ErrMsg = R->getErrorString();
2088
2089 // Don't let the BitcodeReader dtor delete 'Buffer'.
2090 R->releaseMemoryBuffer();
2091 delete R;
2092 return 0;
2093 }
2094 return R;
2095}
2096
2097/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2098/// If an error occurs, return null and fill in *ErrMsg if non-null.
Owen Anderson92adb182009-07-01 23:13:44 +00002099Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson25209b42009-07-01 16:58:40 +00002100 std::string *ErrMsg){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002101 BitcodeReader *R;
Owen Anderson25209b42009-07-01 16:58:40 +00002102 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2103 ErrMsg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 if (!R) return 0;
2105
2106 // Read in the entire module.
2107 Module *M = R->materializeModule(ErrMsg);
2108
2109 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2110 // there was an error.
2111 R->releaseMemoryBuffer();
2112
2113 // If there was no error, tell ModuleProvider not to delete it when its dtor
2114 // is run.
2115 if (M)
2116 M = R->releaseModule(ErrMsg);
Chris Lattner6b69fff2009-06-16 05:15:21 +00002117
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002118 delete R;
2119 return M;
2120}