1 //===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
3 // This file defines a simple peephole instruction selector for the x86 platform
5 //===----------------------------------------------------------------------===//
8 #include "X86InstrInfo.h"
9 #include "llvm/Function.h"
10 #include "llvm/iTerminators.h"
11 #include "llvm/iOperators.h"
12 #include "llvm/iOther.h"
13 #include "llvm/iPHINode.h"
14 #include "llvm/Type.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Pass.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/Support/InstVisitor.h"
23 struct ISel : public FunctionPass, InstVisitor<ISel> {
25 MachineFunction *F; // The function we are compiling into
26 MachineBasicBlock *BB; // The current MBB we are compiling
29 std::map<Value*, unsigned> RegMap; // Mapping between Val's and SSA Regs
31 ISel(TargetMachine &tm)
32 : TM(tm), F(0), BB(0), CurReg(MRegisterInfo::FirstVirtualRegister) {}
34 /// runOnFunction - Top level implementation of instruction selection for
35 /// the entire function.
37 bool runOnFunction(Function &Fn) {
38 F = &MachineFunction::construct(&Fn, TM);
42 return false; // We never modify the LLVM itself.
45 /// visitBasicBlock - This method is called when we are visiting a new basic
46 /// block. This simply creates a new MachineBasicBlock to emit code into
47 /// and adds it to the current MachineFunction. Subsequent visit* for
48 /// instructions will be invoked for all instructions in the basic block.
50 void visitBasicBlock(BasicBlock &LLVM_BB) {
51 BB = new MachineBasicBlock(&LLVM_BB);
52 // FIXME: Use the auto-insert form when it's available
53 F->getBasicBlockList().push_back(BB);
56 // Visitation methods for various instructions. These methods simply emit
57 // fixed X86 code for each instruction.
59 void visitReturnInst(ReturnInst &RI);
60 void visitBranchInst(BranchInst &BI);
62 // Arithmetic operators
63 void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
64 void visitAdd(BinaryOperator &B) { visitSimpleBinary(B, 0); }
65 void visitSub(BinaryOperator &B) { visitSimpleBinary(B, 1); }
66 void visitMul(BinaryOperator &B);
68 void visitDiv(BinaryOperator &B) { visitDivRem(B); }
69 void visitRem(BinaryOperator &B) { visitDivRem(B); }
70 void visitDivRem(BinaryOperator &B);
73 void visitAnd(BinaryOperator &B) { visitSimpleBinary(B, 2); }
74 void visitOr (BinaryOperator &B) { visitSimpleBinary(B, 3); }
75 void visitXor(BinaryOperator &B) { visitSimpleBinary(B, 4); }
77 // Binary comparison operators
80 void visitShiftInst(ShiftInst &I);
81 void visitSetCondInst(SetCondInst &I);
82 void visitPHINode(PHINode &I);
84 void visitInstruction(Instruction &I) {
85 std::cerr << "Cannot instruction select: " << I;
90 /// copyConstantToRegister - Output the instructions required to put the
91 /// specified constant into the specified register.
93 void copyConstantToRegister(Constant *C, unsigned Reg);
95 /// getReg - This method turns an LLVM value into a register number. This
96 /// is guaranteed to produce the same register number for a particular value
97 /// every time it is queried.
99 unsigned getReg(Value &V) { return getReg(&V); } // Allow references
100 unsigned getReg(Value *V) {
101 unsigned &Reg = RegMap[V];
105 // If this operand is a constant, emit the code to copy the constant into
106 // the register here...
108 if (Constant *C = dyn_cast<Constant>(V))
109 copyConstantToRegister(C, Reg);
116 /// getClass - Turn a primitive type into a "class" number which is based on the
117 /// size of the type, and whether or not it is floating point.
119 static inline unsigned getClass(const Type *Ty) {
120 switch (Ty->getPrimitiveID()) {
121 case Type::SByteTyID:
122 case Type::UByteTyID: return 0; // Byte operands are class #0
123 case Type::ShortTyID:
124 case Type::UShortTyID: return 1; // Short operands are class #1
127 case Type::PointerTyID: return 2; // Int's and pointers are class #2
130 case Type::ULongTyID: return 3; // Longs are class #3
131 case Type::FloatTyID: return 4; // Float is class #4
132 case Type::DoubleTyID: return 5; // Doubles are class #5
134 assert(0 && "Invalid type to getClass!");
135 return 0; // not reached
139 /// copyConstantToRegister - Output the instructions required to put the
140 /// specified constant into the specified register.
142 void ISel::copyConstantToRegister(Constant *C, unsigned R) {
143 assert (!isa<ConstantExpr>(C) && "Constant expressions not yet handled!\n");
145 if (C->getType()->isIntegral()) {
146 unsigned Class = getClass(C->getType());
147 assert(Class != 3 && "Type not handled yet!");
149 static const unsigned IntegralOpcodeTab[] = {
150 X86::MOVir8, X86::MOVir16, X86::MOVir32
153 if (C->getType()->isSigned()) {
154 ConstantSInt *CSI = cast<ConstantSInt>(C);
155 BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addSImm(CSI->getValue());
157 ConstantUInt *CUI = cast<ConstantUInt>(C);
158 BuildMI(BB, IntegralOpcodeTab[Class], 1, R).addZImm(CUI->getValue());
161 assert(0 && "Type not handled yet!");
165 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
166 /// register, then move it to wherever the result should be.
167 /// We handle FP setcc instructions by pushing them, doing a
168 /// compare-and-pop-twice, and then copying the concodes to the main
169 /// processor's concodes (I didn't make this up, it's in the Intel manual)
172 ISel::visitSetCondInst (SetCondInst & I)
174 // The arguments are already supposed to be of the same type.
175 Value *var1 = I.getOperand (0);
176 Value *var2 = I.getOperand (1);
177 unsigned reg1 = getReg (var1);
178 unsigned reg2 = getReg (var2);
179 unsigned resultReg = getReg (I);
180 unsigned comparisonWidth = var1->getType ()->getPrimitiveSize ();
181 unsigned unsignedComparison = var1->getType ()->isUnsigned ();
182 unsigned resultWidth = I.getType ()->getPrimitiveSize ();
183 bool fpComparison = var1->getType ()->isFloatingPoint ();
186 // Push the variables on the stack with fldl opcodes.
187 // FIXME: assuming var1, var2 are in memory, if not, spill to
189 switch (comparisonWidth)
192 BuildMI (BB, X86::FLDr4, 1, X86::NoReg).addReg (reg1);
195 BuildMI (BB, X86::FLDr8, 1, X86::NoReg).addReg (reg1);
198 visitInstruction (I);
201 switch (comparisonWidth)
204 BuildMI (BB, X86::FLDr4, 1, X86::NoReg).addReg (reg2);
207 BuildMI (BB, X86::FLDr8, 1, X86::NoReg).addReg (reg2);
210 visitInstruction (I);
213 // (Non-trapping) compare and pop twice.
214 // FIXME: Result of comparison -> condition codes, not a register.
215 BuildMI (BB, X86::FUCOMPP, 0);
216 // Move fp status word (concodes) to ax.
217 BuildMI (BB, X86::FNSTSWr8, 1, X86::AX);
218 // Load real concodes from ax.
219 // FIXME: Once again, flags are not modeled.
220 BuildMI (BB, X86::SAHF, 0);
223 { // integer comparison
224 // Emit: cmp <var1>, <var2> (do the comparison). We can
225 // compare 8-bit with 8-bit, 16-bit with 16-bit, 32-bit with
227 // FIXME: Result of comparison -> condition codes, not a register.
228 switch (comparisonWidth)
231 BuildMI (BB, X86::CMPrr8, 2,
232 X86::NoReg).addReg (reg1).addReg (reg2);
235 BuildMI (BB, X86::CMPrr16, 2,
236 X86::NoReg).addReg (reg1).addReg (reg2);
239 BuildMI (BB, X86::CMPrr32, 2,
240 X86::NoReg).addReg (reg1).addReg (reg2);
244 visitInstruction (I);
248 // Emit setOp instruction (extract concode; clobbers ax),
249 // using the following mapping:
250 // LLVM -> X86 signed X86 unsigned
252 // seteq -> sete sete
253 // setne -> setne setne
254 // setlt -> setl setb
255 // setgt -> setg seta
256 // setle -> setle setbe
257 // setge -> setge setae
258 switch (I.getOpcode ())
260 case Instruction::SetEQ:
261 BuildMI (BB, X86::SETE, 0, X86::AL);
263 case Instruction::SetGE:
264 if (unsignedComparison)
265 BuildMI (BB, X86::SETAE, 0, X86::AL);
267 BuildMI (BB, X86::SETGE, 0, X86::AL);
269 case Instruction::SetGT:
270 if (unsignedComparison)
271 BuildMI (BB, X86::SETA, 0, X86::AL);
273 BuildMI (BB, X86::SETG, 0, X86::AL);
275 case Instruction::SetLE:
276 if (unsignedComparison)
277 BuildMI (BB, X86::SETBE, 0, X86::AL);
279 BuildMI (BB, X86::SETLE, 0, X86::AL);
281 case Instruction::SetLT:
282 if (unsignedComparison)
283 BuildMI (BB, X86::SETB, 0, X86::AL);
285 BuildMI (BB, X86::SETL, 0, X86::AL);
287 case Instruction::SetNE:
288 BuildMI (BB, X86::SETNE, 0, X86::AL);
291 visitInstruction (I);
294 // Put it in the result using a move.
298 BuildMI (BB, X86::MOVrr8, 1, resultReg).addReg (X86::AL);
300 // FIXME: What to do about implicit destination registers?
301 // E.g., you don't specify it, but CBW is more like AX = CBW(AL).
303 BuildMI (BB, X86::CBW, 0, X86::AX);
304 BuildMI (BB, X86::MOVrr16, 1, resultReg).addReg (X86::AX);
307 BuildMI (BB, X86::CWDE, 0, X86::EAX);
308 BuildMI (BB, X86::MOVrr32, 1, resultReg).addReg (X86::EAX);
312 visitInstruction (I);
318 /// 'ret' instruction - Here we are interested in meeting the x86 ABI. As such,
319 /// we have the following possibilities:
321 /// ret void: No return value, simply emit a 'ret' instruction
322 /// ret sbyte, ubyte : Extend value into EAX and return
323 /// ret short, ushort: Extend value into EAX and return
324 /// ret int, uint : Move value into EAX and return
325 /// ret pointer : Move value into EAX and return
326 /// ret long, ulong : Move value into EAX/EDX (?) and return
327 /// ret float/double : ? Top of FP stack? XMM0?
329 void ISel::visitReturnInst(ReturnInst &I) {
330 if (I.getNumOperands() != 0) { // Not 'ret void'?
331 // Move result into a hard register... then emit a ret
332 visitInstruction(I); // abort
335 // Emit a simple 'ret' instruction... appending it to the end of the basic
337 BuildMI(BB, X86::RET, 0);
340 /// visitBranchInst - Handle conditional and unconditional branches here. Note
341 /// that since code layout is frozen at this point, that if we are trying to
342 /// jump to a block that is the immediate successor of the current block, we can
343 /// just make a fall-through. (but we don't currently).
345 void ISel::visitBranchInst(BranchInst &BI) {
346 if (BI.isConditional()) // Only handles unconditional branches so far...
347 visitInstruction(BI);
349 BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
353 /// visitSimpleBinary - Implement simple binary operators for integral types...
354 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
357 void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
358 if (B.getType() == Type::BoolTy) // FIXME: Handle bools for logicals
361 unsigned Class = getClass(B.getType());
362 if (Class > 2) // FIXME: Handle longs
365 static const unsigned OpcodeTab[][4] = {
366 // Arithmetic operators
367 { X86::ADDrr8, X86::ADDrr16, X86::ADDrr32, 0 }, // ADD
368 { X86::SUBrr8, X86::SUBrr16, X86::SUBrr32, 0 }, // SUB
371 { X86::ANDrr8, X86::ANDrr16, X86::ANDrr32, 0 }, // AND
372 { X86:: ORrr8, X86:: ORrr16, X86:: ORrr32, 0 }, // OR
373 { X86::XORrr8, X86::XORrr16, X86::XORrr32, 0 }, // XOR
376 unsigned Opcode = OpcodeTab[OperatorClass][Class];
377 unsigned Op0r = getReg(B.getOperand(0));
378 unsigned Op1r = getReg(B.getOperand(1));
379 BuildMI(BB, Opcode, 2, getReg(B)).addReg(Op0r).addReg(Op1r);
382 /// visitMul - Multiplies are not simple binary operators because they must deal
383 /// with the EAX register explicitly.
385 void ISel::visitMul(BinaryOperator &I) {
386 unsigned Class = getClass(I.getType());
387 if (Class > 2) // FIXME: Handle longs
390 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
391 static const unsigned MulOpcode[]={ X86::MULrr8, X86::MULrr16, X86::MULrr32 };
392 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
394 unsigned Reg = Regs[Class];
395 unsigned Op0Reg = getReg(I.getOperand(1));
396 unsigned Op1Reg = getReg(I.getOperand(1));
398 // Put the first operand into one of the A registers...
399 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
401 // Emit the appropriate multiple instruction...
402 // FIXME: We need to mark that this modified AH, DX, or EDX also!!
403 BuildMI(BB, MulOpcode[Class], 2, Reg).addReg(Reg).addReg(Op1Reg);
405 // Put the result into the destination register...
406 BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(Reg);
409 /// visitDivRem - Handle division and remainder instructions... these
410 /// instruction both require the same instructions to be generated, they just
411 /// select the result from a different register. Note that both of these
412 /// instructions work differently for signed and unsigned operands.
414 void ISel::visitDivRem(BinaryOperator &I) {
415 unsigned Class = getClass(I.getType());
416 if (Class > 2) // FIXME: Handle longs
419 static const unsigned Regs[] ={ X86::AL , X86::AX , X86::EAX };
420 static const unsigned MovOpcode[]={ X86::MOVrr8, X86::MOVrr16, X86::MOVrr32 };
421 static const unsigned ExtOpcode[]={ X86::CBW , X86::CWD , X86::CWQ };
422 static const unsigned ClrOpcode[]={ X86::XORrr8, X86::XORrr16, X86::XORrr32 };
423 static const unsigned ExtRegs[] ={ X86::AH , X86::DX , X86::EDX };
425 static const unsigned DivOpcode[][4] = {
426 { X86::DIVrr8 , X86::DIVrr16 , X86::DIVrr32 , 0 }, // Unsigned division
427 { X86::IDIVrr8, X86::IDIVrr16, X86::IDIVrr32, 0 }, // Signed division
430 bool isSigned = I.getType()->isSigned();
431 unsigned Reg = Regs[Class];
432 unsigned ExtReg = ExtRegs[Class];
433 unsigned Op0Reg = getReg(I.getOperand(1));
434 unsigned Op1Reg = getReg(I.getOperand(1));
436 // Put the first operand into one of the A registers...
437 BuildMI(BB, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
440 // Emit a sign extension instruction...
441 BuildMI(BB, ExtOpcode[Class], 1, ExtReg).addReg(Reg);
443 // If unsigned, emit a zeroing instruction... (reg = xor reg, reg)
444 BuildMI(BB, ClrOpcode[Class], 2, ExtReg).addReg(ExtReg).addReg(ExtReg);
447 // Figure out which register we want to pick the result out of...
448 unsigned DestReg = (I.getOpcode() == Instruction::Div) ? Reg : ExtReg;
450 // Emit the appropriate multiple instruction...
451 // FIXME: We need to mark that this modified AH, DX, or EDX also!!
452 BuildMI(BB,DivOpcode[isSigned][Class], 2, DestReg).addReg(Reg).addReg(Op1Reg);
454 // Put the result into the destination register...
455 BuildMI(BB, MovOpcode[Class], 1, getReg(I)).addReg(DestReg);
458 /// Shift instructions: 'shl', 'sar', 'shr' - Some special cases here
459 /// for constant immediate shift values, and for constant immediate
460 /// shift values equal to 1. Even the general case is sort of special,
461 /// because the shift amount has to be in CL, not just any old register.
463 void ISel::visitShiftInst (ShiftInst &I) {
464 unsigned Op0r = getReg (I.getOperand(0));
465 unsigned DestReg = getReg(I);
466 bool isLeftShift = I.getOpcode() == Instruction::Shl;
467 bool isOperandSigned = I.getType()->isUnsigned();
468 unsigned OperandClass = getClass(I.getType());
470 if (OperandClass > 2)
471 visitInstruction(I); // Can't handle longs yet!
473 if (ConstantUInt *CUI = dyn_cast <ConstantUInt> (I.getOperand (1)))
475 // The shift amount is constant, guaranteed to be a ubyte. Get its value.
476 assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
477 unsigned char shAmt = CUI->getValue();
479 static const unsigned ConstantOperand[][4] = {
480 { X86::SHRir8, X86::SHRir16, X86::SHRir32, 0 }, // SHR
481 { X86::SARir8, X86::SARir16, X86::SARir32, 0 }, // SAR
482 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SHL
483 { X86::SHLir8, X86::SHLir16, X86::SHLir32, 0 }, // SAL = SHL
486 const unsigned *OpTab = // Figure out the operand table to use
487 ConstantOperand[isLeftShift*2+isOperandSigned];
489 // Emit: <insn> reg, shamt (shift-by-immediate opcode "ir" form.)
490 BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addZImm(shAmt);
494 // The shift amount is non-constant.
496 // In fact, you can only shift with a variable shift amount if
497 // that amount is already in the CL register, so we have to put it
501 // Emit: move cl, shiftAmount (put the shift amount in CL.)
502 BuildMI(BB, X86::MOVrr8, 1, X86::CL).addReg(getReg(I.getOperand(1)));
504 // This is a shift right (SHR).
505 static const unsigned NonConstantOperand[][4] = {
506 { X86::SHRrr8, X86::SHRrr16, X86::SHRrr32, 0 }, // SHR
507 { X86::SARrr8, X86::SARrr16, X86::SARrr32, 0 }, // SAR
508 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SHL
509 { X86::SHLrr8, X86::SHLrr16, X86::SHLrr32, 0 }, // SAL = SHL
512 const unsigned *OpTab = // Figure out the operand table to use
513 NonConstantOperand[isLeftShift*2+isOperandSigned];
515 BuildMI(BB, OpTab[OperandClass], 2, DestReg).addReg(Op0r).addReg(X86::CL);
519 /// visitPHINode - Turn an LLVM PHI node into an X86 PHI node...
521 void ISel::visitPHINode(PHINode &PN) {
522 MachineInstr *MI = BuildMI(BB, X86::PHI, PN.getNumOperands(), getReg(PN));
524 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
525 // FIXME: This will put constants after the PHI nodes in the block, which
526 // is invalid. They should be put inline into the PHI node eventually.
528 MI->addRegOperand(getReg(PN.getIncomingValue(i)));
529 MI->addPCDispOperand(PN.getIncomingBlock(i));
534 /// createSimpleX86InstructionSelector - This pass converts an LLVM function
535 /// into a machine code representation is a very simple peep-hole fashion. The
536 /// generated code sucks but the implementation is nice and simple.
538 Pass *createSimpleX86InstructionSelector(TargetMachine &TM) {