Merge Dumper.cpp and AnalyzerWrappers.cpp into this file. Also, adjust the
[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     Result = new VANextInst(getValue(RI.Type, Args[0]), getType(Args[1]));
128     break;
129   case Instruction::Cast:
130     Result = new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
131     break;
132   case Instruction::Select:
133     Result = new SelectInst(getValue(Type::BoolTyID, Args[0]),
134                             getValue(RI.Type, Args[1]),
135                             getValue(RI.Type, Args[2]));
136     break;
137   case Instruction::PHI: {
138     if (Args.size() == 0 || (Args.size() & 1))
139       throw std::string("Invalid phi node encountered!\n");
140
141     PHINode *PN = new PHINode(InstTy);
142     PN->op_reserve(Args.size());
143     for (unsigned i = 0, e = Args.size(); i != e; i += 2)
144       PN->addIncoming(getValue(RI.Type, Args[i]), getBasicBlock(Args[i+1]));
145     Result = PN;
146     break;
147   }
148
149   case Instruction::Shl:
150   case Instruction::Shr:
151     Result = new ShiftInst((Instruction::OtherOps)RI.Opcode,
152                            getValue(RI.Type, Args[0]),
153                            getValue(Type::UByteTyID, Args[1]));
154     break;
155   case Instruction::Ret:
156     if (Args.size() == 0)
157       Result = new ReturnInst();
158     else if (Args.size() == 1)
159       Result = new ReturnInst(getValue(RI.Type, Args[0]));
160     else
161       throw std::string("Unrecognized instruction!");
162     break;
163
164   case Instruction::Br:
165     if (Args.size() == 1)
166       Result = new BranchInst(getBasicBlock(Args[0]));
167     else if (Args.size() == 3)
168       Result = new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
169                               getValue(Type::BoolTyID , Args[2]));
170     else
171       throw std::string("Invalid number of operands for a 'br' instruction!");
172     break;
173   case Instruction::Switch: {
174     if (Args.size() & 1)
175       throw std::string("Switch statement with odd number of arguments!");
176
177     SwitchInst *I = new SwitchInst(getValue(RI.Type, Args[0]),
178                                    getBasicBlock(Args[1]));
179     for (unsigned i = 2, e = Args.size(); i != e; i += 2)
180       I->addCase(cast<Constant>(getValue(RI.Type, Args[i])),
181                  getBasicBlock(Args[i+1]));
182     Result = I;
183     break;
184   }
185
186   case Instruction::Call: {
187     if (Args.size() == 0)
188       throw std::string("Invalid call instruction encountered!");
189
190     Value *F = getValue(RI.Type, Args[0]);
191
192     // Check to make sure we have a pointer to function type
193     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
194     if (PTy == 0) throw std::string("Call to non function pointer value!");
195     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
196     if (FTy == 0) throw std::string("Call to non function pointer value!");
197
198     std::vector<Value *> Params;
199     if (!FTy->isVarArg()) {
200       FunctionType::param_iterator It = FTy->param_begin();
201
202       for (unsigned i = 1, e = Args.size(); i != e; ++i) {
203         if (It == FTy->param_end())
204           throw std::string("Invalid call instruction!");
205         Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
206       }
207       if (It != FTy->param_end())
208         throw std::string("Invalid call instruction!");
209     } else {
210       Args.erase(Args.begin(), Args.begin()+1);
211
212       unsigned FirstVariableOperand;
213       if (Args.size() < FTy->getNumParams())
214         throw std::string("Call instruction missing operands!");
215
216       // Read all of the fixed arguments
217       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
218         Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Args[i]));
219       
220       FirstVariableOperand = FTy->getNumParams();
221
222       if ((Args.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
223         throw std::string("Invalid call instruction!");
224         
225       for (unsigned i = FirstVariableOperand, e = Args.size(); i != e; i += 2)
226         Params.push_back(getValue(Args[i], Args[i+1]));
227     }
228
229     Result = new CallInst(F, Params);
230     break;
231   }
232   case Instruction::Invoke: {
233     if (Args.size() < 3) throw std::string("Invalid invoke instruction!");
234     Value *F = getValue(RI.Type, Args[0]);
235
236     // Check to make sure we have a pointer to function type
237     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
238     if (PTy == 0) throw std::string("Invoke to non function pointer value!");
239     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
240     if (FTy == 0) throw std::string("Invoke to non function pointer value!");
241
242     std::vector<Value *> Params;
243     BasicBlock *Normal, *Except;
244
245     if (!FTy->isVarArg()) {
246       Normal = getBasicBlock(Args[1]);
247       Except = getBasicBlock(Args[2]);
248
249       FunctionType::param_iterator It = FTy->param_begin();
250       for (unsigned i = 3, e = Args.size(); i != e; ++i) {
251         if (It == FTy->param_end())
252           throw std::string("Invalid invoke instruction!");
253         Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
254       }
255       if (It != FTy->param_end())
256         throw std::string("Invalid invoke instruction!");
257     } else {
258       Args.erase(Args.begin(), Args.begin()+1);
259
260       Normal = getBasicBlock(Args[0]);
261       Except = getBasicBlock(Args[1]);
262       
263       unsigned FirstVariableArgument = FTy->getNumParams()+2;
264       for (unsigned i = 2; i != FirstVariableArgument; ++i)
265         Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
266                                   Args[i]));
267       
268       if (Args.size()-FirstVariableArgument & 1)  // Must be pairs of type/value
269         throw std::string("Invalid invoke instruction!");
270
271       for (unsigned i = FirstVariableArgument; i < Args.size(); i += 2)
272         Params.push_back(getValue(Args[i], Args[i+1]));
273     }
274
275     Result = new InvokeInst(F, Normal, Except, Params);
276     break;
277   }
278   case Instruction::Malloc:
279     if (Args.size() > 2) throw std::string("Invalid malloc instruction!");
280     if (!isa<PointerType>(InstTy))
281       throw std::string("Invalid malloc instruction!");
282
283     Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
284                             Args.size() ? getValue(Type::UIntTyID,
285                                                    Args[0]) : 0);
286     break;
287
288   case Instruction::Alloca:
289     if (Args.size() > 2) throw std::string("Invalid alloca instruction!");
290     if (!isa<PointerType>(InstTy))
291       throw std::string("Invalid alloca instruction!");
292
293     Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
294                             Args.size() ? getValue(Type::UIntTyID, Args[0]) :0);
295     break;
296   case Instruction::Free:
297     if (!isa<PointerType>(InstTy))
298       throw std::string("Invalid free instruction!");
299     Result = new FreeInst(getValue(RI.Type, Args[0]));
300     break;
301   case Instruction::GetElementPtr: {
302     if (Args.size() == 0 || !isa<PointerType>(InstTy))
303       throw std::string("Invalid getelementptr instruction!");
304
305     std::vector<Value*> Idx;
306
307     const Type *NextTy = InstTy;
308     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
309       const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
310       if (!TopTy) throw std::string("Invalid getelementptr instruction!"); 
311
312       unsigned ValIdx = Args[i];
313       unsigned IdxTy = 0;
314       if (!hasRestrictedGEPTypes) {
315         // Struct indices are always uints, sequential type indices can be any
316         // of the 32 or 64-bit integer types.  The actual choice of type is
317         // encoded in the low two bits of the slot number.
318         if (isa<StructType>(TopTy))
319           IdxTy = Type::UIntTyID;
320         else {
321           switch (ValIdx & 3) {
322           default:
323           case 0: IdxTy = Type::UIntTyID; break;
324           case 1: IdxTy = Type::IntTyID; break;
325           case 2: IdxTy = Type::ULongTyID; break;
326           case 3: IdxTy = Type::LongTyID; break;
327           }
328           ValIdx >>= 2;
329         }
330       } else {
331         IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
332       }
333
334       Idx.push_back(getValue(IdxTy, ValIdx));
335
336       // Convert ubyte struct indices into uint struct indices.
337       if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
338         if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
339           Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
340
341       NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
342     }
343
344     Result = new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
345     break;
346   }
347
348   case 62:   // volatile load
349   case Instruction::Load:
350     if (Args.size() != 1 || !isa<PointerType>(InstTy))
351       throw std::string("Invalid load instruction!");
352     Result = new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
353     break;
354
355   case 63:   // volatile store 
356   case Instruction::Store: {
357     if (!isa<PointerType>(InstTy) || Args.size() != 2)
358       throw std::string("Invalid store instruction!");
359
360     Value *Ptr = getValue(RI.Type, Args[1]);
361     const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
362     Result = new StoreInst(getValue(getTypeSlot(ValTy), Args[0]), Ptr,
363                            RI.Opcode == 63);
364     break;
365   }
366   case Instruction::Unwind:
367     if (Args.size() != 0) throw std::string("Invalid unwind instruction!");
368     Result = new UnwindInst();
369     break;
370   }  // end switch(RI.Opcode) 
371
372   unsigned TypeSlot;
373   if (Result->getType() == InstTy)
374     TypeSlot = RI.Type;
375   else
376     TypeSlot = getTypeSlot(Result->getType());
377
378   insertValue(Result, TypeSlot, Values);
379   BB->getInstList().push_back(Result);
380   BCR_TRACE(4, *Result);
381 }