1 //===-- FloatingPoint.cpp - Floating point Reg -> Stack converter ---------===//
3 // This file defines the pass which converts floating point instructions from
4 // virtual registers into register stack instructions.
6 //===----------------------------------------------------------------------===//
8 #define DEBUG_TYPE "fp"
10 #include "X86InstrInfo.h"
11 #include "llvm/CodeGen/MachineFunctionPass.h"
12 #include "llvm/CodeGen/MachineInstrBuilder.h"
13 #include "llvm/CodeGen/LiveVariables.h"
14 #include "llvm/Target/TargetInstrInfo.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "Support/Debug.h"
17 #include "Support/Statistic.h"
22 Statistic<> NumFXCH("x86-codegen", "Number of fxch instructions inserted");
23 Statistic<> NumFP ("x86-codegen", "Number of floating point instructions");
25 struct FPS : public MachineFunctionPass {
26 virtual bool runOnMachineFunction(MachineFunction &MF);
28 virtual const char *getPassName() const { return "X86 FP Stackifier"; }
30 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
31 AU.addRequired<LiveVariables>();
32 MachineFunctionPass::getAnalysisUsage(AU);
35 LiveVariables *LV; // Live variable info for current function...
36 MachineBasicBlock *MBB; // Current basic block
37 unsigned Stack[8]; // FP<n> Registers in each stack slot...
38 unsigned RegMap[8]; // Track which stack slot contains each register
39 unsigned StackTop; // The current top of the FP stack.
41 void dumpStack() const {
42 std::cerr << "Stack contents:";
43 for (unsigned i = 0; i != StackTop; ++i) {
44 std::cerr << " FP" << Stack[i];
45 assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!");
50 // getSlot - Return the stack slot number a particular register number is
52 unsigned getSlot(unsigned RegNo) const {
53 assert(RegNo < 8 && "Regno out of range!");
57 // getStackEntry - Return the X86::FP<n> register in register ST(i)
58 unsigned getStackEntry(unsigned STi) const {
59 assert(STi < StackTop && "Access past stack top!");
60 return Stack[StackTop-1-STi];
63 // getSTReg - Return the X86::ST(i) register which contains the specified
65 unsigned getSTReg(unsigned RegNo) const {
66 return StackTop - 1 - getSlot(RegNo) + X86::ST0;
69 // pushReg - Push the specifiex FP<n> register onto the stack
70 void pushReg(unsigned Reg) {
71 assert(Reg < 8 && "Register number out of range!");
72 assert(StackTop < 8 && "Stack overflow!");
73 Stack[StackTop] = Reg;
74 RegMap[Reg] = StackTop++;
77 bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }
78 void moveToTop(unsigned RegNo, MachineBasicBlock::iterator &I) {
79 if (!isAtTop(RegNo)) {
80 unsigned Slot = getSlot(RegNo);
81 unsigned STReg = getSTReg(RegNo);
82 unsigned RegOnTop = getStackEntry(0);
84 // Swap the slots the regs are in
85 std::swap(RegMap[RegNo], RegMap[RegOnTop]);
87 // Swap stack slot contents
88 assert(RegMap[RegOnTop] < StackTop);
89 std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
91 // Emit an fxch to update the runtime processors version of the state
92 MachineInstr *MI = BuildMI(X86::FXCH, 1).addReg(STReg);
93 I = 1+MBB->insert(I, MI);
98 void duplicateToTop(unsigned RegNo, unsigned AsReg,
99 MachineBasicBlock::iterator &I) {
100 unsigned STReg = getSTReg(RegNo);
101 pushReg(AsReg); // New register on top of stack
103 MachineInstr *MI = BuildMI(X86::FLDrr, 1).addReg(STReg);
104 I = 1+MBB->insert(I, MI);
107 // popStackAfter - Pop the current value off of the top of the FP stack
108 // after the specified instruction.
109 void popStackAfter(MachineBasicBlock::iterator &I);
111 bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
113 void handleZeroArgFP(MachineBasicBlock::iterator &I);
114 void handleOneArgFP(MachineBasicBlock::iterator &I);
115 void handleTwoArgFP(MachineBasicBlock::iterator &I);
116 void handleSpecialFP(MachineBasicBlock::iterator &I);
120 Pass *createX86FloatingPointStackifierPass() { return new FPS(); }
122 /// runOnMachineFunction - Loop over all of the basic blocks, transforming FP
123 /// register references into FP stack references.
125 bool FPS::runOnMachineFunction(MachineFunction &MF) {
126 LV = &getAnalysis<LiveVariables>();
129 bool Changed = false;
130 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
131 Changed |= processBasicBlock(MF, *I);
135 /// processBasicBlock - Loop over all of the instructions in the basic block,
136 /// transforming FP instructions into their stack form.
138 bool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {
139 const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
140 bool Changed = false;
143 for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
144 MachineInstr *MI = *I;
145 MachineInstr *PrevMI = I == BB.begin() ? 0 : *(I-1);
146 unsigned Flags = TII.get(MI->getOpcode()).TSFlags;
148 if ((Flags & X86II::FPTypeMask) == 0) continue; // Ignore non-fp insts!
150 ++NumFP; // Keep track of # of pseudo instrs
151 DEBUG(std::cerr << "\nFPInst:\t";
152 MI->print(std::cerr, MF.getTarget()));
154 // Get dead variables list now because the MI pointer may be deleted as part
156 LiveVariables::killed_iterator IB = LV->dead_begin(MI);
157 LiveVariables::killed_iterator IE = LV->dead_end(MI);
159 DEBUG(const MRegisterInfo *MRI = MF.getTarget().getRegisterInfo();
160 LiveVariables::killed_iterator I = LV->killed_begin(MI);
161 LiveVariables::killed_iterator E = LV->killed_end(MI);
163 std::cerr << "Killed Operands:";
165 std::cerr << " %" << MRI->getName(I->second);
169 switch (Flags & X86II::FPTypeMask) {
170 case X86II::ZeroArgFP: handleZeroArgFP(I); break;
171 case X86II::OneArgFP: handleOneArgFP(I); break;
173 case X86II::OneArgFPRW: // ST(0) = fsqrt(ST(0))
174 assert(0 && "FP instr type not handled yet!");
176 case X86II::TwoArgFP: handleTwoArgFP(I); break;
177 case X86II::SpecialFP: handleSpecialFP(I); break;
178 default: assert(0 && "Unknown FP Type!");
181 // Check to see if any of the values defined by this instruction are dead
182 // after definition. If so, pop them.
183 for (; IB != IE; ++IB) {
184 unsigned Reg = IB->second;
185 if (Reg >= X86::FP0 && Reg <= X86::FP6) {
186 DEBUG(std::cerr << "Register FP#" << Reg-X86::FP0 << " is dead!\n");
187 ++I; // Insert fxch AFTER the instruction
188 moveToTop(Reg-X86::FP0, I); // Insert fxch if neccesary
189 --I; // Move to fxch or old instruction
190 popStackAfter(I); // Pop the top of the stack, killing value
194 // Print out all of the instructions expanded to if -debug
195 DEBUG(if (*I == PrevMI) {
196 std::cerr<< "Just deleted pseudo instruction\n";
198 MachineBasicBlock::iterator Start = I;
199 // Rewind to first instruction newly inserted.
200 while (Start != BB.begin() && *(Start-1) != PrevMI) --Start;
201 std::cerr << "Inserted instructions:\n\t";
202 (*Start)->print(std::cerr, MF.getTarget());
203 while (++Start != I+1);
211 assert(StackTop == 0 && "Stack not empty at end of basic block?");
215 //===----------------------------------------------------------------------===//
216 // Efficient Lookup Table Support
217 //===----------------------------------------------------------------------===//
222 bool operator<(const TableEntry &TE) const { return from < TE.from; }
223 bool operator<(unsigned V) const { return from < V; }
226 static bool TableIsSorted(const TableEntry *Table, unsigned NumEntries) {
227 for (unsigned i = 0; i != NumEntries-1; ++i)
228 if (!(Table[i] < Table[i+1])) return false;
232 static int Lookup(const TableEntry *Table, unsigned N, unsigned Opcode) {
233 const TableEntry *I = std::lower_bound(Table, Table+N, Opcode);
234 if (I != Table+N && I->from == Opcode)
239 #define ARRAY_SIZE(TABLE) \
240 (sizeof(TABLE)/sizeof(TABLE[0]))
243 #define ASSERT_SORTED(TABLE)
245 #define ASSERT_SORTED(TABLE) \
246 { static bool TABLE##Checked = false; \
247 if (!TABLE##Checked) \
248 assert(TableIsSorted(TABLE, ARRAY_SIZE(TABLE)) && \
249 "All lookup tables must be sorted for efficient access!"); \
254 //===----------------------------------------------------------------------===//
256 //===----------------------------------------------------------------------===//
258 // PopTable - Sorted map of instructions to their popping version. The first
259 // element is an instruction, the second is the version which pops.
261 static const TableEntry PopTable[] = {
262 { X86::FSTr32 , X86::FSTPr32 },
263 { X86::FSTr64 , X86::FSTPr64 },
264 { X86::FSTrr , X86::FSTPrr },
265 { X86::FISTr16 , X86::FISTPr16 },
266 { X86::FISTr32 , X86::FISTPr32 },
268 { X86::FADDrST0 , X86::FADDPrST0 },
269 { X86::FSUBrST0 , X86::FSUBPrST0 },
270 { X86::FSUBRrST0, X86::FSUBRPrST0 },
271 { X86::FMULrST0 , X86::FMULPrST0 },
272 { X86::FDIVrST0 , X86::FDIVPrST0 },
273 { X86::FDIVRrST0, X86::FDIVRPrST0 },
275 { X86::FUCOMr , X86::FUCOMPr },
276 { X86::FUCOMPr , X86::FUCOMPPr },
279 /// popStackAfter - Pop the current value off of the top of the FP stack after
280 /// the specified instruction. This attempts to be sneaky and combine the pop
281 /// into the instruction itself if possible. The iterator is left pointing to
282 /// the last instruction, be it a new pop instruction inserted, or the old
283 /// instruction if it was modified in place.
285 void FPS::popStackAfter(MachineBasicBlock::iterator &I) {
286 ASSERT_SORTED(PopTable);
287 assert(StackTop > 0 && "Cannot pop empty stack!");
288 RegMap[Stack[--StackTop]] = ~0; // Update state
290 // Check to see if there is a popping version of this instruction...
291 int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), (*I)->getOpcode());
293 (*I)->setOpcode(Opcode);
294 if (Opcode == X86::FUCOMPPr)
295 (*I)->RemoveOperand(0);
297 } else { // Insert an explicit pop
298 MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(X86::ST0);
299 I = MBB->insert(I+1, MI);
303 static unsigned getFPReg(const MachineOperand &MO) {
304 assert(MO.isPhysicalRegister() && "Expected an FP register!");
305 unsigned Reg = MO.getReg();
306 assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");
307 return Reg - X86::FP0;
311 //===----------------------------------------------------------------------===//
312 // Instruction transformation implementation
313 //===----------------------------------------------------------------------===//
315 /// handleZeroArgFP - ST(0) = fld0 ST(0) = flds <mem>
317 void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
318 MachineInstr *MI = *I;
319 unsigned DestReg = getFPReg(MI->getOperand(0));
320 MI->RemoveOperand(0); // Remove the explicit ST(0) operand
322 // Result gets pushed on the stack...
326 /// handleOneArgFP - fst ST(0), <mem>
328 void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
329 MachineInstr *MI = *I;
330 assert(MI->getNumOperands() == 5 && "Can only handle fst* instructions!");
332 unsigned Reg = getFPReg(MI->getOperand(4));
333 bool KillsSrc = false;
334 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
335 E = LV->killed_end(MI); KI != E; ++KI)
336 KillsSrc |= KI->second == X86::FP0+Reg;
338 // FSTPr80 and FISTPr64 are strange because there are no non-popping versions.
339 // If we have one _and_ we don't want to pop the operand, duplicate the value
340 // on the stack instead of moving it. This ensure that popping the value is
343 if ((MI->getOpcode() == X86::FSTPr80 ||
344 MI->getOpcode() == X86::FISTPr64) && !KillsSrc) {
345 duplicateToTop(Reg, 7 /*temp register*/, I);
347 moveToTop(Reg, I); // Move to the top of the stack...
349 MI->RemoveOperand(4); // Remove explicit ST(0) operand
351 if (MI->getOpcode() == X86::FSTPr80 || MI->getOpcode() == X86::FISTPr64) {
352 assert(StackTop > 0 && "Stack empty??");
354 } else if (KillsSrc) { // Last use of operand?
359 //===----------------------------------------------------------------------===//
360 // Define tables of various ways to map pseudo instructions
363 // ForwardST0Table - Map: A = B op C into: ST(0) = ST(0) op ST(i)
364 static const TableEntry ForwardST0Table[] = {
365 { X86::FpADD, X86::FADDST0r },
366 { X86::FpSUB, X86::FSUBST0r },
367 { X86::FpMUL, X86::FMULST0r },
368 { X86::FpDIV, X86::FDIVST0r },
369 { X86::FpUCOM, X86::FUCOMr },
372 // ReverseST0Table - Map: A = B op C into: ST(0) = ST(i) op ST(0)
373 static const TableEntry ReverseST0Table[] = {
374 { X86::FpADD, X86::FADDST0r }, // commutative
375 { X86::FpSUB, X86::FSUBRST0r },
376 { X86::FpMUL, X86::FMULST0r }, // commutative
377 { X86::FpDIV, X86::FDIVRST0r },
381 // ForwardSTiTable - Map: A = B op C into: ST(i) = ST(0) op ST(i)
382 static const TableEntry ForwardSTiTable[] = {
383 { X86::FpADD, X86::FADDrST0 }, // commutative
384 { X86::FpSUB, X86::FSUBRrST0 },
385 { X86::FpMUL, X86::FMULrST0 }, // commutative
386 { X86::FpDIV, X86::FDIVRrST0 },
387 { X86::FpUCOM, X86::FUCOMr },
390 // ReverseSTiTable - Map: A = B op C into: ST(i) = ST(i) op ST(0)
391 static const TableEntry ReverseSTiTable[] = {
392 { X86::FpADD, X86::FADDrST0 },
393 { X86::FpSUB, X86::FSUBrST0 },
394 { X86::FpMUL, X86::FMULrST0 },
395 { X86::FpDIV, X86::FDIVrST0 },
400 /// handleTwoArgFP - Handle instructions like FADD and friends which are virtual
401 /// instructions which need to be simplified and possibly transformed.
403 /// Result: ST(0) = fsub ST(0), ST(i)
404 /// ST(i) = fsub ST(0), ST(i)
405 /// ST(0) = fsubr ST(0), ST(i)
406 /// ST(i) = fsubr ST(0), ST(i)
408 /// In addition to three address instructions, this also handles the FpUCOM
409 /// instruction which only has two operands, but no destination. This
410 /// instruction is also annoying because there is no "reverse" form of it
413 void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
414 ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
415 ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
416 MachineInstr *MI = *I;
418 unsigned NumOperands = MI->getNumOperands();
419 assert(NumOperands == 3 ||
420 (NumOperands == 2 && MI->getOpcode() == X86::FpUCOM) &&
421 "Illegal TwoArgFP instruction!");
422 unsigned Dest = getFPReg(MI->getOperand(0));
423 unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
424 unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
425 bool KillsOp0 = false, KillsOp1 = false;
427 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
428 E = LV->killed_end(MI); KI != E; ++KI) {
429 KillsOp0 |= (KI->second == X86::FP0+Op0);
430 KillsOp1 |= (KI->second == X86::FP0+Op1);
433 // If this is an FpUCOM instruction, we must make sure the first operand is on
434 // the top of stack, the other one can be anywhere...
435 if (MI->getOpcode() == X86::FpUCOM)
438 unsigned TOS = getStackEntry(0);
440 // One of our operands must be on the top of the stack. If neither is yet, we
442 if (Op0 != TOS && Op1 != TOS) { // No operand at TOS?
443 // We can choose to move either operand to the top of the stack. If one of
444 // the operands is killed by this instruction, we want that one so that we
445 // can update right on top of the old version.
447 moveToTop(Op0, I); // Move dead operand to TOS.
449 } else if (KillsOp1) {
453 // All of the operands are live after this instruction executes, so we
454 // cannot update on top of any operand. Because of this, we must
455 // duplicate one of the stack elements to the top. It doesn't matter
456 // which one we pick.
458 duplicateToTop(Op0, Dest, I);
462 } else if (!KillsOp0 && !KillsOp1 && MI->getOpcode() != X86::FpUCOM) {
463 // If we DO have one of our operands at the top of the stack, but we don't
464 // have a dead operand, we must duplicate one of the operands to a new slot
466 duplicateToTop(Op0, Dest, I);
471 // Now we know that one of our operands is on the top of the stack, and at
472 // least one of our operands is killed by this instruction.
473 assert((TOS == Op0 || TOS == Op1) &&
474 (KillsOp0 || KillsOp1 || MI->getOpcode() == X86::FpUCOM) &&
475 "Stack conditions not set up right!");
477 // We decide which form to use based on what is on the top of the stack, and
478 // which operand is killed by this instruction.
479 const TableEntry *InstTable;
480 bool isForward = TOS == Op0;
481 bool updateST0 = (TOS == Op0 && !KillsOp1) || (TOS == Op1 && !KillsOp0);
484 InstTable = ForwardST0Table;
486 InstTable = ReverseST0Table;
489 InstTable = ForwardSTiTable;
491 InstTable = ReverseSTiTable;
494 int Opcode = Lookup(InstTable, ARRAY_SIZE(ForwardST0Table), MI->getOpcode());
495 assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");
497 // NotTOS - The register which is not on the top of stack...
498 unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
500 // Replace the old instruction with a new instruction
501 *I = BuildMI(Opcode, 1).addReg(getSTReg(NotTOS));
503 // If both operands are killed, pop one off of the stack in addition to
504 // overwriting the other one.
505 if (KillsOp0 && KillsOp1 && Op0 != Op1) {
506 assert(!updateST0 && "Should have updated other operand!");
507 popStackAfter(I); // Pop the top of stack
510 // Insert an explicit pop of the "updated" operand for FUCOM
511 if (MI->getOpcode() == X86::FpUCOM) {
512 if (KillsOp0 && !KillsOp1)
513 popStackAfter(I); // If we kill the first operand, pop it!
514 else if (KillsOp1 && Op0 != Op1) {
515 if (getStackEntry(0) == Op1) {
516 popStackAfter(I); // If it's right at the top of stack, just pop it
518 // Otherwise, move the top of stack into the dead slot, killing the
519 // operand without having to add in an explicit xchg then pop.
521 unsigned STReg = getSTReg(Op1);
522 unsigned OldSlot = getSlot(Op1);
523 unsigned TopReg = Stack[StackTop-1];
524 Stack[OldSlot] = TopReg;
525 RegMap[TopReg] = OldSlot;
527 Stack[--StackTop] = ~0;
529 MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(STReg);
530 I = MBB->insert(I+1, MI);
535 // Update stack information so that we know the destination register is now on
537 if (MI->getOpcode() != X86::FpUCOM) {
538 unsigned UpdatedSlot = getSlot(updateST0 ? TOS : NotTOS);
539 assert(UpdatedSlot < StackTop && Dest < 7);
540 Stack[UpdatedSlot] = Dest;
541 RegMap[Dest] = UpdatedSlot;
543 delete MI; // Remove the old instruction
547 /// handleSpecialFP - Handle special instructions which behave unlike other
548 /// floating point instructions. This is primarily inteaded for use by pseudo
551 void FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
552 MachineInstr *MI = *I;
553 switch (MI->getOpcode()) {
554 default: assert(0 && "Unknown SpecialFP instruction!");
555 case X86::FpGETRESULT: // Appears immediately after a call returning FP type!
556 assert(StackTop == 0 && "Stack should be empty after a call!");
557 pushReg(getFPReg(MI->getOperand(0)));
559 case X86::FpSETRESULT:
560 assert(StackTop == 1 && "Stack should have one element on it to return!");
561 --StackTop; // "Forget" we have something on the top of stack!
564 unsigned SrcReg = getFPReg(MI->getOperand(1));
565 unsigned DestReg = getFPReg(MI->getOperand(0));
566 bool KillsSrc = false;
567 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
568 E = LV->killed_end(MI); KI != E; ++KI)
569 KillsSrc |= KI->second == X86::FP0+SrcReg;
572 // If the input operand is killed, we can just change the owner of the
573 // incoming stack slot into the result.
574 unsigned Slot = getSlot(SrcReg);
575 assert(Slot < 7 && DestReg < 7 && "FpMOV operands invalid!");
576 Stack[Slot] = DestReg;
577 RegMap[DestReg] = Slot;
580 // For FMOV we just duplicate the specified value to a new stack slot.
581 // This could be made better, but would require substantial changes.
582 duplicateToTop(SrcReg, DestReg, I);
588 I = MBB->erase(I)-1; // Remove the pseudo instruction