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