Bug Summary

File:lib/Bitcode/Reader/BitcodeReader.cpp
Location:line 1124, column 7
Description:Value stored to 'IsFunctionLocal' is never read

Annotated Source Code

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