1f22ef01cSRoman Divacky //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This header defines the BitcodeReader class.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "llvm/Bitcode/ReaderWriter.h"
15f22ef01cSRoman Divacky #include "BitcodeReader.h"
16f22ef01cSRoman Divacky #include "llvm/Constants.h"
17f22ef01cSRoman Divacky #include "llvm/DerivedTypes.h"
18f22ef01cSRoman Divacky #include "llvm/InlineAsm.h"
19f22ef01cSRoman Divacky #include "llvm/IntrinsicInst.h"
20f22ef01cSRoman Divacky #include "llvm/Module.h"
21f22ef01cSRoman Divacky #include "llvm/Operator.h"
22f22ef01cSRoman Divacky #include "llvm/AutoUpgrade.h"
23f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h"
24f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h"
25f22ef01cSRoman Divacky #include "llvm/Support/MathExtras.h"
26f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h"
27f22ef01cSRoman Divacky #include "llvm/OperandTraits.h"
28f22ef01cSRoman Divacky using namespace llvm;
29f22ef01cSRoman Divacky 
30f22ef01cSRoman Divacky void BitcodeReader::FreeState() {
31f22ef01cSRoman Divacky   if (BufferOwned)
32f22ef01cSRoman Divacky     delete Buffer;
33f22ef01cSRoman Divacky   Buffer = 0;
3417a519f9SDimitry Andric   std::vector<Type*>().swap(TypeList);
35f22ef01cSRoman Divacky   ValueList.clear();
36f22ef01cSRoman Divacky   MDValueList.clear();
37f22ef01cSRoman Divacky 
38f22ef01cSRoman Divacky   std::vector<AttrListPtr>().swap(MAttributes);
39f22ef01cSRoman Divacky   std::vector<BasicBlock*>().swap(FunctionBBs);
40f22ef01cSRoman Divacky   std::vector<Function*>().swap(FunctionsWithBodies);
41f22ef01cSRoman Divacky   DeferredFunctionInfo.clear();
42e580952dSDimitry Andric   MDKindMap.clear();
43f22ef01cSRoman Divacky }
44f22ef01cSRoman Divacky 
45f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
46f22ef01cSRoman Divacky //  Helper functions to implement forward reference resolution, etc.
47f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
48f22ef01cSRoman Divacky 
49f22ef01cSRoman Divacky /// ConvertToString - Convert a string from a record into an std::string, return
50f22ef01cSRoman Divacky /// true on failure.
51f22ef01cSRoman Divacky template<typename StrTy>
52f22ef01cSRoman Divacky static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
53f22ef01cSRoman Divacky                             StrTy &Result) {
54f22ef01cSRoman Divacky   if (Idx > Record.size())
55f22ef01cSRoman Divacky     return true;
56f22ef01cSRoman Divacky 
57f22ef01cSRoman Divacky   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
58f22ef01cSRoman Divacky     Result += (char)Record[i];
59f22ef01cSRoman Divacky   return false;
60f22ef01cSRoman Divacky }
61f22ef01cSRoman Divacky 
62f22ef01cSRoman Divacky static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
63f22ef01cSRoman Divacky   switch (Val) {
64f22ef01cSRoman Divacky   default: // Map unknown/new linkages to external
65f22ef01cSRoman Divacky   case 0:  return GlobalValue::ExternalLinkage;
66f22ef01cSRoman Divacky   case 1:  return GlobalValue::WeakAnyLinkage;
67f22ef01cSRoman Divacky   case 2:  return GlobalValue::AppendingLinkage;
68f22ef01cSRoman Divacky   case 3:  return GlobalValue::InternalLinkage;
69f22ef01cSRoman Divacky   case 4:  return GlobalValue::LinkOnceAnyLinkage;
70f22ef01cSRoman Divacky   case 5:  return GlobalValue::DLLImportLinkage;
71f22ef01cSRoman Divacky   case 6:  return GlobalValue::DLLExportLinkage;
72f22ef01cSRoman Divacky   case 7:  return GlobalValue::ExternalWeakLinkage;
73f22ef01cSRoman Divacky   case 8:  return GlobalValue::CommonLinkage;
74f22ef01cSRoman Divacky   case 9:  return GlobalValue::PrivateLinkage;
75f22ef01cSRoman Divacky   case 10: return GlobalValue::WeakODRLinkage;
76f22ef01cSRoman Divacky   case 11: return GlobalValue::LinkOnceODRLinkage;
77f22ef01cSRoman Divacky   case 12: return GlobalValue::AvailableExternallyLinkage;
78f22ef01cSRoman Divacky   case 13: return GlobalValue::LinkerPrivateLinkage;
79ffd1746dSEd Schouten   case 14: return GlobalValue::LinkerPrivateWeakLinkage;
80e580952dSDimitry Andric   case 15: return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
81f22ef01cSRoman Divacky   }
82f22ef01cSRoman Divacky }
83f22ef01cSRoman Divacky 
84f22ef01cSRoman Divacky static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
85f22ef01cSRoman Divacky   switch (Val) {
86f22ef01cSRoman Divacky   default: // Map unknown visibilities to default.
87f22ef01cSRoman Divacky   case 0: return GlobalValue::DefaultVisibility;
88f22ef01cSRoman Divacky   case 1: return GlobalValue::HiddenVisibility;
89f22ef01cSRoman Divacky   case 2: return GlobalValue::ProtectedVisibility;
90f22ef01cSRoman Divacky   }
91f22ef01cSRoman Divacky }
92f22ef01cSRoman Divacky 
93f22ef01cSRoman Divacky static int GetDecodedCastOpcode(unsigned Val) {
94f22ef01cSRoman Divacky   switch (Val) {
95f22ef01cSRoman Divacky   default: return -1;
96f22ef01cSRoman Divacky   case bitc::CAST_TRUNC   : return Instruction::Trunc;
97f22ef01cSRoman Divacky   case bitc::CAST_ZEXT    : return Instruction::ZExt;
98f22ef01cSRoman Divacky   case bitc::CAST_SEXT    : return Instruction::SExt;
99f22ef01cSRoman Divacky   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
100f22ef01cSRoman Divacky   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
101f22ef01cSRoman Divacky   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
102f22ef01cSRoman Divacky   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
103f22ef01cSRoman Divacky   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
104f22ef01cSRoman Divacky   case bitc::CAST_FPEXT   : return Instruction::FPExt;
105f22ef01cSRoman Divacky   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
106f22ef01cSRoman Divacky   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
107f22ef01cSRoman Divacky   case bitc::CAST_BITCAST : return Instruction::BitCast;
108f22ef01cSRoman Divacky   }
109f22ef01cSRoman Divacky }
1106122f3e6SDimitry Andric static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
111f22ef01cSRoman Divacky   switch (Val) {
112f22ef01cSRoman Divacky   default: return -1;
113f22ef01cSRoman Divacky   case bitc::BINOP_ADD:
114f22ef01cSRoman Divacky     return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
115f22ef01cSRoman Divacky   case bitc::BINOP_SUB:
116f22ef01cSRoman Divacky     return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
117f22ef01cSRoman Divacky   case bitc::BINOP_MUL:
118f22ef01cSRoman Divacky     return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
119f22ef01cSRoman Divacky   case bitc::BINOP_UDIV: return Instruction::UDiv;
120f22ef01cSRoman Divacky   case bitc::BINOP_SDIV:
121f22ef01cSRoman Divacky     return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
122f22ef01cSRoman Divacky   case bitc::BINOP_UREM: return Instruction::URem;
123f22ef01cSRoman Divacky   case bitc::BINOP_SREM:
124f22ef01cSRoman Divacky     return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
125f22ef01cSRoman Divacky   case bitc::BINOP_SHL:  return Instruction::Shl;
126f22ef01cSRoman Divacky   case bitc::BINOP_LSHR: return Instruction::LShr;
127f22ef01cSRoman Divacky   case bitc::BINOP_ASHR: return Instruction::AShr;
128f22ef01cSRoman Divacky   case bitc::BINOP_AND:  return Instruction::And;
129f22ef01cSRoman Divacky   case bitc::BINOP_OR:   return Instruction::Or;
130f22ef01cSRoman Divacky   case bitc::BINOP_XOR:  return Instruction::Xor;
131f22ef01cSRoman Divacky   }
132f22ef01cSRoman Divacky }
133f22ef01cSRoman Divacky 
1346122f3e6SDimitry Andric static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
1356122f3e6SDimitry Andric   switch (Val) {
1366122f3e6SDimitry Andric   default: return AtomicRMWInst::BAD_BINOP;
1376122f3e6SDimitry Andric   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1386122f3e6SDimitry Andric   case bitc::RMW_ADD: return AtomicRMWInst::Add;
1396122f3e6SDimitry Andric   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1406122f3e6SDimitry Andric   case bitc::RMW_AND: return AtomicRMWInst::And;
1416122f3e6SDimitry Andric   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1426122f3e6SDimitry Andric   case bitc::RMW_OR: return AtomicRMWInst::Or;
1436122f3e6SDimitry Andric   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1446122f3e6SDimitry Andric   case bitc::RMW_MAX: return AtomicRMWInst::Max;
1456122f3e6SDimitry Andric   case bitc::RMW_MIN: return AtomicRMWInst::Min;
1466122f3e6SDimitry Andric   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1476122f3e6SDimitry Andric   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1486122f3e6SDimitry Andric   }
1496122f3e6SDimitry Andric }
1506122f3e6SDimitry Andric 
1516122f3e6SDimitry Andric static AtomicOrdering GetDecodedOrdering(unsigned Val) {
1526122f3e6SDimitry Andric   switch (Val) {
1536122f3e6SDimitry Andric   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
1546122f3e6SDimitry Andric   case bitc::ORDERING_UNORDERED: return Unordered;
1556122f3e6SDimitry Andric   case bitc::ORDERING_MONOTONIC: return Monotonic;
1566122f3e6SDimitry Andric   case bitc::ORDERING_ACQUIRE: return Acquire;
1576122f3e6SDimitry Andric   case bitc::ORDERING_RELEASE: return Release;
1586122f3e6SDimitry Andric   case bitc::ORDERING_ACQREL: return AcquireRelease;
1596122f3e6SDimitry Andric   default: // Map unknown orderings to sequentially-consistent.
1606122f3e6SDimitry Andric   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
1616122f3e6SDimitry Andric   }
1626122f3e6SDimitry Andric }
1636122f3e6SDimitry Andric 
1646122f3e6SDimitry Andric static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
1656122f3e6SDimitry Andric   switch (Val) {
1666122f3e6SDimitry Andric   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
1676122f3e6SDimitry Andric   default: // Map unknown scopes to cross-thread.
1686122f3e6SDimitry Andric   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
1696122f3e6SDimitry Andric   }
1706122f3e6SDimitry Andric }
1716122f3e6SDimitry Andric 
172f22ef01cSRoman Divacky namespace llvm {
173f22ef01cSRoman Divacky namespace {
174f22ef01cSRoman Divacky   /// @brief A class for maintaining the slot number definition
175f22ef01cSRoman Divacky   /// as a placeholder for the actual definition for forward constants defs.
176f22ef01cSRoman Divacky   class ConstantPlaceHolder : public ConstantExpr {
177f22ef01cSRoman Divacky     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
178f22ef01cSRoman Divacky   public:
179f22ef01cSRoman Divacky     // allocate space for exactly one operand
180f22ef01cSRoman Divacky     void *operator new(size_t s) {
181f22ef01cSRoman Divacky       return User::operator new(s, 1);
182f22ef01cSRoman Divacky     }
1836122f3e6SDimitry Andric     explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
184f22ef01cSRoman Divacky       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
185f22ef01cSRoman Divacky       Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
186f22ef01cSRoman Divacky     }
187f22ef01cSRoman Divacky 
188f22ef01cSRoman Divacky     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
1892754fe60SDimitry Andric     //static inline bool classof(const ConstantPlaceHolder *) { return true; }
190f22ef01cSRoman Divacky     static bool classof(const Value *V) {
191f22ef01cSRoman Divacky       return isa<ConstantExpr>(V) &&
192f22ef01cSRoman Divacky              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
193f22ef01cSRoman Divacky     }
194f22ef01cSRoman Divacky 
195f22ef01cSRoman Divacky 
196f22ef01cSRoman Divacky     /// Provide fast operand accessors
197f22ef01cSRoman Divacky     //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
198f22ef01cSRoman Divacky   };
199f22ef01cSRoman Divacky }
200f22ef01cSRoman Divacky 
201f22ef01cSRoman Divacky // FIXME: can we inherit this from ConstantExpr?
202f22ef01cSRoman Divacky template <>
2032754fe60SDimitry Andric struct OperandTraits<ConstantPlaceHolder> :
2042754fe60SDimitry Andric   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
205f22ef01cSRoman Divacky };
206f22ef01cSRoman Divacky }
207f22ef01cSRoman Divacky 
208f22ef01cSRoman Divacky 
209f22ef01cSRoman Divacky void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
210f22ef01cSRoman Divacky   if (Idx == size()) {
211f22ef01cSRoman Divacky     push_back(V);
212f22ef01cSRoman Divacky     return;
213f22ef01cSRoman Divacky   }
214f22ef01cSRoman Divacky 
215f22ef01cSRoman Divacky   if (Idx >= size())
216f22ef01cSRoman Divacky     resize(Idx+1);
217f22ef01cSRoman Divacky 
218f22ef01cSRoman Divacky   WeakVH &OldV = ValuePtrs[Idx];
219f22ef01cSRoman Divacky   if (OldV == 0) {
220f22ef01cSRoman Divacky     OldV = V;
221f22ef01cSRoman Divacky     return;
222f22ef01cSRoman Divacky   }
223f22ef01cSRoman Divacky 
224f22ef01cSRoman Divacky   // Handle constants and non-constants (e.g. instrs) differently for
225f22ef01cSRoman Divacky   // efficiency.
226f22ef01cSRoman Divacky   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
227f22ef01cSRoman Divacky     ResolveConstants.push_back(std::make_pair(PHC, Idx));
228f22ef01cSRoman Divacky     OldV = V;
229f22ef01cSRoman Divacky   } else {
230f22ef01cSRoman Divacky     // If there was a forward reference to this value, replace it.
231f22ef01cSRoman Divacky     Value *PrevVal = OldV;
232f22ef01cSRoman Divacky     OldV->replaceAllUsesWith(V);
233f22ef01cSRoman Divacky     delete PrevVal;
234f22ef01cSRoman Divacky   }
235f22ef01cSRoman Divacky }
236f22ef01cSRoman Divacky 
237f22ef01cSRoman Divacky 
238f22ef01cSRoman Divacky Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
2396122f3e6SDimitry Andric                                                     Type *Ty) {
240f22ef01cSRoman Divacky   if (Idx >= size())
241f22ef01cSRoman Divacky     resize(Idx + 1);
242f22ef01cSRoman Divacky 
243f22ef01cSRoman Divacky   if (Value *V = ValuePtrs[Idx]) {
244f22ef01cSRoman Divacky     assert(Ty == V->getType() && "Type mismatch in constant table!");
245f22ef01cSRoman Divacky     return cast<Constant>(V);
246f22ef01cSRoman Divacky   }
247f22ef01cSRoman Divacky 
248f22ef01cSRoman Divacky   // Create and return a placeholder, which will later be RAUW'd.
249f22ef01cSRoman Divacky   Constant *C = new ConstantPlaceHolder(Ty, Context);
250f22ef01cSRoman Divacky   ValuePtrs[Idx] = C;
251f22ef01cSRoman Divacky   return C;
252f22ef01cSRoman Divacky }
253f22ef01cSRoman Divacky 
2546122f3e6SDimitry Andric Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
255f22ef01cSRoman Divacky   if (Idx >= size())
256f22ef01cSRoman Divacky     resize(Idx + 1);
257f22ef01cSRoman Divacky 
258f22ef01cSRoman Divacky   if (Value *V = ValuePtrs[Idx]) {
259f22ef01cSRoman Divacky     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
260f22ef01cSRoman Divacky     return V;
261f22ef01cSRoman Divacky   }
262f22ef01cSRoman Divacky 
263f22ef01cSRoman Divacky   // No type specified, must be invalid reference.
264f22ef01cSRoman Divacky   if (Ty == 0) return 0;
265f22ef01cSRoman Divacky 
266f22ef01cSRoman Divacky   // Create and return a placeholder, which will later be RAUW'd.
267f22ef01cSRoman Divacky   Value *V = new Argument(Ty);
268f22ef01cSRoman Divacky   ValuePtrs[Idx] = V;
269f22ef01cSRoman Divacky   return V;
270f22ef01cSRoman Divacky }
271f22ef01cSRoman Divacky 
272f22ef01cSRoman Divacky /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
273f22ef01cSRoman Divacky /// resolves any forward references.  The idea behind this is that we sometimes
274f22ef01cSRoman Divacky /// get constants (such as large arrays) which reference *many* forward ref
275f22ef01cSRoman Divacky /// constants.  Replacing each of these causes a lot of thrashing when
276f22ef01cSRoman Divacky /// building/reuniquing the constant.  Instead of doing this, we look at all the
277f22ef01cSRoman Divacky /// uses and rewrite all the place holders at once for any constant that uses
278f22ef01cSRoman Divacky /// a placeholder.
279f22ef01cSRoman Divacky void BitcodeReaderValueList::ResolveConstantForwardRefs() {
280f22ef01cSRoman Divacky   // Sort the values by-pointer so that they are efficient to look up with a
281f22ef01cSRoman Divacky   // binary search.
282f22ef01cSRoman Divacky   std::sort(ResolveConstants.begin(), ResolveConstants.end());
283f22ef01cSRoman Divacky 
284f22ef01cSRoman Divacky   SmallVector<Constant*, 64> NewOps;
285f22ef01cSRoman Divacky 
286f22ef01cSRoman Divacky   while (!ResolveConstants.empty()) {
287f22ef01cSRoman Divacky     Value *RealVal = operator[](ResolveConstants.back().second);
288f22ef01cSRoman Divacky     Constant *Placeholder = ResolveConstants.back().first;
289f22ef01cSRoman Divacky     ResolveConstants.pop_back();
290f22ef01cSRoman Divacky 
291f22ef01cSRoman Divacky     // Loop over all users of the placeholder, updating them to reference the
292f22ef01cSRoman Divacky     // new value.  If they reference more than one placeholder, update them all
293f22ef01cSRoman Divacky     // at once.
294f22ef01cSRoman Divacky     while (!Placeholder->use_empty()) {
295f22ef01cSRoman Divacky       Value::use_iterator UI = Placeholder->use_begin();
296ffd1746dSEd Schouten       User *U = *UI;
297f22ef01cSRoman Divacky 
298f22ef01cSRoman Divacky       // If the using object isn't uniqued, just update the operands.  This
299f22ef01cSRoman Divacky       // handles instructions and initializers for global variables.
300ffd1746dSEd Schouten       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
301f22ef01cSRoman Divacky         UI.getUse().set(RealVal);
302f22ef01cSRoman Divacky         continue;
303f22ef01cSRoman Divacky       }
304f22ef01cSRoman Divacky 
305f22ef01cSRoman Divacky       // Otherwise, we have a constant that uses the placeholder.  Replace that
306f22ef01cSRoman Divacky       // constant with a new constant that has *all* placeholder uses updated.
307ffd1746dSEd Schouten       Constant *UserC = cast<Constant>(U);
308f22ef01cSRoman Divacky       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
309f22ef01cSRoman Divacky            I != E; ++I) {
310f22ef01cSRoman Divacky         Value *NewOp;
311f22ef01cSRoman Divacky         if (!isa<ConstantPlaceHolder>(*I)) {
312f22ef01cSRoman Divacky           // Not a placeholder reference.
313f22ef01cSRoman Divacky           NewOp = *I;
314f22ef01cSRoman Divacky         } else if (*I == Placeholder) {
315f22ef01cSRoman Divacky           // Common case is that it just references this one placeholder.
316f22ef01cSRoman Divacky           NewOp = RealVal;
317f22ef01cSRoman Divacky         } else {
318f22ef01cSRoman Divacky           // Otherwise, look up the placeholder in ResolveConstants.
319f22ef01cSRoman Divacky           ResolveConstantsTy::iterator It =
320f22ef01cSRoman Divacky             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
321f22ef01cSRoman Divacky                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
322f22ef01cSRoman Divacky                                                             0));
323f22ef01cSRoman Divacky           assert(It != ResolveConstants.end() && It->first == *I);
324f22ef01cSRoman Divacky           NewOp = operator[](It->second);
325f22ef01cSRoman Divacky         }
326f22ef01cSRoman Divacky 
327f22ef01cSRoman Divacky         NewOps.push_back(cast<Constant>(NewOp));
328f22ef01cSRoman Divacky       }
329f22ef01cSRoman Divacky 
330f22ef01cSRoman Divacky       // Make the new constant.
331f22ef01cSRoman Divacky       Constant *NewC;
332f22ef01cSRoman Divacky       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
33317a519f9SDimitry Andric         NewC = ConstantArray::get(UserCA->getType(), NewOps);
334f22ef01cSRoman Divacky       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
33517a519f9SDimitry Andric         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
336f22ef01cSRoman Divacky       } else if (isa<ConstantVector>(UserC)) {
3372754fe60SDimitry Andric         NewC = ConstantVector::get(NewOps);
338f22ef01cSRoman Divacky       } else {
339f22ef01cSRoman Divacky         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
3403b0f4066SDimitry Andric         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
341f22ef01cSRoman Divacky       }
342f22ef01cSRoman Divacky 
343f22ef01cSRoman Divacky       UserC->replaceAllUsesWith(NewC);
344f22ef01cSRoman Divacky       UserC->destroyConstant();
345f22ef01cSRoman Divacky       NewOps.clear();
346f22ef01cSRoman Divacky     }
347f22ef01cSRoman Divacky 
348f22ef01cSRoman Divacky     // Update all ValueHandles, they should be the only users at this point.
349f22ef01cSRoman Divacky     Placeholder->replaceAllUsesWith(RealVal);
350f22ef01cSRoman Divacky     delete Placeholder;
351f22ef01cSRoman Divacky   }
352f22ef01cSRoman Divacky }
353f22ef01cSRoman Divacky 
354f22ef01cSRoman Divacky void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
355f22ef01cSRoman Divacky   if (Idx == size()) {
356f22ef01cSRoman Divacky     push_back(V);
357f22ef01cSRoman Divacky     return;
358f22ef01cSRoman Divacky   }
359f22ef01cSRoman Divacky 
360f22ef01cSRoman Divacky   if (Idx >= size())
361f22ef01cSRoman Divacky     resize(Idx+1);
362f22ef01cSRoman Divacky 
363f22ef01cSRoman Divacky   WeakVH &OldV = MDValuePtrs[Idx];
364f22ef01cSRoman Divacky   if (OldV == 0) {
365f22ef01cSRoman Divacky     OldV = V;
366f22ef01cSRoman Divacky     return;
367f22ef01cSRoman Divacky   }
368f22ef01cSRoman Divacky 
369f22ef01cSRoman Divacky   // If there was a forward reference to this value, replace it.
370e580952dSDimitry Andric   MDNode *PrevVal = cast<MDNode>(OldV);
371f22ef01cSRoman Divacky   OldV->replaceAllUsesWith(V);
372e580952dSDimitry Andric   MDNode::deleteTemporary(PrevVal);
373f22ef01cSRoman Divacky   // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
374f22ef01cSRoman Divacky   // value for Idx.
375f22ef01cSRoman Divacky   MDValuePtrs[Idx] = V;
376f22ef01cSRoman Divacky }
377f22ef01cSRoman Divacky 
378f22ef01cSRoman Divacky Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
379f22ef01cSRoman Divacky   if (Idx >= size())
380f22ef01cSRoman Divacky     resize(Idx + 1);
381f22ef01cSRoman Divacky 
382f22ef01cSRoman Divacky   if (Value *V = MDValuePtrs[Idx]) {
383f22ef01cSRoman Divacky     assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
384f22ef01cSRoman Divacky     return V;
385f22ef01cSRoman Divacky   }
386f22ef01cSRoman Divacky 
387f22ef01cSRoman Divacky   // Create and return a placeholder, which will later be RAUW'd.
3883b0f4066SDimitry Andric   Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
389f22ef01cSRoman Divacky   MDValuePtrs[Idx] = V;
390f22ef01cSRoman Divacky   return V;
391f22ef01cSRoman Divacky }
392f22ef01cSRoman Divacky 
39317a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
39417a519f9SDimitry Andric   // The type table size is always specified correctly.
39517a519f9SDimitry Andric   if (ID >= TypeList.size())
39617a519f9SDimitry Andric     return 0;
397f22ef01cSRoman Divacky 
39817a519f9SDimitry Andric   if (Type *Ty = TypeList[ID])
39917a519f9SDimitry Andric     return Ty;
40017a519f9SDimitry Andric 
40117a519f9SDimitry Andric   // If we have a forward reference, the only possible case is when it is to a
40217a519f9SDimitry Andric   // named struct.  Just create a placeholder for now.
4036122f3e6SDimitry Andric   return TypeList[ID] = StructType::create(Context);
404f22ef01cSRoman Divacky }
405f22ef01cSRoman Divacky 
40617a519f9SDimitry Andric /// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
40717a519f9SDimitry Andric Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
40817a519f9SDimitry Andric   if (ID >= TypeList.size())
40917a519f9SDimitry Andric     TypeList.resize(ID+1);
41017a519f9SDimitry Andric 
41117a519f9SDimitry Andric   return TypeList[ID];
41217a519f9SDimitry Andric }
41317a519f9SDimitry Andric 
41417a519f9SDimitry Andric 
415f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
416f22ef01cSRoman Divacky //  Functions for parsing blocks from the bitcode file
417f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
418f22ef01cSRoman Divacky 
419f22ef01cSRoman Divacky bool BitcodeReader::ParseAttributeBlock() {
420f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
421f22ef01cSRoman Divacky     return Error("Malformed block record");
422f22ef01cSRoman Divacky 
423f22ef01cSRoman Divacky   if (!MAttributes.empty())
424f22ef01cSRoman Divacky     return Error("Multiple PARAMATTR blocks found!");
425f22ef01cSRoman Divacky 
426f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
427f22ef01cSRoman Divacky 
428f22ef01cSRoman Divacky   SmallVector<AttributeWithIndex, 8> Attrs;
429f22ef01cSRoman Divacky 
430f22ef01cSRoman Divacky   // Read all the records.
431f22ef01cSRoman Divacky   while (1) {
432f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
433f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK) {
434f22ef01cSRoman Divacky       if (Stream.ReadBlockEnd())
435f22ef01cSRoman Divacky         return Error("Error at end of PARAMATTR block");
436f22ef01cSRoman Divacky       return false;
437f22ef01cSRoman Divacky     }
438f22ef01cSRoman Divacky 
439f22ef01cSRoman Divacky     if (Code == bitc::ENTER_SUBBLOCK) {
440f22ef01cSRoman Divacky       // No known subblocks, always skip them.
441f22ef01cSRoman Divacky       Stream.ReadSubBlockID();
442f22ef01cSRoman Divacky       if (Stream.SkipBlock())
443f22ef01cSRoman Divacky         return Error("Malformed block record");
444f22ef01cSRoman Divacky       continue;
445f22ef01cSRoman Divacky     }
446f22ef01cSRoman Divacky 
447f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
448f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
449f22ef01cSRoman Divacky       continue;
450f22ef01cSRoman Divacky     }
451f22ef01cSRoman Divacky 
452f22ef01cSRoman Divacky     // Read a record.
453f22ef01cSRoman Divacky     Record.clear();
454f22ef01cSRoman Divacky     switch (Stream.ReadRecord(Code, Record)) {
455f22ef01cSRoman Divacky     default:  // Default behavior: ignore.
456f22ef01cSRoman Divacky       break;
457f22ef01cSRoman Divacky     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
458f22ef01cSRoman Divacky       if (Record.size() & 1)
459f22ef01cSRoman Divacky         return Error("Invalid ENTRY record");
460f22ef01cSRoman Divacky 
461f22ef01cSRoman Divacky       // FIXME : Remove this autoupgrade code in LLVM 3.0.
462f22ef01cSRoman Divacky       // If Function attributes are using index 0 then transfer them
463f22ef01cSRoman Divacky       // to index ~0. Index 0 is used for return value attributes but used to be
464f22ef01cSRoman Divacky       // used for function attributes.
465f22ef01cSRoman Divacky       Attributes RetAttribute = Attribute::None;
466f22ef01cSRoman Divacky       Attributes FnAttribute = Attribute::None;
467f22ef01cSRoman Divacky       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
468f22ef01cSRoman Divacky         // FIXME: remove in LLVM 3.0
469f22ef01cSRoman Divacky         // The alignment is stored as a 16-bit raw value from bits 31--16.
470f22ef01cSRoman Divacky         // We shift the bits above 31 down by 11 bits.
471f22ef01cSRoman Divacky 
472f22ef01cSRoman Divacky         unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
473f22ef01cSRoman Divacky         if (Alignment && !isPowerOf2_32(Alignment))
474f22ef01cSRoman Divacky           return Error("Alignment is not a power of two.");
475f22ef01cSRoman Divacky 
476f22ef01cSRoman Divacky         Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
477f22ef01cSRoman Divacky         if (Alignment)
478f22ef01cSRoman Divacky           ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
479f22ef01cSRoman Divacky         ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
480f22ef01cSRoman Divacky         Record[i+1] = ReconstitutedAttr;
481f22ef01cSRoman Divacky 
482f22ef01cSRoman Divacky         if (Record[i] == 0)
483f22ef01cSRoman Divacky           RetAttribute = Record[i+1];
484f22ef01cSRoman Divacky         else if (Record[i] == ~0U)
485f22ef01cSRoman Divacky           FnAttribute = Record[i+1];
486f22ef01cSRoman Divacky       }
487f22ef01cSRoman Divacky 
488f22ef01cSRoman Divacky       unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
489f22ef01cSRoman Divacky                               Attribute::ReadOnly|Attribute::ReadNone);
490f22ef01cSRoman Divacky 
491f22ef01cSRoman Divacky       if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
492f22ef01cSRoman Divacky           (RetAttribute & OldRetAttrs) != 0) {
493f22ef01cSRoman Divacky         if (FnAttribute == Attribute::None) { // add a slot so they get added.
494f22ef01cSRoman Divacky           Record.push_back(~0U);
495f22ef01cSRoman Divacky           Record.push_back(0);
496f22ef01cSRoman Divacky         }
497f22ef01cSRoman Divacky 
498f22ef01cSRoman Divacky         FnAttribute  |= RetAttribute & OldRetAttrs;
499f22ef01cSRoman Divacky         RetAttribute &= ~OldRetAttrs;
500f22ef01cSRoman Divacky       }
501f22ef01cSRoman Divacky 
502f22ef01cSRoman Divacky       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
503f22ef01cSRoman Divacky         if (Record[i] == 0) {
504f22ef01cSRoman Divacky           if (RetAttribute != Attribute::None)
505f22ef01cSRoman Divacky             Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
506f22ef01cSRoman Divacky         } else if (Record[i] == ~0U) {
507f22ef01cSRoman Divacky           if (FnAttribute != Attribute::None)
508f22ef01cSRoman Divacky             Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
509f22ef01cSRoman Divacky         } else if (Record[i+1] != Attribute::None)
510f22ef01cSRoman Divacky           Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
511f22ef01cSRoman Divacky       }
512f22ef01cSRoman Divacky 
513f22ef01cSRoman Divacky       MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
514f22ef01cSRoman Divacky       Attrs.clear();
515f22ef01cSRoman Divacky       break;
516f22ef01cSRoman Divacky     }
517f22ef01cSRoman Divacky     }
518f22ef01cSRoman Divacky   }
519f22ef01cSRoman Divacky }
520f22ef01cSRoman Divacky 
521f22ef01cSRoman Divacky bool BitcodeReader::ParseTypeTable() {
52217a519f9SDimitry Andric   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
523f22ef01cSRoman Divacky     return Error("Malformed block record");
524f22ef01cSRoman Divacky 
52517a519f9SDimitry Andric   return ParseTypeTableBody();
52617a519f9SDimitry Andric }
52717a519f9SDimitry Andric 
52817a519f9SDimitry Andric bool BitcodeReader::ParseTypeTableBody() {
529f22ef01cSRoman Divacky   if (!TypeList.empty())
530f22ef01cSRoman Divacky     return Error("Multiple TYPE_BLOCKs found!");
531f22ef01cSRoman Divacky 
532f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
533f22ef01cSRoman Divacky   unsigned NumRecords = 0;
534f22ef01cSRoman Divacky 
53517a519f9SDimitry Andric   SmallString<64> TypeName;
53617a519f9SDimitry Andric 
537f22ef01cSRoman Divacky   // Read all the records for this type table.
538f22ef01cSRoman Divacky   while (1) {
539f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
540f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK) {
541f22ef01cSRoman Divacky       if (NumRecords != TypeList.size())
542f22ef01cSRoman Divacky         return Error("Invalid type forward reference in TYPE_BLOCK");
543f22ef01cSRoman Divacky       if (Stream.ReadBlockEnd())
544f22ef01cSRoman Divacky         return Error("Error at end of type table block");
545f22ef01cSRoman Divacky       return false;
546f22ef01cSRoman Divacky     }
547f22ef01cSRoman Divacky 
548f22ef01cSRoman Divacky     if (Code == bitc::ENTER_SUBBLOCK) {
549f22ef01cSRoman Divacky       // No known subblocks, always skip them.
550f22ef01cSRoman Divacky       Stream.ReadSubBlockID();
551f22ef01cSRoman Divacky       if (Stream.SkipBlock())
552f22ef01cSRoman Divacky         return Error("Malformed block record");
553f22ef01cSRoman Divacky       continue;
554f22ef01cSRoman Divacky     }
555f22ef01cSRoman Divacky 
556f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
557f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
558f22ef01cSRoman Divacky       continue;
559f22ef01cSRoman Divacky     }
560f22ef01cSRoman Divacky 
561f22ef01cSRoman Divacky     // Read a record.
562f22ef01cSRoman Divacky     Record.clear();
56317a519f9SDimitry Andric     Type *ResultTy = 0;
564f22ef01cSRoman Divacky     switch (Stream.ReadRecord(Code, Record)) {
56517a519f9SDimitry Andric     default: return Error("unknown type in type table");
566f22ef01cSRoman Divacky     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
567f22ef01cSRoman Divacky       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
568f22ef01cSRoman Divacky       // type list.  This allows us to reserve space.
569f22ef01cSRoman Divacky       if (Record.size() < 1)
570f22ef01cSRoman Divacky         return Error("Invalid TYPE_CODE_NUMENTRY record");
57117a519f9SDimitry Andric       TypeList.resize(Record[0]);
572f22ef01cSRoman Divacky       continue;
573f22ef01cSRoman Divacky     case bitc::TYPE_CODE_VOID:      // VOID
574f22ef01cSRoman Divacky       ResultTy = Type::getVoidTy(Context);
575f22ef01cSRoman Divacky       break;
576f22ef01cSRoman Divacky     case bitc::TYPE_CODE_FLOAT:     // FLOAT
577f22ef01cSRoman Divacky       ResultTy = Type::getFloatTy(Context);
578f22ef01cSRoman Divacky       break;
579f22ef01cSRoman Divacky     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
580f22ef01cSRoman Divacky       ResultTy = Type::getDoubleTy(Context);
581f22ef01cSRoman Divacky       break;
582f22ef01cSRoman Divacky     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
583f22ef01cSRoman Divacky       ResultTy = Type::getX86_FP80Ty(Context);
584f22ef01cSRoman Divacky       break;
585f22ef01cSRoman Divacky     case bitc::TYPE_CODE_FP128:     // FP128
586f22ef01cSRoman Divacky       ResultTy = Type::getFP128Ty(Context);
587f22ef01cSRoman Divacky       break;
588f22ef01cSRoman Divacky     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
589f22ef01cSRoman Divacky       ResultTy = Type::getPPC_FP128Ty(Context);
590f22ef01cSRoman Divacky       break;
591f22ef01cSRoman Divacky     case bitc::TYPE_CODE_LABEL:     // LABEL
592f22ef01cSRoman Divacky       ResultTy = Type::getLabelTy(Context);
593f22ef01cSRoman Divacky       break;
594f22ef01cSRoman Divacky     case bitc::TYPE_CODE_METADATA:  // METADATA
595f22ef01cSRoman Divacky       ResultTy = Type::getMetadataTy(Context);
596f22ef01cSRoman Divacky       break;
5972754fe60SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
5982754fe60SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
5992754fe60SDimitry Andric       break;
600f22ef01cSRoman Divacky     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
601f22ef01cSRoman Divacky       if (Record.size() < 1)
602f22ef01cSRoman Divacky         return Error("Invalid Integer type record");
603f22ef01cSRoman Divacky 
604f22ef01cSRoman Divacky       ResultTy = IntegerType::get(Context, Record[0]);
605f22ef01cSRoman Divacky       break;
606f22ef01cSRoman Divacky     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
607f22ef01cSRoman Divacky                                     //          [pointee type, address space]
608f22ef01cSRoman Divacky       if (Record.size() < 1)
609f22ef01cSRoman Divacky         return Error("Invalid POINTER type record");
610f22ef01cSRoman Divacky       unsigned AddressSpace = 0;
611f22ef01cSRoman Divacky       if (Record.size() == 2)
612f22ef01cSRoman Divacky         AddressSpace = Record[1];
61317a519f9SDimitry Andric       ResultTy = getTypeByID(Record[0]);
61417a519f9SDimitry Andric       if (ResultTy == 0) return Error("invalid element type in pointer type");
61517a519f9SDimitry Andric       ResultTy = PointerType::get(ResultTy, AddressSpace);
616f22ef01cSRoman Divacky       break;
617f22ef01cSRoman Divacky     }
618f22ef01cSRoman Divacky     case bitc::TYPE_CODE_FUNCTION: {
619f22ef01cSRoman Divacky       // FIXME: attrid is dead, remove it in LLVM 3.0
620f22ef01cSRoman Divacky       // FUNCTION: [vararg, attrid, retty, paramty x N]
621f22ef01cSRoman Divacky       if (Record.size() < 3)
622f22ef01cSRoman Divacky         return Error("Invalid FUNCTION type record");
62317a519f9SDimitry Andric       std::vector<Type*> ArgTys;
62417a519f9SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
62517a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
62617a519f9SDimitry Andric           ArgTys.push_back(T);
62717a519f9SDimitry Andric         else
628f22ef01cSRoman Divacky           break;
629f22ef01cSRoman Divacky       }
63017a519f9SDimitry Andric 
63117a519f9SDimitry Andric       ResultTy = getTypeByID(Record[2]);
63217a519f9SDimitry Andric       if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
63317a519f9SDimitry Andric         return Error("invalid type in function type");
63417a519f9SDimitry Andric 
63517a519f9SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
63617a519f9SDimitry Andric       break;
63717a519f9SDimitry Andric     }
63817a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
639f22ef01cSRoman Divacky       if (Record.size() < 1)
640f22ef01cSRoman Divacky         return Error("Invalid STRUCT type record");
64117a519f9SDimitry Andric       std::vector<Type*> EltTys;
64217a519f9SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
64317a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
64417a519f9SDimitry Andric           EltTys.push_back(T);
64517a519f9SDimitry Andric         else
64617a519f9SDimitry Andric           break;
64717a519f9SDimitry Andric       }
64817a519f9SDimitry Andric       if (EltTys.size() != Record.size()-1)
64917a519f9SDimitry Andric         return Error("invalid type in struct type");
650f22ef01cSRoman Divacky       ResultTy = StructType::get(Context, EltTys, Record[0]);
651f22ef01cSRoman Divacky       break;
652f22ef01cSRoman Divacky     }
65317a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
65417a519f9SDimitry Andric       if (ConvertToString(Record, 0, TypeName))
65517a519f9SDimitry Andric         return Error("Invalid STRUCT_NAME record");
65617a519f9SDimitry Andric       continue;
65717a519f9SDimitry Andric 
65817a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
65917a519f9SDimitry Andric       if (Record.size() < 1)
66017a519f9SDimitry Andric         return Error("Invalid STRUCT type record");
66117a519f9SDimitry Andric 
66217a519f9SDimitry Andric       if (NumRecords >= TypeList.size())
66317a519f9SDimitry Andric         return Error("invalid TYPE table");
66417a519f9SDimitry Andric 
66517a519f9SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
66617a519f9SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
66717a519f9SDimitry Andric       if (Res) {
66817a519f9SDimitry Andric         Res->setName(TypeName);
66917a519f9SDimitry Andric         TypeList[NumRecords] = 0;
67017a519f9SDimitry Andric       } else  // Otherwise, create a new struct.
6716122f3e6SDimitry Andric         Res = StructType::create(Context, TypeName);
67217a519f9SDimitry Andric       TypeName.clear();
67317a519f9SDimitry Andric 
67417a519f9SDimitry Andric       SmallVector<Type*, 8> EltTys;
67517a519f9SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
67617a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
67717a519f9SDimitry Andric           EltTys.push_back(T);
67817a519f9SDimitry Andric         else
67917a519f9SDimitry Andric           break;
68017a519f9SDimitry Andric       }
68117a519f9SDimitry Andric       if (EltTys.size() != Record.size()-1)
68217a519f9SDimitry Andric         return Error("invalid STRUCT type record");
68317a519f9SDimitry Andric       Res->setBody(EltTys, Record[0]);
68417a519f9SDimitry Andric       ResultTy = Res;
68517a519f9SDimitry Andric       break;
68617a519f9SDimitry Andric     }
68717a519f9SDimitry Andric     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
68817a519f9SDimitry Andric       if (Record.size() != 1)
68917a519f9SDimitry Andric         return Error("Invalid OPAQUE type record");
69017a519f9SDimitry Andric 
69117a519f9SDimitry Andric       if (NumRecords >= TypeList.size())
69217a519f9SDimitry Andric         return Error("invalid TYPE table");
69317a519f9SDimitry Andric 
69417a519f9SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
69517a519f9SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
69617a519f9SDimitry Andric       if (Res) {
69717a519f9SDimitry Andric         Res->setName(TypeName);
69817a519f9SDimitry Andric         TypeList[NumRecords] = 0;
69917a519f9SDimitry Andric       } else  // Otherwise, create a new struct with no body.
7006122f3e6SDimitry Andric         Res = StructType::create(Context, TypeName);
70117a519f9SDimitry Andric       TypeName.clear();
70217a519f9SDimitry Andric       ResultTy = Res;
70317a519f9SDimitry Andric       break;
70417a519f9SDimitry Andric     }
705f22ef01cSRoman Divacky     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
706f22ef01cSRoman Divacky       if (Record.size() < 2)
707f22ef01cSRoman Divacky         return Error("Invalid ARRAY type record");
70817a519f9SDimitry Andric       if ((ResultTy = getTypeByID(Record[1])))
70917a519f9SDimitry Andric         ResultTy = ArrayType::get(ResultTy, Record[0]);
71017a519f9SDimitry Andric       else
71117a519f9SDimitry Andric         return Error("Invalid ARRAY type element");
712f22ef01cSRoman Divacky       break;
713f22ef01cSRoman Divacky     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
714f22ef01cSRoman Divacky       if (Record.size() < 2)
715f22ef01cSRoman Divacky         return Error("Invalid VECTOR type record");
71617a519f9SDimitry Andric       if ((ResultTy = getTypeByID(Record[1])))
71717a519f9SDimitry Andric         ResultTy = VectorType::get(ResultTy, Record[0]);
71817a519f9SDimitry Andric       else
71917a519f9SDimitry Andric         return Error("Invalid ARRAY type element");
720f22ef01cSRoman Divacky       break;
721f22ef01cSRoman Divacky     }
722f22ef01cSRoman Divacky 
72317a519f9SDimitry Andric     if (NumRecords >= TypeList.size())
72417a519f9SDimitry Andric       return Error("invalid TYPE table");
72517a519f9SDimitry Andric     assert(ResultTy && "Didn't read a type?");
72617a519f9SDimitry Andric     assert(TypeList[NumRecords] == 0 && "Already read type?");
72717a519f9SDimitry Andric     TypeList[NumRecords++] = ResultTy;
728f22ef01cSRoman Divacky   }
729f22ef01cSRoman Divacky }
73017a519f9SDimitry Andric 
73117a519f9SDimitry Andric // FIXME: Remove in LLVM 3.1
73217a519f9SDimitry Andric bool BitcodeReader::ParseOldTypeTable() {
73317a519f9SDimitry Andric   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_OLD))
73417a519f9SDimitry Andric     return Error("Malformed block record");
73517a519f9SDimitry Andric 
73617a519f9SDimitry Andric   if (!TypeList.empty())
73717a519f9SDimitry Andric     return Error("Multiple TYPE_BLOCKs found!");
73817a519f9SDimitry Andric 
73917a519f9SDimitry Andric 
74017a519f9SDimitry Andric   // While horrible, we have no good ordering of types in the bc file.  Just
74117a519f9SDimitry Andric   // iteratively parse types out of the bc file in multiple passes until we get
74217a519f9SDimitry Andric   // them all.  Do this by saving a cursor for the start of the type block.
74317a519f9SDimitry Andric   BitstreamCursor StartOfTypeBlockCursor(Stream);
74417a519f9SDimitry Andric 
74517a519f9SDimitry Andric   unsigned NumTypesRead = 0;
74617a519f9SDimitry Andric 
74717a519f9SDimitry Andric   SmallVector<uint64_t, 64> Record;
74817a519f9SDimitry Andric RestartScan:
74917a519f9SDimitry Andric   unsigned NextTypeID = 0;
75017a519f9SDimitry Andric   bool ReadAnyTypes = false;
75117a519f9SDimitry Andric 
75217a519f9SDimitry Andric   // Read all the records for this type table.
75317a519f9SDimitry Andric   while (1) {
75417a519f9SDimitry Andric     unsigned Code = Stream.ReadCode();
75517a519f9SDimitry Andric     if (Code == bitc::END_BLOCK) {
75617a519f9SDimitry Andric       if (NextTypeID != TypeList.size())
75717a519f9SDimitry Andric         return Error("Invalid type forward reference in TYPE_BLOCK_ID_OLD");
75817a519f9SDimitry Andric 
75917a519f9SDimitry Andric       // If we haven't read all of the types yet, iterate again.
76017a519f9SDimitry Andric       if (NumTypesRead != TypeList.size()) {
76117a519f9SDimitry Andric         // If we didn't successfully read any types in this pass, then we must
76217a519f9SDimitry Andric         // have an unhandled forward reference.
76317a519f9SDimitry Andric         if (!ReadAnyTypes)
76417a519f9SDimitry Andric           return Error("Obsolete bitcode contains unhandled recursive type");
76517a519f9SDimitry Andric 
76617a519f9SDimitry Andric         Stream = StartOfTypeBlockCursor;
76717a519f9SDimitry Andric         goto RestartScan;
76817a519f9SDimitry Andric       }
76917a519f9SDimitry Andric 
77017a519f9SDimitry Andric       if (Stream.ReadBlockEnd())
77117a519f9SDimitry Andric         return Error("Error at end of type table block");
77217a519f9SDimitry Andric       return false;
77317a519f9SDimitry Andric     }
77417a519f9SDimitry Andric 
77517a519f9SDimitry Andric     if (Code == bitc::ENTER_SUBBLOCK) {
77617a519f9SDimitry Andric       // No known subblocks, always skip them.
77717a519f9SDimitry Andric       Stream.ReadSubBlockID();
77817a519f9SDimitry Andric       if (Stream.SkipBlock())
77917a519f9SDimitry Andric         return Error("Malformed block record");
78017a519f9SDimitry Andric       continue;
78117a519f9SDimitry Andric     }
78217a519f9SDimitry Andric 
78317a519f9SDimitry Andric     if (Code == bitc::DEFINE_ABBREV) {
78417a519f9SDimitry Andric       Stream.ReadAbbrevRecord();
78517a519f9SDimitry Andric       continue;
78617a519f9SDimitry Andric     }
78717a519f9SDimitry Andric 
78817a519f9SDimitry Andric     // Read a record.
78917a519f9SDimitry Andric     Record.clear();
79017a519f9SDimitry Andric     Type *ResultTy = 0;
79117a519f9SDimitry Andric     switch (Stream.ReadRecord(Code, Record)) {
79217a519f9SDimitry Andric     default: return Error("unknown type in type table");
79317a519f9SDimitry Andric     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
79417a519f9SDimitry Andric       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
79517a519f9SDimitry Andric       // type list.  This allows us to reserve space.
79617a519f9SDimitry Andric       if (Record.size() < 1)
79717a519f9SDimitry Andric         return Error("Invalid TYPE_CODE_NUMENTRY record");
79817a519f9SDimitry Andric       TypeList.resize(Record[0]);
79917a519f9SDimitry Andric       continue;
80017a519f9SDimitry Andric     case bitc::TYPE_CODE_VOID:      // VOID
80117a519f9SDimitry Andric       ResultTy = Type::getVoidTy(Context);
80217a519f9SDimitry Andric       break;
80317a519f9SDimitry Andric     case bitc::TYPE_CODE_FLOAT:     // FLOAT
80417a519f9SDimitry Andric       ResultTy = Type::getFloatTy(Context);
80517a519f9SDimitry Andric       break;
80617a519f9SDimitry Andric     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
80717a519f9SDimitry Andric       ResultTy = Type::getDoubleTy(Context);
80817a519f9SDimitry Andric       break;
80917a519f9SDimitry Andric     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
81017a519f9SDimitry Andric       ResultTy = Type::getX86_FP80Ty(Context);
81117a519f9SDimitry Andric       break;
81217a519f9SDimitry Andric     case bitc::TYPE_CODE_FP128:     // FP128
81317a519f9SDimitry Andric       ResultTy = Type::getFP128Ty(Context);
81417a519f9SDimitry Andric       break;
81517a519f9SDimitry Andric     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
81617a519f9SDimitry Andric       ResultTy = Type::getPPC_FP128Ty(Context);
81717a519f9SDimitry Andric       break;
81817a519f9SDimitry Andric     case bitc::TYPE_CODE_LABEL:     // LABEL
81917a519f9SDimitry Andric       ResultTy = Type::getLabelTy(Context);
82017a519f9SDimitry Andric       break;
82117a519f9SDimitry Andric     case bitc::TYPE_CODE_METADATA:  // METADATA
82217a519f9SDimitry Andric       ResultTy = Type::getMetadataTy(Context);
82317a519f9SDimitry Andric       break;
82417a519f9SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
82517a519f9SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
82617a519f9SDimitry Andric       break;
82717a519f9SDimitry Andric     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
82817a519f9SDimitry Andric       if (Record.size() < 1)
82917a519f9SDimitry Andric         return Error("Invalid Integer type record");
83017a519f9SDimitry Andric       ResultTy = IntegerType::get(Context, Record[0]);
83117a519f9SDimitry Andric       break;
83217a519f9SDimitry Andric     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
83317a519f9SDimitry Andric       if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0)
8346122f3e6SDimitry Andric         ResultTy = StructType::create(Context);
83517a519f9SDimitry Andric       break;
83617a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_OLD: {// STRUCT_OLD
83717a519f9SDimitry Andric       if (NextTypeID >= TypeList.size()) break;
83817a519f9SDimitry Andric       // If we already read it, don't reprocess.
83917a519f9SDimitry Andric       if (TypeList[NextTypeID] &&
84017a519f9SDimitry Andric           !cast<StructType>(TypeList[NextTypeID])->isOpaque())
84117a519f9SDimitry Andric         break;
84217a519f9SDimitry Andric 
84317a519f9SDimitry Andric       // Set a type.
84417a519f9SDimitry Andric       if (TypeList[NextTypeID] == 0)
8456122f3e6SDimitry Andric         TypeList[NextTypeID] = StructType::create(Context);
84617a519f9SDimitry Andric 
84717a519f9SDimitry Andric       std::vector<Type*> EltTys;
84817a519f9SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
84917a519f9SDimitry Andric         if (Type *Elt = getTypeByIDOrNull(Record[i]))
85017a519f9SDimitry Andric           EltTys.push_back(Elt);
85117a519f9SDimitry Andric         else
85217a519f9SDimitry Andric           break;
85317a519f9SDimitry Andric       }
85417a519f9SDimitry Andric 
85517a519f9SDimitry Andric       if (EltTys.size() != Record.size()-1)
85617a519f9SDimitry Andric         break;      // Not all elements are ready.
85717a519f9SDimitry Andric 
85817a519f9SDimitry Andric       cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
85917a519f9SDimitry Andric       ResultTy = TypeList[NextTypeID];
86017a519f9SDimitry Andric       TypeList[NextTypeID] = 0;
86117a519f9SDimitry Andric       break;
86217a519f9SDimitry Andric     }
86317a519f9SDimitry Andric     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
86417a519f9SDimitry Andric       //          [pointee type, address space]
86517a519f9SDimitry Andric       if (Record.size() < 1)
86617a519f9SDimitry Andric         return Error("Invalid POINTER type record");
86717a519f9SDimitry Andric       unsigned AddressSpace = 0;
86817a519f9SDimitry Andric       if (Record.size() == 2)
86917a519f9SDimitry Andric         AddressSpace = Record[1];
87017a519f9SDimitry Andric       if ((ResultTy = getTypeByIDOrNull(Record[0])))
87117a519f9SDimitry Andric         ResultTy = PointerType::get(ResultTy, AddressSpace);
87217a519f9SDimitry Andric       break;
87317a519f9SDimitry Andric     }
87417a519f9SDimitry Andric     case bitc::TYPE_CODE_FUNCTION: {
87517a519f9SDimitry Andric       // FIXME: attrid is dead, remove it in LLVM 3.0
87617a519f9SDimitry Andric       // FUNCTION: [vararg, attrid, retty, paramty x N]
87717a519f9SDimitry Andric       if (Record.size() < 3)
87817a519f9SDimitry Andric         return Error("Invalid FUNCTION type record");
87917a519f9SDimitry Andric       std::vector<Type*> ArgTys;
88017a519f9SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
88117a519f9SDimitry Andric         if (Type *Elt = getTypeByIDOrNull(Record[i]))
88217a519f9SDimitry Andric           ArgTys.push_back(Elt);
88317a519f9SDimitry Andric         else
88417a519f9SDimitry Andric           break;
88517a519f9SDimitry Andric       }
88617a519f9SDimitry Andric       if (ArgTys.size()+3 != Record.size())
88717a519f9SDimitry Andric         break;  // Something was null.
88817a519f9SDimitry Andric       if ((ResultTy = getTypeByIDOrNull(Record[2])))
88917a519f9SDimitry Andric         ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
89017a519f9SDimitry Andric       break;
89117a519f9SDimitry Andric     }
89217a519f9SDimitry Andric     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
89317a519f9SDimitry Andric       if (Record.size() < 2)
89417a519f9SDimitry Andric         return Error("Invalid ARRAY type record");
89517a519f9SDimitry Andric       if ((ResultTy = getTypeByIDOrNull(Record[1])))
89617a519f9SDimitry Andric         ResultTy = ArrayType::get(ResultTy, Record[0]);
89717a519f9SDimitry Andric       break;
89817a519f9SDimitry Andric     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
89917a519f9SDimitry Andric       if (Record.size() < 2)
90017a519f9SDimitry Andric         return Error("Invalid VECTOR type record");
90117a519f9SDimitry Andric       if ((ResultTy = getTypeByIDOrNull(Record[1])))
90217a519f9SDimitry Andric         ResultTy = VectorType::get(ResultTy, Record[0]);
90317a519f9SDimitry Andric       break;
90417a519f9SDimitry Andric     }
90517a519f9SDimitry Andric 
90617a519f9SDimitry Andric     if (NextTypeID >= TypeList.size())
90717a519f9SDimitry Andric       return Error("invalid TYPE table");
90817a519f9SDimitry Andric 
90917a519f9SDimitry Andric     if (ResultTy && TypeList[NextTypeID] == 0) {
91017a519f9SDimitry Andric       ++NumTypesRead;
91117a519f9SDimitry Andric       ReadAnyTypes = true;
91217a519f9SDimitry Andric 
91317a519f9SDimitry Andric       TypeList[NextTypeID] = ResultTy;
91417a519f9SDimitry Andric     }
91517a519f9SDimitry Andric 
91617a519f9SDimitry Andric     ++NextTypeID;
91717a519f9SDimitry Andric   }
918f22ef01cSRoman Divacky }
919f22ef01cSRoman Divacky 
920f22ef01cSRoman Divacky 
92117a519f9SDimitry Andric bool BitcodeReader::ParseOldTypeSymbolTable() {
92217a519f9SDimitry Andric   if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID_OLD))
923f22ef01cSRoman Divacky     return Error("Malformed block record");
924f22ef01cSRoman Divacky 
925f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
926f22ef01cSRoman Divacky 
927f22ef01cSRoman Divacky   // Read all the records for this type table.
928f22ef01cSRoman Divacky   std::string TypeName;
929f22ef01cSRoman Divacky   while (1) {
930f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
931f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK) {
932f22ef01cSRoman Divacky       if (Stream.ReadBlockEnd())
933f22ef01cSRoman Divacky         return Error("Error at end of type symbol table block");
934f22ef01cSRoman Divacky       return false;
935f22ef01cSRoman Divacky     }
936f22ef01cSRoman Divacky 
937f22ef01cSRoman Divacky     if (Code == bitc::ENTER_SUBBLOCK) {
938f22ef01cSRoman Divacky       // No known subblocks, always skip them.
939f22ef01cSRoman Divacky       Stream.ReadSubBlockID();
940f22ef01cSRoman Divacky       if (Stream.SkipBlock())
941f22ef01cSRoman Divacky         return Error("Malformed block record");
942f22ef01cSRoman Divacky       continue;
943f22ef01cSRoman Divacky     }
944f22ef01cSRoman Divacky 
945f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
946f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
947f22ef01cSRoman Divacky       continue;
948f22ef01cSRoman Divacky     }
949f22ef01cSRoman Divacky 
950f22ef01cSRoman Divacky     // Read a record.
951f22ef01cSRoman Divacky     Record.clear();
952f22ef01cSRoman Divacky     switch (Stream.ReadRecord(Code, Record)) {
953f22ef01cSRoman Divacky     default:  // Default behavior: unknown type.
954f22ef01cSRoman Divacky       break;
955f22ef01cSRoman Divacky     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
956f22ef01cSRoman Divacky       if (ConvertToString(Record, 1, TypeName))
957f22ef01cSRoman Divacky         return Error("Invalid TST_ENTRY record");
958f22ef01cSRoman Divacky       unsigned TypeID = Record[0];
959f22ef01cSRoman Divacky       if (TypeID >= TypeList.size())
960f22ef01cSRoman Divacky         return Error("Invalid Type ID in TST_ENTRY record");
961f22ef01cSRoman Divacky 
96217a519f9SDimitry Andric       // Only apply the type name to a struct type with no name.
96317a519f9SDimitry Andric       if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID]))
9646122f3e6SDimitry Andric         if (!STy->isLiteral() && !STy->hasName())
96517a519f9SDimitry Andric           STy->setName(TypeName);
966f22ef01cSRoman Divacky       TypeName.clear();
967f22ef01cSRoman Divacky       break;
968f22ef01cSRoman Divacky     }
969f22ef01cSRoman Divacky   }
970f22ef01cSRoman Divacky }
971f22ef01cSRoman Divacky 
972f22ef01cSRoman Divacky bool BitcodeReader::ParseValueSymbolTable() {
973f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
974f22ef01cSRoman Divacky     return Error("Malformed block record");
975f22ef01cSRoman Divacky 
976f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
977f22ef01cSRoman Divacky 
978f22ef01cSRoman Divacky   // Read all the records for this value table.
979f22ef01cSRoman Divacky   SmallString<128> ValueName;
980f22ef01cSRoman Divacky   while (1) {
981f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
982f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK) {
983f22ef01cSRoman Divacky       if (Stream.ReadBlockEnd())
984f22ef01cSRoman Divacky         return Error("Error at end of value symbol table block");
985f22ef01cSRoman Divacky       return false;
986f22ef01cSRoman Divacky     }
987f22ef01cSRoman Divacky     if (Code == bitc::ENTER_SUBBLOCK) {
988f22ef01cSRoman Divacky       // No known subblocks, always skip them.
989f22ef01cSRoman Divacky       Stream.ReadSubBlockID();
990f22ef01cSRoman Divacky       if (Stream.SkipBlock())
991f22ef01cSRoman Divacky         return Error("Malformed block record");
992f22ef01cSRoman Divacky       continue;
993f22ef01cSRoman Divacky     }
994f22ef01cSRoman Divacky 
995f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
996f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
997f22ef01cSRoman Divacky       continue;
998f22ef01cSRoman Divacky     }
999f22ef01cSRoman Divacky 
1000f22ef01cSRoman Divacky     // Read a record.
1001f22ef01cSRoman Divacky     Record.clear();
1002f22ef01cSRoman Divacky     switch (Stream.ReadRecord(Code, Record)) {
1003f22ef01cSRoman Divacky     default:  // Default behavior: unknown type.
1004f22ef01cSRoman Divacky       break;
1005f22ef01cSRoman Divacky     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1006f22ef01cSRoman Divacky       if (ConvertToString(Record, 1, ValueName))
1007f22ef01cSRoman Divacky         return Error("Invalid VST_ENTRY record");
1008f22ef01cSRoman Divacky       unsigned ValueID = Record[0];
1009f22ef01cSRoman Divacky       if (ValueID >= ValueList.size())
1010f22ef01cSRoman Divacky         return Error("Invalid Value ID in VST_ENTRY record");
1011f22ef01cSRoman Divacky       Value *V = ValueList[ValueID];
1012f22ef01cSRoman Divacky 
1013f22ef01cSRoman Divacky       V->setName(StringRef(ValueName.data(), ValueName.size()));
1014f22ef01cSRoman Divacky       ValueName.clear();
1015f22ef01cSRoman Divacky       break;
1016f22ef01cSRoman Divacky     }
1017f22ef01cSRoman Divacky     case bitc::VST_CODE_BBENTRY: {
1018f22ef01cSRoman Divacky       if (ConvertToString(Record, 1, ValueName))
1019f22ef01cSRoman Divacky         return Error("Invalid VST_BBENTRY record");
1020f22ef01cSRoman Divacky       BasicBlock *BB = getBasicBlock(Record[0]);
1021f22ef01cSRoman Divacky       if (BB == 0)
1022f22ef01cSRoman Divacky         return Error("Invalid BB ID in VST_BBENTRY record");
1023f22ef01cSRoman Divacky 
1024f22ef01cSRoman Divacky       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1025f22ef01cSRoman Divacky       ValueName.clear();
1026f22ef01cSRoman Divacky       break;
1027f22ef01cSRoman Divacky     }
1028f22ef01cSRoman Divacky     }
1029f22ef01cSRoman Divacky   }
1030f22ef01cSRoman Divacky }
1031f22ef01cSRoman Divacky 
1032f22ef01cSRoman Divacky bool BitcodeReader::ParseMetadata() {
1033f22ef01cSRoman Divacky   unsigned NextMDValueNo = MDValueList.size();
1034f22ef01cSRoman Divacky 
1035f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1036f22ef01cSRoman Divacky     return Error("Malformed block record");
1037f22ef01cSRoman Divacky 
1038f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1039f22ef01cSRoman Divacky 
1040f22ef01cSRoman Divacky   // Read all the records.
1041f22ef01cSRoman Divacky   while (1) {
1042f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
1043f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK) {
1044f22ef01cSRoman Divacky       if (Stream.ReadBlockEnd())
1045f22ef01cSRoman Divacky         return Error("Error at end of PARAMATTR block");
1046f22ef01cSRoman Divacky       return false;
1047f22ef01cSRoman Divacky     }
1048f22ef01cSRoman Divacky 
1049f22ef01cSRoman Divacky     if (Code == bitc::ENTER_SUBBLOCK) {
1050f22ef01cSRoman Divacky       // No known subblocks, always skip them.
1051f22ef01cSRoman Divacky       Stream.ReadSubBlockID();
1052f22ef01cSRoman Divacky       if (Stream.SkipBlock())
1053f22ef01cSRoman Divacky         return Error("Malformed block record");
1054f22ef01cSRoman Divacky       continue;
1055f22ef01cSRoman Divacky     }
1056f22ef01cSRoman Divacky 
1057f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
1058f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
1059f22ef01cSRoman Divacky       continue;
1060f22ef01cSRoman Divacky     }
1061f22ef01cSRoman Divacky 
1062f22ef01cSRoman Divacky     bool IsFunctionLocal = false;
1063f22ef01cSRoman Divacky     // Read a record.
1064f22ef01cSRoman Divacky     Record.clear();
1065e580952dSDimitry Andric     Code = Stream.ReadRecord(Code, Record);
1066e580952dSDimitry Andric     switch (Code) {
1067f22ef01cSRoman Divacky     default:  // Default behavior: ignore.
1068f22ef01cSRoman Divacky       break;
1069f22ef01cSRoman Divacky     case bitc::METADATA_NAME: {
1070f22ef01cSRoman Divacky       // Read named of the named metadata.
1071f22ef01cSRoman Divacky       unsigned NameLength = Record.size();
1072f22ef01cSRoman Divacky       SmallString<8> Name;
1073f22ef01cSRoman Divacky       Name.resize(NameLength);
1074f22ef01cSRoman Divacky       for (unsigned i = 0; i != NameLength; ++i)
1075f22ef01cSRoman Divacky         Name[i] = Record[i];
1076f22ef01cSRoman Divacky       Record.clear();
1077f22ef01cSRoman Divacky       Code = Stream.ReadCode();
1078f22ef01cSRoman Divacky 
107917a519f9SDimitry Andric       // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1080e580952dSDimitry Andric       unsigned NextBitCode = Stream.ReadRecord(Code, Record);
108117a519f9SDimitry Andric       assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1082f22ef01cSRoman Divacky 
1083f22ef01cSRoman Divacky       // Read named metadata elements.
1084f22ef01cSRoman Divacky       unsigned Size = Record.size();
1085e580952dSDimitry Andric       NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1086f22ef01cSRoman Divacky       for (unsigned i = 0; i != Size; ++i) {
1087f22ef01cSRoman Divacky         MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1088f22ef01cSRoman Divacky         if (MD == 0)
1089f22ef01cSRoman Divacky           return Error("Malformed metadata record");
1090e580952dSDimitry Andric         NMD->addOperand(MD);
1091f22ef01cSRoman Divacky       }
1092f22ef01cSRoman Divacky       break;
1093f22ef01cSRoman Divacky     }
109417a519f9SDimitry Andric     case bitc::METADATA_FN_NODE:
1095f22ef01cSRoman Divacky       IsFunctionLocal = true;
1096f22ef01cSRoman Divacky       // fall-through
109717a519f9SDimitry Andric     case bitc::METADATA_NODE: {
1098ffd1746dSEd Schouten       if (Record.size() % 2 == 1)
109917a519f9SDimitry Andric         return Error("Invalid METADATA_NODE record");
1100f22ef01cSRoman Divacky 
1101f22ef01cSRoman Divacky       unsigned Size = Record.size();
1102f22ef01cSRoman Divacky       SmallVector<Value*, 8> Elts;
1103f22ef01cSRoman Divacky       for (unsigned i = 0; i != Size; i += 2) {
11046122f3e6SDimitry Andric         Type *Ty = getTypeByID(Record[i]);
110517a519f9SDimitry Andric         if (!Ty) return Error("Invalid METADATA_NODE record");
1106f22ef01cSRoman Divacky         if (Ty->isMetadataTy())
1107f22ef01cSRoman Divacky           Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1108f22ef01cSRoman Divacky         else if (!Ty->isVoidTy())
1109f22ef01cSRoman Divacky           Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1110f22ef01cSRoman Divacky         else
1111f22ef01cSRoman Divacky           Elts.push_back(NULL);
1112f22ef01cSRoman Divacky       }
11133b0f4066SDimitry Andric       Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1114f22ef01cSRoman Divacky       IsFunctionLocal = false;
1115f22ef01cSRoman Divacky       MDValueList.AssignValue(V, NextMDValueNo++);
1116f22ef01cSRoman Divacky       break;
1117f22ef01cSRoman Divacky     }
1118f22ef01cSRoman Divacky     case bitc::METADATA_STRING: {
1119f22ef01cSRoman Divacky       unsigned MDStringLength = Record.size();
1120f22ef01cSRoman Divacky       SmallString<8> String;
1121f22ef01cSRoman Divacky       String.resize(MDStringLength);
1122f22ef01cSRoman Divacky       for (unsigned i = 0; i != MDStringLength; ++i)
1123f22ef01cSRoman Divacky         String[i] = Record[i];
1124f22ef01cSRoman Divacky       Value *V = MDString::get(Context,
1125f22ef01cSRoman Divacky                                StringRef(String.data(), String.size()));
1126f22ef01cSRoman Divacky       MDValueList.AssignValue(V, NextMDValueNo++);
1127f22ef01cSRoman Divacky       break;
1128f22ef01cSRoman Divacky     }
1129f22ef01cSRoman Divacky     case bitc::METADATA_KIND: {
1130f22ef01cSRoman Divacky       unsigned RecordLength = Record.size();
1131f22ef01cSRoman Divacky       if (Record.empty() || RecordLength < 2)
1132f22ef01cSRoman Divacky         return Error("Invalid METADATA_KIND record");
1133f22ef01cSRoman Divacky       SmallString<8> Name;
1134f22ef01cSRoman Divacky       Name.resize(RecordLength-1);
1135f22ef01cSRoman Divacky       unsigned Kind = Record[0];
1136f22ef01cSRoman Divacky       for (unsigned i = 1; i != RecordLength; ++i)
1137f22ef01cSRoman Divacky         Name[i-1] = Record[i];
1138f22ef01cSRoman Divacky 
1139f22ef01cSRoman Divacky       unsigned NewKind = TheModule->getMDKindID(Name.str());
1140e580952dSDimitry Andric       if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1141e580952dSDimitry Andric         return Error("Conflicting METADATA_KIND records");
1142f22ef01cSRoman Divacky       break;
1143f22ef01cSRoman Divacky     }
1144f22ef01cSRoman Divacky     }
1145f22ef01cSRoman Divacky   }
1146f22ef01cSRoman Divacky }
1147f22ef01cSRoman Divacky 
1148f22ef01cSRoman Divacky /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
1149f22ef01cSRoman Divacky /// the LSB for dense VBR encoding.
1150f22ef01cSRoman Divacky static uint64_t DecodeSignRotatedValue(uint64_t V) {
1151f22ef01cSRoman Divacky   if ((V & 1) == 0)
1152f22ef01cSRoman Divacky     return V >> 1;
1153f22ef01cSRoman Divacky   if (V != 1)
1154f22ef01cSRoman Divacky     return -(V >> 1);
1155f22ef01cSRoman Divacky   // There is no such thing as -0 with integers.  "-0" really means MININT.
1156f22ef01cSRoman Divacky   return 1ULL << 63;
1157f22ef01cSRoman Divacky }
1158f22ef01cSRoman Divacky 
1159f22ef01cSRoman Divacky /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1160f22ef01cSRoman Divacky /// values and aliases that we can.
1161f22ef01cSRoman Divacky bool BitcodeReader::ResolveGlobalAndAliasInits() {
1162f22ef01cSRoman Divacky   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1163f22ef01cSRoman Divacky   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1164f22ef01cSRoman Divacky 
1165f22ef01cSRoman Divacky   GlobalInitWorklist.swap(GlobalInits);
1166f22ef01cSRoman Divacky   AliasInitWorklist.swap(AliasInits);
1167f22ef01cSRoman Divacky 
1168f22ef01cSRoman Divacky   while (!GlobalInitWorklist.empty()) {
1169f22ef01cSRoman Divacky     unsigned ValID = GlobalInitWorklist.back().second;
1170f22ef01cSRoman Divacky     if (ValID >= ValueList.size()) {
1171f22ef01cSRoman Divacky       // Not ready to resolve this yet, it requires something later in the file.
1172f22ef01cSRoman Divacky       GlobalInits.push_back(GlobalInitWorklist.back());
1173f22ef01cSRoman Divacky     } else {
1174f22ef01cSRoman Divacky       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1175f22ef01cSRoman Divacky         GlobalInitWorklist.back().first->setInitializer(C);
1176f22ef01cSRoman Divacky       else
1177f22ef01cSRoman Divacky         return Error("Global variable initializer is not a constant!");
1178f22ef01cSRoman Divacky     }
1179f22ef01cSRoman Divacky     GlobalInitWorklist.pop_back();
1180f22ef01cSRoman Divacky   }
1181f22ef01cSRoman Divacky 
1182f22ef01cSRoman Divacky   while (!AliasInitWorklist.empty()) {
1183f22ef01cSRoman Divacky     unsigned ValID = AliasInitWorklist.back().second;
1184f22ef01cSRoman Divacky     if (ValID >= ValueList.size()) {
1185f22ef01cSRoman Divacky       AliasInits.push_back(AliasInitWorklist.back());
1186f22ef01cSRoman Divacky     } else {
1187f22ef01cSRoman Divacky       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1188f22ef01cSRoman Divacky         AliasInitWorklist.back().first->setAliasee(C);
1189f22ef01cSRoman Divacky       else
1190f22ef01cSRoman Divacky         return Error("Alias initializer is not a constant!");
1191f22ef01cSRoman Divacky     }
1192f22ef01cSRoman Divacky     AliasInitWorklist.pop_back();
1193f22ef01cSRoman Divacky   }
1194f22ef01cSRoman Divacky   return false;
1195f22ef01cSRoman Divacky }
1196f22ef01cSRoman Divacky 
1197f22ef01cSRoman Divacky bool BitcodeReader::ParseConstants() {
1198f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1199f22ef01cSRoman Divacky     return Error("Malformed block record");
1200f22ef01cSRoman Divacky 
1201f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1202f22ef01cSRoman Divacky 
1203f22ef01cSRoman Divacky   // Read all the records for this value table.
12046122f3e6SDimitry Andric   Type *CurTy = Type::getInt32Ty(Context);
1205f22ef01cSRoman Divacky   unsigned NextCstNo = ValueList.size();
1206f22ef01cSRoman Divacky   while (1) {
1207f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
1208f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK)
1209f22ef01cSRoman Divacky       break;
1210f22ef01cSRoman Divacky 
1211f22ef01cSRoman Divacky     if (Code == bitc::ENTER_SUBBLOCK) {
1212f22ef01cSRoman Divacky       // No known subblocks, always skip them.
1213f22ef01cSRoman Divacky       Stream.ReadSubBlockID();
1214f22ef01cSRoman Divacky       if (Stream.SkipBlock())
1215f22ef01cSRoman Divacky         return Error("Malformed block record");
1216f22ef01cSRoman Divacky       continue;
1217f22ef01cSRoman Divacky     }
1218f22ef01cSRoman Divacky 
1219f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
1220f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
1221f22ef01cSRoman Divacky       continue;
1222f22ef01cSRoman Divacky     }
1223f22ef01cSRoman Divacky 
1224f22ef01cSRoman Divacky     // Read a record.
1225f22ef01cSRoman Divacky     Record.clear();
1226f22ef01cSRoman Divacky     Value *V = 0;
1227f22ef01cSRoman Divacky     unsigned BitCode = Stream.ReadRecord(Code, Record);
1228f22ef01cSRoman Divacky     switch (BitCode) {
1229f22ef01cSRoman Divacky     default:  // Default behavior: unknown constant
1230f22ef01cSRoman Divacky     case bitc::CST_CODE_UNDEF:     // UNDEF
1231f22ef01cSRoman Divacky       V = UndefValue::get(CurTy);
1232f22ef01cSRoman Divacky       break;
1233f22ef01cSRoman Divacky     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1234f22ef01cSRoman Divacky       if (Record.empty())
1235f22ef01cSRoman Divacky         return Error("Malformed CST_SETTYPE record");
1236f22ef01cSRoman Divacky       if (Record[0] >= TypeList.size())
1237f22ef01cSRoman Divacky         return Error("Invalid Type ID in CST_SETTYPE record");
1238f22ef01cSRoman Divacky       CurTy = TypeList[Record[0]];
1239f22ef01cSRoman Divacky       continue;  // Skip the ValueList manipulation.
1240f22ef01cSRoman Divacky     case bitc::CST_CODE_NULL:      // NULL
1241f22ef01cSRoman Divacky       V = Constant::getNullValue(CurTy);
1242f22ef01cSRoman Divacky       break;
1243f22ef01cSRoman Divacky     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1244f22ef01cSRoman Divacky       if (!CurTy->isIntegerTy() || Record.empty())
1245f22ef01cSRoman Divacky         return Error("Invalid CST_INTEGER record");
1246f22ef01cSRoman Divacky       V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1247f22ef01cSRoman Divacky       break;
1248f22ef01cSRoman Divacky     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1249f22ef01cSRoman Divacky       if (!CurTy->isIntegerTy() || Record.empty())
1250f22ef01cSRoman Divacky         return Error("Invalid WIDE_INTEGER record");
1251f22ef01cSRoman Divacky 
1252f22ef01cSRoman Divacky       unsigned NumWords = Record.size();
1253f22ef01cSRoman Divacky       SmallVector<uint64_t, 8> Words;
1254f22ef01cSRoman Divacky       Words.resize(NumWords);
1255f22ef01cSRoman Divacky       for (unsigned i = 0; i != NumWords; ++i)
1256f22ef01cSRoman Divacky         Words[i] = DecodeSignRotatedValue(Record[i]);
1257f22ef01cSRoman Divacky       V = ConstantInt::get(Context,
1258f22ef01cSRoman Divacky                            APInt(cast<IntegerType>(CurTy)->getBitWidth(),
12596122f3e6SDimitry Andric                                  Words));
1260f22ef01cSRoman Divacky       break;
1261f22ef01cSRoman Divacky     }
1262f22ef01cSRoman Divacky     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1263f22ef01cSRoman Divacky       if (Record.empty())
1264f22ef01cSRoman Divacky         return Error("Invalid FLOAT record");
1265f22ef01cSRoman Divacky       if (CurTy->isFloatTy())
1266f22ef01cSRoman Divacky         V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1267f22ef01cSRoman Divacky       else if (CurTy->isDoubleTy())
1268f22ef01cSRoman Divacky         V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1269f22ef01cSRoman Divacky       else if (CurTy->isX86_FP80Ty()) {
1270f22ef01cSRoman Divacky         // Bits are not stored the same way as a normal i80 APInt, compensate.
1271f22ef01cSRoman Divacky         uint64_t Rearrange[2];
1272f22ef01cSRoman Divacky         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1273f22ef01cSRoman Divacky         Rearrange[1] = Record[0] >> 48;
12746122f3e6SDimitry Andric         V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1275f22ef01cSRoman Divacky       } else if (CurTy->isFP128Ty())
12766122f3e6SDimitry Andric         V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1277f22ef01cSRoman Divacky       else if (CurTy->isPPC_FP128Ty())
12786122f3e6SDimitry Andric         V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1279f22ef01cSRoman Divacky       else
1280f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);
1281f22ef01cSRoman Divacky       break;
1282f22ef01cSRoman Divacky     }
1283f22ef01cSRoman Divacky 
1284f22ef01cSRoman Divacky     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1285f22ef01cSRoman Divacky       if (Record.empty())
1286f22ef01cSRoman Divacky         return Error("Invalid CST_AGGREGATE record");
1287f22ef01cSRoman Divacky 
1288f22ef01cSRoman Divacky       unsigned Size = Record.size();
1289f22ef01cSRoman Divacky       std::vector<Constant*> Elts;
1290f22ef01cSRoman Divacky 
12916122f3e6SDimitry Andric       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1292f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
1293f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1294f22ef01cSRoman Divacky                                                      STy->getElementType(i)));
1295f22ef01cSRoman Divacky         V = ConstantStruct::get(STy, Elts);
12966122f3e6SDimitry Andric       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
12976122f3e6SDimitry Andric         Type *EltTy = ATy->getElementType();
1298f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
1299f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1300f22ef01cSRoman Divacky         V = ConstantArray::get(ATy, Elts);
13016122f3e6SDimitry Andric       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
13026122f3e6SDimitry Andric         Type *EltTy = VTy->getElementType();
1303f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
1304f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1305f22ef01cSRoman Divacky         V = ConstantVector::get(Elts);
1306f22ef01cSRoman Divacky       } else {
1307f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);
1308f22ef01cSRoman Divacky       }
1309f22ef01cSRoman Divacky       break;
1310f22ef01cSRoman Divacky     }
1311f22ef01cSRoman Divacky     case bitc::CST_CODE_STRING: { // STRING: [values]
1312f22ef01cSRoman Divacky       if (Record.empty())
1313f22ef01cSRoman Divacky         return Error("Invalid CST_AGGREGATE record");
1314f22ef01cSRoman Divacky 
13156122f3e6SDimitry Andric       ArrayType *ATy = cast<ArrayType>(CurTy);
13166122f3e6SDimitry Andric       Type *EltTy = ATy->getElementType();
1317f22ef01cSRoman Divacky 
1318f22ef01cSRoman Divacky       unsigned Size = Record.size();
1319f22ef01cSRoman Divacky       std::vector<Constant*> Elts;
1320f22ef01cSRoman Divacky       for (unsigned i = 0; i != Size; ++i)
1321f22ef01cSRoman Divacky         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1322f22ef01cSRoman Divacky       V = ConstantArray::get(ATy, Elts);
1323f22ef01cSRoman Divacky       break;
1324f22ef01cSRoman Divacky     }
1325f22ef01cSRoman Divacky     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1326f22ef01cSRoman Divacky       if (Record.empty())
1327f22ef01cSRoman Divacky         return Error("Invalid CST_AGGREGATE record");
1328f22ef01cSRoman Divacky 
13296122f3e6SDimitry Andric       ArrayType *ATy = cast<ArrayType>(CurTy);
13306122f3e6SDimitry Andric       Type *EltTy = ATy->getElementType();
1331f22ef01cSRoman Divacky 
1332f22ef01cSRoman Divacky       unsigned Size = Record.size();
1333f22ef01cSRoman Divacky       std::vector<Constant*> Elts;
1334f22ef01cSRoman Divacky       for (unsigned i = 0; i != Size; ++i)
1335f22ef01cSRoman Divacky         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1336f22ef01cSRoman Divacky       Elts.push_back(Constant::getNullValue(EltTy));
1337f22ef01cSRoman Divacky       V = ConstantArray::get(ATy, Elts);
1338f22ef01cSRoman Divacky       break;
1339f22ef01cSRoman Divacky     }
1340f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1341f22ef01cSRoman Divacky       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1342f22ef01cSRoman Divacky       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1343f22ef01cSRoman Divacky       if (Opc < 0) {
1344f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);  // Unknown binop.
1345f22ef01cSRoman Divacky       } else {
1346f22ef01cSRoman Divacky         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1347f22ef01cSRoman Divacky         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1348f22ef01cSRoman Divacky         unsigned Flags = 0;
1349f22ef01cSRoman Divacky         if (Record.size() >= 4) {
1350f22ef01cSRoman Divacky           if (Opc == Instruction::Add ||
1351f22ef01cSRoman Divacky               Opc == Instruction::Sub ||
13522754fe60SDimitry Andric               Opc == Instruction::Mul ||
13532754fe60SDimitry Andric               Opc == Instruction::Shl) {
1354f22ef01cSRoman Divacky             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1355f22ef01cSRoman Divacky               Flags |= OverflowingBinaryOperator::NoSignedWrap;
1356f22ef01cSRoman Divacky             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1357f22ef01cSRoman Divacky               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
13582754fe60SDimitry Andric           } else if (Opc == Instruction::SDiv ||
13592754fe60SDimitry Andric                      Opc == Instruction::UDiv ||
13602754fe60SDimitry Andric                      Opc == Instruction::LShr ||
13612754fe60SDimitry Andric                      Opc == Instruction::AShr) {
13622754fe60SDimitry Andric             if (Record[3] & (1 << bitc::PEO_EXACT))
1363f22ef01cSRoman Divacky               Flags |= SDivOperator::IsExact;
1364f22ef01cSRoman Divacky           }
1365f22ef01cSRoman Divacky         }
1366f22ef01cSRoman Divacky         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1367f22ef01cSRoman Divacky       }
1368f22ef01cSRoman Divacky       break;
1369f22ef01cSRoman Divacky     }
1370f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1371f22ef01cSRoman Divacky       if (Record.size() < 3) return Error("Invalid CE_CAST record");
1372f22ef01cSRoman Divacky       int Opc = GetDecodedCastOpcode(Record[0]);
1373f22ef01cSRoman Divacky       if (Opc < 0) {
1374f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);  // Unknown cast.
1375f22ef01cSRoman Divacky       } else {
13766122f3e6SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
1377f22ef01cSRoman Divacky         if (!OpTy) return Error("Invalid CE_CAST record");
1378f22ef01cSRoman Divacky         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1379f22ef01cSRoman Divacky         V = ConstantExpr::getCast(Opc, Op, CurTy);
1380f22ef01cSRoman Divacky       }
1381f22ef01cSRoman Divacky       break;
1382f22ef01cSRoman Divacky     }
1383f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_INBOUNDS_GEP:
1384f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1385f22ef01cSRoman Divacky       if (Record.size() & 1) return Error("Invalid CE_GEP record");
1386f22ef01cSRoman Divacky       SmallVector<Constant*, 16> Elts;
1387f22ef01cSRoman Divacky       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
13886122f3e6SDimitry Andric         Type *ElTy = getTypeByID(Record[i]);
1389f22ef01cSRoman Divacky         if (!ElTy) return Error("Invalid CE_GEP record");
1390f22ef01cSRoman Divacky         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1391f22ef01cSRoman Divacky       }
13926122f3e6SDimitry Andric       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
13936122f3e6SDimitry Andric       V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
13946122f3e6SDimitry Andric                                          BitCode ==
13956122f3e6SDimitry Andric                                            bitc::CST_CODE_CE_INBOUNDS_GEP);
1396f22ef01cSRoman Divacky       break;
1397f22ef01cSRoman Divacky     }
1398f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1399f22ef01cSRoman Divacky       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1400f22ef01cSRoman Divacky       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1401f22ef01cSRoman Divacky                                                               Type::getInt1Ty(Context)),
1402f22ef01cSRoman Divacky                                   ValueList.getConstantFwdRef(Record[1],CurTy),
1403f22ef01cSRoman Divacky                                   ValueList.getConstantFwdRef(Record[2],CurTy));
1404f22ef01cSRoman Divacky       break;
1405f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1406f22ef01cSRoman Divacky       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
14076122f3e6SDimitry Andric       VectorType *OpTy =
1408f22ef01cSRoman Divacky         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1409f22ef01cSRoman Divacky       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1410f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1411f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1412f22ef01cSRoman Divacky       V = ConstantExpr::getExtractElement(Op0, Op1);
1413f22ef01cSRoman Divacky       break;
1414f22ef01cSRoman Divacky     }
1415f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
14166122f3e6SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1417f22ef01cSRoman Divacky       if (Record.size() < 3 || OpTy == 0)
1418f22ef01cSRoman Divacky         return Error("Invalid CE_INSERTELT record");
1419f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1420f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1421f22ef01cSRoman Divacky                                                   OpTy->getElementType());
1422f22ef01cSRoman Divacky       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1423f22ef01cSRoman Divacky       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1424f22ef01cSRoman Divacky       break;
1425f22ef01cSRoman Divacky     }
1426f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
14276122f3e6SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1428f22ef01cSRoman Divacky       if (Record.size() < 3 || OpTy == 0)
1429f22ef01cSRoman Divacky         return Error("Invalid CE_SHUFFLEVEC record");
1430f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1431f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
14326122f3e6SDimitry Andric       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1433f22ef01cSRoman Divacky                                                  OpTy->getNumElements());
1434f22ef01cSRoman Divacky       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1435f22ef01cSRoman Divacky       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1436f22ef01cSRoman Divacky       break;
1437f22ef01cSRoman Divacky     }
1438f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
14396122f3e6SDimitry Andric       VectorType *RTy = dyn_cast<VectorType>(CurTy);
14406122f3e6SDimitry Andric       VectorType *OpTy =
14412754fe60SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1442f22ef01cSRoman Divacky       if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1443f22ef01cSRoman Divacky         return Error("Invalid CE_SHUFVEC_EX record");
1444f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1445f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
14466122f3e6SDimitry Andric       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1447f22ef01cSRoman Divacky                                                  RTy->getNumElements());
1448f22ef01cSRoman Divacky       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1449f22ef01cSRoman Divacky       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1450f22ef01cSRoman Divacky       break;
1451f22ef01cSRoman Divacky     }
1452f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1453f22ef01cSRoman Divacky       if (Record.size() < 4) return Error("Invalid CE_CMP record");
14546122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
1455f22ef01cSRoman Divacky       if (OpTy == 0) return Error("Invalid CE_CMP record");
1456f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1457f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1458f22ef01cSRoman Divacky 
1459f22ef01cSRoman Divacky       if (OpTy->isFPOrFPVectorTy())
1460f22ef01cSRoman Divacky         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1461f22ef01cSRoman Divacky       else
1462f22ef01cSRoman Divacky         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1463f22ef01cSRoman Divacky       break;
1464f22ef01cSRoman Divacky     }
1465f22ef01cSRoman Divacky     case bitc::CST_CODE_INLINEASM: {
1466f22ef01cSRoman Divacky       if (Record.size() < 2) return Error("Invalid INLINEASM record");
1467f22ef01cSRoman Divacky       std::string AsmStr, ConstrStr;
1468f22ef01cSRoman Divacky       bool HasSideEffects = Record[0] & 1;
1469f22ef01cSRoman Divacky       bool IsAlignStack = Record[0] >> 1;
1470f22ef01cSRoman Divacky       unsigned AsmStrSize = Record[1];
1471f22ef01cSRoman Divacky       if (2+AsmStrSize >= Record.size())
1472f22ef01cSRoman Divacky         return Error("Invalid INLINEASM record");
1473f22ef01cSRoman Divacky       unsigned ConstStrSize = Record[2+AsmStrSize];
1474f22ef01cSRoman Divacky       if (3+AsmStrSize+ConstStrSize > Record.size())
1475f22ef01cSRoman Divacky         return Error("Invalid INLINEASM record");
1476f22ef01cSRoman Divacky 
1477f22ef01cSRoman Divacky       for (unsigned i = 0; i != AsmStrSize; ++i)
1478f22ef01cSRoman Divacky         AsmStr += (char)Record[2+i];
1479f22ef01cSRoman Divacky       for (unsigned i = 0; i != ConstStrSize; ++i)
1480f22ef01cSRoman Divacky         ConstrStr += (char)Record[3+AsmStrSize+i];
14816122f3e6SDimitry Andric       PointerType *PTy = cast<PointerType>(CurTy);
1482f22ef01cSRoman Divacky       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1483f22ef01cSRoman Divacky                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1484f22ef01cSRoman Divacky       break;
1485f22ef01cSRoman Divacky     }
1486f22ef01cSRoman Divacky     case bitc::CST_CODE_BLOCKADDRESS:{
1487f22ef01cSRoman Divacky       if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
14886122f3e6SDimitry Andric       Type *FnTy = getTypeByID(Record[0]);
1489f22ef01cSRoman Divacky       if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1490f22ef01cSRoman Divacky       Function *Fn =
1491f22ef01cSRoman Divacky         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1492f22ef01cSRoman Divacky       if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1493f22ef01cSRoman Divacky 
1494f22ef01cSRoman Divacky       GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1495f22ef01cSRoman Divacky                                                   Type::getInt8Ty(Context),
1496f22ef01cSRoman Divacky                                             false, GlobalValue::InternalLinkage,
1497f22ef01cSRoman Divacky                                                   0, "");
1498f22ef01cSRoman Divacky       BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1499f22ef01cSRoman Divacky       V = FwdRef;
1500f22ef01cSRoman Divacky       break;
1501f22ef01cSRoman Divacky     }
1502f22ef01cSRoman Divacky     }
1503f22ef01cSRoman Divacky 
1504f22ef01cSRoman Divacky     ValueList.AssignValue(V, NextCstNo);
1505f22ef01cSRoman Divacky     ++NextCstNo;
1506f22ef01cSRoman Divacky   }
1507f22ef01cSRoman Divacky 
1508f22ef01cSRoman Divacky   if (NextCstNo != ValueList.size())
1509f22ef01cSRoman Divacky     return Error("Invalid constant reference!");
1510f22ef01cSRoman Divacky 
1511f22ef01cSRoman Divacky   if (Stream.ReadBlockEnd())
1512f22ef01cSRoman Divacky     return Error("Error at end of constants block");
1513f22ef01cSRoman Divacky 
1514f22ef01cSRoman Divacky   // Once all the constants have been read, go through and resolve forward
1515f22ef01cSRoman Divacky   // references.
1516f22ef01cSRoman Divacky   ValueList.ResolveConstantForwardRefs();
1517f22ef01cSRoman Divacky   return false;
1518f22ef01cSRoman Divacky }
1519f22ef01cSRoman Divacky 
1520f22ef01cSRoman Divacky /// RememberAndSkipFunctionBody - When we see the block for a function body,
1521f22ef01cSRoman Divacky /// remember where it is and then skip it.  This lets us lazily deserialize the
1522f22ef01cSRoman Divacky /// functions.
1523f22ef01cSRoman Divacky bool BitcodeReader::RememberAndSkipFunctionBody() {
1524f22ef01cSRoman Divacky   // Get the function we are talking about.
1525f22ef01cSRoman Divacky   if (FunctionsWithBodies.empty())
1526f22ef01cSRoman Divacky     return Error("Insufficient function protos");
1527f22ef01cSRoman Divacky 
1528f22ef01cSRoman Divacky   Function *Fn = FunctionsWithBodies.back();
1529f22ef01cSRoman Divacky   FunctionsWithBodies.pop_back();
1530f22ef01cSRoman Divacky 
1531f22ef01cSRoman Divacky   // Save the current stream state.
1532f22ef01cSRoman Divacky   uint64_t CurBit = Stream.GetCurrentBitNo();
1533f22ef01cSRoman Divacky   DeferredFunctionInfo[Fn] = CurBit;
1534f22ef01cSRoman Divacky 
1535f22ef01cSRoman Divacky   // Skip over the function block for now.
1536f22ef01cSRoman Divacky   if (Stream.SkipBlock())
1537f22ef01cSRoman Divacky     return Error("Malformed block record");
1538f22ef01cSRoman Divacky   return false;
1539f22ef01cSRoman Divacky }
1540f22ef01cSRoman Divacky 
1541f22ef01cSRoman Divacky bool BitcodeReader::ParseModule() {
1542f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1543f22ef01cSRoman Divacky     return Error("Malformed block record");
1544f22ef01cSRoman Divacky 
1545f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1546f22ef01cSRoman Divacky   std::vector<std::string> SectionTable;
1547f22ef01cSRoman Divacky   std::vector<std::string> GCTable;
1548f22ef01cSRoman Divacky 
1549f22ef01cSRoman Divacky   // Read all the records for this module.
1550f22ef01cSRoman Divacky   while (!Stream.AtEndOfStream()) {
1551f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
1552f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK) {
1553f22ef01cSRoman Divacky       if (Stream.ReadBlockEnd())
1554f22ef01cSRoman Divacky         return Error("Error at end of module block");
1555f22ef01cSRoman Divacky 
1556f22ef01cSRoman Divacky       // Patch the initializers for globals and aliases up.
1557f22ef01cSRoman Divacky       ResolveGlobalAndAliasInits();
1558f22ef01cSRoman Divacky       if (!GlobalInits.empty() || !AliasInits.empty())
1559f22ef01cSRoman Divacky         return Error("Malformed global initializer set");
1560f22ef01cSRoman Divacky       if (!FunctionsWithBodies.empty())
1561f22ef01cSRoman Divacky         return Error("Too few function bodies found");
1562f22ef01cSRoman Divacky 
1563f22ef01cSRoman Divacky       // Look for intrinsic functions which need to be upgraded at some point
1564f22ef01cSRoman Divacky       for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1565f22ef01cSRoman Divacky            FI != FE; ++FI) {
1566f22ef01cSRoman Divacky         Function* NewFn;
1567f22ef01cSRoman Divacky         if (UpgradeIntrinsicFunction(FI, NewFn))
1568f22ef01cSRoman Divacky           UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1569f22ef01cSRoman Divacky       }
1570f22ef01cSRoman Divacky 
1571e580952dSDimitry Andric       // Look for global variables which need to be renamed.
1572e580952dSDimitry Andric       for (Module::global_iterator
1573e580952dSDimitry Andric              GI = TheModule->global_begin(), GE = TheModule->global_end();
1574e580952dSDimitry Andric            GI != GE; ++GI)
1575e580952dSDimitry Andric         UpgradeGlobalVariable(GI);
1576e580952dSDimitry Andric 
1577f22ef01cSRoman Divacky       // Force deallocation of memory for these vectors to favor the client that
1578f22ef01cSRoman Divacky       // want lazy deserialization.
1579f22ef01cSRoman Divacky       std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1580f22ef01cSRoman Divacky       std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1581f22ef01cSRoman Divacky       std::vector<Function*>().swap(FunctionsWithBodies);
1582f22ef01cSRoman Divacky       return false;
1583f22ef01cSRoman Divacky     }
1584f22ef01cSRoman Divacky 
1585f22ef01cSRoman Divacky     if (Code == bitc::ENTER_SUBBLOCK) {
1586f22ef01cSRoman Divacky       switch (Stream.ReadSubBlockID()) {
1587f22ef01cSRoman Divacky       default:  // Skip unknown content.
1588f22ef01cSRoman Divacky         if (Stream.SkipBlock())
1589f22ef01cSRoman Divacky           return Error("Malformed block record");
1590f22ef01cSRoman Divacky         break;
1591f22ef01cSRoman Divacky       case bitc::BLOCKINFO_BLOCK_ID:
1592f22ef01cSRoman Divacky         if (Stream.ReadBlockInfoBlock())
1593f22ef01cSRoman Divacky           return Error("Malformed BlockInfoBlock");
1594f22ef01cSRoman Divacky         break;
1595f22ef01cSRoman Divacky       case bitc::PARAMATTR_BLOCK_ID:
1596f22ef01cSRoman Divacky         if (ParseAttributeBlock())
1597f22ef01cSRoman Divacky           return true;
1598f22ef01cSRoman Divacky         break;
159917a519f9SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
1600f22ef01cSRoman Divacky         if (ParseTypeTable())
1601f22ef01cSRoman Divacky           return true;
1602f22ef01cSRoman Divacky         break;
160317a519f9SDimitry Andric       case bitc::TYPE_BLOCK_ID_OLD:
160417a519f9SDimitry Andric         if (ParseOldTypeTable())
160517a519f9SDimitry Andric           return true;
160617a519f9SDimitry Andric         break;
160717a519f9SDimitry Andric       case bitc::TYPE_SYMTAB_BLOCK_ID_OLD:
160817a519f9SDimitry Andric         if (ParseOldTypeSymbolTable())
1609f22ef01cSRoman Divacky           return true;
1610f22ef01cSRoman Divacky         break;
1611f22ef01cSRoman Divacky       case bitc::VALUE_SYMTAB_BLOCK_ID:
1612f22ef01cSRoman Divacky         if (ParseValueSymbolTable())
1613f22ef01cSRoman Divacky           return true;
1614f22ef01cSRoman Divacky         break;
1615f22ef01cSRoman Divacky       case bitc::CONSTANTS_BLOCK_ID:
1616f22ef01cSRoman Divacky         if (ParseConstants() || ResolveGlobalAndAliasInits())
1617f22ef01cSRoman Divacky           return true;
1618f22ef01cSRoman Divacky         break;
1619f22ef01cSRoman Divacky       case bitc::METADATA_BLOCK_ID:
1620f22ef01cSRoman Divacky         if (ParseMetadata())
1621f22ef01cSRoman Divacky           return true;
1622f22ef01cSRoman Divacky         break;
1623f22ef01cSRoman Divacky       case bitc::FUNCTION_BLOCK_ID:
1624f22ef01cSRoman Divacky         // If this is the first function body we've seen, reverse the
1625f22ef01cSRoman Divacky         // FunctionsWithBodies list.
1626f22ef01cSRoman Divacky         if (!HasReversedFunctionsWithBodies) {
1627f22ef01cSRoman Divacky           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1628f22ef01cSRoman Divacky           HasReversedFunctionsWithBodies = true;
1629f22ef01cSRoman Divacky         }
1630f22ef01cSRoman Divacky 
1631f22ef01cSRoman Divacky         if (RememberAndSkipFunctionBody())
1632f22ef01cSRoman Divacky           return true;
1633f22ef01cSRoman Divacky         break;
1634f22ef01cSRoman Divacky       }
1635f22ef01cSRoman Divacky       continue;
1636f22ef01cSRoman Divacky     }
1637f22ef01cSRoman Divacky 
1638f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
1639f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
1640f22ef01cSRoman Divacky       continue;
1641f22ef01cSRoman Divacky     }
1642f22ef01cSRoman Divacky 
1643f22ef01cSRoman Divacky     // Read a record.
1644f22ef01cSRoman Divacky     switch (Stream.ReadRecord(Code, Record)) {
1645f22ef01cSRoman Divacky     default: break;  // Default behavior, ignore unknown content.
1646f22ef01cSRoman Divacky     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1647f22ef01cSRoman Divacky       if (Record.size() < 1)
1648f22ef01cSRoman Divacky         return Error("Malformed MODULE_CODE_VERSION");
1649f22ef01cSRoman Divacky       // Only version #0 is supported so far.
1650f22ef01cSRoman Divacky       if (Record[0] != 0)
1651f22ef01cSRoman Divacky         return Error("Unknown bitstream version!");
1652f22ef01cSRoman Divacky       break;
1653f22ef01cSRoman Divacky     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1654f22ef01cSRoman Divacky       std::string S;
1655f22ef01cSRoman Divacky       if (ConvertToString(Record, 0, S))
1656f22ef01cSRoman Divacky         return Error("Invalid MODULE_CODE_TRIPLE record");
1657f22ef01cSRoman Divacky       TheModule->setTargetTriple(S);
1658f22ef01cSRoman Divacky       break;
1659f22ef01cSRoman Divacky     }
1660f22ef01cSRoman Divacky     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1661f22ef01cSRoman Divacky       std::string S;
1662f22ef01cSRoman Divacky       if (ConvertToString(Record, 0, S))
1663f22ef01cSRoman Divacky         return Error("Invalid MODULE_CODE_DATALAYOUT record");
1664f22ef01cSRoman Divacky       TheModule->setDataLayout(S);
1665f22ef01cSRoman Divacky       break;
1666f22ef01cSRoman Divacky     }
1667f22ef01cSRoman Divacky     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1668f22ef01cSRoman Divacky       std::string S;
1669f22ef01cSRoman Divacky       if (ConvertToString(Record, 0, S))
1670f22ef01cSRoman Divacky         return Error("Invalid MODULE_CODE_ASM record");
1671f22ef01cSRoman Divacky       TheModule->setModuleInlineAsm(S);
1672f22ef01cSRoman Divacky       break;
1673f22ef01cSRoman Divacky     }
1674f22ef01cSRoman Divacky     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1675f22ef01cSRoman Divacky       std::string S;
1676f22ef01cSRoman Divacky       if (ConvertToString(Record, 0, S))
1677f22ef01cSRoman Divacky         return Error("Invalid MODULE_CODE_DEPLIB record");
1678f22ef01cSRoman Divacky       TheModule->addLibrary(S);
1679f22ef01cSRoman Divacky       break;
1680f22ef01cSRoman Divacky     }
1681f22ef01cSRoman Divacky     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1682f22ef01cSRoman Divacky       std::string S;
1683f22ef01cSRoman Divacky       if (ConvertToString(Record, 0, S))
1684f22ef01cSRoman Divacky         return Error("Invalid MODULE_CODE_SECTIONNAME record");
1685f22ef01cSRoman Divacky       SectionTable.push_back(S);
1686f22ef01cSRoman Divacky       break;
1687f22ef01cSRoman Divacky     }
1688f22ef01cSRoman Divacky     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1689f22ef01cSRoman Divacky       std::string S;
1690f22ef01cSRoman Divacky       if (ConvertToString(Record, 0, S))
1691f22ef01cSRoman Divacky         return Error("Invalid MODULE_CODE_GCNAME record");
1692f22ef01cSRoman Divacky       GCTable.push_back(S);
1693f22ef01cSRoman Divacky       break;
1694f22ef01cSRoman Divacky     }
1695f22ef01cSRoman Divacky     // GLOBALVAR: [pointer type, isconst, initid,
16962754fe60SDimitry Andric     //             linkage, alignment, section, visibility, threadlocal,
16972754fe60SDimitry Andric     //             unnamed_addr]
1698f22ef01cSRoman Divacky     case bitc::MODULE_CODE_GLOBALVAR: {
1699f22ef01cSRoman Divacky       if (Record.size() < 6)
1700f22ef01cSRoman Divacky         return Error("Invalid MODULE_CODE_GLOBALVAR record");
17016122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
17022754fe60SDimitry Andric       if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1703f22ef01cSRoman Divacky       if (!Ty->isPointerTy())
1704f22ef01cSRoman Divacky         return Error("Global not a pointer type!");
1705f22ef01cSRoman Divacky       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1706f22ef01cSRoman Divacky       Ty = cast<PointerType>(Ty)->getElementType();
1707f22ef01cSRoman Divacky 
1708f22ef01cSRoman Divacky       bool isConstant = Record[1];
1709f22ef01cSRoman Divacky       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1710f22ef01cSRoman Divacky       unsigned Alignment = (1 << Record[4]) >> 1;
1711f22ef01cSRoman Divacky       std::string Section;
1712f22ef01cSRoman Divacky       if (Record[5]) {
1713f22ef01cSRoman Divacky         if (Record[5]-1 >= SectionTable.size())
1714f22ef01cSRoman Divacky           return Error("Invalid section ID");
1715f22ef01cSRoman Divacky         Section = SectionTable[Record[5]-1];
1716f22ef01cSRoman Divacky       }
1717f22ef01cSRoman Divacky       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1718f22ef01cSRoman Divacky       if (Record.size() > 6)
1719f22ef01cSRoman Divacky         Visibility = GetDecodedVisibility(Record[6]);
1720f22ef01cSRoman Divacky       bool isThreadLocal = false;
1721f22ef01cSRoman Divacky       if (Record.size() > 7)
1722f22ef01cSRoman Divacky         isThreadLocal = Record[7];
1723f22ef01cSRoman Divacky 
17242754fe60SDimitry Andric       bool UnnamedAddr = false;
17252754fe60SDimitry Andric       if (Record.size() > 8)
17262754fe60SDimitry Andric         UnnamedAddr = Record[8];
17272754fe60SDimitry Andric 
1728f22ef01cSRoman Divacky       GlobalVariable *NewGV =
1729f22ef01cSRoman Divacky         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1730f22ef01cSRoman Divacky                            isThreadLocal, AddressSpace);
1731f22ef01cSRoman Divacky       NewGV->setAlignment(Alignment);
1732f22ef01cSRoman Divacky       if (!Section.empty())
1733f22ef01cSRoman Divacky         NewGV->setSection(Section);
1734f22ef01cSRoman Divacky       NewGV->setVisibility(Visibility);
1735f22ef01cSRoman Divacky       NewGV->setThreadLocal(isThreadLocal);
17362754fe60SDimitry Andric       NewGV->setUnnamedAddr(UnnamedAddr);
1737f22ef01cSRoman Divacky 
1738f22ef01cSRoman Divacky       ValueList.push_back(NewGV);
1739f22ef01cSRoman Divacky 
1740f22ef01cSRoman Divacky       // Remember which value to use for the global initializer.
1741f22ef01cSRoman Divacky       if (unsigned InitID = Record[2])
1742f22ef01cSRoman Divacky         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1743f22ef01cSRoman Divacky       break;
1744f22ef01cSRoman Divacky     }
1745f22ef01cSRoman Divacky     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
17462754fe60SDimitry Andric     //             alignment, section, visibility, gc, unnamed_addr]
1747f22ef01cSRoman Divacky     case bitc::MODULE_CODE_FUNCTION: {
1748f22ef01cSRoman Divacky       if (Record.size() < 8)
1749f22ef01cSRoman Divacky         return Error("Invalid MODULE_CODE_FUNCTION record");
17506122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
17512754fe60SDimitry Andric       if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1752f22ef01cSRoman Divacky       if (!Ty->isPointerTy())
1753f22ef01cSRoman Divacky         return Error("Function not a pointer type!");
17546122f3e6SDimitry Andric       FunctionType *FTy =
1755f22ef01cSRoman Divacky         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1756f22ef01cSRoman Divacky       if (!FTy)
1757f22ef01cSRoman Divacky         return Error("Function not a pointer to function type!");
1758f22ef01cSRoman Divacky 
1759f22ef01cSRoman Divacky       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1760f22ef01cSRoman Divacky                                         "", TheModule);
1761f22ef01cSRoman Divacky 
1762f22ef01cSRoman Divacky       Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1763f22ef01cSRoman Divacky       bool isProto = Record[2];
1764f22ef01cSRoman Divacky       Func->setLinkage(GetDecodedLinkage(Record[3]));
1765f22ef01cSRoman Divacky       Func->setAttributes(getAttributes(Record[4]));
1766f22ef01cSRoman Divacky 
1767f22ef01cSRoman Divacky       Func->setAlignment((1 << Record[5]) >> 1);
1768f22ef01cSRoman Divacky       if (Record[6]) {
1769f22ef01cSRoman Divacky         if (Record[6]-1 >= SectionTable.size())
1770f22ef01cSRoman Divacky           return Error("Invalid section ID");
1771f22ef01cSRoman Divacky         Func->setSection(SectionTable[Record[6]-1]);
1772f22ef01cSRoman Divacky       }
1773f22ef01cSRoman Divacky       Func->setVisibility(GetDecodedVisibility(Record[7]));
1774f22ef01cSRoman Divacky       if (Record.size() > 8 && Record[8]) {
1775f22ef01cSRoman Divacky         if (Record[8]-1 > GCTable.size())
1776f22ef01cSRoman Divacky           return Error("Invalid GC ID");
1777f22ef01cSRoman Divacky         Func->setGC(GCTable[Record[8]-1].c_str());
1778f22ef01cSRoman Divacky       }
17792754fe60SDimitry Andric       bool UnnamedAddr = false;
17802754fe60SDimitry Andric       if (Record.size() > 9)
17812754fe60SDimitry Andric         UnnamedAddr = Record[9];
17822754fe60SDimitry Andric       Func->setUnnamedAddr(UnnamedAddr);
1783f22ef01cSRoman Divacky       ValueList.push_back(Func);
1784f22ef01cSRoman Divacky 
1785f22ef01cSRoman Divacky       // If this is a function with a body, remember the prototype we are
1786f22ef01cSRoman Divacky       // creating now, so that we can match up the body with them later.
1787f22ef01cSRoman Divacky       if (!isProto)
1788f22ef01cSRoman Divacky         FunctionsWithBodies.push_back(Func);
1789f22ef01cSRoman Divacky       break;
1790f22ef01cSRoman Divacky     }
1791f22ef01cSRoman Divacky     // ALIAS: [alias type, aliasee val#, linkage]
1792f22ef01cSRoman Divacky     // ALIAS: [alias type, aliasee val#, linkage, visibility]
1793f22ef01cSRoman Divacky     case bitc::MODULE_CODE_ALIAS: {
1794f22ef01cSRoman Divacky       if (Record.size() < 3)
1795f22ef01cSRoman Divacky         return Error("Invalid MODULE_ALIAS record");
17966122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
17972754fe60SDimitry Andric       if (!Ty) return Error("Invalid MODULE_ALIAS record");
1798f22ef01cSRoman Divacky       if (!Ty->isPointerTy())
1799f22ef01cSRoman Divacky         return Error("Function not a pointer type!");
1800f22ef01cSRoman Divacky 
1801f22ef01cSRoman Divacky       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1802f22ef01cSRoman Divacky                                            "", 0, TheModule);
1803f22ef01cSRoman Divacky       // Old bitcode files didn't have visibility field.
1804f22ef01cSRoman Divacky       if (Record.size() > 3)
1805f22ef01cSRoman Divacky         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1806f22ef01cSRoman Divacky       ValueList.push_back(NewGA);
1807f22ef01cSRoman Divacky       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1808f22ef01cSRoman Divacky       break;
1809f22ef01cSRoman Divacky     }
1810f22ef01cSRoman Divacky     /// MODULE_CODE_PURGEVALS: [numvals]
1811f22ef01cSRoman Divacky     case bitc::MODULE_CODE_PURGEVALS:
1812f22ef01cSRoman Divacky       // Trim down the value list to the specified size.
1813f22ef01cSRoman Divacky       if (Record.size() < 1 || Record[0] > ValueList.size())
1814f22ef01cSRoman Divacky         return Error("Invalid MODULE_PURGEVALS record");
1815f22ef01cSRoman Divacky       ValueList.shrinkTo(Record[0]);
1816f22ef01cSRoman Divacky       break;
1817f22ef01cSRoman Divacky     }
1818f22ef01cSRoman Divacky     Record.clear();
1819f22ef01cSRoman Divacky   }
1820f22ef01cSRoman Divacky 
1821f22ef01cSRoman Divacky   return Error("Premature end of bitstream");
1822f22ef01cSRoman Divacky }
1823f22ef01cSRoman Divacky 
1824f22ef01cSRoman Divacky bool BitcodeReader::ParseBitcodeInto(Module *M) {
1825f22ef01cSRoman Divacky   TheModule = 0;
1826f22ef01cSRoman Divacky 
1827f22ef01cSRoman Divacky   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1828f22ef01cSRoman Divacky   unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1829f22ef01cSRoman Divacky 
1830f22ef01cSRoman Divacky   if (Buffer->getBufferSize() & 3) {
1831f22ef01cSRoman Divacky     if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
1832f22ef01cSRoman Divacky       return Error("Invalid bitcode signature");
1833f22ef01cSRoman Divacky     else
1834f22ef01cSRoman Divacky       return Error("Bitcode stream should be a multiple of 4 bytes in length");
1835f22ef01cSRoman Divacky   }
1836f22ef01cSRoman Divacky 
1837f22ef01cSRoman Divacky   // If we have a wrapper header, parse it and ignore the non-bc file contents.
1838f22ef01cSRoman Divacky   // The magic number is 0x0B17C0DE stored in little endian.
1839f22ef01cSRoman Divacky   if (isBitcodeWrapper(BufPtr, BufEnd))
1840f22ef01cSRoman Divacky     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1841f22ef01cSRoman Divacky       return Error("Invalid bitcode wrapper header");
1842f22ef01cSRoman Divacky 
1843f22ef01cSRoman Divacky   StreamFile.init(BufPtr, BufEnd);
1844f22ef01cSRoman Divacky   Stream.init(StreamFile);
1845f22ef01cSRoman Divacky 
1846f22ef01cSRoman Divacky   // Sniff for the signature.
1847f22ef01cSRoman Divacky   if (Stream.Read(8) != 'B' ||
1848f22ef01cSRoman Divacky       Stream.Read(8) != 'C' ||
1849f22ef01cSRoman Divacky       Stream.Read(4) != 0x0 ||
1850f22ef01cSRoman Divacky       Stream.Read(4) != 0xC ||
1851f22ef01cSRoman Divacky       Stream.Read(4) != 0xE ||
1852f22ef01cSRoman Divacky       Stream.Read(4) != 0xD)
1853f22ef01cSRoman Divacky     return Error("Invalid bitcode signature");
1854f22ef01cSRoman Divacky 
1855f22ef01cSRoman Divacky   // We expect a number of well-defined blocks, though we don't necessarily
1856f22ef01cSRoman Divacky   // need to understand them all.
1857f22ef01cSRoman Divacky   while (!Stream.AtEndOfStream()) {
1858f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
1859f22ef01cSRoman Divacky 
1860bd5abe19SDimitry Andric     if (Code != bitc::ENTER_SUBBLOCK) {
1861bd5abe19SDimitry Andric 
18626122f3e6SDimitry Andric       // The ranlib in xcode 4 will align archive members by appending newlines
18636122f3e6SDimitry Andric       // to the end of them. If this file size is a multiple of 4 but not 8, we
18646122f3e6SDimitry Andric       // have to read and ignore these final 4 bytes :-(
1865bd5abe19SDimitry Andric       if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1866bd5abe19SDimitry Andric           Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1867bd5abe19SDimitry Andric 	  Stream.AtEndOfStream())
1868bd5abe19SDimitry Andric         return false;
1869bd5abe19SDimitry Andric 
1870f22ef01cSRoman Divacky       return Error("Invalid record at top-level");
1871bd5abe19SDimitry Andric     }
1872f22ef01cSRoman Divacky 
1873f22ef01cSRoman Divacky     unsigned BlockID = Stream.ReadSubBlockID();
1874f22ef01cSRoman Divacky 
1875f22ef01cSRoman Divacky     // We only know the MODULE subblock ID.
1876f22ef01cSRoman Divacky     switch (BlockID) {
1877f22ef01cSRoman Divacky     case bitc::BLOCKINFO_BLOCK_ID:
1878f22ef01cSRoman Divacky       if (Stream.ReadBlockInfoBlock())
1879f22ef01cSRoman Divacky         return Error("Malformed BlockInfoBlock");
1880f22ef01cSRoman Divacky       break;
1881f22ef01cSRoman Divacky     case bitc::MODULE_BLOCK_ID:
1882f22ef01cSRoman Divacky       // Reject multiple MODULE_BLOCK's in a single bitstream.
1883f22ef01cSRoman Divacky       if (TheModule)
1884f22ef01cSRoman Divacky         return Error("Multiple MODULE_BLOCKs in same stream");
1885f22ef01cSRoman Divacky       TheModule = M;
1886f22ef01cSRoman Divacky       if (ParseModule())
1887f22ef01cSRoman Divacky         return true;
1888f22ef01cSRoman Divacky       break;
1889f22ef01cSRoman Divacky     default:
1890f22ef01cSRoman Divacky       if (Stream.SkipBlock())
1891f22ef01cSRoman Divacky         return Error("Malformed block record");
1892f22ef01cSRoman Divacky       break;
1893f22ef01cSRoman Divacky     }
1894f22ef01cSRoman Divacky   }
1895f22ef01cSRoman Divacky 
1896f22ef01cSRoman Divacky   return false;
1897f22ef01cSRoman Divacky }
1898f22ef01cSRoman Divacky 
18992754fe60SDimitry Andric bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
19002754fe60SDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
19012754fe60SDimitry Andric     return Error("Malformed block record");
19022754fe60SDimitry Andric 
19032754fe60SDimitry Andric   SmallVector<uint64_t, 64> Record;
19042754fe60SDimitry Andric 
19052754fe60SDimitry Andric   // Read all the records for this module.
19062754fe60SDimitry Andric   while (!Stream.AtEndOfStream()) {
19072754fe60SDimitry Andric     unsigned Code = Stream.ReadCode();
19082754fe60SDimitry Andric     if (Code == bitc::END_BLOCK) {
19092754fe60SDimitry Andric       if (Stream.ReadBlockEnd())
19102754fe60SDimitry Andric         return Error("Error at end of module block");
19112754fe60SDimitry Andric 
19122754fe60SDimitry Andric       return false;
19132754fe60SDimitry Andric     }
19142754fe60SDimitry Andric 
19152754fe60SDimitry Andric     if (Code == bitc::ENTER_SUBBLOCK) {
19162754fe60SDimitry Andric       switch (Stream.ReadSubBlockID()) {
19172754fe60SDimitry Andric       default:  // Skip unknown content.
19182754fe60SDimitry Andric         if (Stream.SkipBlock())
19192754fe60SDimitry Andric           return Error("Malformed block record");
19202754fe60SDimitry Andric         break;
19212754fe60SDimitry Andric       }
19222754fe60SDimitry Andric       continue;
19232754fe60SDimitry Andric     }
19242754fe60SDimitry Andric 
19252754fe60SDimitry Andric     if (Code == bitc::DEFINE_ABBREV) {
19262754fe60SDimitry Andric       Stream.ReadAbbrevRecord();
19272754fe60SDimitry Andric       continue;
19282754fe60SDimitry Andric     }
19292754fe60SDimitry Andric 
19302754fe60SDimitry Andric     // Read a record.
19312754fe60SDimitry Andric     switch (Stream.ReadRecord(Code, Record)) {
19322754fe60SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
19332754fe60SDimitry Andric     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
19342754fe60SDimitry Andric       if (Record.size() < 1)
19352754fe60SDimitry Andric         return Error("Malformed MODULE_CODE_VERSION");
19362754fe60SDimitry Andric       // Only version #0 is supported so far.
19372754fe60SDimitry Andric       if (Record[0] != 0)
19382754fe60SDimitry Andric         return Error("Unknown bitstream version!");
19392754fe60SDimitry Andric       break;
19402754fe60SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
19412754fe60SDimitry Andric       std::string S;
19422754fe60SDimitry Andric       if (ConvertToString(Record, 0, S))
19432754fe60SDimitry Andric         return Error("Invalid MODULE_CODE_TRIPLE record");
19442754fe60SDimitry Andric       Triple = S;
19452754fe60SDimitry Andric       break;
19462754fe60SDimitry Andric     }
19472754fe60SDimitry Andric     }
19482754fe60SDimitry Andric     Record.clear();
19492754fe60SDimitry Andric   }
19502754fe60SDimitry Andric 
19512754fe60SDimitry Andric   return Error("Premature end of bitstream");
19522754fe60SDimitry Andric }
19532754fe60SDimitry Andric 
19542754fe60SDimitry Andric bool BitcodeReader::ParseTriple(std::string &Triple) {
19552754fe60SDimitry Andric   if (Buffer->getBufferSize() & 3)
19562754fe60SDimitry Andric     return Error("Bitcode stream should be a multiple of 4 bytes in length");
19572754fe60SDimitry Andric 
19582754fe60SDimitry Andric   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
19592754fe60SDimitry Andric   unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
19602754fe60SDimitry Andric 
19612754fe60SDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
19622754fe60SDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
19632754fe60SDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
19642754fe60SDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
19652754fe60SDimitry Andric       return Error("Invalid bitcode wrapper header");
19662754fe60SDimitry Andric 
19672754fe60SDimitry Andric   StreamFile.init(BufPtr, BufEnd);
19682754fe60SDimitry Andric   Stream.init(StreamFile);
19692754fe60SDimitry Andric 
19702754fe60SDimitry Andric   // Sniff for the signature.
19712754fe60SDimitry Andric   if (Stream.Read(8) != 'B' ||
19722754fe60SDimitry Andric       Stream.Read(8) != 'C' ||
19732754fe60SDimitry Andric       Stream.Read(4) != 0x0 ||
19742754fe60SDimitry Andric       Stream.Read(4) != 0xC ||
19752754fe60SDimitry Andric       Stream.Read(4) != 0xE ||
19762754fe60SDimitry Andric       Stream.Read(4) != 0xD)
19772754fe60SDimitry Andric     return Error("Invalid bitcode signature");
19782754fe60SDimitry Andric 
19792754fe60SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
19802754fe60SDimitry Andric   // need to understand them all.
19812754fe60SDimitry Andric   while (!Stream.AtEndOfStream()) {
19822754fe60SDimitry Andric     unsigned Code = Stream.ReadCode();
19832754fe60SDimitry Andric 
19842754fe60SDimitry Andric     if (Code != bitc::ENTER_SUBBLOCK)
19852754fe60SDimitry Andric       return Error("Invalid record at top-level");
19862754fe60SDimitry Andric 
19872754fe60SDimitry Andric     unsigned BlockID = Stream.ReadSubBlockID();
19882754fe60SDimitry Andric 
19892754fe60SDimitry Andric     // We only know the MODULE subblock ID.
19902754fe60SDimitry Andric     switch (BlockID) {
19912754fe60SDimitry Andric     case bitc::MODULE_BLOCK_ID:
19922754fe60SDimitry Andric       if (ParseModuleTriple(Triple))
19932754fe60SDimitry Andric         return true;
19942754fe60SDimitry Andric       break;
19952754fe60SDimitry Andric     default:
19962754fe60SDimitry Andric       if (Stream.SkipBlock())
19972754fe60SDimitry Andric         return Error("Malformed block record");
19982754fe60SDimitry Andric       break;
19992754fe60SDimitry Andric     }
20002754fe60SDimitry Andric   }
20012754fe60SDimitry Andric 
20022754fe60SDimitry Andric   return false;
20032754fe60SDimitry Andric }
20042754fe60SDimitry Andric 
2005f22ef01cSRoman Divacky /// ParseMetadataAttachment - Parse metadata attachments.
2006f22ef01cSRoman Divacky bool BitcodeReader::ParseMetadataAttachment() {
2007f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2008f22ef01cSRoman Divacky     return Error("Malformed block record");
2009f22ef01cSRoman Divacky 
2010f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
2011f22ef01cSRoman Divacky   while(1) {
2012f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
2013f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK) {
2014f22ef01cSRoman Divacky       if (Stream.ReadBlockEnd())
2015f22ef01cSRoman Divacky         return Error("Error at end of PARAMATTR block");
2016f22ef01cSRoman Divacky       break;
2017f22ef01cSRoman Divacky     }
2018f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
2019f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
2020f22ef01cSRoman Divacky       continue;
2021f22ef01cSRoman Divacky     }
2022f22ef01cSRoman Divacky     // Read a metadata attachment record.
2023f22ef01cSRoman Divacky     Record.clear();
2024f22ef01cSRoman Divacky     switch (Stream.ReadRecord(Code, Record)) {
2025f22ef01cSRoman Divacky     default:  // Default behavior: ignore.
2026f22ef01cSRoman Divacky       break;
202717a519f9SDimitry Andric     case bitc::METADATA_ATTACHMENT: {
2028f22ef01cSRoman Divacky       unsigned RecordLength = Record.size();
2029f22ef01cSRoman Divacky       if (Record.empty() || (RecordLength - 1) % 2 == 1)
2030f22ef01cSRoman Divacky         return Error ("Invalid METADATA_ATTACHMENT reader!");
2031f22ef01cSRoman Divacky       Instruction *Inst = InstructionList[Record[0]];
2032f22ef01cSRoman Divacky       for (unsigned i = 1; i != RecordLength; i = i+2) {
2033f22ef01cSRoman Divacky         unsigned Kind = Record[i];
2034e580952dSDimitry Andric         DenseMap<unsigned, unsigned>::iterator I =
2035e580952dSDimitry Andric           MDKindMap.find(Kind);
2036e580952dSDimitry Andric         if (I == MDKindMap.end())
2037e580952dSDimitry Andric           return Error("Invalid metadata kind ID");
2038f22ef01cSRoman Divacky         Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
2039e580952dSDimitry Andric         Inst->setMetadata(I->second, cast<MDNode>(Node));
2040f22ef01cSRoman Divacky       }
2041f22ef01cSRoman Divacky       break;
2042f22ef01cSRoman Divacky     }
2043f22ef01cSRoman Divacky     }
2044f22ef01cSRoman Divacky   }
2045f22ef01cSRoman Divacky   return false;
2046f22ef01cSRoman Divacky }
2047f22ef01cSRoman Divacky 
2048f22ef01cSRoman Divacky /// ParseFunctionBody - Lazily parse the specified function body block.
2049f22ef01cSRoman Divacky bool BitcodeReader::ParseFunctionBody(Function *F) {
2050f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2051f22ef01cSRoman Divacky     return Error("Malformed block record");
2052f22ef01cSRoman Divacky 
2053f22ef01cSRoman Divacky   InstructionList.clear();
2054f22ef01cSRoman Divacky   unsigned ModuleValueListSize = ValueList.size();
2055e580952dSDimitry Andric   unsigned ModuleMDValueListSize = MDValueList.size();
2056f22ef01cSRoman Divacky 
2057f22ef01cSRoman Divacky   // Add all the function arguments to the value table.
2058f22ef01cSRoman Divacky   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2059f22ef01cSRoman Divacky     ValueList.push_back(I);
2060f22ef01cSRoman Divacky 
2061f22ef01cSRoman Divacky   unsigned NextValueNo = ValueList.size();
2062f22ef01cSRoman Divacky   BasicBlock *CurBB = 0;
2063f22ef01cSRoman Divacky   unsigned CurBBNo = 0;
2064f22ef01cSRoman Divacky 
2065f22ef01cSRoman Divacky   DebugLoc LastLoc;
2066f22ef01cSRoman Divacky 
2067f22ef01cSRoman Divacky   // Read all the records.
2068f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
2069f22ef01cSRoman Divacky   while (1) {
2070f22ef01cSRoman Divacky     unsigned Code = Stream.ReadCode();
2071f22ef01cSRoman Divacky     if (Code == bitc::END_BLOCK) {
2072f22ef01cSRoman Divacky       if (Stream.ReadBlockEnd())
2073f22ef01cSRoman Divacky         return Error("Error at end of function block");
2074f22ef01cSRoman Divacky       break;
2075f22ef01cSRoman Divacky     }
2076f22ef01cSRoman Divacky 
2077f22ef01cSRoman Divacky     if (Code == bitc::ENTER_SUBBLOCK) {
2078f22ef01cSRoman Divacky       switch (Stream.ReadSubBlockID()) {
2079f22ef01cSRoman Divacky       default:  // Skip unknown content.
2080f22ef01cSRoman Divacky         if (Stream.SkipBlock())
2081f22ef01cSRoman Divacky           return Error("Malformed block record");
2082f22ef01cSRoman Divacky         break;
2083f22ef01cSRoman Divacky       case bitc::CONSTANTS_BLOCK_ID:
2084f22ef01cSRoman Divacky         if (ParseConstants()) return true;
2085f22ef01cSRoman Divacky         NextValueNo = ValueList.size();
2086f22ef01cSRoman Divacky         break;
2087f22ef01cSRoman Divacky       case bitc::VALUE_SYMTAB_BLOCK_ID:
2088f22ef01cSRoman Divacky         if (ParseValueSymbolTable()) return true;
2089f22ef01cSRoman Divacky         break;
2090f22ef01cSRoman Divacky       case bitc::METADATA_ATTACHMENT_ID:
2091f22ef01cSRoman Divacky         if (ParseMetadataAttachment()) return true;
2092f22ef01cSRoman Divacky         break;
2093f22ef01cSRoman Divacky       case bitc::METADATA_BLOCK_ID:
2094f22ef01cSRoman Divacky         if (ParseMetadata()) return true;
2095f22ef01cSRoman Divacky         break;
2096f22ef01cSRoman Divacky       }
2097f22ef01cSRoman Divacky       continue;
2098f22ef01cSRoman Divacky     }
2099f22ef01cSRoman Divacky 
2100f22ef01cSRoman Divacky     if (Code == bitc::DEFINE_ABBREV) {
2101f22ef01cSRoman Divacky       Stream.ReadAbbrevRecord();
2102f22ef01cSRoman Divacky       continue;
2103f22ef01cSRoman Divacky     }
2104f22ef01cSRoman Divacky 
2105f22ef01cSRoman Divacky     // Read a record.
2106f22ef01cSRoman Divacky     Record.clear();
2107f22ef01cSRoman Divacky     Instruction *I = 0;
2108f22ef01cSRoman Divacky     unsigned BitCode = Stream.ReadRecord(Code, Record);
2109f22ef01cSRoman Divacky     switch (BitCode) {
2110f22ef01cSRoman Divacky     default: // Default behavior: reject
2111f22ef01cSRoman Divacky       return Error("Unknown instruction");
2112f22ef01cSRoman Divacky     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
2113f22ef01cSRoman Divacky       if (Record.size() < 1 || Record[0] == 0)
2114f22ef01cSRoman Divacky         return Error("Invalid DECLAREBLOCKS record");
2115f22ef01cSRoman Divacky       // Create all the basic blocks for the function.
2116f22ef01cSRoman Divacky       FunctionBBs.resize(Record[0]);
2117f22ef01cSRoman Divacky       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2118f22ef01cSRoman Divacky         FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2119f22ef01cSRoman Divacky       CurBB = FunctionBBs[0];
2120f22ef01cSRoman Divacky       continue;
2121f22ef01cSRoman Divacky 
2122f22ef01cSRoman Divacky     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
2123f22ef01cSRoman Divacky       // This record indicates that the last instruction is at the same
2124f22ef01cSRoman Divacky       // location as the previous instruction with a location.
2125f22ef01cSRoman Divacky       I = 0;
2126f22ef01cSRoman Divacky 
2127f22ef01cSRoman Divacky       // Get the last instruction emitted.
2128f22ef01cSRoman Divacky       if (CurBB && !CurBB->empty())
2129f22ef01cSRoman Divacky         I = &CurBB->back();
2130f22ef01cSRoman Divacky       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2131f22ef01cSRoman Divacky                !FunctionBBs[CurBBNo-1]->empty())
2132f22ef01cSRoman Divacky         I = &FunctionBBs[CurBBNo-1]->back();
2133f22ef01cSRoman Divacky 
2134f22ef01cSRoman Divacky       if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
2135f22ef01cSRoman Divacky       I->setDebugLoc(LastLoc);
2136f22ef01cSRoman Divacky       I = 0;
2137f22ef01cSRoman Divacky       continue;
2138f22ef01cSRoman Divacky 
213917a519f9SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
2140f22ef01cSRoman Divacky       I = 0;     // Get the last instruction emitted.
2141f22ef01cSRoman Divacky       if (CurBB && !CurBB->empty())
2142f22ef01cSRoman Divacky         I = &CurBB->back();
2143f22ef01cSRoman Divacky       else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2144f22ef01cSRoman Divacky                !FunctionBBs[CurBBNo-1]->empty())
2145f22ef01cSRoman Divacky         I = &FunctionBBs[CurBBNo-1]->back();
2146f22ef01cSRoman Divacky       if (I == 0 || Record.size() < 4)
2147f22ef01cSRoman Divacky         return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2148f22ef01cSRoman Divacky 
2149f22ef01cSRoman Divacky       unsigned Line = Record[0], Col = Record[1];
2150f22ef01cSRoman Divacky       unsigned ScopeID = Record[2], IAID = Record[3];
2151f22ef01cSRoman Divacky 
2152f22ef01cSRoman Divacky       MDNode *Scope = 0, *IA = 0;
2153f22ef01cSRoman Divacky       if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2154f22ef01cSRoman Divacky       if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2155f22ef01cSRoman Divacky       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2156f22ef01cSRoman Divacky       I->setDebugLoc(LastLoc);
2157f22ef01cSRoman Divacky       I = 0;
2158f22ef01cSRoman Divacky       continue;
2159f22ef01cSRoman Divacky     }
2160f22ef01cSRoman Divacky 
2161f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2162f22ef01cSRoman Divacky       unsigned OpNum = 0;
2163f22ef01cSRoman Divacky       Value *LHS, *RHS;
2164f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2165f22ef01cSRoman Divacky           getValue(Record, OpNum, LHS->getType(), RHS) ||
2166f22ef01cSRoman Divacky           OpNum+1 > Record.size())
2167f22ef01cSRoman Divacky         return Error("Invalid BINOP record");
2168f22ef01cSRoman Divacky 
2169f22ef01cSRoman Divacky       int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2170f22ef01cSRoman Divacky       if (Opc == -1) return Error("Invalid BINOP record");
2171f22ef01cSRoman Divacky       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2172f22ef01cSRoman Divacky       InstructionList.push_back(I);
2173f22ef01cSRoman Divacky       if (OpNum < Record.size()) {
2174f22ef01cSRoman Divacky         if (Opc == Instruction::Add ||
2175f22ef01cSRoman Divacky             Opc == Instruction::Sub ||
21762754fe60SDimitry Andric             Opc == Instruction::Mul ||
21772754fe60SDimitry Andric             Opc == Instruction::Shl) {
2178f22ef01cSRoman Divacky           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2179f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2180f22ef01cSRoman Divacky           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2181f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
21822754fe60SDimitry Andric         } else if (Opc == Instruction::SDiv ||
21832754fe60SDimitry Andric                    Opc == Instruction::UDiv ||
21842754fe60SDimitry Andric                    Opc == Instruction::LShr ||
21852754fe60SDimitry Andric                    Opc == Instruction::AShr) {
21862754fe60SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2187f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setIsExact(true);
2188f22ef01cSRoman Divacky         }
2189f22ef01cSRoman Divacky       }
2190f22ef01cSRoman Divacky       break;
2191f22ef01cSRoman Divacky     }
2192f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2193f22ef01cSRoman Divacky       unsigned OpNum = 0;
2194f22ef01cSRoman Divacky       Value *Op;
2195f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2196f22ef01cSRoman Divacky           OpNum+2 != Record.size())
2197f22ef01cSRoman Divacky         return Error("Invalid CAST record");
2198f22ef01cSRoman Divacky 
21996122f3e6SDimitry Andric       Type *ResTy = getTypeByID(Record[OpNum]);
2200f22ef01cSRoman Divacky       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2201f22ef01cSRoman Divacky       if (Opc == -1 || ResTy == 0)
2202f22ef01cSRoman Divacky         return Error("Invalid CAST record");
2203f22ef01cSRoman Divacky       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2204f22ef01cSRoman Divacky       InstructionList.push_back(I);
2205f22ef01cSRoman Divacky       break;
2206f22ef01cSRoman Divacky     }
2207f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2208f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2209f22ef01cSRoman Divacky       unsigned OpNum = 0;
2210f22ef01cSRoman Divacky       Value *BasePtr;
2211f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2212f22ef01cSRoman Divacky         return Error("Invalid GEP record");
2213f22ef01cSRoman Divacky 
2214f22ef01cSRoman Divacky       SmallVector<Value*, 16> GEPIdx;
2215f22ef01cSRoman Divacky       while (OpNum != Record.size()) {
2216f22ef01cSRoman Divacky         Value *Op;
2217f22ef01cSRoman Divacky         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2218f22ef01cSRoman Divacky           return Error("Invalid GEP record");
2219f22ef01cSRoman Divacky         GEPIdx.push_back(Op);
2220f22ef01cSRoman Divacky       }
2221f22ef01cSRoman Divacky 
22226122f3e6SDimitry Andric       I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2223f22ef01cSRoman Divacky       InstructionList.push_back(I);
2224f22ef01cSRoman Divacky       if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2225f22ef01cSRoman Divacky         cast<GetElementPtrInst>(I)->setIsInBounds(true);
2226f22ef01cSRoman Divacky       break;
2227f22ef01cSRoman Divacky     }
2228f22ef01cSRoman Divacky 
2229f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2230f22ef01cSRoman Divacky                                        // EXTRACTVAL: [opty, opval, n x indices]
2231f22ef01cSRoman Divacky       unsigned OpNum = 0;
2232f22ef01cSRoman Divacky       Value *Agg;
2233f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2234f22ef01cSRoman Divacky         return Error("Invalid EXTRACTVAL record");
2235f22ef01cSRoman Divacky 
2236f22ef01cSRoman Divacky       SmallVector<unsigned, 4> EXTRACTVALIdx;
2237f22ef01cSRoman Divacky       for (unsigned RecSize = Record.size();
2238f22ef01cSRoman Divacky            OpNum != RecSize; ++OpNum) {
2239f22ef01cSRoman Divacky         uint64_t Index = Record[OpNum];
2240f22ef01cSRoman Divacky         if ((unsigned)Index != Index)
2241f22ef01cSRoman Divacky           return Error("Invalid EXTRACTVAL index");
2242f22ef01cSRoman Divacky         EXTRACTVALIdx.push_back((unsigned)Index);
2243f22ef01cSRoman Divacky       }
2244f22ef01cSRoman Divacky 
224517a519f9SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2246f22ef01cSRoman Divacky       InstructionList.push_back(I);
2247f22ef01cSRoman Divacky       break;
2248f22ef01cSRoman Divacky     }
2249f22ef01cSRoman Divacky 
2250f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INSERTVAL: {
2251f22ef01cSRoman Divacky                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
2252f22ef01cSRoman Divacky       unsigned OpNum = 0;
2253f22ef01cSRoman Divacky       Value *Agg;
2254f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2255f22ef01cSRoman Divacky         return Error("Invalid INSERTVAL record");
2256f22ef01cSRoman Divacky       Value *Val;
2257f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2258f22ef01cSRoman Divacky         return Error("Invalid INSERTVAL record");
2259f22ef01cSRoman Divacky 
2260f22ef01cSRoman Divacky       SmallVector<unsigned, 4> INSERTVALIdx;
2261f22ef01cSRoman Divacky       for (unsigned RecSize = Record.size();
2262f22ef01cSRoman Divacky            OpNum != RecSize; ++OpNum) {
2263f22ef01cSRoman Divacky         uint64_t Index = Record[OpNum];
2264f22ef01cSRoman Divacky         if ((unsigned)Index != Index)
2265f22ef01cSRoman Divacky           return Error("Invalid INSERTVAL index");
2266f22ef01cSRoman Divacky         INSERTVALIdx.push_back((unsigned)Index);
2267f22ef01cSRoman Divacky       }
2268f22ef01cSRoman Divacky 
226917a519f9SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2270f22ef01cSRoman Divacky       InstructionList.push_back(I);
2271f22ef01cSRoman Divacky       break;
2272f22ef01cSRoman Divacky     }
2273f22ef01cSRoman Divacky 
2274f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2275f22ef01cSRoman Divacky       // obsolete form of select
2276f22ef01cSRoman Divacky       // handles select i1 ... in old bitcode
2277f22ef01cSRoman Divacky       unsigned OpNum = 0;
2278f22ef01cSRoman Divacky       Value *TrueVal, *FalseVal, *Cond;
2279f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2280f22ef01cSRoman Divacky           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2281f22ef01cSRoman Divacky           getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2282f22ef01cSRoman Divacky         return Error("Invalid SELECT record");
2283f22ef01cSRoman Divacky 
2284f22ef01cSRoman Divacky       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2285f22ef01cSRoman Divacky       InstructionList.push_back(I);
2286f22ef01cSRoman Divacky       break;
2287f22ef01cSRoman Divacky     }
2288f22ef01cSRoman Divacky 
2289f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2290f22ef01cSRoman Divacky       // new form of select
2291f22ef01cSRoman Divacky       // handles select i1 or select [N x i1]
2292f22ef01cSRoman Divacky       unsigned OpNum = 0;
2293f22ef01cSRoman Divacky       Value *TrueVal, *FalseVal, *Cond;
2294f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2295f22ef01cSRoman Divacky           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2296f22ef01cSRoman Divacky           getValueTypePair(Record, OpNum, NextValueNo, Cond))
2297f22ef01cSRoman Divacky         return Error("Invalid SELECT record");
2298f22ef01cSRoman Divacky 
2299f22ef01cSRoman Divacky       // select condition can be either i1 or [N x i1]
23006122f3e6SDimitry Andric       if (VectorType* vector_type =
23016122f3e6SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
2302f22ef01cSRoman Divacky         // expect <n x i1>
2303f22ef01cSRoman Divacky         if (vector_type->getElementType() != Type::getInt1Ty(Context))
2304f22ef01cSRoman Divacky           return Error("Invalid SELECT condition type");
2305f22ef01cSRoman Divacky       } else {
2306f22ef01cSRoman Divacky         // expect i1
2307f22ef01cSRoman Divacky         if (Cond->getType() != Type::getInt1Ty(Context))
2308f22ef01cSRoman Divacky           return Error("Invalid SELECT condition type");
2309f22ef01cSRoman Divacky       }
2310f22ef01cSRoman Divacky 
2311f22ef01cSRoman Divacky       I = SelectInst::Create(Cond, TrueVal, FalseVal);
2312f22ef01cSRoman Divacky       InstructionList.push_back(I);
2313f22ef01cSRoman Divacky       break;
2314f22ef01cSRoman Divacky     }
2315f22ef01cSRoman Divacky 
2316f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2317f22ef01cSRoman Divacky       unsigned OpNum = 0;
2318f22ef01cSRoman Divacky       Value *Vec, *Idx;
2319f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2320f22ef01cSRoman Divacky           getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2321f22ef01cSRoman Divacky         return Error("Invalid EXTRACTELT record");
2322f22ef01cSRoman Divacky       I = ExtractElementInst::Create(Vec, Idx);
2323f22ef01cSRoman Divacky       InstructionList.push_back(I);
2324f22ef01cSRoman Divacky       break;
2325f22ef01cSRoman Divacky     }
2326f22ef01cSRoman Divacky 
2327f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2328f22ef01cSRoman Divacky       unsigned OpNum = 0;
2329f22ef01cSRoman Divacky       Value *Vec, *Elt, *Idx;
2330f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2331f22ef01cSRoman Divacky           getValue(Record, OpNum,
2332f22ef01cSRoman Divacky                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2333f22ef01cSRoman Divacky           getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2334f22ef01cSRoman Divacky         return Error("Invalid INSERTELT record");
2335f22ef01cSRoman Divacky       I = InsertElementInst::Create(Vec, Elt, Idx);
2336f22ef01cSRoman Divacky       InstructionList.push_back(I);
2337f22ef01cSRoman Divacky       break;
2338f22ef01cSRoman Divacky     }
2339f22ef01cSRoman Divacky 
2340f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2341f22ef01cSRoman Divacky       unsigned OpNum = 0;
2342f22ef01cSRoman Divacky       Value *Vec1, *Vec2, *Mask;
2343f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2344f22ef01cSRoman Divacky           getValue(Record, OpNum, Vec1->getType(), Vec2))
2345f22ef01cSRoman Divacky         return Error("Invalid SHUFFLEVEC record");
2346f22ef01cSRoman Divacky 
2347f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2348f22ef01cSRoman Divacky         return Error("Invalid SHUFFLEVEC record");
2349f22ef01cSRoman Divacky       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2350f22ef01cSRoman Divacky       InstructionList.push_back(I);
2351f22ef01cSRoman Divacky       break;
2352f22ef01cSRoman Divacky     }
2353f22ef01cSRoman Divacky 
2354f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2355f22ef01cSRoman Divacky       // Old form of ICmp/FCmp returning bool
2356f22ef01cSRoman Divacky       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2357f22ef01cSRoman Divacky       // both legal on vectors but had different behaviour.
2358f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2359f22ef01cSRoman Divacky       // FCmp/ICmp returning bool or vector of bool
2360f22ef01cSRoman Divacky 
2361f22ef01cSRoman Divacky       unsigned OpNum = 0;
2362f22ef01cSRoman Divacky       Value *LHS, *RHS;
2363f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2364f22ef01cSRoman Divacky           getValue(Record, OpNum, LHS->getType(), RHS) ||
2365f22ef01cSRoman Divacky           OpNum+1 != Record.size())
2366f22ef01cSRoman Divacky         return Error("Invalid CMP record");
2367f22ef01cSRoman Divacky 
2368f22ef01cSRoman Divacky       if (LHS->getType()->isFPOrFPVectorTy())
2369f22ef01cSRoman Divacky         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2370f22ef01cSRoman Divacky       else
2371f22ef01cSRoman Divacky         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2372f22ef01cSRoman Divacky       InstructionList.push_back(I);
2373f22ef01cSRoman Divacky       break;
2374f22ef01cSRoman Divacky     }
2375f22ef01cSRoman Divacky 
2376f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2377f22ef01cSRoman Divacky       {
2378f22ef01cSRoman Divacky         unsigned Size = Record.size();
2379f22ef01cSRoman Divacky         if (Size == 0) {
2380f22ef01cSRoman Divacky           I = ReturnInst::Create(Context);
2381f22ef01cSRoman Divacky           InstructionList.push_back(I);
2382f22ef01cSRoman Divacky           break;
2383f22ef01cSRoman Divacky         }
2384f22ef01cSRoman Divacky 
2385f22ef01cSRoman Divacky         unsigned OpNum = 0;
2386f22ef01cSRoman Divacky         Value *Op = NULL;
2387f22ef01cSRoman Divacky         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2388f22ef01cSRoman Divacky           return Error("Invalid RET record");
238917a519f9SDimitry Andric         if (OpNum != Record.size())
239017a519f9SDimitry Andric           return Error("Invalid RET record");
2391f22ef01cSRoman Divacky 
239217a519f9SDimitry Andric         I = ReturnInst::Create(Context, Op);
2393f22ef01cSRoman Divacky         InstructionList.push_back(I);
2394f22ef01cSRoman Divacky         break;
2395f22ef01cSRoman Divacky       }
2396f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2397f22ef01cSRoman Divacky       if (Record.size() != 1 && Record.size() != 3)
2398f22ef01cSRoman Divacky         return Error("Invalid BR record");
2399f22ef01cSRoman Divacky       BasicBlock *TrueDest = getBasicBlock(Record[0]);
2400f22ef01cSRoman Divacky       if (TrueDest == 0)
2401f22ef01cSRoman Divacky         return Error("Invalid BR record");
2402f22ef01cSRoman Divacky 
2403f22ef01cSRoman Divacky       if (Record.size() == 1) {
2404f22ef01cSRoman Divacky         I = BranchInst::Create(TrueDest);
2405f22ef01cSRoman Divacky         InstructionList.push_back(I);
2406f22ef01cSRoman Divacky       }
2407f22ef01cSRoman Divacky       else {
2408f22ef01cSRoman Divacky         BasicBlock *FalseDest = getBasicBlock(Record[1]);
2409f22ef01cSRoman Divacky         Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2410f22ef01cSRoman Divacky         if (FalseDest == 0 || Cond == 0)
2411f22ef01cSRoman Divacky           return Error("Invalid BR record");
2412f22ef01cSRoman Divacky         I = BranchInst::Create(TrueDest, FalseDest, Cond);
2413f22ef01cSRoman Divacky         InstructionList.push_back(I);
2414f22ef01cSRoman Divacky       }
2415f22ef01cSRoman Divacky       break;
2416f22ef01cSRoman Divacky     }
2417f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2418f22ef01cSRoman Divacky       if (Record.size() < 3 || (Record.size() & 1) == 0)
2419f22ef01cSRoman Divacky         return Error("Invalid SWITCH record");
24206122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
2421f22ef01cSRoman Divacky       Value *Cond = getFnValueByID(Record[1], OpTy);
2422f22ef01cSRoman Divacky       BasicBlock *Default = getBasicBlock(Record[2]);
2423f22ef01cSRoman Divacky       if (OpTy == 0 || Cond == 0 || Default == 0)
2424f22ef01cSRoman Divacky         return Error("Invalid SWITCH record");
2425f22ef01cSRoman Divacky       unsigned NumCases = (Record.size()-3)/2;
2426f22ef01cSRoman Divacky       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2427f22ef01cSRoman Divacky       InstructionList.push_back(SI);
2428f22ef01cSRoman Divacky       for (unsigned i = 0, e = NumCases; i != e; ++i) {
2429f22ef01cSRoman Divacky         ConstantInt *CaseVal =
2430f22ef01cSRoman Divacky           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2431f22ef01cSRoman Divacky         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2432f22ef01cSRoman Divacky         if (CaseVal == 0 || DestBB == 0) {
2433f22ef01cSRoman Divacky           delete SI;
2434f22ef01cSRoman Divacky           return Error("Invalid SWITCH record!");
2435f22ef01cSRoman Divacky         }
2436f22ef01cSRoman Divacky         SI->addCase(CaseVal, DestBB);
2437f22ef01cSRoman Divacky       }
2438f22ef01cSRoman Divacky       I = SI;
2439f22ef01cSRoman Divacky       break;
2440f22ef01cSRoman Divacky     }
2441f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2442f22ef01cSRoman Divacky       if (Record.size() < 2)
2443f22ef01cSRoman Divacky         return Error("Invalid INDIRECTBR record");
24446122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
2445f22ef01cSRoman Divacky       Value *Address = getFnValueByID(Record[1], OpTy);
2446f22ef01cSRoman Divacky       if (OpTy == 0 || Address == 0)
2447f22ef01cSRoman Divacky         return Error("Invalid INDIRECTBR record");
2448f22ef01cSRoman Divacky       unsigned NumDests = Record.size()-2;
2449f22ef01cSRoman Divacky       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2450f22ef01cSRoman Divacky       InstructionList.push_back(IBI);
2451f22ef01cSRoman Divacky       for (unsigned i = 0, e = NumDests; i != e; ++i) {
2452f22ef01cSRoman Divacky         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2453f22ef01cSRoman Divacky           IBI->addDestination(DestBB);
2454f22ef01cSRoman Divacky         } else {
2455f22ef01cSRoman Divacky           delete IBI;
2456f22ef01cSRoman Divacky           return Error("Invalid INDIRECTBR record!");
2457f22ef01cSRoman Divacky         }
2458f22ef01cSRoman Divacky       }
2459f22ef01cSRoman Divacky       I = IBI;
2460f22ef01cSRoman Divacky       break;
2461f22ef01cSRoman Divacky     }
2462f22ef01cSRoman Divacky 
2463f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INVOKE: {
2464f22ef01cSRoman Divacky       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2465f22ef01cSRoman Divacky       if (Record.size() < 4) return Error("Invalid INVOKE record");
2466f22ef01cSRoman Divacky       AttrListPtr PAL = getAttributes(Record[0]);
2467f22ef01cSRoman Divacky       unsigned CCInfo = Record[1];
2468f22ef01cSRoman Divacky       BasicBlock *NormalBB = getBasicBlock(Record[2]);
2469f22ef01cSRoman Divacky       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2470f22ef01cSRoman Divacky 
2471f22ef01cSRoman Divacky       unsigned OpNum = 4;
2472f22ef01cSRoman Divacky       Value *Callee;
2473f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2474f22ef01cSRoman Divacky         return Error("Invalid INVOKE record");
2475f22ef01cSRoman Divacky 
24766122f3e6SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
24776122f3e6SDimitry Andric       FunctionType *FTy = !CalleeTy ? 0 :
2478f22ef01cSRoman Divacky         dyn_cast<FunctionType>(CalleeTy->getElementType());
2479f22ef01cSRoman Divacky 
2480f22ef01cSRoman Divacky       // Check that the right number of fixed parameters are here.
2481f22ef01cSRoman Divacky       if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2482f22ef01cSRoman Divacky           Record.size() < OpNum+FTy->getNumParams())
2483f22ef01cSRoman Divacky         return Error("Invalid INVOKE record");
2484f22ef01cSRoman Divacky 
2485f22ef01cSRoman Divacky       SmallVector<Value*, 16> Ops;
2486f22ef01cSRoman Divacky       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2487f22ef01cSRoman Divacky         Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2488f22ef01cSRoman Divacky         if (Ops.back() == 0) return Error("Invalid INVOKE record");
2489f22ef01cSRoman Divacky       }
2490f22ef01cSRoman Divacky 
2491f22ef01cSRoman Divacky       if (!FTy->isVarArg()) {
2492f22ef01cSRoman Divacky         if (Record.size() != OpNum)
2493f22ef01cSRoman Divacky           return Error("Invalid INVOKE record");
2494f22ef01cSRoman Divacky       } else {
2495f22ef01cSRoman Divacky         // Read type/value pairs for varargs params.
2496f22ef01cSRoman Divacky         while (OpNum != Record.size()) {
2497f22ef01cSRoman Divacky           Value *Op;
2498f22ef01cSRoman Divacky           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2499f22ef01cSRoman Divacky             return Error("Invalid INVOKE record");
2500f22ef01cSRoman Divacky           Ops.push_back(Op);
2501f22ef01cSRoman Divacky         }
2502f22ef01cSRoman Divacky       }
2503f22ef01cSRoman Divacky 
250417a519f9SDimitry Andric       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2505f22ef01cSRoman Divacky       InstructionList.push_back(I);
2506f22ef01cSRoman Divacky       cast<InvokeInst>(I)->setCallingConv(
2507f22ef01cSRoman Divacky         static_cast<CallingConv::ID>(CCInfo));
2508f22ef01cSRoman Divacky       cast<InvokeInst>(I)->setAttributes(PAL);
2509f22ef01cSRoman Divacky       break;
2510f22ef01cSRoman Divacky     }
25116122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
25126122f3e6SDimitry Andric       unsigned Idx = 0;
25136122f3e6SDimitry Andric       Value *Val = 0;
25146122f3e6SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val))
25156122f3e6SDimitry Andric         return Error("Invalid RESUME record");
25166122f3e6SDimitry Andric       I = ResumeInst::Create(Val);
25176122f3e6SDimitry Andric       InstructionList.push_back(I);
25186122f3e6SDimitry Andric       break;
25196122f3e6SDimitry Andric     }
2520f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2521f22ef01cSRoman Divacky       I = new UnwindInst(Context);
2522f22ef01cSRoman Divacky       InstructionList.push_back(I);
2523f22ef01cSRoman Divacky       break;
2524f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2525f22ef01cSRoman Divacky       I = new UnreachableInst(Context);
2526f22ef01cSRoman Divacky       InstructionList.push_back(I);
2527f22ef01cSRoman Divacky       break;
2528f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2529f22ef01cSRoman Divacky       if (Record.size() < 1 || ((Record.size()-1)&1))
2530f22ef01cSRoman Divacky         return Error("Invalid PHI record");
25316122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
2532f22ef01cSRoman Divacky       if (!Ty) return Error("Invalid PHI record");
2533f22ef01cSRoman Divacky 
25343b0f4066SDimitry Andric       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2535f22ef01cSRoman Divacky       InstructionList.push_back(PN);
2536f22ef01cSRoman Divacky 
2537f22ef01cSRoman Divacky       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2538f22ef01cSRoman Divacky         Value *V = getFnValueByID(Record[1+i], Ty);
2539f22ef01cSRoman Divacky         BasicBlock *BB = getBasicBlock(Record[2+i]);
2540f22ef01cSRoman Divacky         if (!V || !BB) return Error("Invalid PHI record");
2541f22ef01cSRoman Divacky         PN->addIncoming(V, BB);
2542f22ef01cSRoman Divacky       }
2543f22ef01cSRoman Divacky       I = PN;
2544f22ef01cSRoman Divacky       break;
2545f22ef01cSRoman Divacky     }
2546f22ef01cSRoman Divacky 
25476122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD: {
25486122f3e6SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
25496122f3e6SDimitry Andric       unsigned Idx = 0;
25506122f3e6SDimitry Andric       if (Record.size() < 4)
25516122f3e6SDimitry Andric         return Error("Invalid LANDINGPAD record");
25526122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[Idx++]);
25536122f3e6SDimitry Andric       if (!Ty) return Error("Invalid LANDINGPAD record");
25546122f3e6SDimitry Andric       Value *PersFn = 0;
25556122f3e6SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
25566122f3e6SDimitry Andric         return Error("Invalid LANDINGPAD record");
25576122f3e6SDimitry Andric 
25586122f3e6SDimitry Andric       bool IsCleanup = !!Record[Idx++];
25596122f3e6SDimitry Andric       unsigned NumClauses = Record[Idx++];
25606122f3e6SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
25616122f3e6SDimitry Andric       LP->setCleanup(IsCleanup);
25626122f3e6SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
25636122f3e6SDimitry Andric         LandingPadInst::ClauseType CT =
25646122f3e6SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
25656122f3e6SDimitry Andric         Value *Val;
25666122f3e6SDimitry Andric 
25676122f3e6SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
25686122f3e6SDimitry Andric           delete LP;
25696122f3e6SDimitry Andric           return Error("Invalid LANDINGPAD record");
25706122f3e6SDimitry Andric         }
25716122f3e6SDimitry Andric 
25726122f3e6SDimitry Andric         assert((CT != LandingPadInst::Catch ||
25736122f3e6SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
25746122f3e6SDimitry Andric                "Catch clause has a invalid type!");
25756122f3e6SDimitry Andric         assert((CT != LandingPadInst::Filter ||
25766122f3e6SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
25776122f3e6SDimitry Andric                "Filter clause has invalid type!");
25786122f3e6SDimitry Andric         LP->addClause(Val);
25796122f3e6SDimitry Andric       }
25806122f3e6SDimitry Andric 
25816122f3e6SDimitry Andric       I = LP;
25826122f3e6SDimitry Andric       InstructionList.push_back(I);
25836122f3e6SDimitry Andric       break;
25846122f3e6SDimitry Andric     }
25856122f3e6SDimitry Andric 
258617a519f9SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
258717a519f9SDimitry Andric       if (Record.size() != 4)
258817a519f9SDimitry Andric         return Error("Invalid ALLOCA record");
25896122f3e6SDimitry Andric       PointerType *Ty =
2590f22ef01cSRoman Divacky         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
25916122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[1]);
259217a519f9SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy);
259317a519f9SDimitry Andric       unsigned Align = Record[3];
2594f22ef01cSRoman Divacky       if (!Ty || !Size) return Error("Invalid ALLOCA record");
2595f22ef01cSRoman Divacky       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2596f22ef01cSRoman Divacky       InstructionList.push_back(I);
2597f22ef01cSRoman Divacky       break;
2598f22ef01cSRoman Divacky     }
2599f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2600f22ef01cSRoman Divacky       unsigned OpNum = 0;
2601f22ef01cSRoman Divacky       Value *Op;
2602f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2603f22ef01cSRoman Divacky           OpNum+2 != Record.size())
2604f22ef01cSRoman Divacky         return Error("Invalid LOAD record");
2605f22ef01cSRoman Divacky 
2606f22ef01cSRoman Divacky       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2607f22ef01cSRoman Divacky       InstructionList.push_back(I);
2608f22ef01cSRoman Divacky       break;
2609f22ef01cSRoman Divacky     }
26106122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
26116122f3e6SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
26126122f3e6SDimitry Andric       unsigned OpNum = 0;
26136122f3e6SDimitry Andric       Value *Op;
26146122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
26156122f3e6SDimitry Andric           OpNum+4 != Record.size())
26166122f3e6SDimitry Andric         return Error("Invalid LOADATOMIC record");
26176122f3e6SDimitry Andric 
26186122f3e6SDimitry Andric 
26196122f3e6SDimitry Andric       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
26206122f3e6SDimitry Andric       if (Ordering == NotAtomic || Ordering == Release ||
26216122f3e6SDimitry Andric           Ordering == AcquireRelease)
26226122f3e6SDimitry Andric         return Error("Invalid LOADATOMIC record");
26236122f3e6SDimitry Andric       if (Ordering != NotAtomic && Record[OpNum] == 0)
26246122f3e6SDimitry Andric         return Error("Invalid LOADATOMIC record");
26256122f3e6SDimitry Andric       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
26266122f3e6SDimitry Andric 
26276122f3e6SDimitry Andric       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
26286122f3e6SDimitry Andric                        Ordering, SynchScope);
26296122f3e6SDimitry Andric       InstructionList.push_back(I);
26306122f3e6SDimitry Andric       break;
26316122f3e6SDimitry Andric     }
263217a519f9SDimitry Andric     case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2633f22ef01cSRoman Divacky       unsigned OpNum = 0;
2634f22ef01cSRoman Divacky       Value *Val, *Ptr;
2635f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2636f22ef01cSRoman Divacky           getValue(Record, OpNum,
2637f22ef01cSRoman Divacky                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2638f22ef01cSRoman Divacky           OpNum+2 != Record.size())
2639f22ef01cSRoman Divacky         return Error("Invalid STORE record");
2640f22ef01cSRoman Divacky 
2641f22ef01cSRoman Divacky       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2642f22ef01cSRoman Divacky       InstructionList.push_back(I);
2643f22ef01cSRoman Divacky       break;
2644f22ef01cSRoman Divacky     }
26456122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC: {
26466122f3e6SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
26476122f3e6SDimitry Andric       unsigned OpNum = 0;
26486122f3e6SDimitry Andric       Value *Val, *Ptr;
26496122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
26506122f3e6SDimitry Andric           getValue(Record, OpNum,
26516122f3e6SDimitry Andric                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
26526122f3e6SDimitry Andric           OpNum+4 != Record.size())
26536122f3e6SDimitry Andric         return Error("Invalid STOREATOMIC record");
26546122f3e6SDimitry Andric 
26556122f3e6SDimitry Andric       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
26566122f3e6SDimitry Andric       if (Ordering == NotAtomic || Ordering == Acquire ||
26576122f3e6SDimitry Andric           Ordering == AcquireRelease)
26586122f3e6SDimitry Andric         return Error("Invalid STOREATOMIC record");
26596122f3e6SDimitry Andric       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
26606122f3e6SDimitry Andric       if (Ordering != NotAtomic && Record[OpNum] == 0)
26616122f3e6SDimitry Andric         return Error("Invalid STOREATOMIC record");
26626122f3e6SDimitry Andric 
26636122f3e6SDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
26646122f3e6SDimitry Andric                         Ordering, SynchScope);
26656122f3e6SDimitry Andric       InstructionList.push_back(I);
26666122f3e6SDimitry Andric       break;
26676122f3e6SDimitry Andric     }
26686122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
26696122f3e6SDimitry Andric       // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
26706122f3e6SDimitry Andric       unsigned OpNum = 0;
26716122f3e6SDimitry Andric       Value *Ptr, *Cmp, *New;
26726122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
26736122f3e6SDimitry Andric           getValue(Record, OpNum,
26746122f3e6SDimitry Andric                     cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
26756122f3e6SDimitry Andric           getValue(Record, OpNum,
26766122f3e6SDimitry Andric                     cast<PointerType>(Ptr->getType())->getElementType(), New) ||
26776122f3e6SDimitry Andric           OpNum+3 != Record.size())
26786122f3e6SDimitry Andric         return Error("Invalid CMPXCHG record");
26796122f3e6SDimitry Andric       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
26806122f3e6SDimitry Andric       if (Ordering == NotAtomic || Ordering == Unordered)
26816122f3e6SDimitry Andric         return Error("Invalid CMPXCHG record");
26826122f3e6SDimitry Andric       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
26836122f3e6SDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
26846122f3e6SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
26856122f3e6SDimitry Andric       InstructionList.push_back(I);
26866122f3e6SDimitry Andric       break;
26876122f3e6SDimitry Andric     }
26886122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
26896122f3e6SDimitry Andric       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
26906122f3e6SDimitry Andric       unsigned OpNum = 0;
26916122f3e6SDimitry Andric       Value *Ptr, *Val;
26926122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
26936122f3e6SDimitry Andric           getValue(Record, OpNum,
26946122f3e6SDimitry Andric                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
26956122f3e6SDimitry Andric           OpNum+4 != Record.size())
26966122f3e6SDimitry Andric         return Error("Invalid ATOMICRMW record");
26976122f3e6SDimitry Andric       AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
26986122f3e6SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
26996122f3e6SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
27006122f3e6SDimitry Andric         return Error("Invalid ATOMICRMW record");
27016122f3e6SDimitry Andric       AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
27026122f3e6SDimitry Andric       if (Ordering == NotAtomic || Ordering == Unordered)
27036122f3e6SDimitry Andric         return Error("Invalid ATOMICRMW record");
27046122f3e6SDimitry Andric       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
27056122f3e6SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
27066122f3e6SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
27076122f3e6SDimitry Andric       InstructionList.push_back(I);
27086122f3e6SDimitry Andric       break;
27096122f3e6SDimitry Andric     }
27106122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
27116122f3e6SDimitry Andric       if (2 != Record.size())
27126122f3e6SDimitry Andric         return Error("Invalid FENCE record");
27136122f3e6SDimitry Andric       AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
27146122f3e6SDimitry Andric       if (Ordering == NotAtomic || Ordering == Unordered ||
27156122f3e6SDimitry Andric           Ordering == Monotonic)
27166122f3e6SDimitry Andric         return Error("Invalid FENCE record");
27176122f3e6SDimitry Andric       SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
27186122f3e6SDimitry Andric       I = new FenceInst(Context, Ordering, SynchScope);
27196122f3e6SDimitry Andric       InstructionList.push_back(I);
27206122f3e6SDimitry Andric       break;
27216122f3e6SDimitry Andric     }
272217a519f9SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
2723f22ef01cSRoman Divacky       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2724f22ef01cSRoman Divacky       if (Record.size() < 3)
2725f22ef01cSRoman Divacky         return Error("Invalid CALL record");
2726f22ef01cSRoman Divacky 
2727f22ef01cSRoman Divacky       AttrListPtr PAL = getAttributes(Record[0]);
2728f22ef01cSRoman Divacky       unsigned CCInfo = Record[1];
2729f22ef01cSRoman Divacky 
2730f22ef01cSRoman Divacky       unsigned OpNum = 2;
2731f22ef01cSRoman Divacky       Value *Callee;
2732f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2733f22ef01cSRoman Divacky         return Error("Invalid CALL record");
2734f22ef01cSRoman Divacky 
27356122f3e6SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
27366122f3e6SDimitry Andric       FunctionType *FTy = 0;
2737f22ef01cSRoman Divacky       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2738f22ef01cSRoman Divacky       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2739f22ef01cSRoman Divacky         return Error("Invalid CALL record");
2740f22ef01cSRoman Divacky 
2741f22ef01cSRoman Divacky       SmallVector<Value*, 16> Args;
2742f22ef01cSRoman Divacky       // Read the fixed params.
2743f22ef01cSRoman Divacky       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
274417a519f9SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
2745f22ef01cSRoman Divacky           Args.push_back(getBasicBlock(Record[OpNum]));
2746f22ef01cSRoman Divacky         else
2747f22ef01cSRoman Divacky           Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2748f22ef01cSRoman Divacky         if (Args.back() == 0) return Error("Invalid CALL record");
2749f22ef01cSRoman Divacky       }
2750f22ef01cSRoman Divacky 
2751f22ef01cSRoman Divacky       // Read type/value pairs for varargs params.
2752f22ef01cSRoman Divacky       if (!FTy->isVarArg()) {
2753f22ef01cSRoman Divacky         if (OpNum != Record.size())
2754f22ef01cSRoman Divacky           return Error("Invalid CALL record");
2755f22ef01cSRoman Divacky       } else {
2756f22ef01cSRoman Divacky         while (OpNum != Record.size()) {
2757f22ef01cSRoman Divacky           Value *Op;
2758f22ef01cSRoman Divacky           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2759f22ef01cSRoman Divacky             return Error("Invalid CALL record");
2760f22ef01cSRoman Divacky           Args.push_back(Op);
2761f22ef01cSRoman Divacky         }
2762f22ef01cSRoman Divacky       }
2763f22ef01cSRoman Divacky 
276417a519f9SDimitry Andric       I = CallInst::Create(Callee, Args);
2765f22ef01cSRoman Divacky       InstructionList.push_back(I);
2766f22ef01cSRoman Divacky       cast<CallInst>(I)->setCallingConv(
2767f22ef01cSRoman Divacky         static_cast<CallingConv::ID>(CCInfo>>1));
2768f22ef01cSRoman Divacky       cast<CallInst>(I)->setTailCall(CCInfo & 1);
2769f22ef01cSRoman Divacky       cast<CallInst>(I)->setAttributes(PAL);
2770f22ef01cSRoman Divacky       break;
2771f22ef01cSRoman Divacky     }
2772f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2773f22ef01cSRoman Divacky       if (Record.size() < 3)
2774f22ef01cSRoman Divacky         return Error("Invalid VAARG record");
27756122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
2776f22ef01cSRoman Divacky       Value *Op = getFnValueByID(Record[1], OpTy);
27776122f3e6SDimitry Andric       Type *ResTy = getTypeByID(Record[2]);
2778f22ef01cSRoman Divacky       if (!OpTy || !Op || !ResTy)
2779f22ef01cSRoman Divacky         return Error("Invalid VAARG record");
2780f22ef01cSRoman Divacky       I = new VAArgInst(Op, ResTy);
2781f22ef01cSRoman Divacky       InstructionList.push_back(I);
2782f22ef01cSRoman Divacky       break;
2783f22ef01cSRoman Divacky     }
2784f22ef01cSRoman Divacky     }
2785f22ef01cSRoman Divacky 
2786f22ef01cSRoman Divacky     // Add instruction to end of current BB.  If there is no current BB, reject
2787f22ef01cSRoman Divacky     // this file.
2788f22ef01cSRoman Divacky     if (CurBB == 0) {
2789f22ef01cSRoman Divacky       delete I;
2790f22ef01cSRoman Divacky       return Error("Invalid instruction with no BB");
2791f22ef01cSRoman Divacky     }
2792f22ef01cSRoman Divacky     CurBB->getInstList().push_back(I);
2793f22ef01cSRoman Divacky 
2794f22ef01cSRoman Divacky     // If this was a terminator instruction, move to the next block.
2795f22ef01cSRoman Divacky     if (isa<TerminatorInst>(I)) {
2796f22ef01cSRoman Divacky       ++CurBBNo;
2797f22ef01cSRoman Divacky       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2798f22ef01cSRoman Divacky     }
2799f22ef01cSRoman Divacky 
2800f22ef01cSRoman Divacky     // Non-void values get registered in the value table for future use.
2801f22ef01cSRoman Divacky     if (I && !I->getType()->isVoidTy())
2802f22ef01cSRoman Divacky       ValueList.AssignValue(I, NextValueNo++);
2803f22ef01cSRoman Divacky   }
2804f22ef01cSRoman Divacky 
2805f22ef01cSRoman Divacky   // Check the function list for unresolved values.
2806f22ef01cSRoman Divacky   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2807f22ef01cSRoman Divacky     if (A->getParent() == 0) {
2808f22ef01cSRoman Divacky       // We found at least one unresolved value.  Nuke them all to avoid leaks.
2809f22ef01cSRoman Divacky       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2810e580952dSDimitry Andric         if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2811f22ef01cSRoman Divacky           A->replaceAllUsesWith(UndefValue::get(A->getType()));
2812f22ef01cSRoman Divacky           delete A;
2813f22ef01cSRoman Divacky         }
2814f22ef01cSRoman Divacky       }
2815f22ef01cSRoman Divacky       return Error("Never resolved value found in function!");
2816f22ef01cSRoman Divacky     }
2817f22ef01cSRoman Divacky   }
2818f22ef01cSRoman Divacky 
2819e580952dSDimitry Andric   // FIXME: Check for unresolved forward-declared metadata references
2820e580952dSDimitry Andric   // and clean up leaks.
2821e580952dSDimitry Andric 
2822f22ef01cSRoman Divacky   // See if anything took the address of blocks in this function.  If so,
2823f22ef01cSRoman Divacky   // resolve them now.
2824f22ef01cSRoman Divacky   DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2825f22ef01cSRoman Divacky     BlockAddrFwdRefs.find(F);
2826f22ef01cSRoman Divacky   if (BAFRI != BlockAddrFwdRefs.end()) {
2827f22ef01cSRoman Divacky     std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2828f22ef01cSRoman Divacky     for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2829f22ef01cSRoman Divacky       unsigned BlockIdx = RefList[i].first;
2830f22ef01cSRoman Divacky       if (BlockIdx >= FunctionBBs.size())
2831f22ef01cSRoman Divacky         return Error("Invalid blockaddress block #");
2832f22ef01cSRoman Divacky 
2833f22ef01cSRoman Divacky       GlobalVariable *FwdRef = RefList[i].second;
2834f22ef01cSRoman Divacky       FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2835f22ef01cSRoman Divacky       FwdRef->eraseFromParent();
2836f22ef01cSRoman Divacky     }
2837f22ef01cSRoman Divacky 
2838f22ef01cSRoman Divacky     BlockAddrFwdRefs.erase(BAFRI);
2839f22ef01cSRoman Divacky   }
2840f22ef01cSRoman Divacky 
2841f22ef01cSRoman Divacky   // Trim the value list down to the size it was before we parsed this function.
2842f22ef01cSRoman Divacky   ValueList.shrinkTo(ModuleValueListSize);
2843e580952dSDimitry Andric   MDValueList.shrinkTo(ModuleMDValueListSize);
2844f22ef01cSRoman Divacky   std::vector<BasicBlock*>().swap(FunctionBBs);
2845f22ef01cSRoman Divacky   return false;
2846f22ef01cSRoman Divacky }
2847f22ef01cSRoman Divacky 
2848f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
2849f22ef01cSRoman Divacky // GVMaterializer implementation
2850f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
2851f22ef01cSRoman Divacky 
2852f22ef01cSRoman Divacky 
2853f22ef01cSRoman Divacky bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2854f22ef01cSRoman Divacky   if (const Function *F = dyn_cast<Function>(GV)) {
2855f22ef01cSRoman Divacky     return F->isDeclaration() &&
2856f22ef01cSRoman Divacky       DeferredFunctionInfo.count(const_cast<Function*>(F));
2857f22ef01cSRoman Divacky   }
2858f22ef01cSRoman Divacky   return false;
2859f22ef01cSRoman Divacky }
2860f22ef01cSRoman Divacky 
2861f22ef01cSRoman Divacky bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2862f22ef01cSRoman Divacky   Function *F = dyn_cast<Function>(GV);
2863f22ef01cSRoman Divacky   // If it's not a function or is already material, ignore the request.
2864f22ef01cSRoman Divacky   if (!F || !F->isMaterializable()) return false;
2865f22ef01cSRoman Divacky 
2866f22ef01cSRoman Divacky   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2867f22ef01cSRoman Divacky   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2868f22ef01cSRoman Divacky 
2869f22ef01cSRoman Divacky   // Move the bit stream to the saved position of the deferred function body.
2870f22ef01cSRoman Divacky   Stream.JumpToBit(DFII->second);
2871f22ef01cSRoman Divacky 
2872f22ef01cSRoman Divacky   if (ParseFunctionBody(F)) {
2873f22ef01cSRoman Divacky     if (ErrInfo) *ErrInfo = ErrorString;
2874f22ef01cSRoman Divacky     return true;
2875f22ef01cSRoman Divacky   }
2876f22ef01cSRoman Divacky 
2877f22ef01cSRoman Divacky   // Upgrade any old intrinsic calls in the function.
2878f22ef01cSRoman Divacky   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2879f22ef01cSRoman Divacky        E = UpgradedIntrinsics.end(); I != E; ++I) {
2880f22ef01cSRoman Divacky     if (I->first != I->second) {
2881f22ef01cSRoman Divacky       for (Value::use_iterator UI = I->first->use_begin(),
2882f22ef01cSRoman Divacky            UE = I->first->use_end(); UI != UE; ) {
2883f22ef01cSRoman Divacky         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2884f22ef01cSRoman Divacky           UpgradeIntrinsicCall(CI, I->second);
2885f22ef01cSRoman Divacky       }
2886f22ef01cSRoman Divacky     }
2887f22ef01cSRoman Divacky   }
2888f22ef01cSRoman Divacky 
2889f22ef01cSRoman Divacky   return false;
2890f22ef01cSRoman Divacky }
2891f22ef01cSRoman Divacky 
2892f22ef01cSRoman Divacky bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2893f22ef01cSRoman Divacky   const Function *F = dyn_cast<Function>(GV);
2894f22ef01cSRoman Divacky   if (!F || F->isDeclaration())
2895f22ef01cSRoman Divacky     return false;
2896f22ef01cSRoman Divacky   return DeferredFunctionInfo.count(const_cast<Function*>(F));
2897f22ef01cSRoman Divacky }
2898f22ef01cSRoman Divacky 
2899f22ef01cSRoman Divacky void BitcodeReader::Dematerialize(GlobalValue *GV) {
2900f22ef01cSRoman Divacky   Function *F = dyn_cast<Function>(GV);
2901f22ef01cSRoman Divacky   // If this function isn't dematerializable, this is a noop.
2902f22ef01cSRoman Divacky   if (!F || !isDematerializable(F))
2903f22ef01cSRoman Divacky     return;
2904f22ef01cSRoman Divacky 
2905f22ef01cSRoman Divacky   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2906f22ef01cSRoman Divacky 
2907f22ef01cSRoman Divacky   // Just forget the function body, we can remat it later.
2908f22ef01cSRoman Divacky   F->deleteBody();
2909f22ef01cSRoman Divacky }
2910f22ef01cSRoman Divacky 
2911f22ef01cSRoman Divacky 
2912f22ef01cSRoman Divacky bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2913f22ef01cSRoman Divacky   assert(M == TheModule &&
2914f22ef01cSRoman Divacky          "Can only Materialize the Module this BitcodeReader is attached to.");
2915f22ef01cSRoman Divacky   // Iterate over the module, deserializing any functions that are still on
2916f22ef01cSRoman Divacky   // disk.
2917f22ef01cSRoman Divacky   for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2918f22ef01cSRoman Divacky        F != E; ++F)
2919f22ef01cSRoman Divacky     if (F->isMaterializable() &&
2920f22ef01cSRoman Divacky         Materialize(F, ErrInfo))
2921f22ef01cSRoman Divacky       return true;
2922f22ef01cSRoman Divacky 
2923f22ef01cSRoman Divacky   // Upgrade any intrinsic calls that slipped through (should not happen!) and
2924f22ef01cSRoman Divacky   // delete the old functions to clean up. We can't do this unless the entire
2925f22ef01cSRoman Divacky   // module is materialized because there could always be another function body
2926f22ef01cSRoman Divacky   // with calls to the old function.
2927f22ef01cSRoman Divacky   for (std::vector<std::pair<Function*, Function*> >::iterator I =
2928f22ef01cSRoman Divacky        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2929f22ef01cSRoman Divacky     if (I->first != I->second) {
2930f22ef01cSRoman Divacky       for (Value::use_iterator UI = I->first->use_begin(),
2931f22ef01cSRoman Divacky            UE = I->first->use_end(); UI != UE; ) {
2932f22ef01cSRoman Divacky         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2933f22ef01cSRoman Divacky           UpgradeIntrinsicCall(CI, I->second);
2934f22ef01cSRoman Divacky       }
2935f22ef01cSRoman Divacky       if (!I->first->use_empty())
2936f22ef01cSRoman Divacky         I->first->replaceAllUsesWith(I->second);
2937f22ef01cSRoman Divacky       I->first->eraseFromParent();
2938f22ef01cSRoman Divacky     }
2939f22ef01cSRoman Divacky   }
2940f22ef01cSRoman Divacky   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2941f22ef01cSRoman Divacky 
29426122f3e6SDimitry Andric   // Upgrade to new EH scheme. N.B. This will go away in 3.1.
29436122f3e6SDimitry Andric   UpgradeExceptionHandling(M);
29446122f3e6SDimitry Andric 
2945f22ef01cSRoman Divacky   // Check debug info intrinsics.
2946f22ef01cSRoman Divacky   CheckDebugInfoIntrinsics(TheModule);
2947f22ef01cSRoman Divacky 
2948f22ef01cSRoman Divacky   return false;
2949f22ef01cSRoman Divacky }
2950f22ef01cSRoman Divacky 
2951f22ef01cSRoman Divacky 
2952f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
2953f22ef01cSRoman Divacky // External interface
2954f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
2955f22ef01cSRoman Divacky 
2956f22ef01cSRoman Divacky /// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2957f22ef01cSRoman Divacky ///
2958f22ef01cSRoman Divacky Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2959f22ef01cSRoman Divacky                                    LLVMContext& Context,
2960f22ef01cSRoman Divacky                                    std::string *ErrMsg) {
2961f22ef01cSRoman Divacky   Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2962f22ef01cSRoman Divacky   BitcodeReader *R = new BitcodeReader(Buffer, Context);
2963f22ef01cSRoman Divacky   M->setMaterializer(R);
2964f22ef01cSRoman Divacky   if (R->ParseBitcodeInto(M)) {
2965f22ef01cSRoman Divacky     if (ErrMsg)
2966f22ef01cSRoman Divacky       *ErrMsg = R->getErrorString();
2967f22ef01cSRoman Divacky 
2968f22ef01cSRoman Divacky     delete M;  // Also deletes R.
2969f22ef01cSRoman Divacky     return 0;
2970f22ef01cSRoman Divacky   }
2971f22ef01cSRoman Divacky   // Have the BitcodeReader dtor delete 'Buffer'.
2972f22ef01cSRoman Divacky   R->setBufferOwned(true);
2973f22ef01cSRoman Divacky   return M;
2974f22ef01cSRoman Divacky }
2975f22ef01cSRoman Divacky 
2976f22ef01cSRoman Divacky /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2977f22ef01cSRoman Divacky /// If an error occurs, return null and fill in *ErrMsg if non-null.
2978f22ef01cSRoman Divacky Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2979f22ef01cSRoman Divacky                                std::string *ErrMsg){
2980f22ef01cSRoman Divacky   Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2981f22ef01cSRoman Divacky   if (!M) return 0;
2982f22ef01cSRoman Divacky 
2983f22ef01cSRoman Divacky   // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2984f22ef01cSRoman Divacky   // there was an error.
2985f22ef01cSRoman Divacky   static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2986f22ef01cSRoman Divacky 
2987f22ef01cSRoman Divacky   // Read in the entire module, and destroy the BitcodeReader.
2988f22ef01cSRoman Divacky   if (M->MaterializeAllPermanently(ErrMsg)) {
2989f22ef01cSRoman Divacky     delete M;
29902754fe60SDimitry Andric     return 0;
2991f22ef01cSRoman Divacky   }
29922754fe60SDimitry Andric 
2993f22ef01cSRoman Divacky   return M;
2994f22ef01cSRoman Divacky }
29952754fe60SDimitry Andric 
29962754fe60SDimitry Andric std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
29972754fe60SDimitry Andric                                          LLVMContext& Context,
29982754fe60SDimitry Andric                                          std::string *ErrMsg) {
29992754fe60SDimitry Andric   BitcodeReader *R = new BitcodeReader(Buffer, Context);
30002754fe60SDimitry Andric   // Don't let the BitcodeReader dtor delete 'Buffer'.
30012754fe60SDimitry Andric   R->setBufferOwned(false);
30022754fe60SDimitry Andric 
30032754fe60SDimitry Andric   std::string Triple("");
30042754fe60SDimitry Andric   if (R->ParseTriple(Triple))
30052754fe60SDimitry Andric     if (ErrMsg)
30062754fe60SDimitry Andric       *ErrMsg = R->getErrorString();
30072754fe60SDimitry Andric 
30082754fe60SDimitry Andric   delete R;
30092754fe60SDimitry Andric   return Triple;
30102754fe60SDimitry Andric }
3011