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 //===----------------------------------------------------------------------===//
9 #include "X86InstrInfo.h"
10 #include "llvm/CodeGen/MachineFunctionPass.h"
11 #include "llvm/CodeGen/MachineInstrBuilder.h"
12 #include "llvm/CodeGen/LiveVariables.h"
13 #include "llvm/Target/TargetInstrInfo.h"
14 #include "llvm/Target/TargetMachine.h"
15 #include "Support/Statistic.h"
20 Statistic<> NumFXCH("x86-codegen", "Number of fxch instructions inserted");
21 Statistic<> NumFP ("x86-codegen", "Number of floating point instructions");
23 struct FPS : public MachineFunctionPass {
24 virtual bool runOnMachineFunction(MachineFunction &MF);
26 virtual const char *getPassName() const { return "X86 FP Stackifier"; }
28 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
29 AU.addRequired<LiveVariables>();
30 MachineFunctionPass::getAnalysisUsage(AU);
33 LiveVariables *LV; // Live variable info for current function...
34 MachineBasicBlock *MBB; // Current basic block
35 unsigned Stack[8]; // FP<n> Registers in each stack slot...
36 unsigned RegMap[8]; // Track which stack slot contains each register
37 unsigned StackTop; // The current top of the FP stack.
39 void dumpStack() const {
40 std::cerr << "Stack contents:";
41 for (unsigned i = 0; i != StackTop; ++i) {
42 std::cerr << " FP" << Stack[i];
43 assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!");
48 // getSlot - Return the stack slot number a particular register number is
50 unsigned getSlot(unsigned RegNo) const {
51 assert(RegNo < 8 && "Regno out of range!");
55 // getStackEntry - Return the X86::FP<n> register in register ST(i)
56 unsigned getStackEntry(unsigned STi) const {
57 assert(STi < StackTop && "Access past stack top!");
58 return Stack[StackTop-1-STi];
61 // getSTReg - Return the X86::ST(i) register which contains the specified
63 unsigned getSTReg(unsigned RegNo) const {
64 return StackTop - 1 - getSlot(RegNo) + X86::ST0;
67 // pushReg - Push the specifiex FP<n> register onto the stack
68 void pushReg(unsigned Reg) {
69 assert(Reg < 8 && "Register number out of range!");
70 assert(StackTop < 8 && "Stack overflow!");
71 Stack[StackTop] = Reg;
72 RegMap[Reg] = StackTop++;
75 bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }
76 void moveToTop(unsigned RegNo, MachineBasicBlock::iterator &I) {
77 if (!isAtTop(RegNo)) {
78 unsigned Slot = getSlot(RegNo);
79 unsigned STReg = getSTReg(RegNo);
80 unsigned RegOnTop = getStackEntry(0);
82 // Swap the slots the regs are in
83 std::swap(RegMap[RegNo], RegMap[RegOnTop]);
85 // Swap stack slot contents
86 assert(RegMap[RegOnTop] < StackTop);
87 std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
89 // Emit an fxch to update the runtime processors version of the state
90 MachineInstr *MI = BuildMI(X86::FXCH, 1).addReg(STReg);
91 I = 1+MBB->insert(I, MI);
96 void duplicateToTop(unsigned RegNo, unsigned AsReg,
97 MachineBasicBlock::iterator &I) {
98 unsigned STReg = getSTReg(RegNo);
99 pushReg(AsReg); // New register on top of stack
101 MachineInstr *MI = BuildMI(X86::FLDrr, 1).addReg(STReg);
102 I = 1+MBB->insert(I, MI);
105 // popStackAfter - Pop the current value off of the top of the FP stack
106 // after the specified instruction.
107 void popStackAfter(MachineBasicBlock::iterator &I);
109 bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
111 void handleZeroArgFP(MachineBasicBlock::iterator &I);
112 void handleOneArgFP(MachineBasicBlock::iterator &I);
113 void handleTwoArgFP(MachineBasicBlock::iterator &I);
114 void handleSpecialFP(MachineBasicBlock::iterator &I);
118 Pass *createX86FloatingPointStackifierPass() { return new FPS(); }
120 /// runOnMachineFunction - Loop over all of the basic blocks, transforming FP
121 /// register references into FP stack references.
123 bool FPS::runOnMachineFunction(MachineFunction &MF) {
124 LV = &getAnalysis<LiveVariables>();
127 bool Changed = false;
128 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
129 Changed |= processBasicBlock(MF, *I);
133 /// processBasicBlock - Loop over all of the instructions in the basic block,
134 /// transforming FP instructions into their stack form.
136 bool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {
137 const TargetInstrInfo &TII = MF.getTarget().getInstrInfo();
138 bool Changed = false;
141 for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
142 MachineInstr *MI = *I;
143 MachineInstr *PrevMI = I == BB.begin() ? 0 : *(I-1);
144 unsigned Flags = TII.get(MI->getOpcode()).TSFlags;
146 if ((Flags & X86II::FPTypeMask) == 0) continue; // Ignore non-fp insts!
148 ++NumFP; // Keep track of # of pseudo instrs
149 DEBUG(std::cerr << "\nFPInst:\t";
150 MI->print(std::cerr, MF.getTarget()));
152 // Get dead variables list now because the MI pointer may be deleted as part
154 LiveVariables::killed_iterator IB = LV->dead_begin(MI);
155 LiveVariables::killed_iterator IE = LV->dead_end(MI);
157 DEBUG(const MRegisterInfo *MRI = MF.getTarget().getRegisterInfo();
158 LiveVariables::killed_iterator I = LV->killed_begin(MI);
159 LiveVariables::killed_iterator E = LV->killed_end(MI);
161 std::cerr << "Killed Operands:";
163 std::cerr << " %" << MRI->getName(I->second);
167 switch (Flags & X86II::FPTypeMask) {
168 case X86II::ZeroArgFP: handleZeroArgFP(I); break;
169 case X86II::OneArgFP: handleOneArgFP(I); break;
171 case X86II::OneArgFPRW: // ST(0) = fsqrt(ST(0))
172 assert(0 && "FP instr type not handled yet!");
174 case X86II::TwoArgFP: handleTwoArgFP(I); break;
175 case X86II::SpecialFP: handleSpecialFP(I); break;
176 default: assert(0 && "Unknown FP Type!");
179 // Check to see if any of the values defined by this instruction are dead
180 // after definition. If so, pop them.
181 for (; IB != IE; ++IB) {
182 unsigned Reg = IB->second;
183 if (Reg >= X86::FP0 && Reg <= X86::FP6) {
184 DEBUG(std::cerr << "Register FP#" << Reg-X86::FP0 << " is dead!\n");
185 ++I; // Insert fxch AFTER the instruction
186 moveToTop(Reg-X86::FP0, I); // Insert fxch if neccesary
187 --I; // Move to fxch or old instruction
188 popStackAfter(I); // Pop the top of the stack, killing value
192 // Print out all of the instructions expanded to if -debug
193 DEBUG(if (*I == PrevMI) {
194 std::cerr<< "Just deleted pseudo instruction\n";
196 MachineBasicBlock::iterator Start = I;
197 // Rewind to first instruction newly inserted.
198 while (Start != BB.begin() && *(Start-1) != PrevMI) --Start;
199 std::cerr << "Inserted instructions:\n";
200 do TII.print(*Start, std::cerr << "\t", MF.getTarget());
201 while (++Start != I+1);
209 assert(StackTop == 0 && "Stack not empty at end of basic block?");
213 //===----------------------------------------------------------------------===//
214 // Efficient Lookup Table Support
215 //===----------------------------------------------------------------------===//
220 bool operator<(const TableEntry &TE) const { return from < TE.from; }
221 bool operator<(unsigned V) const { return from < V; }
224 static bool TableIsSorted(const TableEntry *Table, unsigned NumEntries) {
225 for (unsigned i = 0; i != NumEntries-1; ++i)
226 if (!(Table[i] < Table[i+1])) return false;
230 static int Lookup(const TableEntry *Table, unsigned N, unsigned Opcode) {
231 const TableEntry *I = std::lower_bound(Table, Table+N, Opcode);
232 if (I != Table+N && I->from == Opcode)
237 #define ARRAY_SIZE(TABLE) \
238 (sizeof(TABLE)/sizeof(TABLE[0]))
241 #define ASSERT_SORTED(TABLE)
243 #define ASSERT_SORTED(TABLE) \
244 { static bool TABLE##Checked = false; \
245 if (!TABLE##Checked) \
246 assert(TableIsSorted(TABLE, ARRAY_SIZE(TABLE)) && \
247 "All lookup tables must be sorted for efficient access!"); \
252 //===----------------------------------------------------------------------===//
254 //===----------------------------------------------------------------------===//
256 // PopTable - Sorted map of instructions to their popping version. The first
257 // element is an instruction, the second is the version which pops.
259 static const TableEntry PopTable[] = {
260 { X86::FSTr32 , X86::FSTPr32 },
261 { X86::FSTr64 , X86::FSTPr64 },
262 { X86::FSTrr , X86::FSTPrr },
263 { X86::FISTr16 , X86::FISTPr16 },
264 { X86::FISTr32 , X86::FISTPr32 },
266 { X86::FADDrST0 , X86::FADDPrST0 },
267 { X86::FSUBrST0 , X86::FSUBPrST0 },
268 { X86::FSUBRrST0, X86::FSUBRPrST0 },
269 { X86::FMULrST0 , X86::FMULPrST0 },
270 { X86::FDIVrST0 , X86::FDIVPrST0 },
271 { X86::FDIVRrST0, X86::FDIVRPrST0 },
273 { X86::FUCOMr , X86::FUCOMPr },
274 { X86::FUCOMPr , X86::FUCOMPPr },
277 /// popStackAfter - Pop the current value off of the top of the FP stack after
278 /// the specified instruction. This attempts to be sneaky and combine the pop
279 /// into the instruction itself if possible. The iterator is left pointing to
280 /// the last instruction, be it a new pop instruction inserted, or the old
281 /// instruction if it was modified in place.
283 void FPS::popStackAfter(MachineBasicBlock::iterator &I) {
284 ASSERT_SORTED(PopTable);
285 assert(StackTop > 0 && "Cannot pop empty stack!");
286 RegMap[Stack[--StackTop]] = ~0; // Update state
288 // Check to see if there is a popping version of this instruction...
289 int Opcode = Lookup(PopTable, ARRAY_SIZE(PopTable), (*I)->getOpcode());
291 (*I)->setOpcode(Opcode);
292 if (Opcode == X86::FUCOMPPr)
293 (*I)->RemoveOperand(0);
295 } else { // Insert an explicit pop
296 MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(X86::ST0);
297 I = MBB->insert(I+1, MI);
301 static unsigned getFPReg(const MachineOperand &MO) {
302 assert(MO.isPhysicalRegister() && "Expected an FP register!");
303 unsigned Reg = MO.getReg();
304 assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");
305 return Reg - X86::FP0;
309 //===----------------------------------------------------------------------===//
310 // Instruction transformation implementation
311 //===----------------------------------------------------------------------===//
313 /// handleZeroArgFP - ST(0) = fld0 ST(0) = flds <mem>
315 void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
316 MachineInstr *MI = *I;
317 unsigned DestReg = getFPReg(MI->getOperand(0));
318 MI->RemoveOperand(0); // Remove the explicit ST(0) operand
320 // Result gets pushed on the stack...
324 /// handleOneArgFP - fst ST(0), <mem>
326 void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
327 MachineInstr *MI = *I;
328 assert(MI->getNumOperands() == 5 && "Can only handle fst* instructions!");
330 unsigned Reg = getFPReg(MI->getOperand(4));
331 bool KillsSrc = false;
332 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
333 E = LV->killed_end(MI); KI != E; ++KI)
334 KillsSrc |= KI->second == X86::FP0+Reg;
336 // FSTPr80 and FISTPr64 are strange because there are no non-popping versions.
337 // If we have one _and_ we don't want to pop the operand, duplicate the value
338 // on the stack instead of moving it. This ensure that popping the value is
341 if ((MI->getOpcode() == X86::FSTPr80 ||
342 MI->getOpcode() == X86::FISTPr64) && !KillsSrc) {
343 duplicateToTop(Reg, 7 /*temp register*/, I);
345 moveToTop(Reg, I); // Move to the top of the stack...
347 MI->RemoveOperand(4); // Remove explicit ST(0) operand
349 if (MI->getOpcode() == X86::FSTPr80 || MI->getOpcode() == X86::FISTPr64) {
350 assert(StackTop > 0 && "Stack empty??");
352 } else if (KillsSrc) { // Last use of operand?
357 //===----------------------------------------------------------------------===//
358 // Define tables of various ways to map pseudo instructions
361 // ForwardST0Table - Map: A = B op C into: ST(0) = ST(0) op ST(i)
362 static const TableEntry ForwardST0Table[] = {
363 { X86::FpADD, X86::FADDST0r },
364 { X86::FpSUB, X86::FSUBST0r },
365 { X86::FpMUL, X86::FMULST0r },
366 { X86::FpDIV, X86::FDIVST0r },
367 { X86::FpUCOM, X86::FUCOMr },
370 // ReverseST0Table - Map: A = B op C into: ST(0) = ST(i) op ST(0)
371 static const TableEntry ReverseST0Table[] = {
372 { X86::FpADD, X86::FADDST0r }, // commutative
373 { X86::FpSUB, X86::FSUBRST0r },
374 { X86::FpMUL, X86::FMULST0r }, // commutative
375 { X86::FpDIV, X86::FDIVRST0r },
379 // ForwardSTiTable - Map: A = B op C into: ST(i) = ST(0) op ST(i)
380 static const TableEntry ForwardSTiTable[] = {
381 { X86::FpADD, X86::FADDrST0 }, // commutative
382 { X86::FpSUB, X86::FSUBRrST0 },
383 { X86::FpMUL, X86::FMULrST0 }, // commutative
384 { X86::FpDIV, X86::FDIVRrST0 },
385 { X86::FpUCOM, X86::FUCOMr },
388 // ReverseSTiTable - Map: A = B op C into: ST(i) = ST(i) op ST(0)
389 static const TableEntry ReverseSTiTable[] = {
390 { X86::FpADD, X86::FADDrST0 },
391 { X86::FpSUB, X86::FSUBrST0 },
392 { X86::FpMUL, X86::FMULrST0 },
393 { X86::FpDIV, X86::FDIVrST0 },
398 /// handleTwoArgFP - Handle instructions like FADD and friends which are virtual
399 /// instructions which need to be simplified and possibly transformed.
401 /// Result: ST(0) = fsub ST(0), ST(i)
402 /// ST(i) = fsub ST(0), ST(i)
403 /// ST(0) = fsubr ST(0), ST(i)
404 /// ST(i) = fsubr ST(0), ST(i)
406 /// In addition to three address instructions, this also handles the FpUCOM
407 /// instruction which only has two operands, but no destination. This
408 /// instruction is also annoying because there is no "reverse" form of it
411 void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
412 ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
413 ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
414 MachineInstr *MI = *I;
416 unsigned NumOperands = MI->getNumOperands();
417 assert(NumOperands == 3 ||
418 (NumOperands == 2 && MI->getOpcode() == X86::FpUCOM) &&
419 "Illegal TwoArgFP instruction!");
420 unsigned Dest = getFPReg(MI->getOperand(0));
421 unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
422 unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
423 bool KillsOp0 = false, KillsOp1 = false;
425 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
426 E = LV->killed_end(MI); KI != E; ++KI) {
427 KillsOp0 |= (KI->second == X86::FP0+Op0);
428 KillsOp1 |= (KI->second == X86::FP0+Op1);
431 // If this is an FpUCOM instruction, we must make sure the first operand is on
432 // the top of stack, the other one can be anywhere...
433 if (MI->getOpcode() == X86::FpUCOM)
436 unsigned TOS = getStackEntry(0);
438 // One of our operands must be on the top of the stack. If neither is yet, we
440 if (Op0 != TOS && Op1 != TOS) { // No operand at TOS?
441 // We can choose to move either operand to the top of the stack. If one of
442 // the operands is killed by this instruction, we want that one so that we
443 // can update right on top of the old version.
445 moveToTop(Op0, I); // Move dead operand to TOS.
447 } else if (KillsOp1) {
451 // All of the operands are live after this instruction executes, so we
452 // cannot update on top of any operand. Because of this, we must
453 // duplicate one of the stack elements to the top. It doesn't matter
454 // which one we pick.
456 duplicateToTop(Op0, Dest, I);
460 } else if (!KillsOp0 && !KillsOp1 && MI->getOpcode() != X86::FpUCOM) {
461 // If we DO have one of our operands at the top of the stack, but we don't
462 // have a dead operand, we must duplicate one of the operands to a new slot
464 duplicateToTop(Op0, Dest, I);
469 // Now we know that one of our operands is on the top of the stack, and at
470 // least one of our operands is killed by this instruction.
471 assert((TOS == Op0 || TOS == Op1) &&
472 (KillsOp0 || KillsOp1 || MI->getOpcode() == X86::FpUCOM) &&
473 "Stack conditions not set up right!");
475 // We decide which form to use based on what is on the top of the stack, and
476 // which operand is killed by this instruction.
477 const TableEntry *InstTable;
478 bool isForward = TOS == Op0;
479 bool updateST0 = (TOS == Op0 && !KillsOp1) || (TOS == Op1 && !KillsOp0);
482 InstTable = ForwardST0Table;
484 InstTable = ReverseST0Table;
487 InstTable = ForwardSTiTable;
489 InstTable = ReverseSTiTable;
492 int Opcode = Lookup(InstTable, ARRAY_SIZE(ForwardST0Table), MI->getOpcode());
493 assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");
495 // NotTOS - The register which is not on the top of stack...
496 unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
498 // Replace the old instruction with a new instruction
499 *I = BuildMI(Opcode, 1).addReg(getSTReg(NotTOS));
501 // If both operands are killed, pop one off of the stack in addition to
502 // overwriting the other one.
503 if (KillsOp0 && KillsOp1 && Op0 != Op1) {
504 assert(!updateST0 && "Should have updated other operand!");
505 popStackAfter(I); // Pop the top of stack
508 // Insert an explicit pop of the "updated" operand for FUCOM
509 if (MI->getOpcode() == X86::FpUCOM) {
510 if (KillsOp0 && !KillsOp1)
511 popStackAfter(I); // If we kill the first operand, pop it!
512 else if (KillsOp1 && Op0 != Op1) {
513 if (getStackEntry(0) == Op1) {
514 popStackAfter(I); // If it's right at the top of stack, just pop it
516 // Otherwise, move the top of stack into the dead slot, killing the
517 // operand without having to add in an explicit xchg then pop.
519 unsigned STReg = getSTReg(Op1);
520 unsigned OldSlot = getSlot(Op1);
521 unsigned TopReg = Stack[StackTop-1];
522 Stack[OldSlot] = TopReg;
523 RegMap[TopReg] = OldSlot;
525 Stack[--StackTop] = ~0;
527 MachineInstr *MI = BuildMI(X86::FSTPrr, 1).addReg(STReg);
528 I = MBB->insert(I+1, MI);
533 // Update stack information so that we know the destination register is now on
535 if (MI->getOpcode() != X86::FpUCOM) {
536 unsigned UpdatedSlot = getSlot(updateST0 ? TOS : NotTOS);
537 assert(UpdatedSlot < StackTop && Dest < 7);
538 Stack[UpdatedSlot] = Dest;
539 RegMap[Dest] = UpdatedSlot;
541 delete MI; // Remove the old instruction
545 /// handleSpecialFP - Handle special instructions which behave unlike other
546 /// floating point instructions. This is primarily inteaded for use by pseudo
549 void FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
550 MachineInstr *MI = *I;
551 switch (MI->getOpcode()) {
552 default: assert(0 && "Unknown SpecialFP instruction!");
553 case X86::FpGETRESULT: // Appears immediately after a call returning FP type!
554 assert(StackTop == 0 && "Stack should be empty after a call!");
555 pushReg(getFPReg(MI->getOperand(0)));
557 case X86::FpSETRESULT:
558 assert(StackTop == 1 && "Stack should have one element on it to return!");
559 --StackTop; // "Forget" we have something on the top of stack!
562 unsigned SrcReg = getFPReg(MI->getOperand(1));
563 unsigned DestReg = getFPReg(MI->getOperand(0));
564 bool KillsSrc = false;
565 for (LiveVariables::killed_iterator KI = LV->killed_begin(MI),
566 E = LV->killed_end(MI); KI != E; ++KI)
567 KillsSrc |= KI->second == X86::FP0+SrcReg;
570 // If the input operand is killed, we can just change the owner of the
571 // incoming stack slot into the result.
572 unsigned Slot = getSlot(SrcReg);
573 assert(Slot < 7 && DestReg < 7 && "FpMOV operands invalid!");
574 Stack[Slot] = DestReg;
575 RegMap[DestReg] = Slot;
578 // For FMOV we just duplicate the specified value to a new stack slot.
579 // This could be made better, but would require substantial changes.
580 duplicateToTop(SrcReg, DestReg, I);
586 I = MBB->erase(I)-1; // Remove the pseudo instruction