a409ceebef975f2e384a003f1e569529382760c5
[oota-llvm.git] / lib / Bytecode / Reader / InstructionReader.cpp
1 //===- ReadInst.cpp - Code to read an instruction from bytecode -----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the mechanism to read an instruction from a bytecode 
11 // stream.
12 //
13 // Note that this library should be as fast as possible, reentrant, and 
14 // threadsafe!!
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "ReaderInternals.h"
19 #include "llvm/iTerminators.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/iOther.h"
23 #include "llvm/Module.h"
24
25 namespace {
26   struct RawInst {       // The raw fields out of the bytecode stream...
27     unsigned NumOperands;
28     unsigned Opcode;
29     unsigned Type;
30     
31     RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
32             std::vector<unsigned> &Args);
33   };
34 }
35
36
37
38 RawInst::RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
39                  std::vector<unsigned> &Args) {
40   unsigned Op, Typ;
41   if (read(Buf, EndBuf, Op)) 
42     throw std::string("Error reading from buffer.");
43
44   // bits   Instruction format:        Common to all formats
45   // --------------------------
46   // 01-00: Opcode type, fixed to 1.
47   // 07-02: Opcode
48   Opcode    = (Op >> 2) & 63;
49   Args.resize((Op >> 0) & 03);
50
51   switch (Args.size()) {
52   case 1:
53     // bits   Instruction format:
54     // --------------------------
55     // 19-08: Resulting type plane
56     // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
57     //
58     Type    = (Op >>  8) & 4095;
59     Args[0] = (Op >> 20) & 4095;
60     if (Args[0] == 4095)    // Handle special encoding for 0 operands...
61       Args.resize(0);
62     break;
63   case 2:
64     // bits   Instruction format:
65     // --------------------------
66     // 15-08: Resulting type plane
67     // 23-16: Operand #1
68     // 31-24: Operand #2  
69     //
70     Type    = (Op >>  8) & 255;
71     Args[0] = (Op >> 16) & 255;
72     Args[1] = (Op >> 24) & 255;
73     break;
74   case 3:
75     // bits   Instruction format:
76     // --------------------------
77     // 13-08: Resulting type plane
78     // 19-14: Operand #1
79     // 25-20: Operand #2
80     // 31-26: Operand #3
81     //
82     Type    = (Op >>  8) & 63;
83     Args[0] = (Op >> 14) & 63;
84     Args[1] = (Op >> 20) & 63;
85     Args[2] = (Op >> 26) & 63;
86     break;
87   case 0:
88     Buf -= 4;  // Hrm, try this again...
89     if (read_vbr(Buf, EndBuf, Opcode))
90       throw std::string("Error reading from buffer.");
91     Opcode >>= 2;
92     if (read_vbr(Buf, EndBuf, Type))
93       throw std::string("Error reading from buffer.");
94
95     unsigned NumOperands;
96     if (read_vbr(Buf, EndBuf, NumOperands))
97       throw std::string("Error reading from buffer.");
98     Args.resize(NumOperands);
99
100     if (NumOperands == 0)
101       throw std::string("Zero-argument instruction found; this is invalid.");
102
103     for (unsigned i = 0; i != NumOperands; ++i)
104       if (read_vbr(Buf, EndBuf, Args[i])) 
105         throw std::string("Error reading from buffer");
106     if (align32(Buf, EndBuf))
107       throw std::string("Unaligned bytecode buffer.");
108     break;
109   }
110 }
111
112
113 void BytecodeParser::ParseInstruction(const unsigned char *&Buf,
114                                       const unsigned char *EndBuf,
115                                       std::vector<unsigned> &Args,
116                                       BasicBlock *BB) {
117   Args.clear();
118   RawInst RI(Buf, EndBuf, Args);
119   const Type *InstTy = getType(RI.Type);
120
121   Instruction *Result = 0;
122   if (RI.Opcode >= Instruction::BinaryOpsBegin &&
123       RI.Opcode <  Instruction::BinaryOpsEnd  && Args.size() == 2)
124     Result = BinaryOperator::create((Instruction::BinaryOps)RI.Opcode,
125                                     getValue(RI.Type, Args[0]),
126                                     getValue(RI.Type, Args[1]));
127
128   switch (RI.Opcode) {
129   default: 
130     if (Result == 0) throw std::string("Illegal instruction read!");
131     break;
132   case Instruction::VAArg:
133     Result = new VAArgInst(getValue(RI.Type, Args[0]), getType(Args[1]));
134     break;
135   case Instruction::VANext:
136     if (!hasOldStyleVarargs) {
137       Result = new VANextInst(getValue(RI.Type, Args[0]), getType(Args[1]));
138     } else {
139       // In the old-style varargs scheme, this was the "va_arg" instruction.
140       // Emit emulation code now.
141       if (!usesOldStyleVarargs) {
142         usesOldStyleVarargs = true;
143         std::cerr << "WARNING: this bytecode file uses obsolete features.  "
144                   << "Disassemble and assemble to update it.\n";
145       }
146
147       Value *VAListPtr = getValue(RI.Type, Args[0]);
148       const Type *ArgTy = getType(Args[1]);
149
150       // First, load the valist...
151       Instruction *CurVAList = new LoadInst(VAListPtr, "");
152       BB->getInstList().push_back(CurVAList);
153       
154       // Construct the vaarg
155       Result = new VAArgInst(CurVAList, ArgTy);
156       
157       // Now we must advance the pointer and update it in memory.
158       Instruction *TheVANext = new VANextInst(CurVAList, ArgTy);
159       BB->getInstList().push_back(TheVANext);
160       
161       BB->getInstList().push_back(new StoreInst(TheVANext, VAListPtr));
162     }
163
164     break;
165   case Instruction::Cast:
166     Result = new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
167     break;
168   case Instruction::PHI: {
169     if (Args.size() == 0 || (Args.size() & 1))
170       throw std::string("Invalid phi node encountered!\n");
171
172     PHINode *PN = new PHINode(InstTy);
173     PN->op_reserve(Args.size());
174     for (unsigned i = 0, e = Args.size(); i != e; i += 2)
175       PN->addIncoming(getValue(RI.Type, Args[i]), getBasicBlock(Args[i+1]));
176     Result = PN;
177     break;
178   }
179
180   case Instruction::Shl:
181   case Instruction::Shr:
182     Result = new ShiftInst((Instruction::OtherOps)RI.Opcode,
183                            getValue(RI.Type, Args[0]),
184                            getValue(Type::UByteTyID, Args[1]));
185     break;
186   case Instruction::Ret:
187     if (Args.size() == 0)
188       Result = new ReturnInst();
189     else if (Args.size() == 1)
190       Result = new ReturnInst(getValue(RI.Type, Args[0]));
191     else
192       throw std::string("Unrecognized instruction!");
193     break;
194
195   case Instruction::Br:
196     if (Args.size() == 1)
197       Result = new BranchInst(getBasicBlock(Args[0]));
198     else if (Args.size() == 3)
199       Result = new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
200                               getValue(Type::BoolTyID , Args[2]));
201     else
202       throw std::string("Invalid number of operands for a 'br' instruction!");
203     break;
204   case Instruction::Switch: {
205     if (Args.size() & 1)
206       throw std::string("Switch statement with odd number of arguments!");
207
208     SwitchInst *I = new SwitchInst(getValue(RI.Type, Args[0]),
209                                    getBasicBlock(Args[1]));
210     for (unsigned i = 2, e = Args.size(); i != e; i += 2)
211       I->addCase(cast<Constant>(getValue(RI.Type, Args[i])),
212                  getBasicBlock(Args[i+1]));
213     Result = I;
214     break;
215   }
216
217   case Instruction::Call: {
218     if (Args.size() == 0)
219       throw std::string("Invalid call instruction encountered!");
220
221     Value *F = getValue(RI.Type, Args[0]);
222
223     // Check to make sure we have a pointer to function type
224     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
225     if (PTy == 0) throw std::string("Call to non function pointer value!");
226     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
227     if (FTy == 0) throw std::string("Call to non function pointer value!");
228
229     std::vector<Value *> Params;
230     const FunctionType::ParamTypes &PL = FTy->getParamTypes();
231
232     if (!FTy->isVarArg()) {
233       FunctionType::ParamTypes::const_iterator It = PL.begin();
234
235       for (unsigned i = 1, e = Args.size(); i != e; ++i) {
236         if (It == PL.end()) throw std::string("Invalid call instruction!");
237         Params.push_back(getValue(*It++, Args[i]));
238       }
239       if (It != PL.end()) throw std::string("Invalid call instruction!");
240     } else {
241       Args.erase(Args.begin(), Args.begin()+1+hasVarArgCallPadding);
242
243       unsigned FirstVariableOperand;
244       if (!hasVarArgCallPadding) {
245         if (Args.size() < FTy->getNumParams())
246           throw std::string("Call instruction missing operands!");
247
248         // Read all of the fixed arguments
249         for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
250           Params.push_back(getValue(FTy->getParamType(i), Args[i]));
251
252         FirstVariableOperand = FTy->getNumParams();
253       } else {
254         FirstVariableOperand = 0;
255       }
256
257       if ((Args.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
258         throw std::string("Invalid call instruction!");
259         
260       for (unsigned i = FirstVariableOperand, e = Args.size(); i != e; i += 2)
261         Params.push_back(getValue(Args[i], Args[i+1]));
262     }
263
264     Result = new CallInst(F, Params);
265     break;
266   }
267   case Instruction::Invoke: {
268     if (Args.size() < 3) throw std::string("Invalid invoke instruction!");
269     Value *F = getValue(RI.Type, Args[0]);
270
271     // Check to make sure we have a pointer to function type
272     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
273     if (PTy == 0) throw std::string("Invoke to non function pointer value!");
274     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
275     if (FTy == 0) throw std::string("Invoke to non function pointer value!");
276
277     std::vector<Value *> Params;
278     BasicBlock *Normal, *Except;
279
280     const FunctionType::ParamTypes &PL = FTy->getParamTypes();
281
282     if (!FTy->isVarArg()) {
283       Normal = getBasicBlock(Args[1]);
284       Except = getBasicBlock(Args[2]);
285
286       FunctionType::ParamTypes::const_iterator It = PL.begin();
287       for (unsigned i = 3, e = Args.size(); i != e; ++i) {
288         if (It == PL.end()) throw std::string("Invalid invoke instruction!");
289         Params.push_back(getValue(*It++, Args[i]));
290       }
291       if (It != PL.end()) throw std::string("Invalid invoke instruction!");
292     } else {
293       Args.erase(Args.begin(), Args.begin()+1+hasVarArgCallPadding);
294
295       unsigned FirstVariableArgument;
296       if (!hasVarArgCallPadding) {
297         Normal = getBasicBlock(Args[0]);
298         Except = getBasicBlock(Args[1]);
299
300         FirstVariableArgument = FTy->getNumParams()+2;
301         for (unsigned i = 2; i != FirstVariableArgument; ++i)
302           Params.push_back(getValue(FTy->getParamType(i-2), Args[i]));
303           
304       } else {
305         if (Args.size() < 4) throw std::string("Invalid invoke instruction!");
306         if (Args[0] != Type::LabelTyID || Args[2] != Type::LabelTyID)
307           throw std::string("Invalid invoke instruction!");
308         Normal = getBasicBlock(Args[1]);
309         Except = getBasicBlock(Args[3]);
310
311         FirstVariableArgument = 4;
312       }
313
314       if (Args.size()-FirstVariableArgument & 1)  // Must be pairs of type/value
315         throw std::string("Invalid invoke instruction!");
316
317       for (unsigned i = FirstVariableArgument; i < Args.size(); i += 2)
318         Params.push_back(getValue(Args[i], Args[i+1]));
319     }
320
321     Result = new InvokeInst(F, Normal, Except, Params);
322     break;
323   }
324   case Instruction::Malloc:
325     if (Args.size() > 2) throw std::string("Invalid malloc instruction!");
326     if (!isa<PointerType>(InstTy))
327       throw std::string("Invalid malloc instruction!");
328
329     Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
330                             Args.size() ? getValue(Type::UIntTyID,
331                                                    Args[0]) : 0);
332     break;
333
334   case Instruction::Alloca:
335     if (Args.size() > 2) throw std::string("Invalid alloca instruction!");
336     if (!isa<PointerType>(InstTy))
337       throw std::string("Invalid alloca instruction!");
338
339     Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
340                             Args.size() ? getValue(Type::UIntTyID, Args[0]) :0);
341     break;
342   case Instruction::Free:
343     if (!isa<PointerType>(InstTy))
344       throw std::string("Invalid free instruction!");
345     Result = new FreeInst(getValue(RI.Type, Args[0]));
346     break;
347   case Instruction::GetElementPtr: {
348     if (Args.size() == 0 || !isa<PointerType>(InstTy))
349       throw std::string("Invalid getelementptr instruction!");
350
351     std::vector<Value*> Idx;
352
353     const Type *NextTy = InstTy;
354     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
355       const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
356       if (!TopTy) throw std::string("Invalid getelementptr instruction!"); 
357       Idx.push_back(getValue(TopTy->getIndexType(), Args[i]));
358       NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
359     }
360
361     Result = new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
362     break;
363   }
364
365   case 62:   // volatile load
366   case Instruction::Load:
367     if (Args.size() != 1 || !isa<PointerType>(InstTy))
368       throw std::string("Invalid load instruction!");
369     Result = new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
370     break;
371
372   case 63:   // volatile store 
373   case Instruction::Store: {
374     if (!isa<PointerType>(InstTy) || Args.size() != 2)
375       throw std::string("Invalid store instruction!");
376
377     Value *Ptr = getValue(RI.Type, Args[1]);
378     const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
379     Result = new StoreInst(getValue(ValTy, Args[0]), Ptr, RI.Opcode == 63);
380     break;
381   }
382   case Instruction::Unwind:
383     if (Args.size() != 0) throw std::string("Invalid unwind instruction!");
384     Result = new UnwindInst();
385     break;
386   }  // end switch(RI.Opcode) 
387
388   insertValue(Result, Values);
389   BB->getInstList().push_back(Result);
390   BCR_TRACE(4, *Result);
391 }