AVX-512: Added more intrinsics for convert and min/max.
[oota-llvm.git] / lib / Target / X86 / X86VZeroUpper.cpp
1 //===-- X86VZeroUpper.cpp - AVX vzeroupper instruction inserter -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the pass which inserts x86 AVX vzeroupper instructions
11 // before calls to SSE encoded functions. This avoids transition latency
12 // penalty when tranfering control between AVX encoded instructions and old
13 // SSE encoding mode.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "x86-vzeroupper"
18 #include "X86.h"
19 #include "X86InstrInfo.h"
20 #include "X86Subtarget.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 using namespace llvm;
30
31 STATISTIC(NumVZU, "Number of vzeroupper instructions inserted");
32
33 namespace {
34   struct VZeroUpperInserter : public MachineFunctionPass {
35     static char ID;
36     VZeroUpperInserter() : MachineFunctionPass(ID) {}
37
38     virtual bool runOnMachineFunction(MachineFunction &MF);
39
40     bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
41
42     virtual const char *getPassName() const { return "X86 vzeroupper inserter";}
43
44   private:
45     const TargetInstrInfo *TII; // Machine instruction info.
46
47     // Any YMM register live-in to this function?
48     bool FnHasLiveInYmm;
49
50     // BBState - Contains the state of each MBB: unknown, clean, dirty
51     SmallVector<uint8_t, 8> BBState;
52
53     // BBSolved - Keep track of all MBB which had been already analyzed
54     // and there is no further processing required.
55     BitVector BBSolved;
56
57     // Machine Basic Blocks are classified according this pass:
58     //
59     //  ST_UNKNOWN - The MBB state is unknown, meaning from the entry state
60     //    until the MBB exit there isn't a instruction using YMM to change
61     //    the state to dirty, or one of the incoming predecessors is unknown
62     //    and there's not a dirty predecessor between them.
63     //
64     //  ST_CLEAN - No YMM usage in the end of the MBB. A MBB could have
65     //    instructions using YMM and be marked ST_CLEAN, as long as the state
66     //    is cleaned by a vzeroupper before any call.
67     //
68     //  ST_DIRTY - Any MBB ending with a YMM usage not cleaned up by a
69     //    vzeroupper instruction.
70     //
71     //  ST_INIT - Placeholder for an empty state set
72     //
73     enum {
74       ST_UNKNOWN = 0,
75       ST_CLEAN   = 1,
76       ST_DIRTY   = 2,
77       ST_INIT    = 3
78     };
79
80     // computeState - Given two states, compute the resulting state, in
81     // the following way
82     //
83     //  1) One dirty state yields another dirty state
84     //  2) All states must be clean for the result to be clean
85     //  3) If none above and one unknown, the result state is also unknown
86     //
87     static unsigned computeState(unsigned PrevState, unsigned CurState) {
88       if (PrevState == ST_INIT)
89         return CurState;
90
91       if (PrevState == ST_DIRTY || CurState == ST_DIRTY)
92         return ST_DIRTY;
93
94       if (PrevState == ST_CLEAN && CurState == ST_CLEAN)
95         return ST_CLEAN;
96
97       return ST_UNKNOWN;
98     }
99
100   };
101   char VZeroUpperInserter::ID = 0;
102 }
103
104 FunctionPass *llvm::createX86IssueVZeroUpperPass() {
105   return new VZeroUpperInserter();
106 }
107
108 static bool isYmmReg(unsigned Reg) {
109   return (Reg >= X86::YMM0 && Reg <= X86::YMM15);
110 }
111
112 static bool checkFnHasLiveInYmm(MachineRegisterInfo &MRI) {
113   for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(),
114        E = MRI.livein_end(); I != E; ++I)
115     if (isYmmReg(I->first))
116       return true;
117
118   return false;
119 }
120
121 static bool clobbersAllYmmRegs(const MachineOperand &MO) {
122   for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
123     if (!MO.clobbersPhysReg(reg))
124       return false;
125   }
126   return true;
127 }
128
129 static bool hasYmmReg(MachineInstr *MI) {
130   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
131     const MachineOperand &MO = MI->getOperand(i);
132     if (MI->isCall() && MO.isRegMask() && !clobbersAllYmmRegs(MO))
133       return true;
134     if (!MO.isReg())
135       continue;
136     if (MO.isDebug())
137       continue;
138     if (isYmmReg(MO.getReg()))
139       return true;
140   }
141   return false;
142 }
143
144 /// clobbersAnyYmmReg() - Check if any YMM register will be clobbered by this
145 /// instruction.
146 static bool clobbersAnyYmmReg(MachineInstr *MI) {
147   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
148     const MachineOperand &MO = MI->getOperand(i);
149     if (!MO.isRegMask())
150       continue;
151     for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
152       if (MO.clobbersPhysReg(reg))
153         return true;
154     }
155   }
156   return false;
157 }
158
159 /// runOnMachineFunction - Loop over all of the basic blocks, inserting
160 /// vzero upper instructions before function calls.
161 bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) {
162   if (MF.getTarget().getSubtarget<X86Subtarget>().hasAVX512())
163     return false;
164   TII = MF.getTarget().getInstrInfo();
165   MachineRegisterInfo &MRI = MF.getRegInfo();
166   bool EverMadeChange = false;
167
168   // Fast check: if the function doesn't use any ymm registers, we don't need
169   // to insert any VZEROUPPER instructions.  This is constant-time, so it is
170   // cheap in the common case of no ymm use.
171   bool YMMUsed = false;
172   const TargetRegisterClass *RC = &X86::VR256RegClass;
173   for (TargetRegisterClass::iterator i = RC->begin(), e = RC->end();
174        i != e; i++) {
175     if (!MRI.reg_nodbg_empty(*i)) {
176       YMMUsed = true;
177       break;
178     }
179   }
180   if (!YMMUsed)
181     return EverMadeChange;
182
183   // Pre-compute the existence of any live-in YMM registers to this function
184   FnHasLiveInYmm = checkFnHasLiveInYmm(MRI);
185
186   assert(BBState.empty());
187   BBState.resize(MF.getNumBlockIDs(), 0);
188   BBSolved.resize(MF.getNumBlockIDs(), 0);
189
190   // Each BB state depends on all predecessors, loop over until everything
191   // converges.  (Once we converge, we can implicitly mark everything that is
192   // still ST_UNKNOWN as ST_CLEAN.)
193   while (1) {
194     bool MadeChange = false;
195
196     // Process all basic blocks.
197     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
198       MadeChange |= processBasicBlock(MF, *I);
199
200     // If this iteration over the code changed anything, keep iterating.
201     if (!MadeChange) break;
202     EverMadeChange = true;
203   }
204
205   BBState.clear();
206   BBSolved.clear();
207   return EverMadeChange;
208 }
209
210 /// processBasicBlock - Loop over all of the instructions in the basic block,
211 /// inserting vzero upper instructions before function calls.
212 bool VZeroUpperInserter::processBasicBlock(MachineFunction &MF,
213                                            MachineBasicBlock &BB) {
214   bool Changed = false;
215   unsigned BBNum = BB.getNumber();
216
217   // Don't process already solved BBs
218   if (BBSolved[BBNum])
219     return false; // No changes
220
221   // Check the state of all predecessors
222   unsigned EntryState = ST_INIT;
223   for (MachineBasicBlock::const_pred_iterator PI = BB.pred_begin(),
224        PE = BB.pred_end(); PI != PE; ++PI) {
225     EntryState = computeState(EntryState, BBState[(*PI)->getNumber()]);
226     if (EntryState == ST_DIRTY)
227       break;
228   }
229
230
231   // The entry MBB for the function may set the initial state to dirty if
232   // the function receives any YMM incoming arguments
233   if (&BB == MF.begin()) {
234     EntryState = ST_CLEAN;
235     if (FnHasLiveInYmm)
236       EntryState = ST_DIRTY;
237   }
238
239   // The current state is initialized according to the predecessors
240   unsigned CurState = EntryState;
241   bool BBHasCall = false;
242
243   for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
244     DebugLoc dl = I->getDebugLoc();
245     MachineInstr *MI = I;
246
247     bool isControlFlow = MI->isCall() || MI->isReturn();
248
249     // Shortcut: don't need to check regular instructions in dirty state.
250     if (!isControlFlow && CurState == ST_DIRTY)
251       continue;
252
253     if (hasYmmReg(MI)) {
254       // We found a ymm-using instruction; this could be an AVX instruction,
255       // or it could be control flow.
256       CurState = ST_DIRTY;
257       continue;
258     }
259
260     // Check for control-flow out of the current function (which might
261     // indirectly execute SSE instructions).
262     if (!isControlFlow)
263       continue;
264
265     // If the call won't clobber any YMM register, skip it as well. It usually
266     // happens on helper function calls (such as '_chkstk', '_ftol2') where
267     // standard calling convention is not used (RegMask is not used to mark
268     // register clobbered and register usage (def/imp-def/use) is well-dfined
269     // and explicitly specified.
270     if (MI->isCall() && !clobbersAnyYmmReg(MI))
271       continue;
272
273     BBHasCall = true;
274
275     // The VZEROUPPER instruction resets the upper 128 bits of all Intel AVX
276     // registers. This instruction has zero latency. In addition, the processor
277     // changes back to Clean state, after which execution of Intel SSE
278     // instructions or Intel AVX instructions has no transition penalty. Add
279     // the VZEROUPPER instruction before any function call/return that might
280     // execute SSE code.
281     // FIXME: In some cases, we may want to move the VZEROUPPER into a
282     // predecessor block.
283     if (CurState == ST_DIRTY) {
284       // Only insert the VZEROUPPER in case the entry state isn't unknown.
285       // When unknown, only compute the information within the block to have
286       // it available in the exit if possible, but don't change the block.
287       if (EntryState != ST_UNKNOWN) {
288         BuildMI(BB, I, dl, TII->get(X86::VZEROUPPER));
289         ++NumVZU;
290       }
291
292       // After the inserted VZEROUPPER the state becomes clean again, but
293       // other YMM may appear before other subsequent calls or even before
294       // the end of the BB.
295       CurState = ST_CLEAN;
296     }
297   }
298
299   DEBUG(dbgs() << "MBB #" << BBNum
300                << ", current state: " << CurState << '\n');
301
302   // A BB can only be considered solved when we both have done all the
303   // necessary transformations, and have computed the exit state.  This happens
304   // in two cases:
305   //  1) We know the entry state: this immediately implies the exit state and
306   //     all the necessary transformations.
307   //  2) There are no calls, and and a non-call instruction marks this block:
308   //     no transformations are necessary, and we know the exit state.
309   if (EntryState != ST_UNKNOWN || (!BBHasCall && CurState != ST_UNKNOWN))
310     BBSolved[BBNum] = true;
311
312   if (CurState != BBState[BBNum])
313     Changed = true;
314
315   BBState[BBNum] = CurState;
316   return Changed;
317 }