1f1485e2f2e56c082627a668b496f9cfc67f2baa
[oota-llvm.git] / lib / Bytecode / Reader / InstructionReader.cpp
1 //===- ReadInst.cpp - Code to read an instruction from bytecode -----------===//
2 //
3 // This file defines the mechanism to read an instruction from a bytecode 
4 // stream.
5 //
6 // Note that this library should be as fast as possible, reentrant, and 
7 // threadsafe!!
8 //
9 // TODO: Change from getValue(Raw.Arg1) etc, to getArg(Raw, 1)
10 //       Make it check type, so that casts are checked.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ReaderInternals.h"
15 #include "llvm/iTerminators.h"
16 #include "llvm/iMemory.h"
17 #include "llvm/iPHINode.h"
18 #include "llvm/iOther.h"
19 using std::vector;
20 using std::cerr;
21
22 bool BytecodeParser::ParseRawInst(const uchar *&Buf, const uchar *EndBuf, 
23                                   RawInst &Result) {
24   unsigned Op, Typ;
25   if (read(Buf, EndBuf, Op)) return true;
26
27   // bits   Instruction format:        Common to all formats
28   // --------------------------
29   // 01-00: Opcode type, fixed to 1.
30   // 07-02: Opcode
31   Result.NumOperands = (Op >> 0) & 03;
32   Result.Opcode      = (Op >> 2) & 63;
33
34   switch (Result.NumOperands) {
35   case 1:
36     // bits   Instruction format:
37     // --------------------------
38     // 19-08: Resulting type plane
39     // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
40     //
41     Result.Ty   = getType((Op >> 8) & 4095);
42     Result.Arg1 = (Op >> 20) & 4095;
43     if (Result.Arg1 == 4095)    // Handle special encoding for 0 operands...
44       Result.NumOperands = 0;
45     break;
46   case 2:
47     // bits   Instruction format:
48     // --------------------------
49     // 15-08: Resulting type plane
50     // 23-16: Operand #1
51     // 31-24: Operand #2  
52     //
53     Result.Ty   = getType((Op >> 8) & 255);
54     Result.Arg1 = (Op >> 16) & 255;
55     Result.Arg2 = (Op >> 24) & 255;
56     break;
57   case 3:
58     // bits   Instruction format:
59     // --------------------------
60     // 13-08: Resulting type plane
61     // 19-14: Operand #1
62     // 25-20: Operand #2
63     // 31-26: Operand #3
64     //
65     Result.Ty   = getType((Op >> 8) & 63);
66     Result.Arg1 = (Op >> 14) & 63;
67     Result.Arg2 = (Op >> 20) & 63;
68     Result.Arg3 = (Op >> 26) & 63;
69     break;
70   case 0:
71     Buf -= 4;  // Hrm, try this again...
72     if (read_vbr(Buf, EndBuf, Result.Opcode)) return true;
73     Result.Opcode >>= 2;
74     if (read_vbr(Buf, EndBuf, Typ)) return true;
75     Result.Ty = getType(Typ);
76     if (Result.Ty == 0) return true;
77     if (read_vbr(Buf, EndBuf, Result.NumOperands)) return true;
78
79     switch (Result.NumOperands) {
80     case 0: 
81       cerr << "Zero Arg instr found!\n"; 
82       return true;  // This encoding is invalid!
83     case 1: 
84       if (read_vbr(Buf, EndBuf, Result.Arg1)) return true;
85       break;
86     case 2:
87       if (read_vbr(Buf, EndBuf, Result.Arg1) || 
88           read_vbr(Buf, EndBuf, Result.Arg2)) return true;
89       break;
90     case 3:
91       if (read_vbr(Buf, EndBuf, Result.Arg1) || 
92           read_vbr(Buf, EndBuf, Result.Arg2) ||
93           read_vbr(Buf, EndBuf, Result.Arg3)) return true;
94       break;
95     default:
96       if (read_vbr(Buf, EndBuf, Result.Arg1) || 
97           read_vbr(Buf, EndBuf, Result.Arg2)) return true;
98
99       // Allocate a vector to hold arguments 3, 4, 5, 6 ...
100       Result.VarArgs = new vector<unsigned>(Result.NumOperands-2);
101       for (unsigned a = 0; a < Result.NumOperands-2; a++)
102         if (read_vbr(Buf, EndBuf, (*Result.VarArgs)[a])) return true;
103       break;
104     }
105     if (align32(Buf, EndBuf)) return true;
106     break;
107   }
108
109 #if 0
110   cerr << "NO: "  << Result.NumOperands   << " opcode: " << Result.Opcode 
111        << " Ty: " << Result.Ty->getDescription() << " arg1: "   << Result.Arg1 
112        << " arg2: "   << Result.Arg2 << " arg3: "   << Result.Arg3 << "\n";
113 #endif
114   return false;
115 }
116
117
118 bool BytecodeParser::ParseInstruction(const uchar *&Buf, const uchar *EndBuf,
119                                       Instruction *&Res,
120                                       BasicBlock *BB /*HACK*/) {
121   RawInst Raw;
122   if (ParseRawInst(Buf, EndBuf, Raw))
123     return true;
124
125   if (Raw.Opcode >= Instruction::FirstBinaryOp &&
126       Raw.Opcode <  Instruction::NumBinaryOps  && Raw.NumOperands == 2) {
127     Res = BinaryOperator::create((Instruction::BinaryOps)Raw.Opcode,
128                                  getValue(Raw.Ty, Raw.Arg1),
129                                  getValue(Raw.Ty, Raw.Arg2));
130     return false;
131   } 
132
133   Value *V;
134   switch (Raw.Opcode) {
135   case Instruction::Cast: {
136     V = getValue(Raw.Ty, Raw.Arg1);
137     const Type *Ty = getType(Raw.Arg2);
138     if (V == 0 || Ty == 0) { cerr << "Invalid cast!\n"; return true; }
139     Res = new CastInst(V, Ty);
140     return false;
141   }
142   case Instruction::PHINode: {
143     PHINode *PN = new PHINode(Raw.Ty);
144     switch (Raw.NumOperands) {
145     case 0: 
146     case 1: 
147     case 3: cerr << "Invalid phi node encountered!\n"; 
148             delete PN; 
149             return true;
150     case 2: PN->addIncoming(getValue(Raw.Ty, Raw.Arg1),
151                             cast<BasicBlock>(getValue(Type::LabelTy,Raw.Arg2)));
152       break;
153     default:
154       PN->addIncoming(getValue(Raw.Ty, Raw.Arg1), 
155                       cast<BasicBlock>(getValue(Type::LabelTy, Raw.Arg2)));
156       if (Raw.VarArgs->size() & 1) {
157         cerr << "PHI Node with ODD number of arguments!\n";
158         delete PN;
159         return true;
160       } else {
161         vector<unsigned> &args = *Raw.VarArgs;
162         for (unsigned i = 0; i < args.size(); i+=2)
163           PN->addIncoming(getValue(Raw.Ty, args[i]),
164                           cast<BasicBlock>(getValue(Type::LabelTy, args[i+1])));
165       }
166       delete Raw.VarArgs; 
167       break;
168     }
169     Res = PN;
170     return false;
171   }
172
173   case Instruction::Shl:
174   case Instruction::Shr:
175     Res = new ShiftInst((Instruction::OtherOps)Raw.Opcode,
176                         getValue(Raw.Ty, Raw.Arg1),
177                         getValue(Type::UByteTy, Raw.Arg2));
178     return false;
179   case Instruction::Ret:
180     if (Raw.NumOperands == 0) {
181       Res = new ReturnInst(); return false; 
182     } else if (Raw.NumOperands == 1) {
183       Res = new ReturnInst(getValue(Raw.Ty, Raw.Arg1)); return false; 
184     }
185     break;
186
187   case Instruction::Br:
188     if (Raw.NumOperands == 1) {
189       Res = new BranchInst(cast<BasicBlock>(getValue(Type::LabelTy, Raw.Arg1)));
190       return false;
191     } else if (Raw.NumOperands == 3) {
192       Res = new BranchInst(cast<BasicBlock>(getValue(Type::LabelTy, Raw.Arg1)),
193                            cast<BasicBlock>(getValue(Type::LabelTy, Raw.Arg2)),
194                                             getValue(Type::BoolTy , Raw.Arg3));
195       return false;
196     }
197     break;
198     
199   case Instruction::Switch: {
200     SwitchInst *I = 
201       new SwitchInst(getValue(Raw.Ty, Raw.Arg1), 
202                      cast<BasicBlock>(getValue(Type::LabelTy, Raw.Arg2)));
203     Res = I;
204     if (Raw.NumOperands < 3) return false;  // No destinations?  Wierd.
205
206     if (Raw.NumOperands == 3 || Raw.VarArgs->size() & 1) {
207       cerr << "Switch statement with odd number of arguments!\n";
208       delete I;
209       return true;
210     }      
211     
212     vector<unsigned> &args = *Raw.VarArgs;
213     for (unsigned i = 0; i < args.size(); i += 2)
214       I->dest_push_back(cast<Constant>(getValue(Raw.Ty, args[i])),
215                         cast<BasicBlock>(getValue(Type::LabelTy, args[i+1])));
216
217     delete Raw.VarArgs;
218     return false;
219   }
220
221   case Instruction::Call: {
222     Value *M = getValue(Raw.Ty, Raw.Arg1);
223     if (M == 0) return true;
224
225     // Check to make sure we have a pointer to method type
226     const PointerType *PTy = dyn_cast<PointerType>(M->getType());
227     if (PTy == 0) return true;
228     const FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
229     if (MTy == 0) return true;
230
231     vector<Value *> Params;
232     const FunctionType::ParamTypes &PL = MTy->getParamTypes();
233
234     if (!MTy->isVarArg()) {
235       FunctionType::ParamTypes::const_iterator It = PL.begin();
236
237       switch (Raw.NumOperands) {
238       case 0: cerr << "Invalid call instruction encountered!\n";
239         return true;
240       case 1: break;
241       case 2: Params.push_back(getValue(*It++, Raw.Arg2)); break;
242       case 3: Params.push_back(getValue(*It++, Raw.Arg2)); 
243         if (It == PL.end()) return true;
244         Params.push_back(getValue(*It++, Raw.Arg3)); break;
245       default:
246         Params.push_back(getValue(*It++, Raw.Arg2));
247         {
248           vector<unsigned> &args = *Raw.VarArgs;
249           for (unsigned i = 0; i < args.size(); i++) {
250             if (It == PL.end()) return true;
251             // TODO: Check getValue for null!
252             Params.push_back(getValue(*It++, args[i]));
253           }
254         }
255         delete Raw.VarArgs;
256       }
257       if (It != PL.end()) return true;
258     } else {
259       if (Raw.NumOperands > 2) {
260         vector<unsigned> &args = *Raw.VarArgs;
261         if (args.size() < 1) return true;
262
263         if ((args.size() & 1) != 0)
264           return true;  // Must be pairs of type/value
265         for (unsigned i = 0; i < args.size(); i+=2) {
266           const Type *Ty = getType(args[i]);
267           if (Ty == 0)
268             return true;
269           
270           Value *V = getValue(Ty, args[i+1]);
271           if (V == 0) return true;
272           Params.push_back(V);
273         }
274         delete Raw.VarArgs;
275       }
276     }
277
278     Res = new CallInst(M, Params);
279     return false;
280   }
281   case Instruction::Invoke: {
282     Value *M = getValue(Raw.Ty, Raw.Arg1);
283     if (M == 0) return true;
284
285     // Check to make sure we have a pointer to method type
286     const PointerType *PTy = dyn_cast<PointerType>(M->getType());
287     if (PTy == 0) return true;
288     const FunctionType *MTy = dyn_cast<FunctionType>(PTy->getElementType());
289     if (MTy == 0) return true;
290
291     vector<Value *> Params;
292     const FunctionType::ParamTypes &PL = MTy->getParamTypes();
293     vector<unsigned> &args = *Raw.VarArgs;
294
295     BasicBlock *Normal, *Except;
296
297     if (!MTy->isVarArg()) {
298       if (Raw.NumOperands < 3) return true;
299
300       Normal = cast<BasicBlock>(getValue(Type::LabelTy, Raw.Arg2));
301       Except = cast<BasicBlock>(getValue(Type::LabelTy, args[0]));
302
303       FunctionType::ParamTypes::const_iterator It = PL.begin();
304       for (unsigned i = 1; i < args.size(); i++) {
305         if (It == PL.end()) return true;
306         // TODO: Check getValue for null!
307         Params.push_back(getValue(*It++, args[i]));
308       }
309
310       if (It != PL.end()) return true;
311     } else {
312       if (args.size() < 4) return true;
313
314       Normal = cast<BasicBlock>(getValue(Type::LabelTy, args[0]));
315       Except = cast<BasicBlock>(getValue(Type::LabelTy, args[2]));
316
317       if ((args.size() & 1) != 0)
318         return true;  // Must be pairs of type/value
319       for (unsigned i = 4; i < args.size(); i+=2) {
320         // TODO: Check getValue for null!
321         Params.push_back(getValue(getType(args[i]), args[i+1]));
322       }
323     }
324
325     delete Raw.VarArgs;
326     Res = new InvokeInst(M, Normal, Except, Params);
327     return false;
328   }
329   case Instruction::Malloc:
330     if (Raw.NumOperands > 2) return true;
331     V = Raw.NumOperands ? getValue(Type::UIntTy, Raw.Arg1) : 0;
332     Res = new MallocInst(Raw.Ty, V);
333     return false;
334
335   case Instruction::Alloca:
336     if (Raw.NumOperands > 2) return true;
337     V = Raw.NumOperands ? getValue(Type::UIntTy, Raw.Arg1) : 0;
338     Res = new AllocaInst(Raw.Ty, V);
339     return false;
340
341   case Instruction::Free:
342     V = getValue(Raw.Ty, Raw.Arg1);
343     if (!isa<PointerType>(V->getType())) return true;
344     Res = new FreeInst(V);
345     return false;
346
347   case Instruction::Load:
348   case Instruction::GetElementPtr: {
349     vector<Value*> Idx;
350     if (!isa<PointerType>(Raw.Ty)) return true;
351     const CompositeType *TopTy = dyn_cast<CompositeType>(Raw.Ty);
352
353     switch (Raw.NumOperands) {
354     case 0: cerr << "Invalid load encountered!\n"; return true;
355     case 1: break;
356     case 2:
357       if (!TopTy) return true;
358       Idx.push_back(V = getValue(TopTy->getIndexType(), Raw.Arg2));
359       if (!V) return true;
360       break;
361     case 3: {
362       if (!TopTy) return true;
363       Idx.push_back(V = getValue(TopTy->getIndexType(), Raw.Arg2));
364       if (!V) return true;
365
366       const Type *ETy = MemAccessInst::getIndexedType(TopTy, Idx, true);
367       const CompositeType *ElTy = dyn_cast_or_null<CompositeType>(ETy);
368       if (!ElTy) return true;
369
370       Idx.push_back(V = getValue(ElTy->getIndexType(), Raw.Arg3));
371       if (!V) return true;
372       break;
373     }
374     default:
375       if (!TopTy) return true;
376       Idx.push_back(V = getValue(TopTy->getIndexType(), Raw.Arg2));
377       if (!V) return true;
378
379       vector<unsigned> &args = *Raw.VarArgs;
380       for (unsigned i = 0, E = args.size(); i != E; ++i) {
381         const Type *ETy = MemAccessInst::getIndexedType(Raw.Ty, Idx, true);
382         const CompositeType *ElTy = dyn_cast_or_null<CompositeType>(ETy);
383         if (!ElTy) return true;
384         Idx.push_back(V = getValue(ElTy->getIndexType(), args[i]));
385         if (!V) return true;
386       }
387       delete Raw.VarArgs; 
388       break;
389     }
390
391     if (Raw.Opcode == Instruction::Load) {
392       Value *Src = getValue(Raw.Ty, Raw.Arg1);
393       if (!Idx.empty()) {
394         cerr << "WARNING: Bytecode contains load instruction with indices.  "
395              << "Replacing with getelementptr/load pair\n";
396         assert(MemAccessInst::getIndexedType(Raw.Ty, Idx) && 
397                "Bad indices for Load!");
398         Src = new GetElementPtrInst(Src, Idx);
399         // FIXME: Remove this compatibility code and the BB parameter to this
400         // method.
401         BB->getInstList().push_back(cast<Instruction>(Src));
402       }
403       Res = new LoadInst(Src);
404     } else if (Raw.Opcode == Instruction::GetElementPtr)
405       Res = new GetElementPtrInst(getValue(Raw.Ty, Raw.Arg1), Idx);
406     else
407       abort();
408     return false;
409   }
410   case Instruction::Store: {
411     vector<Value*> Idx;
412     if (!isa<PointerType>(Raw.Ty)) return true;
413     const CompositeType *TopTy = dyn_cast<CompositeType>(Raw.Ty);
414
415     switch (Raw.NumOperands) {
416     case 0: 
417     case 1: cerr << "Invalid store encountered!\n"; return true;
418     case 2: break;
419     case 3:
420       if (!TopTy) return true;
421       Idx.push_back(V = getValue(TopTy->getIndexType(), Raw.Arg3));
422       if (!V) return true;
423       break;
424     default:
425       vector<unsigned> &args = *Raw.VarArgs;
426       const CompositeType *ElTy = TopTy;
427       unsigned i, E;
428       for (i = 0, E = args.size(); ElTy && i != E; ++i) {
429         Idx.push_back(V = getValue(ElTy->getIndexType(), args[i]));
430         if (!V) return true;
431
432         const Type *ETy = MemAccessInst::getIndexedType(Raw.Ty, Idx, true);
433         ElTy = dyn_cast_or_null<CompositeType>(ETy);
434       }
435       if (i != E)
436         return true;  // didn't use up all of the indices!
437
438       delete Raw.VarArgs; 
439       break;
440     }
441
442     Value *Ptr = getValue(Raw.Ty, Raw.Arg2);
443     if (!Idx.empty()) {
444       cerr << "WARNING: Bytecode contains load instruction with indices.  "
445            << "Replacing with getelementptr/load pair\n";
446
447       const Type *ElType = StoreInst::getIndexedType(Raw.Ty, Idx);
448       if (ElType == 0) return true;
449
450       Ptr = new GetElementPtrInst(Ptr, Idx);
451       // FIXME: Remove this compatibility code and the BB parameter to this
452       // method.
453       BB->getInstList().push_back(cast<Instruction>(Ptr));
454     }
455
456     const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
457     Res = new StoreInst(getValue(ValTy, Raw.Arg1), Ptr);
458     return false;
459   }
460   }  // end switch(Raw.Opcode) 
461
462   cerr << "Unrecognized instruction! " << Raw.Opcode 
463        << " ADDR = 0x" << (void*)Buf << "\n";
464   return true;
465 }