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 "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"
30 STATISTIC(NumVZU, "Number of vzeroupper instructions inserted");
33 struct VZeroUpperInserter : public MachineFunctionPass {
35 VZeroUpperInserter() : MachineFunctionPass(ID) {}
37 virtual bool runOnMachineFunction(MachineFunction &MF);
39 bool processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
41 virtual const char *getPassName() const { return "X86 vzeroupper inserter";}
44 const TargetInstrInfo *TII; // Machine instruction info.
46 // Any YMM register live-in to this function?
49 // BBState - Contains the state of each MBB: unknown, clean, dirty
50 SmallVector<uint8_t, 8> BBState;
52 // BBSolved - Keep track of all MBB which had been already analyzed
53 // and there is no further processing required.
56 // Machine Basic Blocks are classified according this pass:
58 // ST_UNKNOWN - The MBB state is unknown, meaning from the entry state
59 // until the MBB exit there isn't a instruction using YMM to change
60 // the state to dirty, or one of the incoming predecessors is unknown
61 // and there's not a dirty predecessor between them.
63 // ST_CLEAN - No YMM usage in the end of the MBB. A MBB could have
64 // instructions using YMM and be marked ST_CLEAN, as long as the state
65 // is cleaned by a vzeroupper before any call.
67 // ST_DIRTY - Any MBB ending with a YMM usage not cleaned up by a
68 // vzeroupper instruction.
70 // ST_INIT - Placeholder for an empty state set
79 // computeState - Given two states, compute the resulting state, in
82 // 1) One dirty state yields another dirty state
83 // 2) All states must be clean for the result to be clean
84 // 3) If none above and one unknown, the result state is also unknown
86 static unsigned computeState(unsigned PrevState, unsigned CurState) {
87 if (PrevState == ST_INIT)
90 if (PrevState == ST_DIRTY || CurState == ST_DIRTY)
93 if (PrevState == ST_CLEAN && CurState == ST_CLEAN)
100 char VZeroUpperInserter::ID = 0;
103 FunctionPass *llvm::createX86IssueVZeroUpperPass() {
104 return new VZeroUpperInserter();
107 static bool isYmmReg(unsigned Reg) {
108 if (Reg >= X86::YMM0 && Reg <= X86::YMM15)
114 static bool checkFnHasLiveInYmm(MachineRegisterInfo &MRI) {
115 for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(),
116 E = MRI.livein_end(); I != E; ++I)
117 if (isYmmReg(I->first))
123 static bool hasYmmReg(MachineInstr *MI) {
124 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
125 const MachineOperand &MO = MI->getOperand(i);
130 if (isYmmReg(MO.getReg()))
136 /// runOnMachineFunction - Loop over all of the basic blocks, inserting
137 /// vzero upper instructions before function calls.
138 bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) {
139 TII = MF.getTarget().getInstrInfo();
140 MachineRegisterInfo &MRI = MF.getRegInfo();
141 bool EverMadeChange = false;
143 // Fast check: if the function doesn't use any ymm registers, we don't need
144 // to insert any VZEROUPPER instructions. This is constant-time, so it is
145 // cheap in the common case of no ymm use.
146 bool YMMUsed = false;
147 const TargetRegisterClass *RC = &X86::VR256RegClass;
148 for (TargetRegisterClass::iterator i = RC->begin(), e = RC->end();
150 if (MRI.isPhysRegUsed(*i)) {
156 return EverMadeChange;
158 // Pre-compute the existence of any live-in YMM registers to this function
159 FnHasLiveInYmm = checkFnHasLiveInYmm(MRI);
161 assert(BBState.empty());
162 BBState.resize(MF.getNumBlockIDs(), 0);
163 BBSolved.resize(MF.getNumBlockIDs(), 0);
165 // Each BB state depends on all predecessors, loop over until everything
166 // converges. (Once we converge, we can implicitly mark everything that is
167 // still ST_UNKNOWN as ST_CLEAN.)
169 bool MadeChange = false;
171 // Process all basic blocks.
172 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
173 MadeChange |= processBasicBlock(MF, *I);
175 // If this iteration over the code changed anything, keep iterating.
176 if (!MadeChange) break;
177 EverMadeChange = true;
182 return EverMadeChange;
185 /// processBasicBlock - Loop over all of the instructions in the basic block,
186 /// inserting vzero upper instructions before function calls.
187 bool VZeroUpperInserter::processBasicBlock(MachineFunction &MF,
188 MachineBasicBlock &BB) {
189 bool Changed = false;
190 unsigned BBNum = BB.getNumber();
192 // Don't process already solved BBs
194 return false; // No changes
196 // Check the state of all predecessors
197 unsigned EntryState = ST_INIT;
198 for (MachineBasicBlock::const_pred_iterator PI = BB.pred_begin(),
199 PE = BB.pred_end(); PI != PE; ++PI) {
200 EntryState = computeState(EntryState, BBState[(*PI)->getNumber()]);
201 if (EntryState == ST_DIRTY)
206 // The entry MBB for the function may set the initial state to dirty if
207 // the function receives any YMM incoming arguments
208 if (&BB == MF.begin()) {
209 EntryState = ST_CLEAN;
211 EntryState = ST_DIRTY;
214 // The current state is initialized according to the predecessors
215 unsigned CurState = EntryState;
216 bool BBHasCall = false;
218 for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) {
219 MachineInstr *MI = I;
220 DebugLoc dl = I->getDebugLoc();
221 bool isControlFlow = MI->isCall() || MI->isReturn();
223 // Shortcut: don't need to check regular instructions in dirty state.
224 if (!isControlFlow && CurState == ST_DIRTY)
228 // We found a ymm-using instruction; this could be an AVX instruction,
229 // or it could be control flow.
234 // Check for control-flow out of the current function (which might
235 // indirectly execute SSE instructions).
241 // The VZEROUPPER instruction resets the upper 128 bits of all Intel AVX
242 // registers. This instruction has zero latency. In addition, the processor
243 // changes back to Clean state, after which execution of Intel SSE
244 // instructions or Intel AVX instructions has no transition penalty. Add
245 // the VZEROUPPER instruction before any function call/return that might
247 // FIXME: In some cases, we may want to move the VZEROUPPER into a
248 // predecessor block.
249 if (CurState == ST_DIRTY) {
250 // Only insert the VZEROUPPER in case the entry state isn't unknown.
251 // When unknown, only compute the information within the block to have
252 // it available in the exit if possible, but don't change the block.
253 if (EntryState != ST_UNKNOWN) {
254 BuildMI(BB, I, dl, TII->get(X86::VZEROUPPER));
258 // After the inserted VZEROUPPER the state becomes clean again, but
259 // other YMM may appear before other subsequent calls or even before
260 // the end of the BB.
265 DEBUG(dbgs() << "MBB #" << BBNum
266 << ", current state: " << CurState << '\n');
268 // A BB can only be considered solved when we both have done all the
269 // necessary transformations, and have computed the exit state. This happens
271 // 1) We know the entry state: this immediately implies the exit state and
272 // all the necessary transformations.
273 // 2) There are no calls, and and a non-call instruction marks this block:
274 // no transformations are necessary, and we know the exit state.
275 if (EntryState != ST_UNKNOWN || (!BBHasCall && CurState != ST_UNKNOWN))
276 BBSolved[BBNum] = true;
278 if (CurState != BBState[BBNum])
281 BBState[BBNum] = CurState;