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