1 //===-- FloatingPoint.cpp - Floating point Reg -> Stack converter ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the pass which converts floating point instructions from
11 // virtual registers into register stack instructions.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "fp"
17 #include "X86InstrInfo.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "Support/Debug.h"
24 #include "Support/Statistic.h"
29 Statistic<> NumFXCH("x86-codegen", "Number of fxch instructions inserted");
30 Statistic<> NumFP ("x86-codegen", "Number of floating point instructions");
32 struct FPS : public MachineFunctionPass {
33 virtual bool runOnMachineFunction(MachineFunction &MF);
35 virtual const char *getPassName() const { return "X86 FP Stackifier"; }
37 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
38 AU.addRequired<LiveVariables>();
39 MachineFunctionPass::getAnalysisUsage(AU);
42 LiveVariables *LV; // Live variable info for current function...
43 MachineBasicBlock *MBB; // Current basic block
44 unsigned Stack[8]; // FP<n> Registers in each stack slot...
45 unsigned RegMap[8]; // Track which stack slot contains each register
46 unsigned StackTop; // The current top of the FP stack.
48 void dumpStack() const {
49 std::cerr << "Stack contents:";
50 for (unsigned i = 0; i != StackTop; ++i) {
51 std::cerr << " FP" << Stack[i];
52 assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!");
57 // getSlot - Return the stack slot number a particular register number is
59 unsigned getSlot(unsigned RegNo) const {
60 assert(RegNo < 8 && "Regno out of range!");
64 // getStackEntry - Return the X86::FP<n> register in register ST(i)
65 unsigned getStackEntry(unsigned STi) const {
66 assert(STi < StackTop && "Access past stack top!");
67 return Stack[StackTop-1-STi];
70 // getSTReg - Return the X86::ST(i) register which contains the specified
72 unsigned getSTReg(unsigned RegNo) const {
73 return StackTop - 1 - getSlot(RegNo) + X86::ST0;
76 // pushReg - Push the specifiex FP<n> register onto the stack
77 void pushReg(unsigned Reg) {
78 assert(Reg < 8 && "Register number out of range!");
79 assert(StackTop < 8 && "Stack overflow!");
80 Stack[StackTop] = Reg;
81 RegMap[Reg] = StackTop++;
84 bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }
85 void moveToTop(unsigned RegNo, MachineBasicBlock::iterator &I) {
86 if (!isAtTop(RegNo)) {
87 unsigned Slot = getSlot(RegNo);
88 unsigned STReg = getSTReg(RegNo);
89 unsigned RegOnTop = getStackEntry(0);
91 // Swap the slots the regs are in
92 std::swap(RegMap[RegNo], RegMap[RegOnTop]);
94 // Swap stack slot contents
95 assert(RegMap[RegOnTop] < StackTop);
96 std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
98 // Emit an fxch to update the runtime processors version of the state
99 MachineInstr *MI = BuildMI(X86::FXCH, 1).addReg(STReg);
100 I = 1+MBB->insert(I, MI);
105 void duplicateToTop(unsigned RegNo, unsigned AsReg,
106 MachineBasicBlock::iterator &I) {
107 unsigned STReg = getSTReg(RegNo);
108 pushReg(AsReg); // New register on top of stack
110 MachineInstr *MI = BuildMI(X86::FLDrr, 1).addReg(STReg);
111 I = 1+MBB->insert(I, MI);
114 // popStackAfter - Pop the current value off of the top of the FP stack
115 // after the specified instruction.
116 void popStackAfter(MachineBasicBlock::iterator &I);
118 bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
120 void handleZeroArgFP(MachineBasicBlock::iterator &I);
121 void handleOneArgFP(MachineBasicBlock::iterator &I);
122 void handleTwoArgFP(MachineBasicBlock::iterator &I);
123 void handleSpecialFP(MachineBasicBlock::iterator &I);
127 FunctionPass *createX86FloatingPointStackifierPass() { return new FPS(); }
129 /// runOnMachineFunction - Loop over all of the basic blocks, transforming FP
130 /// register references into FP stack references.
132 bool FPS::runOnMachineFunction(MachineFunction &MF) {
133 LV = &getAnalysis<LiveVariables>();
136 bool Changed = false;
137 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
138 Changed |= processBasicBlock(MF, *I);
142 /// processBasicBlock - Loop over all of the instructions in the basic block,
143 /// transforming FP instructions into their stack form.
145 bool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {
146 const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
147 bool Changed = false;
150 for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
151 MachineInstr *MI = *I;
152 MachineInstr *PrevMI = I == BB.begin() ? 0 : *(I-1);
153 unsigned Flags = TII.get(MI->getOpcode()).TSFlags;
155 if ((Flags & X86II::FPTypeMask) == 0) continue; // Ignore non-fp insts!
157 ++NumFP; // Keep track of # of pseudo instrs
158 DEBUG(std::cerr << "\nFPInst:\t";
159 MI->print(std::cerr, MF.getTarget()));
161 // Get dead variables list now because the MI pointer may be deleted as part
163 LiveVariables::killed_iterator IB = LV->dead_begin(MI);
164 LiveVariables::killed_iterator IE = LV->dead_end(MI);
166 DEBUG(const MRegisterInfo *MRI = MF.getTarget().getRegisterInfo();
167 LiveVariables::killed_iterator I = LV->killed_begin(MI);
168 LiveVariables::killed_iterator E = LV->killed_end(MI);
170 std::cerr << "Killed Operands:";
172 std::cerr << " %" << MRI->getName(I->second);
176 switch (Flags & X86II::FPTypeMask) {
177 case X86II::ZeroArgFP: handleZeroArgFP(I); break;
178 case X86II::OneArgFP: handleOneArgFP(I); break;
180 case X86II::OneArgFPRW: // ST(0) = fsqrt(ST(0))
181 assert(0 && "FP instr type not handled yet!");
183 case X86II::TwoArgFP: handleTwoArgFP(I); break;
184 case X86II::SpecialFP: handleSpecialFP(I); break;
185 default: assert(0 && "Unknown FP Type!");
188 // Check to see if any of the values defined by this instruction are dead
189 // after definition. If so, pop them.
190 for (; IB != IE; ++IB) {
191 unsigned Reg = IB->second;
192 if (Reg >= X86::FP0 && Reg <= X86::FP6) {
193 DEBUG(std::cerr << "Register FP#" << Reg-X86::FP0 << " is dead!\n");
194 ++I; // Insert fxch AFTER the instruction
195 moveToTop(Reg-X86::FP0, I); // Insert fxch if necessary
196 --I; // Move to fxch or old instruction
197 popStackAfter(I); // Pop the top of the stack, killing value
201 // Print out all of the instructions expanded to if -debug
202 DEBUG(if (*I == PrevMI) {
203 std::cerr<< "Just deleted pseudo instruction\n";
205 MachineBasicBlock::iterator Start = I;
206 // Rewind to first instruction newly inserted.
207 while (Start != BB.begin() && *(Start-1) != PrevMI) --Start;
208 std::cerr << "Inserted instructions:\n\t";
209 (*Start)->print(std::cerr, MF.getTarget());
210 while (++Start != I+1);
218 assert(StackTop == 0 && "Stack not empty at end of basic block?");
222 //===----------------------------------------------------------------------===//
223 // Efficient Lookup Table Support
224 //===----------------------------------------------------------------------===//
229 bool operator<(const TableEntry &TE) const { return from < TE.from; }
230 bool operator<(unsigned V) const { return from < V; }
233 static bool TableIsSorted(const TableEntry *Table, unsigned NumEntries) {
234 for (unsigned i = 0; i != NumEntries-1; ++i)
235 if (!(Table[i] < Table[i+1])) return false;
239 static int Lookup(const TableEntry *Table, unsigned N, unsigned Opcode) {
240 const TableEntry *I = std::lower_bound(Table, Table+N, Opcode);
241 if (I != Table+N && I->from == Opcode)
246 #define ARRAY_SIZE(TABLE) \
247 (sizeof(TABLE)/sizeof(TABLE[0]))
250 #define ASSERT_SORTED(TABLE)
252 #define ASSERT_SORTED(TABLE) \
253 { static bool TABLE##Checked = false; \
254 if (!TABLE##Checked) \
255 assert(TableIsSorted(TABLE, ARRAY_SIZE(TABLE)) && \
256 "All lookup tables must be sorted for efficient access!"); \
261 //===----------------------------------------------------------------------===//
263 //===----------------------------------------------------------------------===//
265 // PopTable - Sorted map of instructions to their popping version. The first
266 // element is an instruction, the second is the version which pops.
268 static const TableEntry PopTable[] = {
269 { X86::FADDrST0 , X86::FADDPrST0 },
271 { X86::FDIVRrST0, X86::FDIVRPrST0 },
272 { X86::FDIVrST0 , X86::FDIVPrST0 },
274 { X86::FISTr16 , X86::FISTPr16 },
275 { X86::FISTr32 , X86::FISTPr32 },
277 { X86::FMULrST0 , X86::FMULPrST0 },
279 { X86::FSTr32 , X86::FSTPr32 },
280 { X86::FSTr64 , X86::FSTPr64 },
281 { X86::FSTrr , X86::FSTPrr },
283 { X86::FSUBRrST0, X86::FSUBRPrST0 },
284 { X86::FSUBrST0 , X86::FSUBPrST0 },
286 { X86::FUCOMPr , X86::FUCOMPPr },
287 { X86::FUCOMr , X86::FUCOMPr },
290 /// popStackAfter - Pop the current value off of the top of the FP stack after
291 /// the specified instruction. This attempts to be sneaky and combine the pop
292 /// into the instruction itself if possible. The iterator is left pointing to
293 /// the last instruction, be it a new pop instruction inserted, or the old
294 /// instruction if it was modified in place.
296 void FPS::popStackAfter(MachineBasicBlock::iterator &I) {
297 ASSERT_SORTED(PopTable);
298 assert(StackTop > 0 && "Cannot pop empty stack!");
299 RegMap[Stack[--StackTop]] = ~0; // Update state
301 // Check to see if there is a popping version of this instruction...
302 int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), (*I)->getOpcode());
304 (*I)->setOpcode(Opcode);
305 if (Opcode == X86::FUCOMPPr)
306 (*I)->RemoveOperand(0);
308 } else { // Insert an explicit pop
309 MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(X86::ST0);
310 I = MBB->insert(I+1, MI);
314 static unsigned getFPReg(const MachineOperand &MO) {
315 assert(MO.isPhysicalRegister() && "Expected an FP register!");
316 unsigned Reg = MO.getReg();
317 assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");
318 return Reg - X86::FP0;
322 //===----------------------------------------------------------------------===//
323 // Instruction transformation implementation
324 //===----------------------------------------------------------------------===//
326 /// handleZeroArgFP - ST(0) = fld0 ST(0) = flds <mem>
328 void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
329 MachineInstr *MI = *I;
330 unsigned DestReg = getFPReg(MI->getOperand(0));
331 MI->RemoveOperand(0); // Remove the explicit ST(0) operand
333 // Result gets pushed on the stack...
337 /// handleOneArgFP - fst ST(0), <mem>
339 void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
340 MachineInstr *MI = *I;
341 assert(MI->getNumOperands() == 5 && "Can only handle fst* instructions!");
343 unsigned Reg = getFPReg(MI->getOperand(4));
344 bool KillsSrc = false;
345 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
346 E = LV->killed_end(MI); KI != E; ++KI)
347 KillsSrc |= KI->second == X86::FP0+Reg;
349 // FSTPr80 and FISTPr64 are strange because there are no non-popping versions.
350 // If we have one _and_ we don't want to pop the operand, duplicate the value
351 // on the stack instead of moving it. This ensure that popping the value is
354 if ((MI->getOpcode() == X86::FSTPr80 ||
355 MI->getOpcode() == X86::FISTPr64) && !KillsSrc) {
356 duplicateToTop(Reg, 7 /*temp register*/, I);
358 moveToTop(Reg, I); // Move to the top of the stack...
360 MI->RemoveOperand(4); // Remove explicit ST(0) operand
362 if (MI->getOpcode() == X86::FSTPr80 || MI->getOpcode() == X86::FISTPr64) {
363 assert(StackTop > 0 && "Stack empty??");
365 } else if (KillsSrc) { // Last use of operand?
370 //===----------------------------------------------------------------------===//
371 // Define tables of various ways to map pseudo instructions
374 // ForwardST0Table - Map: A = B op C into: ST(0) = ST(0) op ST(i)
375 static const TableEntry ForwardST0Table[] = {
376 { X86::FpADD, X86::FADDST0r },
377 { X86::FpDIV, X86::FDIVST0r },
378 { X86::FpMUL, X86::FMULST0r },
379 { X86::FpSUB, X86::FSUBST0r },
380 { X86::FpUCOM, X86::FUCOMr },
383 // ReverseST0Table - Map: A = B op C into: ST(0) = ST(i) op ST(0)
384 static const TableEntry ReverseST0Table[] = {
385 { X86::FpADD, X86::FADDST0r }, // commutative
386 { X86::FpDIV, X86::FDIVRST0r },
387 { X86::FpMUL, X86::FMULST0r }, // commutative
388 { X86::FpSUB, X86::FSUBRST0r },
392 // ForwardSTiTable - Map: A = B op C into: ST(i) = ST(0) op ST(i)
393 static const TableEntry ForwardSTiTable[] = {
394 { X86::FpADD, X86::FADDrST0 }, // commutative
395 { X86::FpDIV, X86::FDIVRrST0 },
396 { X86::FpMUL, X86::FMULrST0 }, // commutative
397 { X86::FpSUB, X86::FSUBRrST0 },
398 { X86::FpUCOM, X86::FUCOMr },
401 // ReverseSTiTable - Map: A = B op C into: ST(i) = ST(i) op ST(0)
402 static const TableEntry ReverseSTiTable[] = {
403 { X86::FpADD, X86::FADDrST0 },
404 { X86::FpDIV, X86::FDIVrST0 },
405 { X86::FpMUL, X86::FMULrST0 },
406 { X86::FpSUB, X86::FSUBrST0 },
411 /// handleTwoArgFP - Handle instructions like FADD and friends which are virtual
412 /// instructions which need to be simplified and possibly transformed.
414 /// Result: ST(0) = fsub ST(0), ST(i)
415 /// ST(i) = fsub ST(0), ST(i)
416 /// ST(0) = fsubr ST(0), ST(i)
417 /// ST(i) = fsubr ST(0), ST(i)
419 /// In addition to three address instructions, this also handles the FpUCOM
420 /// instruction which only has two operands, but no destination. This
421 /// instruction is also annoying because there is no "reverse" form of it
424 void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
425 ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
426 ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
427 MachineInstr *MI = *I;
429 unsigned NumOperands = MI->getNumOperands();
430 assert(NumOperands == 3 ||
431 (NumOperands == 2 && MI->getOpcode() == X86::FpUCOM) &&
432 "Illegal TwoArgFP instruction!");
433 unsigned Dest = getFPReg(MI->getOperand(0));
434 unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
435 unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
436 bool KillsOp0 = false, KillsOp1 = false;
438 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
439 E = LV->killed_end(MI); KI != E; ++KI) {
440 KillsOp0 |= (KI->second == X86::FP0+Op0);
441 KillsOp1 |= (KI->second == X86::FP0+Op1);
444 // If this is an FpUCOM instruction, we must make sure the first operand is on
445 // the top of stack, the other one can be anywhere...
446 if (MI->getOpcode() == X86::FpUCOM)
449 unsigned TOS = getStackEntry(0);
451 // One of our operands must be on the top of the stack. If neither is yet, we
453 if (Op0 != TOS && Op1 != TOS) { // No operand at TOS?
454 // We can choose to move either operand to the top of the stack. If one of
455 // the operands is killed by this instruction, we want that one so that we
456 // can update right on top of the old version.
458 moveToTop(Op0, I); // Move dead operand to TOS.
460 } else if (KillsOp1) {
464 // All of the operands are live after this instruction executes, so we
465 // cannot update on top of any operand. Because of this, we must
466 // duplicate one of the stack elements to the top. It doesn't matter
467 // which one we pick.
469 duplicateToTop(Op0, Dest, I);
473 } else if (!KillsOp0 && !KillsOp1 && MI->getOpcode() != X86::FpUCOM) {
474 // If we DO have one of our operands at the top of the stack, but we don't
475 // have a dead operand, we must duplicate one of the operands to a new slot
477 duplicateToTop(Op0, Dest, I);
482 // Now we know that one of our operands is on the top of the stack, and at
483 // least one of our operands is killed by this instruction.
484 assert((TOS == Op0 || TOS == Op1) &&
485 (KillsOp0 || KillsOp1 || MI->getOpcode() == X86::FpUCOM) &&
486 "Stack conditions not set up right!");
488 // We decide which form to use based on what is on the top of the stack, and
489 // which operand is killed by this instruction.
490 const TableEntry *InstTable;
491 bool isForward = TOS == Op0;
492 bool updateST0 = (TOS == Op0 && !KillsOp1) || (TOS == Op1 && !KillsOp0);
495 InstTable = ForwardST0Table;
497 InstTable = ReverseST0Table;
500 InstTable = ForwardSTiTable;
502 InstTable = ReverseSTiTable;
505 int Opcode = Lookup(InstTable, ARRAY_SIZE(ForwardST0Table), MI->getOpcode());
506 assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");
508 // NotTOS - The register which is not on the top of stack...
509 unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
511 // Replace the old instruction with a new instruction
512 *I = BuildMI(Opcode, 1).addReg(getSTReg(NotTOS));
514 // If both operands are killed, pop one off of the stack in addition to
515 // overwriting the other one.
516 if (KillsOp0 && KillsOp1 && Op0 != Op1) {
517 assert(!updateST0 && "Should have updated other operand!");
518 popStackAfter(I); // Pop the top of stack
521 // Insert an explicit pop of the "updated" operand for FUCOM
522 if (MI->getOpcode() == X86::FpUCOM) {
523 if (KillsOp0 && !KillsOp1)
524 popStackAfter(I); // If we kill the first operand, pop it!
525 else if (KillsOp1 && Op0 != Op1) {
526 if (getStackEntry(0) == Op1) {
527 popStackAfter(I); // If it's right at the top of stack, just pop it
529 // Otherwise, move the top of stack into the dead slot, killing the
530 // operand without having to add in an explicit xchg then pop.
532 unsigned STReg = getSTReg(Op1);
533 unsigned OldSlot = getSlot(Op1);
534 unsigned TopReg = Stack[StackTop-1];
535 Stack[OldSlot] = TopReg;
536 RegMap[TopReg] = OldSlot;
538 Stack[--StackTop] = ~0;
540 MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(STReg);
541 I = MBB->insert(I+1, MI);
546 // Update stack information so that we know the destination register is now on
548 if (MI->getOpcode() != X86::FpUCOM) {
549 unsigned UpdatedSlot = getSlot(updateST0 ? TOS : NotTOS);
550 assert(UpdatedSlot < StackTop && Dest < 7);
551 Stack[UpdatedSlot] = Dest;
552 RegMap[Dest] = UpdatedSlot;
554 delete MI; // Remove the old instruction
558 /// handleSpecialFP - Handle special instructions which behave unlike other
559 /// floating point instructions. This is primarily intended for use by pseudo
562 void FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
563 MachineInstr *MI = *I;
564 switch (MI->getOpcode()) {
565 default: assert(0 && "Unknown SpecialFP instruction!");
566 case X86::FpGETRESULT: // Appears immediately after a call returning FP type!
567 assert(StackTop == 0 && "Stack should be empty after a call!");
568 pushReg(getFPReg(MI->getOperand(0)));
570 case X86::FpSETRESULT:
571 assert(StackTop == 1 && "Stack should have one element on it to return!");
572 --StackTop; // "Forget" we have something on the top of stack!
575 unsigned SrcReg = getFPReg(MI->getOperand(1));
576 unsigned DestReg = getFPReg(MI->getOperand(0));
577 bool KillsSrc = false;
578 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
579 E = LV->killed_end(MI); KI != E; ++KI)
580 KillsSrc |= KI->second == X86::FP0+SrcReg;
583 // If the input operand is killed, we can just change the owner of the
584 // incoming stack slot into the result.
585 unsigned Slot = getSlot(SrcReg);
586 assert(Slot < 7 && DestReg < 7 && "FpMOV operands invalid!");
587 Stack[Slot] = DestReg;
588 RegMap[DestReg] = Slot;
591 // For FMOV we just duplicate the specified value to a new stack slot.
592 // This could be made better, but would require substantial changes.
593 duplicateToTop(SrcReg, DestReg, I);
599 I = MBB->erase(I)-1; // Remove the pseudo instruction