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"
31 Statistic<> NumFXCH("x86-codegen", "Number of fxch instructions inserted");
32 Statistic<> NumFP ("x86-codegen", "Number of floating point instructions");
34 struct FPS : public MachineFunctionPass {
35 virtual bool runOnMachineFunction(MachineFunction &MF);
37 virtual const char *getPassName() const { return "X86 FP Stackifier"; }
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<LiveVariables>();
41 MachineFunctionPass::getAnalysisUsage(AU);
44 LiveVariables *LV; // Live variable info for current function...
45 MachineBasicBlock *MBB; // Current basic block
46 unsigned Stack[8]; // FP<n> Registers in each stack slot...
47 unsigned RegMap[8]; // Track which stack slot contains each register
48 unsigned StackTop; // The current top of the FP stack.
50 void dumpStack() const {
51 std::cerr << "Stack contents:";
52 for (unsigned i = 0; i != StackTop; ++i) {
53 std::cerr << " FP" << Stack[i];
54 assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!");
59 // getSlot - Return the stack slot number a particular register number is
61 unsigned getSlot(unsigned RegNo) const {
62 assert(RegNo < 8 && "Regno out of range!");
66 // getStackEntry - Return the X86::FP<n> register in register ST(i)
67 unsigned getStackEntry(unsigned STi) const {
68 assert(STi < StackTop && "Access past stack top!");
69 return Stack[StackTop-1-STi];
72 // getSTReg - Return the X86::ST(i) register which contains the specified
74 unsigned getSTReg(unsigned RegNo) const {
75 return StackTop - 1 - getSlot(RegNo) + llvm::X86::ST0;
78 // pushReg - Push the specifiex FP<n> register onto the stack
79 void pushReg(unsigned Reg) {
80 assert(Reg < 8 && "Register number out of range!");
81 assert(StackTop < 8 && "Stack overflow!");
82 Stack[StackTop] = Reg;
83 RegMap[Reg] = StackTop++;
86 bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }
87 void moveToTop(unsigned RegNo, MachineBasicBlock::iterator &I) {
88 if (!isAtTop(RegNo)) {
89 unsigned Slot = getSlot(RegNo);
90 unsigned STReg = getSTReg(RegNo);
91 unsigned RegOnTop = getStackEntry(0);
93 // Swap the slots the regs are in
94 std::swap(RegMap[RegNo], RegMap[RegOnTop]);
96 // Swap stack slot contents
97 assert(RegMap[RegOnTop] < StackTop);
98 std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
100 // Emit an fxch to update the runtime processors version of the state
101 MachineInstr *MI = BuildMI(X86::FXCH, 1).addReg(STReg);
102 I = 1+MBB->insert(I, MI);
107 void duplicateToTop(unsigned RegNo, unsigned AsReg,
108 MachineBasicBlock::iterator &I) {
109 unsigned STReg = getSTReg(RegNo);
110 pushReg(AsReg); // New register on top of stack
112 MachineInstr *MI = BuildMI(X86::FLDrr, 1).addReg(STReg);
113 I = 1+MBB->insert(I, MI);
116 // popStackAfter - Pop the current value off of the top of the FP stack
117 // after the specified instruction.
118 void popStackAfter(MachineBasicBlock::iterator &I);
120 bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
122 void handleZeroArgFP(MachineBasicBlock::iterator &I);
123 void handleOneArgFP(MachineBasicBlock::iterator &I);
124 void handleTwoArgFP(MachineBasicBlock::iterator &I);
125 void handleSpecialFP(MachineBasicBlock::iterator &I);
129 FunctionPass *createX86FloatingPointStackifierPass() { return new FPS(); }
131 /// runOnMachineFunction - Loop over all of the basic blocks, transforming FP
132 /// register references into FP stack references.
134 bool FPS::runOnMachineFunction(MachineFunction &MF) {
135 LV = &getAnalysis<LiveVariables>();
138 bool Changed = false;
139 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
140 Changed |= processBasicBlock(MF, *I);
144 /// processBasicBlock - Loop over all of the instructions in the basic block,
145 /// transforming FP instructions into their stack form.
147 bool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {
148 const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
149 bool Changed = false;
152 for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
153 MachineInstr *MI = *I;
154 MachineInstr *PrevMI = I == BB.begin() ? 0 : *(I-1);
155 unsigned Flags = TII.get(MI->getOpcode()).TSFlags;
157 if ((Flags & X86II::FPTypeMask) == 0) continue; // Ignore non-fp insts!
159 ++NumFP; // Keep track of # of pseudo instrs
160 DEBUG(std::cerr << "\nFPInst:\t";
161 MI->print(std::cerr, MF.getTarget()));
163 // Get dead variables list now because the MI pointer may be deleted as part
165 LiveVariables::killed_iterator IB = LV->dead_begin(MI);
166 LiveVariables::killed_iterator IE = LV->dead_end(MI);
168 DEBUG(const MRegisterInfo *MRI = MF.getTarget().getRegisterInfo();
169 LiveVariables::killed_iterator I = LV->killed_begin(MI);
170 LiveVariables::killed_iterator E = LV->killed_end(MI);
172 std::cerr << "Killed Operands:";
174 std::cerr << " %" << MRI->getName(I->second);
178 switch (Flags & X86II::FPTypeMask) {
179 case X86II::ZeroArgFP: handleZeroArgFP(I); break;
180 case X86II::OneArgFP: handleOneArgFP(I); break;
182 case X86II::OneArgFPRW: // ST(0) = fsqrt(ST(0))
183 assert(0 && "FP instr type not handled yet!");
185 case X86II::TwoArgFP: handleTwoArgFP(I); break;
186 case X86II::SpecialFP: handleSpecialFP(I); break;
187 default: assert(0 && "Unknown FP Type!");
190 // Check to see if any of the values defined by this instruction are dead
191 // after definition. If so, pop them.
192 for (; IB != IE; ++IB) {
193 unsigned Reg = IB->second;
194 if (Reg >= X86::FP0 && Reg <= X86::FP6) {
195 DEBUG(std::cerr << "Register FP#" << Reg-X86::FP0 << " is dead!\n");
196 ++I; // Insert fxch AFTER the instruction
197 moveToTop(Reg-X86::FP0, I); // Insert fxch if necessary
198 --I; // Move to fxch or old instruction
199 popStackAfter(I); // Pop the top of the stack, killing value
203 // Print out all of the instructions expanded to if -debug
204 DEBUG(if (*I == PrevMI) {
205 std::cerr<< "Just deleted pseudo instruction\n";
207 MachineBasicBlock::iterator Start = I;
208 // Rewind to first instruction newly inserted.
209 while (Start != BB.begin() && *(Start-1) != PrevMI) --Start;
210 std::cerr << "Inserted instructions:\n\t";
211 (*Start)->print(std::cerr, MF.getTarget());
212 while (++Start != I+1);
220 assert(StackTop == 0 && "Stack not empty at end of basic block?");
224 //===----------------------------------------------------------------------===//
225 // Efficient Lookup Table Support
226 //===----------------------------------------------------------------------===//
231 bool operator<(const TableEntry &TE) const { return from < TE.from; }
232 bool operator<(unsigned V) const { return from < V; }
235 static bool TableIsSorted(const TableEntry *Table, unsigned NumEntries) {
236 for (unsigned i = 0; i != NumEntries-1; ++i)
237 if (!(Table[i] < Table[i+1])) return false;
241 static int Lookup(const TableEntry *Table, unsigned N, unsigned Opcode) {
242 const TableEntry *I = std::lower_bound(Table, Table+N, Opcode);
243 if (I != Table+N && I->from == Opcode)
248 #define ARRAY_SIZE(TABLE) \
249 (sizeof(TABLE)/sizeof(TABLE[0]))
252 #define ASSERT_SORTED(TABLE)
254 #define ASSERT_SORTED(TABLE) \
255 { static bool TABLE##Checked = false; \
256 if (!TABLE##Checked) \
257 assert(TableIsSorted(TABLE, ARRAY_SIZE(TABLE)) && \
258 "All lookup tables must be sorted for efficient access!"); \
263 //===----------------------------------------------------------------------===//
265 //===----------------------------------------------------------------------===//
267 // PopTable - Sorted map of instructions to their popping version. The first
268 // element is an instruction, the second is the version which pops.
270 static const TableEntry PopTable[] = {
271 { X86::FADDrST0 , X86::FADDPrST0 },
273 { X86::FDIVRrST0, X86::FDIVRPrST0 },
274 { X86::FDIVrST0 , X86::FDIVPrST0 },
276 { X86::FISTr16 , X86::FISTPr16 },
277 { X86::FISTr32 , X86::FISTPr32 },
279 { X86::FMULrST0 , X86::FMULPrST0 },
281 { X86::FSTr32 , X86::FSTPr32 },
282 { X86::FSTr64 , X86::FSTPr64 },
283 { X86::FSTrr , X86::FSTPrr },
285 { X86::FSUBRrST0, X86::FSUBRPrST0 },
286 { X86::FSUBrST0 , X86::FSUBPrST0 },
288 { X86::FUCOMPr , X86::FUCOMPPr },
289 { X86::FUCOMr , X86::FUCOMPr },
292 /// popStackAfter - Pop the current value off of the top of the FP stack after
293 /// the specified instruction. This attempts to be sneaky and combine the pop
294 /// into the instruction itself if possible. The iterator is left pointing to
295 /// the last instruction, be it a new pop instruction inserted, or the old
296 /// instruction if it was modified in place.
298 void FPS::popStackAfter(MachineBasicBlock::iterator &I) {
299 ASSERT_SORTED(PopTable);
300 assert(StackTop > 0 && "Cannot pop empty stack!");
301 RegMap[Stack[--StackTop]] = ~0; // Update state
303 // Check to see if there is a popping version of this instruction...
304 int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), (*I)->getOpcode());
306 (*I)->setOpcode(Opcode);
307 if (Opcode == X86::FUCOMPPr)
308 (*I)->RemoveOperand(0);
310 } else { // Insert an explicit pop
311 MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(X86::ST0);
312 I = MBB->insert(I+1, MI);
316 static unsigned getFPReg(const MachineOperand &MO) {
317 assert(MO.isPhysicalRegister() && "Expected an FP register!");
318 unsigned Reg = MO.getReg();
319 assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");
320 return Reg - X86::FP0;
324 //===----------------------------------------------------------------------===//
325 // Instruction transformation implementation
326 //===----------------------------------------------------------------------===//
328 /// handleZeroArgFP - ST(0) = fld0 ST(0) = flds <mem>
330 void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
331 MachineInstr *MI = *I;
332 unsigned DestReg = getFPReg(MI->getOperand(0));
333 MI->RemoveOperand(0); // Remove the explicit ST(0) operand
335 // Result gets pushed on the stack...
339 /// handleOneArgFP - fst ST(0), <mem>
341 void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
342 MachineInstr *MI = *I;
343 assert(MI->getNumOperands() == 5 && "Can only handle fst* instructions!");
345 unsigned Reg = getFPReg(MI->getOperand(4));
346 bool KillsSrc = false;
347 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
348 E = LV->killed_end(MI); KI != E; ++KI)
349 KillsSrc |= KI->second == X86::FP0+Reg;
351 // FSTPr80 and FISTPr64 are strange because there are no non-popping versions.
352 // If we have one _and_ we don't want to pop the operand, duplicate the value
353 // on the stack instead of moving it. This ensure that popping the value is
356 if ((MI->getOpcode() == X86::FSTPr80 ||
357 MI->getOpcode() == X86::FISTPr64) && !KillsSrc) {
358 duplicateToTop(Reg, 7 /*temp register*/, I);
360 moveToTop(Reg, I); // Move to the top of the stack...
362 MI->RemoveOperand(4); // Remove explicit ST(0) operand
364 if (MI->getOpcode() == X86::FSTPr80 || MI->getOpcode() == X86::FISTPr64) {
365 assert(StackTop > 0 && "Stack empty??");
367 } else if (KillsSrc) { // Last use of operand?
372 //===----------------------------------------------------------------------===//
373 // Define tables of various ways to map pseudo instructions
376 // ForwardST0Table - Map: A = B op C into: ST(0) = ST(0) op ST(i)
377 static const TableEntry ForwardST0Table[] = {
378 { X86::FpADD, X86::FADDST0r },
379 { X86::FpDIV, X86::FDIVST0r },
380 { X86::FpMUL, X86::FMULST0r },
381 { X86::FpSUB, X86::FSUBST0r },
382 { X86::FpUCOM, X86::FUCOMr },
385 // ReverseST0Table - Map: A = B op C into: ST(0) = ST(i) op ST(0)
386 static const TableEntry ReverseST0Table[] = {
387 { X86::FpADD, X86::FADDST0r }, // commutative
388 { X86::FpDIV, X86::FDIVRST0r },
389 { X86::FpMUL, X86::FMULST0r }, // commutative
390 { X86::FpSUB, X86::FSUBRST0r },
394 // ForwardSTiTable - Map: A = B op C into: ST(i) = ST(0) op ST(i)
395 static const TableEntry ForwardSTiTable[] = {
396 { X86::FpADD, X86::FADDrST0 }, // commutative
397 { X86::FpDIV, X86::FDIVRrST0 },
398 { X86::FpMUL, X86::FMULrST0 }, // commutative
399 { X86::FpSUB, X86::FSUBRrST0 },
400 { X86::FpUCOM, X86::FUCOMr },
403 // ReverseSTiTable - Map: A = B op C into: ST(i) = ST(i) op ST(0)
404 static const TableEntry ReverseSTiTable[] = {
405 { X86::FpADD, X86::FADDrST0 },
406 { X86::FpDIV, X86::FDIVrST0 },
407 { X86::FpMUL, X86::FMULrST0 },
408 { X86::FpSUB, X86::FSUBrST0 },
413 /// handleTwoArgFP - Handle instructions like FADD and friends which are virtual
414 /// instructions which need to be simplified and possibly transformed.
416 /// Result: ST(0) = fsub ST(0), ST(i)
417 /// ST(i) = fsub ST(0), ST(i)
418 /// ST(0) = fsubr ST(0), ST(i)
419 /// ST(i) = fsubr ST(0), ST(i)
421 /// In addition to three address instructions, this also handles the FpUCOM
422 /// instruction which only has two operands, but no destination. This
423 /// instruction is also annoying because there is no "reverse" form of it
426 void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
427 ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
428 ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
429 MachineInstr *MI = *I;
431 unsigned NumOperands = MI->getNumOperands();
432 assert(NumOperands == 3 ||
433 (NumOperands == 2 && MI->getOpcode() == X86::FpUCOM) &&
434 "Illegal TwoArgFP instruction!");
435 unsigned Dest = getFPReg(MI->getOperand(0));
436 unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
437 unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
438 bool KillsOp0 = false, KillsOp1 = false;
440 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
441 E = LV->killed_end(MI); KI != E; ++KI) {
442 KillsOp0 |= (KI->second == X86::FP0+Op0);
443 KillsOp1 |= (KI->second == X86::FP0+Op1);
446 // If this is an FpUCOM instruction, we must make sure the first operand is on
447 // the top of stack, the other one can be anywhere...
448 if (MI->getOpcode() == X86::FpUCOM)
451 unsigned TOS = getStackEntry(0);
453 // One of our operands must be on the top of the stack. If neither is yet, we
455 if (Op0 != TOS && Op1 != TOS) { // No operand at TOS?
456 // We can choose to move either operand to the top of the stack. If one of
457 // the operands is killed by this instruction, we want that one so that we
458 // can update right on top of the old version.
460 moveToTop(Op0, I); // Move dead operand to TOS.
462 } else if (KillsOp1) {
466 // All of the operands are live after this instruction executes, so we
467 // cannot update on top of any operand. Because of this, we must
468 // duplicate one of the stack elements to the top. It doesn't matter
469 // which one we pick.
471 duplicateToTop(Op0, Dest, I);
475 } else if (!KillsOp0 && !KillsOp1 && MI->getOpcode() != X86::FpUCOM) {
476 // If we DO have one of our operands at the top of the stack, but we don't
477 // have a dead operand, we must duplicate one of the operands to a new slot
479 duplicateToTop(Op0, Dest, I);
484 // Now we know that one of our operands is on the top of the stack, and at
485 // least one of our operands is killed by this instruction.
486 assert((TOS == Op0 || TOS == Op1) &&
487 (KillsOp0 || KillsOp1 || MI->getOpcode() == X86::FpUCOM) &&
488 "Stack conditions not set up right!");
490 // We decide which form to use based on what is on the top of the stack, and
491 // which operand is killed by this instruction.
492 const TableEntry *InstTable;
493 bool isForward = TOS == Op0;
494 bool updateST0 = (TOS == Op0 && !KillsOp1) || (TOS == Op1 && !KillsOp0);
497 InstTable = ForwardST0Table;
499 InstTable = ReverseST0Table;
502 InstTable = ForwardSTiTable;
504 InstTable = ReverseSTiTable;
507 int Opcode = Lookup(InstTable, ARRAY_SIZE(ForwardST0Table), MI->getOpcode());
508 assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");
510 // NotTOS - The register which is not on the top of stack...
511 unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
513 // Replace the old instruction with a new instruction
514 *I = BuildMI(Opcode, 1).addReg(getSTReg(NotTOS));
516 // If both operands are killed, pop one off of the stack in addition to
517 // overwriting the other one.
518 if (KillsOp0 && KillsOp1 && Op0 != Op1) {
519 assert(!updateST0 && "Should have updated other operand!");
520 popStackAfter(I); // Pop the top of stack
523 // Insert an explicit pop of the "updated" operand for FUCOM
524 if (MI->getOpcode() == X86::FpUCOM) {
525 if (KillsOp0 && !KillsOp1)
526 popStackAfter(I); // If we kill the first operand, pop it!
527 else if (KillsOp1 && Op0 != Op1) {
528 if (getStackEntry(0) == Op1) {
529 popStackAfter(I); // If it's right at the top of stack, just pop it
531 // Otherwise, move the top of stack into the dead slot, killing the
532 // operand without having to add in an explicit xchg then pop.
534 unsigned STReg = getSTReg(Op1);
535 unsigned OldSlot = getSlot(Op1);
536 unsigned TopReg = Stack[StackTop-1];
537 Stack[OldSlot] = TopReg;
538 RegMap[TopReg] = OldSlot;
540 Stack[--StackTop] = ~0;
542 MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(STReg);
543 I = MBB->insert(I+1, MI);
548 // Update stack information so that we know the destination register is now on
550 if (MI->getOpcode() != X86::FpUCOM) {
551 unsigned UpdatedSlot = getSlot(updateST0 ? TOS : NotTOS);
552 assert(UpdatedSlot < StackTop && Dest < 7);
553 Stack[UpdatedSlot] = Dest;
554 RegMap[Dest] = UpdatedSlot;
556 delete MI; // Remove the old instruction
560 /// handleSpecialFP - Handle special instructions which behave unlike other
561 /// floating point instructions. This is primarily intended for use by pseudo
564 void FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
565 MachineInstr *MI = *I;
566 switch (MI->getOpcode()) {
567 default: assert(0 && "Unknown SpecialFP instruction!");
568 case X86::FpGETRESULT: // Appears immediately after a call returning FP type!
569 assert(StackTop == 0 && "Stack should be empty after a call!");
570 pushReg(getFPReg(MI->getOperand(0)));
572 case X86::FpSETRESULT:
573 assert(StackTop == 1 && "Stack should have one element on it to return!");
574 --StackTop; // "Forget" we have something on the top of stack!
577 unsigned SrcReg = getFPReg(MI->getOperand(1));
578 unsigned DestReg = getFPReg(MI->getOperand(0));
579 bool KillsSrc = false;
580 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
581 E = LV->killed_end(MI); KI != E; ++KI)
582 KillsSrc |= KI->second == X86::FP0+SrcReg;
585 // If the input operand is killed, we can just change the owner of the
586 // incoming stack slot into the result.
587 unsigned Slot = getSlot(SrcReg);
588 assert(Slot < 7 && DestReg < 7 && "FpMOV operands invalid!");
589 Stack[Slot] = DestReg;
590 RegMap[DestReg] = Slot;
593 // For FMOV we just duplicate the specified value to a new stack slot.
594 // This could be made better, but would require substantial changes.
595 duplicateToTop(SrcReg, DestReg, I);
601 I = MBB->erase(I)-1; // Remove the pseudo instruction
604 } // End llvm namespace