1 //===-- X86VZeroUpper.cpp - AVX vzeroupper instruction inserter -----------===//
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 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
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "x86-vzeroupper"
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"
31 STATISTIC(NumVZU, "Number of vzeroupper instructions inserted");
34 struct VZeroUpperInserter : public MachineFunctionPass {
36 VZeroUpperInserter() : MachineFunctionPass(ID) {}
38 bool runOnMachineFunction(MachineFunction &MF) override;
40 bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
42 const char *getPassName() const override {return "X86 vzeroupper inserter";}
45 const TargetInstrInfo *TII; // Machine instruction info.
47 // Any YMM register live-in to this function?
50 // BBState - Contains the state of each MBB: unknown, clean, dirty
51 SmallVector<uint8_t, 8> BBState;
53 // BBSolved - Keep track of all MBB which had been already analyzed
54 // and there is no further processing required.
57 // Machine Basic Blocks are classified according this pass:
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.
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.
68 // ST_DIRTY - Any MBB ending with a YMM usage not cleaned up by a
69 // vzeroupper instruction.
71 // ST_INIT - Placeholder for an empty state set
80 // computeState - Given two states, compute the resulting state, in
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
87 static unsigned computeState(unsigned PrevState, unsigned CurState) {
88 if (PrevState == ST_INIT)
91 if (PrevState == ST_DIRTY || CurState == ST_DIRTY)
94 if (PrevState == ST_CLEAN && CurState == ST_CLEAN)
101 char VZeroUpperInserter::ID = 0;
104 FunctionPass *llvm::createX86IssueVZeroUpperPass() {
105 return new VZeroUpperInserter();
108 static bool isYmmReg(unsigned Reg) {
109 return (Reg >= X86::YMM0 && Reg <= X86::YMM15);
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))
121 static bool clobbersAllYmmRegs(const MachineOperand &MO) {
122 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
123 if (!MO.clobbersPhysReg(reg))
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))
138 if (isYmmReg(MO.getReg()))
144 /// clobbersAnyYmmReg() - Check if any YMM register will be clobbered by this
146 static bool clobbersAnyYmmReg(MachineInstr *MI) {
147 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
148 const MachineOperand &MO = MI->getOperand(i);
151 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
152 if (MO.clobbersPhysReg(reg))
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())
164 TII = MF.getTarget().getInstrInfo();
165 MachineRegisterInfo &MRI = MF.getRegInfo();
166 bool EverMadeChange = false;
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();
175 if (!MRI.reg_nodbg_empty(*i)) {
181 return EverMadeChange;
183 // Pre-compute the existence of any live-in YMM registers to this function
184 FnHasLiveInYmm = checkFnHasLiveInYmm(MRI);
186 assert(BBState.empty());
187 BBState.resize(MF.getNumBlockIDs(), 0);
188 BBSolved.resize(MF.getNumBlockIDs(), 0);
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.)
194 bool MadeChange = false;
196 // Process all basic blocks.
197 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
198 MadeChange |= processBasicBlock(MF, *I);
200 // If this iteration over the code changed anything, keep iterating.
201 if (!MadeChange) break;
202 EverMadeChange = true;
207 return EverMadeChange;
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();
217 // Don't process already solved BBs
219 return false; // No changes
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)
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;
236 EntryState = ST_DIRTY;
239 // The current state is initialized according to the predecessors
240 unsigned CurState = EntryState;
241 bool BBHasCall = false;
243 for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
244 DebugLoc dl = I->getDebugLoc();
245 MachineInstr *MI = I;
247 bool isControlFlow = MI->isCall() || MI->isReturn();
249 // Shortcut: don't need to check regular instructions in dirty state.
250 if (!isControlFlow && CurState == ST_DIRTY)
254 // We found a ymm-using instruction; this could be an AVX instruction,
255 // or it could be control flow.
260 // Check for control-flow out of the current function (which might
261 // indirectly execute SSE instructions).
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))
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
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));
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.
299 DEBUG(dbgs() << "MBB #" << BBNum
300 << ", current state: " << CurState << '\n');
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
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;
312 if (CurState != BBState[BBNum])
315 BBState[BBNum] = CurState;