blob: 07a4279e13cab8b85af48fa88ff736ada471e425 [file] [log] [blame]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnerc453f762007-04-29 07:54:31 +000014#include "llvm/Bitcode/ReaderWriter.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000015#include "BitcodeReader.h"
Chris Lattnere16504e2007-04-24 03:30:34 +000016#include "llvm/Constants.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000017#include "llvm/DerivedTypes.h"
Chris Lattner2bce93a2007-05-06 01:58:20 +000018#include "llvm/InlineAsm.h"
Chris Lattnera7c49aa2007-05-01 07:01:57 +000019#include "llvm/Instructions.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000020#include "llvm/Module.h"
Chris Lattner48c85b82007-05-04 03:30:17 +000021#include "llvm/ParameterAttributes.h"
Chandler Carruth69940402007-08-04 01:51:18 +000022#include "llvm/AutoUpgrade.h"
Chris Lattner0b2482a2007-04-23 21:26:05 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner0eef0802007-04-24 04:04:35 +000024#include "llvm/Support/MathExtras.h"
Chris Lattnerc453f762007-04-29 07:54:31 +000025#include "llvm/Support/MemoryBuffer.h"
Chris Lattnercaee0dc2007-04-22 06:23:29 +000026using namespace llvm;
27
Chris Lattnerb348bb82007-05-18 04:02:46 +000028void BitcodeReader::FreeState() {
Chris Lattnerc453f762007-04-29 07:54:31 +000029 delete Buffer;
Chris Lattnerb348bb82007-05-18 04:02:46 +000030 Buffer = 0;
31 std::vector<PATypeHolder>().swap(TypeList);
32 ValueList.clear();
33 std::vector<const ParamAttrsList*>().swap(ParamAttrs);
34 std::vector<BasicBlock*>().swap(FunctionBBs);
35 std::vector<Function*>().swap(FunctionsWithBodies);
36 DeferredFunctionInfo.clear();
Chris Lattnerc453f762007-04-29 07:54:31 +000037}
38
Chris Lattner48c85b82007-05-04 03:30:17 +000039//===----------------------------------------------------------------------===//
40// Helper functions to implement forward reference resolution, etc.
41//===----------------------------------------------------------------------===//
Chris Lattnerc453f762007-04-29 07:54:31 +000042
Chris Lattnercaee0dc2007-04-22 06:23:29 +000043/// ConvertToString - Convert a string from a record into an std::string, return
44/// true on failure.
Chris Lattner0b2482a2007-04-23 21:26:05 +000045template<typename StrTy>
Chris Lattnercaee0dc2007-04-22 06:23:29 +000046static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
Chris Lattner0b2482a2007-04-23 21:26:05 +000047 StrTy &Result) {
Chris Lattner15e6d172007-05-04 19:11:41 +000048 if (Idx > Record.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +000049 return true;
50
Chris Lattner15e6d172007-05-04 19:11:41 +000051 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
52 Result += (char)Record[i];
Chris Lattnercaee0dc2007-04-22 06:23:29 +000053 return false;
54}
55
56static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
57 switch (Val) {
58 default: // Map unknown/new linkages to external
59 case 0: return GlobalValue::ExternalLinkage;
60 case 1: return GlobalValue::WeakLinkage;
61 case 2: return GlobalValue::AppendingLinkage;
62 case 3: return GlobalValue::InternalLinkage;
63 case 4: return GlobalValue::LinkOnceLinkage;
64 case 5: return GlobalValue::DLLImportLinkage;
65 case 6: return GlobalValue::DLLExportLinkage;
66 case 7: return GlobalValue::ExternalWeakLinkage;
67 }
68}
69
70static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
71 switch (Val) {
72 default: // Map unknown visibilities to default.
73 case 0: return GlobalValue::DefaultVisibility;
74 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov9cd3ccf2007-04-29 20:56:48 +000075 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattnercaee0dc2007-04-22 06:23:29 +000076 }
77}
78
Chris Lattnerf581c3b2007-04-24 07:07:11 +000079static int GetDecodedCastOpcode(unsigned Val) {
80 switch (Val) {
81 default: return -1;
82 case bitc::CAST_TRUNC : return Instruction::Trunc;
83 case bitc::CAST_ZEXT : return Instruction::ZExt;
84 case bitc::CAST_SEXT : return Instruction::SExt;
85 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
86 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
87 case bitc::CAST_UITOFP : return Instruction::UIToFP;
88 case bitc::CAST_SITOFP : return Instruction::SIToFP;
89 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
90 case bitc::CAST_FPEXT : return Instruction::FPExt;
91 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
92 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
93 case bitc::CAST_BITCAST : return Instruction::BitCast;
94 }
95}
96static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
97 switch (Val) {
98 default: return -1;
99 case bitc::BINOP_ADD: return Instruction::Add;
100 case bitc::BINOP_SUB: return Instruction::Sub;
101 case bitc::BINOP_MUL: return Instruction::Mul;
102 case bitc::BINOP_UDIV: return Instruction::UDiv;
103 case bitc::BINOP_SDIV:
104 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
105 case bitc::BINOP_UREM: return Instruction::URem;
106 case bitc::BINOP_SREM:
107 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
108 case bitc::BINOP_SHL: return Instruction::Shl;
109 case bitc::BINOP_LSHR: return Instruction::LShr;
110 case bitc::BINOP_ASHR: return Instruction::AShr;
111 case bitc::BINOP_AND: return Instruction::And;
112 case bitc::BINOP_OR: return Instruction::Or;
113 case bitc::BINOP_XOR: return Instruction::Xor;
114 }
115}
116
117
Chris Lattner522b7b12007-04-24 05:48:56 +0000118namespace {
119 /// @brief A class for maintaining the slot number definition
120 /// as a placeholder for the actual definition for forward constants defs.
121 class ConstantPlaceHolder : public ConstantExpr {
122 ConstantPlaceHolder(); // DO NOT IMPLEMENT
123 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000124 public:
125 Use Op;
126 ConstantPlaceHolder(const Type *Ty)
127 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
128 Op(UndefValue::get(Type::Int32Ty), this) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000129 }
130 };
131}
132
133Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
134 const Type *Ty) {
135 if (Idx >= size()) {
136 // Insert a bunch of null values.
137 Uses.resize(Idx+1);
138 OperandList = &Uses[0];
139 NumOperands = Idx+1;
140 }
141
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000142 if (Value *V = Uses[Idx]) {
143 assert(Ty == V->getType() && "Type mismatch in constant table!");
144 return cast<Constant>(V);
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000145 }
Chris Lattner522b7b12007-04-24 05:48:56 +0000146
147 // Create and return a placeholder, which will later be RAUW'd.
148 Constant *C = new ConstantPlaceHolder(Ty);
149 Uses[Idx].init(C, this);
150 return C;
151}
152
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000153Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
154 if (Idx >= size()) {
155 // Insert a bunch of null values.
156 Uses.resize(Idx+1);
157 OperandList = &Uses[0];
158 NumOperands = Idx+1;
159 }
160
161 if (Value *V = Uses[Idx]) {
162 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
163 return V;
164 }
165
Chris Lattner01ff65f2007-05-02 05:16:49 +0000166 // No type specified, must be invalid reference.
167 if (Ty == 0) return 0;
168
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000169 // Create and return a placeholder, which will later be RAUW'd.
170 Value *V = new Argument(Ty);
171 Uses[Idx].init(V, this);
172 return V;
173}
174
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000175
176const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
177 // If the TypeID is in range, return it.
178 if (ID < TypeList.size())
179 return TypeList[ID].get();
180 if (!isTypeTable) return 0;
181
182 // The type table allows forward references. Push as many Opaque types as
183 // needed to get up to ID.
184 while (TypeList.size() <= ID)
185 TypeList.push_back(OpaqueType::get());
186 return TypeList.back().get();
187}
188
Chris Lattner48c85b82007-05-04 03:30:17 +0000189//===----------------------------------------------------------------------===//
190// Functions for parsing blocks from the bitcode file
191//===----------------------------------------------------------------------===//
192
193bool BitcodeReader::ParseParamAttrBlock() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000194 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Chris Lattner48c85b82007-05-04 03:30:17 +0000195 return Error("Malformed block record");
196
197 if (!ParamAttrs.empty())
198 return Error("Multiple PARAMATTR blocks found!");
199
200 SmallVector<uint64_t, 64> Record;
201
202 ParamAttrsVector Attrs;
203
204 // Read all the records.
205 while (1) {
206 unsigned Code = Stream.ReadCode();
207 if (Code == bitc::END_BLOCK) {
208 if (Stream.ReadBlockEnd())
209 return Error("Error at end of PARAMATTR block");
210 return false;
211 }
212
213 if (Code == bitc::ENTER_SUBBLOCK) {
214 // No known subblocks, always skip them.
215 Stream.ReadSubBlockID();
216 if (Stream.SkipBlock())
217 return Error("Malformed block record");
218 continue;
219 }
220
221 if (Code == bitc::DEFINE_ABBREV) {
222 Stream.ReadAbbrevRecord();
223 continue;
224 }
225
226 // Read a record.
227 Record.clear();
228 switch (Stream.ReadRecord(Code, Record)) {
229 default: // Default behavior: ignore.
230 break;
231 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
232 if (Record.size() & 1)
233 return Error("Invalid ENTRY record");
234
235 ParamAttrsWithIndex PAWI;
236 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
237 PAWI.index = Record[i];
238 PAWI.attrs = Record[i+1];
239 Attrs.push_back(PAWI);
240 }
241 ParamAttrs.push_back(ParamAttrsList::get(Attrs));
242 Attrs.clear();
243 break;
244 }
245 }
246 }
247}
248
249
Chris Lattner86697142007-05-01 05:01:34 +0000250bool BitcodeReader::ParseTypeTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000251 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000252 return Error("Malformed block record");
253
254 if (!TypeList.empty())
255 return Error("Multiple TYPE_BLOCKs found!");
256
257 SmallVector<uint64_t, 64> Record;
258 unsigned NumRecords = 0;
259
260 // Read all the records for this type table.
261 while (1) {
262 unsigned Code = Stream.ReadCode();
263 if (Code == bitc::END_BLOCK) {
264 if (NumRecords != TypeList.size())
265 return Error("Invalid type forward reference in TYPE_BLOCK");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000266 if (Stream.ReadBlockEnd())
267 return Error("Error at end of type table block");
268 return false;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000269 }
270
271 if (Code == bitc::ENTER_SUBBLOCK) {
272 // No known subblocks, always skip them.
273 Stream.ReadSubBlockID();
274 if (Stream.SkipBlock())
275 return Error("Malformed block record");
276 continue;
277 }
278
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000279 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000280 Stream.ReadAbbrevRecord();
281 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000282 }
283
284 // Read a record.
285 Record.clear();
286 const Type *ResultTy = 0;
287 switch (Stream.ReadRecord(Code, Record)) {
288 default: // Default behavior: unknown type.
289 ResultTy = 0;
290 break;
291 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
292 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
293 // type list. This allows us to reserve space.
294 if (Record.size() < 1)
295 return Error("Invalid TYPE_CODE_NUMENTRY record");
296 TypeList.reserve(Record[0]);
297 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000298 case bitc::TYPE_CODE_VOID: // VOID
299 ResultTy = Type::VoidTy;
300 break;
301 case bitc::TYPE_CODE_FLOAT: // FLOAT
302 ResultTy = Type::FloatTy;
303 break;
304 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
305 ResultTy = Type::DoubleTy;
306 break;
Dale Johannesen320fc8a2007-08-03 01:03:46 +0000307 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
308 ResultTy = Type::X86_FP80Ty;
309 break;
310 case bitc::TYPE_CODE_FP128: // FP128
311 ResultTy = Type::FP128Ty;
312 break;
313 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
314 ResultTy = Type::PPC_FP128Ty;
315 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000316 case bitc::TYPE_CODE_LABEL: // LABEL
317 ResultTy = Type::LabelTy;
318 break;
319 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
320 ResultTy = 0;
321 break;
322 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
323 if (Record.size() < 1)
324 return Error("Invalid Integer type record");
325
326 ResultTy = IntegerType::get(Record[0]);
327 break;
328 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
329 if (Record.size() < 1)
330 return Error("Invalid POINTER type record");
331 ResultTy = PointerType::get(getTypeByID(Record[0], true));
332 break;
333 case bitc::TYPE_CODE_FUNCTION: {
Chris Lattner15e6d172007-05-04 19:11:41 +0000334 // FUNCTION: [vararg, attrid, retty, paramty x N]
335 if (Record.size() < 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000336 return Error("Invalid FUNCTION type record");
337 std::vector<const Type*> ArgTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000338 for (unsigned i = 3, e = Record.size(); i != e; ++i)
339 ArgTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000340
Chris Lattner9113e732007-05-04 03:41:34 +0000341 ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
342 Record[0], getParamAttrs(Record[1]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000343 break;
344 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000345 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, eltty x N]
Chris Lattner7108dce2007-05-06 08:21:50 +0000346 if (Record.size() < 1)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000347 return Error("Invalid STRUCT type record");
348 std::vector<const Type*> EltTys;
Chris Lattner15e6d172007-05-04 19:11:41 +0000349 for (unsigned i = 1, e = Record.size(); i != e; ++i)
350 EltTys.push_back(getTypeByID(Record[i], true));
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000351 ResultTy = StructType::get(EltTys, Record[0]);
352 break;
353 }
354 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
355 if (Record.size() < 2)
356 return Error("Invalid ARRAY type record");
357 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
358 break;
359 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
360 if (Record.size() < 2)
361 return Error("Invalid VECTOR type record");
362 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
363 break;
364 }
365
366 if (NumRecords == TypeList.size()) {
367 // If this is a new type slot, just append it.
368 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
369 ++NumRecords;
370 } else if (ResultTy == 0) {
371 // Otherwise, this was forward referenced, so an opaque type was created,
372 // but the result type is actually just an opaque. Leave the one we
373 // created previously.
374 ++NumRecords;
375 } else {
376 // Otherwise, this was forward referenced, so an opaque type was created.
377 // Resolve the opaque type to the real type now.
378 assert(NumRecords < TypeList.size() && "Typelist imbalance");
379 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
380
381 // Don't directly push the new type on the Tab. Instead we want to replace
382 // the opaque type we previously inserted with the new concrete value. The
383 // refinement from the abstract (opaque) type to the new type causes all
384 // uses of the abstract type to use the concrete type (NewTy). This will
385 // also cause the opaque type to be deleted.
386 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
387
388 // This should have replaced the old opaque type with the new type in the
Chris Lattner0eef0802007-04-24 04:04:35 +0000389 // value table... or with a preexisting type that was already in the
390 // system. Let's just make sure it did.
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000391 assert(TypeList[NumRecords-1].get() != OldTy &&
392 "refineAbstractType didn't work!");
393 }
394 }
395}
396
397
Chris Lattner86697142007-05-01 05:01:34 +0000398bool BitcodeReader::ParseTypeSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000399 if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000400 return Error("Malformed block record");
401
402 SmallVector<uint64_t, 64> Record;
403
404 // Read all the records for this type table.
405 std::string TypeName;
406 while (1) {
407 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000408 if (Code == bitc::END_BLOCK) {
409 if (Stream.ReadBlockEnd())
410 return Error("Error at end of type symbol table block");
411 return false;
412 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000413
414 if (Code == bitc::ENTER_SUBBLOCK) {
415 // No known subblocks, always skip them.
416 Stream.ReadSubBlockID();
417 if (Stream.SkipBlock())
418 return Error("Malformed block record");
419 continue;
420 }
421
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000422 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000423 Stream.ReadAbbrevRecord();
424 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000425 }
426
427 // Read a record.
428 Record.clear();
429 switch (Stream.ReadRecord(Code, Record)) {
430 default: // Default behavior: unknown type.
431 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000432 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namechar x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000433 if (ConvertToString(Record, 1, TypeName))
434 return Error("Invalid TST_ENTRY record");
435 unsigned TypeID = Record[0];
436 if (TypeID >= TypeList.size())
437 return Error("Invalid Type ID in TST_ENTRY record");
438
439 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
440 TypeName.clear();
441 break;
442 }
443 }
444}
445
Chris Lattner86697142007-05-01 05:01:34 +0000446bool BitcodeReader::ParseValueSymbolTable() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000447 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Chris Lattner0b2482a2007-04-23 21:26:05 +0000448 return Error("Malformed block record");
449
450 SmallVector<uint64_t, 64> Record;
451
452 // Read all the records for this value table.
453 SmallString<128> ValueName;
454 while (1) {
455 unsigned Code = Stream.ReadCode();
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000456 if (Code == bitc::END_BLOCK) {
457 if (Stream.ReadBlockEnd())
458 return Error("Error at end of value symbol table block");
459 return false;
460 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000461 if (Code == bitc::ENTER_SUBBLOCK) {
462 // No known subblocks, always skip them.
463 Stream.ReadSubBlockID();
464 if (Stream.SkipBlock())
465 return Error("Malformed block record");
466 continue;
467 }
468
469 if (Code == bitc::DEFINE_ABBREV) {
470 Stream.ReadAbbrevRecord();
471 continue;
472 }
473
474 // Read a record.
475 Record.clear();
476 switch (Stream.ReadRecord(Code, Record)) {
477 default: // Default behavior: unknown type.
478 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000479 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Chris Lattner0b2482a2007-04-23 21:26:05 +0000480 if (ConvertToString(Record, 1, ValueName))
481 return Error("Invalid TST_ENTRY record");
482 unsigned ValueID = Record[0];
483 if (ValueID >= ValueList.size())
484 return Error("Invalid Value ID in VST_ENTRY record");
485 Value *V = ValueList[ValueID];
486
487 V->setName(&ValueName[0], ValueName.size());
488 ValueName.clear();
489 break;
Reid Spencerc8f8a242007-05-04 01:43:33 +0000490 }
491 case bitc::VST_CODE_BBENTRY: {
Chris Lattnere825ed52007-05-03 22:18:21 +0000492 if (ConvertToString(Record, 1, ValueName))
493 return Error("Invalid VST_BBENTRY record");
494 BasicBlock *BB = getBasicBlock(Record[0]);
495 if (BB == 0)
496 return Error("Invalid BB ID in VST_BBENTRY record");
497
498 BB->setName(&ValueName[0], ValueName.size());
499 ValueName.clear();
500 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000501 }
Reid Spencerc8f8a242007-05-04 01:43:33 +0000502 }
Chris Lattner0b2482a2007-04-23 21:26:05 +0000503 }
504}
505
Chris Lattner0eef0802007-04-24 04:04:35 +0000506/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
507/// the LSB for dense VBR encoding.
508static uint64_t DecodeSignRotatedValue(uint64_t V) {
509 if ((V & 1) == 0)
510 return V >> 1;
511 if (V != 1)
512 return -(V >> 1);
513 // There is no such thing as -0 with integers. "-0" really means MININT.
514 return 1ULL << 63;
515}
516
Chris Lattner07d98b42007-04-26 02:46:40 +0000517/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
518/// values and aliases that we can.
519bool BitcodeReader::ResolveGlobalAndAliasInits() {
520 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
521 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
522
523 GlobalInitWorklist.swap(GlobalInits);
524 AliasInitWorklist.swap(AliasInits);
525
526 while (!GlobalInitWorklist.empty()) {
Chris Lattner198f34a2007-04-26 03:27:58 +0000527 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner07d98b42007-04-26 02:46:40 +0000528 if (ValID >= ValueList.size()) {
529 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner198f34a2007-04-26 03:27:58 +0000530 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner07d98b42007-04-26 02:46:40 +0000531 } else {
532 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
533 GlobalInitWorklist.back().first->setInitializer(C);
534 else
535 return Error("Global variable initializer is not a constant!");
536 }
537 GlobalInitWorklist.pop_back();
538 }
539
540 while (!AliasInitWorklist.empty()) {
541 unsigned ValID = AliasInitWorklist.back().second;
542 if (ValID >= ValueList.size()) {
543 AliasInits.push_back(AliasInitWorklist.back());
544 } else {
545 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
Anton Korobeynikov7dde0ff2007-04-28 14:57:59 +0000546 AliasInitWorklist.back().first->setAliasee(C);
Chris Lattner07d98b42007-04-26 02:46:40 +0000547 else
548 return Error("Alias initializer is not a constant!");
549 }
550 AliasInitWorklist.pop_back();
551 }
552 return false;
553}
554
555
Chris Lattner86697142007-05-01 05:01:34 +0000556bool BitcodeReader::ParseConstants() {
Chris Lattnere17b6582007-05-05 00:17:00 +0000557 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Chris Lattnere16504e2007-04-24 03:30:34 +0000558 return Error("Malformed block record");
559
560 SmallVector<uint64_t, 64> Record;
561
562 // Read all the records for this value table.
563 const Type *CurTy = Type::Int32Ty;
Chris Lattner522b7b12007-04-24 05:48:56 +0000564 unsigned NextCstNo = ValueList.size();
Chris Lattnere16504e2007-04-24 03:30:34 +0000565 while (1) {
566 unsigned Code = Stream.ReadCode();
567 if (Code == bitc::END_BLOCK) {
Chris Lattner522b7b12007-04-24 05:48:56 +0000568 if (NextCstNo != ValueList.size())
569 return Error("Invalid constant reference!");
570
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000571 if (Stream.ReadBlockEnd())
572 return Error("Error at end of constants block");
573 return false;
Chris Lattnere16504e2007-04-24 03:30:34 +0000574 }
575
576 if (Code == bitc::ENTER_SUBBLOCK) {
577 // No known subblocks, always skip them.
578 Stream.ReadSubBlockID();
579 if (Stream.SkipBlock())
580 return Error("Malformed block record");
581 continue;
582 }
583
584 if (Code == bitc::DEFINE_ABBREV) {
585 Stream.ReadAbbrevRecord();
586 continue;
587 }
588
589 // Read a record.
590 Record.clear();
591 Value *V = 0;
592 switch (Stream.ReadRecord(Code, Record)) {
593 default: // Default behavior: unknown constant
594 case bitc::CST_CODE_UNDEF: // UNDEF
595 V = UndefValue::get(CurTy);
596 break;
597 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
598 if (Record.empty())
599 return Error("Malformed CST_SETTYPE record");
600 if (Record[0] >= TypeList.size())
601 return Error("Invalid Type ID in CST_SETTYPE record");
602 CurTy = TypeList[Record[0]];
Chris Lattner0eef0802007-04-24 04:04:35 +0000603 continue; // Skip the ValueList manipulation.
Chris Lattnere16504e2007-04-24 03:30:34 +0000604 case bitc::CST_CODE_NULL: // NULL
605 V = Constant::getNullValue(CurTy);
606 break;
607 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Chris Lattner0eef0802007-04-24 04:04:35 +0000608 if (!isa<IntegerType>(CurTy) || Record.empty())
609 return Error("Invalid CST_INTEGER record");
610 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
611 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000612 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
613 if (!isa<IntegerType>(CurTy) || Record.empty())
Chris Lattner0eef0802007-04-24 04:04:35 +0000614 return Error("Invalid WIDE_INTEGER record");
615
Chris Lattner15e6d172007-05-04 19:11:41 +0000616 unsigned NumWords = Record.size();
Chris Lattner084a8442007-04-24 17:22:05 +0000617 SmallVector<uint64_t, 8> Words;
618 Words.resize(NumWords);
Chris Lattner0eef0802007-04-24 04:04:35 +0000619 for (unsigned i = 0; i != NumWords; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000620 Words[i] = DecodeSignRotatedValue(Record[i]);
Chris Lattner0eef0802007-04-24 04:04:35 +0000621 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
Chris Lattner084a8442007-04-24 17:22:05 +0000622 NumWords, &Words[0]));
Chris Lattner0eef0802007-04-24 04:04:35 +0000623 break;
624 }
625 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
626 if (Record.empty())
627 return Error("Invalid FLOAT record");
628 if (CurTy == Type::FloatTy)
629 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
630 else if (CurTy == Type::DoubleTy)
631 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
Chris Lattnere16504e2007-04-24 03:30:34 +0000632 else
Chris Lattner0eef0802007-04-24 04:04:35 +0000633 V = UndefValue::get(CurTy);
Chris Lattnere16504e2007-04-24 03:30:34 +0000634 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000635
Chris Lattner15e6d172007-05-04 19:11:41 +0000636 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
637 if (Record.empty())
Chris Lattner522b7b12007-04-24 05:48:56 +0000638 return Error("Invalid CST_AGGREGATE record");
639
Chris Lattner15e6d172007-05-04 19:11:41 +0000640 unsigned Size = Record.size();
Chris Lattner522b7b12007-04-24 05:48:56 +0000641 std::vector<Constant*> Elts;
642
643 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
644 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000645 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner522b7b12007-04-24 05:48:56 +0000646 STy->getElementType(i)));
647 V = ConstantStruct::get(STy, Elts);
648 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
649 const Type *EltTy = ATy->getElementType();
650 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000651 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000652 V = ConstantArray::get(ATy, Elts);
653 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
654 const Type *EltTy = VTy->getElementType();
655 for (unsigned i = 0; i != Size; ++i)
Chris Lattner15e6d172007-05-04 19:11:41 +0000656 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Chris Lattner522b7b12007-04-24 05:48:56 +0000657 V = ConstantVector::get(Elts);
658 } else {
659 V = UndefValue::get(CurTy);
660 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000661 break;
662 }
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000663 case bitc::CST_CODE_STRING: { // STRING: [values]
664 if (Record.empty())
665 return Error("Invalid CST_AGGREGATE record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000666
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000667 const ArrayType *ATy = cast<ArrayType>(CurTy);
668 const Type *EltTy = ATy->getElementType();
669
670 unsigned Size = Record.size();
671 std::vector<Constant*> Elts;
Chris Lattnerff7fc5d2007-05-06 00:35:24 +0000672 for (unsigned i = 0; i != Size; ++i)
673 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
674 V = ConstantArray::get(ATy, Elts);
675 break;
676 }
Chris Lattnercb3d91b2007-05-06 00:53:07 +0000677 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
678 if (Record.empty())
679 return Error("Invalid CST_AGGREGATE record");
680
681 const ArrayType *ATy = cast<ArrayType>(CurTy);
682 const Type *EltTy = ATy->getElementType();
683
684 unsigned Size = Record.size();
685 std::vector<Constant*> Elts;
686 for (unsigned i = 0; i != Size; ++i)
687 Elts.push_back(ConstantInt::get(EltTy, Record[i]));
688 Elts.push_back(Constant::getNullValue(EltTy));
689 V = ConstantArray::get(ATy, Elts);
690 break;
691 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000692 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
693 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
694 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000695 if (Opc < 0) {
696 V = UndefValue::get(CurTy); // Unknown binop.
697 } else {
698 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
699 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
700 V = ConstantExpr::get(Opc, LHS, RHS);
701 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000702 break;
703 }
704 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
705 if (Record.size() < 3) return Error("Invalid CE_CAST record");
706 int Opc = GetDecodedCastOpcode(Record[0]);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000707 if (Opc < 0) {
708 V = UndefValue::get(CurTy); // Unknown cast.
709 } else {
710 const Type *OpTy = getTypeByID(Record[1]);
Chris Lattnerbfcc3802007-05-06 07:33:01 +0000711 if (!OpTy) return Error("Invalid CE_CAST record");
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000712 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
713 V = ConstantExpr::getCast(Opc, Op, CurTy);
714 }
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000715 break;
716 }
717 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
Chris Lattner15e6d172007-05-04 19:11:41 +0000718 if (Record.size() & 1) return Error("Invalid CE_GEP record");
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000719 SmallVector<Constant*, 16> Elts;
Chris Lattner15e6d172007-05-04 19:11:41 +0000720 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000721 const Type *ElTy = getTypeByID(Record[i]);
722 if (!ElTy) return Error("Invalid CE_GEP record");
723 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
724 }
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000725 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
726 break;
Chris Lattnerf581c3b2007-04-24 07:07:11 +0000727 }
728 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
729 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
730 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
731 Type::Int1Ty),
732 ValueList.getConstantFwdRef(Record[1],CurTy),
733 ValueList.getConstantFwdRef(Record[2],CurTy));
734 break;
735 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
736 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
737 const VectorType *OpTy =
738 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
739 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
740 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
741 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
742 OpTy->getElementType());
743 V = ConstantExpr::getExtractElement(Op0, Op1);
744 break;
745 }
746 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
747 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
748 if (Record.size() < 3 || OpTy == 0)
749 return Error("Invalid CE_INSERTELT record");
750 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
751 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
752 OpTy->getElementType());
753 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
754 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
755 break;
756 }
757 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
758 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
759 if (Record.size() < 3 || OpTy == 0)
760 return Error("Invalid CE_INSERTELT record");
761 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
762 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
763 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
764 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
765 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
766 break;
767 }
768 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
769 if (Record.size() < 4) return Error("Invalid CE_CMP record");
770 const Type *OpTy = getTypeByID(Record[0]);
771 if (OpTy == 0) return Error("Invalid CE_CMP record");
772 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
773 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
774
775 if (OpTy->isFloatingPoint())
776 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
777 else
778 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
779 break;
Chris Lattner522b7b12007-04-24 05:48:56 +0000780 }
Chris Lattner2bce93a2007-05-06 01:58:20 +0000781 case bitc::CST_CODE_INLINEASM: {
782 if (Record.size() < 2) return Error("Invalid INLINEASM record");
783 std::string AsmStr, ConstrStr;
784 bool HasSideEffects = Record[0];
785 unsigned AsmStrSize = Record[1];
786 if (2+AsmStrSize >= Record.size())
787 return Error("Invalid INLINEASM record");
788 unsigned ConstStrSize = Record[2+AsmStrSize];
789 if (3+AsmStrSize+ConstStrSize > Record.size())
790 return Error("Invalid INLINEASM record");
791
792 for (unsigned i = 0; i != AsmStrSize; ++i)
793 AsmStr += (char)Record[2+i];
794 for (unsigned i = 0; i != ConstStrSize; ++i)
795 ConstrStr += (char)Record[3+AsmStrSize+i];
796 const PointerType *PTy = cast<PointerType>(CurTy);
797 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
798 AsmStr, ConstrStr, HasSideEffects);
799 break;
800 }
Chris Lattnere16504e2007-04-24 03:30:34 +0000801 }
802
Chris Lattnera7c49aa2007-05-01 07:01:57 +0000803 ValueList.AssignValue(V, NextCstNo);
Chris Lattner522b7b12007-04-24 05:48:56 +0000804 ++NextCstNo;
Chris Lattnere16504e2007-04-24 03:30:34 +0000805 }
806}
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000807
Chris Lattner980e5aa2007-05-01 05:52:21 +0000808/// RememberAndSkipFunctionBody - When we see the block for a function body,
809/// remember where it is and then skip it. This lets us lazily deserialize the
810/// functions.
811bool BitcodeReader::RememberAndSkipFunctionBody() {
Chris Lattner48f84872007-05-01 04:59:48 +0000812 // Get the function we are talking about.
813 if (FunctionsWithBodies.empty())
814 return Error("Insufficient function protos");
815
816 Function *Fn = FunctionsWithBodies.back();
817 FunctionsWithBodies.pop_back();
818
819 // Save the current stream state.
820 uint64_t CurBit = Stream.GetCurrentBitNo();
821 DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
822
823 // Set the functions linkage to GhostLinkage so we know it is lazily
824 // deserialized.
825 Fn->setLinkage(GlobalValue::GhostLinkage);
826
827 // Skip over the function block for now.
828 if (Stream.SkipBlock())
829 return Error("Malformed block record");
830 return false;
831}
832
Chris Lattner86697142007-05-01 05:01:34 +0000833bool BitcodeReader::ParseModule(const std::string &ModuleID) {
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000834 // Reject multiple MODULE_BLOCK's in a single bitstream.
835 if (TheModule)
836 return Error("Multiple MODULE_BLOCKs in same stream");
837
Chris Lattnere17b6582007-05-05 00:17:00 +0000838 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000839 return Error("Malformed block record");
840
841 // Otherwise, create the module.
842 TheModule = new Module(ModuleID);
843
844 SmallVector<uint64_t, 64> Record;
845 std::vector<std::string> SectionTable;
846
847 // Read all the records for this module.
848 while (!Stream.AtEndOfStream()) {
849 unsigned Code = Stream.ReadCode();
Chris Lattnere84bcb92007-04-24 00:21:45 +0000850 if (Code == bitc::END_BLOCK) {
Chris Lattner980e5aa2007-05-01 05:52:21 +0000851 if (Stream.ReadBlockEnd())
852 return Error("Error at end of module block");
853
854 // Patch the initializers for globals and aliases up.
Chris Lattner07d98b42007-04-26 02:46:40 +0000855 ResolveGlobalAndAliasInits();
856 if (!GlobalInits.empty() || !AliasInits.empty())
Chris Lattnere84bcb92007-04-24 00:21:45 +0000857 return Error("Malformed global initializer set");
Chris Lattner48f84872007-05-01 04:59:48 +0000858 if (!FunctionsWithBodies.empty())
859 return Error("Too few function bodies found");
Chris Lattner980e5aa2007-05-01 05:52:21 +0000860
Chandler Carruth69940402007-08-04 01:51:18 +0000861 // Look for intrinsic functions which need to be upgraded at some point
862 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
863 FI != FE; ++FI) {
864 if (Function* NewFn = UpgradeIntrinsicFunction(FI))
865 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
866 }
867
Chris Lattner980e5aa2007-05-01 05:52:21 +0000868 // Force deallocation of memory for these vectors to favor the client that
869 // want lazy deserialization.
870 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
871 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
872 std::vector<Function*>().swap(FunctionsWithBodies);
Chris Lattnerf66d20d2007-04-24 18:15:21 +0000873 return false;
Chris Lattnere84bcb92007-04-24 00:21:45 +0000874 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000875
876 if (Code == bitc::ENTER_SUBBLOCK) {
877 switch (Stream.ReadSubBlockID()) {
878 default: // Skip unknown content.
879 if (Stream.SkipBlock())
880 return Error("Malformed block record");
881 break;
Chris Lattner3f799802007-05-05 18:57:30 +0000882 case bitc::BLOCKINFO_BLOCK_ID:
883 if (Stream.ReadBlockInfoBlock())
884 return Error("Malformed BlockInfoBlock");
885 break;
Chris Lattner48c85b82007-05-04 03:30:17 +0000886 case bitc::PARAMATTR_BLOCK_ID:
887 if (ParseParamAttrBlock())
888 return true;
889 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000890 case bitc::TYPE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000891 if (ParseTypeTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000892 return true;
893 break;
894 case bitc::TYPE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000895 if (ParseTypeSymbolTable())
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000896 return true;
897 break;
Chris Lattner0b2482a2007-04-23 21:26:05 +0000898 case bitc::VALUE_SYMTAB_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000899 if (ParseValueSymbolTable())
Chris Lattner0b2482a2007-04-23 21:26:05 +0000900 return true;
901 break;
Chris Lattnere16504e2007-04-24 03:30:34 +0000902 case bitc::CONSTANTS_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +0000903 if (ParseConstants() || ResolveGlobalAndAliasInits())
Chris Lattnere16504e2007-04-24 03:30:34 +0000904 return true;
905 break;
Chris Lattner48f84872007-05-01 04:59:48 +0000906 case bitc::FUNCTION_BLOCK_ID:
907 // If this is the first function body we've seen, reverse the
908 // FunctionsWithBodies list.
909 if (!HasReversedFunctionsWithBodies) {
910 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
911 HasReversedFunctionsWithBodies = true;
912 }
913
Chris Lattner980e5aa2007-05-01 05:52:21 +0000914 if (RememberAndSkipFunctionBody())
Chris Lattner48f84872007-05-01 04:59:48 +0000915 return true;
916 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000917 }
918 continue;
919 }
920
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000921 if (Code == bitc::DEFINE_ABBREV) {
Chris Lattnerd127c1b2007-04-23 18:58:34 +0000922 Stream.ReadAbbrevRecord();
923 continue;
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000924 }
925
926 // Read a record.
927 switch (Stream.ReadRecord(Code, Record)) {
928 default: break; // Default behavior, ignore unknown content.
929 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
930 if (Record.size() < 1)
931 return Error("Malformed MODULE_CODE_VERSION");
932 // Only version #0 is supported so far.
933 if (Record[0] != 0)
934 return Error("Unknown bitstream version!");
935 break;
Chris Lattner15e6d172007-05-04 19:11:41 +0000936 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000937 std::string S;
938 if (ConvertToString(Record, 0, S))
939 return Error("Invalid MODULE_CODE_TRIPLE record");
940 TheModule->setTargetTriple(S);
941 break;
942 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000943 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000944 std::string S;
945 if (ConvertToString(Record, 0, S))
946 return Error("Invalid MODULE_CODE_DATALAYOUT record");
947 TheModule->setDataLayout(S);
948 break;
949 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000950 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000951 std::string S;
952 if (ConvertToString(Record, 0, S))
953 return Error("Invalid MODULE_CODE_ASM record");
954 TheModule->setModuleInlineAsm(S);
955 break;
956 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000957 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000958 std::string S;
959 if (ConvertToString(Record, 0, S))
960 return Error("Invalid MODULE_CODE_DEPLIB record");
961 TheModule->addLibrary(S);
962 break;
963 }
Chris Lattner15e6d172007-05-04 19:11:41 +0000964 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000965 std::string S;
966 if (ConvertToString(Record, 0, S))
967 return Error("Invalid MODULE_CODE_SECTIONNAME record");
968 SectionTable.push_back(S);
969 break;
970 }
971 // GLOBALVAR: [type, isconst, initid,
972 // linkage, alignment, section, visibility, threadlocal]
973 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000974 if (Record.size() < 6)
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000975 return Error("Invalid MODULE_CODE_GLOBALVAR record");
976 const Type *Ty = getTypeByID(Record[0]);
977 if (!isa<PointerType>(Ty))
978 return Error("Global not a pointer type!");
979 Ty = cast<PointerType>(Ty)->getElementType();
980
981 bool isConstant = Record[1];
982 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
983 unsigned Alignment = (1 << Record[4]) >> 1;
984 std::string Section;
985 if (Record[5]) {
986 if (Record[5]-1 >= SectionTable.size())
987 return Error("Invalid section ID");
988 Section = SectionTable[Record[5]-1];
989 }
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000990 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Chris Lattner5f32c012007-05-06 19:27:46 +0000991 if (Record.size() > 6)
992 Visibility = GetDecodedVisibility(Record[6]);
Chris Lattner36d5e7d2007-04-23 16:04:05 +0000993 bool isThreadLocal = false;
Chris Lattner5f32c012007-05-06 19:27:46 +0000994 if (Record.size() > 7)
995 isThreadLocal = Record[7];
Chris Lattnercaee0dc2007-04-22 06:23:29 +0000996
997 GlobalVariable *NewGV =
998 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
999 NewGV->setAlignment(Alignment);
1000 if (!Section.empty())
1001 NewGV->setSection(Section);
1002 NewGV->setVisibility(Visibility);
1003 NewGV->setThreadLocal(isThreadLocal);
1004
Chris Lattner0b2482a2007-04-23 21:26:05 +00001005 ValueList.push_back(NewGV);
1006
Chris Lattner6dbfd7b2007-04-24 00:18:21 +00001007 // Remember which value to use for the global initializer.
1008 if (unsigned InitID = Record[2])
1009 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001010 break;
1011 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001012 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
1013 // alignment, section, visibility]
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001014 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattnera9bb7132007-05-08 05:38:01 +00001015 if (Record.size() < 8)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001016 return Error("Invalid MODULE_CODE_FUNCTION record");
1017 const Type *Ty = getTypeByID(Record[0]);
1018 if (!isa<PointerType>(Ty))
1019 return Error("Function not a pointer type!");
1020 const FunctionType *FTy =
1021 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1022 if (!FTy)
1023 return Error("Function not a pointer to function type!");
1024
1025 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
1026 "", TheModule);
1027
1028 Func->setCallingConv(Record[1]);
Chris Lattner48f84872007-05-01 04:59:48 +00001029 bool isProto = Record[2];
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001030 Func->setLinkage(GetDecodedLinkage(Record[3]));
Chris Lattnera9bb7132007-05-08 05:38:01 +00001031
1032 assert(Func->getFunctionType()->getParamAttrs() ==
1033 getParamAttrs(Record[4]));
1034
1035 Func->setAlignment((1 << Record[5]) >> 1);
1036 if (Record[6]) {
1037 if (Record[6]-1 >= SectionTable.size())
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001038 return Error("Invalid section ID");
Chris Lattnera9bb7132007-05-08 05:38:01 +00001039 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001040 }
Chris Lattnera9bb7132007-05-08 05:38:01 +00001041 Func->setVisibility(GetDecodedVisibility(Record[7]));
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001042
Chris Lattner0b2482a2007-04-23 21:26:05 +00001043 ValueList.push_back(Func);
Chris Lattner48f84872007-05-01 04:59:48 +00001044
1045 // If this is a function with a body, remember the prototype we are
1046 // creating now, so that we can match up the body with them later.
1047 if (!isProto)
1048 FunctionsWithBodies.push_back(Func);
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001049 break;
1050 }
Chris Lattner07d98b42007-04-26 02:46:40 +00001051 // ALIAS: [alias type, aliasee val#, linkage]
Chris Lattner198f34a2007-04-26 03:27:58 +00001052 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner07d98b42007-04-26 02:46:40 +00001053 if (Record.size() < 3)
1054 return Error("Invalid MODULE_ALIAS record");
1055 const Type *Ty = getTypeByID(Record[0]);
1056 if (!isa<PointerType>(Ty))
1057 return Error("Function not a pointer type!");
1058
1059 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1060 "", 0, TheModule);
1061 ValueList.push_back(NewGA);
1062 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1063 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001064 }
Chris Lattner198f34a2007-04-26 03:27:58 +00001065 /// MODULE_CODE_PURGEVALS: [numvals]
1066 case bitc::MODULE_CODE_PURGEVALS:
1067 // Trim down the value list to the specified size.
1068 if (Record.size() < 1 || Record[0] > ValueList.size())
1069 return Error("Invalid MODULE_PURGEVALS record");
1070 ValueList.shrinkTo(Record[0]);
1071 break;
1072 }
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001073 Record.clear();
1074 }
1075
1076 return Error("Premature end of bitstream");
1077}
1078
1079
Chris Lattnerc453f762007-04-29 07:54:31 +00001080bool BitcodeReader::ParseBitcode() {
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001081 TheModule = 0;
1082
Chris Lattnerc453f762007-04-29 07:54:31 +00001083 if (Buffer->getBufferSize() & 3)
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001084 return Error("Bitcode stream should be a multiple of 4 bytes in length");
1085
Chris Lattnerc453f762007-04-29 07:54:31 +00001086 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
Chris Lattner48f84872007-05-01 04:59:48 +00001087 Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001088
1089 // Sniff for the signature.
1090 if (Stream.Read(8) != 'B' ||
1091 Stream.Read(8) != 'C' ||
1092 Stream.Read(4) != 0x0 ||
1093 Stream.Read(4) != 0xC ||
1094 Stream.Read(4) != 0xE ||
1095 Stream.Read(4) != 0xD)
1096 return Error("Invalid bitcode signature");
1097
1098 // We expect a number of well-defined blocks, though we don't necessarily
1099 // need to understand them all.
1100 while (!Stream.AtEndOfStream()) {
1101 unsigned Code = Stream.ReadCode();
1102
1103 if (Code != bitc::ENTER_SUBBLOCK)
1104 return Error("Invalid record at top-level");
1105
1106 unsigned BlockID = Stream.ReadSubBlockID();
1107
1108 // We only know the MODULE subblock ID.
Chris Lattnere17b6582007-05-05 00:17:00 +00001109 switch (BlockID) {
1110 case bitc::BLOCKINFO_BLOCK_ID:
1111 if (Stream.ReadBlockInfoBlock())
1112 return Error("Malformed BlockInfoBlock");
1113 break;
1114 case bitc::MODULE_BLOCK_ID:
Chris Lattner86697142007-05-01 05:01:34 +00001115 if (ParseModule(Buffer->getBufferIdentifier()))
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001116 return true;
Chris Lattnere17b6582007-05-05 00:17:00 +00001117 break;
1118 default:
1119 if (Stream.SkipBlock())
1120 return Error("Malformed block record");
1121 break;
Chris Lattnercaee0dc2007-04-22 06:23:29 +00001122 }
1123 }
1124
1125 return false;
1126}
Chris Lattnerc453f762007-04-29 07:54:31 +00001127
Chris Lattner48f84872007-05-01 04:59:48 +00001128
Chris Lattner980e5aa2007-05-01 05:52:21 +00001129/// ParseFunctionBody - Lazily parse the specified function body block.
1130bool BitcodeReader::ParseFunctionBody(Function *F) {
Chris Lattnere17b6582007-05-05 00:17:00 +00001131 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Chris Lattner980e5aa2007-05-01 05:52:21 +00001132 return Error("Malformed block record");
1133
1134 unsigned ModuleValueListSize = ValueList.size();
1135
1136 // Add all the function arguments to the value table.
1137 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1138 ValueList.push_back(I);
1139
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001140 unsigned NextValueNo = ValueList.size();
Chris Lattner231cbcb2007-05-02 04:27:25 +00001141 BasicBlock *CurBB = 0;
1142 unsigned CurBBNo = 0;
1143
Chris Lattner980e5aa2007-05-01 05:52:21 +00001144 // Read all the records.
1145 SmallVector<uint64_t, 64> Record;
1146 while (1) {
1147 unsigned Code = Stream.ReadCode();
1148 if (Code == bitc::END_BLOCK) {
1149 if (Stream.ReadBlockEnd())
1150 return Error("Error at end of function block");
1151 break;
1152 }
1153
1154 if (Code == bitc::ENTER_SUBBLOCK) {
1155 switch (Stream.ReadSubBlockID()) {
1156 default: // Skip unknown content.
1157 if (Stream.SkipBlock())
1158 return Error("Malformed block record");
1159 break;
1160 case bitc::CONSTANTS_BLOCK_ID:
1161 if (ParseConstants()) return true;
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001162 NextValueNo = ValueList.size();
Chris Lattner980e5aa2007-05-01 05:52:21 +00001163 break;
1164 case bitc::VALUE_SYMTAB_BLOCK_ID:
1165 if (ParseValueSymbolTable()) return true;
1166 break;
1167 }
1168 continue;
1169 }
1170
1171 if (Code == bitc::DEFINE_ABBREV) {
1172 Stream.ReadAbbrevRecord();
1173 continue;
1174 }
1175
1176 // Read a record.
1177 Record.clear();
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001178 Instruction *I = 0;
Chris Lattner980e5aa2007-05-01 05:52:21 +00001179 switch (Stream.ReadRecord(Code, Record)) {
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001180 default: // Default behavior: reject
1181 return Error("Unknown instruction");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001182 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001183 if (Record.size() < 1 || Record[0] == 0)
1184 return Error("Invalid DECLAREBLOCKS record");
Chris Lattner980e5aa2007-05-01 05:52:21 +00001185 // Create all the basic blocks for the function.
Chris Lattnerf61e6452007-05-03 22:09:51 +00001186 FunctionBBs.resize(Record[0]);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001187 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1188 FunctionBBs[i] = new BasicBlock("", F);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001189 CurBB = FunctionBBs[0];
1190 continue;
1191
Chris Lattnerabfbf852007-05-06 00:21:25 +00001192 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
1193 unsigned OpNum = 0;
1194 Value *LHS, *RHS;
1195 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1196 getValue(Record, OpNum, LHS->getType(), RHS) ||
1197 OpNum+1 != Record.size())
1198 return Error("Invalid BINOP record");
1199
1200 int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1201 if (Opc == -1) return Error("Invalid BINOP record");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001202 I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001203 break;
1204 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001205 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
1206 unsigned OpNum = 0;
1207 Value *Op;
1208 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1209 OpNum+2 != Record.size())
1210 return Error("Invalid CAST record");
1211
1212 const Type *ResTy = getTypeByID(Record[OpNum]);
1213 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1214 if (Opc == -1 || ResTy == 0)
Chris Lattner231cbcb2007-05-02 04:27:25 +00001215 return Error("Invalid CAST record");
1216 I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1217 break;
1218 }
Chris Lattner15e6d172007-05-04 19:11:41 +00001219 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
Chris Lattner7337ab92007-05-06 00:00:00 +00001220 unsigned OpNum = 0;
1221 Value *BasePtr;
1222 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001223 return Error("Invalid GEP record");
1224
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001225 SmallVector<Value*, 16> GEPIdx;
Chris Lattner7337ab92007-05-06 00:00:00 +00001226 while (OpNum != Record.size()) {
1227 Value *Op;
1228 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001229 return Error("Invalid GEP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001230 GEPIdx.push_back(Op);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001231 }
1232
Chris Lattner7337ab92007-05-06 00:00:00 +00001233 I = new GetElementPtrInst(BasePtr, &GEPIdx[0], GEPIdx.size());
Chris Lattner01ff65f2007-05-02 05:16:49 +00001234 break;
1235 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001236
Chris Lattnerabfbf852007-05-06 00:21:25 +00001237 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1238 unsigned OpNum = 0;
1239 Value *TrueVal, *FalseVal, *Cond;
1240 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1241 getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1242 getValue(Record, OpNum, Type::Int1Ty, Cond))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001243 return Error("Invalid SELECT record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001244
1245 I = new SelectInst(Cond, TrueVal, FalseVal);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001246 break;
1247 }
1248
1249 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001250 unsigned OpNum = 0;
1251 Value *Vec, *Idx;
1252 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1253 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001254 return Error("Invalid EXTRACTELT record");
1255 I = new ExtractElementInst(Vec, Idx);
1256 break;
1257 }
1258
1259 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnerabfbf852007-05-06 00:21:25 +00001260 unsigned OpNum = 0;
1261 Value *Vec, *Elt, *Idx;
1262 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1263 getValue(Record, OpNum,
1264 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1265 getValue(Record, OpNum, Type::Int32Ty, Idx))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001266 return Error("Invalid INSERTELT record");
1267 I = new InsertElementInst(Vec, Elt, Idx);
1268 break;
1269 }
1270
Chris Lattnerabfbf852007-05-06 00:21:25 +00001271 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1272 unsigned OpNum = 0;
1273 Value *Vec1, *Vec2, *Mask;
1274 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1275 getValue(Record, OpNum, Vec1->getType(), Vec2))
1276 return Error("Invalid SHUFFLEVEC record");
1277
1278 const Type *MaskTy =
1279 VectorType::get(Type::Int32Ty,
1280 cast<VectorType>(Vec1->getType())->getNumElements());
1281
1282 if (getValue(Record, OpNum, MaskTy, Mask))
Chris Lattner01ff65f2007-05-02 05:16:49 +00001283 return Error("Invalid SHUFFLEVEC record");
1284 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1285 break;
1286 }
1287
1288 case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
Chris Lattner7337ab92007-05-06 00:00:00 +00001289 unsigned OpNum = 0;
1290 Value *LHS, *RHS;
1291 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1292 getValue(Record, OpNum, LHS->getType(), RHS) ||
1293 OpNum+1 != Record.size())
Chris Lattner01ff65f2007-05-02 05:16:49 +00001294 return Error("Invalid CMP record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001295
1296 if (LHS->getType()->isFPOrFPVector())
1297 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001298 else
Chris Lattner7337ab92007-05-06 00:00:00 +00001299 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
Chris Lattner01ff65f2007-05-02 05:16:49 +00001300 break;
1301 }
1302
Chris Lattner231cbcb2007-05-02 04:27:25 +00001303 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1304 if (Record.size() == 0) {
1305 I = new ReturnInst();
1306 break;
Chris Lattner7337ab92007-05-06 00:00:00 +00001307 } else {
1308 unsigned OpNum = 0;
1309 Value *Op;
1310 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1311 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001312 return Error("Invalid RET record");
Chris Lattner231cbcb2007-05-02 04:27:25 +00001313 I = new ReturnInst(Op);
1314 break;
1315 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001316 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattnerf61e6452007-05-03 22:09:51 +00001317 if (Record.size() != 1 && Record.size() != 3)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001318 return Error("Invalid BR record");
1319 BasicBlock *TrueDest = getBasicBlock(Record[0]);
1320 if (TrueDest == 0)
1321 return Error("Invalid BR record");
1322
1323 if (Record.size() == 1)
1324 I = new BranchInst(TrueDest);
1325 else {
1326 BasicBlock *FalseDest = getBasicBlock(Record[1]);
1327 Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1328 if (FalseDest == 0 || Cond == 0)
1329 return Error("Invalid BR record");
1330 I = new BranchInst(TrueDest, FalseDest, Cond);
1331 }
1332 break;
1333 }
1334 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1335 if (Record.size() < 3 || (Record.size() & 1) == 0)
1336 return Error("Invalid SWITCH record");
1337 const Type *OpTy = getTypeByID(Record[0]);
1338 Value *Cond = getFnValueByID(Record[1], OpTy);
1339 BasicBlock *Default = getBasicBlock(Record[2]);
1340 if (OpTy == 0 || Cond == 0 || Default == 0)
1341 return Error("Invalid SWITCH record");
1342 unsigned NumCases = (Record.size()-3)/2;
1343 SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1344 for (unsigned i = 0, e = NumCases; i != e; ++i) {
1345 ConstantInt *CaseVal =
1346 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1347 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1348 if (CaseVal == 0 || DestBB == 0) {
1349 delete SI;
1350 return Error("Invalid SWITCH record!");
1351 }
1352 SI->addCase(CaseVal, DestBB);
1353 }
1354 I = SI;
1355 break;
1356 }
1357
Chris Lattner76520192007-05-03 22:34:03 +00001358 case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001359 if (Record.size() < 4) return Error("Invalid INVOKE record");
1360 unsigned CCInfo = Record[1];
1361 BasicBlock *NormalBB = getBasicBlock(Record[2]);
1362 BasicBlock *UnwindBB = getBasicBlock(Record[3]);
Chris Lattner7337ab92007-05-06 00:00:00 +00001363
Chris Lattnera9bb7132007-05-08 05:38:01 +00001364 unsigned OpNum = 4;
Chris Lattner7337ab92007-05-06 00:00:00 +00001365 Value *Callee;
1366 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001367 return Error("Invalid INVOKE record");
1368
Chris Lattner7337ab92007-05-06 00:00:00 +00001369 const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1370 const FunctionType *FTy = !CalleeTy ? 0 :
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001371 dyn_cast<FunctionType>(CalleeTy->getElementType());
1372
1373 // Check that the right number of fixed parameters are here.
Chris Lattner7337ab92007-05-06 00:00:00 +00001374 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1375 Record.size() < OpNum+FTy->getNumParams())
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001376 return Error("Invalid INVOKE record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001377
Chris Lattnera9bb7132007-05-08 05:38:01 +00001378 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1379
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001380 SmallVector<Value*, 16> Ops;
Chris Lattner7337ab92007-05-06 00:00:00 +00001381 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1382 Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1383 if (Ops.back() == 0) return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001384 }
1385
Chris Lattner7337ab92007-05-06 00:00:00 +00001386 if (!FTy->isVarArg()) {
1387 if (Record.size() != OpNum)
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001388 return Error("Invalid INVOKE record");
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001389 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001390 // Read type/value pairs for varargs params.
1391 while (OpNum != Record.size()) {
1392 Value *Op;
1393 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1394 return Error("Invalid INVOKE record");
1395 Ops.push_back(Op);
1396 }
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001397 }
1398
1399 I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
Chris Lattner76520192007-05-03 22:34:03 +00001400 cast<InvokeInst>(I)->setCallingConv(CCInfo);
Chris Lattnerf4c8e522007-05-02 05:46:45 +00001401 break;
1402 }
Chris Lattner231cbcb2007-05-02 04:27:25 +00001403 case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1404 I = new UnwindInst();
1405 break;
1406 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1407 I = new UnreachableInst();
1408 break;
Chris Lattnerabfbf852007-05-06 00:21:25 +00001409 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattner15e6d172007-05-04 19:11:41 +00001410 if (Record.size() < 1 || ((Record.size()-1)&1))
Chris Lattner2a98cca2007-05-03 18:58:09 +00001411 return Error("Invalid PHI record");
1412 const Type *Ty = getTypeByID(Record[0]);
1413 if (!Ty) return Error("Invalid PHI record");
1414
1415 PHINode *PN = new PHINode(Ty);
Chris Lattner15e6d172007-05-04 19:11:41 +00001416 PN->reserveOperandSpace(Record.size()-1);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001417
Chris Lattner15e6d172007-05-04 19:11:41 +00001418 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1419 Value *V = getFnValueByID(Record[1+i], Ty);
1420 BasicBlock *BB = getBasicBlock(Record[2+i]);
Chris Lattner2a98cca2007-05-03 18:58:09 +00001421 if (!V || !BB) return Error("Invalid PHI record");
1422 PN->addIncoming(V, BB);
1423 }
1424 I = PN;
1425 break;
1426 }
1427
1428 case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1429 if (Record.size() < 3)
1430 return Error("Invalid MALLOC record");
1431 const PointerType *Ty =
1432 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1433 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1434 unsigned Align = Record[2];
1435 if (!Ty || !Size) return Error("Invalid MALLOC record");
1436 I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1437 break;
1438 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001439 case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1440 unsigned OpNum = 0;
1441 Value *Op;
1442 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1443 OpNum != Record.size())
Chris Lattner2a98cca2007-05-03 18:58:09 +00001444 return Error("Invalid FREE record");
1445 I = new FreeInst(Op);
1446 break;
1447 }
1448 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1449 if (Record.size() < 3)
1450 return Error("Invalid ALLOCA record");
1451 const PointerType *Ty =
1452 dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1453 Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1454 unsigned Align = Record[2];
1455 if (!Ty || !Size) return Error("Invalid ALLOCA record");
1456 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1457 break;
1458 }
Chris Lattner0579f7f2007-05-03 22:04:19 +00001459 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattner7337ab92007-05-06 00:00:00 +00001460 unsigned OpNum = 0;
1461 Value *Op;
1462 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1463 OpNum+2 != Record.size())
Chris Lattnerabfbf852007-05-06 00:21:25 +00001464 return Error("Invalid LOAD record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001465
1466 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001467 break;
Chris Lattner0579f7f2007-05-03 22:04:19 +00001468 }
Chris Lattnerabfbf852007-05-06 00:21:25 +00001469 case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1470 unsigned OpNum = 0;
1471 Value *Val, *Ptr;
1472 if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1473 getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1474 OpNum+2 != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001475 return Error("Invalid STORE record");
Chris Lattnerabfbf852007-05-06 00:21:25 +00001476
1477 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001478 break;
1479 }
Chris Lattner76520192007-05-03 22:34:03 +00001480 case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
Chris Lattnera9bb7132007-05-08 05:38:01 +00001481 if (Record.size() < 2)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001482 return Error("Invalid CALL record");
Chris Lattner7337ab92007-05-06 00:00:00 +00001483
Chris Lattnera9bb7132007-05-08 05:38:01 +00001484 unsigned CCInfo = Record[1];
1485
1486 unsigned OpNum = 2;
Chris Lattner7337ab92007-05-06 00:00:00 +00001487 Value *Callee;
1488 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1489 return Error("Invalid CALL record");
1490
1491 const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
Chris Lattner0579f7f2007-05-03 22:04:19 +00001492 const FunctionType *FTy = 0;
1493 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
Chris Lattner7337ab92007-05-06 00:00:00 +00001494 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
Chris Lattner0579f7f2007-05-03 22:04:19 +00001495 return Error("Invalid CALL record");
1496
Chris Lattnera9bb7132007-05-08 05:38:01 +00001497 assert(FTy->getParamAttrs() == getParamAttrs(Record[0]));
1498
Chris Lattner0579f7f2007-05-03 22:04:19 +00001499 SmallVector<Value*, 16> Args;
1500 // Read the fixed params.
Chris Lattner7337ab92007-05-06 00:00:00 +00001501 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1502 Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
Chris Lattner0579f7f2007-05-03 22:04:19 +00001503 if (Args.back() == 0) return Error("Invalid CALL record");
1504 }
1505
Chris Lattner0579f7f2007-05-03 22:04:19 +00001506 // Read type/value pairs for varargs params.
Chris Lattner0579f7f2007-05-03 22:04:19 +00001507 if (!FTy->isVarArg()) {
Chris Lattner7337ab92007-05-06 00:00:00 +00001508 if (OpNum != Record.size())
Chris Lattner0579f7f2007-05-03 22:04:19 +00001509 return Error("Invalid CALL record");
1510 } else {
Chris Lattner7337ab92007-05-06 00:00:00 +00001511 while (OpNum != Record.size()) {
1512 Value *Op;
1513 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1514 return Error("Invalid CALL record");
1515 Args.push_back(Op);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001516 }
1517 }
1518
David Greene52eec542007-08-01 03:43:44 +00001519 I = new CallInst(Callee, Args.begin(), Args.end());
Chris Lattner76520192007-05-03 22:34:03 +00001520 cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1521 cast<CallInst>(I)->setTailCall(CCInfo & 1);
Chris Lattner0579f7f2007-05-03 22:04:19 +00001522 break;
1523 }
1524 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1525 if (Record.size() < 3)
1526 return Error("Invalid VAARG record");
1527 const Type *OpTy = getTypeByID(Record[0]);
1528 Value *Op = getFnValueByID(Record[1], OpTy);
1529 const Type *ResTy = getTypeByID(Record[2]);
1530 if (!OpTy || !Op || !ResTy)
1531 return Error("Invalid VAARG record");
1532 I = new VAArgInst(Op, ResTy);
1533 break;
1534 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001535 }
1536
1537 // Add instruction to end of current BB. If there is no current BB, reject
1538 // this file.
1539 if (CurBB == 0) {
1540 delete I;
1541 return Error("Invalid instruction with no BB");
1542 }
1543 CurBB->getInstList().push_back(I);
1544
1545 // If this was a terminator instruction, move to the next block.
1546 if (isa<TerminatorInst>(I)) {
1547 ++CurBBNo;
1548 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1549 }
1550
1551 // Non-void values get registered in the value table for future use.
1552 if (I && I->getType() != Type::VoidTy)
1553 ValueList.AssignValue(I, NextValueNo++);
Chris Lattner980e5aa2007-05-01 05:52:21 +00001554 }
1555
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001556 // Check the function list for unresolved values.
1557 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1558 if (A->getParent() == 0) {
1559 // We found at least one unresolved value. Nuke them all to avoid leaks.
1560 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1561 if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1562 A->replaceAllUsesWith(UndefValue::get(A->getType()));
1563 delete A;
1564 }
1565 }
Chris Lattner35a04702007-05-04 03:50:29 +00001566 return Error("Never resolved value found in function!");
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001567 }
Chris Lattnera7c49aa2007-05-01 07:01:57 +00001568 }
Chris Lattner980e5aa2007-05-01 05:52:21 +00001569
1570 // Trim the value list down to the size it was before we parsed this function.
1571 ValueList.shrinkTo(ModuleValueListSize);
1572 std::vector<BasicBlock*>().swap(FunctionBBs);
1573
Chris Lattner48f84872007-05-01 04:59:48 +00001574 return false;
1575}
1576
Chris Lattnerb348bb82007-05-18 04:02:46 +00001577//===----------------------------------------------------------------------===//
1578// ModuleProvider implementation
1579//===----------------------------------------------------------------------===//
1580
1581
1582bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1583 // If it already is material, ignore the request.
Gabor Greifa99be512007-07-05 17:07:56 +00001584 if (!F->hasNotBeenReadFromBitcode()) return false;
Chris Lattnerb348bb82007-05-18 04:02:46 +00001585
1586 DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1587 DeferredFunctionInfo.find(F);
1588 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1589
1590 // Move the bit stream to the saved position of the deferred function body and
1591 // restore the real linkage type for the function.
1592 Stream.JumpToBit(DFII->second.first);
1593 F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1594
1595 if (ParseFunctionBody(F)) {
1596 if (ErrInfo) *ErrInfo = ErrorString;
1597 return true;
1598 }
Chandler Carruth69940402007-08-04 01:51:18 +00001599
1600 // Upgrade any old intrinsic calls in the function.
1601 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1602 E = UpgradedIntrinsics.end(); I != E; ++I) {
1603 if (I->first != I->second) {
1604 for (Value::use_iterator UI = I->first->use_begin(),
1605 UE = I->first->use_end(); UI != UE; ) {
1606 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1607 UpgradeIntrinsicCall(CI, I->second);
1608 }
1609 }
1610 }
Chris Lattnerb348bb82007-05-18 04:02:46 +00001611
1612 return false;
1613}
1614
1615void BitcodeReader::dematerializeFunction(Function *F) {
1616 // If this function isn't materialized, or if it is a proto, this is a noop.
Gabor Greifa99be512007-07-05 17:07:56 +00001617 if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
Chris Lattnerb348bb82007-05-18 04:02:46 +00001618 return;
1619
1620 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1621
1622 // Just forget the function body, we can remat it later.
1623 F->deleteBody();
1624 F->setLinkage(GlobalValue::GhostLinkage);
1625}
1626
1627
1628Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1629 for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1630 DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1631 ++I) {
1632 Function *F = I->first;
Gabor Greifa99be512007-07-05 17:07:56 +00001633 if (F->hasNotBeenReadFromBitcode() &&
Chris Lattnerb348bb82007-05-18 04:02:46 +00001634 materializeFunction(F, ErrInfo))
1635 return 0;
1636 }
Chandler Carruth69940402007-08-04 01:51:18 +00001637
1638 // Upgrade any intrinsic calls that slipped through (should not happen!) and
1639 // delete the old functions to clean up. We can't do this unless the entire
1640 // module is materialized because there could always be another function body
1641 // with calls to the old function.
1642 for (std::vector<std::pair<Function*, Function*> >::iterator I =
1643 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1644 if (I->first != I->second) {
1645 for (Value::use_iterator UI = I->first->use_begin(),
1646 UE = I->first->use_end(); UI != UE; ) {
1647 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1648 UpgradeIntrinsicCall(CI, I->second);
1649 }
1650 ValueList.replaceUsesOfWith(I->first, I->second);
1651 I->first->eraseFromParent();
1652 }
1653 }
1654 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1655
Chris Lattnerb348bb82007-05-18 04:02:46 +00001656 return TheModule;
1657}
1658
1659
1660/// This method is provided by the parent ModuleProvde class and overriden
1661/// here. It simply releases the module from its provided and frees up our
1662/// state.
1663/// @brief Release our hold on the generated module
1664Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1665 // Since we're losing control of this Module, we must hand it back complete
1666 Module *M = ModuleProvider::releaseModule(ErrInfo);
1667 FreeState();
1668 return M;
1669}
1670
Chris Lattner48f84872007-05-01 04:59:48 +00001671
Chris Lattnerc453f762007-04-29 07:54:31 +00001672//===----------------------------------------------------------------------===//
1673// External interface
1674//===----------------------------------------------------------------------===//
1675
1676/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1677///
1678ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1679 std::string *ErrMsg) {
1680 BitcodeReader *R = new BitcodeReader(Buffer);
1681 if (R->ParseBitcode()) {
1682 if (ErrMsg)
1683 *ErrMsg = R->getErrorString();
1684
1685 // Don't let the BitcodeReader dtor delete 'Buffer'.
1686 R->releaseMemoryBuffer();
1687 delete R;
1688 return 0;
1689 }
1690 return R;
1691}
1692
1693/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1694/// If an error occurs, return null and fill in *ErrMsg if non-null.
1695Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1696 BitcodeReader *R;
1697 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1698 if (!R) return 0;
1699
Chris Lattnerb348bb82007-05-18 04:02:46 +00001700 // Read in the entire module.
1701 Module *M = R->materializeModule(ErrMsg);
1702
1703 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
1704 // there was an error.
Chris Lattnerc453f762007-04-29 07:54:31 +00001705 R->releaseMemoryBuffer();
Chris Lattnerb348bb82007-05-18 04:02:46 +00001706
1707 // If there was no error, tell ModuleProvider not to delete it when its dtor
1708 // is run.
1709 if (M)
1710 M = R->releaseModule(ErrMsg);
1711
Chris Lattnerc453f762007-04-29 07:54:31 +00001712 delete R;
1713 return M;
1714}