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