blob: 21c4e6975a3e7d85f8832df1296fa9c038e96d6e [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"
Devang Patel7c368852009-07-28 21:49:47 +000021#include "llvm/Metadata.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Module.h"
Dan Gohman799a8c82009-07-20 21:19:07 +000023#include "llvm/Operator.h"
Chandler Carrutha228e392007-08-04 01:51:18 +000024#include "llvm/AutoUpgrade.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025#include "llvm/ADT/SmallString.h"
Devang Patel57652392008-02-26 19:38:17 +000026#include "llvm/ADT/SmallVector.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include "llvm/Support/MathExtras.h"
28#include "llvm/Support/MemoryBuffer.h"
Gabor Greif25bc3222008-05-10 08:32:32 +000029#include "llvm/OperandTraits.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030using namespace llvm;
31
32void BitcodeReader::FreeState() {
33 delete Buffer;
34 Buffer = 0;
35 std::vector<PATypeHolder>().swap(TypeList);
36 ValueList.clear();
Chris Lattner2ee85532008-03-12 02:25:52 +000037
Devang Patelf2a4a922008-09-26 22:53:05 +000038 std::vector<AttrListPtr>().swap(MAttributes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039 std::vector<BasicBlock*>().swap(FunctionBBs);
40 std::vector<Function*>().swap(FunctionsWithBodies);
41 DeferredFunctionInfo.clear();
42}
43
44//===----------------------------------------------------------------------===//
45// Helper functions to implement forward reference resolution, etc.
46//===----------------------------------------------------------------------===//
47
48/// ConvertToString - Convert a string from a record into an std::string, return
49/// true on failure.
50template<typename StrTy>
51static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
52 StrTy &Result) {
53 if (Idx > Record.size())
54 return true;
55
56 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
57 Result += (char)Record[i];
58 return false;
59}
60
61static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
62 switch (Val) {
63 default: // Map unknown/new linkages to external
Bill Wendling41a07852009-07-20 01:03:30 +000064 case 0: return GlobalValue::ExternalLinkage;
65 case 1: return GlobalValue::WeakAnyLinkage;
66 case 2: return GlobalValue::AppendingLinkage;
67 case 3: return GlobalValue::InternalLinkage;
68 case 4: return GlobalValue::LinkOnceAnyLinkage;
69 case 5: return GlobalValue::DLLImportLinkage;
70 case 6: return GlobalValue::DLLExportLinkage;
71 case 7: return GlobalValue::ExternalWeakLinkage;
72 case 8: return GlobalValue::CommonLinkage;
73 case 9: return GlobalValue::PrivateLinkage;
Duncan Sands19d161f2009-03-07 15:45:40 +000074 case 10: return GlobalValue::WeakODRLinkage;
75 case 11: return GlobalValue::LinkOnceODRLinkage;
Chris Lattner68433442009-04-13 05:44:34 +000076 case 12: return GlobalValue::AvailableExternallyLinkage;
Bill Wendling41a07852009-07-20 01:03:30 +000077 case 13: return GlobalValue::LinkerPrivateLinkage;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 }
79}
80
81static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
82 switch (Val) {
83 default: // Map unknown visibilities to default.
84 case 0: return GlobalValue::DefaultVisibility;
85 case 1: return GlobalValue::HiddenVisibility;
86 case 2: return GlobalValue::ProtectedVisibility;
87 }
88}
89
90static int GetDecodedCastOpcode(unsigned Val) {
91 switch (Val) {
92 default: return -1;
93 case bitc::CAST_TRUNC : return Instruction::Trunc;
94 case bitc::CAST_ZEXT : return Instruction::ZExt;
95 case bitc::CAST_SEXT : return Instruction::SExt;
96 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
97 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
98 case bitc::CAST_UITOFP : return Instruction::UIToFP;
99 case bitc::CAST_SITOFP : return Instruction::SIToFP;
100 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
101 case bitc::CAST_FPEXT : return Instruction::FPExt;
102 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
103 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
104 case bitc::CAST_BITCAST : return Instruction::BitCast;
105 }
106}
107static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
108 switch (Val) {
109 default: return -1;
Dan Gohman7ce405e2009-06-04 22:49:04 +0000110 case bitc::BINOP_ADD:
111 return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
112 case bitc::BINOP_SUB:
113 return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
114 case bitc::BINOP_MUL:
115 return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 case bitc::BINOP_UDIV: return Instruction::UDiv;
117 case bitc::BINOP_SDIV:
118 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
119 case bitc::BINOP_UREM: return Instruction::URem;
120 case bitc::BINOP_SREM:
121 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
122 case bitc::BINOP_SHL: return Instruction::Shl;
123 case bitc::BINOP_LSHR: return Instruction::LShr;
124 case bitc::BINOP_ASHR: return Instruction::AShr;
125 case bitc::BINOP_AND: return Instruction::And;
126 case bitc::BINOP_OR: return Instruction::Or;
127 case bitc::BINOP_XOR: return Instruction::Xor;
128 }
129}
130
Gabor Greif25bc3222008-05-10 08:32:32 +0000131namespace llvm {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132namespace {
133 /// @brief A class for maintaining the slot number definition
134 /// as a placeholder for the actual definition for forward constants defs.
135 class ConstantPlaceHolder : public ConstantExpr {
136 ConstantPlaceHolder(); // DO NOT IMPLEMENT
137 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Gabor Greifd6da1d02008-04-06 20:25:17 +0000138 public:
139 // allocate space for exactly one operand
140 void *operator new(size_t s) {
141 return User::operator new(s, 1);
142 }
Owen Anderson4956cde2009-07-07 20:18:58 +0000143 explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
Gabor Greif25bc3222008-05-10 08:32:32 +0000144 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000145 Op<0>() = Context.getUndef(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 }
Chris Lattner345bbb72008-08-21 02:34:16 +0000147
148 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
149 static inline bool classof(const ConstantPlaceHolder *) { return true; }
150 static bool classof(const Value *V) {
151 return isa<ConstantExpr>(V) &&
152 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
153 }
154
155
Gabor Greif25bc3222008-05-10 08:32:32 +0000156 /// Provide fast operand accessors
Chris Lattnered490d12009-03-31 22:55:09 +0000157 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 };
159}
160
Chris Lattnered490d12009-03-31 22:55:09 +0000161// FIXME: can we inherit this from ConstantExpr?
Gabor Greif25bc3222008-05-10 08:32:32 +0000162template <>
163struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
164};
Gabor Greif25bc3222008-05-10 08:32:32 +0000165}
166
Chris Lattnered490d12009-03-31 22:55:09 +0000167
168void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
169 if (Idx == size()) {
170 push_back(V);
171 return;
172 }
173
174 if (Idx >= size())
175 resize(Idx+1);
176
177 WeakVH &OldV = ValuePtrs[Idx];
178 if (OldV == 0) {
179 OldV = V;
180 return;
181 }
182
183 // Handle constants and non-constants (e.g. instrs) differently for
184 // efficiency.
185 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
186 ResolveConstants.push_back(std::make_pair(PHC, Idx));
187 OldV = V;
188 } else {
189 // If there was a forward reference to this value, replace it.
190 Value *PrevVal = OldV;
191 OldV->replaceAllUsesWith(V);
192 delete PrevVal;
Gabor Greif25bc3222008-05-10 08:32:32 +0000193 }
194}
Chris Lattnered490d12009-03-31 22:55:09 +0000195
Gabor Greif25bc3222008-05-10 08:32:32 +0000196
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
198 const Type *Ty) {
Chris Lattnered490d12009-03-31 22:55:09 +0000199 if (Idx >= size())
Gabor Greif25bc3222008-05-10 08:32:32 +0000200 resize(Idx + 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201
Chris Lattnered490d12009-03-31 22:55:09 +0000202 if (Value *V = ValuePtrs[Idx]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 assert(Ty == V->getType() && "Type mismatch in constant table!");
204 return cast<Constant>(V);
205 }
206
207 // Create and return a placeholder, which will later be RAUW'd.
Owen Anderson4956cde2009-07-07 20:18:58 +0000208 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattnered490d12009-03-31 22:55:09 +0000209 ValuePtrs[Idx] = C;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 return C;
211}
212
213Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
Chris Lattnered490d12009-03-31 22:55:09 +0000214 if (Idx >= size())
Gabor Greif25bc3222008-05-10 08:32:32 +0000215 resize(Idx + 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216
Chris Lattnered490d12009-03-31 22:55:09 +0000217 if (Value *V = ValuePtrs[Idx]) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000218 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
219 return V;
220 }
221
222 // No type specified, must be invalid reference.
223 if (Ty == 0) return 0;
224
225 // Create and return a placeholder, which will later be RAUW'd.
226 Value *V = new Argument(Ty);
Chris Lattnered490d12009-03-31 22:55:09 +0000227 ValuePtrs[Idx] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 return V;
229}
230
Chris Lattner345bbb72008-08-21 02:34:16 +0000231/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
232/// resolves any forward references. The idea behind this is that we sometimes
233/// get constants (such as large arrays) which reference *many* forward ref
234/// constants. Replacing each of these causes a lot of thrashing when
235/// building/reuniquing the constant. Instead of doing this, we look at all the
236/// uses and rewrite all the place holders at once for any constant that uses
237/// a placeholder.
238void BitcodeReaderValueList::ResolveConstantForwardRefs() {
239 // Sort the values by-pointer so that they are efficient to look up with a
240 // binary search.
241 std::sort(ResolveConstants.begin(), ResolveConstants.end());
242
243 SmallVector<Constant*, 64> NewOps;
244
245 while (!ResolveConstants.empty()) {
Chris Lattnered490d12009-03-31 22:55:09 +0000246 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner345bbb72008-08-21 02:34:16 +0000247 Constant *Placeholder = ResolveConstants.back().first;
248 ResolveConstants.pop_back();
249
250 // Loop over all users of the placeholder, updating them to reference the
251 // new value. If they reference more than one placeholder, update them all
252 // at once.
253 while (!Placeholder->use_empty()) {
Chris Lattner8ae2e252008-08-21 17:31:45 +0000254 Value::use_iterator UI = Placeholder->use_begin();
255
Chris Lattner345bbb72008-08-21 02:34:16 +0000256 // If the using object isn't uniqued, just update the operands. This
257 // handles instructions and initializers for global variables.
Chris Lattner8ae2e252008-08-21 17:31:45 +0000258 if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
259 UI.getUse().set(RealVal);
Chris Lattner345bbb72008-08-21 02:34:16 +0000260 continue;
261 }
262
263 // Otherwise, we have a constant that uses the placeholder. Replace that
264 // constant with a new constant that has *all* placeholder uses updated.
Chris Lattner8ae2e252008-08-21 17:31:45 +0000265 Constant *UserC = cast<Constant>(*UI);
Chris Lattner345bbb72008-08-21 02:34:16 +0000266 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
267 I != E; ++I) {
268 Value *NewOp;
269 if (!isa<ConstantPlaceHolder>(*I)) {
270 // Not a placeholder reference.
271 NewOp = *I;
272 } else if (*I == Placeholder) {
273 // Common case is that it just references this one placeholder.
274 NewOp = RealVal;
275 } else {
276 // Otherwise, look up the placeholder in ResolveConstants.
277 ResolveConstantsTy::iterator It =
278 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
279 std::pair<Constant*, unsigned>(cast<Constant>(*I),
280 0));
281 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattnered490d12009-03-31 22:55:09 +0000282 NewOp = operator[](It->second);
Chris Lattner345bbb72008-08-21 02:34:16 +0000283 }
284
285 NewOps.push_back(cast<Constant>(NewOp));
286 }
287
288 // Make the new constant.
289 Constant *NewC;
290 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Owen Anderson7b4f9f82009-07-28 18:32:17 +0000291 NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
Owen Anderson4956cde2009-07-07 20:18:58 +0000292 NewOps.size());
Chris Lattner345bbb72008-08-21 02:34:16 +0000293 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Owen Anderson9c9f10e2009-07-27 22:29:26 +0000294 NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
Owen Anderson4956cde2009-07-07 20:18:58 +0000295 UserCS->getType()->isPacked());
Chris Lattner345bbb72008-08-21 02:34:16 +0000296 } else if (isa<ConstantVector>(UserC)) {
Owen Anderson2f422e02009-07-28 21:19:26 +0000297 NewC = ConstantVector::get(&NewOps[0], NewOps.size());
Nick Lewycky117f4382009-05-10 20:57:05 +0000298 } else {
299 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Chris Lattner345bbb72008-08-21 02:34:16 +0000300 NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
301 NewOps.size());
302 }
303
304 UserC->replaceAllUsesWith(NewC);
305 UserC->destroyConstant();
306 NewOps.clear();
307 }
308
Nick Lewycky117f4382009-05-10 20:57:05 +0000309 // Update all ValueHandles, they should be the only users at this point.
310 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner345bbb72008-08-21 02:34:16 +0000311 delete Placeholder;
312 }
313}
314
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315
316const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
317 // If the TypeID is in range, return it.
318 if (ID < TypeList.size())
319 return TypeList[ID].get();
320 if (!isTypeTable) return 0;
321
322 // The type table allows forward references. Push as many Opaque types as
323 // needed to get up to ID.
324 while (TypeList.size() <= ID)
Owen Anderson4956cde2009-07-07 20:18:58 +0000325 TypeList.push_back(Context.getOpaqueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 return TypeList.back().get();
327}
328
329//===----------------------------------------------------------------------===//
330// Functions for parsing blocks from the bitcode file
331//===----------------------------------------------------------------------===//
332
Devang Pateld222f862008-09-25 21:00:45 +0000333bool BitcodeReader::ParseAttributeBlock() {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
335 return Error("Malformed block record");
336
Devang Patelf2a4a922008-09-26 22:53:05 +0000337 if (!MAttributes.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338 return Error("Multiple PARAMATTR blocks found!");
339
340 SmallVector<uint64_t, 64> Record;
341
Devang Pateld222f862008-09-25 21:00:45 +0000342 SmallVector<AttributeWithIndex, 8> Attrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343
344 // Read all the records.
345 while (1) {
346 unsigned Code = Stream.ReadCode();
347 if (Code == bitc::END_BLOCK) {
348 if (Stream.ReadBlockEnd())
349 return Error("Error at end of PARAMATTR block");
350 return false;
351 }
352
353 if (Code == bitc::ENTER_SUBBLOCK) {
354 // No known subblocks, always skip them.
355 Stream.ReadSubBlockID();
356 if (Stream.SkipBlock())
357 return Error("Malformed block record");
358 continue;
359 }
360
361 if (Code == bitc::DEFINE_ABBREV) {
362 Stream.ReadAbbrevRecord();
363 continue;
364 }
365
366 // Read a record.
367 Record.clear();
368 switch (Stream.ReadRecord(Code, Record)) {
369 default: // Default behavior: ignore.
370 break;
371 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
372 if (Record.size() & 1)
373 return Error("Invalid ENTRY record");
374
Chris Lattner58601542008-10-05 18:22:09 +0000375 // FIXME : Remove this autoupgrade code in LLVM 3.0.
Devang Patelf2a4a922008-09-26 22:53:05 +0000376 // If Function attributes are using index 0 then transfer them
Chris Lattner58601542008-10-05 18:22:09 +0000377 // to index ~0. Index 0 is used for return value attributes but used to be
378 // used for function attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +0000379 Attributes RetAttribute = Attribute::None;
380 Attributes FnAttribute = Attribute::None;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Nick Lewycky4029a942008-12-19 09:38:31 +0000382 // FIXME: remove in LLVM 3.0
383 // The alignment is stored as a 16-bit raw value from bits 31--16.
384 // We shift the bits above 31 down by 11 bits.
385
386 unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
387 if (Alignment && !isPowerOf2_32(Alignment))
388 return Error("Alignment is not a power of two.");
389
390 Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
391 if (Alignment)
392 ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
393 ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
394 Record[i+1] = ReconstitutedAttr;
395
Devang Patelf2a4a922008-09-26 22:53:05 +0000396 if (Record[i] == 0)
397 RetAttribute = Record[i+1];
398 else if (Record[i] == ~0U)
399 FnAttribute = Record[i+1];
400 }
Chris Lattner58601542008-10-05 18:22:09 +0000401
402 unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
403 Attribute::ReadOnly|Attribute::ReadNone);
404
405 if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
406 (RetAttribute & OldRetAttrs) != 0) {
407 if (FnAttribute == Attribute::None) { // add a slot so they get added.
408 Record.push_back(~0U);
409 Record.push_back(0);
Devang Patelf2a4a922008-09-26 22:53:05 +0000410 }
Chris Lattner58601542008-10-05 18:22:09 +0000411
412 FnAttribute |= RetAttribute & OldRetAttrs;
413 RetAttribute &= ~OldRetAttrs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 }
Chris Lattner2ee85532008-03-12 02:25:52 +0000415
Devang Patelf2a4a922008-09-26 22:53:05 +0000416 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattner58601542008-10-05 18:22:09 +0000417 if (Record[i] == 0) {
418 if (RetAttribute != Attribute::None)
419 Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
420 } else if (Record[i] == ~0U) {
421 if (FnAttribute != Attribute::None)
422 Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
423 } else if (Record[i+1] != Attribute::None)
Devang Patelf2a4a922008-09-26 22:53:05 +0000424 Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
425 }
Devang Patelf2a4a922008-09-26 22:53:05 +0000426
427 MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000428 Attrs.clear();
429 break;
430 }
Duncan Sandse2898f02007-11-20 14:09:29 +0000431 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 }
433}
434
435
436bool BitcodeReader::ParseTypeTable() {
437 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
438 return Error("Malformed block record");
439
440 if (!TypeList.empty())
441 return Error("Multiple TYPE_BLOCKs found!");
442
443 SmallVector<uint64_t, 64> Record;
444 unsigned NumRecords = 0;
445
446 // Read all the records for this type table.
447 while (1) {
448 unsigned Code = Stream.ReadCode();
449 if (Code == bitc::END_BLOCK) {
450 if (NumRecords != TypeList.size())
451 return Error("Invalid type forward reference in TYPE_BLOCK");
452 if (Stream.ReadBlockEnd())
453 return Error("Error at end of type table block");
454 return false;
455 }
456
457 if (Code == bitc::ENTER_SUBBLOCK) {
458 // No known subblocks, always skip them.
459 Stream.ReadSubBlockID();
460 if (Stream.SkipBlock())
461 return Error("Malformed block record");
462 continue;
463 }
464
465 if (Code == bitc::DEFINE_ABBREV) {
466 Stream.ReadAbbrevRecord();
467 continue;
468 }
469
470 // Read a record.
471 Record.clear();
472 const Type *ResultTy = 0;
473 switch (Stream.ReadRecord(Code, Record)) {
474 default: // Default behavior: unknown type.
475 ResultTy = 0;
476 break;
477 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
478 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
479 // type list. This allows us to reserve space.
480 if (Record.size() < 1)
481 return Error("Invalid TYPE_CODE_NUMENTRY record");
482 TypeList.reserve(Record[0]);
483 continue;
484 case bitc::TYPE_CODE_VOID: // VOID
485 ResultTy = Type::VoidTy;
486 break;
487 case bitc::TYPE_CODE_FLOAT: // FLOAT
488 ResultTy = Type::FloatTy;
489 break;
490 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
491 ResultTy = Type::DoubleTy;
492 break;
Dale Johannesenf325d9f2007-08-03 01:03:46 +0000493 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
494 ResultTy = Type::X86_FP80Ty;
495 break;
496 case bitc::TYPE_CODE_FP128: // FP128
497 ResultTy = Type::FP128Ty;
498 break;
499 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
500 ResultTy = Type::PPC_FP128Ty;
501 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502 case bitc::TYPE_CODE_LABEL: // LABEL
503 ResultTy = Type::LabelTy;
504 break;
505 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
506 ResultTy = 0;
507 break;
Nick Lewycky29aaef82009-05-30 05:06:04 +0000508 case bitc::TYPE_CODE_METADATA: // METADATA
509 ResultTy = Type::MetadataTy;
510 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000511 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
512 if (Record.size() < 1)
513 return Error("Invalid Integer type record");
514
Owen Anderson4956cde2009-07-07 20:18:58 +0000515 ResultTy = Context.getIntegerType(Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516 break;
Christopher Lamb44d62f62007-12-11 08:59:05 +0000517 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
518 // [pointee type, address space]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 if (Record.size() < 1)
520 return Error("Invalid POINTER type record");
Christopher Lamb44d62f62007-12-11 08:59:05 +0000521 unsigned AddressSpace = 0;
522 if (Record.size() == 2)
523 AddressSpace = Record[1];
Owen Anderson4956cde2009-07-07 20:18:58 +0000524 ResultTy = Context.getPointerType(getTypeByID(Record[0], true),
525 AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000526 break;
Christopher Lamb44d62f62007-12-11 08:59:05 +0000527 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000528 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattner70b644d2007-11-27 17:48:06 +0000529 // FIXME: attrid is dead, remove it in LLVM 3.0
530 // FUNCTION: [vararg, attrid, retty, paramty x N]
531 if (Record.size() < 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 return Error("Invalid FUNCTION type record");
533 std::vector<const Type*> ArgTys;
Chris Lattner70b644d2007-11-27 17:48:06 +0000534 for (unsigned i = 3, e = Record.size(); i != e; ++i)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 ArgTys.push_back(getTypeByID(Record[i], true));
536
Owen Anderson4956cde2009-07-07 20:18:58 +0000537 ResultTy = Context.getFunctionType(getTypeByID(Record[2], true), ArgTys,
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000538 Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 break;
540 }
541 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
542 if (Record.size() < 1)
543 return Error("Invalid STRUCT type record");
544 std::vector<const Type*> EltTys;
545 for (unsigned i = 1, e = Record.size(); i != e; ++i)
546 EltTys.push_back(getTypeByID(Record[i], true));
Owen Anderson4956cde2009-07-07 20:18:58 +0000547 ResultTy = Context.getStructType(EltTys, Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 break;
549 }
550 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
551 if (Record.size() < 2)
552 return Error("Invalid ARRAY type record");
Owen Anderson4956cde2009-07-07 20:18:58 +0000553 ResultTy = Context.getArrayType(getTypeByID(Record[1], true), Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 break;
555 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
556 if (Record.size() < 2)
557 return Error("Invalid VECTOR type record");
Owen Anderson4956cde2009-07-07 20:18:58 +0000558 ResultTy = Context.getVectorType(getTypeByID(Record[1], true), Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 break;
560 }
561
562 if (NumRecords == TypeList.size()) {
563 // If this is a new type slot, just append it.
Owen Anderson4956cde2009-07-07 20:18:58 +0000564 TypeList.push_back(ResultTy ? ResultTy : Context.getOpaqueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 ++NumRecords;
566 } else if (ResultTy == 0) {
567 // Otherwise, this was forward referenced, so an opaque type was created,
568 // but the result type is actually just an opaque. Leave the one we
569 // created previously.
570 ++NumRecords;
571 } else {
572 // Otherwise, this was forward referenced, so an opaque type was created.
573 // Resolve the opaque type to the real type now.
574 assert(NumRecords < TypeList.size() && "Typelist imbalance");
575 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
576
577 // Don't directly push the new type on the Tab. Instead we want to replace
578 // the opaque type we previously inserted with the new concrete value. The
579 // refinement from the abstract (opaque) type to the new type causes all
580 // uses of the abstract type to use the concrete type (NewTy). This will
581 // also cause the opaque type to be deleted.
582 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
583
584 // This should have replaced the old opaque type with the new type in the
585 // value table... or with a preexisting type that was already in the
586 // system. Let's just make sure it did.
587 assert(TypeList[NumRecords-1].get() != OldTy &&
588 "refineAbstractType didn't work!");
589 }
590 }
591}
592
593
594bool BitcodeReader::ParseTypeSymbolTable() {
595 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
596 return Error("Malformed block record");
597
598 SmallVector<uint64_t, 64> Record;
599
600 // Read all the records for this type table.
601 std::string TypeName;
602 while (1) {
603 unsigned Code = Stream.ReadCode();
604 if (Code == bitc::END_BLOCK) {
605 if (Stream.ReadBlockEnd())
606 return Error("Error at end of type symbol table block");
607 return false;
608 }
609
610 if (Code == bitc::ENTER_SUBBLOCK) {
611 // No known subblocks, always skip them.
612 Stream.ReadSubBlockID();
613 if (Stream.SkipBlock())
614 return Error("Malformed block record");
615 continue;
616 }
617
618 if (Code == bitc::DEFINE_ABBREV) {
619 Stream.ReadAbbrevRecord();
620 continue;
621 }
622
623 // Read a record.
624 Record.clear();
625 switch (Stream.ReadRecord(Code, Record)) {
626 default: // Default behavior: unknown type.
627 break;
628 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
629 if (ConvertToString(Record, 1, TypeName))
630 return Error("Invalid TST_ENTRY record");
631 unsigned TypeID = Record[0];
632 if (TypeID >= TypeList.size())
633 return Error("Invalid Type ID in TST_ENTRY record");
634
635 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
636 TypeName.clear();
637 break;
638 }
639 }
640}
641
642bool BitcodeReader::ParseValueSymbolTable() {
643 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
644 return Error("Malformed block record");
645
646 SmallVector<uint64_t, 64> Record;
647
648 // Read all the records for this value table.
649 SmallString<128> ValueName;
650 while (1) {
651 unsigned Code = Stream.ReadCode();
652 if (Code == bitc::END_BLOCK) {
653 if (Stream.ReadBlockEnd())
654 return Error("Error at end of value symbol table block");
655 return false;
656 }
657 if (Code == bitc::ENTER_SUBBLOCK) {
658 // No known subblocks, always skip them.
659 Stream.ReadSubBlockID();
660 if (Stream.SkipBlock())
661 return Error("Malformed block record");
662 continue;
663 }
664
665 if (Code == bitc::DEFINE_ABBREV) {
666 Stream.ReadAbbrevRecord();
667 continue;
668 }
669
670 // Read a record.
671 Record.clear();
672 switch (Stream.ReadRecord(Code, Record)) {
673 default: // Default behavior: unknown type.
674 break;
675 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
676 if (ConvertToString(Record, 1, ValueName))
Nick Lewyckydc9b1b52009-05-31 06:07:28 +0000677 return Error("Invalid VST_ENTRY record");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000678 unsigned ValueID = Record[0];
679 if (ValueID >= ValueList.size())
680 return Error("Invalid Value ID in VST_ENTRY record");
681 Value *V = ValueList[ValueID];
682
Daniel Dunbar1be13862009-07-26 00:34:27 +0000683 V->setName(StringRef(ValueName.data(), ValueName.size()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 ValueName.clear();
685 break;
686 }
687 case bitc::VST_CODE_BBENTRY: {
688 if (ConvertToString(Record, 1, ValueName))
689 return Error("Invalid VST_BBENTRY record");
690 BasicBlock *BB = getBasicBlock(Record[0]);
691 if (BB == 0)
692 return Error("Invalid BB ID in VST_BBENTRY record");
693
Daniel Dunbar1be13862009-07-26 00:34:27 +0000694 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 ValueName.clear();
696 break;
697 }
698 }
699 }
700}
701
Devang Patel0c0a6ca2009-07-22 17:43:22 +0000702bool BitcodeReader::ParseMetadata() {
703 unsigned NextValueNo = ValueList.size();
704
705 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
706 return Error("Malformed block record");
707
708 SmallVector<uint64_t, 64> Record;
709
710 // Read all the records.
711 while (1) {
712 unsigned Code = Stream.ReadCode();
713 if (Code == bitc::END_BLOCK) {
714 if (Stream.ReadBlockEnd())
715 return Error("Error at end of PARAMATTR block");
716 return false;
717 }
718
719 if (Code == bitc::ENTER_SUBBLOCK) {
720 // No known subblocks, always skip them.
721 Stream.ReadSubBlockID();
722 if (Stream.SkipBlock())
723 return Error("Malformed block record");
724 continue;
725 }
726
727 if (Code == bitc::DEFINE_ABBREV) {
728 Stream.ReadAbbrevRecord();
729 continue;
730 }
731
732 // Read a record.
733 Record.clear();
734 switch (Stream.ReadRecord(Code, Record)) {
735 default: // Default behavior: ignore.
736 break;
Devang Patel54199ef2009-07-23 01:07:34 +0000737 case bitc::METADATA_NODE: {
738 if (Record.empty() || Record.size() % 2 == 1)
739 return Error("Invalid METADATA_NODE record");
740
741 unsigned Size = Record.size();
742 SmallVector<Value*, 8> Elts;
743 for (unsigned i = 0; i != Size; i += 2) {
744 const Type *Ty = getTypeByID(Record[i], false);
745 if (Ty != Type::VoidTy)
746 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
747 else
748 Elts.push_back(NULL);
749 }
750 Value *V = Context.getMDNode(&Elts[0], Elts.size());
751 ValueList.AssignValue(V, NextValueNo++);
752 break;
753 }
Devang Patel0c0a6ca2009-07-22 17:43:22 +0000754 case bitc::METADATA_STRING: {
755 unsigned MDStringLength = Record.size();
756 SmallString<8> String;
757 String.resize(MDStringLength);
758 for (unsigned i = 0; i != MDStringLength; ++i)
759 String[i] = Record[i];
Daniel Dunbara49de6f2009-07-25 06:02:13 +0000760 Value *V = Context.getMDString(StringRef(String.data(), String.size()));
Devang Patel0c0a6ca2009-07-22 17:43:22 +0000761 ValueList.AssignValue(V, NextValueNo++);
762 break;
763 }
764 }
765 }
766}
767
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
769/// the LSB for dense VBR encoding.
770static uint64_t DecodeSignRotatedValue(uint64_t V) {
771 if ((V & 1) == 0)
772 return V >> 1;
773 if (V != 1)
774 return -(V >> 1);
775 // There is no such thing as -0 with integers. "-0" really means MININT.
776 return 1ULL << 63;
777}
778
779/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
780/// values and aliases that we can.
781bool BitcodeReader::ResolveGlobalAndAliasInits() {
782 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
783 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
784
785 GlobalInitWorklist.swap(GlobalInits);
786 AliasInitWorklist.swap(AliasInits);
787
788 while (!GlobalInitWorklist.empty()) {
789 unsigned ValID = GlobalInitWorklist.back().second;
790 if (ValID >= ValueList.size()) {
791 // Not ready to resolve this yet, it requires something later in the file.
792 GlobalInits.push_back(GlobalInitWorklist.back());
793 } else {
794 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
795 GlobalInitWorklist.back().first->setInitializer(C);
796 else
797 return Error("Global variable initializer is not a constant!");
798 }
799 GlobalInitWorklist.pop_back();
800 }
801
802 while (!AliasInitWorklist.empty()) {
803 unsigned ValID = AliasInitWorklist.back().second;
804 if (ValID >= ValueList.size()) {
805 AliasInits.push_back(AliasInitWorklist.back());
806 } else {
807 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
808 AliasInitWorklist.back().first->setAliasee(C);
809 else
810 return Error("Alias initializer is not a constant!");
811 }
812 AliasInitWorklist.pop_back();
813 }
814 return false;
815}
816
Dan Gohman799a8c82009-07-20 21:19:07 +0000817static void SetOptimizationFlags(Value *V, uint64_t Flags) {
818 if (OverflowingBinaryOperator *OBO =
819 dyn_cast<OverflowingBinaryOperator>(V)) {
820 if (Flags & (1 << bitc::OBO_NO_SIGNED_OVERFLOW))
821 OBO->setHasNoSignedOverflow(true);
822 if (Flags & (1 << bitc::OBO_NO_UNSIGNED_OVERFLOW))
823 OBO->setHasNoUnsignedOverflow(true);
824 } else if (SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
825 if (Flags & (1 << bitc::SDIV_EXACT))
826 Div->setIsExact(true);
827 }
828}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000829
830bool BitcodeReader::ParseConstants() {
831 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
832 return Error("Malformed block record");
833
834 SmallVector<uint64_t, 64> Record;
835
836 // Read all the records for this value table.
837 const Type *CurTy = Type::Int32Ty;
838 unsigned NextCstNo = ValueList.size();
839 while (1) {
840 unsigned Code = Stream.ReadCode();
Chris Lattner345bbb72008-08-21 02:34:16 +0000841 if (Code == bitc::END_BLOCK)
842 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843
844 if (Code == bitc::ENTER_SUBBLOCK) {
845 // No known subblocks, always skip them.
846 Stream.ReadSubBlockID();
847 if (Stream.SkipBlock())
848 return Error("Malformed block record");
849 continue;
850 }
851
852 if (Code == bitc::DEFINE_ABBREV) {
853 Stream.ReadAbbrevRecord();
854 continue;
855 }
856
857 // Read a record.
858 Record.clear();
859 Value *V = 0;
Dan Gohman799a8c82009-07-20 21:19:07 +0000860 unsigned BitCode = Stream.ReadRecord(Code, Record);
861 switch (BitCode) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 default: // Default behavior: unknown constant
863 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Anderson4956cde2009-07-07 20:18:58 +0000864 V = Context.getUndef(CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 break;
866 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
867 if (Record.empty())
868 return Error("Malformed CST_SETTYPE record");
869 if (Record[0] >= TypeList.size())
870 return Error("Invalid Type ID in CST_SETTYPE record");
871 CurTy = TypeList[Record[0]];
872 continue; // Skip the ValueList manipulation.
873 case bitc::CST_CODE_NULL: // NULL
Owen Anderson4956cde2009-07-07 20:18:58 +0000874 V = Context.getNullValue(CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 break;
876 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
877 if (!isa<IntegerType>(CurTy) || Record.empty())
878 return Error("Invalid CST_INTEGER record");
Owen Andersoneacb44d2009-07-24 23:12:02 +0000879 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 break;
881 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
882 if (!isa<IntegerType>(CurTy) || Record.empty())
883 return Error("Invalid WIDE_INTEGER record");
884
885 unsigned NumWords = Record.size();
886 SmallVector<uint64_t, 8> Words;
887 Words.resize(NumWords);
888 for (unsigned i = 0; i != NumWords; ++i)
889 Words[i] = DecodeSignRotatedValue(Record[i]);
Owen Andersoneacb44d2009-07-24 23:12:02 +0000890 V = ConstantInt::get(Context,
891 APInt(cast<IntegerType>(CurTy)->getBitWidth(),
892 NumWords, &Words[0]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 break;
894 }
Dale Johannesen1616e902007-09-11 18:32:33 +0000895 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896 if (Record.empty())
897 return Error("Invalid FLOAT record");
898 if (CurTy == Type::FloatTy)
Owen Andersond363a0e2009-07-27 20:59:43 +0000899 V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 else if (CurTy == Type::DoubleTy)
Owen Andersond363a0e2009-07-27 20:59:43 +0000901 V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
Dale Johannesen0a92eac2009-03-23 21:16:53 +0000902 else if (CurTy == Type::X86_FP80Ty) {
903 // Bits are not stored the same way as a normal i80 APInt, compensate.
904 uint64_t Rearrange[2];
905 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
906 Rearrange[1] = Record[0] >> 48;
Owen Andersond363a0e2009-07-27 20:59:43 +0000907 V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
Dale Johannesen0a92eac2009-03-23 21:16:53 +0000908 } else if (CurTy == Type::FP128Ty)
Owen Andersond363a0e2009-07-27 20:59:43 +0000909 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000910 else if (CurTy == Type::PPC_FP128Ty)
Owen Andersond363a0e2009-07-27 20:59:43 +0000911 V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912 else
Owen Anderson4956cde2009-07-07 20:18:58 +0000913 V = Context.getUndef(CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 break;
Dale Johannesen1616e902007-09-11 18:32:33 +0000915 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916
917 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
918 if (Record.empty())
919 return Error("Invalid CST_AGGREGATE record");
920
921 unsigned Size = Record.size();
922 std::vector<Constant*> Elts;
923
924 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
925 for (unsigned i = 0; i != Size; ++i)
926 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
927 STy->getElementType(i)));
Owen Anderson9c9f10e2009-07-27 22:29:26 +0000928 V = ConstantStruct::get(STy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
930 const Type *EltTy = ATy->getElementType();
931 for (unsigned i = 0; i != Size; ++i)
932 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson7b4f9f82009-07-28 18:32:17 +0000933 V = ConstantArray::get(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
935 const Type *EltTy = VTy->getElementType();
936 for (unsigned i = 0; i != Size; ++i)
937 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson2f422e02009-07-28 21:19:26 +0000938 V = ConstantVector::get(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 } else {
Owen Anderson4956cde2009-07-07 20:18:58 +0000940 V = Context.getUndef(CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 }
942 break;
943 }
944 case bitc::CST_CODE_STRING: { // STRING: [values]
945 if (Record.empty())
946 return Error("Invalid CST_AGGREGATE record");
947
948 const ArrayType *ATy = cast<ArrayType>(CurTy);
949 const Type *EltTy = ATy->getElementType();
950
951 unsigned Size = Record.size();
952 std::vector<Constant*> Elts;
953 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +0000954 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson7b4f9f82009-07-28 18:32:17 +0000955 V = ConstantArray::get(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 break;
957 }
958 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
959 if (Record.empty())
960 return Error("Invalid CST_AGGREGATE record");
961
962 const ArrayType *ATy = cast<ArrayType>(CurTy);
963 const Type *EltTy = ATy->getElementType();
964
965 unsigned Size = Record.size();
966 std::vector<Constant*> Elts;
967 for (unsigned i = 0; i != Size; ++i)
Owen Andersoneacb44d2009-07-24 23:12:02 +0000968 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
Owen Anderson4956cde2009-07-07 20:18:58 +0000969 Elts.push_back(Context.getNullValue(EltTy));
Owen Anderson7b4f9f82009-07-28 18:32:17 +0000970 V = ConstantArray::get(ATy, Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000971 break;
972 }
973 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
974 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
975 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
976 if (Opc < 0) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000977 V = Context.getUndef(CurTy); // Unknown binop.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 } else {
979 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
980 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Owen Anderson4956cde2009-07-07 20:18:58 +0000981 V = Context.getConstantExpr(Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000982 }
Dan Gohman799a8c82009-07-20 21:19:07 +0000983 if (Record.size() >= 4)
984 SetOptimizationFlags(V, Record[3]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 break;
986 }
987 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
988 if (Record.size() < 3) return Error("Invalid CE_CAST record");
989 int Opc = GetDecodedCastOpcode(Record[0]);
990 if (Opc < 0) {
Owen Anderson4956cde2009-07-07 20:18:58 +0000991 V = Context.getUndef(CurTy); // Unknown cast.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 } else {
993 const Type *OpTy = getTypeByID(Record[1]);
994 if (!OpTy) return Error("Invalid CE_CAST record");
995 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Anderson4956cde2009-07-07 20:18:58 +0000996 V = Context.getConstantExprCast(Opc, Op, CurTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997 }
998 break;
999 }
Dan Gohman106b2ae2009-07-27 21:53:46 +00001000 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
1002 if (Record.size() & 1) return Error("Invalid CE_GEP record");
1003 SmallVector<Constant*, 16> Elts;
1004 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1005 const Type *ElTy = getTypeByID(Record[i]);
1006 if (!ElTy) return Error("Invalid CE_GEP record");
1007 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1008 }
Owen Anderson4956cde2009-07-07 20:18:58 +00001009 V = Context.getConstantExprGetElementPtr(Elts[0], &Elts[1],
1010 Elts.size()-1);
Dan Gohman106b2ae2009-07-27 21:53:46 +00001011 if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1012 cast<GEPOperator>(V)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 break;
1014 }
1015 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
1016 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
Owen Anderson4956cde2009-07-07 20:18:58 +00001017 V = Context.getConstantExprSelect(ValueList.getConstantFwdRef(Record[0],
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 Type::Int1Ty),
1019 ValueList.getConstantFwdRef(Record[1],CurTy),
1020 ValueList.getConstantFwdRef(Record[2],CurTy));
1021 break;
1022 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1023 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1024 const VectorType *OpTy =
1025 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1026 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1027 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner12b4aee2009-02-03 02:11:28 +00001028 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Owen Anderson4956cde2009-07-07 20:18:58 +00001029 V = Context.getConstantExprExtractElement(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030 break;
1031 }
1032 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1033 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1034 if (Record.size() < 3 || OpTy == 0)
1035 return Error("Invalid CE_INSERTELT record");
1036 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1037 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1038 OpTy->getElementType());
1039 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
Owen Anderson4956cde2009-07-07 20:18:58 +00001040 V = Context.getConstantExprInsertElement(Op0, Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041 break;
1042 }
1043 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1044 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1045 if (Record.size() < 3 || OpTy == 0)
Nate Begemand6d715b2009-02-12 21:28:33 +00001046 return Error("Invalid CE_SHUFFLEVEC record");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1048 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Owen Anderson4956cde2009-07-07 20:18:58 +00001049 const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
1050 OpTy->getNumElements());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson4956cde2009-07-07 20:18:58 +00001052 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 break;
1054 }
Nate Begemand6d715b2009-02-12 21:28:33 +00001055 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1056 const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1057 const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
1058 if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1059 return Error("Invalid CE_SHUFVEC_EX record");
1060 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1061 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Owen Anderson4956cde2009-07-07 20:18:58 +00001062 const Type *ShufTy = Context.getVectorType(Type::Int32Ty,
1063 RTy->getNumElements());
Nate Begemand6d715b2009-02-12 21:28:33 +00001064 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson4956cde2009-07-07 20:18:58 +00001065 V = Context.getConstantExprShuffleVector(Op0, Op1, Op2);
Nate Begemand6d715b2009-02-12 21:28:33 +00001066 break;
1067 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001068 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
1069 if (Record.size() < 4) return Error("Invalid CE_CMP record");
1070 const Type *OpTy = getTypeByID(Record[0]);
1071 if (OpTy == 0) return Error("Invalid CE_CMP record");
1072 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1073 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1074
1075 if (OpTy->isFloatingPoint())
Owen Anderson4956cde2009-07-07 20:18:58 +00001076 V = Context.getConstantExprFCmp(Record[3], Op0, Op1);
Nate Begeman646fa482008-05-12 19:01:56 +00001077 else
Nick Lewycky8f5253b2009-07-08 03:04:38 +00001078 V = Context.getConstantExprICmp(Record[3], Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 break;
1080 }
1081 case bitc::CST_CODE_INLINEASM: {
1082 if (Record.size() < 2) return Error("Invalid INLINEASM record");
1083 std::string AsmStr, ConstrStr;
1084 bool HasSideEffects = Record[0];
1085 unsigned AsmStrSize = Record[1];
1086 if (2+AsmStrSize >= Record.size())
1087 return Error("Invalid INLINEASM record");
1088 unsigned ConstStrSize = Record[2+AsmStrSize];
1089 if (3+AsmStrSize+ConstStrSize > Record.size())
1090 return Error("Invalid INLINEASM record");
1091
1092 for (unsigned i = 0; i != AsmStrSize; ++i)
1093 AsmStr += (char)Record[2+i];
1094 for (unsigned i = 0; i != ConstStrSize; ++i)
1095 ConstrStr += (char)Record[3+AsmStrSize+i];
1096 const PointerType *PTy = cast<PointerType>(CurTy);
1097 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1098 AsmStr, ConstrStr, HasSideEffects);
1099 break;
1100 }
1101 }
1102
1103 ValueList.AssignValue(V, NextCstNo);
1104 ++NextCstNo;
1105 }
Chris Lattner345bbb72008-08-21 02:34:16 +00001106
1107 if (NextCstNo != ValueList.size())
1108 return Error("Invalid constant reference!");
1109
1110 if (Stream.ReadBlockEnd())
1111 return Error("Error at end of constants block");
1112
1113 // Once all the constants have been read, go through and resolve forward
1114 // references.
1115 ValueList.ResolveConstantForwardRefs();
1116 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117}
1118
1119/// RememberAndSkipFunctionBody - When we see the block for a function body,
1120/// remember where it is and then skip it. This lets us lazily deserialize the
1121/// functions.
1122bool BitcodeReader::RememberAndSkipFunctionBody() {
1123 // Get the function we are talking about.
1124 if (FunctionsWithBodies.empty())
1125 return Error("Insufficient function protos");
1126
1127 Function *Fn = FunctionsWithBodies.back();
1128 FunctionsWithBodies.pop_back();
1129
1130 // Save the current stream state.
1131 uint64_t CurBit = Stream.GetCurrentBitNo();
1132 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1133
1134 // Set the functions linkage to GhostLinkage so we know it is lazily
1135 // deserialized.
1136 Fn->setLinkage(GlobalValue::GhostLinkage);
1137
1138 // Skip over the function block for now.
1139 if (Stream.SkipBlock())
1140 return Error("Malformed block record");
1141 return false;
1142}
1143
1144bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1145 // Reject multiple MODULE_BLOCK's in a single bitstream.
1146 if (TheModule)
1147 return Error("Multiple MODULE_BLOCKs in same stream");
1148
1149 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1150 return Error("Malformed block record");
1151
1152 // Otherwise, create the module.
Owen Anderson25209b42009-07-01 16:58:40 +00001153 TheModule = new Module(ModuleID, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154
1155 SmallVector<uint64_t, 64> Record;
1156 std::vector<std::string> SectionTable;
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001157 std::vector<std::string> GCTable;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158
1159 // Read all the records for this module.
1160 while (!Stream.AtEndOfStream()) {
1161 unsigned Code = Stream.ReadCode();
1162 if (Code == bitc::END_BLOCK) {
1163 if (Stream.ReadBlockEnd())
1164 return Error("Error at end of module block");
1165
1166 // Patch the initializers for globals and aliases up.
1167 ResolveGlobalAndAliasInits();
1168 if (!GlobalInits.empty() || !AliasInits.empty())
1169 return Error("Malformed global initializer set");
1170 if (!FunctionsWithBodies.empty())
1171 return Error("Too few function bodies found");
1172
Chandler Carrutha228e392007-08-04 01:51:18 +00001173 // Look for intrinsic functions which need to be upgraded at some point
1174 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1175 FI != FE; ++FI) {
Evan Cheng7f05d852007-12-17 22:33:23 +00001176 Function* NewFn;
1177 if (UpgradeIntrinsicFunction(FI, NewFn))
Chandler Carrutha228e392007-08-04 01:51:18 +00001178 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1179 }
1180
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 // Force deallocation of memory for these vectors to favor the client that
1182 // want lazy deserialization.
1183 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1184 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1185 std::vector<Function*>().swap(FunctionsWithBodies);
1186 return false;
1187 }
1188
1189 if (Code == bitc::ENTER_SUBBLOCK) {
1190 switch (Stream.ReadSubBlockID()) {
1191 default: // Skip unknown content.
1192 if (Stream.SkipBlock())
1193 return Error("Malformed block record");
1194 break;
1195 case bitc::BLOCKINFO_BLOCK_ID:
1196 if (Stream.ReadBlockInfoBlock())
1197 return Error("Malformed BlockInfoBlock");
1198 break;
1199 case bitc::PARAMATTR_BLOCK_ID:
Devang Pateld222f862008-09-25 21:00:45 +00001200 if (ParseAttributeBlock())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001201 return true;
1202 break;
1203 case bitc::TYPE_BLOCK_ID:
1204 if (ParseTypeTable())
1205 return true;
1206 break;
1207 case bitc::TYPE_SYMTAB_BLOCK_ID:
1208 if (ParseTypeSymbolTable())
1209 return true;
1210 break;
1211 case bitc::VALUE_SYMTAB_BLOCK_ID:
1212 if (ParseValueSymbolTable())
1213 return true;
1214 break;
1215 case bitc::CONSTANTS_BLOCK_ID:
1216 if (ParseConstants() || ResolveGlobalAndAliasInits())
1217 return true;
1218 break;
Devang Patel0c0a6ca2009-07-22 17:43:22 +00001219 case bitc::METADATA_BLOCK_ID:
1220 if (ParseMetadata())
1221 return true;
1222 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 case bitc::FUNCTION_BLOCK_ID:
1224 // If this is the first function body we've seen, reverse the
1225 // FunctionsWithBodies list.
1226 if (!HasReversedFunctionsWithBodies) {
1227 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1228 HasReversedFunctionsWithBodies = true;
1229 }
1230
1231 if (RememberAndSkipFunctionBody())
1232 return true;
1233 break;
1234 }
1235 continue;
1236 }
1237
1238 if (Code == bitc::DEFINE_ABBREV) {
1239 Stream.ReadAbbrevRecord();
1240 continue;
1241 }
1242
1243 // Read a record.
1244 switch (Stream.ReadRecord(Code, Record)) {
1245 default: break; // Default behavior, ignore unknown content.
1246 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
1247 if (Record.size() < 1)
1248 return Error("Malformed MODULE_CODE_VERSION");
1249 // Only version #0 is supported so far.
1250 if (Record[0] != 0)
1251 return Error("Unknown bitstream version!");
1252 break;
1253 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
1254 std::string S;
1255 if (ConvertToString(Record, 0, S))
1256 return Error("Invalid MODULE_CODE_TRIPLE record");
1257 TheModule->setTargetTriple(S);
1258 break;
1259 }
1260 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
1261 std::string S;
1262 if (ConvertToString(Record, 0, S))
1263 return Error("Invalid MODULE_CODE_DATALAYOUT record");
1264 TheModule->setDataLayout(S);
1265 break;
1266 }
1267 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
1268 std::string S;
1269 if (ConvertToString(Record, 0, S))
1270 return Error("Invalid MODULE_CODE_ASM record");
1271 TheModule->setModuleInlineAsm(S);
1272 break;
1273 }
1274 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
1275 std::string S;
1276 if (ConvertToString(Record, 0, S))
1277 return Error("Invalid MODULE_CODE_DEPLIB record");
1278 TheModule->addLibrary(S);
1279 break;
1280 }
1281 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
1282 std::string S;
1283 if (ConvertToString(Record, 0, S))
1284 return Error("Invalid MODULE_CODE_SECTIONNAME record");
1285 SectionTable.push_back(S);
1286 break;
1287 }
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001288 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001289 std::string S;
1290 if (ConvertToString(Record, 0, S))
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001291 return Error("Invalid MODULE_CODE_GCNAME record");
1292 GCTable.push_back(S);
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001293 break;
1294 }
Christopher Lamb44d62f62007-12-11 08:59:05 +00001295 // GLOBALVAR: [pointer type, isconst, initid,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 // linkage, alignment, section, visibility, threadlocal]
1297 case bitc::MODULE_CODE_GLOBALVAR: {
1298 if (Record.size() < 6)
1299 return Error("Invalid MODULE_CODE_GLOBALVAR record");
1300 const Type *Ty = getTypeByID(Record[0]);
1301 if (!isa<PointerType>(Ty))
1302 return Error("Global not a pointer type!");
Christopher Lamb44d62f62007-12-11 08:59:05 +00001303 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 Ty = cast<PointerType>(Ty)->getElementType();
1305
1306 bool isConstant = Record[1];
1307 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1308 unsigned Alignment = (1 << Record[4]) >> 1;
1309 std::string Section;
1310 if (Record[5]) {
1311 if (Record[5]-1 >= SectionTable.size())
1312 return Error("Invalid section ID");
1313 Section = SectionTable[Record[5]-1];
1314 }
1315 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1316 if (Record.size() > 6)
1317 Visibility = GetDecodedVisibility(Record[6]);
1318 bool isThreadLocal = false;
1319 if (Record.size() > 7)
1320 isThreadLocal = Record[7];
1321
1322 GlobalVariable *NewGV =
Owen Andersone17fc1d2009-07-08 19:03:57 +00001323 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
Christopher Lamb44d62f62007-12-11 08:59:05 +00001324 isThreadLocal, AddressSpace);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 NewGV->setAlignment(Alignment);
1326 if (!Section.empty())
1327 NewGV->setSection(Section);
1328 NewGV->setVisibility(Visibility);
1329 NewGV->setThreadLocal(isThreadLocal);
1330
1331 ValueList.push_back(NewGV);
1332
1333 // Remember which value to use for the global initializer.
1334 if (unsigned InitID = Record[2])
1335 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1336 break;
1337 }
1338 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001339 // alignment, section, visibility, gc]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 case bitc::MODULE_CODE_FUNCTION: {
1341 if (Record.size() < 8)
1342 return Error("Invalid MODULE_CODE_FUNCTION record");
1343 const Type *Ty = getTypeByID(Record[0]);
1344 if (!isa<PointerType>(Ty))
1345 return Error("Function not a pointer type!");
1346 const FunctionType *FTy =
1347 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1348 if (!FTy)
1349 return Error("Function not a pointer to function type!");
1350
Gabor Greifd6da1d02008-04-06 20:25:17 +00001351 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1352 "", TheModule);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353
1354 Func->setCallingConv(Record[1]);
1355 bool isProto = Record[2];
1356 Func->setLinkage(GetDecodedLinkage(Record[3]));
Devang Pateld222f862008-09-25 21:00:45 +00001357 Func->setAttributes(getAttributes(Record[4]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001358
1359 Func->setAlignment((1 << Record[5]) >> 1);
1360 if (Record[6]) {
1361 if (Record[6]-1 >= SectionTable.size())
1362 return Error("Invalid section ID");
1363 Func->setSection(SectionTable[Record[6]-1]);
1364 }
1365 Func->setVisibility(GetDecodedVisibility(Record[7]));
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001366 if (Record.size() > 8 && Record[8]) {
Gordon Henriksen1aed5992008-08-17 18:44:35 +00001367 if (Record[8]-1 > GCTable.size())
1368 return Error("Invalid GC ID");
1369 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen13fe5e32007-12-10 03:18:06 +00001370 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001371 ValueList.push_back(Func);
1372
1373 // If this is a function with a body, remember the prototype we are
1374 // creating now, so that we can match up the body with them later.
1375 if (!isProto)
1376 FunctionsWithBodies.push_back(Func);
1377 break;
1378 }
Anton Korobeynikov5789f8d2008-03-12 00:49:19 +00001379 // ALIAS: [alias type, aliasee val#, linkage]
Anton Korobeynikov902a0112008-03-11 21:40:17 +00001380 // ALIAS: [alias type, aliasee val#, linkage, visibility]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 case bitc::MODULE_CODE_ALIAS: {
1382 if (Record.size() < 3)
1383 return Error("Invalid MODULE_ALIAS record");
1384 const Type *Ty = getTypeByID(Record[0]);
1385 if (!isa<PointerType>(Ty))
1386 return Error("Function not a pointer type!");
1387
1388 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1389 "", 0, TheModule);
Anton Korobeynikov5789f8d2008-03-12 00:49:19 +00001390 // Old bitcode files didn't have visibility field.
1391 if (Record.size() > 3)
1392 NewGA->setVisibility(GetDecodedVisibility(Record[3]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 ValueList.push_back(NewGA);
1394 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1395 break;
1396 }
1397 /// MODULE_CODE_PURGEVALS: [numvals]
1398 case bitc::MODULE_CODE_PURGEVALS:
1399 // Trim down the value list to the specified size.
1400 if (Record.size() < 1 || Record[0] > ValueList.size())
1401 return Error("Invalid MODULE_PURGEVALS record");
1402 ValueList.shrinkTo(Record[0]);
1403 break;
1404 }
1405 Record.clear();
1406 }
1407
1408 return Error("Premature end of bitstream");
1409}
1410
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411bool BitcodeReader::ParseBitcode() {
1412 TheModule = 0;
1413
1414 if (Buffer->getBufferSize() & 3)
1415 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1416
1417 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner65b13ff2008-07-09 05:14:23 +00001418 unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1419
1420 // If we have a wrapper header, parse it and ignore the non-bc file contents.
1421 // The magic number is 0x0B17C0DE stored in little endian.
Chris Lattnerabd0e442009-04-06 20:54:32 +00001422 if (isBitcodeWrapper(BufPtr, BufEnd))
1423 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
Chris Lattner65b13ff2008-07-09 05:14:23 +00001424 return Error("Invalid bitcode wrapper header");
1425
Chris Lattner25a6abf2009-04-26 20:59:02 +00001426 StreamFile.init(BufPtr, BufEnd);
1427 Stream.init(StreamFile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428
1429 // Sniff for the signature.
1430 if (Stream.Read(8) != 'B' ||
1431 Stream.Read(8) != 'C' ||
1432 Stream.Read(4) != 0x0 ||
1433 Stream.Read(4) != 0xC ||
1434 Stream.Read(4) != 0xE ||
1435 Stream.Read(4) != 0xD)
1436 return Error("Invalid bitcode signature");
1437
1438 // We expect a number of well-defined blocks, though we don't necessarily
1439 // need to understand them all.
1440 while (!Stream.AtEndOfStream()) {
1441 unsigned Code = Stream.ReadCode();
1442
1443 if (Code != bitc::ENTER_SUBBLOCK)
1444 return Error("Invalid record at top-level");
1445
1446 unsigned BlockID = Stream.ReadSubBlockID();
1447
1448 // We only know the MODULE subblock ID.
1449 switch (BlockID) {
1450 case bitc::BLOCKINFO_BLOCK_ID:
1451 if (Stream.ReadBlockInfoBlock())
1452 return Error("Malformed BlockInfoBlock");
1453 break;
1454 case bitc::MODULE_BLOCK_ID:
1455 if (ParseModule(Buffer->getBufferIdentifier()))
1456 return true;
1457 break;
1458 default:
1459 if (Stream.SkipBlock())
1460 return Error("Malformed block record");
1461 break;
1462 }
1463 }
1464
1465 return false;
1466}
1467
1468
1469/// ParseFunctionBody - Lazily parse the specified function body block.
1470bool BitcodeReader::ParseFunctionBody(Function *F) {
1471 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1472 return Error("Malformed block record");
1473
1474 unsigned ModuleValueListSize = ValueList.size();
1475
1476 // Add all the function arguments to the value table.
1477 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1478 ValueList.push_back(I);
1479
1480 unsigned NextValueNo = ValueList.size();
1481 BasicBlock *CurBB = 0;
1482 unsigned CurBBNo = 0;
1483
1484 // Read all the records.
1485 SmallVector<uint64_t, 64> Record;
1486 while (1) {
1487 unsigned Code = Stream.ReadCode();
1488 if (Code == bitc::END_BLOCK) {
1489 if (Stream.ReadBlockEnd())
1490 return Error("Error at end of function block");
1491 break;
1492 }
1493
1494 if (Code == bitc::ENTER_SUBBLOCK) {
1495 switch (Stream.ReadSubBlockID()) {
1496 default: // Skip unknown content.
1497 if (Stream.SkipBlock())
1498 return Error("Malformed block record");
1499 break;
1500 case bitc::CONSTANTS_BLOCK_ID:
1501 if (ParseConstants()) return true;
1502 NextValueNo = ValueList.size();
1503 break;
1504 case bitc::VALUE_SYMTAB_BLOCK_ID:
1505 if (ParseValueSymbolTable()) return true;
1506 break;
1507 }
1508 continue;
1509 }
1510
1511 if (Code == bitc::DEFINE_ABBREV) {
1512 Stream.ReadAbbrevRecord();
1513 continue;
1514 }
1515
1516 // Read a record.
1517 Record.clear();
1518 Instruction *I = 0;
Dan Gohman799a8c82009-07-20 21:19:07 +00001519 unsigned BitCode = Stream.ReadRecord(Code, Record);
1520 switch (BitCode) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 default: // Default behavior: reject
1522 return Error("Unknown instruction");
1523 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
1524 if (Record.size() < 1 || Record[0] == 0)
1525 return Error("Invalid DECLAREBLOCKS record");
1526 // Create all the basic blocks for the function.
1527 FunctionBBs.resize(Record[0]);
1528 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
Gabor Greifd6da1d02008-04-06 20:25:17 +00001529 FunctionBBs[i] = BasicBlock::Create("", F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 CurBB = FunctionBBs[0];
1531 continue;
1532
1533 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1534 unsigned OpNum = 0;
1535 Value *LHS, *RHS;
1536 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1537 getValue(Record, OpNum, LHS->getType(), RHS) ||
Dan Gohman799a8c82009-07-20 21:19:07 +00001538 OpNum+1 > Record.size())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001539 return Error("Invalid BINOP record");
1540
Dan Gohman799a8c82009-07-20 21:19:07 +00001541 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 if (Opc == -1) return Error("Invalid BINOP record");
Gabor Greifa645dd32008-05-16 19:29:10 +00001543 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohman799a8c82009-07-20 21:19:07 +00001544 if (OpNum < Record.size())
1545 SetOptimizationFlags(I, Record[3]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 break;
1547 }
1548 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1549 unsigned OpNum = 0;
1550 Value *Op;
1551 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1552 OpNum+2 != Record.size())
1553 return Error("Invalid CAST record");
1554
1555 const Type *ResTy = getTypeByID(Record[OpNum]);
1556 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1557 if (Opc == -1 || ResTy == 0)
1558 return Error("Invalid CAST record");
Gabor Greifa645dd32008-05-16 19:29:10 +00001559 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 break;
1561 }
Dan Gohman106b2ae2009-07-27 21:53:46 +00001562 case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1564 unsigned OpNum = 0;
1565 Value *BasePtr;
1566 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1567 return Error("Invalid GEP record");
1568
1569 SmallVector<Value*, 16> GEPIdx;
1570 while (OpNum != Record.size()) {
1571 Value *Op;
1572 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1573 return Error("Invalid GEP record");
1574 GEPIdx.push_back(Op);
1575 }
1576
Gabor Greifd6da1d02008-04-06 20:25:17 +00001577 I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
Dan Gohman106b2ae2009-07-27 21:53:46 +00001578 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1579 cast<GEPOperator>(I)->setIsInBounds(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001580 break;
1581 }
1582
Dan Gohmane5febe42008-05-31 00:58:22 +00001583 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1584 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001585 unsigned OpNum = 0;
1586 Value *Agg;
1587 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1588 return Error("Invalid EXTRACTVAL record");
1589
Dan Gohmane5febe42008-05-31 00:58:22 +00001590 SmallVector<unsigned, 4> EXTRACTVALIdx;
1591 for (unsigned RecSize = Record.size();
1592 OpNum != RecSize; ++OpNum) {
1593 uint64_t Index = Record[OpNum];
1594 if ((unsigned)Index != Index)
1595 return Error("Invalid EXTRACTVAL index");
1596 EXTRACTVALIdx.push_back((unsigned)Index);
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001597 }
1598
1599 I = ExtractValueInst::Create(Agg,
1600 EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1601 break;
1602 }
1603
Dan Gohmane5febe42008-05-31 00:58:22 +00001604 case bitc::FUNC_CODE_INST_INSERTVAL: {
1605 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001606 unsigned OpNum = 0;
1607 Value *Agg;
1608 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1609 return Error("Invalid INSERTVAL record");
1610 Value *Val;
1611 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1612 return Error("Invalid INSERTVAL record");
1613
Dan Gohmane5febe42008-05-31 00:58:22 +00001614 SmallVector<unsigned, 4> INSERTVALIdx;
1615 for (unsigned RecSize = Record.size();
1616 OpNum != RecSize; ++OpNum) {
1617 uint64_t Index = Record[OpNum];
1618 if ((unsigned)Index != Index)
1619 return Error("Invalid INSERTVAL index");
1620 INSERTVALIdx.push_back((unsigned)Index);
Dan Gohmane6b1ee62008-05-23 01:55:30 +00001621 }
1622
1623 I = InsertValueInst::Create(Agg, Val,
1624 INSERTVALIdx.begin(), INSERTVALIdx.end());
1625 break;
1626 }
1627
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001628 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohman6fa5bce2008-09-16 01:01:33 +00001629 // obsolete form of select
1630 // handles select i1 ... in old bitcode
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631 unsigned OpNum = 0;
1632 Value *TrueVal, *FalseVal, *Cond;
1633 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1634 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
Dan Gohman607ddb92008-09-09 02:08:49 +00001635 getValue(Record, OpNum, Type::Int1Ty, Cond))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 return Error("Invalid SELECT record");
Dan Gohman6fa5bce2008-09-16 01:01:33 +00001637
1638 I = SelectInst::Create(Cond, TrueVal, FalseVal);
1639 break;
1640 }
1641
1642 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1643 // new form of select
1644 // handles select i1 or select [N x i1]
1645 unsigned OpNum = 0;
1646 Value *TrueVal, *FalseVal, *Cond;
1647 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1648 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1649 getValueTypePair(Record, OpNum, NextValueNo, Cond))
1650 return Error("Invalid SELECT record");
Dan Gohmanb60ca3c2008-09-09 01:02:47 +00001651
1652 // select condition can be either i1 or [N x i1]
Dan Gohman6fa5bce2008-09-16 01:01:33 +00001653 if (const VectorType* vector_type =
1654 dyn_cast<const VectorType>(Cond->getType())) {
Dan Gohmanb60ca3c2008-09-09 01:02:47 +00001655 // expect <n x i1>
1656 if (vector_type->getElementType() != Type::Int1Ty)
1657 return Error("Invalid SELECT condition type");
1658 } else {
1659 // expect i1
1660 if (Cond->getType() != Type::Int1Ty)
1661 return Error("Invalid SELECT condition type");
1662 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663
Gabor Greifd6da1d02008-04-06 20:25:17 +00001664 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001665 break;
1666 }
1667
1668 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1669 unsigned OpNum = 0;
1670 Value *Vec, *Idx;
1671 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1672 getValue(Record, OpNum, Type::Int32Ty, Idx))
1673 return Error("Invalid EXTRACTELT record");
Eric Christopher1ba36872009-07-25 02:28:41 +00001674 I = ExtractElementInst::Create(Vec, Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001675 break;
1676 }
1677
1678 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1679 unsigned OpNum = 0;
1680 Value *Vec, *Elt, *Idx;
1681 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1682 getValue(Record, OpNum,
1683 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1684 getValue(Record, OpNum, Type::Int32Ty, Idx))
1685 return Error("Invalid INSERTELT record");
Gabor Greifd6da1d02008-04-06 20:25:17 +00001686 I = InsertElementInst::Create(Vec, Elt, Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687 break;
1688 }
1689
1690 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1691 unsigned OpNum = 0;
1692 Value *Vec1, *Vec2, *Mask;
1693 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1694 getValue(Record, OpNum, Vec1->getType(), Vec2))
1695 return Error("Invalid SHUFFLEVEC record");
1696
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001697 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698 return Error("Invalid SHUFFLEVEC record");
1699 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1700 break;
1701 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001702
Nick Lewycky8f5253b2009-07-08 03:04:38 +00001703 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
1704 // Old form of ICmp/FCmp returning bool
1705 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1706 // both legal on vectors but had different behaviour.
1707 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1708 // FCmp/ICmp returning bool or vector of bool
1709
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001710 unsigned OpNum = 0;
1711 Value *LHS, *RHS;
1712 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1713 getValue(Record, OpNum, LHS->getType(), RHS) ||
1714 OpNum+1 != Record.size())
1715 return Error("Invalid CMP record");
1716
Dan Gohmanb60ca3c2008-09-09 01:02:47 +00001717 if (LHS->getType()->isFPOrFPVector())
Owen Anderson6601fcd2009-07-09 23:48:35 +00001718 I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Nick Lewycky8f5253b2009-07-08 03:04:38 +00001719 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00001720 I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Dan Gohmanb60ca3c2008-09-09 01:02:47 +00001721 break;
1722 }
Nick Lewycky8f5253b2009-07-08 03:04:38 +00001723
Devang Patel774ee9e2008-02-22 02:49:49 +00001724 case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1725 if (Record.size() != 2)
1726 return Error("Invalid GETRESULT record");
1727 unsigned OpNum = 0;
1728 Value *Op;
1729 getValueTypePair(Record, OpNum, NextValueNo, Op);
1730 unsigned Index = Record[1];
Dan Gohman29474e92008-07-23 00:34:11 +00001731 I = ExtractValueInst::Create(Op, Index);
Devang Patel774ee9e2008-02-22 02:49:49 +00001732 break;
1733 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734
1735 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelb7fbc8b2008-02-26 01:29:32 +00001736 {
1737 unsigned Size = Record.size();
1738 if (Size == 0) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00001739 I = ReturnInst::Create();
Devang Patelb7fbc8b2008-02-26 01:29:32 +00001740 break;
Dan Gohman29474e92008-07-23 00:34:11 +00001741 }
Devang Patelb7fbc8b2008-02-26 01:29:32 +00001742
Dan Gohman29474e92008-07-23 00:34:11 +00001743 unsigned OpNum = 0;
1744 SmallVector<Value *,4> Vs;
1745 do {
1746 Value *Op = NULL;
1747 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1748 return Error("Invalid RET record");
1749 Vs.push_back(Op);
1750 } while(OpNum != Record.size());
1751
1752 const Type *ReturnType = F->getReturnType();
1753 if (Vs.size() > 1 ||
1754 (isa<StructType>(ReturnType) &&
1755 (Vs.empty() || Vs[0]->getType() != ReturnType))) {
Owen Anderson4956cde2009-07-07 20:18:58 +00001756 Value *RV = Context.getUndef(ReturnType);
Dan Gohman29474e92008-07-23 00:34:11 +00001757 for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1758 I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1759 CurBB->getInstList().push_back(I);
1760 ValueList.AssignValue(I, NextValueNo++);
1761 RV = I;
1762 }
1763 I = ReturnInst::Create(RV);
Devang Patelb7fbc8b2008-02-26 01:29:32 +00001764 break;
1765 }
Dan Gohman29474e92008-07-23 00:34:11 +00001766
1767 I = ReturnInst::Create(Vs[0]);
1768 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769 }
1770 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1771 if (Record.size() != 1 && Record.size() != 3)
1772 return Error("Invalid BR record");
1773 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1774 if (TrueDest == 0)
1775 return Error("Invalid BR record");
1776
1777 if (Record.size() == 1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00001778 I = BranchInst::Create(TrueDest);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779 else {
1780 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1781 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1782 if (FalseDest == 0 || Cond == 0)
1783 return Error("Invalid BR record");
Gabor Greifd6da1d02008-04-06 20:25:17 +00001784 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785 }
1786 break;
1787 }
1788 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1789 if (Record.size() < 3 || (Record.size() & 1) == 0)
1790 return Error("Invalid SWITCH record");
1791 const Type *OpTy = getTypeByID(Record[0]);
1792 Value *Cond = getFnValueByID(Record[1], OpTy);
1793 BasicBlock *Default = getBasicBlock(Record[2]);
1794 if (OpTy == 0 || Cond == 0 || Default == 0)
1795 return Error("Invalid SWITCH record");
1796 unsigned NumCases = (Record.size()-3)/2;
Gabor Greifd6da1d02008-04-06 20:25:17 +00001797 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1799 ConstantInt *CaseVal =
1800 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1801 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1802 if (CaseVal == 0 || DestBB == 0) {
1803 delete SI;
1804 return Error("Invalid SWITCH record!");
1805 }
1806 SI->addCase(CaseVal, DestBB);
1807 }
1808 I = SI;
1809 break;
1810 }
1811
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001812 case bitc::FUNC_CODE_INST_INVOKE: {
1813 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001814 if (Record.size() < 4) return Error("Invalid INVOKE record");
Devang Pateld222f862008-09-25 21:00:45 +00001815 AttrListPtr PAL = getAttributes(Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001816 unsigned CCInfo = Record[1];
1817 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1818 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1819
1820 unsigned OpNum = 4;
1821 Value *Callee;
1822 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1823 return Error("Invalid INVOKE record");
1824
1825 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1826 const FunctionType *FTy = !CalleeTy ? 0 :
1827 dyn_cast<FunctionType>(CalleeTy->getElementType());
1828
1829 // Check that the right number of fixed parameters are here.
1830 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1831 Record.size() < OpNum+FTy->getNumParams())
1832 return Error("Invalid INVOKE record");
1833
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 SmallVector<Value*, 16> Ops;
1835 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1836 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1837 if (Ops.back() == 0) return Error("Invalid INVOKE record");
1838 }
1839
1840 if (!FTy->isVarArg()) {
1841 if (Record.size() != OpNum)
1842 return Error("Invalid INVOKE record");
1843 } else {
1844 // Read type/value pairs for varargs params.
1845 while (OpNum != Record.size()) {
1846 Value *Op;
1847 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1848 return Error("Invalid INVOKE record");
1849 Ops.push_back(Op);
1850 }
1851 }
1852
Gabor Greifb91ea9d2008-05-15 10:04:30 +00001853 I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1854 Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001855 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Devang Pateld222f862008-09-25 21:00:45 +00001856 cast<InvokeInst>(I)->setAttributes(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857 break;
1858 }
1859 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1860 I = new UnwindInst();
1861 break;
1862 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1863 I = new UnreachableInst();
1864 break;
1865 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1866 if (Record.size() < 1 || ((Record.size()-1)&1))
1867 return Error("Invalid PHI record");
1868 const Type *Ty = getTypeByID(Record[0]);
1869 if (!Ty) return Error("Invalid PHI record");
1870
Gabor Greifd6da1d02008-04-06 20:25:17 +00001871 PHINode *PN = PHINode::Create(Ty);
Chris Lattner20e7f1a2008-04-13 00:14:42 +00001872 PN->reserveOperandSpace((Record.size()-1)/2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001873
1874 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1875 Value *V = getFnValueByID(Record[1+i], Ty);
1876 BasicBlock *BB = getBasicBlock(Record[2+i]);
1877 if (!V || !BB) return Error("Invalid PHI record");
1878 PN->addIncoming(V, BB);
1879 }
1880 I = PN;
1881 break;
1882 }
1883
1884 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1885 if (Record.size() < 3)
1886 return Error("Invalid MALLOC record");
1887 const PointerType *Ty =
1888 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1889 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1890 unsigned Align = Record[2];
1891 if (!Ty || !Size) return Error("Invalid MALLOC record");
Owen Anderson140166d2009-07-15 23:53:25 +00001892 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 break;
1894 }
1895 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1896 unsigned OpNum = 0;
1897 Value *Op;
1898 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1899 OpNum != Record.size())
1900 return Error("Invalid FREE record");
1901 I = new FreeInst(Op);
1902 break;
1903 }
1904 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1905 if (Record.size() < 3)
1906 return Error("Invalid ALLOCA record");
1907 const PointerType *Ty =
1908 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1909 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1910 unsigned Align = Record[2];
1911 if (!Ty || !Size) return Error("Invalid ALLOCA record");
Owen Anderson140166d2009-07-15 23:53:25 +00001912 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001913 break;
1914 }
1915 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1916 unsigned OpNum = 0;
1917 Value *Op;
1918 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1919 OpNum+2 != Record.size())
1920 return Error("Invalid LOAD record");
1921
1922 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1923 break;
1924 }
Christopher Lamb44d62f62007-12-11 08:59:05 +00001925 case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1926 unsigned OpNum = 0;
1927 Value *Val, *Ptr;
1928 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1929 getValue(Record, OpNum,
1930 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1931 OpNum+2 != Record.size())
1932 return Error("Invalid STORE record");
1933
1934 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1935 break;
1936 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001937 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
Christopher Lamb44d62f62007-12-11 08:59:05 +00001938 // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001939 unsigned OpNum = 0;
1940 Value *Val, *Ptr;
1941 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
Owen Anderson4956cde2009-07-07 20:18:58 +00001942 getValue(Record, OpNum,
1943 Context.getPointerTypeUnqual(Val->getType()), Ptr)||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001944 OpNum+2 != Record.size())
1945 return Error("Invalid STORE record");
1946
1947 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1948 break;
1949 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +00001950 case bitc::FUNC_CODE_INST_CALL: {
1951 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1952 if (Record.size() < 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001953 return Error("Invalid CALL record");
1954
Devang Pateld222f862008-09-25 21:00:45 +00001955 AttrListPtr PAL = getAttributes(Record[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001956 unsigned CCInfo = Record[1];
1957
1958 unsigned OpNum = 2;
1959 Value *Callee;
1960 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1961 return Error("Invalid CALL record");
1962
1963 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1964 const FunctionType *FTy = 0;
1965 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1966 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1967 return Error("Invalid CALL record");
1968
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001969 SmallVector<Value*, 16> Args;
1970 // Read the fixed params.
1971 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Dale Johannesencfb19e62007-11-05 21:20:28 +00001972 if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1973 Args.push_back(getBasicBlock(Record[OpNum]));
1974 else
1975 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976 if (Args.back() == 0) return Error("Invalid CALL record");
1977 }
1978
1979 // Read type/value pairs for varargs params.
1980 if (!FTy->isVarArg()) {
1981 if (OpNum != Record.size())
1982 return Error("Invalid CALL record");
1983 } else {
1984 while (OpNum != Record.size()) {
1985 Value *Op;
1986 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1987 return Error("Invalid CALL record");
1988 Args.push_back(Op);
1989 }
1990 }
1991
Gabor Greifd6da1d02008-04-06 20:25:17 +00001992 I = CallInst::Create(Callee, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001993 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1994 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Devang Pateld222f862008-09-25 21:00:45 +00001995 cast<CallInst>(I)->setAttributes(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996 break;
1997 }
1998 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1999 if (Record.size() < 3)
2000 return Error("Invalid VAARG record");
2001 const Type *OpTy = getTypeByID(Record[0]);
2002 Value *Op = getFnValueByID(Record[1], OpTy);
2003 const Type *ResTy = getTypeByID(Record[2]);
2004 if (!OpTy || !Op || !ResTy)
2005 return Error("Invalid VAARG record");
2006 I = new VAArgInst(Op, ResTy);
2007 break;
2008 }
2009 }
2010
2011 // Add instruction to end of current BB. If there is no current BB, reject
2012 // this file.
2013 if (CurBB == 0) {
2014 delete I;
2015 return Error("Invalid instruction with no BB");
2016 }
2017 CurBB->getInstList().push_back(I);
2018
2019 // If this was a terminator instruction, move to the next block.
2020 if (isa<TerminatorInst>(I)) {
2021 ++CurBBNo;
2022 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2023 }
2024
2025 // Non-void values get registered in the value table for future use.
2026 if (I && I->getType() != Type::VoidTy)
2027 ValueList.AssignValue(I, NextValueNo++);
2028 }
2029
2030 // Check the function list for unresolved values.
2031 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2032 if (A->getParent() == 0) {
2033 // We found at least one unresolved value. Nuke them all to avoid leaks.
2034 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2035 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
Owen Anderson4956cde2009-07-07 20:18:58 +00002036 A->replaceAllUsesWith(Context.getUndef(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002037 delete A;
2038 }
2039 }
2040 return Error("Never resolved value found in function!");
2041 }
2042 }
2043
2044 // Trim the value list down to the size it was before we parsed this function.
2045 ValueList.shrinkTo(ModuleValueListSize);
2046 std::vector<BasicBlock*>().swap(FunctionBBs);
2047
2048 return false;
2049}
2050
2051//===----------------------------------------------------------------------===//
2052// ModuleProvider implementation
2053//===----------------------------------------------------------------------===//
2054
2055
2056bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2057 // If it already is material, ignore the request.
2058 if (!F->hasNotBeenReadFromBitcode()) return false;
2059
2060 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2061 DeferredFunctionInfo.find(F);
2062 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2063
2064 // Move the bit stream to the saved position of the deferred function body and
2065 // restore the real linkage type for the function.
2066 Stream.JumpToBit(DFII->second.first);
2067 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2068
2069 if (ParseFunctionBody(F)) {
2070 if (ErrInfo) *ErrInfo = ErrorString;
2071 return true;
2072 }
Chandler Carrutha228e392007-08-04 01:51:18 +00002073
2074 // Upgrade any old intrinsic calls in the function.
2075 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2076 E = UpgradedIntrinsics.end(); I != E; ++I) {
2077 if (I->first != I->second) {
2078 for (Value::use_iterator UI = I->first->use_begin(),
2079 UE = I->first->use_end(); UI != UE; ) {
2080 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2081 UpgradeIntrinsicCall(CI, I->second);
2082 }
2083 }
2084 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085
2086 return false;
2087}
2088
2089void BitcodeReader::dematerializeFunction(Function *F) {
2090 // If this function isn't materialized, or if it is a proto, this is a noop.
2091 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2092 return;
2093
2094 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2095
2096 // Just forget the function body, we can remat it later.
2097 F->deleteBody();
2098 F->setLinkage(GlobalValue::GhostLinkage);
2099}
2100
2101
2102Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
Chris Lattner6b69fff2009-06-16 05:15:21 +00002103 // Iterate over the module, deserializing any functions that are still on
2104 // disk.
2105 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2106 F != E; ++F)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107 if (F->hasNotBeenReadFromBitcode() &&
2108 materializeFunction(F, ErrInfo))
2109 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00002110
2111 // Upgrade any intrinsic calls that slipped through (should not happen!) and
2112 // delete the old functions to clean up. We can't do this unless the entire
2113 // module is materialized because there could always be another function body
2114 // with calls to the old function.
2115 for (std::vector<std::pair<Function*, Function*> >::iterator I =
2116 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2117 if (I->first != I->second) {
2118 for (Value::use_iterator UI = I->first->use_begin(),
2119 UE = I->first->use_end(); UI != UE; ) {
2120 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2121 UpgradeIntrinsicCall(CI, I->second);
2122 }
Chris Lattnerda486ce2009-04-01 01:43:03 +00002123 if (!I->first->use_empty())
2124 I->first->replaceAllUsesWith(I->second);
Chandler Carrutha228e392007-08-04 01:51:18 +00002125 I->first->eraseFromParent();
2126 }
2127 }
2128 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2129
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130 return TheModule;
2131}
2132
2133
2134/// This method is provided by the parent ModuleProvde class and overriden
2135/// here. It simply releases the module from its provided and frees up our
2136/// state.
2137/// @brief Release our hold on the generated module
2138Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2139 // Since we're losing control of this Module, we must hand it back complete
2140 Module *M = ModuleProvider::releaseModule(ErrInfo);
2141 FreeState();
2142 return M;
2143}
2144
2145
2146//===----------------------------------------------------------------------===//
2147// External interface
2148//===----------------------------------------------------------------------===//
2149
2150/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2151///
2152ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
Owen Anderson92adb182009-07-01 23:13:44 +00002153 LLVMContext& Context,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154 std::string *ErrMsg) {
Owen Anderson25209b42009-07-01 16:58:40 +00002155 BitcodeReader *R = new BitcodeReader(Buffer, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002156 if (R->ParseBitcode()) {
2157 if (ErrMsg)
2158 *ErrMsg = R->getErrorString();
2159
2160 // Don't let the BitcodeReader dtor delete 'Buffer'.
2161 R->releaseMemoryBuffer();
2162 delete R;
2163 return 0;
2164 }
2165 return R;
2166}
2167
2168/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2169/// If an error occurs, return null and fill in *ErrMsg if non-null.
Owen Anderson92adb182009-07-01 23:13:44 +00002170Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
Owen Anderson25209b42009-07-01 16:58:40 +00002171 std::string *ErrMsg){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172 BitcodeReader *R;
Owen Anderson25209b42009-07-01 16:58:40 +00002173 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2174 ErrMsg));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175 if (!R) return 0;
2176
2177 // Read in the entire module.
2178 Module *M = R->materializeModule(ErrMsg);
2179
2180 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2181 // there was an error.
2182 R->releaseMemoryBuffer();
2183
2184 // If there was no error, tell ModuleProvider not to delete it when its dtor
2185 // is run.
2186 if (M)
2187 M = R->releaseModule(ErrMsg);
Chris Lattner6b69fff2009-06-16 05:15:21 +00002188
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189 delete R;
2190 return M;
2191}