1 //===-- X86FloatingPoint.cpp - Floating point Reg -> Stack converter ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the pass which converts floating point instructions from
11 // pseudo registers into register stack instructions. This pass uses live
12 // variable information to indicate where the FPn registers are used and their
15 // The x87 hardware tracks liveness of the stack registers, so it is necessary
16 // to implement exact liveness tracking between basic blocks. The CFG edges are
17 // partitioned into bundles where the same FP registers must be live in
18 // identical stack positions. Instructions are inserted at the end of each basic
19 // block to rearrange the live registers to match the outgoing bundle.
21 // This approach avoids splitting critical edges at the potential cost of more
22 // live register shuffling instructions when critical edges are present.
24 //===----------------------------------------------------------------------===//
26 #define DEBUG_TYPE "x86-codegen"
28 #include "X86InstrInfo.h"
29 #include "llvm/ADT/DepthFirstIterator.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/CodeGen/EdgeBundles.h"
36 #include "llvm/CodeGen/MachineFunctionPass.h"
37 #include "llvm/CodeGen/MachineInstrBuilder.h"
38 #include "llvm/CodeGen/MachineRegisterInfo.h"
39 #include "llvm/CodeGen/Passes.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetMachine.h"
48 STATISTIC(NumFXCH, "Number of fxch instructions inserted");
49 STATISTIC(NumFP , "Number of floating point instructions");
52 struct FPS : public MachineFunctionPass {
54 FPS() : MachineFunctionPass(ID) {
55 initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
56 // This is really only to keep valgrind quiet.
57 // The logic in isLive() is too much for it.
58 memset(Stack, 0, sizeof(Stack));
59 memset(RegMap, 0, sizeof(RegMap));
62 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addRequired<EdgeBundles>();
65 AU.addPreservedID(MachineLoopInfoID);
66 AU.addPreservedID(MachineDominatorsID);
67 MachineFunctionPass::getAnalysisUsage(AU);
70 virtual bool runOnMachineFunction(MachineFunction &MF);
72 virtual const char *getPassName() const { return "X86 FP Stackifier"; }
75 const TargetInstrInfo *TII; // Machine instruction info.
77 // Two CFG edges are related if they leave the same block, or enter the same
78 // block. The transitive closure of an edge under this relation is a
79 // LiveBundle. It represents a set of CFG edges where the live FP stack
80 // registers must be allocated identically in the x87 stack.
82 // A LiveBundle is usually all the edges leaving a block, or all the edges
83 // entering a block, but it can contain more edges if critical edges are
86 // The set of live FP registers in a LiveBundle is calculated by bundleCFG,
87 // but the exact mapping of FP registers to stack slots is fixed later.
89 // Bit mask of live FP registers. Bit 0 = FP0, bit 1 = FP1, &c.
92 // Number of pre-assigned live registers in FixStack. This is 0 when the
93 // stack order has not yet been fixed.
96 // Assigned stack order for live-in registers.
97 // FixStack[i] == getStackEntry(i) for all i < FixCount.
98 unsigned char FixStack[8];
100 LiveBundle() : Mask(0), FixCount(0) {}
102 // Have the live registers been assigned a stack order yet?
103 bool isFixed() const { return !Mask || FixCount; }
106 // Numbered LiveBundle structs. LiveBundles[0] is used for all CFG edges
107 // with no live FP registers.
108 SmallVector<LiveBundle, 8> LiveBundles;
110 // The edge bundle analysis provides indices into the LiveBundles vector.
111 EdgeBundles *Bundles;
113 // Return a bitmask of FP registers in block's live-in list.
114 unsigned calcLiveInMask(MachineBasicBlock *MBB) {
116 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
117 E = MBB->livein_end(); I != E; ++I) {
118 unsigned Reg = *I - X86::FP0;
125 // Partition all the CFG edges into LiveBundles.
126 void bundleCFG(MachineFunction &MF);
128 MachineBasicBlock *MBB; // Current basic block
130 // The hardware keeps track of how many FP registers are live, so we have
131 // to model that exactly. Usually, each live register corresponds to an
132 // FP<n> register, but when dealing with calls, returns, and inline
133 // assembly, it is sometimes neccesary to have live scratch registers.
134 unsigned Stack[8]; // FP<n> Registers in each stack slot...
135 unsigned StackTop; // The current top of the FP stack.
137 // For each live FP<n> register, point to its Stack[] entry.
138 // The first entries correspond to FP0-FP6, the rest are scratch registers
139 // used when we need slightly different live registers than what the
140 // register allocator thinks.
143 // Set up our stack model to match the incoming registers to MBB.
144 void setupBlockStack();
146 // Shuffle live registers to match the expectations of successor blocks.
147 void finishBlockStack();
149 void dumpStack() const {
150 dbgs() << "Stack contents:";
151 for (unsigned i = 0; i != StackTop; ++i) {
152 dbgs() << " FP" << Stack[i];
153 assert(RegMap[Stack[i]] == i && "Stack[] doesn't match RegMap[]!");
158 /// getSlot - Return the stack slot number a particular register number is
160 unsigned getSlot(unsigned RegNo) const {
161 assert(RegNo < array_lengthof(RegMap) && "Regno out of range!");
162 return RegMap[RegNo];
165 /// isLive - Is RegNo currently live in the stack?
166 bool isLive(unsigned RegNo) const {
167 unsigned Slot = getSlot(RegNo);
168 return Slot < StackTop && Stack[Slot] == RegNo;
171 /// getScratchReg - Return an FP register that is not currently in use.
172 unsigned getScratchReg() {
173 for (int i = array_lengthof(RegMap) - 1; i >= 8; --i)
176 llvm_unreachable("Ran out of scratch FP registers");
179 /// getStackEntry - Return the X86::FP<n> register in register ST(i).
180 unsigned getStackEntry(unsigned STi) const {
182 report_fatal_error("Access past stack top!");
183 return Stack[StackTop-1-STi];
186 /// getSTReg - Return the X86::ST(i) register which contains the specified
187 /// FP<RegNo> register.
188 unsigned getSTReg(unsigned RegNo) const {
189 return StackTop - 1 - getSlot(RegNo) + llvm::X86::ST0;
192 // pushReg - Push the specified FP<n> register onto the stack.
193 void pushReg(unsigned Reg) {
194 assert(Reg < array_lengthof(RegMap) && "Register number out of range!");
196 report_fatal_error("Stack overflow!");
197 Stack[StackTop] = Reg;
198 RegMap[Reg] = StackTop++;
201 bool isAtTop(unsigned RegNo) const { return getSlot(RegNo) == StackTop-1; }
202 void moveToTop(unsigned RegNo, MachineBasicBlock::iterator I) {
203 DebugLoc dl = I == MBB->end() ? DebugLoc() : I->getDebugLoc();
204 if (isAtTop(RegNo)) return;
206 unsigned STReg = getSTReg(RegNo);
207 unsigned RegOnTop = getStackEntry(0);
209 // Swap the slots the regs are in.
210 std::swap(RegMap[RegNo], RegMap[RegOnTop]);
212 // Swap stack slot contents.
213 if (RegMap[RegOnTop] >= StackTop)
214 report_fatal_error("Access past stack top!");
215 std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
217 // Emit an fxch to update the runtime processors version of the state.
218 BuildMI(*MBB, I, dl, TII->get(X86::XCH_F)).addReg(STReg);
222 void duplicateToTop(unsigned RegNo, unsigned AsReg, MachineInstr *I) {
223 DebugLoc dl = I == MBB->end() ? DebugLoc() : I->getDebugLoc();
224 unsigned STReg = getSTReg(RegNo);
225 pushReg(AsReg); // New register on top of stack
227 BuildMI(*MBB, I, dl, TII->get(X86::LD_Frr)).addReg(STReg);
230 /// popStackAfter - Pop the current value off of the top of the FP stack
231 /// after the specified instruction.
232 void popStackAfter(MachineBasicBlock::iterator &I);
234 /// freeStackSlotAfter - Free the specified register from the register
235 /// stack, so that it is no longer in a register. If the register is
236 /// currently at the top of the stack, we just pop the current instruction,
237 /// otherwise we store the current top-of-stack into the specified slot,
238 /// then pop the top of stack.
239 void freeStackSlotAfter(MachineBasicBlock::iterator &I, unsigned Reg);
241 /// freeStackSlotBefore - Just the pop, no folding. Return the inserted
243 MachineBasicBlock::iterator
244 freeStackSlotBefore(MachineBasicBlock::iterator I, unsigned FPRegNo);
246 /// Adjust the live registers to be the set in Mask.
247 void adjustLiveRegs(unsigned Mask, MachineBasicBlock::iterator I);
249 /// Shuffle the top FixCount stack entries such that FP reg FixStack[0] is
250 /// st(0), FP reg FixStack[1] is st(1) etc.
251 void shuffleStackTop(const unsigned char *FixStack, unsigned FixCount,
252 MachineBasicBlock::iterator I);
254 bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
256 void handleZeroArgFP(MachineBasicBlock::iterator &I);
257 void handleOneArgFP(MachineBasicBlock::iterator &I);
258 void handleOneArgFPRW(MachineBasicBlock::iterator &I);
259 void handleTwoArgFP(MachineBasicBlock::iterator &I);
260 void handleCompareFP(MachineBasicBlock::iterator &I);
261 void handleCondMovFP(MachineBasicBlock::iterator &I);
262 void handleSpecialFP(MachineBasicBlock::iterator &I);
264 bool translateCopy(MachineInstr*);
269 FunctionPass *llvm::createX86FloatingPointStackifierPass() { return new FPS(); }
271 /// getFPReg - Return the X86::FPx register number for the specified operand.
272 /// For example, this returns 3 for X86::FP3.
273 static unsigned getFPReg(const MachineOperand &MO) {
274 assert(MO.isReg() && "Expected an FP register!");
275 unsigned Reg = MO.getReg();
276 assert(Reg >= X86::FP0 && Reg <= X86::FP6 && "Expected FP register!");
277 return Reg - X86::FP0;
280 /// runOnMachineFunction - Loop over all of the basic blocks, transforming FP
281 /// register references into FP stack references.
283 bool FPS::runOnMachineFunction(MachineFunction &MF) {
284 // We only need to run this pass if there are any FP registers used in this
285 // function. If it is all integer, there is nothing for us to do!
286 bool FPIsUsed = false;
288 assert(X86::FP6 == X86::FP0+6 && "Register enums aren't sorted right!");
289 for (unsigned i = 0; i <= 6; ++i)
290 if (MF.getRegInfo().isPhysRegUsed(X86::FP0+i)) {
296 if (!FPIsUsed) return false;
298 Bundles = &getAnalysis<EdgeBundles>();
299 TII = MF.getTarget().getInstrInfo();
301 // Prepare cross-MBB liveness.
306 // Process the function in depth first order so that we process at least one
307 // of the predecessors for every reachable block in the function.
308 SmallPtrSet<MachineBasicBlock*, 8> Processed;
309 MachineBasicBlock *Entry = MF.begin();
311 bool Changed = false;
312 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8> >
313 I = df_ext_begin(Entry, Processed), E = df_ext_end(Entry, Processed);
315 Changed |= processBasicBlock(MF, **I);
317 // Process any unreachable blocks in arbitrary order now.
318 if (MF.size() != Processed.size())
319 for (MachineFunction::iterator BB = MF.begin(), E = MF.end(); BB != E; ++BB)
320 if (Processed.insert(BB))
321 Changed |= processBasicBlock(MF, *BB);
328 /// bundleCFG - Scan all the basic blocks to determine consistent live-in and
329 /// live-out sets for the FP registers. Consistent means that the set of
330 /// registers live-out from a block is identical to the live-in set of all
331 /// successors. This is not enforced by the normal live-in lists since
332 /// registers may be implicitly defined, or not used by all successors.
333 void FPS::bundleCFG(MachineFunction &MF) {
334 assert(LiveBundles.empty() && "Stale data in LiveBundles");
335 LiveBundles.resize(Bundles->getNumBundles());
337 // Gather the actual live-in masks for all MBBs.
338 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
339 MachineBasicBlock *MBB = I;
340 const unsigned Mask = calcLiveInMask(MBB);
343 // Update MBB ingoing bundle mask.
344 LiveBundles[Bundles->getBundle(MBB->getNumber(), false)].Mask |= Mask;
348 /// processBasicBlock - Loop over all of the instructions in the basic block,
349 /// transforming FP instructions into their stack form.
351 bool FPS::processBasicBlock(MachineFunction &MF, MachineBasicBlock &BB) {
352 bool Changed = false;
357 for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
358 MachineInstr *MI = I;
359 uint64_t Flags = MI->getDesc().TSFlags;
361 unsigned FPInstClass = Flags & X86II::FPTypeMask;
362 if (MI->isInlineAsm())
363 FPInstClass = X86II::SpecialFP;
365 if (MI->isCopy() && translateCopy(MI))
366 FPInstClass = X86II::SpecialFP;
368 if (FPInstClass == X86II::NotFP)
369 continue; // Efficiently ignore non-fp insts!
371 MachineInstr *PrevMI = 0;
375 ++NumFP; // Keep track of # of pseudo instrs
376 DEBUG(dbgs() << "\nFPInst:\t" << *MI);
378 // Get dead variables list now because the MI pointer may be deleted as part
380 SmallVector<unsigned, 8> DeadRegs;
381 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
382 const MachineOperand &MO = MI->getOperand(i);
383 if (MO.isReg() && MO.isDead())
384 DeadRegs.push_back(MO.getReg());
387 switch (FPInstClass) {
388 case X86II::ZeroArgFP: handleZeroArgFP(I); break;
389 case X86II::OneArgFP: handleOneArgFP(I); break; // fstp ST(0)
390 case X86II::OneArgFPRW: handleOneArgFPRW(I); break; // ST(0) = fsqrt(ST(0))
391 case X86II::TwoArgFP: handleTwoArgFP(I); break;
392 case X86II::CompareFP: handleCompareFP(I); break;
393 case X86II::CondMovFP: handleCondMovFP(I); break;
394 case X86II::SpecialFP: handleSpecialFP(I); break;
395 default: llvm_unreachable("Unknown FP Type!");
398 // Check to see if any of the values defined by this instruction are dead
399 // after definition. If so, pop them.
400 for (unsigned i = 0, e = DeadRegs.size(); i != e; ++i) {
401 unsigned Reg = DeadRegs[i];
402 if (Reg >= X86::FP0 && Reg <= X86::FP6) {
403 DEBUG(dbgs() << "Register FP#" << Reg-X86::FP0 << " is dead!\n");
404 freeStackSlotAfter(I, Reg-X86::FP0);
408 // Print out all of the instructions expanded to if -debug
410 MachineBasicBlock::iterator PrevI(PrevMI);
412 dbgs() << "Just deleted pseudo instruction\n";
414 MachineBasicBlock::iterator Start = I;
415 // Rewind to first instruction newly inserted.
416 while (Start != BB.begin() && prior(Start) != PrevI) --Start;
417 dbgs() << "Inserted instructions:\n\t";
418 Start->print(dbgs(), &MF.getTarget());
419 while (++Start != llvm::next(I)) {}
432 /// setupBlockStack - Use the live bundles to set up our model of the stack
433 /// to match predecessors' live out stack.
434 void FPS::setupBlockStack() {
435 DEBUG(dbgs() << "\nSetting up live-ins for BB#" << MBB->getNumber()
436 << " derived from " << MBB->getName() << ".\n");
438 // Get the live-in bundle for MBB.
439 const LiveBundle &Bundle =
440 LiveBundles[Bundles->getBundle(MBB->getNumber(), false)];
443 DEBUG(dbgs() << "Block has no FP live-ins.\n");
447 // Depth-first iteration should ensure that we always have an assigned stack.
448 assert(Bundle.isFixed() && "Reached block before any predecessors");
450 // Push the fixed live-in registers.
451 for (unsigned i = Bundle.FixCount; i > 0; --i) {
452 MBB->addLiveIn(X86::ST0+i-1);
453 DEBUG(dbgs() << "Live-in st(" << (i-1) << "): %FP"
454 << unsigned(Bundle.FixStack[i-1]) << '\n');
455 pushReg(Bundle.FixStack[i-1]);
458 // Kill off unwanted live-ins. This can happen with a critical edge.
459 // FIXME: We could keep these live registers around as zombies. They may need
460 // to be revived at the end of a short block. It might save a few instrs.
461 adjustLiveRegs(calcLiveInMask(MBB), MBB->begin());
465 /// finishBlockStack - Revive live-outs that are implicitly defined out of
466 /// MBB. Shuffle live registers to match the expected fixed stack of any
467 /// predecessors, and ensure that all predecessors are expecting the same
469 void FPS::finishBlockStack() {
470 // The RET handling below takes care of return blocks for us.
471 if (MBB->succ_empty())
474 DEBUG(dbgs() << "Setting up live-outs for BB#" << MBB->getNumber()
475 << " derived from " << MBB->getName() << ".\n");
477 // Get MBB's live-out bundle.
478 unsigned BundleIdx = Bundles->getBundle(MBB->getNumber(), true);
479 LiveBundle &Bundle = LiveBundles[BundleIdx];
481 // We may need to kill and define some registers to match successors.
482 // FIXME: This can probably be combined with the shuffle below.
483 MachineBasicBlock::iterator Term = MBB->getFirstTerminator();
484 adjustLiveRegs(Bundle.Mask, Term);
487 DEBUG(dbgs() << "No live-outs.\n");
491 // Has the stack order been fixed yet?
492 DEBUG(dbgs() << "LB#" << BundleIdx << ": ");
493 if (Bundle.isFixed()) {
494 DEBUG(dbgs() << "Shuffling stack to match.\n");
495 shuffleStackTop(Bundle.FixStack, Bundle.FixCount, Term);
497 // Not fixed yet, we get to choose.
498 DEBUG(dbgs() << "Fixing stack order now.\n");
499 Bundle.FixCount = StackTop;
500 for (unsigned i = 0; i < StackTop; ++i)
501 Bundle.FixStack[i] = getStackEntry(i);
506 //===----------------------------------------------------------------------===//
507 // Efficient Lookup Table Support
508 //===----------------------------------------------------------------------===//
514 bool operator<(const TableEntry &TE) const { return from < TE.from; }
515 friend bool operator<(const TableEntry &TE, unsigned V) {
518 friend bool LLVM_ATTRIBUTE_USED operator<(unsigned V,
519 const TableEntry &TE) {
526 static bool TableIsSorted(const TableEntry *Table, unsigned NumEntries) {
527 for (unsigned i = 0; i != NumEntries-1; ++i)
528 if (!(Table[i] < Table[i+1])) return false;
533 static int Lookup(const TableEntry *Table, unsigned N, unsigned Opcode) {
534 const TableEntry *I = std::lower_bound(Table, Table+N, Opcode);
535 if (I != Table+N && I->from == Opcode)
541 #define ASSERT_SORTED(TABLE)
543 #define ASSERT_SORTED(TABLE) \
544 { static bool TABLE##Checked = false; \
545 if (!TABLE##Checked) { \
546 assert(TableIsSorted(TABLE, array_lengthof(TABLE)) && \
547 "All lookup tables must be sorted for efficient access!"); \
548 TABLE##Checked = true; \
553 //===----------------------------------------------------------------------===//
554 // Register File -> Register Stack Mapping Methods
555 //===----------------------------------------------------------------------===//
557 // OpcodeTable - Sorted map of register instructions to their stack version.
558 // The first element is an register file pseudo instruction, the second is the
559 // concrete X86 instruction which uses the register stack.
561 static const TableEntry OpcodeTable[] = {
562 { X86::ABS_Fp32 , X86::ABS_F },
563 { X86::ABS_Fp64 , X86::ABS_F },
564 { X86::ABS_Fp80 , X86::ABS_F },
565 { X86::ADD_Fp32m , X86::ADD_F32m },
566 { X86::ADD_Fp64m , X86::ADD_F64m },
567 { X86::ADD_Fp64m32 , X86::ADD_F32m },
568 { X86::ADD_Fp80m32 , X86::ADD_F32m },
569 { X86::ADD_Fp80m64 , X86::ADD_F64m },
570 { X86::ADD_FpI16m32 , X86::ADD_FI16m },
571 { X86::ADD_FpI16m64 , X86::ADD_FI16m },
572 { X86::ADD_FpI16m80 , X86::ADD_FI16m },
573 { X86::ADD_FpI32m32 , X86::ADD_FI32m },
574 { X86::ADD_FpI32m64 , X86::ADD_FI32m },
575 { X86::ADD_FpI32m80 , X86::ADD_FI32m },
576 { X86::CHS_Fp32 , X86::CHS_F },
577 { X86::CHS_Fp64 , X86::CHS_F },
578 { X86::CHS_Fp80 , X86::CHS_F },
579 { X86::CMOVBE_Fp32 , X86::CMOVBE_F },
580 { X86::CMOVBE_Fp64 , X86::CMOVBE_F },
581 { X86::CMOVBE_Fp80 , X86::CMOVBE_F },
582 { X86::CMOVB_Fp32 , X86::CMOVB_F },
583 { X86::CMOVB_Fp64 , X86::CMOVB_F },
584 { X86::CMOVB_Fp80 , X86::CMOVB_F },
585 { X86::CMOVE_Fp32 , X86::CMOVE_F },
586 { X86::CMOVE_Fp64 , X86::CMOVE_F },
587 { X86::CMOVE_Fp80 , X86::CMOVE_F },
588 { X86::CMOVNBE_Fp32 , X86::CMOVNBE_F },
589 { X86::CMOVNBE_Fp64 , X86::CMOVNBE_F },
590 { X86::CMOVNBE_Fp80 , X86::CMOVNBE_F },
591 { X86::CMOVNB_Fp32 , X86::CMOVNB_F },
592 { X86::CMOVNB_Fp64 , X86::CMOVNB_F },
593 { X86::CMOVNB_Fp80 , X86::CMOVNB_F },
594 { X86::CMOVNE_Fp32 , X86::CMOVNE_F },
595 { X86::CMOVNE_Fp64 , X86::CMOVNE_F },
596 { X86::CMOVNE_Fp80 , X86::CMOVNE_F },
597 { X86::CMOVNP_Fp32 , X86::CMOVNP_F },
598 { X86::CMOVNP_Fp64 , X86::CMOVNP_F },
599 { X86::CMOVNP_Fp80 , X86::CMOVNP_F },
600 { X86::CMOVP_Fp32 , X86::CMOVP_F },
601 { X86::CMOVP_Fp64 , X86::CMOVP_F },
602 { X86::CMOVP_Fp80 , X86::CMOVP_F },
603 { X86::COS_Fp32 , X86::COS_F },
604 { X86::COS_Fp64 , X86::COS_F },
605 { X86::COS_Fp80 , X86::COS_F },
606 { X86::DIVR_Fp32m , X86::DIVR_F32m },
607 { X86::DIVR_Fp64m , X86::DIVR_F64m },
608 { X86::DIVR_Fp64m32 , X86::DIVR_F32m },
609 { X86::DIVR_Fp80m32 , X86::DIVR_F32m },
610 { X86::DIVR_Fp80m64 , X86::DIVR_F64m },
611 { X86::DIVR_FpI16m32, X86::DIVR_FI16m},
612 { X86::DIVR_FpI16m64, X86::DIVR_FI16m},
613 { X86::DIVR_FpI16m80, X86::DIVR_FI16m},
614 { X86::DIVR_FpI32m32, X86::DIVR_FI32m},
615 { X86::DIVR_FpI32m64, X86::DIVR_FI32m},
616 { X86::DIVR_FpI32m80, X86::DIVR_FI32m},
617 { X86::DIV_Fp32m , X86::DIV_F32m },
618 { X86::DIV_Fp64m , X86::DIV_F64m },
619 { X86::DIV_Fp64m32 , X86::DIV_F32m },
620 { X86::DIV_Fp80m32 , X86::DIV_F32m },
621 { X86::DIV_Fp80m64 , X86::DIV_F64m },
622 { X86::DIV_FpI16m32 , X86::DIV_FI16m },
623 { X86::DIV_FpI16m64 , X86::DIV_FI16m },
624 { X86::DIV_FpI16m80 , X86::DIV_FI16m },
625 { X86::DIV_FpI32m32 , X86::DIV_FI32m },
626 { X86::DIV_FpI32m64 , X86::DIV_FI32m },
627 { X86::DIV_FpI32m80 , X86::DIV_FI32m },
628 { X86::ILD_Fp16m32 , X86::ILD_F16m },
629 { X86::ILD_Fp16m64 , X86::ILD_F16m },
630 { X86::ILD_Fp16m80 , X86::ILD_F16m },
631 { X86::ILD_Fp32m32 , X86::ILD_F32m },
632 { X86::ILD_Fp32m64 , X86::ILD_F32m },
633 { X86::ILD_Fp32m80 , X86::ILD_F32m },
634 { X86::ILD_Fp64m32 , X86::ILD_F64m },
635 { X86::ILD_Fp64m64 , X86::ILD_F64m },
636 { X86::ILD_Fp64m80 , X86::ILD_F64m },
637 { X86::ISTT_Fp16m32 , X86::ISTT_FP16m},
638 { X86::ISTT_Fp16m64 , X86::ISTT_FP16m},
639 { X86::ISTT_Fp16m80 , X86::ISTT_FP16m},
640 { X86::ISTT_Fp32m32 , X86::ISTT_FP32m},
641 { X86::ISTT_Fp32m64 , X86::ISTT_FP32m},
642 { X86::ISTT_Fp32m80 , X86::ISTT_FP32m},
643 { X86::ISTT_Fp64m32 , X86::ISTT_FP64m},
644 { X86::ISTT_Fp64m64 , X86::ISTT_FP64m},
645 { X86::ISTT_Fp64m80 , X86::ISTT_FP64m},
646 { X86::IST_Fp16m32 , X86::IST_F16m },
647 { X86::IST_Fp16m64 , X86::IST_F16m },
648 { X86::IST_Fp16m80 , X86::IST_F16m },
649 { X86::IST_Fp32m32 , X86::IST_F32m },
650 { X86::IST_Fp32m64 , X86::IST_F32m },
651 { X86::IST_Fp32m80 , X86::IST_F32m },
652 { X86::IST_Fp64m32 , X86::IST_FP64m },
653 { X86::IST_Fp64m64 , X86::IST_FP64m },
654 { X86::IST_Fp64m80 , X86::IST_FP64m },
655 { X86::LD_Fp032 , X86::LD_F0 },
656 { X86::LD_Fp064 , X86::LD_F0 },
657 { X86::LD_Fp080 , X86::LD_F0 },
658 { X86::LD_Fp132 , X86::LD_F1 },
659 { X86::LD_Fp164 , X86::LD_F1 },
660 { X86::LD_Fp180 , X86::LD_F1 },
661 { X86::LD_Fp32m , X86::LD_F32m },
662 { X86::LD_Fp32m64 , X86::LD_F32m },
663 { X86::LD_Fp32m80 , X86::LD_F32m },
664 { X86::LD_Fp64m , X86::LD_F64m },
665 { X86::LD_Fp64m80 , X86::LD_F64m },
666 { X86::LD_Fp80m , X86::LD_F80m },
667 { X86::MUL_Fp32m , X86::MUL_F32m },
668 { X86::MUL_Fp64m , X86::MUL_F64m },
669 { X86::MUL_Fp64m32 , X86::MUL_F32m },
670 { X86::MUL_Fp80m32 , X86::MUL_F32m },
671 { X86::MUL_Fp80m64 , X86::MUL_F64m },
672 { X86::MUL_FpI16m32 , X86::MUL_FI16m },
673 { X86::MUL_FpI16m64 , X86::MUL_FI16m },
674 { X86::MUL_FpI16m80 , X86::MUL_FI16m },
675 { X86::MUL_FpI32m32 , X86::MUL_FI32m },
676 { X86::MUL_FpI32m64 , X86::MUL_FI32m },
677 { X86::MUL_FpI32m80 , X86::MUL_FI32m },
678 { X86::SIN_Fp32 , X86::SIN_F },
679 { X86::SIN_Fp64 , X86::SIN_F },
680 { X86::SIN_Fp80 , X86::SIN_F },
681 { X86::SQRT_Fp32 , X86::SQRT_F },
682 { X86::SQRT_Fp64 , X86::SQRT_F },
683 { X86::SQRT_Fp80 , X86::SQRT_F },
684 { X86::ST_Fp32m , X86::ST_F32m },
685 { X86::ST_Fp64m , X86::ST_F64m },
686 { X86::ST_Fp64m32 , X86::ST_F32m },
687 { X86::ST_Fp80m32 , X86::ST_F32m },
688 { X86::ST_Fp80m64 , X86::ST_F64m },
689 { X86::ST_FpP80m , X86::ST_FP80m },
690 { X86::SUBR_Fp32m , X86::SUBR_F32m },
691 { X86::SUBR_Fp64m , X86::SUBR_F64m },
692 { X86::SUBR_Fp64m32 , X86::SUBR_F32m },
693 { X86::SUBR_Fp80m32 , X86::SUBR_F32m },
694 { X86::SUBR_Fp80m64 , X86::SUBR_F64m },
695 { X86::SUBR_FpI16m32, X86::SUBR_FI16m},
696 { X86::SUBR_FpI16m64, X86::SUBR_FI16m},
697 { X86::SUBR_FpI16m80, X86::SUBR_FI16m},
698 { X86::SUBR_FpI32m32, X86::SUBR_FI32m},
699 { X86::SUBR_FpI32m64, X86::SUBR_FI32m},
700 { X86::SUBR_FpI32m80, X86::SUBR_FI32m},
701 { X86::SUB_Fp32m , X86::SUB_F32m },
702 { X86::SUB_Fp64m , X86::SUB_F64m },
703 { X86::SUB_Fp64m32 , X86::SUB_F32m },
704 { X86::SUB_Fp80m32 , X86::SUB_F32m },
705 { X86::SUB_Fp80m64 , X86::SUB_F64m },
706 { X86::SUB_FpI16m32 , X86::SUB_FI16m },
707 { X86::SUB_FpI16m64 , X86::SUB_FI16m },
708 { X86::SUB_FpI16m80 , X86::SUB_FI16m },
709 { X86::SUB_FpI32m32 , X86::SUB_FI32m },
710 { X86::SUB_FpI32m64 , X86::SUB_FI32m },
711 { X86::SUB_FpI32m80 , X86::SUB_FI32m },
712 { X86::TST_Fp32 , X86::TST_F },
713 { X86::TST_Fp64 , X86::TST_F },
714 { X86::TST_Fp80 , X86::TST_F },
715 { X86::UCOM_FpIr32 , X86::UCOM_FIr },
716 { X86::UCOM_FpIr64 , X86::UCOM_FIr },
717 { X86::UCOM_FpIr80 , X86::UCOM_FIr },
718 { X86::UCOM_Fpr32 , X86::UCOM_Fr },
719 { X86::UCOM_Fpr64 , X86::UCOM_Fr },
720 { X86::UCOM_Fpr80 , X86::UCOM_Fr },
723 static unsigned getConcreteOpcode(unsigned Opcode) {
724 ASSERT_SORTED(OpcodeTable);
725 int Opc = Lookup(OpcodeTable, array_lengthof(OpcodeTable), Opcode);
726 assert(Opc != -1 && "FP Stack instruction not in OpcodeTable!");
730 //===----------------------------------------------------------------------===//
732 //===----------------------------------------------------------------------===//
734 // PopTable - Sorted map of instructions to their popping version. The first
735 // element is an instruction, the second is the version which pops.
737 static const TableEntry PopTable[] = {
738 { X86::ADD_FrST0 , X86::ADD_FPrST0 },
740 { X86::DIVR_FrST0, X86::DIVR_FPrST0 },
741 { X86::DIV_FrST0 , X86::DIV_FPrST0 },
743 { X86::IST_F16m , X86::IST_FP16m },
744 { X86::IST_F32m , X86::IST_FP32m },
746 { X86::MUL_FrST0 , X86::MUL_FPrST0 },
748 { X86::ST_F32m , X86::ST_FP32m },
749 { X86::ST_F64m , X86::ST_FP64m },
750 { X86::ST_Frr , X86::ST_FPrr },
752 { X86::SUBR_FrST0, X86::SUBR_FPrST0 },
753 { X86::SUB_FrST0 , X86::SUB_FPrST0 },
755 { X86::UCOM_FIr , X86::UCOM_FIPr },
757 { X86::UCOM_FPr , X86::UCOM_FPPr },
758 { X86::UCOM_Fr , X86::UCOM_FPr },
761 /// popStackAfter - Pop the current value off of the top of the FP stack after
762 /// the specified instruction. This attempts to be sneaky and combine the pop
763 /// into the instruction itself if possible. The iterator is left pointing to
764 /// the last instruction, be it a new pop instruction inserted, or the old
765 /// instruction if it was modified in place.
767 void FPS::popStackAfter(MachineBasicBlock::iterator &I) {
768 MachineInstr* MI = I;
769 DebugLoc dl = MI->getDebugLoc();
770 ASSERT_SORTED(PopTable);
772 report_fatal_error("Cannot pop empty stack!");
773 RegMap[Stack[--StackTop]] = ~0; // Update state
775 // Check to see if there is a popping version of this instruction...
776 int Opcode = Lookup(PopTable, array_lengthof(PopTable), I->getOpcode());
778 I->setDesc(TII->get(Opcode));
779 if (Opcode == X86::UCOM_FPPr)
781 } else { // Insert an explicit pop
782 I = BuildMI(*MBB, ++I, dl, TII->get(X86::ST_FPrr)).addReg(X86::ST0);
786 /// freeStackSlotAfter - Free the specified register from the register stack, so
787 /// that it is no longer in a register. If the register is currently at the top
788 /// of the stack, we just pop the current instruction, otherwise we store the
789 /// current top-of-stack into the specified slot, then pop the top of stack.
790 void FPS::freeStackSlotAfter(MachineBasicBlock::iterator &I, unsigned FPRegNo) {
791 if (getStackEntry(0) == FPRegNo) { // already at the top of stack? easy.
796 // Otherwise, store the top of stack into the dead slot, killing the operand
797 // without having to add in an explicit xchg then pop.
799 I = freeStackSlotBefore(++I, FPRegNo);
802 /// freeStackSlotBefore - Free the specified register without trying any
804 MachineBasicBlock::iterator
805 FPS::freeStackSlotBefore(MachineBasicBlock::iterator I, unsigned FPRegNo) {
806 unsigned STReg = getSTReg(FPRegNo);
807 unsigned OldSlot = getSlot(FPRegNo);
808 unsigned TopReg = Stack[StackTop-1];
809 Stack[OldSlot] = TopReg;
810 RegMap[TopReg] = OldSlot;
811 RegMap[FPRegNo] = ~0;
812 Stack[--StackTop] = ~0;
813 return BuildMI(*MBB, I, DebugLoc(), TII->get(X86::ST_FPrr)).addReg(STReg);
816 /// adjustLiveRegs - Kill and revive registers such that exactly the FP
817 /// registers with a bit in Mask are live.
818 void FPS::adjustLiveRegs(unsigned Mask, MachineBasicBlock::iterator I) {
819 unsigned Defs = Mask;
821 for (unsigned i = 0; i < StackTop; ++i) {
822 unsigned RegNo = Stack[i];
823 if (!(Defs & (1 << RegNo)))
824 // This register is live, but we don't want it.
825 Kills |= (1 << RegNo);
827 // We don't need to imp-def this live register.
828 Defs &= ~(1 << RegNo);
830 assert((Kills & Defs) == 0 && "Register needs killing and def'ing?");
832 // Produce implicit-defs for free by using killed registers.
833 while (Kills && Defs) {
834 unsigned KReg = CountTrailingZeros_32(Kills);
835 unsigned DReg = CountTrailingZeros_32(Defs);
836 DEBUG(dbgs() << "Renaming %FP" << KReg << " as imp %FP" << DReg << "\n");
837 std::swap(Stack[getSlot(KReg)], Stack[getSlot(DReg)]);
838 std::swap(RegMap[KReg], RegMap[DReg]);
839 Kills &= ~(1 << KReg);
840 Defs &= ~(1 << DReg);
843 // Kill registers by popping.
844 if (Kills && I != MBB->begin()) {
845 MachineBasicBlock::iterator I2 = llvm::prior(I);
847 unsigned KReg = getStackEntry(0);
848 if (!(Kills & (1 << KReg)))
850 DEBUG(dbgs() << "Popping %FP" << KReg << "\n");
852 Kills &= ~(1 << KReg);
856 // Manually kill the rest.
858 unsigned KReg = CountTrailingZeros_32(Kills);
859 DEBUG(dbgs() << "Killing %FP" << KReg << "\n");
860 freeStackSlotBefore(I, KReg);
861 Kills &= ~(1 << KReg);
864 // Load zeros for all the imp-defs.
866 unsigned DReg = CountTrailingZeros_32(Defs);
867 DEBUG(dbgs() << "Defining %FP" << DReg << " as 0\n");
868 BuildMI(*MBB, I, DebugLoc(), TII->get(X86::LD_F0));
870 Defs &= ~(1 << DReg);
873 // Now we should have the correct registers live.
875 assert(StackTop == CountPopulation_32(Mask) && "Live count mismatch");
878 /// shuffleStackTop - emit fxch instructions before I to shuffle the top
879 /// FixCount entries into the order given by FixStack.
880 /// FIXME: Is there a better algorithm than insertion sort?
881 void FPS::shuffleStackTop(const unsigned char *FixStack,
883 MachineBasicBlock::iterator I) {
884 // Move items into place, starting from the desired stack bottom.
886 // Old register at position FixCount.
887 unsigned OldReg = getStackEntry(FixCount);
888 // Desired register at position FixCount.
889 unsigned Reg = FixStack[FixCount];
892 // (Reg st0) (OldReg st0) = (Reg OldReg st0)
894 moveToTop(OldReg, I);
900 //===----------------------------------------------------------------------===//
901 // Instruction transformation implementation
902 //===----------------------------------------------------------------------===//
904 /// handleZeroArgFP - ST(0) = fld0 ST(0) = flds <mem>
906 void FPS::handleZeroArgFP(MachineBasicBlock::iterator &I) {
907 MachineInstr *MI = I;
908 unsigned DestReg = getFPReg(MI->getOperand(0));
910 // Change from the pseudo instruction to the concrete instruction.
911 MI->RemoveOperand(0); // Remove the explicit ST(0) operand
912 MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
914 // Result gets pushed on the stack.
918 /// handleOneArgFP - fst <mem>, ST(0)
920 void FPS::handleOneArgFP(MachineBasicBlock::iterator &I) {
921 MachineInstr *MI = I;
922 unsigned NumOps = MI->getDesc().getNumOperands();
923 assert((NumOps == X86::AddrNumOperands + 1 || NumOps == 1) &&
924 "Can only handle fst* & ftst instructions!");
926 // Is this the last use of the source register?
927 unsigned Reg = getFPReg(MI->getOperand(NumOps-1));
928 bool KillsSrc = MI->killsRegister(X86::FP0+Reg);
930 // FISTP64m is strange because there isn't a non-popping versions.
931 // If we have one _and_ we don't want to pop the operand, duplicate the value
932 // on the stack instead of moving it. This ensure that popping the value is
934 // Ditto FISTTP16m, FISTTP32m, FISTTP64m, ST_FpP80m.
937 (MI->getOpcode() == X86::IST_Fp64m32 ||
938 MI->getOpcode() == X86::ISTT_Fp16m32 ||
939 MI->getOpcode() == X86::ISTT_Fp32m32 ||
940 MI->getOpcode() == X86::ISTT_Fp64m32 ||
941 MI->getOpcode() == X86::IST_Fp64m64 ||
942 MI->getOpcode() == X86::ISTT_Fp16m64 ||
943 MI->getOpcode() == X86::ISTT_Fp32m64 ||
944 MI->getOpcode() == X86::ISTT_Fp64m64 ||
945 MI->getOpcode() == X86::IST_Fp64m80 ||
946 MI->getOpcode() == X86::ISTT_Fp16m80 ||
947 MI->getOpcode() == X86::ISTT_Fp32m80 ||
948 MI->getOpcode() == X86::ISTT_Fp64m80 ||
949 MI->getOpcode() == X86::ST_FpP80m)) {
950 duplicateToTop(Reg, getScratchReg(), I);
952 moveToTop(Reg, I); // Move to the top of the stack...
955 // Convert from the pseudo instruction to the concrete instruction.
956 MI->RemoveOperand(NumOps-1); // Remove explicit ST(0) operand
957 MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
959 if (MI->getOpcode() == X86::IST_FP64m ||
960 MI->getOpcode() == X86::ISTT_FP16m ||
961 MI->getOpcode() == X86::ISTT_FP32m ||
962 MI->getOpcode() == X86::ISTT_FP64m ||
963 MI->getOpcode() == X86::ST_FP80m) {
965 report_fatal_error("Stack empty??");
967 } else if (KillsSrc) { // Last use of operand?
973 /// handleOneArgFPRW: Handle instructions that read from the top of stack and
974 /// replace the value with a newly computed value. These instructions may have
975 /// non-fp operands after their FP operands.
979 /// R1 = fadd R2, [mem]
981 void FPS::handleOneArgFPRW(MachineBasicBlock::iterator &I) {
982 MachineInstr *MI = I;
984 unsigned NumOps = MI->getDesc().getNumOperands();
985 assert(NumOps >= 2 && "FPRW instructions must have 2 ops!!");
988 // Is this the last use of the source register?
989 unsigned Reg = getFPReg(MI->getOperand(1));
990 bool KillsSrc = MI->killsRegister(X86::FP0+Reg);
993 // If this is the last use of the source register, just make sure it's on
994 // the top of the stack.
997 report_fatal_error("Stack cannot be empty!");
999 pushReg(getFPReg(MI->getOperand(0)));
1001 // If this is not the last use of the source register, _copy_ it to the top
1003 duplicateToTop(Reg, getFPReg(MI->getOperand(0)), I);
1006 // Change from the pseudo instruction to the concrete instruction.
1007 MI->RemoveOperand(1); // Drop the source operand.
1008 MI->RemoveOperand(0); // Drop the destination operand.
1009 MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
1013 //===----------------------------------------------------------------------===//
1014 // Define tables of various ways to map pseudo instructions
1017 // ForwardST0Table - Map: A = B op C into: ST(0) = ST(0) op ST(i)
1018 static const TableEntry ForwardST0Table[] = {
1019 { X86::ADD_Fp32 , X86::ADD_FST0r },
1020 { X86::ADD_Fp64 , X86::ADD_FST0r },
1021 { X86::ADD_Fp80 , X86::ADD_FST0r },
1022 { X86::DIV_Fp32 , X86::DIV_FST0r },
1023 { X86::DIV_Fp64 , X86::DIV_FST0r },
1024 { X86::DIV_Fp80 , X86::DIV_FST0r },
1025 { X86::MUL_Fp32 , X86::MUL_FST0r },
1026 { X86::MUL_Fp64 , X86::MUL_FST0r },
1027 { X86::MUL_Fp80 , X86::MUL_FST0r },
1028 { X86::SUB_Fp32 , X86::SUB_FST0r },
1029 { X86::SUB_Fp64 , X86::SUB_FST0r },
1030 { X86::SUB_Fp80 , X86::SUB_FST0r },
1033 // ReverseST0Table - Map: A = B op C into: ST(0) = ST(i) op ST(0)
1034 static const TableEntry ReverseST0Table[] = {
1035 { X86::ADD_Fp32 , X86::ADD_FST0r }, // commutative
1036 { X86::ADD_Fp64 , X86::ADD_FST0r }, // commutative
1037 { X86::ADD_Fp80 , X86::ADD_FST0r }, // commutative
1038 { X86::DIV_Fp32 , X86::DIVR_FST0r },
1039 { X86::DIV_Fp64 , X86::DIVR_FST0r },
1040 { X86::DIV_Fp80 , X86::DIVR_FST0r },
1041 { X86::MUL_Fp32 , X86::MUL_FST0r }, // commutative
1042 { X86::MUL_Fp64 , X86::MUL_FST0r }, // commutative
1043 { X86::MUL_Fp80 , X86::MUL_FST0r }, // commutative
1044 { X86::SUB_Fp32 , X86::SUBR_FST0r },
1045 { X86::SUB_Fp64 , X86::SUBR_FST0r },
1046 { X86::SUB_Fp80 , X86::SUBR_FST0r },
1049 // ForwardSTiTable - Map: A = B op C into: ST(i) = ST(0) op ST(i)
1050 static const TableEntry ForwardSTiTable[] = {
1051 { X86::ADD_Fp32 , X86::ADD_FrST0 }, // commutative
1052 { X86::ADD_Fp64 , X86::ADD_FrST0 }, // commutative
1053 { X86::ADD_Fp80 , X86::ADD_FrST0 }, // commutative
1054 { X86::DIV_Fp32 , X86::DIVR_FrST0 },
1055 { X86::DIV_Fp64 , X86::DIVR_FrST0 },
1056 { X86::DIV_Fp80 , X86::DIVR_FrST0 },
1057 { X86::MUL_Fp32 , X86::MUL_FrST0 }, // commutative
1058 { X86::MUL_Fp64 , X86::MUL_FrST0 }, // commutative
1059 { X86::MUL_Fp80 , X86::MUL_FrST0 }, // commutative
1060 { X86::SUB_Fp32 , X86::SUBR_FrST0 },
1061 { X86::SUB_Fp64 , X86::SUBR_FrST0 },
1062 { X86::SUB_Fp80 , X86::SUBR_FrST0 },
1065 // ReverseSTiTable - Map: A = B op C into: ST(i) = ST(i) op ST(0)
1066 static const TableEntry ReverseSTiTable[] = {
1067 { X86::ADD_Fp32 , X86::ADD_FrST0 },
1068 { X86::ADD_Fp64 , X86::ADD_FrST0 },
1069 { X86::ADD_Fp80 , X86::ADD_FrST0 },
1070 { X86::DIV_Fp32 , X86::DIV_FrST0 },
1071 { X86::DIV_Fp64 , X86::DIV_FrST0 },
1072 { X86::DIV_Fp80 , X86::DIV_FrST0 },
1073 { X86::MUL_Fp32 , X86::MUL_FrST0 },
1074 { X86::MUL_Fp64 , X86::MUL_FrST0 },
1075 { X86::MUL_Fp80 , X86::MUL_FrST0 },
1076 { X86::SUB_Fp32 , X86::SUB_FrST0 },
1077 { X86::SUB_Fp64 , X86::SUB_FrST0 },
1078 { X86::SUB_Fp80 , X86::SUB_FrST0 },
1082 /// handleTwoArgFP - Handle instructions like FADD and friends which are virtual
1083 /// instructions which need to be simplified and possibly transformed.
1085 /// Result: ST(0) = fsub ST(0), ST(i)
1086 /// ST(i) = fsub ST(0), ST(i)
1087 /// ST(0) = fsubr ST(0), ST(i)
1088 /// ST(i) = fsubr ST(0), ST(i)
1090 void FPS::handleTwoArgFP(MachineBasicBlock::iterator &I) {
1091 ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
1092 ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
1093 MachineInstr *MI = I;
1095 unsigned NumOperands = MI->getDesc().getNumOperands();
1096 assert(NumOperands == 3 && "Illegal TwoArgFP instruction!");
1097 unsigned Dest = getFPReg(MI->getOperand(0));
1098 unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
1099 unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
1100 bool KillsOp0 = MI->killsRegister(X86::FP0+Op0);
1101 bool KillsOp1 = MI->killsRegister(X86::FP0+Op1);
1102 DebugLoc dl = MI->getDebugLoc();
1104 unsigned TOS = getStackEntry(0);
1106 // One of our operands must be on the top of the stack. If neither is yet, we
1107 // need to move one.
1108 if (Op0 != TOS && Op1 != TOS) { // No operand at TOS?
1109 // We can choose to move either operand to the top of the stack. If one of
1110 // the operands is killed by this instruction, we want that one so that we
1111 // can update right on top of the old version.
1113 moveToTop(Op0, I); // Move dead operand to TOS.
1115 } else if (KillsOp1) {
1119 // All of the operands are live after this instruction executes, so we
1120 // cannot update on top of any operand. Because of this, we must
1121 // duplicate one of the stack elements to the top. It doesn't matter
1122 // which one we pick.
1124 duplicateToTop(Op0, Dest, I);
1128 } else if (!KillsOp0 && !KillsOp1) {
1129 // If we DO have one of our operands at the top of the stack, but we don't
1130 // have a dead operand, we must duplicate one of the operands to a new slot
1132 duplicateToTop(Op0, Dest, I);
1137 // Now we know that one of our operands is on the top of the stack, and at
1138 // least one of our operands is killed by this instruction.
1139 assert((TOS == Op0 || TOS == Op1) && (KillsOp0 || KillsOp1) &&
1140 "Stack conditions not set up right!");
1142 // We decide which form to use based on what is on the top of the stack, and
1143 // which operand is killed by this instruction.
1144 const TableEntry *InstTable;
1145 bool isForward = TOS == Op0;
1146 bool updateST0 = (TOS == Op0 && !KillsOp1) || (TOS == Op1 && !KillsOp0);
1149 InstTable = ForwardST0Table;
1151 InstTable = ReverseST0Table;
1154 InstTable = ForwardSTiTable;
1156 InstTable = ReverseSTiTable;
1159 int Opcode = Lookup(InstTable, array_lengthof(ForwardST0Table),
1161 assert(Opcode != -1 && "Unknown TwoArgFP pseudo instruction!");
1163 // NotTOS - The register which is not on the top of stack...
1164 unsigned NotTOS = (TOS == Op0) ? Op1 : Op0;
1166 // Replace the old instruction with a new instruction
1168 I = BuildMI(*MBB, I, dl, TII->get(Opcode)).addReg(getSTReg(NotTOS));
1170 // If both operands are killed, pop one off of the stack in addition to
1171 // overwriting the other one.
1172 if (KillsOp0 && KillsOp1 && Op0 != Op1) {
1173 assert(!updateST0 && "Should have updated other operand!");
1174 popStackAfter(I); // Pop the top of stack
1177 // Update stack information so that we know the destination register is now on
1179 unsigned UpdatedSlot = getSlot(updateST0 ? TOS : NotTOS);
1180 assert(UpdatedSlot < StackTop && Dest < 7);
1181 Stack[UpdatedSlot] = Dest;
1182 RegMap[Dest] = UpdatedSlot;
1183 MBB->getParent()->DeleteMachineInstr(MI); // Remove the old instruction
1186 /// handleCompareFP - Handle FUCOM and FUCOMI instructions, which have two FP
1187 /// register arguments and no explicit destinations.
1189 void FPS::handleCompareFP(MachineBasicBlock::iterator &I) {
1190 ASSERT_SORTED(ForwardST0Table); ASSERT_SORTED(ReverseST0Table);
1191 ASSERT_SORTED(ForwardSTiTable); ASSERT_SORTED(ReverseSTiTable);
1192 MachineInstr *MI = I;
1194 unsigned NumOperands = MI->getDesc().getNumOperands();
1195 assert(NumOperands == 2 && "Illegal FUCOM* instruction!");
1196 unsigned Op0 = getFPReg(MI->getOperand(NumOperands-2));
1197 unsigned Op1 = getFPReg(MI->getOperand(NumOperands-1));
1198 bool KillsOp0 = MI->killsRegister(X86::FP0+Op0);
1199 bool KillsOp1 = MI->killsRegister(X86::FP0+Op1);
1201 // Make sure the first operand is on the top of stack, the other one can be
1205 // Change from the pseudo instruction to the concrete instruction.
1206 MI->getOperand(0).setReg(getSTReg(Op1));
1207 MI->RemoveOperand(1);
1208 MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
1210 // If any of the operands are killed by this instruction, free them.
1211 if (KillsOp0) freeStackSlotAfter(I, Op0);
1212 if (KillsOp1 && Op0 != Op1) freeStackSlotAfter(I, Op1);
1215 /// handleCondMovFP - Handle two address conditional move instructions. These
1216 /// instructions move a st(i) register to st(0) iff a condition is true. These
1217 /// instructions require that the first operand is at the top of the stack, but
1218 /// otherwise don't modify the stack at all.
1219 void FPS::handleCondMovFP(MachineBasicBlock::iterator &I) {
1220 MachineInstr *MI = I;
1222 unsigned Op0 = getFPReg(MI->getOperand(0));
1223 unsigned Op1 = getFPReg(MI->getOperand(2));
1224 bool KillsOp1 = MI->killsRegister(X86::FP0+Op1);
1226 // The first operand *must* be on the top of the stack.
1229 // Change the second operand to the stack register that the operand is in.
1230 // Change from the pseudo instruction to the concrete instruction.
1231 MI->RemoveOperand(0);
1232 MI->RemoveOperand(1);
1233 MI->getOperand(0).setReg(getSTReg(Op1));
1234 MI->setDesc(TII->get(getConcreteOpcode(MI->getOpcode())));
1236 // If we kill the second operand, make sure to pop it from the stack.
1237 if (Op0 != Op1 && KillsOp1) {
1238 // Get this value off of the register stack.
1239 freeStackSlotAfter(I, Op1);
1244 /// handleSpecialFP - Handle special instructions which behave unlike other
1245 /// floating point instructions. This is primarily intended for use by pseudo
1248 void FPS::handleSpecialFP(MachineBasicBlock::iterator &I) {
1249 MachineInstr *MI = I;
1250 switch (MI->getOpcode()) {
1251 default: llvm_unreachable("Unknown SpecialFP instruction!");
1252 case X86::FpGET_ST0_32:// Appears immediately after a call returning FP type!
1253 case X86::FpGET_ST0_64:// Appears immediately after a call returning FP type!
1254 case X86::FpGET_ST0_80:// Appears immediately after a call returning FP type!
1255 assert(StackTop == 0 && "Stack should be empty after a call!");
1256 pushReg(getFPReg(MI->getOperand(0)));
1258 case X86::FpGET_ST1_32:// Appears immediately after a call returning FP type!
1259 case X86::FpGET_ST1_64:// Appears immediately after a call returning FP type!
1260 case X86::FpGET_ST1_80:{// Appears immediately after a call returning FP type!
1261 // FpGET_ST1 should occur right after a FpGET_ST0 for a call or inline asm.
1262 // The pattern we expect is:
1267 // At this point, we've pushed FP1 on the top of stack, so it should be
1268 // present if it isn't dead. If it was dead, we already emitted a pop to
1269 // remove it from the stack and StackTop = 0.
1271 // Push FP4 as top of stack next.
1272 pushReg(getFPReg(MI->getOperand(0)));
1274 // If StackTop was 0 before we pushed our operand, then ST(0) must have been
1275 // dead. In this case, the ST(1) value is the only thing that is live, so
1276 // it should be on the TOS (after the pop that was emitted) and is. Just
1277 // continue in this case.
1281 // Because pushReg just pushed ST(1) as TOS, we now have to swap the two top
1282 // elements so that our accounting is correct.
1283 unsigned RegOnTop = getStackEntry(0);
1284 unsigned RegNo = getStackEntry(1);
1286 // Swap the slots the regs are in.
1287 std::swap(RegMap[RegNo], RegMap[RegOnTop]);
1289 // Swap stack slot contents.
1290 if (RegMap[RegOnTop] >= StackTop)
1291 report_fatal_error("Access past stack top!");
1292 std::swap(Stack[RegMap[RegOnTop]], Stack[StackTop-1]);
1295 case X86::FpSET_ST0_32:
1296 case X86::FpSET_ST0_64:
1297 case X86::FpSET_ST0_80: {
1298 // FpSET_ST0_80 is generated by copyRegToReg for setting up inline asm
1299 // arguments that use an st constraint. We expect a sequence of
1300 // instructions: Fp_SET_ST0 Fp_SET_ST1? INLINEASM
1301 unsigned Op0 = getFPReg(MI->getOperand(0));
1303 if (!MI->killsRegister(X86::FP0 + Op0)) {
1304 // Duplicate Op0 into a temporary on the stack top.
1305 duplicateToTop(Op0, getScratchReg(), I);
1307 // Op0 is killed, so just swap it into position.
1310 --StackTop; // "Forget" we have something on the top of stack!
1313 case X86::FpSET_ST1_32:
1314 case X86::FpSET_ST1_64:
1315 case X86::FpSET_ST1_80: {
1316 // Set up st(1) for inline asm. We are assuming that st(0) has already been
1317 // set up by FpSET_ST0, and our StackTop is off by one because of it.
1318 unsigned Op0 = getFPReg(MI->getOperand(0));
1319 // Restore the actual StackTop from before Fp_SET_ST0.
1320 // Note we can't handle Fp_SET_ST1 without a preceding Fp_SET_ST0, and we
1321 // are not enforcing the constraint.
1323 unsigned RegOnTop = getStackEntry(0); // This reg must remain in st(0).
1324 if (!MI->killsRegister(X86::FP0 + Op0)) {
1325 duplicateToTop(Op0, getScratchReg(), I);
1326 moveToTop(RegOnTop, I);
1327 } else if (getSTReg(Op0) != X86::ST1) {
1328 // We have the wrong value at st(1). Shuffle! Untested!
1329 moveToTop(getStackEntry(1), I);
1331 moveToTop(RegOnTop, I);
1333 assert(StackTop >= 2 && "Too few live registers");
1334 StackTop -= 2; // "Forget" both st(0) and st(1).
1337 case X86::MOV_Fp3232:
1338 case X86::MOV_Fp3264:
1339 case X86::MOV_Fp6432:
1340 case X86::MOV_Fp6464:
1341 case X86::MOV_Fp3280:
1342 case X86::MOV_Fp6480:
1343 case X86::MOV_Fp8032:
1344 case X86::MOV_Fp8064:
1345 case X86::MOV_Fp8080: {
1346 const MachineOperand &MO1 = MI->getOperand(1);
1347 unsigned SrcReg = getFPReg(MO1);
1349 const MachineOperand &MO0 = MI->getOperand(0);
1350 unsigned DestReg = getFPReg(MO0);
1351 if (MI->killsRegister(X86::FP0+SrcReg)) {
1352 // If the input operand is killed, we can just change the owner of the
1353 // incoming stack slot into the result.
1354 unsigned Slot = getSlot(SrcReg);
1355 assert(Slot < 7 && DestReg < 7 && "FpMOV operands invalid!");
1356 Stack[Slot] = DestReg;
1357 RegMap[DestReg] = Slot;
1360 // For FMOV we just duplicate the specified value to a new stack slot.
1361 // This could be made better, but would require substantial changes.
1362 duplicateToTop(SrcReg, DestReg, I);
1366 case TargetOpcode::INLINEASM: {
1367 // The inline asm MachineInstr currently only *uses* FP registers for the
1368 // 'f' constraint. These should be turned into the current ST(x) register
1369 // in the machine instr. Also, any kills should be explicitly popped after
1372 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1373 MachineOperand &Op = MI->getOperand(i);
1374 if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)
1376 assert(Op.isUse() && "Only handle inline asm uses right now");
1378 unsigned FPReg = getFPReg(Op);
1379 Op.setReg(getSTReg(FPReg));
1381 // If we kill this operand, make sure to pop it from the stack after the
1382 // asm. We just remember it for now, and pop them all off at the end in
1385 Kills |= 1U << FPReg;
1388 // If this asm kills any FP registers (is the last use of them) we must
1389 // explicitly emit pop instructions for them. Do this now after the asm has
1390 // executed so that the ST(x) numbers are not off (which would happen if we
1391 // did this inline with operand rewriting).
1393 // Note: this might be a non-optimal pop sequence. We might be able to do
1394 // better by trying to pop in stack order or something.
1395 MachineBasicBlock::iterator InsertPt = MI;
1397 unsigned FPReg = CountTrailingZeros_32(Kills);
1398 freeStackSlotAfter(InsertPt, FPReg);
1399 Kills &= ~(1U << FPReg);
1401 // Don't delete the inline asm!
1407 // If RET has an FP register use operand, pass the first one in ST(0) and
1408 // the second one in ST(1).
1410 // Find the register operands.
1411 unsigned FirstFPRegOp = ~0U, SecondFPRegOp = ~0U;
1412 unsigned LiveMask = 0;
1414 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1415 MachineOperand &Op = MI->getOperand(i);
1416 if (!Op.isReg() || Op.getReg() < X86::FP0 || Op.getReg() > X86::FP6)
1418 // FP Register uses must be kills unless there are two uses of the same
1419 // register, in which case only one will be a kill.
1420 assert(Op.isUse() &&
1421 (Op.isKill() || // Marked kill.
1422 getFPReg(Op) == FirstFPRegOp || // Second instance.
1423 MI->killsRegister(Op.getReg())) && // Later use is marked kill.
1424 "Ret only defs operands, and values aren't live beyond it");
1426 if (FirstFPRegOp == ~0U)
1427 FirstFPRegOp = getFPReg(Op);
1429 assert(SecondFPRegOp == ~0U && "More than two fp operands!");
1430 SecondFPRegOp = getFPReg(Op);
1432 LiveMask |= (1 << getFPReg(Op));
1434 // Remove the operand so that later passes don't see it.
1435 MI->RemoveOperand(i);
1439 // We may have been carrying spurious live-ins, so make sure only the returned
1440 // registers are left live.
1441 adjustLiveRegs(LiveMask, MI);
1442 if (!LiveMask) return; // Quick check to see if any are possible.
1444 // There are only four possibilities here:
1445 // 1) we are returning a single FP value. In this case, it has to be in
1446 // ST(0) already, so just declare success by removing the value from the
1448 if (SecondFPRegOp == ~0U) {
1449 // Assert that the top of stack contains the right FP register.
1450 assert(StackTop == 1 && FirstFPRegOp == getStackEntry(0) &&
1451 "Top of stack not the right register for RET!");
1453 // Ok, everything is good, mark the value as not being on the stack
1454 // anymore so that our assertion about the stack being empty at end of
1455 // block doesn't fire.
1460 // Otherwise, we are returning two values:
1461 // 2) If returning the same value for both, we only have one thing in the FP
1462 // stack. Consider: RET FP1, FP1
1463 if (StackTop == 1) {
1464 assert(FirstFPRegOp == SecondFPRegOp && FirstFPRegOp == getStackEntry(0)&&
1465 "Stack misconfiguration for RET!");
1467 // Duplicate the TOS so that we return it twice. Just pick some other FPx
1468 // register to hold it.
1469 unsigned NewReg = getScratchReg();
1470 duplicateToTop(FirstFPRegOp, NewReg, MI);
1471 FirstFPRegOp = NewReg;
1474 /// Okay we know we have two different FPx operands now:
1475 assert(StackTop == 2 && "Must have two values live!");
1477 /// 3) If SecondFPRegOp is currently in ST(0) and FirstFPRegOp is currently
1478 /// in ST(1). In this case, emit an fxch.
1479 if (getStackEntry(0) == SecondFPRegOp) {
1480 assert(getStackEntry(1) == FirstFPRegOp && "Unknown regs live");
1481 moveToTop(FirstFPRegOp, MI);
1484 /// 4) Finally, FirstFPRegOp must be in ST(0) and SecondFPRegOp must be in
1485 /// ST(1). Just remove both from our understanding of the stack and return.
1486 assert(getStackEntry(0) == FirstFPRegOp && "Unknown regs live");
1487 assert(getStackEntry(1) == SecondFPRegOp && "Unknown regs live");
1492 I = MBB->erase(I); // Remove the pseudo instruction
1494 // We want to leave I pointing to the previous instruction, but what if we
1495 // just erased the first instruction?
1496 if (I == MBB->begin()) {
1497 DEBUG(dbgs() << "Inserting dummy KILL\n");
1498 I = BuildMI(*MBB, I, DebugLoc(), TII->get(TargetOpcode::KILL));
1503 // Translate a COPY instruction to a pseudo-op that handleSpecialFP understands.
1504 bool FPS::translateCopy(MachineInstr *MI) {
1505 unsigned DstReg = MI->getOperand(0).getReg();
1506 unsigned SrcReg = MI->getOperand(1).getReg();
1508 if (DstReg == X86::ST0) {
1509 MI->setDesc(TII->get(X86::FpSET_ST0_80));
1510 MI->RemoveOperand(0);
1513 if (DstReg == X86::ST1) {
1514 MI->setDesc(TII->get(X86::FpSET_ST1_80));
1515 MI->RemoveOperand(0);
1518 if (SrcReg == X86::ST0) {
1519 MI->setDesc(TII->get(X86::FpGET_ST0_80));
1522 if (SrcReg == X86::ST1) {
1523 MI->setDesc(TII->get(X86::FpGET_ST1_80));
1526 if (X86::RFP80RegClass.contains(DstReg, SrcReg)) {
1527 MI->setDesc(TII->get(X86::MOV_Fp8080));