Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(457)

Side by Side Diff: lib/Bitcode/NaCl/Reader/NaClBitcodeReader.cpp

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

Powered by Google App Engine
This is Rietveld 408576698