Reserve space for PHI operands
[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 //===----------------------------------------------------------------------===//
10
11 #include "ReaderInternals.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/iOther.h"
16
17 namespace {
18   struct RawInst {       // The raw fields out of the bytecode stream...
19     unsigned NumOperands;
20     unsigned Opcode;
21     unsigned Type;
22     
23     RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
24             std::vector<unsigned> &Args);
25   };
26 }
27
28
29
30 RawInst::RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
31                  std::vector<unsigned> &Args) {
32   unsigned Op, Typ;
33   if (read(Buf, EndBuf, Op)) 
34     throw std::string("Error reading from buffer.");
35
36   // bits   Instruction format:        Common to all formats
37   // --------------------------
38   // 01-00: Opcode type, fixed to 1.
39   // 07-02: Opcode
40   Opcode    = (Op >> 2) & 63;
41   Args.resize((Op >> 0) & 03);
42
43   switch (Args.size()) {
44   case 1:
45     // bits   Instruction format:
46     // --------------------------
47     // 19-08: Resulting type plane
48     // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
49     //
50     Type    = (Op >>  8) & 4095;
51     Args[0] = (Op >> 20) & 4095;
52     if (Args[0] == 4095)    // Handle special encoding for 0 operands...
53       Args.resize(0);
54     break;
55   case 2:
56     // bits   Instruction format:
57     // --------------------------
58     // 15-08: Resulting type plane
59     // 23-16: Operand #1
60     // 31-24: Operand #2  
61     //
62     Type    = (Op >>  8) & 255;
63     Args[0] = (Op >> 16) & 255;
64     Args[1] = (Op >> 24) & 255;
65     break;
66   case 3:
67     // bits   Instruction format:
68     // --------------------------
69     // 13-08: Resulting type plane
70     // 19-14: Operand #1
71     // 25-20: Operand #2
72     // 31-26: Operand #3
73     //
74     Type    = (Op >>  8) & 63;
75     Args[0] = (Op >> 14) & 63;
76     Args[1] = (Op >> 20) & 63;
77     Args[2] = (Op >> 26) & 63;
78     break;
79   case 0:
80     Buf -= 4;  // Hrm, try this again...
81     if (read_vbr(Buf, EndBuf, Opcode))
82       throw std::string("Error reading from buffer.");
83     Opcode >>= 2;
84     if (read_vbr(Buf, EndBuf, Type))
85       throw std::string("Error reading from buffer.");
86
87     unsigned NumOperands;
88     if (read_vbr(Buf, EndBuf, NumOperands))
89       throw std::string("Error reading from buffer.");
90     Args.resize(NumOperands);
91
92     if (NumOperands == 0)
93       throw std::string("Zero-argument instruction found; this is invalid.");
94
95     for (unsigned i = 0; i != NumOperands; ++i)
96       if (read_vbr(Buf, EndBuf, Args[i])) 
97         throw std::string("Error reading from buffer");
98     if (align32(Buf, EndBuf))
99       throw std::string("Unaligned bytecode buffer.");
100     break;
101   }
102 }
103
104
105 Instruction *BytecodeParser::ParseInstruction(const unsigned char *&Buf,
106                                               const unsigned char *EndBuf,
107                                               std::vector<unsigned> &Args) {
108   Args.clear();
109   RawInst RI(Buf, EndBuf, Args);
110   const Type *InstTy = getType(RI.Type);
111
112   if (RI.Opcode >= Instruction::BinaryOpsBegin &&
113       RI.Opcode <  Instruction::BinaryOpsEnd  && Args.size() == 2)
114     return BinaryOperator::create((Instruction::BinaryOps)RI.Opcode,
115                                   getValue(RI.Type, Args[0]),
116                                   getValue(RI.Type, Args[1]));
117
118   switch (RI.Opcode) {
119   case Instruction::VarArg:
120     return new VarArgInst(getValue(RI.Type, Args[0]), getType(Args[1]));
121   case Instruction::Cast:
122     return new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
123   case Instruction::PHINode: {
124     if (Args.size() == 0 || (Args.size() & 1))
125       throw std::string("Invalid phi node encountered!\n");
126
127     PHINode *PN = new PHINode(InstTy);
128     PN->op_reserve(Args.size());
129     for (unsigned i = 0, e = Args.size(); i != e; i += 2)
130       PN->addIncoming(getValue(RI.Type, Args[i]), getBasicBlock(Args[i+1]));
131     return PN;
132   }
133
134   case Instruction::Shl:
135   case Instruction::Shr:
136     return new ShiftInst((Instruction::OtherOps)RI.Opcode,
137                          getValue(RI.Type, Args[0]),
138                          getValue(Type::UByteTyID, Args[1]));
139   case Instruction::Ret:
140     if (Args.size() == 0)
141       return new ReturnInst();
142     else if (Args.size() == 1)
143       return new ReturnInst(getValue(RI.Type, Args[0]));
144     break;
145
146   case Instruction::Br:
147     if (Args.size() == 1)
148       return new BranchInst(getBasicBlock(Args[0]));
149     else if (Args.size() == 3)
150       return new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
151                             getValue(Type::BoolTyID , Args[2]));
152     throw std::string("Invalid number of operands for a 'br' instruction!");
153     
154   case Instruction::Switch: {
155     if (Args.size() & 1)
156       throw std::string("Switch statement with odd number of arguments!");
157
158     SwitchInst *I = new SwitchInst(getValue(RI.Type, Args[0]),
159                                    getBasicBlock(Args[1]));
160     for (unsigned i = 2, e = Args.size(); i != e; i += 2)
161       I->addCase(cast<Constant>(getValue(RI.Type, Args[i])),
162                  getBasicBlock(Args[i+1]));
163     return I;
164   }
165
166   case Instruction::Call: {
167     if (Args.size() == 0)
168       throw std::string("Invalid call instruction encountered!");
169
170     Value *F = getValue(RI.Type, Args[0]);
171
172     // Check to make sure we have a pointer to function type
173     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
174     if (PTy == 0) throw std::string("Call to non function pointer value!");
175     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
176     if (FTy == 0) throw std::string("Call to non function pointer value!");
177
178     std::vector<Value *> Params;
179     const FunctionType::ParamTypes &PL = FTy->getParamTypes();
180
181     if (!FTy->isVarArg()) {
182       FunctionType::ParamTypes::const_iterator It = PL.begin();
183
184       for (unsigned i = 1, e = Args.size(); i != e; ++i) {
185         if (It == PL.end()) throw std::string("Invalid call instruction!");
186         Params.push_back(getValue(*It++, Args[i]));
187       }
188       if (It != PL.end()) throw std::string("Invalid call instruction!");
189     } else {
190       // FIXME: Args[1] is currently just a dummy padding field!
191
192       if (Args.size() & 1)  // Must be pairs of type/value
193         throw std::string("Invalid call instruction!");
194
195       for (unsigned i = 2, e = Args.size(); i != e; i += 2)
196         Params.push_back(getValue(Args[i], Args[i+1]));
197     }
198
199     return new CallInst(F, Params);
200   }
201   case Instruction::Invoke: {
202     if (Args.size() < 3) throw std::string("Invalid invoke instruction!");
203     Value *F = getValue(RI.Type, Args[0]);
204
205     // Check to make sure we have a pointer to function type
206     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
207     if (PTy == 0) throw std::string("Invoke to non function pointer value!");
208     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
209     if (FTy == 0) throw std::string("Invoke to non function pointer value!");
210
211     std::vector<Value *> Params;
212     BasicBlock *Normal, *Except;
213
214     const FunctionType::ParamTypes &PL = FTy->getParamTypes();
215
216     if (!FTy->isVarArg()) {
217       Normal = getBasicBlock(Args[1]);
218       Except = getBasicBlock(Args[2]);
219
220       FunctionType::ParamTypes::const_iterator It = PL.begin();
221       for (unsigned i = 3, e = Args.size(); i != e; ++i) {
222         if (It == PL.end()) throw std::string("Invalid invoke instruction!");
223         Params.push_back(getValue(*It++, Args[i]));
224       }
225       if (It != PL.end()) throw std::string("Invalid invoke instruction!");
226     } else {
227       // FIXME: Args[1] is a dummy padding field
228
229       if (Args.size() < 6) throw std::string("Invalid invoke instruction!");
230       if (Args[2] != Type::LabelTyID || Args[4] != Type::LabelTyID)
231         throw std::string("Invalid invoke instruction!");
232           
233       Normal = getBasicBlock(Args[3]);
234       Except = getBasicBlock(Args[5]);
235
236       if (Args.size() & 1)   // Must be pairs of type/value
237         throw std::string("Invalid invoke instruction!");
238
239       for (unsigned i = 6; i < Args.size(); i += 2)
240         Params.push_back(getValue(Args[i], Args[i+1]));
241     }
242
243     return new InvokeInst(F, Normal, Except, Params);
244   }
245   case Instruction::Malloc:
246     if (Args.size() > 2) throw std::string("Invalid malloc instruction!");
247     if (!isa<PointerType>(InstTy))
248       throw std::string("Invalid malloc instruction!");
249
250     return new MallocInst(cast<PointerType>(InstTy)->getElementType(),
251                           Args.size() ? getValue(Type::UIntTyID,
252                                                       Args[0]) : 0);
253
254   case Instruction::Alloca:
255     if (Args.size() > 2) throw std::string("Invalid alloca instruction!");
256     if (!isa<PointerType>(InstTy))
257       throw std::string("Invalid alloca instruction!");
258
259     return new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
260                           Args.size() ? getValue(Type::UIntTyID,
261                                                       Args[0]) : 0);
262   case Instruction::Free:
263     if (!isa<PointerType>(InstTy))
264       throw std::string("Invalid free instruction!");
265     return new FreeInst(getValue(RI.Type, Args[0]));
266
267   case Instruction::GetElementPtr: {
268     if (Args.size() == 0 || !isa<PointerType>(InstTy))
269       throw std::string("Invalid getelementptr instruction!");
270
271     std::vector<Value*> Idx;
272
273     const Type *NextTy = InstTy;
274     for (unsigned i = 1, e = Args.size(); i != e; ++i) {
275       const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
276       if (!TopTy) throw std::string("Invalid getelementptr instruction!"); 
277       Idx.push_back(getValue(TopTy->getIndexType(), Args[i]));
278       NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
279     }
280
281     return new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
282   }
283
284   case 62:   // volatile load
285   case Instruction::Load:
286     if (Args.size() != 1 || !isa<PointerType>(InstTy))
287       throw std::string("Invalid load instruction!");
288     return new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
289
290   case 63:   // volatile store 
291   case Instruction::Store: {
292     if (!isa<PointerType>(InstTy) || Args.size() != 2)
293       throw std::string("Invalid store instruction!");
294
295     Value *Ptr = getValue(RI.Type, Args[1]);
296     const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
297     return new StoreInst(getValue(ValTy, Args[0]), Ptr, RI.Opcode == 63);
298   }
299   case Instruction::Unwind:
300     if (Args.size() != 0) throw std::string("Invalid unwind instruction!");
301     return new UnwindInst();
302   }  // end switch(RI.Opcode) 
303
304   std::cerr << "Unrecognized instruction! " << RI.Opcode 
305             << " ADDR = 0x" << (void*)Buf << "\n";
306   throw std::string("Unrecognized instruction!");
307 }