0d050c93329c1e57cd0d46bb6da3b4344046258c
[oota-llvm.git] / lib / Target / X86 / InstSelectSimple.cpp
1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
2 //
3 // This file defines a simple peephole instruction selector for the x86 platform
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "X86.h"
8 #include "X86InstrInfo.h"
9 #include "X86InstrBuilder.h"
10 #include "llvm/Function.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iOperators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/iMemory.h"
16 #include "llvm/Type.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Pass.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/InstVisitor.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include <map>
26
27 using namespace MOTy;  // Get Use, Def, UseAndDef
28
29
30 /// BMI - A special BuildMI variant that takes an iterator to insert the
31 /// instruction at as well as a basic block.
32 /// this is the version for when you have a destination register in mind.
33 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
34                                       MachineBasicBlock::iterator &I,
35                                       MachineOpCode Opcode,
36                                       unsigned NumOperands,
37                                       unsigned DestReg) {
38   assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
39   MachineInstr *MI = new MachineInstr(Opcode, NumOperands+1, true, true);
40   I = ++MBB->insert(I, MI);
41   return MachineInstrBuilder(MI).addReg(DestReg, MOTy::Def);
42 }
43
44 /// BMI - A special BuildMI variant that takes an iterator to insert the
45 /// instruction at as well as a basic block.
46 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
47                                       MachineBasicBlock::iterator &I,
48                                       MachineOpCode Opcode,
49                                       unsigned NumOperands) {
50   assert(I > MBB->begin() && I <= MBB->end() && "Bad iterator!");
51   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
52   I = ++MBB->insert(I, MI);
53   return MachineInstrBuilder(MI);
54 }
55
56
57 namespace {
58   struct ISel : public FunctionPass, InstVisitor<ISel> {
59     TargetMachine &TM;
60     MachineFunction *F;                    // The function we are compiling into
61     MachineBasicBlock *BB;                 // The current MBB we are compiling
62
63     unsigned CurReg;
64     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
65
66     // MBBMap - Mapping between LLVM BB -> Machine BB
67     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
68
69     ISel(TargetMachine &tm)
70       : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
71
72     /// runOnFunction - Top level implementation of instruction selection for
73     /// the entire function.
74     ///
75     bool runOnFunction(Function &Fn) {
76       F = &MachineFunction::construct(&Fn, TM);
77
78       for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
79         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
80
81       // Instruction select everything except PHI nodes
82       visit(Fn);
83
84       // Select the PHI nodes
85       SelectPHINodes();
86
87       RegMap.clear();
88       MBBMap.clear();
89       CurReg = MRegisterInfo::FirstVirtualRegister;
90       F = 0;
91       return false;  // We never modify the LLVM itself.
92     }
93
94     virtual const char *getPassName() const {
95       return "X86 Simple Instruction Selection";
96     }
97
98     /// visitBasicBlock - This method is called when we are visiting a new basic
99     /// block.  This simply creates a new MachineBasicBlock to emit code into
100     /// and adds it to the current MachineFunction.  Subsequent visit* for
101     /// instructions will be invoked for all instructions in the basic block.
102     ///
103     void visitBasicBlock(BasicBlock &LLVM_BB) {
104       BB = MBBMap[&LLVM_BB];
105     }
106
107
108     /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
109     /// because we have to generate our sources into the source basic blocks,
110     /// not the current one.
111     ///
112     void SelectPHINodes();
113
114     // Visitation methods for various instructions.  These methods simply emit
115     // fixed X86 code for each instruction.
116     //
117
118     // Control flow operators
119     void visitReturnInst(ReturnInst &RI);
120     void visitBranchInst(BranchInst &BI);
121     void visitCallInst(CallInst &I);
122
123     // Arithmetic operators
124     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
125     void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
126     void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
127     void doMultiply(unsigned destReg, const Type *resultType,
128                     unsigned op0Reg, unsigned op1Reg,
129                     MachineBasicBlock *MBB,
130                     MachineBasicBlock::iterator &MBBI);
131     void visitMul(BinaryOperator &B);
132
133     void visitDiv(BinaryOperator &B) { visitDivRem(B); }
134     void visitRem(BinaryOperator &B) { visitDivRem(B); }
135     void visitDivRem(BinaryOperator &B);
136
137     // Bitwise operators
138     void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
139     void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
140     void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
141
142     // Binary comparison operators
143     void visitSetCCInst(SetCondInst &I, unsigned OpNum);
144     void visitSetEQ(SetCondInst &I) { visitSetCCInst(I, 0); }
145     void visitSetNE(SetCondInst &I) { visitSetCCInst(I, 1); }
146     void visitSetLT(SetCondInst &I) { visitSetCCInst(I, 2); }
147     void visitSetGT(SetCondInst &I) { visitSetCCInst(I, 3); }
148     void visitSetLE(SetCondInst &I) { visitSetCCInst(I, 4); }
149     void visitSetGE(SetCondInst &I) { visitSetCCInst(I, 5); }
150
151     // Memory Instructions
152     void visitLoadInst(LoadInst &I);
153     void visitStoreInst(StoreInst &I);
154     void visitGetElementPtrInst(GetElementPtrInst &I);
155     void visitMallocInst(MallocInst &I);
156     void visitFreeInst(FreeInst &I);
157     void visitAllocaInst(AllocaInst &I);
158     
159     // Other operators
160     void visitShiftInst(ShiftInst &I);
161     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
162     void visitCastInst(CastInst &I);
163
164     void visitInstruction(Instruction &I) {
165       std::cerr << "Cannot instruction select: " << I;
166       abort();
167     }
168
169     /// promote32 - Make a value 32-bits wide, and put it somewhere.
170     void promote32 (const unsigned targetReg, Value *v);
171     
172     // emitGEPOperation - Common code shared between visitGetElementPtrInst and
173     // constant expression GEP support.
174     //
175     void emitGEPOperation(MachineBasicBlock *BB, MachineBasicBlock::iterator&IP,
176                           Value *Src, User::op_iterator IdxBegin,
177                           User::op_iterator IdxEnd, unsigned TargetReg);
178
179     /// copyConstantToRegister - Output the instructions required to put the
180     /// specified constant into the specified register.
181     ///
182     void copyConstantToRegister(Constant *C, unsigned Reg,
183                                 MachineBasicBlock *MBB,
184                                 MachineBasicBlock::iterator &MBBI);
185
186     /// makeAnotherReg - This method returns the next register number
187     /// we haven't yet used.
188     unsigned makeAnotherReg(const Type *Ty) {
189       // Add the mapping of regnumber => reg class to MachineFunction
190       F->addRegMap(CurReg, TM.getRegisterInfo()->getRegClassForType(Ty));
191       return CurReg++;
192     }
193
194     /// getReg - This method turns an LLVM value into a register number.  This
195     /// is guaranteed to produce the same register number for a particular value
196     /// every time it is queried.
197     ///
198     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
199     unsigned getReg(Value *V) {
200       // Just append to the end of the current bb.
201       MachineBasicBlock::iterator It = BB->end();
202       return getReg(V, BB, It);
203     }
204     unsigned getReg(Value *V, MachineBasicBlock *MBB,
205                     MachineBasicBlock::iterator &IPt) {
206       unsigned &Reg = RegMap[V];
207       if (Reg == 0) {
208         Reg = makeAnotherReg(V->getType());
209         RegMap[V] = Reg;
210       }
211
212       // If this operand is a constant, emit the code to copy the constant into
213       // the register here...
214       //
215       if (Constant *C = dyn_cast<Constant>(V)) {
216         copyConstantToRegister(C, Reg, MBB, IPt);
217       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
218         // Move the address of the global into the register
219         BMI(MBB, IPt, X86::MOVir32, 1, Reg).addReg(GV);
220       } else if (Argument *A = dyn_cast<Argument>(V)) {
221         // Find the position of the argument in the argument list.
222         const Function *f = F->getFunction ();
223         // The function's arguments look like this:
224         // [EBP]     -- copy of old EBP
225         // [EBP + 4] -- return address
226         // [EBP + 8] -- first argument (leftmost lexically)
227         // So we want to start with counter = 2.
228         int counter = 2, argPos = -1;
229         for (Function::const_aiterator ai = f->abegin (), ae = f->aend ();
230              ai != ae; ++ai) {
231           if (&(*ai) == A) {
232             argPos = counter;
233             break; // Only need to find it once. ;-)
234           }
235           ++counter;
236         }
237         assert (argPos != -1
238                 && "Argument not found in current function's argument list");
239         // Load it out of the stack frame at EBP + 4*argPos.
240         addRegOffset(BMI(MBB, IPt, X86::MOVmr32, 4, Reg), X86::EBP, 4*argPos);
241       }
242
243       return Reg;
244     }
245   };
246 }
247
248 /// TypeClass - Used by the X86 backend to group LLVM types by their basic X86
249 /// Representation.
250 ///
251 enum TypeClass {
252   cByte, cShort, cInt, cLong, cFloat, cDouble
253 };
254
255 /// getClass - Turn a primitive type into a "class" number which is based on the
256 /// size of the type, and whether or not it is floating point.
257 ///
258 static inline TypeClass getClass(const Type *Ty) {
259   switch (Ty->getPrimitiveID()) {
260   case Type::SByteTyID:
261   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
262   case Type::ShortTyID:
263   case Type::UShortTyID:  return cShort;     // Short operands are class #1
264   case Type::IntTyID:
265   case Type::UIntTyID:
266   case Type::PointerTyID: return cInt;       // Int's and pointers are class #2
267
268   case Type::LongTyID:
269   case Type::ULongTyID:   //return cLong;      // Longs are class #3
270     return cInt;          // FIXME: LONGS ARE TREATED AS INTS!
271
272   case Type::FloatTyID:   return cFloat;     // Float is class #4
273   case Type::DoubleTyID:  return cDouble;    // Doubles are class #5
274   default:
275     assert(0 && "Invalid type to getClass!");
276     return cByte;  // not reached
277   }
278 }
279
280 // getClassB - Just like getClass, but treat boolean values as bytes.
281 static inline TypeClass getClassB(const Type *Ty) {
282   if (Ty == Type::BoolTy) return cByte;
283   return getClass(Ty);
284 }
285
286
287 /// copyConstantToRegister - Output the instructions required to put the
288 /// specified constant into the specified register.
289 ///
290 void ISel::copyConstantToRegister(Constant *C, unsigned R,
291                                   MachineBasicBlock *MBB,
292                                   MachineBasicBlock::iterator &IP) {
293   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
294     if (CE->getOpcode() == Instruction::GetElementPtr) {
295       emitGEPOperation(MBB, IP, CE->getOperand(0),
296                        CE->op_begin()+1, CE->op_end(), R);
297       return;
298     }
299
300     std::cerr << "Offending expr: " << C << "\n";
301     assert (0 && "Constant expressions not yet handled!\n");
302   }
303
304   if (C->getType()->isIntegral()) {
305     unsigned Class = getClassB(C->getType());
306     assert(Class != 3 && "Type not handled yet!");
307
308     static const unsigned IntegralOpcodeTab[] = {
309       X86::MOVir8, X86::MOVir16, X86::MOVir32
310     };
311
312     if (C->getType() == Type::BoolTy) {
313       BMI(MBB, IP, X86::MOVir8, 1, R).addZImm(C == ConstantBool::True);
314     } else if (C->getType()->isSigned()) {
315       ConstantSInt *CSI = cast<ConstantSInt>(C);
316       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
317     } else {
318       ConstantUInt *CUI = cast<ConstantUInt>(C);
319       BMI(MBB, IP, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
320     }
321   } else if (isa<ConstantPointerNull>(C)) {
322     // Copy zero (null pointer) to the register.
323     BMI(MBB, IP, X86::MOVir32, 1, R).addZImm(0);
324   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
325     unsigned SrcReg = getReg(CPR->getValue(), MBB, IP);
326     BMI(MBB, IP, X86::MOVrr32, 1, R).addReg(SrcReg);
327   } else {
328     std::cerr << "Offending constant: " << C << "\n";
329     assert(0 && "Type not handled yet!");
330   }
331 }
332
333 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
334 /// because we have to generate our sources into the source basic blocks, not
335 /// the current one.
336 ///
337 void ISel::SelectPHINodes() {
338   const Function &LF = *F->getFunction();  // The LLVM function...
339   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
340     const BasicBlock *BB = I;
341     MachineBasicBlock *MBB = MBBMap[I];
342
343     // Loop over all of the PHI nodes in the LLVM basic block...
344     unsigned NumPHIs = 0;
345     for (BasicBlock::const_iterator I = BB->begin();
346          PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
347       // Create a new machine instr PHI node, and insert it.
348       MachineInstr *MI = BuildMI(X86::PHI, PN->getNumOperands(), getReg(*PN));
349       MBB->insert(MBB->begin()+NumPHIs++, MI); // Insert it at the top of the BB
350
351       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
352         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
353
354         // Get the incoming value into a virtual register.  If it is not already
355         // available in a virtual register, insert the computation code into
356         // PredMBB
357         //
358
359         MachineBasicBlock::iterator PI = PredMBB->begin();
360         while ((*PI)->getOpcode() == X86::PHI) ++PI;
361         
362         MI->addRegOperand(getReg(PN->getIncomingValue(i), PredMBB, PI));
363         MI->addMachineBasicBlockOperand(PredMBB);
364       }
365     }
366   }
367 }
368
369
370
371 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
372 /// register, then move it to wherever the result should be. 
373 /// We handle FP setcc instructions by pushing them, doing a
374 /// compare-and-pop-twice, and then copying the concodes to the main
375 /// processor's concodes (I didn't make this up, it's in the Intel manual)
376 ///
377 void ISel::visitSetCCInst(SetCondInst &I, unsigned OpNum) {
378   // The arguments are already supposed to be of the same type.
379   const Type *CompTy = I.getOperand(0)->getType();
380   unsigned reg1 = getReg(I.getOperand(0));
381   unsigned reg2 = getReg(I.getOperand(1));
382
383   unsigned Class = getClass(CompTy);
384   switch (Class) {
385     // Emit: cmp <var1>, <var2> (do the comparison).  We can
386     // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
387     // 32-bit.
388   case cByte:
389     BuildMI (BB, X86::CMPrr8, 2).addReg (reg1).addReg (reg2);
390     break;
391   case cShort:
392     BuildMI (BB, X86::CMPrr16, 2).addReg (reg1).addReg (reg2);
393     break;
394   case cInt:
395     BuildMI (BB, X86::CMPrr32, 2).addReg (reg1).addReg (reg2);
396     break;
397
398     // Push the variables on the stack with fldl opcodes.
399     // FIXME: assuming var1, var2 are in memory, if not, spill to
400     // stack first
401   case cFloat:  // Floats
402     BuildMI (BB, X86::FLDr32, 1).addReg (reg1);
403     BuildMI (BB, X86::FLDr32, 1).addReg (reg2);
404     break;
405   case cDouble:  // Doubles
406     BuildMI (BB, X86::FLDr64, 1).addReg (reg1);
407     BuildMI (BB, X86::FLDr64, 1).addReg (reg2);
408     break;
409   case cLong:
410   default:
411     visitInstruction(I);
412   }
413
414   if (CompTy->isFloatingPoint()) {
415     // (Non-trapping) compare and pop twice.
416     BuildMI (BB, X86::FUCOMPP, 0);
417     // Move fp status word (concodes) to ax.
418     BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
419     // Load real concodes from ax.
420     BuildMI (BB, X86::SAHF, 1).addReg(X86::AH);
421   }
422
423   // Emit setOp instruction (extract concode; clobbers ax),
424   // using the following mapping:
425   // LLVM  -> X86 signed  X86 unsigned
426   // -----    -----       -----
427   // seteq -> sete        sete
428   // setne -> setne       setne
429   // setlt -> setl        setb
430   // setgt -> setg        seta
431   // setle -> setle       setbe
432   // setge -> setge       setae
433
434   static const unsigned OpcodeTab[2][6] = {
435     {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
436     {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
437   };
438
439   BuildMI(BB, OpcodeTab[CompTy->isSigned()][OpNum], 0, X86::AL);
440   
441   // Put it in the result using a move.
442   BuildMI (BB, X86::MOVrr8, 1, getReg(I)).addReg(X86::AL);
443 }
444
445 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
446 /// operand, in the specified target register.
447 void
448 ISel::promote32 (unsigned targetReg, Value *v)
449 {
450   unsigned vReg = getReg (v);
451   unsigned Class = getClass (v->getType ());
452   bool isUnsigned = v->getType ()->isUnsigned ();
453   assert (((Class == cByte) || (Class == cShort) || (Class == cInt))
454           && "Unpromotable operand class in promote32");
455   switch (Class)
456     {
457     case cByte:
458       // Extend value into target register (8->32)
459       if (isUnsigned)
460         BuildMI (BB, X86::MOVZXr32r8, 1, targetReg).addReg (vReg);
461       else
462         BuildMI (BB, X86::MOVSXr32r8, 1, targetReg).addReg (vReg);
463       break;
464     case cShort:
465       // Extend value into target register (16->32)
466       if (isUnsigned)
467         BuildMI (BB, X86::MOVZXr32r16, 1, targetReg).addReg (vReg);
468       else
469         BuildMI (BB, X86::MOVSXr32r16, 1, targetReg).addReg (vReg);
470       break;
471     case cInt:
472       // Move value into target register (32->32)
473       BuildMI (BB, X86::MOVrr32, 1, targetReg).addReg (vReg);
474       break;
475     }
476 }
477
478 /// 'ret' instruction - Here we are interested in meeting the x86 ABI.  As such,
479 /// we have the following possibilities:
480 ///
481 ///   ret void: No return value, simply emit a 'ret' instruction
482 ///   ret sbyte, ubyte : Extend value into EAX and return
483 ///   ret short, ushort: Extend value into EAX and return
484 ///   ret int, uint    : Move value into EAX and return
485 ///   ret pointer      : Move value into EAX and return
486 ///   ret long, ulong  : Move value into EAX/EDX and return
487 ///   ret float/double : Top of FP stack
488 ///
489 void
490 ISel::visitReturnInst (ReturnInst &I)
491 {
492   if (I.getNumOperands () == 0)
493     {
494       // Emit a 'ret' instruction
495       BuildMI (BB, X86::RET, 0);
496       return;
497     }
498   Value *rv = I.getOperand (0);
499   unsigned Class = getClass (rv->getType ());
500   switch (Class)
501     {
502       // integral return values: extend or move into EAX and return. 
503     case cByte:
504     case cShort:
505     case cInt:
506       promote32 (X86::EAX, rv);
507       break;
508       // ret float/double: top of FP stack
509       // FLD <val>
510     case cFloat:                // Floats
511       BuildMI (BB, X86::FLDr32, 1).addReg (getReg (rv));
512       break;
513     case cDouble:               // Doubles
514       BuildMI (BB, X86::FLDr64, 1).addReg (getReg (rv));
515       break;
516     case cLong:
517       // ret long: use EAX(least significant 32 bits)/EDX (most
518       // significant 32)...uh, I think so Brain, but how do i call
519       // up the two parts of the value from inside this mouse
520       // cage? *zort*
521     default:
522       visitInstruction (I);
523     }
524   // Emit a 'ret' instruction
525   BuildMI (BB, X86::RET, 0);
526 }
527
528 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
529 /// that since code layout is frozen at this point, that if we are trying to
530 /// jump to a block that is the immediate successor of the current block, we can
531 /// just make a fall-through. (but we don't currently).
532 ///
533 void
534 ISel::visitBranchInst (BranchInst & BI)
535 {
536   if (BI.isConditional ())
537     {
538       BasicBlock *ifTrue = BI.getSuccessor (0);
539       BasicBlock *ifFalse = BI.getSuccessor (1); // this is really unobvious 
540
541       // simplest thing I can think of: compare condition with zero,
542       // followed by jump-if-equal to ifFalse, and jump-if-nonequal to
543       // ifTrue
544       unsigned int condReg = getReg (BI.getCondition ());
545       BuildMI (BB, X86::CMPri8, 2).addReg (condReg).addZImm (0);
546       BuildMI (BB, X86::JNE, 1).addPCDisp (BI.getSuccessor (0));
547       BuildMI (BB, X86::JE, 1).addPCDisp (BI.getSuccessor (1));
548     }
549   else // unconditional branch
550     {
551       BuildMI (BB, X86::JMP, 1).addPCDisp (BI.getSuccessor (0));
552     }
553 }
554
555 /// visitCallInst - Push args on stack and do a procedure call instruction.
556 void
557 ISel::visitCallInst (CallInst & CI)
558 {
559   // keep a counter of how many bytes we pushed on the stack
560   unsigned bytesPushed = 0;
561
562   // Push the arguments on the stack in reverse order, as specified by
563   // the ABI.
564   for (unsigned i = CI.getNumOperands()-1; i >= 1; --i)
565     {
566       Value *v = CI.getOperand (i);
567       switch (getClass (v->getType ()))
568         {
569         case cByte:
570         case cShort:
571           // Promote V to 32 bits wide, and move the result into EAX,
572           // then push EAX.
573           promote32 (X86::EAX, v);
574           BuildMI (BB, X86::PUSHr32, 1).addReg (X86::EAX);
575           bytesPushed += 4;
576           break;
577         case cInt:
578         case cFloat: {
579           unsigned Reg = getReg(v);
580           BuildMI (BB, X86::PUSHr32, 1).addReg(Reg);
581           bytesPushed += 4;
582           break;
583         }
584         default:
585           // FIXME: long/ulong/double args not handled.
586           visitInstruction (CI);
587           break;
588         }
589     }
590
591   if (Function *F = CI.getCalledFunction()) {
592     // Emit a CALL instruction with PC-relative displacement.
593     BuildMI(BB, X86::CALLpcrel32, 1).addPCDisp(F);
594   } else {
595     unsigned Reg = getReg(CI.getCalledValue());
596     BuildMI(BB, X86::CALLr32, 1).addReg(Reg);
597   }
598
599   // Adjust the stack by `bytesPushed' amount if non-zero
600   if (bytesPushed > 0)
601     BuildMI (BB, X86::ADDri32, 2).addReg(X86::ESP).addZImm(bytesPushed);
602
603   // If there is a return value, scavenge the result from the location the call
604   // leaves it in...
605   //
606   if (CI.getType() != Type::VoidTy) {
607     unsigned resultTypeClass = getClass (CI.getType ());
608     switch (resultTypeClass) {
609     case cByte:
610     case cShort:
611     case cInt: {
612       // Integral results are in %eax, or the appropriate portion
613       // thereof.
614       static const unsigned regRegMove[] = {
615         X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
616       };
617       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
618       BuildMI (BB, regRegMove[resultTypeClass], 1,
619                getReg (CI)).addReg (AReg[resultTypeClass]);
620       break;
621     }
622     case cFloat:
623       // Floating-point return values live in %st(0) (i.e., the top of
624       // the FP stack.) The general way to approach this is to do a
625       // FSTP to save the top of the FP stack on the real stack, then
626       // do a MOV to load the top of the real stack into the target
627       // register.
628       visitInstruction (CI); // FIXME: add the right args for the calls below
629       // BuildMI (BB, X86::FSTPm32, 0);
630       // BuildMI (BB, X86::MOVmr32, 0);
631       break;
632     default:
633       std::cerr << "Cannot get return value for call of type '"
634                 << *CI.getType() << "'\n";
635       visitInstruction(CI);
636     }
637   }
638 }
639
640 /// visitSimpleBinary - Implement simple binary operators for integral types...
641 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
642 /// 4 for Xor.
643 ///
644 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
645   if (B.getType() == Type::BoolTy)  // FIXME: Handle bools for logicals
646     visitInstruction(B);
647
648   unsigned Class = getClass(B.getType());
649   if (Class > 2)  // FIXME: Handle longs
650     visitInstruction(B);
651
652   static const unsigned OpcodeTab[][4] = {
653     // Arithmetic operators
654     { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 },  // ADD
655     { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 },  // SUB
656
657     // Bitwise operators
658     { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 },  // AND
659     { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 },  // OR
660     { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 },  // XOR
661   };
662   
663   unsigned Opcode = OpcodeTab[OperatorClass][Class];
664   unsigned Op0r = getReg(B.getOperand(0));
665   unsigned Op1r = getReg(B.getOperand(1));
666   BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
667 }
668
669 /// doMultiply - Emit appropriate instructions to multiply together
670 /// the registers op0Reg and op1Reg, and put the result in destReg.
671 /// The type of the result should be given as resultType.
672 void
673 ISel::doMultiply(unsigned destReg, const Type *resultType,
674                  unsigned op0Reg, unsigned op1Reg,
675                  MachineBasicBlock *MBB, MachineBasicBlock::iterator &MBBI)
676 {
677   unsigned Class = getClass (resultType);
678
679   // FIXME:
680   assert (Class <= 2 && "Someday, we will learn how to multiply"
681           "longs and floating-point numbers. This is not that day.");
682  
683   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
684   static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
685   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
686   unsigned Reg     = Regs[Class];
687
688   // Emit a MOV to put the first operand into the appropriately-sized
689   // subreg of EAX.
690   BMI(MBB, MBBI, MovOpcode[Class], 1, Reg).addReg (op0Reg);
691   
692   // Emit the appropriate multiply instruction.
693   BMI(MBB, MBBI, MulOpcode[Class], 1).addReg (op1Reg);
694
695   // Emit another MOV to put the result into the destination register.
696   BMI(MBB, MBBI, MovOpcode[Class], 1, destReg).addReg (Reg);
697 }
698
699 /// visitMul - Multiplies are not simple binary operators because they must deal
700 /// with the EAX register explicitly.
701 ///
702 void ISel::visitMul(BinaryOperator &I) {
703   unsigned DestReg = getReg(I);
704   unsigned Op0Reg  = getReg(I.getOperand(0));
705   unsigned Op1Reg  = getReg(I.getOperand(1));
706   MachineBasicBlock::iterator MBBI = BB->end();
707   doMultiply(DestReg, I.getType(), Op0Reg, Op1Reg, BB, MBBI);
708 }
709
710
711 /// visitDivRem - Handle division and remainder instructions... these
712 /// instruction both require the same instructions to be generated, they just
713 /// select the result from a different register.  Note that both of these
714 /// instructions work differently for signed and unsigned operands.
715 ///
716 void ISel::visitDivRem(BinaryOperator &I) {
717   unsigned Class = getClass(I.getType());
718   if (Class > 2)  // FIXME: Handle longs
719     visitInstruction(I);
720
721   static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
722   static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
723   static const unsigned ExtOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
724   static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
725   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
726
727   static const unsigned DivOpcode[][4] = {
728     { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 },  // Unsigned division
729     { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 },  // Signed division
730   };
731
732   bool isSigned   = I.getType()->isSigned();
733   unsigned Reg    = Regs[Class];
734   unsigned ExtReg = ExtRegs[Class];
735   unsigned Op0Reg = getReg(I.getOperand(0));
736   unsigned Op1Reg = getReg(I.getOperand(1));
737
738   // Put the first operand into one of the A registers...
739   BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
740
741   if (isSigned) {
742     // Emit a sign extension instruction...
743     BuildMI(BB, ExtOpcode[Class], 0);
744   } else {
745     // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
746     BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
747   }
748
749   // Emit the appropriate divide or remainder instruction...
750   BuildMI(BB, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
751
752   // Figure out which register we want to pick the result out of...
753   unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
754   
755   // Put the result into the destination register...
756   BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
757 }
758
759
760 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
761 /// for constant immediate shift values, and for constant immediate
762 /// shift values equal to 1. Even the general case is sort of special,
763 /// because the shift amount has to be in CL, not just any old register.
764 ///
765 void ISel::visitShiftInst (ShiftInst &I) {
766   unsigned Op0r = getReg (I.getOperand(0));
767   unsigned DestReg = getReg(I);
768   bool isLeftShift = I.getOpcode() == Instruction::Shl;
769   bool isOperandSigned = I.getType()->isUnsigned();
770   unsigned OperandClass = getClass(I.getType());
771
772   if (OperandClass > 2)
773     visitInstruction(I); // Can't handle longs yet!
774
775   if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
776     {
777       // The shift amount is constant, guaranteed to be a ubyte. Get its value.
778       assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
779       unsigned char shAmt = CUI->getValue();
780
781       static const unsigned ConstantOperand[][4] = {
782         { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 },  // SHR
783         { X86::SARir8, X86::SARir16, X86::SARir32, 0 },  // SAR
784         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SHL
785         { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 },  // SAL = SHL
786       };
787
788       const unsigned *OpTab = // Figure out the operand table to use
789         ConstantOperand[isLeftShift*2+isOperandSigned];
790
791       // Emit: <insn> reg, shamt  (shift-by-immediate opcode "ir" form.)
792       BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
793     }
794   else
795     {
796       // The shift amount is non-constant.
797       //
798       // In fact, you can only shift with a variable shift amount if
799       // that amount is already in the CL register, so we have to put it
800       // there first.
801       //
802
803       // Emit: move cl, shiftAmount (put the shift amount in CL.)
804       BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
805
806       // This is a shift right (SHR).
807       static const unsigned NonConstantOperand[][4] = {
808         { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 },  // SHR
809         { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 },  // SAR
810         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SHL
811         { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 },  // SAL = SHL
812       };
813
814       const unsigned *OpTab = // Figure out the operand table to use
815         NonConstantOperand[isLeftShift*2+isOperandSigned];
816
817       BuildMI(BB, OpTab[OperandClass], 1, DestReg).addReg(Op0r);
818     }
819 }
820
821
822 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
823 /// instruction.
824 ///
825 void ISel::visitLoadInst(LoadInst &I) {
826   unsigned Class = getClass(I.getType());
827   if (Class > 2)  // FIXME: Handle longs and others...
828     visitInstruction(I);
829
830   static const unsigned Opcode[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
831
832   unsigned AddressReg = getReg(I.getOperand(0));
833   addDirectMem(BuildMI(BB, Opcode[Class], 4, getReg(I)), AddressReg);
834 }
835
836
837 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
838 /// instruction.
839 ///
840 void ISel::visitStoreInst(StoreInst &I) {
841   unsigned Class = getClass(I.getOperand(0)->getType());
842   if (Class > 2)  // FIXME: Handle longs and others...
843     visitInstruction(I);
844
845   static const unsigned Opcode[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
846
847   unsigned ValReg = getReg(I.getOperand(0));
848   unsigned AddressReg = getReg(I.getOperand(1));
849   addDirectMem(BuildMI(BB, Opcode[Class], 1+4), AddressReg).addReg(ValReg);
850 }
851
852
853 /// visitCastInst - Here we have various kinds of copying with or without
854 /// sign extension going on.
855 void
856 ISel::visitCastInst (CastInst &CI)
857 {
858   const Type *targetType = CI.getType ();
859   Value *operand = CI.getOperand (0);
860   unsigned int operandReg = getReg (operand);
861   const Type *sourceType = operand->getType ();
862   unsigned int destReg = getReg (CI);
863   //
864   // Currently we handle:
865   //
866   // 1) cast * to bool
867   //
868   // 2) cast {sbyte, ubyte} to {sbyte, ubyte}
869   //    cast {short, ushort} to {ushort, short}
870   //    cast {int, uint, ptr} to {int, uint, ptr}
871   //
872   // 3) cast {sbyte, ubyte} to {ushort, short}
873   //    cast {sbyte, ubyte} to {int, uint, ptr}
874   //    cast {short, ushort} to {int, uint, ptr}
875   //
876   // 4) cast {int, uint, ptr} to {short, ushort}
877   //    cast {int, uint, ptr} to {sbyte, ubyte}
878   //    cast {short, ushort} to {sbyte, ubyte}
879
880   // 1) Implement casts to bool by using compare on the operand followed
881   // by set if not zero on the result.
882   if (targetType == Type::BoolTy)
883     {
884       BuildMI (BB, X86::CMPri8, 2).addReg (operandReg).addZImm (0);
885       BuildMI (BB, X86::SETNEr, 1, destReg);
886       return;
887     }
888
889   // 2) Implement casts between values of the same type class (as determined
890   // by getClass) by using a register-to-register move.
891   unsigned srcClass = getClassB (sourceType);
892   unsigned targClass = getClass (targetType);
893   static const unsigned regRegMove[] = {
894     X86::MOVrr8, X86::MOVrr16, X86::MOVrr32
895   };
896   if ((srcClass < cLong) && (targClass < cLong) && (srcClass == targClass))
897     {
898       BuildMI (BB, regRegMove[srcClass], 1, destReg).addReg (operandReg);
899       return;
900     }
901   // 3) Handle cast of SMALLER int to LARGER int using a move with sign
902   // extension or zero extension, depending on whether the source type
903   // was signed.
904   if ((srcClass < cLong) && (targClass < cLong) && (srcClass < targClass))
905     {
906       static const unsigned ops[] = {
907         X86::MOVSXr16r8, X86::MOVSXr32r8, X86::MOVSXr32r16,
908         X86::MOVZXr16r8, X86::MOVZXr32r8, X86::MOVZXr32r16
909       };
910       unsigned srcSigned = sourceType->isSigned ();
911       BuildMI (BB, ops[3 * srcSigned + srcClass + targClass - 1], 1,
912                destReg).addReg (operandReg);
913       return;
914     }
915   // 4) Handle cast of LARGER int to SMALLER int using a move to EAX
916   // followed by a move out of AX or AL.
917   if ((srcClass < cLong) && (targClass < cLong) && (srcClass > targClass))
918     {
919       static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX };
920       BuildMI (BB, regRegMove[srcClass], 1,
921                AReg[srcClass]).addReg (operandReg);
922       BuildMI (BB, regRegMove[targClass], 1, destReg).addReg (AReg[srcClass]);
923       return;
924     }
925   // Anything we haven't handled already, we can't (yet) handle at all.
926   //
927   // FP to integral casts can be handled with FISTP to store onto the
928   // stack while converting to integer, followed by a MOV to load from
929   // the stack into the result register. Integral to FP casts can be
930   // handled with MOV to store onto the stack, followed by a FILD to
931   // load from the stack while converting to FP. For the moment, I
932   // can't quite get straight in my head how to borrow myself some
933   // stack space and write on it. Otherwise, this would be trivial.
934   visitInstruction (CI);
935 }
936
937 /// visitGetElementPtrInst - I don't know, most programs don't have
938 /// getelementptr instructions, right? That means we can put off
939 /// implementing this, right? Right. This method emits machine
940 /// instructions to perform type-safe pointer arithmetic. I am
941 /// guessing this could be cleaned up somewhat to use fewer temporary
942 /// registers.
943 void
944 ISel::visitGetElementPtrInst (GetElementPtrInst &I)
945 {
946   unsigned outputReg = getReg (I);
947   MachineBasicBlock::iterator MI = BB->end();
948   emitGEPOperation(BB, MI, I.getOperand(0),
949                    I.op_begin()+1, I.op_end(), outputReg);
950 }
951
952 void ISel::emitGEPOperation(MachineBasicBlock *MBB,
953                             MachineBasicBlock::iterator &IP,
954                             Value *Src, User::op_iterator IdxBegin,
955                             User::op_iterator IdxEnd, unsigned TargetReg) {
956   const TargetData &TD = TM.getTargetData();
957   const Type *Ty = Src->getType();
958   unsigned basePtrReg = getReg(Src, MBB, IP);
959
960   // GEPs have zero or more indices; we must perform a struct access
961   // or array access for each one.
962   for (GetElementPtrInst::op_iterator oi = IdxBegin,
963          oe = IdxEnd; oi != oe; ++oi) {
964     Value *idx = *oi;
965     unsigned nextBasePtrReg = makeAnotherReg(Type::UIntTy);
966     if (const StructType *StTy = dyn_cast <StructType> (Ty)) {
967       // It's a struct access.  idx is the index into the structure,
968       // which names the field. This index must have ubyte type.
969       const ConstantUInt *CUI = cast <ConstantUInt> (idx);
970       assert (CUI->getType () == Type::UByteTy
971               && "Funny-looking structure index in GEP");
972       // Use the TargetData structure to pick out what the layout of
973       // the structure is in memory.  Since the structure index must
974       // be constant, we can get its value and use it to find the
975       // right byte offset from the StructLayout class's list of
976       // structure member offsets.
977       unsigned idxValue = CUI->getValue ();
978       unsigned memberOffset =
979         TD.getStructLayout (StTy)->MemberOffsets[idxValue];
980       // Emit an ADD to add memberOffset to the basePtr.
981       BMI(MBB, IP, X86::ADDri32, 2,
982           nextBasePtrReg).addReg (basePtrReg).addZImm (memberOffset);
983       // The next type is the member of the structure selected by the
984       // index.
985       Ty = StTy->getElementTypes ()[idxValue];
986     } else if (const SequentialType *SqTy = cast <SequentialType> (Ty)) {
987       // It's an array or pointer access: [ArraySize x ElementType].
988       const Type *typeOfSequentialTypeIndex = SqTy->getIndexType ();
989       // idx is the index into the array.  Unlike with structure
990       // indices, we may not know its actual value at code-generation
991       // time.
992       assert (idx->getType () == typeOfSequentialTypeIndex
993               && "Funny-looking array index in GEP");
994       // We want to add basePtrReg to (idxReg * sizeof
995       // ElementType). First, we must find the size of the pointed-to
996       // type.  (Not coincidentally, the next type is the type of the
997       // elements in the array.)
998       Ty = SqTy->getElementType ();
999       unsigned elementSize = TD.getTypeSize (Ty);
1000       unsigned elementSizeReg = makeAnotherReg(typeOfSequentialTypeIndex);
1001       copyConstantToRegister(ConstantSInt::get(typeOfSequentialTypeIndex,
1002                                               elementSize), elementSizeReg,
1003                              MBB, IP);
1004                              
1005       unsigned idxReg = getReg(idx, MBB, IP);
1006       // Emit a MUL to multiply the register holding the index by
1007       // elementSize, putting the result in memberOffsetReg.
1008       unsigned memberOffsetReg = makeAnotherReg(Type::UIntTy);
1009       doMultiply (memberOffsetReg, typeOfSequentialTypeIndex,
1010                   elementSizeReg, idxReg, MBB, IP);
1011       // Emit an ADD to add memberOffsetReg to the basePtr.
1012       BMI(MBB, IP, X86::ADDrr32, 2,
1013           nextBasePtrReg).addReg (basePtrReg).addReg (memberOffsetReg);
1014     }
1015     // Now that we are here, further indices refer to subtypes of this
1016     // one, so we don't need to worry about basePtrReg itself, anymore.
1017     basePtrReg = nextBasePtrReg;
1018   }
1019   // After we have processed all the indices, the result is left in
1020   // basePtrReg.  Move it to the register where we were expected to
1021   // put the answer.  A 32-bit move should do it, because we are in
1022   // ILP32 land.
1023   BMI(MBB, IP, X86::MOVrr32, 1, TargetReg).addReg (basePtrReg);
1024 }
1025
1026
1027 /// visitMallocInst - I know that personally, whenever I want to remember
1028 /// something, I have to clear off some space in my brain.
1029 void
1030 ISel::visitMallocInst (MallocInst &I)
1031 {
1032   // We assume that by this point, malloc instructions have been
1033   // lowered to calls, and dlsym will magically find malloc for us.
1034   // So we do not want to see malloc instructions here.
1035   visitInstruction (I);
1036 }
1037
1038
1039 /// visitFreeInst - same story as MallocInst
1040 void
1041 ISel::visitFreeInst (FreeInst &I)
1042 {
1043   // We assume that by this point, free instructions have been
1044   // lowered to calls, and dlsym will magically find free for us.
1045   // So we do not want to see free instructions here.
1046   visitInstruction (I);
1047 }
1048
1049
1050 /// visitAllocaInst - I want some stack space. Come on, man, I said I
1051 /// want some freakin' stack space.
1052 void
1053 ISel::visitAllocaInst (AllocaInst &I)
1054 {
1055   // Find the data size of the alloca inst's getAllocatedType.
1056   const Type *allocatedType = I.getAllocatedType ();
1057   const TargetData &TD = TM.DataLayout;
1058   unsigned allocatedTypeSize = TD.getTypeSize (allocatedType);
1059   // Keep stack 32-bit aligned.
1060   unsigned int allocatedTypeWords = allocatedTypeSize / 4;
1061   if (allocatedTypeSize % 4 != 0) { allocatedTypeWords++; }
1062   // Subtract size from stack pointer, thereby allocating some space.
1063   BuildMI (BB, X86::SUBri32, 1, X86::ESP).addZImm (allocatedTypeWords * 4);
1064   // Put a pointer to the space into the result register, by copying
1065   // the stack pointer.
1066   BuildMI (BB, X86::MOVrr32, 1, getReg (I)).addReg (X86::ESP);
1067 }
1068     
1069
1070 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
1071 /// into a machine code representation is a very simple peep-hole fashion.  The
1072 /// generated code sucks but the implementation is nice and simple.
1073 ///
1074 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {
1075   return new ISel(TM);
1076 }