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 transferring control between AVX encoded instructions and old
13 // SSE encoding mode.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "X86.h"
18 #include "X86InstrInfo.h"
19 #include "X86Subtarget.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "x86-vzeroupper"
31 
32 STATISTIC(NumVZU, "Number of vzeroupper instructions inserted");
33 
34 namespace {
35 
36   class VZeroUpperInserter : public MachineFunctionPass {
37   public:
38 
39     VZeroUpperInserter() : MachineFunctionPass(ID) {}
40     bool runOnMachineFunction(MachineFunction &MF) override;
41     MachineFunctionProperties getRequiredProperties() const override {
42       return MachineFunctionProperties().set(
43           MachineFunctionProperties::Property::AllVRegsAllocated);
44     }
45     const char *getPassName() const override {return "X86 vzeroupper inserter";}
46 
47   private:
48 
49     void processBasicBlock(MachineBasicBlock &MBB);
50     void insertVZeroUpper(MachineBasicBlock::iterator I,
51                           MachineBasicBlock &MBB);
52     void addDirtySuccessor(MachineBasicBlock &MBB);
53 
54     typedef enum { PASS_THROUGH, EXITS_CLEAN, EXITS_DIRTY } BlockExitState;
55     static const char* getBlockExitStateName(BlockExitState ST);
56 
57     // Core algorithm state:
58     // BlockState - Each block is either:
59     //   - PASS_THROUGH: There are neither YMM dirtying instructions nor
60     //                   vzeroupper instructions in this block.
61     //   - EXITS_CLEAN: There is (or will be) a vzeroupper instruction in this
62     //                  block that will ensure that YMM is clean on exit.
63     //   - EXITS_DIRTY: An instruction in the block dirties YMM and no
64     //                  subsequent vzeroupper in the block clears it.
65     //
66     // AddedToDirtySuccessors - This flag is raised when a block is added to the
67     //                          DirtySuccessors list to ensure that it's not
68     //                          added multiple times.
69     //
70     // FirstUnguardedCall - Records the location of the first unguarded call in
71     //                      each basic block that may need to be guarded by a
72     //                      vzeroupper. We won't know whether it actually needs
73     //                      to be guarded until we discover a predecessor that
74     //                      is DIRTY_OUT.
75     struct BlockState {
76       BlockState() : ExitState(PASS_THROUGH), AddedToDirtySuccessors(false) {}
77       BlockExitState ExitState;
78       bool AddedToDirtySuccessors;
79       MachineBasicBlock::iterator FirstUnguardedCall;
80     };
81     typedef SmallVector<BlockState, 8> BlockStateMap;
82     typedef SmallVector<MachineBasicBlock*, 8> DirtySuccessorsWorkList;
83 
84     BlockStateMap BlockStates;
85     DirtySuccessorsWorkList DirtySuccessors;
86     bool EverMadeChange;
87     bool IsX86INTR;
88     const TargetInstrInfo *TII;
89 
90     static char ID;
91   };
92 
93   char VZeroUpperInserter::ID = 0;
94 }
95 
96 FunctionPass *llvm::createX86IssueVZeroUpperPass() {
97   return new VZeroUpperInserter();
98 }
99 
100 const char* VZeroUpperInserter::getBlockExitStateName(BlockExitState ST) {
101   switch (ST) {
102     case PASS_THROUGH: return "Pass-through";
103     case EXITS_DIRTY: return "Exits-dirty";
104     case EXITS_CLEAN: return "Exits-clean";
105   }
106   llvm_unreachable("Invalid block exit state.");
107 }
108 
109 static bool isYmmReg(unsigned Reg) {
110   return (Reg >= X86::YMM0 && Reg <= X86::YMM15);
111 }
112 
113 static bool checkFnHasLiveInYmm(MachineRegisterInfo &MRI) {
114   for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(),
115        E = MRI.livein_end(); I != E; ++I)
116     if (isYmmReg(I->first))
117       return true;
118 
119   return false;
120 }
121 
122 static bool clobbersAllYmmRegs(const MachineOperand &MO) {
123   for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
124     if (!MO.clobbersPhysReg(reg))
125       return false;
126   }
127   return true;
128 }
129 
130 static bool hasYmmReg(MachineInstr *MI) {
131   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
132     const MachineOperand &MO = MI->getOperand(i);
133     if (MI->isCall() && MO.isRegMask() && !clobbersAllYmmRegs(MO))
134       return true;
135     if (!MO.isReg())
136       continue;
137     if (MO.isDebug())
138       continue;
139     if (isYmmReg(MO.getReg()))
140       return true;
141   }
142   return false;
143 }
144 
145 /// Check if any YMM register will be clobbered by this instruction.
146 static bool callClobbersAnyYmmReg(MachineInstr *MI) {
147   assert(MI->isCall() && "Can only be called on call instructions.");
148   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
149     const MachineOperand &MO = MI->getOperand(i);
150     if (!MO.isRegMask())
151       continue;
152     for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
153       if (MO.clobbersPhysReg(reg))
154         return true;
155     }
156   }
157   return false;
158 }
159 
160 /// Insert a vzeroupper instruction before I.
161 void VZeroUpperInserter::insertVZeroUpper(MachineBasicBlock::iterator I,
162                                           MachineBasicBlock &MBB) {
163   DebugLoc dl = I->getDebugLoc();
164   BuildMI(MBB, I, dl, TII->get(X86::VZEROUPPER));
165   ++NumVZU;
166   EverMadeChange = true;
167 }
168 
169 /// Add MBB to the DirtySuccessors list if it hasn't already been added.
170 void VZeroUpperInserter::addDirtySuccessor(MachineBasicBlock &MBB) {
171   if (!BlockStates[MBB.getNumber()].AddedToDirtySuccessors) {
172     DirtySuccessors.push_back(&MBB);
173     BlockStates[MBB.getNumber()].AddedToDirtySuccessors = true;
174   }
175 }
176 
177 /// Loop over all of the instructions in the basic block, inserting vzeroupper
178 /// instructions before function calls.
179 void VZeroUpperInserter::processBasicBlock(MachineBasicBlock &MBB) {
180 
181   // Start by assuming that the block PASS_THROUGH, which implies no unguarded
182   // calls.
183   BlockExitState CurState = PASS_THROUGH;
184   BlockStates[MBB.getNumber()].FirstUnguardedCall = MBB.end();
185 
186   for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
187     MachineInstr *MI = I;
188     // No need for vzeroupper before iret in interrupt handler function,
189     // epilogue will restore YMM registers if needed.
190     bool IsReturnFromX86INTR = IsX86INTR && MI->isReturn();
191     bool IsControlFlow = MI->isCall() || MI->isReturn();
192 
193     // Shortcut: don't need to check regular instructions in dirty state.
194     if ((!IsControlFlow || IsReturnFromX86INTR) && CurState == EXITS_DIRTY)
195       continue;
196 
197     if (hasYmmReg(MI)) {
198       // We found a ymm-using instruction; this could be an AVX instruction,
199       // or it could be control flow.
200       CurState = EXITS_DIRTY;
201       continue;
202     }
203 
204     // Check for control-flow out of the current function (which might
205     // indirectly execute SSE instructions).
206     if (!IsControlFlow || IsReturnFromX86INTR)
207       continue;
208 
209     // If the call won't clobber any YMM register, skip it as well. It usually
210     // happens on helper function calls (such as '_chkstk', '_ftol2') where
211     // standard calling convention is not used (RegMask is not used to mark
212     // register clobbered and register usage (def/imp-def/use) is well-defined
213     // and explicitly specified.
214     if (MI->isCall() && !callClobbersAnyYmmReg(MI))
215       continue;
216 
217     // The VZEROUPPER instruction resets the upper 128 bits of all Intel AVX
218     // registers. This instruction has zero latency. In addition, the processor
219     // changes back to Clean state, after which execution of Intel SSE
220     // instructions or Intel AVX instructions has no transition penalty. Add
221     // the VZEROUPPER instruction before any function call/return that might
222     // execute SSE code.
223     // FIXME: In some cases, we may want to move the VZEROUPPER into a
224     // predecessor block.
225     if (CurState == EXITS_DIRTY) {
226       // After the inserted VZEROUPPER the state becomes clean again, but
227       // other YMM may appear before other subsequent calls or even before
228       // the end of the BB.
229       insertVZeroUpper(I, MBB);
230       CurState = EXITS_CLEAN;
231     } else if (CurState == PASS_THROUGH) {
232       // If this block is currently in pass-through state and we encounter a
233       // call then whether we need a vzeroupper or not depends on whether this
234       // block has successors that exit dirty. Record the location of the call,
235       // and set the state to EXITS_CLEAN, but do not insert the vzeroupper yet.
236       // It will be inserted later if necessary.
237       BlockStates[MBB.getNumber()].FirstUnguardedCall = I;
238       CurState = EXITS_CLEAN;
239     }
240   }
241 
242   DEBUG(dbgs() << "MBB #" << MBB.getNumber() << " exit state: "
243                << getBlockExitStateName(CurState) << '\n');
244 
245   if (CurState == EXITS_DIRTY)
246     for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
247                                           SE = MBB.succ_end();
248          SI != SE; ++SI)
249       addDirtySuccessor(**SI);
250 
251   BlockStates[MBB.getNumber()].ExitState = CurState;
252 }
253 
254 /// Loop over all of the basic blocks, inserting vzeroupper instructions before
255 /// function calls.
256 bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) {
257   const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
258   if (!ST.hasAVX() || ST.hasAVX512() || ST.hasFastPartialYMMWrite())
259     return false;
260   TII = ST.getInstrInfo();
261   MachineRegisterInfo &MRI = MF.getRegInfo();
262   EverMadeChange = false;
263   IsX86INTR = MF.getFunction()->getCallingConv() == CallingConv::X86_INTR;
264 
265   bool FnHasLiveInYmm = checkFnHasLiveInYmm(MRI);
266 
267   // Fast check: if the function doesn't use any ymm registers, we don't need
268   // to insert any VZEROUPPER instructions.  This is constant-time, so it is
269   // cheap in the common case of no ymm use.
270   bool YMMUsed = FnHasLiveInYmm;
271   if (!YMMUsed) {
272     const TargetRegisterClass *RC = &X86::VR256RegClass;
273     for (TargetRegisterClass::iterator i = RC->begin(), e = RC->end(); i != e;
274          i++) {
275       if (!MRI.reg_nodbg_empty(*i)) {
276         YMMUsed = true;
277         break;
278       }
279     }
280   }
281   if (!YMMUsed) {
282     return false;
283   }
284 
285   assert(BlockStates.empty() && DirtySuccessors.empty() &&
286          "X86VZeroUpper state should be clear");
287   BlockStates.resize(MF.getNumBlockIDs());
288 
289   // Process all blocks. This will compute block exit states, record the first
290   // unguarded call in each block, and add successors of dirty blocks to the
291   // DirtySuccessors list.
292   for (MachineBasicBlock &MBB : MF)
293     processBasicBlock(MBB);
294 
295   // If any YMM regs are live in to this function, add the entry block to the
296   // DirtySuccessors list
297   if (FnHasLiveInYmm)
298     addDirtySuccessor(MF.front());
299 
300   // Re-visit all blocks that are successors of EXITS_DIRTY bsocks. Add
301   // vzeroupper instructions to unguarded calls, and propagate EXITS_DIRTY
302   // through PASS_THROUGH blocks.
303   while (!DirtySuccessors.empty()) {
304     MachineBasicBlock &MBB = *DirtySuccessors.back();
305     DirtySuccessors.pop_back();
306     BlockState &BBState = BlockStates[MBB.getNumber()];
307 
308     // MBB is a successor of a dirty block, so its first call needs to be
309     // guarded.
310     if (BBState.FirstUnguardedCall != MBB.end())
311       insertVZeroUpper(BBState.FirstUnguardedCall, MBB);
312 
313     // If this successor was a pass-through block then it is now dirty, and its
314     // successors need to be added to the worklist (if they haven't been
315     // already).
316     if (BBState.ExitState == PASS_THROUGH) {
317       DEBUG(dbgs() << "MBB #" << MBB.getNumber()
318                    << " was Pass-through, is now Dirty-out.\n");
319       for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
320                                             SE = MBB.succ_end();
321            SI != SE; ++SI)
322         addDirtySuccessor(**SI);
323     }
324   }
325 
326   BlockStates.clear();
327   return EverMadeChange;
328 }
329