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");
35 class VZeroUpperInserter : public MachineFunctionPass {
38 VZeroUpperInserter() : MachineFunctionPass(ID) {}
39 bool runOnMachineFunction(MachineFunction &MF) override;
40 const char *getPassName() const override {return "X86 vzeroupper inserter";}
44 void processBasicBlock(MachineBasicBlock &MBB);
45 void insertVZeroUpper(MachineBasicBlock::iterator I,
46 MachineBasicBlock &MBB);
47 void addDirtySuccessor(MachineBasicBlock &MBB);
49 typedef enum { PASS_THROUGH, EXITS_CLEAN, EXITS_DIRTY } BlockExitState;
50 static const char* getBlockExitStateName(BlockExitState ST);
52 // Core algorithm state:
53 // BlockState - Each block is either:
54 // - PASS_THROUGH: There are neither YMM dirtying instructions nor
55 // vzeroupper instructions in this block.
56 // - EXITS_CLEAN: There is (or will be) a vzeroupper instruction in this
57 // block that will ensure that YMM is clean on exit.
58 // - EXITS_DIRTY: An instruction in the block dirties YMM and no
59 // subsequent vzeroupper in the block clears it.
61 // AddedToDirtySuccessors - This flag is raised when a block is added to the
62 // DirtySuccessors list to ensure that it's not
63 // added multiple times.
65 // FirstUnguardedCall - Records the location of the first unguarded call in
66 // each basic block that may need to be guarded by a
67 // vzeroupper. We won't know whether it actually needs
68 // to be guarded until we discover a predecessor that
71 BlockState() : ExitState(PASS_THROUGH), AddedToDirtySuccessors(false) {}
72 BlockExitState ExitState;
73 bool AddedToDirtySuccessors;
74 MachineBasicBlock::iterator FirstUnguardedCall;
76 typedef SmallVector<BlockState, 8> BlockStateMap;
77 typedef SmallVector<MachineBasicBlock*, 8> DirtySuccessorsWorkList;
79 BlockStateMap BlockStates;
80 DirtySuccessorsWorkList DirtySuccessors;
82 const TargetInstrInfo *TII;
87 char VZeroUpperInserter::ID = 0;
90 FunctionPass *llvm::createX86IssueVZeroUpperPass() {
91 return new VZeroUpperInserter();
94 const char* VZeroUpperInserter::getBlockExitStateName(BlockExitState ST) {
96 case PASS_THROUGH: return "Pass-through";
97 case EXITS_DIRTY: return "Exits-dirty";
98 case EXITS_CLEAN: return "Exits-clean";
100 llvm_unreachable("Invalid block exit state.");
103 static bool isYmmReg(unsigned Reg) {
104 return (Reg >= X86::YMM0 && Reg <= X86::YMM15);
107 static bool checkFnHasLiveInYmm(MachineRegisterInfo &MRI) {
108 for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(),
109 E = MRI.livein_end(); I != E; ++I)
110 if (isYmmReg(I->first))
116 static bool clobbersAllYmmRegs(const MachineOperand &MO) {
117 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
118 if (!MO.clobbersPhysReg(reg))
124 static bool hasYmmReg(MachineInstr *MI) {
125 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
126 const MachineOperand &MO = MI->getOperand(i);
127 if (MI->isCall() && MO.isRegMask() && !clobbersAllYmmRegs(MO))
133 if (isYmmReg(MO.getReg()))
139 /// clobbersAnyYmmReg() - Check if any YMM register will be clobbered by this
141 static bool callClobbersAnyYmmReg(MachineInstr *MI) {
142 assert(MI->isCall() && "Can only be called on call instructions.");
143 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
144 const MachineOperand &MO = MI->getOperand(i);
147 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
148 if (MO.clobbersPhysReg(reg))
155 // Insert a vzeroupper instruction before I.
156 void VZeroUpperInserter::insertVZeroUpper(MachineBasicBlock::iterator I,
157 MachineBasicBlock &MBB) {
158 DebugLoc dl = I->getDebugLoc();
159 BuildMI(MBB, I, dl, TII->get(X86::VZEROUPPER));
161 EverMadeChange = true;
164 // Add MBB to the DirtySuccessors list if it hasn't already been added.
165 void VZeroUpperInserter::addDirtySuccessor(MachineBasicBlock &MBB) {
166 if (!BlockStates[MBB.getNumber()].AddedToDirtySuccessors) {
167 DirtySuccessors.push_back(&MBB);
168 BlockStates[MBB.getNumber()].AddedToDirtySuccessors = true;
172 /// processBasicBlock - Loop over all of the instructions in the basic block,
173 /// inserting vzero upper instructions before function calls.
174 void VZeroUpperInserter::processBasicBlock(MachineBasicBlock &MBB) {
176 // Start by assuming that the block PASS_THROUGH, which implies no unguarded
178 BlockExitState CurState = PASS_THROUGH;
179 BlockStates[MBB.getNumber()].FirstUnguardedCall = MBB.end();
181 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
182 MachineInstr *MI = I;
183 bool isControlFlow = MI->isCall() || MI->isReturn();
185 // Shortcut: don't need to check regular instructions in dirty state.
186 if (!isControlFlow && CurState == EXITS_DIRTY)
190 // We found a ymm-using instruction; this could be an AVX instruction,
191 // or it could be control flow.
192 CurState = EXITS_DIRTY;
196 // Check for control-flow out of the current function (which might
197 // indirectly execute SSE instructions).
201 // If the call won't clobber any YMM register, skip it as well. It usually
202 // happens on helper function calls (such as '_chkstk', '_ftol2') where
203 // standard calling convention is not used (RegMask is not used to mark
204 // register clobbered and register usage (def/imp-def/use) is well-dfined
205 // and explicitly specified.
206 if (MI->isCall() && !callClobbersAnyYmmReg(MI))
209 // The VZEROUPPER instruction resets the upper 128 bits of all Intel AVX
210 // registers. This instruction has zero latency. In addition, the processor
211 // changes back to Clean state, after which execution of Intel SSE
212 // instructions or Intel AVX instructions has no transition penalty. Add
213 // the VZEROUPPER instruction before any function call/return that might
215 // FIXME: In some cases, we may want to move the VZEROUPPER into a
216 // predecessor block.
217 if (CurState == EXITS_DIRTY) {
218 // After the inserted VZEROUPPER the state becomes clean again, but
219 // other YMM may appear before other subsequent calls or even before
220 // the end of the BB.
221 insertVZeroUpper(I, MBB);
222 CurState = EXITS_CLEAN;
223 } else if (CurState == PASS_THROUGH) {
224 // If this block is currently in pass-through state and we encounter a
225 // call then whether we need a vzeroupper or not depends on whether this
226 // block has successors that exit dirty. Record the location of the call,
227 // and set the state to EXITS_CLEAN, but do not insert the vzeroupper yet.
228 // It will be inserted later if necessary.
229 BlockStates[MBB.getNumber()].FirstUnguardedCall = I;
230 CurState = EXITS_CLEAN;
234 DEBUG(dbgs() << "MBB #" << MBB.getNumber() << " exit state: "
235 << getBlockExitStateName(CurState) << '\n');
237 if (CurState == EXITS_DIRTY)
238 for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
241 addDirtySuccessor(**SI);
243 BlockStates[MBB.getNumber()].ExitState = CurState;
246 /// runOnMachineFunction - Loop over all of the basic blocks, inserting
247 /// vzero upper instructions before function calls.
248 bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) {
249 if (MF.getTarget().getSubtarget<X86Subtarget>().hasAVX512())
251 TII = MF.getTarget().getInstrInfo();
252 MachineRegisterInfo &MRI = MF.getRegInfo();
253 EverMadeChange = false;
255 // Fast check: if the function doesn't use any ymm registers, we don't need
256 // to insert any VZEROUPPER instructions. This is constant-time, so it is
257 // cheap in the common case of no ymm use.
258 bool YMMUsed = false;
259 const TargetRegisterClass *RC = &X86::VR256RegClass;
260 for (TargetRegisterClass::iterator i = RC->begin(), e = RC->end();
262 if (!MRI.reg_nodbg_empty(*i)) {
271 assert(BlockStates.empty() && DirtySuccessors.empty() &&
272 "X86VZeroUpper state should be clear");
273 BlockStates.resize(MF.getNumBlockIDs());
275 // Process all blocks. This will compute block exit states, record the first
276 // unguarded call in each block, and add successors of dirty blocks to the
277 // DirtySuccessors list.
278 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
279 processBasicBlock(*I);
281 // If any YMM regs are live in to this function, add the entry block to the
282 // DirtySuccessors list
283 if (checkFnHasLiveInYmm(MRI))
284 addDirtySuccessor(MF.front());
286 // Re-visit all blocks that are successors of EXITS_DIRTY bsocks. Add
287 // vzeroupper instructions to unguarded calls, and propagate EXITS_DIRTY
288 // through PASS_THROUGH blocks.
289 while (!DirtySuccessors.empty()) {
290 MachineBasicBlock &MBB = *DirtySuccessors.back();
291 DirtySuccessors.pop_back();
292 BlockState &BBState = BlockStates[MBB.getNumber()];
294 // MBB is a successor of a dirty block, so its first call needs to be
296 if (BBState.FirstUnguardedCall != MBB.end())
297 insertVZeroUpper(BBState.FirstUnguardedCall, MBB);
299 // If this successor was a pass-through block then it is now dirty, and its
300 // successors need to be added to the worklist (if they haven't been
302 if (BBState.ExitState == PASS_THROUGH) {
303 DEBUG(dbgs() << "MBB #" << MBB.getNumber()
304 << " was Pass-through, is now Dirty-out.\n");
305 for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
308 addDirtySuccessor(**SI);
313 return EverMadeChange;