1661990f065d918c70e13b7ba314eb4e7afe401d
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Bitcode/ReaderWriter.h"
11 #include "BitcodeReader.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/Bitcode/LLVMBitCodes.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Support/DataStream.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
30 enum {
31   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
32 };
33
34 void BitcodeReader::materializeForwardReferencedFunctions() {
35   while (!BlockAddrFwdRefs.empty()) {
36     Function *F = BlockAddrFwdRefs.begin()->first;
37     F->Materialize();
38   }
39 }
40
41 void BitcodeReader::FreeState() {
42   if (BufferOwned)
43     delete Buffer;
44   Buffer = 0;
45   std::vector<Type*>().swap(TypeList);
46   ValueList.clear();
47   MDValueList.clear();
48
49   std::vector<AttributeSet>().swap(MAttributes);
50   std::vector<BasicBlock*>().swap(FunctionBBs);
51   std::vector<Function*>().swap(FunctionsWithBodies);
52   DeferredFunctionInfo.clear();
53   MDKindMap.clear();
54
55   assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
56 }
57
58 //===----------------------------------------------------------------------===//
59 //  Helper functions to implement forward reference resolution, etc.
60 //===----------------------------------------------------------------------===//
61
62 /// ConvertToString - Convert a string from a record into an std::string, return
63 /// true on failure.
64 template<typename StrTy>
65 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
66                             StrTy &Result) {
67   if (Idx > Record.size())
68     return true;
69
70   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
71     Result += (char)Record[i];
72   return false;
73 }
74
75 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
76   switch (Val) {
77   default: // Map unknown/new linkages to external
78   case 0:  return GlobalValue::ExternalLinkage;
79   case 1:  return GlobalValue::WeakAnyLinkage;
80   case 2:  return GlobalValue::AppendingLinkage;
81   case 3:  return GlobalValue::InternalLinkage;
82   case 4:  return GlobalValue::LinkOnceAnyLinkage;
83   case 5:  return GlobalValue::DLLImportLinkage;
84   case 6:  return GlobalValue::DLLExportLinkage;
85   case 7:  return GlobalValue::ExternalWeakLinkage;
86   case 8:  return GlobalValue::CommonLinkage;
87   case 9:  return GlobalValue::PrivateLinkage;
88   case 10: return GlobalValue::WeakODRLinkage;
89   case 11: return GlobalValue::LinkOnceODRLinkage;
90   case 12: return GlobalValue::AvailableExternallyLinkage;
91   case 13: return GlobalValue::LinkerPrivateLinkage;
92   case 14: return GlobalValue::LinkerPrivateWeakLinkage;
93   case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
94   }
95 }
96
97 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
98   switch (Val) {
99   default: // Map unknown visibilities to default.
100   case 0: return GlobalValue::DefaultVisibility;
101   case 1: return GlobalValue::HiddenVisibility;
102   case 2: return GlobalValue::ProtectedVisibility;
103   }
104 }
105
106 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
107   switch (Val) {
108     case 0: return GlobalVariable::NotThreadLocal;
109     default: // Map unknown non-zero value to general dynamic.
110     case 1: return GlobalVariable::GeneralDynamicTLSModel;
111     case 2: return GlobalVariable::LocalDynamicTLSModel;
112     case 3: return GlobalVariable::InitialExecTLSModel;
113     case 4: return GlobalVariable::LocalExecTLSModel;
114   }
115 }
116
117 static int GetDecodedCastOpcode(unsigned Val) {
118   switch (Val) {
119   default: return -1;
120   case bitc::CAST_TRUNC   : return Instruction::Trunc;
121   case bitc::CAST_ZEXT    : return Instruction::ZExt;
122   case bitc::CAST_SEXT    : return Instruction::SExt;
123   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
124   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
125   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
126   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
127   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
128   case bitc::CAST_FPEXT   : return Instruction::FPExt;
129   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
130   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
131   case bitc::CAST_BITCAST : return Instruction::BitCast;
132   }
133 }
134 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
135   switch (Val) {
136   default: return -1;
137   case bitc::BINOP_ADD:
138     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
139   case bitc::BINOP_SUB:
140     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
141   case bitc::BINOP_MUL:
142     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
143   case bitc::BINOP_UDIV: return Instruction::UDiv;
144   case bitc::BINOP_SDIV:
145     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
146   case bitc::BINOP_UREM: return Instruction::URem;
147   case bitc::BINOP_SREM:
148     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
149   case bitc::BINOP_SHL:  return Instruction::Shl;
150   case bitc::BINOP_LSHR: return Instruction::LShr;
151   case bitc::BINOP_ASHR: return Instruction::AShr;
152   case bitc::BINOP_AND:  return Instruction::And;
153   case bitc::BINOP_OR:   return Instruction::Or;
154   case bitc::BINOP_XOR:  return Instruction::Xor;
155   }
156 }
157
158 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
159   switch (Val) {
160   default: return AtomicRMWInst::BAD_BINOP;
161   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
162   case bitc::RMW_ADD: return AtomicRMWInst::Add;
163   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
164   case bitc::RMW_AND: return AtomicRMWInst::And;
165   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
166   case bitc::RMW_OR: return AtomicRMWInst::Or;
167   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
168   case bitc::RMW_MAX: return AtomicRMWInst::Max;
169   case bitc::RMW_MIN: return AtomicRMWInst::Min;
170   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
171   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
172   }
173 }
174
175 static AtomicOrdering GetDecodedOrdering(unsigned Val) {
176   switch (Val) {
177   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
178   case bitc::ORDERING_UNORDERED: return Unordered;
179   case bitc::ORDERING_MONOTONIC: return Monotonic;
180   case bitc::ORDERING_ACQUIRE: return Acquire;
181   case bitc::ORDERING_RELEASE: return Release;
182   case bitc::ORDERING_ACQREL: return AcquireRelease;
183   default: // Map unknown orderings to sequentially-consistent.
184   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
185   }
186 }
187
188 static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
189   switch (Val) {
190   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
191   default: // Map unknown scopes to cross-thread.
192   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
193   }
194 }
195
196 namespace llvm {
197 namespace {
198   /// @brief A class for maintaining the slot number definition
199   /// as a placeholder for the actual definition for forward constants defs.
200   class ConstantPlaceHolder : public ConstantExpr {
201     void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
202   public:
203     // allocate space for exactly one operand
204     void *operator new(size_t s) {
205       return User::operator new(s, 1);
206     }
207     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
208       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
209       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
210     }
211
212     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
213     static bool classof(const Value *V) {
214       return isa<ConstantExpr>(V) &&
215              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
216     }
217
218
219     /// Provide fast operand accessors
220     //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
221   };
222 }
223
224 // FIXME: can we inherit this from ConstantExpr?
225 template <>
226 struct OperandTraits<ConstantPlaceHolder> :
227   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
228 };
229 }
230
231
232 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
233   if (Idx == size()) {
234     push_back(V);
235     return;
236   }
237
238   if (Idx >= size())
239     resize(Idx+1);
240
241   WeakVH &OldV = ValuePtrs[Idx];
242   if (OldV == 0) {
243     OldV = V;
244     return;
245   }
246
247   // Handle constants and non-constants (e.g. instrs) differently for
248   // efficiency.
249   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
250     ResolveConstants.push_back(std::make_pair(PHC, Idx));
251     OldV = V;
252   } else {
253     // If there was a forward reference to this value, replace it.
254     Value *PrevVal = OldV;
255     OldV->replaceAllUsesWith(V);
256     delete PrevVal;
257   }
258 }
259
260
261 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
262                                                     Type *Ty) {
263   if (Idx >= size())
264     resize(Idx + 1);
265
266   if (Value *V = ValuePtrs[Idx]) {
267     assert(Ty == V->getType() && "Type mismatch in constant table!");
268     return cast<Constant>(V);
269   }
270
271   // Create and return a placeholder, which will later be RAUW'd.
272   Constant *C = new ConstantPlaceHolder(Ty, Context);
273   ValuePtrs[Idx] = C;
274   return C;
275 }
276
277 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
278   if (Idx >= size())
279     resize(Idx + 1);
280
281   if (Value *V = ValuePtrs[Idx]) {
282     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
283     return V;
284   }
285
286   // No type specified, must be invalid reference.
287   if (Ty == 0) return 0;
288
289   // Create and return a placeholder, which will later be RAUW'd.
290   Value *V = new Argument(Ty);
291   ValuePtrs[Idx] = V;
292   return V;
293 }
294
295 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
296 /// resolves any forward references.  The idea behind this is that we sometimes
297 /// get constants (such as large arrays) which reference *many* forward ref
298 /// constants.  Replacing each of these causes a lot of thrashing when
299 /// building/reuniquing the constant.  Instead of doing this, we look at all the
300 /// uses and rewrite all the place holders at once for any constant that uses
301 /// a placeholder.
302 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
303   // Sort the values by-pointer so that they are efficient to look up with a
304   // binary search.
305   std::sort(ResolveConstants.begin(), ResolveConstants.end());
306
307   SmallVector<Constant*, 64> NewOps;
308
309   while (!ResolveConstants.empty()) {
310     Value *RealVal = operator[](ResolveConstants.back().second);
311     Constant *Placeholder = ResolveConstants.back().first;
312     ResolveConstants.pop_back();
313
314     // Loop over all users of the placeholder, updating them to reference the
315     // new value.  If they reference more than one placeholder, update them all
316     // at once.
317     while (!Placeholder->use_empty()) {
318       Value::use_iterator UI = Placeholder->use_begin();
319       User *U = *UI;
320
321       // If the using object isn't uniqued, just update the operands.  This
322       // handles instructions and initializers for global variables.
323       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
324         UI.getUse().set(RealVal);
325         continue;
326       }
327
328       // Otherwise, we have a constant that uses the placeholder.  Replace that
329       // constant with a new constant that has *all* placeholder uses updated.
330       Constant *UserC = cast<Constant>(U);
331       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
332            I != E; ++I) {
333         Value *NewOp;
334         if (!isa<ConstantPlaceHolder>(*I)) {
335           // Not a placeholder reference.
336           NewOp = *I;
337         } else if (*I == Placeholder) {
338           // Common case is that it just references this one placeholder.
339           NewOp = RealVal;
340         } else {
341           // Otherwise, look up the placeholder in ResolveConstants.
342           ResolveConstantsTy::iterator It =
343             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
344                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
345                                                             0));
346           assert(It != ResolveConstants.end() && It->first == *I);
347           NewOp = operator[](It->second);
348         }
349
350         NewOps.push_back(cast<Constant>(NewOp));
351       }
352
353       // Make the new constant.
354       Constant *NewC;
355       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
356         NewC = ConstantArray::get(UserCA->getType(), NewOps);
357       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
358         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
359       } else if (isa<ConstantVector>(UserC)) {
360         NewC = ConstantVector::get(NewOps);
361       } else {
362         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
363         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
364       }
365
366       UserC->replaceAllUsesWith(NewC);
367       UserC->destroyConstant();
368       NewOps.clear();
369     }
370
371     // Update all ValueHandles, they should be the only users at this point.
372     Placeholder->replaceAllUsesWith(RealVal);
373     delete Placeholder;
374   }
375 }
376
377 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
378   if (Idx == size()) {
379     push_back(V);
380     return;
381   }
382
383   if (Idx >= size())
384     resize(Idx+1);
385
386   WeakVH &OldV = MDValuePtrs[Idx];
387   if (OldV == 0) {
388     OldV = V;
389     return;
390   }
391
392   // If there was a forward reference to this value, replace it.
393   MDNode *PrevVal = cast<MDNode>(OldV);
394   OldV->replaceAllUsesWith(V);
395   MDNode::deleteTemporary(PrevVal);
396   // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
397   // value for Idx.
398   MDValuePtrs[Idx] = V;
399 }
400
401 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
402   if (Idx >= size())
403     resize(Idx + 1);
404
405   if (Value *V = MDValuePtrs[Idx]) {
406     assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
407     return V;
408   }
409
410   // Create and return a placeholder, which will later be RAUW'd.
411   Value *V = MDNode::getTemporary(Context, None);
412   MDValuePtrs[Idx] = V;
413   return V;
414 }
415
416 Type *BitcodeReader::getTypeByID(unsigned ID) {
417   // The type table size is always specified correctly.
418   if (ID >= TypeList.size())
419     return 0;
420
421   if (Type *Ty = TypeList[ID])
422     return Ty;
423
424   // If we have a forward reference, the only possible case is when it is to a
425   // named struct.  Just create a placeholder for now.
426   return TypeList[ID] = StructType::create(Context);
427 }
428
429
430 //===----------------------------------------------------------------------===//
431 //  Functions for parsing blocks from the bitcode file
432 //===----------------------------------------------------------------------===//
433
434
435 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
436 /// been decoded from the given integer. This function must stay in sync with
437 /// 'encodeLLVMAttributesForBitcode'.
438 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
439                                            uint64_t EncodedAttrs) {
440   // FIXME: Remove in 4.0.
441
442   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
443   // the bits above 31 down by 11 bits.
444   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
445   assert((!Alignment || isPowerOf2_32(Alignment)) &&
446          "Alignment must be a power of two.");
447
448   if (Alignment)
449     B.addAlignmentAttr(Alignment);
450   B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
451                 (EncodedAttrs & 0xffff));
452 }
453
454 bool BitcodeReader::ParseAttributeBlock() {
455   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
456     return Error("Malformed block record");
457
458   if (!MAttributes.empty())
459     return Error("Multiple PARAMATTR blocks found!");
460
461   SmallVector<uint64_t, 64> Record;
462
463   SmallVector<AttributeSet, 8> Attrs;
464
465   // Read all the records.
466   while (1) {
467     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
468
469     switch (Entry.Kind) {
470     case BitstreamEntry::SubBlock: // Handled for us already.
471     case BitstreamEntry::Error:
472       return Error("Error at end of PARAMATTR block");
473     case BitstreamEntry::EndBlock:
474       return false;
475     case BitstreamEntry::Record:
476       // The interesting case.
477       break;
478     }
479
480     // Read a record.
481     Record.clear();
482     switch (Stream.readRecord(Entry.ID, Record)) {
483     default:  // Default behavior: ignore.
484       break;
485     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
486       // FIXME: Remove in 4.0.
487       if (Record.size() & 1)
488         return Error("Invalid ENTRY record");
489
490       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
491         AttrBuilder B;
492         decodeLLVMAttributesForBitcode(B, Record[i+1]);
493         Attrs.push_back(AttributeSet::get(Context, Record[i], B));
494       }
495
496       MAttributes.push_back(AttributeSet::get(Context, Attrs));
497       Attrs.clear();
498       break;
499     }
500     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
501       for (unsigned i = 0, e = Record.size(); i != e; ++i)
502         Attrs.push_back(MAttributeGroups[Record[i]]);
503
504       MAttributes.push_back(AttributeSet::get(Context, Attrs));
505       Attrs.clear();
506       break;
507     }
508     }
509   }
510 }
511
512 bool BitcodeReader::ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
513   switch (Code) {
514   case bitc::ATTR_KIND_ALIGNMENT:
515     *Kind = Attribute::Alignment;
516     return false;
517   case bitc::ATTR_KIND_ALWAYS_INLINE:
518     *Kind = Attribute::AlwaysInline;
519     return false;
520   case bitc::ATTR_KIND_BUILTIN:
521     *Kind = Attribute::Builtin;
522     return false;
523   case bitc::ATTR_KIND_BY_VAL:
524     *Kind = Attribute::ByVal;
525     return false;
526   case bitc::ATTR_KIND_COLD:
527     *Kind = Attribute::Cold;
528     return false;
529   case bitc::ATTR_KIND_INLINE_HINT:
530     *Kind = Attribute::InlineHint;
531     return false;
532   case bitc::ATTR_KIND_IN_REG:
533     *Kind = Attribute::InReg;
534     return false;
535   case bitc::ATTR_KIND_MIN_SIZE:
536     *Kind = Attribute::MinSize;
537     return false;
538   case bitc::ATTR_KIND_NAKED:
539     *Kind = Attribute::Naked;
540     return false;
541   case bitc::ATTR_KIND_NEST:
542     *Kind = Attribute::Nest;
543     return false;
544   case bitc::ATTR_KIND_NO_ALIAS:
545     *Kind = Attribute::NoAlias;
546     return false;
547   case bitc::ATTR_KIND_NO_BUILTIN:
548     *Kind = Attribute::NoBuiltin;
549     return false;
550   case bitc::ATTR_KIND_NO_CAPTURE:
551     *Kind = Attribute::NoCapture;
552     return false;
553   case bitc::ATTR_KIND_NO_DUPLICATE:
554     *Kind = Attribute::NoDuplicate;
555     return false;
556   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
557     *Kind = Attribute::NoImplicitFloat;
558     return false;
559   case bitc::ATTR_KIND_NO_INLINE:
560     *Kind = Attribute::NoInline;
561     return false;
562   case bitc::ATTR_KIND_NON_LAZY_BIND:
563     *Kind = Attribute::NonLazyBind;
564     return false;
565   case bitc::ATTR_KIND_NO_RED_ZONE:
566     *Kind = Attribute::NoRedZone;
567     return false;
568   case bitc::ATTR_KIND_NO_RETURN:
569     *Kind = Attribute::NoReturn;
570     return false;
571   case bitc::ATTR_KIND_NO_UNWIND:
572     *Kind = Attribute::NoUnwind;
573     return false;
574   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
575     *Kind = Attribute::OptimizeForSize;
576     return false;
577   case bitc::ATTR_KIND_OPTIMIZE_NONE:
578     *Kind = Attribute::OptimizeNone;
579     return false;
580   case bitc::ATTR_KIND_READ_NONE:
581     *Kind = Attribute::ReadNone;
582     return false;
583   case bitc::ATTR_KIND_READ_ONLY:
584     *Kind = Attribute::ReadOnly;
585     return false;
586   case bitc::ATTR_KIND_RETURNED:
587     *Kind = Attribute::Returned;
588     return false;
589   case bitc::ATTR_KIND_RETURNS_TWICE:
590     *Kind = Attribute::ReturnsTwice;
591     return false;
592   case bitc::ATTR_KIND_S_EXT:
593     *Kind = Attribute::SExt;
594     return false;
595   case bitc::ATTR_KIND_STACK_ALIGNMENT:
596     *Kind = Attribute::StackAlignment;
597     return false;
598   case bitc::ATTR_KIND_STACK_PROTECT:
599     *Kind = Attribute::StackProtect;
600     return false;
601   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
602     *Kind = Attribute::StackProtectReq;
603     return false;
604   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
605     *Kind = Attribute::StackProtectStrong;
606     return false;
607   case bitc::ATTR_KIND_STRUCT_RET:
608     *Kind = Attribute::StructRet;
609     return false;
610   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
611     *Kind = Attribute::SanitizeAddress;
612     return false;
613   case bitc::ATTR_KIND_SANITIZE_THREAD:
614     *Kind = Attribute::SanitizeThread;
615     return false;
616   case bitc::ATTR_KIND_SANITIZE_MEMORY:
617     *Kind = Attribute::SanitizeMemory;
618     return false;
619   case bitc::ATTR_KIND_UW_TABLE:
620     *Kind = Attribute::UWTable;
621     return false;
622   case bitc::ATTR_KIND_Z_EXT:
623     *Kind = Attribute::ZExt;
624     return false;
625   default:
626     return Error("Unknown attribute kind");
627   }
628 }
629
630 bool BitcodeReader::ParseAttributeGroupBlock() {
631   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
632     return Error("Malformed block record");
633
634   if (!MAttributeGroups.empty())
635     return Error("Multiple PARAMATTR_GROUP blocks found!");
636
637   SmallVector<uint64_t, 64> Record;
638
639   // Read all the records.
640   while (1) {
641     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
642
643     switch (Entry.Kind) {
644     case BitstreamEntry::SubBlock: // Handled for us already.
645     case BitstreamEntry::Error:
646       return Error("Error at end of PARAMATTR_GROUP block");
647     case BitstreamEntry::EndBlock:
648       return false;
649     case BitstreamEntry::Record:
650       // The interesting case.
651       break;
652     }
653
654     // Read a record.
655     Record.clear();
656     switch (Stream.readRecord(Entry.ID, Record)) {
657     default:  // Default behavior: ignore.
658       break;
659     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
660       if (Record.size() < 3)
661         return Error("Invalid ENTRY record");
662
663       uint64_t GrpID = Record[0];
664       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
665
666       AttrBuilder B;
667       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
668         if (Record[i] == 0) {        // Enum attribute
669           Attribute::AttrKind Kind;
670           if (ParseAttrKind(Record[++i], &Kind))
671             return true;
672
673           B.addAttribute(Kind);
674         } else if (Record[i] == 1) { // Align attribute
675           Attribute::AttrKind Kind;
676           if (ParseAttrKind(Record[++i], &Kind))
677             return true;
678           if (Kind == Attribute::Alignment)
679             B.addAlignmentAttr(Record[++i]);
680           else
681             B.addStackAlignmentAttr(Record[++i]);
682         } else {                     // String attribute
683           assert((Record[i] == 3 || Record[i] == 4) &&
684                  "Invalid attribute group entry");
685           bool HasValue = (Record[i++] == 4);
686           SmallString<64> KindStr;
687           SmallString<64> ValStr;
688
689           while (Record[i] != 0 && i != e)
690             KindStr += Record[i++];
691           assert(Record[i] == 0 && "Kind string not null terminated");
692
693           if (HasValue) {
694             // Has a value associated with it.
695             ++i; // Skip the '0' that terminates the "kind" string.
696             while (Record[i] != 0 && i != e)
697               ValStr += Record[i++];
698             assert(Record[i] == 0 && "Value string not null terminated");
699           }
700
701           B.addAttribute(KindStr.str(), ValStr.str());
702         }
703       }
704
705       MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
706       break;
707     }
708     }
709   }
710 }
711
712 bool BitcodeReader::ParseTypeTable() {
713   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
714     return Error("Malformed block record");
715
716   return ParseTypeTableBody();
717 }
718
719 bool BitcodeReader::ParseTypeTableBody() {
720   if (!TypeList.empty())
721     return Error("Multiple TYPE_BLOCKs found!");
722
723   SmallVector<uint64_t, 64> Record;
724   unsigned NumRecords = 0;
725
726   SmallString<64> TypeName;
727
728   // Read all the records for this type table.
729   while (1) {
730     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
731
732     switch (Entry.Kind) {
733     case BitstreamEntry::SubBlock: // Handled for us already.
734     case BitstreamEntry::Error:
735       Error("Error in the type table block");
736       return true;
737     case BitstreamEntry::EndBlock:
738       if (NumRecords != TypeList.size())
739         return Error("Invalid type forward reference in TYPE_BLOCK");
740       return false;
741     case BitstreamEntry::Record:
742       // The interesting case.
743       break;
744     }
745
746     // Read a record.
747     Record.clear();
748     Type *ResultTy = 0;
749     switch (Stream.readRecord(Entry.ID, Record)) {
750     default: return Error("unknown type in type table");
751     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
752       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
753       // type list.  This allows us to reserve space.
754       if (Record.size() < 1)
755         return Error("Invalid TYPE_CODE_NUMENTRY record");
756       TypeList.resize(Record[0]);
757       continue;
758     case bitc::TYPE_CODE_VOID:      // VOID
759       ResultTy = Type::getVoidTy(Context);
760       break;
761     case bitc::TYPE_CODE_HALF:     // HALF
762       ResultTy = Type::getHalfTy(Context);
763       break;
764     case bitc::TYPE_CODE_FLOAT:     // FLOAT
765       ResultTy = Type::getFloatTy(Context);
766       break;
767     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
768       ResultTy = Type::getDoubleTy(Context);
769       break;
770     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
771       ResultTy = Type::getX86_FP80Ty(Context);
772       break;
773     case bitc::TYPE_CODE_FP128:     // FP128
774       ResultTy = Type::getFP128Ty(Context);
775       break;
776     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
777       ResultTy = Type::getPPC_FP128Ty(Context);
778       break;
779     case bitc::TYPE_CODE_LABEL:     // LABEL
780       ResultTy = Type::getLabelTy(Context);
781       break;
782     case bitc::TYPE_CODE_METADATA:  // METADATA
783       ResultTy = Type::getMetadataTy(Context);
784       break;
785     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
786       ResultTy = Type::getX86_MMXTy(Context);
787       break;
788     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
789       if (Record.size() < 1)
790         return Error("Invalid Integer type record");
791
792       ResultTy = IntegerType::get(Context, Record[0]);
793       break;
794     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
795                                     //          [pointee type, address space]
796       if (Record.size() < 1)
797         return Error("Invalid POINTER type record");
798       unsigned AddressSpace = 0;
799       if (Record.size() == 2)
800         AddressSpace = Record[1];
801       ResultTy = getTypeByID(Record[0]);
802       if (ResultTy == 0) return Error("invalid element type in pointer type");
803       ResultTy = PointerType::get(ResultTy, AddressSpace);
804       break;
805     }
806     case bitc::TYPE_CODE_FUNCTION_OLD: {
807       // FIXME: attrid is dead, remove it in LLVM 4.0
808       // FUNCTION: [vararg, attrid, retty, paramty x N]
809       if (Record.size() < 3)
810         return Error("Invalid FUNCTION type record");
811       SmallVector<Type*, 8> ArgTys;
812       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
813         if (Type *T = getTypeByID(Record[i]))
814           ArgTys.push_back(T);
815         else
816           break;
817       }
818
819       ResultTy = getTypeByID(Record[2]);
820       if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
821         return Error("invalid type in function type");
822
823       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
824       break;
825     }
826     case bitc::TYPE_CODE_FUNCTION: {
827       // FUNCTION: [vararg, retty, paramty x N]
828       if (Record.size() < 2)
829         return Error("Invalid FUNCTION type record");
830       SmallVector<Type*, 8> ArgTys;
831       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
832         if (Type *T = getTypeByID(Record[i]))
833           ArgTys.push_back(T);
834         else
835           break;
836       }
837
838       ResultTy = getTypeByID(Record[1]);
839       if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
840         return Error("invalid type in function type");
841
842       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
843       break;
844     }
845     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
846       if (Record.size() < 1)
847         return Error("Invalid STRUCT type record");
848       SmallVector<Type*, 8> EltTys;
849       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
850         if (Type *T = getTypeByID(Record[i]))
851           EltTys.push_back(T);
852         else
853           break;
854       }
855       if (EltTys.size() != Record.size()-1)
856         return Error("invalid type in struct type");
857       ResultTy = StructType::get(Context, EltTys, Record[0]);
858       break;
859     }
860     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
861       if (ConvertToString(Record, 0, TypeName))
862         return Error("Invalid STRUCT_NAME record");
863       continue;
864
865     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
866       if (Record.size() < 1)
867         return Error("Invalid STRUCT type record");
868
869       if (NumRecords >= TypeList.size())
870         return Error("invalid TYPE table");
871
872       // Check to see if this was forward referenced, if so fill in the temp.
873       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
874       if (Res) {
875         Res->setName(TypeName);
876         TypeList[NumRecords] = 0;
877       } else  // Otherwise, create a new struct.
878         Res = StructType::create(Context, TypeName);
879       TypeName.clear();
880
881       SmallVector<Type*, 8> EltTys;
882       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
883         if (Type *T = getTypeByID(Record[i]))
884           EltTys.push_back(T);
885         else
886           break;
887       }
888       if (EltTys.size() != Record.size()-1)
889         return Error("invalid STRUCT type record");
890       Res->setBody(EltTys, Record[0]);
891       ResultTy = Res;
892       break;
893     }
894     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
895       if (Record.size() != 1)
896         return Error("Invalid OPAQUE type record");
897
898       if (NumRecords >= TypeList.size())
899         return Error("invalid TYPE table");
900
901       // Check to see if this was forward referenced, if so fill in the temp.
902       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
903       if (Res) {
904         Res->setName(TypeName);
905         TypeList[NumRecords] = 0;
906       } else  // Otherwise, create a new struct with no body.
907         Res = StructType::create(Context, TypeName);
908       TypeName.clear();
909       ResultTy = Res;
910       break;
911     }
912     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
913       if (Record.size() < 2)
914         return Error("Invalid ARRAY type record");
915       if ((ResultTy = getTypeByID(Record[1])))
916         ResultTy = ArrayType::get(ResultTy, Record[0]);
917       else
918         return Error("Invalid ARRAY type element");
919       break;
920     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
921       if (Record.size() < 2)
922         return Error("Invalid VECTOR type record");
923       if ((ResultTy = getTypeByID(Record[1])))
924         ResultTy = VectorType::get(ResultTy, Record[0]);
925       else
926         return Error("Invalid ARRAY type element");
927       break;
928     }
929
930     if (NumRecords >= TypeList.size())
931       return Error("invalid TYPE table");
932     assert(ResultTy && "Didn't read a type?");
933     assert(TypeList[NumRecords] == 0 && "Already read type?");
934     TypeList[NumRecords++] = ResultTy;
935   }
936 }
937
938 bool BitcodeReader::ParseValueSymbolTable() {
939   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
940     return Error("Malformed block record");
941
942   SmallVector<uint64_t, 64> Record;
943
944   // Read all the records for this value table.
945   SmallString<128> ValueName;
946   while (1) {
947     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
948
949     switch (Entry.Kind) {
950     case BitstreamEntry::SubBlock: // Handled for us already.
951     case BitstreamEntry::Error:
952       return Error("malformed value symbol table block");
953     case BitstreamEntry::EndBlock:
954       return false;
955     case BitstreamEntry::Record:
956       // The interesting case.
957       break;
958     }
959
960     // Read a record.
961     Record.clear();
962     switch (Stream.readRecord(Entry.ID, Record)) {
963     default:  // Default behavior: unknown type.
964       break;
965     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
966       if (ConvertToString(Record, 1, ValueName))
967         return Error("Invalid VST_ENTRY record");
968       unsigned ValueID = Record[0];
969       if (ValueID >= ValueList.size())
970         return Error("Invalid Value ID in VST_ENTRY record");
971       Value *V = ValueList[ValueID];
972
973       V->setName(StringRef(ValueName.data(), ValueName.size()));
974       ValueName.clear();
975       break;
976     }
977     case bitc::VST_CODE_BBENTRY: {
978       if (ConvertToString(Record, 1, ValueName))
979         return Error("Invalid VST_BBENTRY record");
980       BasicBlock *BB = getBasicBlock(Record[0]);
981       if (BB == 0)
982         return Error("Invalid BB ID in VST_BBENTRY record");
983
984       BB->setName(StringRef(ValueName.data(), ValueName.size()));
985       ValueName.clear();
986       break;
987     }
988     }
989   }
990 }
991
992 bool BitcodeReader::ParseMetadata() {
993   unsigned NextMDValueNo = MDValueList.size();
994
995   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
996     return Error("Malformed block record");
997
998   SmallVector<uint64_t, 64> Record;
999
1000   // Read all the records.
1001   while (1) {
1002     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1003
1004     switch (Entry.Kind) {
1005     case BitstreamEntry::SubBlock: // Handled for us already.
1006     case BitstreamEntry::Error:
1007       Error("malformed metadata block");
1008       return true;
1009     case BitstreamEntry::EndBlock:
1010       return false;
1011     case BitstreamEntry::Record:
1012       // The interesting case.
1013       break;
1014     }
1015
1016     bool IsFunctionLocal = false;
1017     // Read a record.
1018     Record.clear();
1019     unsigned Code = Stream.readRecord(Entry.ID, Record);
1020     switch (Code) {
1021     default:  // Default behavior: ignore.
1022       break;
1023     case bitc::METADATA_NAME: {
1024       // Read name of the named metadata.
1025       SmallString<8> Name(Record.begin(), Record.end());
1026       Record.clear();
1027       Code = Stream.ReadCode();
1028
1029       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1030       unsigned NextBitCode = Stream.readRecord(Code, Record);
1031       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1032
1033       // Read named metadata elements.
1034       unsigned Size = Record.size();
1035       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1036       for (unsigned i = 0; i != Size; ++i) {
1037         MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1038         if (MD == 0)
1039           return Error("Malformed metadata record");
1040         NMD->addOperand(MD);
1041       }
1042       break;
1043     }
1044     case bitc::METADATA_FN_NODE:
1045       IsFunctionLocal = true;
1046       // fall-through
1047     case bitc::METADATA_NODE: {
1048       if (Record.size() % 2 == 1)
1049         return Error("Invalid METADATA_NODE record");
1050
1051       unsigned Size = Record.size();
1052       SmallVector<Value*, 8> Elts;
1053       for (unsigned i = 0; i != Size; i += 2) {
1054         Type *Ty = getTypeByID(Record[i]);
1055         if (!Ty) return Error("Invalid METADATA_NODE record");
1056         if (Ty->isMetadataTy())
1057           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1058         else if (!Ty->isVoidTy())
1059           Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1060         else
1061           Elts.push_back(NULL);
1062       }
1063       Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1064       IsFunctionLocal = false;
1065       MDValueList.AssignValue(V, NextMDValueNo++);
1066       break;
1067     }
1068     case bitc::METADATA_STRING: {
1069       SmallString<8> String(Record.begin(), Record.end());
1070       Value *V = MDString::get(Context, String);
1071       MDValueList.AssignValue(V, NextMDValueNo++);
1072       break;
1073     }
1074     case bitc::METADATA_KIND: {
1075       if (Record.size() < 2)
1076         return Error("Invalid METADATA_KIND record");
1077
1078       unsigned Kind = Record[0];
1079       SmallString<8> Name(Record.begin()+1, Record.end());
1080
1081       unsigned NewKind = TheModule->getMDKindID(Name.str());
1082       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1083         return Error("Conflicting METADATA_KIND records");
1084       break;
1085     }
1086     }
1087   }
1088 }
1089
1090 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1091 /// the LSB for dense VBR encoding.
1092 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1093   if ((V & 1) == 0)
1094     return V >> 1;
1095   if (V != 1)
1096     return -(V >> 1);
1097   // There is no such thing as -0 with integers.  "-0" really means MININT.
1098   return 1ULL << 63;
1099 }
1100
1101 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1102 /// values and aliases that we can.
1103 bool BitcodeReader::ResolveGlobalAndAliasInits() {
1104   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1105   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1106   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1107
1108   GlobalInitWorklist.swap(GlobalInits);
1109   AliasInitWorklist.swap(AliasInits);
1110   FunctionPrefixWorklist.swap(FunctionPrefixes);
1111
1112   while (!GlobalInitWorklist.empty()) {
1113     unsigned ValID = GlobalInitWorklist.back().second;
1114     if (ValID >= ValueList.size()) {
1115       // Not ready to resolve this yet, it requires something later in the file.
1116       GlobalInits.push_back(GlobalInitWorklist.back());
1117     } else {
1118       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1119         GlobalInitWorklist.back().first->setInitializer(C);
1120       else
1121         return Error("Global variable initializer is not a constant!");
1122     }
1123     GlobalInitWorklist.pop_back();
1124   }
1125
1126   while (!AliasInitWorklist.empty()) {
1127     unsigned ValID = AliasInitWorklist.back().second;
1128     if (ValID >= ValueList.size()) {
1129       AliasInits.push_back(AliasInitWorklist.back());
1130     } else {
1131       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1132         AliasInitWorklist.back().first->setAliasee(C);
1133       else
1134         return Error("Alias initializer is not a constant!");
1135     }
1136     AliasInitWorklist.pop_back();
1137   }
1138
1139   while (!FunctionPrefixWorklist.empty()) {
1140     unsigned ValID = FunctionPrefixWorklist.back().second;
1141     if (ValID >= ValueList.size()) {
1142       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1143     } else {
1144       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1145         FunctionPrefixWorklist.back().first->setPrefixData(C);
1146       else
1147         return Error("Function prefix is not a constant!");
1148     }
1149     FunctionPrefixWorklist.pop_back();
1150   }
1151
1152   return false;
1153 }
1154
1155 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1156   SmallVector<uint64_t, 8> Words(Vals.size());
1157   std::transform(Vals.begin(), Vals.end(), Words.begin(),
1158                  BitcodeReader::decodeSignRotatedValue);
1159
1160   return APInt(TypeBits, Words);
1161 }
1162
1163 bool BitcodeReader::ParseConstants() {
1164   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1165     return Error("Malformed block record");
1166
1167   SmallVector<uint64_t, 64> Record;
1168
1169   // Read all the records for this value table.
1170   Type *CurTy = Type::getInt32Ty(Context);
1171   unsigned NextCstNo = ValueList.size();
1172   while (1) {
1173     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1174
1175     switch (Entry.Kind) {
1176     case BitstreamEntry::SubBlock: // Handled for us already.
1177     case BitstreamEntry::Error:
1178       return Error("malformed block record in AST file");
1179     case BitstreamEntry::EndBlock:
1180       if (NextCstNo != ValueList.size())
1181         return Error("Invalid constant reference!");
1182
1183       // Once all the constants have been read, go through and resolve forward
1184       // references.
1185       ValueList.ResolveConstantForwardRefs();
1186       return false;
1187     case BitstreamEntry::Record:
1188       // The interesting case.
1189       break;
1190     }
1191
1192     // Read a record.
1193     Record.clear();
1194     Value *V = 0;
1195     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1196     switch (BitCode) {
1197     default:  // Default behavior: unknown constant
1198     case bitc::CST_CODE_UNDEF:     // UNDEF
1199       V = UndefValue::get(CurTy);
1200       break;
1201     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1202       if (Record.empty())
1203         return Error("Malformed CST_SETTYPE record");
1204       if (Record[0] >= TypeList.size())
1205         return Error("Invalid Type ID in CST_SETTYPE record");
1206       CurTy = TypeList[Record[0]];
1207       continue;  // Skip the ValueList manipulation.
1208     case bitc::CST_CODE_NULL:      // NULL
1209       V = Constant::getNullValue(CurTy);
1210       break;
1211     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1212       if (!CurTy->isIntegerTy() || Record.empty())
1213         return Error("Invalid CST_INTEGER record");
1214       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1215       break;
1216     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1217       if (!CurTy->isIntegerTy() || Record.empty())
1218         return Error("Invalid WIDE_INTEGER record");
1219
1220       APInt VInt = ReadWideAPInt(Record,
1221                                  cast<IntegerType>(CurTy)->getBitWidth());
1222       V = ConstantInt::get(Context, VInt);
1223
1224       break;
1225     }
1226     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1227       if (Record.empty())
1228         return Error("Invalid FLOAT record");
1229       if (CurTy->isHalfTy())
1230         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1231                                              APInt(16, (uint16_t)Record[0])));
1232       else if (CurTy->isFloatTy())
1233         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1234                                              APInt(32, (uint32_t)Record[0])));
1235       else if (CurTy->isDoubleTy())
1236         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1237                                              APInt(64, Record[0])));
1238       else if (CurTy->isX86_FP80Ty()) {
1239         // Bits are not stored the same way as a normal i80 APInt, compensate.
1240         uint64_t Rearrange[2];
1241         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1242         Rearrange[1] = Record[0] >> 48;
1243         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1244                                              APInt(80, Rearrange)));
1245       } else if (CurTy->isFP128Ty())
1246         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1247                                              APInt(128, Record)));
1248       else if (CurTy->isPPC_FP128Ty())
1249         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1250                                              APInt(128, Record)));
1251       else
1252         V = UndefValue::get(CurTy);
1253       break;
1254     }
1255
1256     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1257       if (Record.empty())
1258         return Error("Invalid CST_AGGREGATE record");
1259
1260       unsigned Size = Record.size();
1261       SmallVector<Constant*, 16> Elts;
1262
1263       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1264         for (unsigned i = 0; i != Size; ++i)
1265           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1266                                                      STy->getElementType(i)));
1267         V = ConstantStruct::get(STy, Elts);
1268       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1269         Type *EltTy = ATy->getElementType();
1270         for (unsigned i = 0; i != Size; ++i)
1271           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1272         V = ConstantArray::get(ATy, Elts);
1273       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1274         Type *EltTy = VTy->getElementType();
1275         for (unsigned i = 0; i != Size; ++i)
1276           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1277         V = ConstantVector::get(Elts);
1278       } else {
1279         V = UndefValue::get(CurTy);
1280       }
1281       break;
1282     }
1283     case bitc::CST_CODE_STRING:    // STRING: [values]
1284     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1285       if (Record.empty())
1286         return Error("Invalid CST_STRING record");
1287
1288       SmallString<16> Elts(Record.begin(), Record.end());
1289       V = ConstantDataArray::getString(Context, Elts,
1290                                        BitCode == bitc::CST_CODE_CSTRING);
1291       break;
1292     }
1293     case bitc::CST_CODE_DATA: {// DATA: [n x value]
1294       if (Record.empty())
1295         return Error("Invalid CST_DATA record");
1296
1297       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1298       unsigned Size = Record.size();
1299
1300       if (EltTy->isIntegerTy(8)) {
1301         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1302         if (isa<VectorType>(CurTy))
1303           V = ConstantDataVector::get(Context, Elts);
1304         else
1305           V = ConstantDataArray::get(Context, Elts);
1306       } else if (EltTy->isIntegerTy(16)) {
1307         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1308         if (isa<VectorType>(CurTy))
1309           V = ConstantDataVector::get(Context, Elts);
1310         else
1311           V = ConstantDataArray::get(Context, Elts);
1312       } else if (EltTy->isIntegerTy(32)) {
1313         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1314         if (isa<VectorType>(CurTy))
1315           V = ConstantDataVector::get(Context, Elts);
1316         else
1317           V = ConstantDataArray::get(Context, Elts);
1318       } else if (EltTy->isIntegerTy(64)) {
1319         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1320         if (isa<VectorType>(CurTy))
1321           V = ConstantDataVector::get(Context, Elts);
1322         else
1323           V = ConstantDataArray::get(Context, Elts);
1324       } else if (EltTy->isFloatTy()) {
1325         SmallVector<float, 16> Elts(Size);
1326         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1327         if (isa<VectorType>(CurTy))
1328           V = ConstantDataVector::get(Context, Elts);
1329         else
1330           V = ConstantDataArray::get(Context, Elts);
1331       } else if (EltTy->isDoubleTy()) {
1332         SmallVector<double, 16> Elts(Size);
1333         std::transform(Record.begin(), Record.end(), Elts.begin(),
1334                        BitsToDouble);
1335         if (isa<VectorType>(CurTy))
1336           V = ConstantDataVector::get(Context, Elts);
1337         else
1338           V = ConstantDataArray::get(Context, Elts);
1339       } else {
1340         return Error("Unknown element type in CE_DATA");
1341       }
1342       break;
1343     }
1344
1345     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1346       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1347       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1348       if (Opc < 0) {
1349         V = UndefValue::get(CurTy);  // Unknown binop.
1350       } else {
1351         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1352         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1353         unsigned Flags = 0;
1354         if (Record.size() >= 4) {
1355           if (Opc == Instruction::Add ||
1356               Opc == Instruction::Sub ||
1357               Opc == Instruction::Mul ||
1358               Opc == Instruction::Shl) {
1359             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1360               Flags |= OverflowingBinaryOperator::NoSignedWrap;
1361             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1362               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1363           } else if (Opc == Instruction::SDiv ||
1364                      Opc == Instruction::UDiv ||
1365                      Opc == Instruction::LShr ||
1366                      Opc == Instruction::AShr) {
1367             if (Record[3] & (1 << bitc::PEO_EXACT))
1368               Flags |= SDivOperator::IsExact;
1369           }
1370         }
1371         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1372       }
1373       break;
1374     }
1375     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1376       if (Record.size() < 3) return Error("Invalid CE_CAST record");
1377       int Opc = GetDecodedCastOpcode(Record[0]);
1378       if (Opc < 0) {
1379         V = UndefValue::get(CurTy);  // Unknown cast.
1380       } else {
1381         Type *OpTy = getTypeByID(Record[1]);
1382         if (!OpTy) return Error("Invalid CE_CAST record");
1383         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1384         V = ConstantExpr::getCast(Opc, Op, CurTy);
1385       }
1386       break;
1387     }
1388     case bitc::CST_CODE_CE_INBOUNDS_GEP:
1389     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1390       if (Record.size() & 1) return Error("Invalid CE_GEP record");
1391       SmallVector<Constant*, 16> Elts;
1392       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1393         Type *ElTy = getTypeByID(Record[i]);
1394         if (!ElTy) return Error("Invalid CE_GEP record");
1395         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1396       }
1397       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1398       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1399                                          BitCode ==
1400                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
1401       break;
1402     }
1403     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
1404       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1405
1406       Type *SelectorTy = Type::getInt1Ty(Context);
1407
1408       // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1409       // vector. Otherwise, it must be a single bit.
1410       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1411         SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1412                                      VTy->getNumElements());
1413
1414       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1415                                                               SelectorTy),
1416                                   ValueList.getConstantFwdRef(Record[1],CurTy),
1417                                   ValueList.getConstantFwdRef(Record[2],CurTy));
1418       break;
1419     }
1420     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1421       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1422       VectorType *OpTy =
1423         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1424       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1425       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1426       Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1427                                                   Type::getInt32Ty(Context));
1428       V = ConstantExpr::getExtractElement(Op0, Op1);
1429       break;
1430     }
1431     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1432       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1433       if (Record.size() < 3 || OpTy == 0)
1434         return Error("Invalid CE_INSERTELT record");
1435       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1436       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1437                                                   OpTy->getElementType());
1438       Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1439                                                   Type::getInt32Ty(Context));
1440       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1441       break;
1442     }
1443     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1444       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1445       if (Record.size() < 3 || OpTy == 0)
1446         return Error("Invalid CE_SHUFFLEVEC record");
1447       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1448       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1449       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1450                                                  OpTy->getNumElements());
1451       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1452       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1453       break;
1454     }
1455     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1456       VectorType *RTy = dyn_cast<VectorType>(CurTy);
1457       VectorType *OpTy =
1458         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1459       if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1460         return Error("Invalid CE_SHUFVEC_EX record");
1461       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1462       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1463       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1464                                                  RTy->getNumElements());
1465       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1466       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1467       break;
1468     }
1469     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1470       if (Record.size() < 4) return Error("Invalid CE_CMP record");
1471       Type *OpTy = getTypeByID(Record[0]);
1472       if (OpTy == 0) return Error("Invalid CE_CMP record");
1473       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1474       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1475
1476       if (OpTy->isFPOrFPVectorTy())
1477         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1478       else
1479         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1480       break;
1481     }
1482     // This maintains backward compatibility, pre-asm dialect keywords.
1483     // FIXME: Remove with the 4.0 release.
1484     case bitc::CST_CODE_INLINEASM_OLD: {
1485       if (Record.size() < 2) return Error("Invalid INLINEASM record");
1486       std::string AsmStr, ConstrStr;
1487       bool HasSideEffects = Record[0] & 1;
1488       bool IsAlignStack = Record[0] >> 1;
1489       unsigned AsmStrSize = Record[1];
1490       if (2+AsmStrSize >= Record.size())
1491         return Error("Invalid INLINEASM record");
1492       unsigned ConstStrSize = Record[2+AsmStrSize];
1493       if (3+AsmStrSize+ConstStrSize > Record.size())
1494         return Error("Invalid INLINEASM record");
1495
1496       for (unsigned i = 0; i != AsmStrSize; ++i)
1497         AsmStr += (char)Record[2+i];
1498       for (unsigned i = 0; i != ConstStrSize; ++i)
1499         ConstrStr += (char)Record[3+AsmStrSize+i];
1500       PointerType *PTy = cast<PointerType>(CurTy);
1501       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1502                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1503       break;
1504     }
1505     // This version adds support for the asm dialect keywords (e.g.,
1506     // inteldialect).
1507     case bitc::CST_CODE_INLINEASM: {
1508       if (Record.size() < 2) return Error("Invalid INLINEASM record");
1509       std::string AsmStr, ConstrStr;
1510       bool HasSideEffects = Record[0] & 1;
1511       bool IsAlignStack = (Record[0] >> 1) & 1;
1512       unsigned AsmDialect = Record[0] >> 2;
1513       unsigned AsmStrSize = Record[1];
1514       if (2+AsmStrSize >= Record.size())
1515         return Error("Invalid INLINEASM record");
1516       unsigned ConstStrSize = Record[2+AsmStrSize];
1517       if (3+AsmStrSize+ConstStrSize > Record.size())
1518         return Error("Invalid INLINEASM record");
1519
1520       for (unsigned i = 0; i != AsmStrSize; ++i)
1521         AsmStr += (char)Record[2+i];
1522       for (unsigned i = 0; i != ConstStrSize; ++i)
1523         ConstrStr += (char)Record[3+AsmStrSize+i];
1524       PointerType *PTy = cast<PointerType>(CurTy);
1525       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1526                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1527                          InlineAsm::AsmDialect(AsmDialect));
1528       break;
1529     }
1530     case bitc::CST_CODE_BLOCKADDRESS:{
1531       if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1532       Type *FnTy = getTypeByID(Record[0]);
1533       if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1534       Function *Fn =
1535         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1536       if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1537
1538       // If the function is already parsed we can insert the block address right
1539       // away.
1540       if (!Fn->empty()) {
1541         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1542         for (size_t I = 0, E = Record[2]; I != E; ++I) {
1543           if (BBI == BBE)
1544             return Error("Invalid blockaddress block #");
1545           ++BBI;
1546         }
1547         V = BlockAddress::get(Fn, BBI);
1548       } else {
1549         // Otherwise insert a placeholder and remember it so it can be inserted
1550         // when the function is parsed.
1551         GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1552                                                     Type::getInt8Ty(Context),
1553                                             false, GlobalValue::InternalLinkage,
1554                                                     0, "");
1555         BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1556         V = FwdRef;
1557       }
1558       break;
1559     }
1560     }
1561
1562     ValueList.AssignValue(V, NextCstNo);
1563     ++NextCstNo;
1564   }
1565 }
1566
1567 bool BitcodeReader::ParseUseLists() {
1568   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1569     return Error("Malformed block record");
1570
1571   SmallVector<uint64_t, 64> Record;
1572
1573   // Read all the records.
1574   while (1) {
1575     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1576
1577     switch (Entry.Kind) {
1578     case BitstreamEntry::SubBlock: // Handled for us already.
1579     case BitstreamEntry::Error:
1580       return Error("malformed use list block");
1581     case BitstreamEntry::EndBlock:
1582       return false;
1583     case BitstreamEntry::Record:
1584       // The interesting case.
1585       break;
1586     }
1587
1588     // Read a use list record.
1589     Record.clear();
1590     switch (Stream.readRecord(Entry.ID, Record)) {
1591     default:  // Default behavior: unknown type.
1592       break;
1593     case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1594       unsigned RecordLength = Record.size();
1595       if (RecordLength < 1)
1596         return Error ("Invalid UseList reader!");
1597       UseListRecords.push_back(Record);
1598       break;
1599     }
1600     }
1601   }
1602 }
1603
1604 /// RememberAndSkipFunctionBody - When we see the block for a function body,
1605 /// remember where it is and then skip it.  This lets us lazily deserialize the
1606 /// functions.
1607 bool BitcodeReader::RememberAndSkipFunctionBody() {
1608   // Get the function we are talking about.
1609   if (FunctionsWithBodies.empty())
1610     return Error("Insufficient function protos");
1611
1612   Function *Fn = FunctionsWithBodies.back();
1613   FunctionsWithBodies.pop_back();
1614
1615   // Save the current stream state.
1616   uint64_t CurBit = Stream.GetCurrentBitNo();
1617   DeferredFunctionInfo[Fn] = CurBit;
1618
1619   // Skip over the function block for now.
1620   if (Stream.SkipBlock())
1621     return Error("Malformed block record");
1622   return false;
1623 }
1624
1625 bool BitcodeReader::GlobalCleanup() {
1626   // Patch the initializers for globals and aliases up.
1627   ResolveGlobalAndAliasInits();
1628   if (!GlobalInits.empty() || !AliasInits.empty())
1629     return Error("Malformed global initializer set");
1630
1631   // Look for intrinsic functions which need to be upgraded at some point
1632   for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1633        FI != FE; ++FI) {
1634     Function *NewFn;
1635     if (UpgradeIntrinsicFunction(FI, NewFn))
1636       UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1637   }
1638
1639   // Look for global variables which need to be renamed.
1640   for (Module::global_iterator
1641          GI = TheModule->global_begin(), GE = TheModule->global_end();
1642        GI != GE; ++GI)
1643     UpgradeGlobalVariable(GI);
1644   // Force deallocation of memory for these vectors to favor the client that
1645   // want lazy deserialization.
1646   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1647   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1648   return false;
1649 }
1650
1651 bool BitcodeReader::ParseModule(bool Resume) {
1652   if (Resume)
1653     Stream.JumpToBit(NextUnreadBit);
1654   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1655     return Error("Malformed block record");
1656
1657   SmallVector<uint64_t, 64> Record;
1658   std::vector<std::string> SectionTable;
1659   std::vector<std::string> GCTable;
1660
1661   // Read all the records for this module.
1662   while (1) {
1663     BitstreamEntry Entry = Stream.advance();
1664
1665     switch (Entry.Kind) {
1666     case BitstreamEntry::Error:
1667       Error("malformed module block");
1668       return true;
1669     case BitstreamEntry::EndBlock:
1670       return GlobalCleanup();
1671
1672     case BitstreamEntry::SubBlock:
1673       switch (Entry.ID) {
1674       default:  // Skip unknown content.
1675         if (Stream.SkipBlock())
1676           return Error("Malformed block record");
1677         break;
1678       case bitc::BLOCKINFO_BLOCK_ID:
1679         if (Stream.ReadBlockInfoBlock())
1680           return Error("Malformed BlockInfoBlock");
1681         break;
1682       case bitc::PARAMATTR_BLOCK_ID:
1683         if (ParseAttributeBlock())
1684           return true;
1685         break;
1686       case bitc::PARAMATTR_GROUP_BLOCK_ID:
1687         if (ParseAttributeGroupBlock())
1688           return true;
1689         break;
1690       case bitc::TYPE_BLOCK_ID_NEW:
1691         if (ParseTypeTable())
1692           return true;
1693         break;
1694       case bitc::VALUE_SYMTAB_BLOCK_ID:
1695         if (ParseValueSymbolTable())
1696           return true;
1697         SeenValueSymbolTable = true;
1698         break;
1699       case bitc::CONSTANTS_BLOCK_ID:
1700         if (ParseConstants() || ResolveGlobalAndAliasInits())
1701           return true;
1702         break;
1703       case bitc::METADATA_BLOCK_ID:
1704         if (ParseMetadata())
1705           return true;
1706         break;
1707       case bitc::FUNCTION_BLOCK_ID:
1708         // If this is the first function body we've seen, reverse the
1709         // FunctionsWithBodies list.
1710         if (!SeenFirstFunctionBody) {
1711           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1712           if (GlobalCleanup())
1713             return true;
1714           SeenFirstFunctionBody = true;
1715         }
1716
1717         if (RememberAndSkipFunctionBody())
1718           return true;
1719         // For streaming bitcode, suspend parsing when we reach the function
1720         // bodies. Subsequent materialization calls will resume it when
1721         // necessary. For streaming, the function bodies must be at the end of
1722         // the bitcode. If the bitcode file is old, the symbol table will be
1723         // at the end instead and will not have been seen yet. In this case,
1724         // just finish the parse now.
1725         if (LazyStreamer && SeenValueSymbolTable) {
1726           NextUnreadBit = Stream.GetCurrentBitNo();
1727           return false;
1728         }
1729         break;
1730       case bitc::USELIST_BLOCK_ID:
1731         if (ParseUseLists())
1732           return true;
1733         break;
1734       }
1735       continue;
1736
1737     case BitstreamEntry::Record:
1738       // The interesting case.
1739       break;
1740     }
1741
1742
1743     // Read a record.
1744     switch (Stream.readRecord(Entry.ID, Record)) {
1745     default: break;  // Default behavior, ignore unknown content.
1746     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
1747       if (Record.size() < 1)
1748         return Error("Malformed MODULE_CODE_VERSION");
1749       // Only version #0 and #1 are supported so far.
1750       unsigned module_version = Record[0];
1751       switch (module_version) {
1752         default: return Error("Unknown bitstream version!");
1753         case 0:
1754           UseRelativeIDs = false;
1755           break;
1756         case 1:
1757           UseRelativeIDs = true;
1758           break;
1759       }
1760       break;
1761     }
1762     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1763       std::string S;
1764       if (ConvertToString(Record, 0, S))
1765         return Error("Invalid MODULE_CODE_TRIPLE record");
1766       TheModule->setTargetTriple(S);
1767       break;
1768     }
1769     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1770       std::string S;
1771       if (ConvertToString(Record, 0, S))
1772         return Error("Invalid MODULE_CODE_DATALAYOUT record");
1773       TheModule->setDataLayout(S);
1774       break;
1775     }
1776     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1777       std::string S;
1778       if (ConvertToString(Record, 0, S))
1779         return Error("Invalid MODULE_CODE_ASM record");
1780       TheModule->setModuleInlineAsm(S);
1781       break;
1782     }
1783     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1784       // FIXME: Remove in 4.0.
1785       std::string S;
1786       if (ConvertToString(Record, 0, S))
1787         return Error("Invalid MODULE_CODE_DEPLIB record");
1788       // Ignore value.
1789       break;
1790     }
1791     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1792       std::string S;
1793       if (ConvertToString(Record, 0, S))
1794         return Error("Invalid MODULE_CODE_SECTIONNAME record");
1795       SectionTable.push_back(S);
1796       break;
1797     }
1798     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1799       std::string S;
1800       if (ConvertToString(Record, 0, S))
1801         return Error("Invalid MODULE_CODE_GCNAME record");
1802       GCTable.push_back(S);
1803       break;
1804     }
1805     // GLOBALVAR: [pointer type, isconst, initid,
1806     //             linkage, alignment, section, visibility, threadlocal,
1807     //             unnamed_addr]
1808     case bitc::MODULE_CODE_GLOBALVAR: {
1809       if (Record.size() < 6)
1810         return Error("Invalid MODULE_CODE_GLOBALVAR record");
1811       Type *Ty = getTypeByID(Record[0]);
1812       if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1813       if (!Ty->isPointerTy())
1814         return Error("Global not a pointer type!");
1815       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1816       Ty = cast<PointerType>(Ty)->getElementType();
1817
1818       bool isConstant = Record[1];
1819       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1820       unsigned Alignment = (1 << Record[4]) >> 1;
1821       std::string Section;
1822       if (Record[5]) {
1823         if (Record[5]-1 >= SectionTable.size())
1824           return Error("Invalid section ID");
1825         Section = SectionTable[Record[5]-1];
1826       }
1827       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1828       if (Record.size() > 6)
1829         Visibility = GetDecodedVisibility(Record[6]);
1830
1831       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1832       if (Record.size() > 7)
1833         TLM = GetDecodedThreadLocalMode(Record[7]);
1834
1835       bool UnnamedAddr = false;
1836       if (Record.size() > 8)
1837         UnnamedAddr = Record[8];
1838
1839       bool ExternallyInitialized = false;
1840       if (Record.size() > 9)
1841         ExternallyInitialized = Record[9];
1842
1843       GlobalVariable *NewGV =
1844         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1845                            TLM, AddressSpace, ExternallyInitialized);
1846       NewGV->setAlignment(Alignment);
1847       if (!Section.empty())
1848         NewGV->setSection(Section);
1849       NewGV->setVisibility(Visibility);
1850       NewGV->setUnnamedAddr(UnnamedAddr);
1851
1852       ValueList.push_back(NewGV);
1853
1854       // Remember which value to use for the global initializer.
1855       if (unsigned InitID = Record[2])
1856         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1857       break;
1858     }
1859     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1860     //             alignment, section, visibility, gc, unnamed_addr]
1861     case bitc::MODULE_CODE_FUNCTION: {
1862       if (Record.size() < 8)
1863         return Error("Invalid MODULE_CODE_FUNCTION record");
1864       Type *Ty = getTypeByID(Record[0]);
1865       if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1866       if (!Ty->isPointerTy())
1867         return Error("Function not a pointer type!");
1868       FunctionType *FTy =
1869         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1870       if (!FTy)
1871         return Error("Function not a pointer to function type!");
1872
1873       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1874                                         "", TheModule);
1875
1876       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1877       bool isProto = Record[2];
1878       Func->setLinkage(GetDecodedLinkage(Record[3]));
1879       Func->setAttributes(getAttributes(Record[4]));
1880
1881       Func->setAlignment((1 << Record[5]) >> 1);
1882       if (Record[6]) {
1883         if (Record[6]-1 >= SectionTable.size())
1884           return Error("Invalid section ID");
1885         Func->setSection(SectionTable[Record[6]-1]);
1886       }
1887       Func->setVisibility(GetDecodedVisibility(Record[7]));
1888       if (Record.size() > 8 && Record[8]) {
1889         if (Record[8]-1 > GCTable.size())
1890           return Error("Invalid GC ID");
1891         Func->setGC(GCTable[Record[8]-1].c_str());
1892       }
1893       bool UnnamedAddr = false;
1894       if (Record.size() > 9)
1895         UnnamedAddr = Record[9];
1896       Func->setUnnamedAddr(UnnamedAddr);
1897       if (Record.size() > 10 && Record[10] != 0)
1898         FunctionPrefixes.push_back(std::make_pair(Func, Record[10]-1));
1899       ValueList.push_back(Func);
1900
1901       // If this is a function with a body, remember the prototype we are
1902       // creating now, so that we can match up the body with them later.
1903       if (!isProto) {
1904         FunctionsWithBodies.push_back(Func);
1905         if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1906       }
1907       break;
1908     }
1909     // ALIAS: [alias type, aliasee val#, linkage]
1910     // ALIAS: [alias type, aliasee val#, linkage, visibility]
1911     case bitc::MODULE_CODE_ALIAS: {
1912       if (Record.size() < 3)
1913         return Error("Invalid MODULE_ALIAS record");
1914       Type *Ty = getTypeByID(Record[0]);
1915       if (!Ty) return Error("Invalid MODULE_ALIAS record");
1916       if (!Ty->isPointerTy())
1917         return Error("Function not a pointer type!");
1918
1919       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1920                                            "", 0, TheModule);
1921       // Old bitcode files didn't have visibility field.
1922       if (Record.size() > 3)
1923         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1924       ValueList.push_back(NewGA);
1925       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1926       break;
1927     }
1928     /// MODULE_CODE_PURGEVALS: [numvals]
1929     case bitc::MODULE_CODE_PURGEVALS:
1930       // Trim down the value list to the specified size.
1931       if (Record.size() < 1 || Record[0] > ValueList.size())
1932         return Error("Invalid MODULE_PURGEVALS record");
1933       ValueList.shrinkTo(Record[0]);
1934       break;
1935     }
1936     Record.clear();
1937   }
1938 }
1939
1940 bool BitcodeReader::ParseBitcodeInto(Module *M) {
1941   TheModule = 0;
1942
1943   if (InitStream()) return true;
1944
1945   // Sniff for the signature.
1946   if (Stream.Read(8) != 'B' ||
1947       Stream.Read(8) != 'C' ||
1948       Stream.Read(4) != 0x0 ||
1949       Stream.Read(4) != 0xC ||
1950       Stream.Read(4) != 0xE ||
1951       Stream.Read(4) != 0xD)
1952     return Error("Invalid bitcode signature");
1953
1954   // We expect a number of well-defined blocks, though we don't necessarily
1955   // need to understand them all.
1956   while (1) {
1957     if (Stream.AtEndOfStream())
1958       return false;
1959
1960     BitstreamEntry Entry =
1961       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
1962
1963     switch (Entry.Kind) {
1964     case BitstreamEntry::Error:
1965       Error("malformed module file");
1966       return true;
1967     case BitstreamEntry::EndBlock:
1968       return false;
1969
1970     case BitstreamEntry::SubBlock:
1971       switch (Entry.ID) {
1972       case bitc::BLOCKINFO_BLOCK_ID:
1973         if (Stream.ReadBlockInfoBlock())
1974           return Error("Malformed BlockInfoBlock");
1975         break;
1976       case bitc::MODULE_BLOCK_ID:
1977         // Reject multiple MODULE_BLOCK's in a single bitstream.
1978         if (TheModule)
1979           return Error("Multiple MODULE_BLOCKs in same stream");
1980         TheModule = M;
1981         if (ParseModule(false))
1982           return true;
1983         if (LazyStreamer) return false;
1984         break;
1985       default:
1986         if (Stream.SkipBlock())
1987           return Error("Malformed block record");
1988         break;
1989       }
1990       continue;
1991     case BitstreamEntry::Record:
1992       // There should be no records in the top-level of blocks.
1993
1994       // The ranlib in Xcode 4 will align archive members by appending newlines
1995       // to the end of them. If this file size is a multiple of 4 but not 8, we
1996       // have to read and ignore these final 4 bytes :-(
1997       if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
1998           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1999           Stream.AtEndOfStream())
2000         return false;
2001
2002       return Error("Invalid record at top-level");
2003     }
2004   }
2005 }
2006
2007 bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
2008   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2009     return Error("Malformed block record");
2010
2011   SmallVector<uint64_t, 64> Record;
2012
2013   // Read all the records for this module.
2014   while (1) {
2015     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2016
2017     switch (Entry.Kind) {
2018     case BitstreamEntry::SubBlock: // Handled for us already.
2019     case BitstreamEntry::Error:
2020       return Error("malformed module block");
2021     case BitstreamEntry::EndBlock:
2022       return false;
2023     case BitstreamEntry::Record:
2024       // The interesting case.
2025       break;
2026     }
2027
2028     // Read a record.
2029     switch (Stream.readRecord(Entry.ID, Record)) {
2030     default: break;  // Default behavior, ignore unknown content.
2031     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2032       std::string S;
2033       if (ConvertToString(Record, 0, S))
2034         return Error("Invalid MODULE_CODE_TRIPLE record");
2035       Triple = S;
2036       break;
2037     }
2038     }
2039     Record.clear();
2040   }
2041 }
2042
2043 bool BitcodeReader::ParseTriple(std::string &Triple) {
2044   if (InitStream()) return true;
2045
2046   // Sniff for the signature.
2047   if (Stream.Read(8) != 'B' ||
2048       Stream.Read(8) != 'C' ||
2049       Stream.Read(4) != 0x0 ||
2050       Stream.Read(4) != 0xC ||
2051       Stream.Read(4) != 0xE ||
2052       Stream.Read(4) != 0xD)
2053     return Error("Invalid bitcode signature");
2054
2055   // We expect a number of well-defined blocks, though we don't necessarily
2056   // need to understand them all.
2057   while (1) {
2058     BitstreamEntry Entry = Stream.advance();
2059
2060     switch (Entry.Kind) {
2061     case BitstreamEntry::Error:
2062       Error("malformed module file");
2063       return true;
2064     case BitstreamEntry::EndBlock:
2065       return false;
2066
2067     case BitstreamEntry::SubBlock:
2068       if (Entry.ID == bitc::MODULE_BLOCK_ID)
2069         return ParseModuleTriple(Triple);
2070
2071       // Ignore other sub-blocks.
2072       if (Stream.SkipBlock()) {
2073         Error("malformed block record in AST file");
2074         return true;
2075       }
2076       continue;
2077
2078     case BitstreamEntry::Record:
2079       Stream.skipRecord(Entry.ID);
2080       continue;
2081     }
2082   }
2083 }
2084
2085 /// ParseMetadataAttachment - Parse metadata attachments.
2086 bool BitcodeReader::ParseMetadataAttachment() {
2087   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2088     return Error("Malformed block record");
2089
2090   SmallVector<uint64_t, 64> Record;
2091   while (1) {
2092     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2093
2094     switch (Entry.Kind) {
2095     case BitstreamEntry::SubBlock: // Handled for us already.
2096     case BitstreamEntry::Error:
2097       return Error("malformed metadata block");
2098     case BitstreamEntry::EndBlock:
2099       return false;
2100     case BitstreamEntry::Record:
2101       // The interesting case.
2102       break;
2103     }
2104
2105     // Read a metadata attachment record.
2106     Record.clear();
2107     switch (Stream.readRecord(Entry.ID, Record)) {
2108     default:  // Default behavior: ignore.
2109       break;
2110     case bitc::METADATA_ATTACHMENT: {
2111       unsigned RecordLength = Record.size();
2112       if (Record.empty() || (RecordLength - 1) % 2 == 1)
2113         return Error ("Invalid METADATA_ATTACHMENT reader!");
2114       Instruction *Inst = InstructionList[Record[0]];
2115       for (unsigned i = 1; i != RecordLength; i = i+2) {
2116         unsigned Kind = Record[i];
2117         DenseMap<unsigned, unsigned>::iterator I =
2118           MDKindMap.find(Kind);
2119         if (I == MDKindMap.end())
2120           return Error("Invalid metadata kind ID");
2121         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2122         Inst->setMetadata(I->second, cast<MDNode>(Node));
2123         if (I->second == LLVMContext::MD_tbaa)
2124           InstsWithTBAATag.push_back(Inst);
2125       }
2126       break;
2127     }
2128     }
2129   }
2130 }
2131
2132 /// ParseFunctionBody - Lazily parse the specified function body block.
2133 bool BitcodeReader::ParseFunctionBody(Function *F) {
2134   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2135     return Error("Malformed block record");
2136
2137   InstructionList.clear();
2138   unsigned ModuleValueListSize = ValueList.size();
2139   unsigned ModuleMDValueListSize = MDValueList.size();
2140
2141   // Add all the function arguments to the value table.
2142   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2143     ValueList.push_back(I);
2144
2145   unsigned NextValueNo = ValueList.size();
2146   BasicBlock *CurBB = 0;
2147   unsigned CurBBNo = 0;
2148
2149   DebugLoc LastLoc;
2150
2151   // Read all the records.
2152   SmallVector<uint64_t, 64> Record;
2153   while (1) {
2154     BitstreamEntry Entry = Stream.advance();
2155
2156     switch (Entry.Kind) {
2157     case BitstreamEntry::Error:
2158       return Error("Bitcode error in function block");
2159     case BitstreamEntry::EndBlock:
2160       goto OutOfRecordLoop;
2161
2162     case BitstreamEntry::SubBlock:
2163       switch (Entry.ID) {
2164       default:  // Skip unknown content.
2165         if (Stream.SkipBlock())
2166           return Error("Malformed block record");
2167         break;
2168       case bitc::CONSTANTS_BLOCK_ID:
2169         if (ParseConstants()) return true;
2170         NextValueNo = ValueList.size();
2171         break;
2172       case bitc::VALUE_SYMTAB_BLOCK_ID:
2173         if (ParseValueSymbolTable()) return true;
2174         break;
2175       case bitc::METADATA_ATTACHMENT_ID:
2176         if (ParseMetadataAttachment()) return true;
2177         break;
2178       case bitc::METADATA_BLOCK_ID:
2179         if (ParseMetadata()) return true;
2180         break;
2181       }
2182       continue;
2183
2184     case BitstreamEntry::Record:
2185       // The interesting case.
2186       break;
2187     }
2188
2189     // Read a record.
2190     Record.clear();
2191     Instruction *I = 0;
2192     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2193     switch (BitCode) {
2194     default: // Default behavior: reject
2195       return Error("Unknown instruction");
2196     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
2197       if (Record.size() < 1 || Record[0] == 0)
2198         return Error("Invalid DECLAREBLOCKS record");
2199       // Create all the basic blocks for the function.
2200       FunctionBBs.resize(Record[0]);
2201       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2202         FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2203       CurBB = FunctionBBs[0];
2204       continue;
2205
2206     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
2207       // This record indicates that the last instruction is at the same
2208       // location as the previous instruction with a location.
2209       I = 0;
2210
2211       // Get the last instruction emitted.
2212       if (CurBB && !CurBB->empty())
2213         I = &CurBB->back();
2214       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2215                !FunctionBBs[CurBBNo-1]->empty())
2216         I = &FunctionBBs[CurBBNo-1]->back();
2217
2218       if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2219       I->setDebugLoc(LastLoc);
2220       I = 0;
2221       continue;
2222
2223     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
2224       I = 0;     // Get the last instruction emitted.
2225       if (CurBB && !CurBB->empty())
2226         I = &CurBB->back();
2227       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2228                !FunctionBBs[CurBBNo-1]->empty())
2229         I = &FunctionBBs[CurBBNo-1]->back();
2230       if (I == 0 || Record.size() < 4)
2231         return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2232
2233       unsigned Line = Record[0], Col = Record[1];
2234       unsigned ScopeID = Record[2], IAID = Record[3];
2235
2236       MDNode *Scope = 0, *IA = 0;
2237       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2238       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2239       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2240       I->setDebugLoc(LastLoc);
2241       I = 0;
2242       continue;
2243     }
2244
2245     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2246       unsigned OpNum = 0;
2247       Value *LHS, *RHS;
2248       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2249           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2250           OpNum+1 > Record.size())
2251         return Error("Invalid BINOP record");
2252
2253       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2254       if (Opc == -1) return Error("Invalid BINOP record");
2255       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2256       InstructionList.push_back(I);
2257       if (OpNum < Record.size()) {
2258         if (Opc == Instruction::Add ||
2259             Opc == Instruction::Sub ||
2260             Opc == Instruction::Mul ||
2261             Opc == Instruction::Shl) {
2262           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2263             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2264           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2265             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2266         } else if (Opc == Instruction::SDiv ||
2267                    Opc == Instruction::UDiv ||
2268                    Opc == Instruction::LShr ||
2269                    Opc == Instruction::AShr) {
2270           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2271             cast<BinaryOperator>(I)->setIsExact(true);
2272         } else if (isa<FPMathOperator>(I)) {
2273           FastMathFlags FMF;
2274           if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra))
2275             FMF.setUnsafeAlgebra();
2276           if (0 != (Record[OpNum] & FastMathFlags::NoNaNs))
2277             FMF.setNoNaNs();
2278           if (0 != (Record[OpNum] & FastMathFlags::NoInfs))
2279             FMF.setNoInfs();
2280           if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros))
2281             FMF.setNoSignedZeros();
2282           if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal))
2283             FMF.setAllowReciprocal();
2284           if (FMF.any())
2285             I->setFastMathFlags(FMF);
2286         }
2287
2288       }
2289       break;
2290     }
2291     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2292       unsigned OpNum = 0;
2293       Value *Op;
2294       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2295           OpNum+2 != Record.size())
2296         return Error("Invalid CAST record");
2297
2298       Type *ResTy = getTypeByID(Record[OpNum]);
2299       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2300       if (Opc == -1 || ResTy == 0)
2301         return Error("Invalid CAST record");
2302       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2303       InstructionList.push_back(I);
2304       break;
2305     }
2306     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2307     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2308       unsigned OpNum = 0;
2309       Value *BasePtr;
2310       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2311         return Error("Invalid GEP record");
2312
2313       SmallVector<Value*, 16> GEPIdx;
2314       while (OpNum != Record.size()) {
2315         Value *Op;
2316         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2317           return Error("Invalid GEP record");
2318         GEPIdx.push_back(Op);
2319       }
2320
2321       I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2322       InstructionList.push_back(I);
2323       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2324         cast<GetElementPtrInst>(I)->setIsInBounds(true);
2325       break;
2326     }
2327
2328     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2329                                        // EXTRACTVAL: [opty, opval, n x indices]
2330       unsigned OpNum = 0;
2331       Value *Agg;
2332       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2333         return Error("Invalid EXTRACTVAL record");
2334
2335       SmallVector<unsigned, 4> EXTRACTVALIdx;
2336       for (unsigned RecSize = Record.size();
2337            OpNum != RecSize; ++OpNum) {
2338         uint64_t Index = Record[OpNum];
2339         if ((unsigned)Index != Index)
2340           return Error("Invalid EXTRACTVAL index");
2341         EXTRACTVALIdx.push_back((unsigned)Index);
2342       }
2343
2344       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2345       InstructionList.push_back(I);
2346       break;
2347     }
2348
2349     case bitc::FUNC_CODE_INST_INSERTVAL: {
2350                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
2351       unsigned OpNum = 0;
2352       Value *Agg;
2353       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2354         return Error("Invalid INSERTVAL record");
2355       Value *Val;
2356       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2357         return Error("Invalid INSERTVAL record");
2358
2359       SmallVector<unsigned, 4> INSERTVALIdx;
2360       for (unsigned RecSize = Record.size();
2361            OpNum != RecSize; ++OpNum) {
2362         uint64_t Index = Record[OpNum];
2363         if ((unsigned)Index != Index)
2364           return Error("Invalid INSERTVAL index");
2365         INSERTVALIdx.push_back((unsigned)Index);
2366       }
2367
2368       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2369       InstructionList.push_back(I);
2370       break;
2371     }
2372
2373     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2374       // obsolete form of select
2375       // handles select i1 ... in old bitcode
2376       unsigned OpNum = 0;
2377       Value *TrueVal, *FalseVal, *Cond;
2378       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2379           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2380           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2381         return Error("Invalid SELECT record");
2382
2383       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2384       InstructionList.push_back(I);
2385       break;
2386     }
2387
2388     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2389       // new form of select
2390       // handles select i1 or select [N x i1]
2391       unsigned OpNum = 0;
2392       Value *TrueVal, *FalseVal, *Cond;
2393       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2394           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2395           getValueTypePair(Record, OpNum, NextValueNo, Cond))
2396         return Error("Invalid SELECT record");
2397
2398       // select condition can be either i1 or [N x i1]
2399       if (VectorType* vector_type =
2400           dyn_cast<VectorType>(Cond->getType())) {
2401         // expect <n x i1>
2402         if (vector_type->getElementType() != Type::getInt1Ty(Context))
2403           return Error("Invalid SELECT condition type");
2404       } else {
2405         // expect i1
2406         if (Cond->getType() != Type::getInt1Ty(Context))
2407           return Error("Invalid SELECT condition type");
2408       }
2409
2410       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2411       InstructionList.push_back(I);
2412       break;
2413     }
2414
2415     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2416       unsigned OpNum = 0;
2417       Value *Vec, *Idx;
2418       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2419           popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2420         return Error("Invalid EXTRACTELT record");
2421       I = ExtractElementInst::Create(Vec, Idx);
2422       InstructionList.push_back(I);
2423       break;
2424     }
2425
2426     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2427       unsigned OpNum = 0;
2428       Value *Vec, *Elt, *Idx;
2429       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2430           popValue(Record, OpNum, NextValueNo,
2431                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2432           popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2433         return Error("Invalid INSERTELT record");
2434       I = InsertElementInst::Create(Vec, Elt, Idx);
2435       InstructionList.push_back(I);
2436       break;
2437     }
2438
2439     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2440       unsigned OpNum = 0;
2441       Value *Vec1, *Vec2, *Mask;
2442       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2443           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2444         return Error("Invalid SHUFFLEVEC record");
2445
2446       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2447         return Error("Invalid SHUFFLEVEC record");
2448       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2449       InstructionList.push_back(I);
2450       break;
2451     }
2452
2453     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2454       // Old form of ICmp/FCmp returning bool
2455       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2456       // both legal on vectors but had different behaviour.
2457     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2458       // FCmp/ICmp returning bool or vector of bool
2459
2460       unsigned OpNum = 0;
2461       Value *LHS, *RHS;
2462       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2463           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2464           OpNum+1 != Record.size())
2465         return Error("Invalid CMP record");
2466
2467       if (LHS->getType()->isFPOrFPVectorTy())
2468         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2469       else
2470         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2471       InstructionList.push_back(I);
2472       break;
2473     }
2474
2475     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2476       {
2477         unsigned Size = Record.size();
2478         if (Size == 0) {
2479           I = ReturnInst::Create(Context);
2480           InstructionList.push_back(I);
2481           break;
2482         }
2483
2484         unsigned OpNum = 0;
2485         Value *Op = NULL;
2486         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2487           return Error("Invalid RET record");
2488         if (OpNum != Record.size())
2489           return Error("Invalid RET record");
2490
2491         I = ReturnInst::Create(Context, Op);
2492         InstructionList.push_back(I);
2493         break;
2494       }
2495     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2496       if (Record.size() != 1 && Record.size() != 3)
2497         return Error("Invalid BR record");
2498       BasicBlock *TrueDest = getBasicBlock(Record[0]);
2499       if (TrueDest == 0)
2500         return Error("Invalid BR record");
2501
2502       if (Record.size() == 1) {
2503         I = BranchInst::Create(TrueDest);
2504         InstructionList.push_back(I);
2505       }
2506       else {
2507         BasicBlock *FalseDest = getBasicBlock(Record[1]);
2508         Value *Cond = getValue(Record, 2, NextValueNo,
2509                                Type::getInt1Ty(Context));
2510         if (FalseDest == 0 || Cond == 0)
2511           return Error("Invalid BR record");
2512         I = BranchInst::Create(TrueDest, FalseDest, Cond);
2513         InstructionList.push_back(I);
2514       }
2515       break;
2516     }
2517     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2518       // Check magic
2519       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2520         // "New" SwitchInst format with case ranges. The changes to write this
2521         // format were reverted but we still recognize bitcode that uses it.
2522         // Hopefully someday we will have support for case ranges and can use
2523         // this format again.
2524
2525         Type *OpTy = getTypeByID(Record[1]);
2526         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2527
2528         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2529         BasicBlock *Default = getBasicBlock(Record[3]);
2530         if (OpTy == 0 || Cond == 0 || Default == 0)
2531           return Error("Invalid SWITCH record");
2532
2533         unsigned NumCases = Record[4];
2534
2535         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2536         InstructionList.push_back(SI);
2537
2538         unsigned CurIdx = 5;
2539         for (unsigned i = 0; i != NumCases; ++i) {
2540           SmallVector<ConstantInt*, 1> CaseVals;
2541           unsigned NumItems = Record[CurIdx++];
2542           for (unsigned ci = 0; ci != NumItems; ++ci) {
2543             bool isSingleNumber = Record[CurIdx++];
2544
2545             APInt Low;
2546             unsigned ActiveWords = 1;
2547             if (ValueBitWidth > 64)
2548               ActiveWords = Record[CurIdx++];
2549             Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2550                                 ValueBitWidth);
2551             CurIdx += ActiveWords;
2552
2553             if (!isSingleNumber) {
2554               ActiveWords = 1;
2555               if (ValueBitWidth > 64)
2556                 ActiveWords = Record[CurIdx++];
2557               APInt High =
2558                   ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2559                                 ValueBitWidth);
2560               CurIdx += ActiveWords;
2561
2562               // FIXME: It is not clear whether values in the range should be
2563               // compared as signed or unsigned values. The partially
2564               // implemented changes that used this format in the past used
2565               // unsigned comparisons.
2566               for ( ; Low.ule(High); ++Low)
2567                 CaseVals.push_back(ConstantInt::get(Context, Low));
2568             } else
2569               CaseVals.push_back(ConstantInt::get(Context, Low));
2570           }
2571           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2572           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
2573                  cve = CaseVals.end(); cvi != cve; ++cvi)
2574             SI->addCase(*cvi, DestBB);
2575         }
2576         I = SI;
2577         break;
2578       }
2579
2580       // Old SwitchInst format without case ranges.
2581
2582       if (Record.size() < 3 || (Record.size() & 1) == 0)
2583         return Error("Invalid SWITCH record");
2584       Type *OpTy = getTypeByID(Record[0]);
2585       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2586       BasicBlock *Default = getBasicBlock(Record[2]);
2587       if (OpTy == 0 || Cond == 0 || Default == 0)
2588         return Error("Invalid SWITCH record");
2589       unsigned NumCases = (Record.size()-3)/2;
2590       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2591       InstructionList.push_back(SI);
2592       for (unsigned i = 0, e = NumCases; i != e; ++i) {
2593         ConstantInt *CaseVal =
2594           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2595         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2596         if (CaseVal == 0 || DestBB == 0) {
2597           delete SI;
2598           return Error("Invalid SWITCH record!");
2599         }
2600         SI->addCase(CaseVal, DestBB);
2601       }
2602       I = SI;
2603       break;
2604     }
2605     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2606       if (Record.size() < 2)
2607         return Error("Invalid INDIRECTBR record");
2608       Type *OpTy = getTypeByID(Record[0]);
2609       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2610       if (OpTy == 0 || Address == 0)
2611         return Error("Invalid INDIRECTBR record");
2612       unsigned NumDests = Record.size()-2;
2613       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2614       InstructionList.push_back(IBI);
2615       for (unsigned i = 0, e = NumDests; i != e; ++i) {
2616         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2617           IBI->addDestination(DestBB);
2618         } else {
2619           delete IBI;
2620           return Error("Invalid INDIRECTBR record!");
2621         }
2622       }
2623       I = IBI;
2624       break;
2625     }
2626
2627     case bitc::FUNC_CODE_INST_INVOKE: {
2628       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2629       if (Record.size() < 4) return Error("Invalid INVOKE record");
2630       AttributeSet PAL = getAttributes(Record[0]);
2631       unsigned CCInfo = Record[1];
2632       BasicBlock *NormalBB = getBasicBlock(Record[2]);
2633       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2634
2635       unsigned OpNum = 4;
2636       Value *Callee;
2637       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2638         return Error("Invalid INVOKE record");
2639
2640       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2641       FunctionType *FTy = !CalleeTy ? 0 :
2642         dyn_cast<FunctionType>(CalleeTy->getElementType());
2643
2644       // Check that the right number of fixed parameters are here.
2645       if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2646           Record.size() < OpNum+FTy->getNumParams())
2647         return Error("Invalid INVOKE record");
2648
2649       SmallVector<Value*, 16> Ops;
2650       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2651         Ops.push_back(getValue(Record, OpNum, NextValueNo,
2652                                FTy->getParamType(i)));
2653         if (Ops.back() == 0) return Error("Invalid INVOKE record");
2654       }
2655
2656       if (!FTy->isVarArg()) {
2657         if (Record.size() != OpNum)
2658           return Error("Invalid INVOKE record");
2659       } else {
2660         // Read type/value pairs for varargs params.
2661         while (OpNum != Record.size()) {
2662           Value *Op;
2663           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2664             return Error("Invalid INVOKE record");
2665           Ops.push_back(Op);
2666         }
2667       }
2668
2669       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2670       InstructionList.push_back(I);
2671       cast<InvokeInst>(I)->setCallingConv(
2672         static_cast<CallingConv::ID>(CCInfo));
2673       cast<InvokeInst>(I)->setAttributes(PAL);
2674       break;
2675     }
2676     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2677       unsigned Idx = 0;
2678       Value *Val = 0;
2679       if (getValueTypePair(Record, Idx, NextValueNo, Val))
2680         return Error("Invalid RESUME record");
2681       I = ResumeInst::Create(Val);
2682       InstructionList.push_back(I);
2683       break;
2684     }
2685     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2686       I = new UnreachableInst(Context);
2687       InstructionList.push_back(I);
2688       break;
2689     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2690       if (Record.size() < 1 || ((Record.size()-1)&1))
2691         return Error("Invalid PHI record");
2692       Type *Ty = getTypeByID(Record[0]);
2693       if (!Ty) return Error("Invalid PHI record");
2694
2695       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2696       InstructionList.push_back(PN);
2697
2698       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2699         Value *V;
2700         // With the new function encoding, it is possible that operands have
2701         // negative IDs (for forward references).  Use a signed VBR
2702         // representation to keep the encoding small.
2703         if (UseRelativeIDs)
2704           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2705         else
2706           V = getValue(Record, 1+i, NextValueNo, Ty);
2707         BasicBlock *BB = getBasicBlock(Record[2+i]);
2708         if (!V || !BB) return Error("Invalid PHI record");
2709         PN->addIncoming(V, BB);
2710       }
2711       I = PN;
2712       break;
2713     }
2714
2715     case bitc::FUNC_CODE_INST_LANDINGPAD: {
2716       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2717       unsigned Idx = 0;
2718       if (Record.size() < 4)
2719         return Error("Invalid LANDINGPAD record");
2720       Type *Ty = getTypeByID(Record[Idx++]);
2721       if (!Ty) return Error("Invalid LANDINGPAD record");
2722       Value *PersFn = 0;
2723       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2724         return Error("Invalid LANDINGPAD record");
2725
2726       bool IsCleanup = !!Record[Idx++];
2727       unsigned NumClauses = Record[Idx++];
2728       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2729       LP->setCleanup(IsCleanup);
2730       for (unsigned J = 0; J != NumClauses; ++J) {
2731         LandingPadInst::ClauseType CT =
2732           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2733         Value *Val;
2734
2735         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2736           delete LP;
2737           return Error("Invalid LANDINGPAD record");
2738         }
2739
2740         assert((CT != LandingPadInst::Catch ||
2741                 !isa<ArrayType>(Val->getType())) &&
2742                "Catch clause has a invalid type!");
2743         assert((CT != LandingPadInst::Filter ||
2744                 isa<ArrayType>(Val->getType())) &&
2745                "Filter clause has invalid type!");
2746         LP->addClause(Val);
2747       }
2748
2749       I = LP;
2750       InstructionList.push_back(I);
2751       break;
2752     }
2753
2754     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2755       if (Record.size() != 4)
2756         return Error("Invalid ALLOCA record");
2757       PointerType *Ty =
2758         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2759       Type *OpTy = getTypeByID(Record[1]);
2760       Value *Size = getFnValueByID(Record[2], OpTy);
2761       unsigned Align = Record[3];
2762       if (!Ty || !Size) return Error("Invalid ALLOCA record");
2763       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2764       InstructionList.push_back(I);
2765       break;
2766     }
2767     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2768       unsigned OpNum = 0;
2769       Value *Op;
2770       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2771           OpNum+2 != Record.size())
2772         return Error("Invalid LOAD record");
2773
2774       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2775       InstructionList.push_back(I);
2776       break;
2777     }
2778     case bitc::FUNC_CODE_INST_LOADATOMIC: {
2779        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2780       unsigned OpNum = 0;
2781       Value *Op;
2782       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2783           OpNum+4 != Record.size())
2784         return Error("Invalid LOADATOMIC record");
2785
2786
2787       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2788       if (Ordering == NotAtomic || Ordering == Release ||
2789           Ordering == AcquireRelease)
2790         return Error("Invalid LOADATOMIC record");
2791       if (Ordering != NotAtomic && Record[OpNum] == 0)
2792         return Error("Invalid LOADATOMIC record");
2793       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2794
2795       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2796                        Ordering, SynchScope);
2797       InstructionList.push_back(I);
2798       break;
2799     }
2800     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2801       unsigned OpNum = 0;
2802       Value *Val, *Ptr;
2803       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2804           popValue(Record, OpNum, NextValueNo,
2805                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2806           OpNum+2 != Record.size())
2807         return Error("Invalid STORE record");
2808
2809       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2810       InstructionList.push_back(I);
2811       break;
2812     }
2813     case bitc::FUNC_CODE_INST_STOREATOMIC: {
2814       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2815       unsigned OpNum = 0;
2816       Value *Val, *Ptr;
2817       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2818           popValue(Record, OpNum, NextValueNo,
2819                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2820           OpNum+4 != Record.size())
2821         return Error("Invalid STOREATOMIC record");
2822
2823       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2824       if (Ordering == NotAtomic || Ordering == Acquire ||
2825           Ordering == AcquireRelease)
2826         return Error("Invalid STOREATOMIC record");
2827       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2828       if (Ordering != NotAtomic && Record[OpNum] == 0)
2829         return Error("Invalid STOREATOMIC record");
2830
2831       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2832                         Ordering, SynchScope);
2833       InstructionList.push_back(I);
2834       break;
2835     }
2836     case bitc::FUNC_CODE_INST_CMPXCHG: {
2837       // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2838       unsigned OpNum = 0;
2839       Value *Ptr, *Cmp, *New;
2840       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2841           popValue(Record, OpNum, NextValueNo,
2842                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2843           popValue(Record, OpNum, NextValueNo,
2844                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2845           OpNum+3 != Record.size())
2846         return Error("Invalid CMPXCHG record");
2847       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2848       if (Ordering == NotAtomic || Ordering == Unordered)
2849         return Error("Invalid CMPXCHG record");
2850       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2851       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2852       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2853       InstructionList.push_back(I);
2854       break;
2855     }
2856     case bitc::FUNC_CODE_INST_ATOMICRMW: {
2857       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2858       unsigned OpNum = 0;
2859       Value *Ptr, *Val;
2860       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2861           popValue(Record, OpNum, NextValueNo,
2862                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2863           OpNum+4 != Record.size())
2864         return Error("Invalid ATOMICRMW record");
2865       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2866       if (Operation < AtomicRMWInst::FIRST_BINOP ||
2867           Operation > AtomicRMWInst::LAST_BINOP)
2868         return Error("Invalid ATOMICRMW record");
2869       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2870       if (Ordering == NotAtomic || Ordering == Unordered)
2871         return Error("Invalid ATOMICRMW record");
2872       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2873       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2874       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2875       InstructionList.push_back(I);
2876       break;
2877     }
2878     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2879       if (2 != Record.size())
2880         return Error("Invalid FENCE record");
2881       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2882       if (Ordering == NotAtomic || Ordering == Unordered ||
2883           Ordering == Monotonic)
2884         return Error("Invalid FENCE record");
2885       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2886       I = new FenceInst(Context, Ordering, SynchScope);
2887       InstructionList.push_back(I);
2888       break;
2889     }
2890     case bitc::FUNC_CODE_INST_CALL: {
2891       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2892       if (Record.size() < 3)
2893         return Error("Invalid CALL record");
2894
2895       AttributeSet PAL = getAttributes(Record[0]);
2896       unsigned CCInfo = Record[1];
2897
2898       unsigned OpNum = 2;
2899       Value *Callee;
2900       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2901         return Error("Invalid CALL record");
2902
2903       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2904       FunctionType *FTy = 0;
2905       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2906       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2907         return Error("Invalid CALL record");
2908
2909       SmallVector<Value*, 16> Args;
2910       // Read the fixed params.
2911       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2912         if (FTy->getParamType(i)->isLabelTy())
2913           Args.push_back(getBasicBlock(Record[OpNum]));
2914         else
2915           Args.push_back(getValue(Record, OpNum, NextValueNo,
2916                                   FTy->getParamType(i)));
2917         if (Args.back() == 0) return Error("Invalid CALL record");
2918       }
2919
2920       // Read type/value pairs for varargs params.
2921       if (!FTy->isVarArg()) {
2922         if (OpNum != Record.size())
2923           return Error("Invalid CALL record");
2924       } else {
2925         while (OpNum != Record.size()) {
2926           Value *Op;
2927           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2928             return Error("Invalid CALL record");
2929           Args.push_back(Op);
2930         }
2931       }
2932
2933       I = CallInst::Create(Callee, Args);
2934       InstructionList.push_back(I);
2935       cast<CallInst>(I)->setCallingConv(
2936         static_cast<CallingConv::ID>(CCInfo>>1));
2937       cast<CallInst>(I)->setTailCall(CCInfo & 1);
2938       cast<CallInst>(I)->setAttributes(PAL);
2939       break;
2940     }
2941     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2942       if (Record.size() < 3)
2943         return Error("Invalid VAARG record");
2944       Type *OpTy = getTypeByID(Record[0]);
2945       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2946       Type *ResTy = getTypeByID(Record[2]);
2947       if (!OpTy || !Op || !ResTy)
2948         return Error("Invalid VAARG record");
2949       I = new VAArgInst(Op, ResTy);
2950       InstructionList.push_back(I);
2951       break;
2952     }
2953     }
2954
2955     // Add instruction to end of current BB.  If there is no current BB, reject
2956     // this file.
2957     if (CurBB == 0) {
2958       delete I;
2959       return Error("Invalid instruction with no BB");
2960     }
2961     CurBB->getInstList().push_back(I);
2962
2963     // If this was a terminator instruction, move to the next block.
2964     if (isa<TerminatorInst>(I)) {
2965       ++CurBBNo;
2966       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2967     }
2968
2969     // Non-void values get registered in the value table for future use.
2970     if (I && !I->getType()->isVoidTy())
2971       ValueList.AssignValue(I, NextValueNo++);
2972   }
2973
2974 OutOfRecordLoop:
2975
2976   // Check the function list for unresolved values.
2977   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2978     if (A->getParent() == 0) {
2979       // We found at least one unresolved value.  Nuke them all to avoid leaks.
2980       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2981         if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2982           A->replaceAllUsesWith(UndefValue::get(A->getType()));
2983           delete A;
2984         }
2985       }
2986       return Error("Never resolved value found in function!");
2987     }
2988   }
2989
2990   // FIXME: Check for unresolved forward-declared metadata references
2991   // and clean up leaks.
2992
2993   // See if anything took the address of blocks in this function.  If so,
2994   // resolve them now.
2995   DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2996     BlockAddrFwdRefs.find(F);
2997   if (BAFRI != BlockAddrFwdRefs.end()) {
2998     std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2999     for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3000       unsigned BlockIdx = RefList[i].first;
3001       if (BlockIdx >= FunctionBBs.size())
3002         return Error("Invalid blockaddress block #");
3003
3004       GlobalVariable *FwdRef = RefList[i].second;
3005       FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3006       FwdRef->eraseFromParent();
3007     }
3008
3009     BlockAddrFwdRefs.erase(BAFRI);
3010   }
3011
3012   // Trim the value list down to the size it was before we parsed this function.
3013   ValueList.shrinkTo(ModuleValueListSize);
3014   MDValueList.shrinkTo(ModuleMDValueListSize);
3015   std::vector<BasicBlock*>().swap(FunctionBBs);
3016   return false;
3017 }
3018
3019 /// FindFunctionInStream - Find the function body in the bitcode stream
3020 bool BitcodeReader::FindFunctionInStream(Function *F,
3021        DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
3022   while (DeferredFunctionInfoIterator->second == 0) {
3023     if (Stream.AtEndOfStream())
3024       return Error("Could not find Function in stream");
3025     // ParseModule will parse the next body in the stream and set its
3026     // position in the DeferredFunctionInfo map.
3027     if (ParseModule(true)) return true;
3028   }
3029   return false;
3030 }
3031
3032 //===----------------------------------------------------------------------===//
3033 // GVMaterializer implementation
3034 //===----------------------------------------------------------------------===//
3035
3036
3037 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
3038   if (const Function *F = dyn_cast<Function>(GV)) {
3039     return F->isDeclaration() &&
3040       DeferredFunctionInfo.count(const_cast<Function*>(F));
3041   }
3042   return false;
3043 }
3044
3045 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
3046   Function *F = dyn_cast<Function>(GV);
3047   // If it's not a function or is already material, ignore the request.
3048   if (!F || !F->isMaterializable()) return false;
3049
3050   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3051   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3052   // If its position is recorded as 0, its body is somewhere in the stream
3053   // but we haven't seen it yet.
3054   if (DFII->second == 0)
3055     if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
3056
3057   // Move the bit stream to the saved position of the deferred function body.
3058   Stream.JumpToBit(DFII->second);
3059
3060   if (ParseFunctionBody(F)) {
3061     if (ErrInfo) *ErrInfo = ErrorString;
3062     return true;
3063   }
3064
3065   // Upgrade any old intrinsic calls in the function.
3066   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3067        E = UpgradedIntrinsics.end(); I != E; ++I) {
3068     if (I->first != I->second) {
3069       for (Value::use_iterator UI = I->first->use_begin(),
3070            UE = I->first->use_end(); UI != UE; ) {
3071         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3072           UpgradeIntrinsicCall(CI, I->second);
3073       }
3074     }
3075   }
3076
3077   return false;
3078 }
3079
3080 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3081   const Function *F = dyn_cast<Function>(GV);
3082   if (!F || F->isDeclaration())
3083     return false;
3084   return DeferredFunctionInfo.count(const_cast<Function*>(F));
3085 }
3086
3087 void BitcodeReader::Dematerialize(GlobalValue *GV) {
3088   Function *F = dyn_cast<Function>(GV);
3089   // If this function isn't dematerializable, this is a noop.
3090   if (!F || !isDematerializable(F))
3091     return;
3092
3093   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3094
3095   // Just forget the function body, we can remat it later.
3096   F->deleteBody();
3097 }
3098
3099
3100 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
3101   assert(M == TheModule &&
3102          "Can only Materialize the Module this BitcodeReader is attached to.");
3103   // Iterate over the module, deserializing any functions that are still on
3104   // disk.
3105   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3106        F != E; ++F)
3107     if (F->isMaterializable() &&
3108         Materialize(F, ErrInfo))
3109       return true;
3110
3111   // At this point, if there are any function bodies, the current bit is
3112   // pointing to the END_BLOCK record after them. Now make sure the rest
3113   // of the bits in the module have been read.
3114   if (NextUnreadBit)
3115     ParseModule(true);
3116
3117   // Upgrade any intrinsic calls that slipped through (should not happen!) and
3118   // delete the old functions to clean up. We can't do this unless the entire
3119   // module is materialized because there could always be another function body
3120   // with calls to the old function.
3121   for (std::vector<std::pair<Function*, Function*> >::iterator I =
3122        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3123     if (I->first != I->second) {
3124       for (Value::use_iterator UI = I->first->use_begin(),
3125            UE = I->first->use_end(); UI != UE; ) {
3126         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3127           UpgradeIntrinsicCall(CI, I->second);
3128       }
3129       if (!I->first->use_empty())
3130         I->first->replaceAllUsesWith(I->second);
3131       I->first->eraseFromParent();
3132     }
3133   }
3134   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3135
3136   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
3137     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
3138
3139   return false;
3140 }
3141
3142 bool BitcodeReader::InitStream() {
3143   if (LazyStreamer) return InitLazyStream();
3144   return InitStreamFromBuffer();
3145 }
3146
3147 bool BitcodeReader::InitStreamFromBuffer() {
3148   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3149   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3150
3151   if (Buffer->getBufferSize() & 3) {
3152     if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
3153       return Error("Invalid bitcode signature");
3154     else
3155       return Error("Bitcode stream should be a multiple of 4 bytes in length");
3156   }
3157
3158   // If we have a wrapper header, parse it and ignore the non-bc file contents.
3159   // The magic number is 0x0B17C0DE stored in little endian.
3160   if (isBitcodeWrapper(BufPtr, BufEnd))
3161     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3162       return Error("Invalid bitcode wrapper header");
3163
3164   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3165   Stream.init(*StreamFile);
3166
3167   return false;
3168 }
3169
3170 bool BitcodeReader::InitLazyStream() {
3171   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3172   // see it.
3173   StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
3174   StreamFile.reset(new BitstreamReader(Bytes));
3175   Stream.init(*StreamFile);
3176
3177   unsigned char buf[16];
3178   if (Bytes->readBytes(0, 16, buf) == -1)
3179     return Error("Bitcode stream must be at least 16 bytes in length");
3180
3181   if (!isBitcode(buf, buf + 16))
3182     return Error("Invalid bitcode signature");
3183
3184   if (isBitcodeWrapper(buf, buf + 4)) {
3185     const unsigned char *bitcodeStart = buf;
3186     const unsigned char *bitcodeEnd = buf + 16;
3187     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3188     Bytes->dropLeadingBytes(bitcodeStart - buf);
3189     Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
3190   }
3191   return false;
3192 }
3193
3194 //===----------------------------------------------------------------------===//
3195 // External interface
3196 //===----------------------------------------------------------------------===//
3197
3198 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3199 ///
3200 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
3201                                    LLVMContext& Context,
3202                                    std::string *ErrMsg) {
3203   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3204   BitcodeReader *R = new BitcodeReader(Buffer, Context);
3205   M->setMaterializer(R);
3206   if (R->ParseBitcodeInto(M)) {
3207     if (ErrMsg)
3208       *ErrMsg = R->getErrorString();
3209
3210     delete M;  // Also deletes R.
3211     return 0;
3212   }
3213   // Have the BitcodeReader dtor delete 'Buffer'.
3214   R->setBufferOwned(true);
3215
3216   R->materializeForwardReferencedFunctions();
3217
3218   return M;
3219 }
3220
3221
3222 Module *llvm::getStreamedBitcodeModule(const std::string &name,
3223                                        DataStreamer *streamer,
3224                                        LLVMContext &Context,
3225                                        std::string *ErrMsg) {
3226   Module *M = new Module(name, Context);
3227   BitcodeReader *R = new BitcodeReader(streamer, Context);
3228   M->setMaterializer(R);
3229   if (R->ParseBitcodeInto(M)) {
3230     if (ErrMsg)
3231       *ErrMsg = R->getErrorString();
3232     delete M;  // Also deletes R.
3233     return 0;
3234   }
3235   R->setBufferOwned(false); // no buffer to delete
3236   return M;
3237 }
3238
3239 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3240 /// If an error occurs, return null and fill in *ErrMsg if non-null.
3241 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3242                                std::string *ErrMsg){
3243   Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3244   if (!M) return 0;
3245
3246   // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3247   // there was an error.
3248   static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3249
3250   // Read in the entire module, and destroy the BitcodeReader.
3251   if (M->MaterializeAllPermanently(ErrMsg)) {
3252     delete M;
3253     return 0;
3254   }
3255
3256   // TODO: Restore the use-lists to the in-memory state when the bitcode was
3257   // written.  We must defer until the Module has been fully materialized.
3258
3259   return M;
3260 }
3261
3262 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3263                                          LLVMContext& Context,
3264                                          std::string *ErrMsg) {
3265   BitcodeReader *R = new BitcodeReader(Buffer, Context);
3266   // Don't let the BitcodeReader dtor delete 'Buffer'.
3267   R->setBufferOwned(false);
3268
3269   std::string Triple("");
3270   if (R->ParseTriple(Triple))
3271     if (ErrMsg)
3272       *ErrMsg = R->getErrorString();
3273
3274   delete R;
3275   return Triple;
3276 }