blob: 9320e1e2226fbb5c69f0da6385eb8be7ad12b527 [file] [log] [blame]
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +00001//===-- 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
Andrea Di Biagio4f8bdcb2015-02-07 13:56:20 +000012// penalty when transferring control between AVX encoded instructions and old
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000013// SSE encoding mode.
14//
15//===----------------------------------------------------------------------===//
16
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000017#include "X86.h"
18#include "X86InstrInfo.h"
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +000019#include "X86Subtarget.h"
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000020#include "llvm/ADT/Statistic.h"
21#include "llvm/CodeGen/MachineFunctionPass.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
Eli Friedman8f249602011-11-04 23:46:11 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000024#include "llvm/CodeGen/Passes.h"
Eli Friedman8f249602011-11-04 23:46:11 +000025#include "llvm/Support/Debug.h"
26#include "llvm/Support/raw_ostream.h"
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000027#include "llvm/Target/TargetInstrInfo.h"
28using namespace llvm;
29
Chandler Carruth84e68b22014-04-22 02:41:26 +000030#define DEBUG_TYPE "x86-vzeroupper"
31
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000032STATISTIC(NumVZU, "Number of vzeroupper instructions inserted");
33
34namespace {
Lang Hames7c8189c2014-03-17 01:22:54 +000035
36 class VZeroUpperInserter : public MachineFunctionPass {
37 public:
38
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000039 VZeroUpperInserter() : MachineFunctionPass(ID) {}
Craig Topper2d9361e2014-03-09 07:44:38 +000040 bool runOnMachineFunction(MachineFunction &MF) override;
Derek Schuff1dbf7a52016-04-04 17:09:25 +000041 MachineFunctionProperties getRequiredProperties() const override {
42 return MachineFunctionProperties().set(
43 MachineFunctionProperties::Property::AllVRegsAllocated);
44 }
Craig Topper2d9361e2014-03-09 07:44:38 +000045 const char *getPassName() const override {return "X86 vzeroupper inserter";}
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000046
47 private:
Eli Friedman8f249602011-11-04 23:46:11 +000048
Lang Hames7c8189c2014-03-17 01:22:54 +000049 void processBasicBlock(MachineBasicBlock &MBB);
50 void insertVZeroUpper(MachineBasicBlock::iterator I,
51 MachineBasicBlock &MBB);
52 void addDirtySuccessor(MachineBasicBlock &MBB);
Eli Friedman8f249602011-11-04 23:46:11 +000053
Lang Hames7c8189c2014-03-17 01:22:54 +000054 typedef enum { PASS_THROUGH, EXITS_CLEAN, EXITS_DIRTY } BlockExitState;
55 static const char* getBlockExitStateName(BlockExitState ST);
Eli Friedman8f249602011-11-04 23:46:11 +000056
Lang Hames7c8189c2014-03-17 01:22:54 +000057 // 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.
Eli Friedman8f249602011-11-04 23:46:11 +000065 //
Lang Hames7c8189c2014-03-17 01:22:54 +000066 // 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.
Eli Friedman8f249602011-11-04 23:46:11 +000069 //
Lang Hames7c8189c2014-03-17 01:22:54 +000070 // 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;
Eli Friedman8f249602011-11-04 23:46:11 +000080 };
Lang Hames7c8189c2014-03-17 01:22:54 +000081 typedef SmallVector<BlockState, 8> BlockStateMap;
82 typedef SmallVector<MachineBasicBlock*, 8> DirtySuccessorsWorkList;
Eli Friedman8f249602011-11-04 23:46:11 +000083
Lang Hames7c8189c2014-03-17 01:22:54 +000084 BlockStateMap BlockStates;
85 DirtySuccessorsWorkList DirtySuccessors;
86 bool EverMadeChange;
Amjad Aboud719325fe12016-03-01 11:32:03 +000087 bool IsX86INTR;
Lang Hames7c8189c2014-03-17 01:22:54 +000088 const TargetInstrInfo *TII;
Eli Friedman8f249602011-11-04 23:46:11 +000089
Lang Hames7c8189c2014-03-17 01:22:54 +000090 static char ID;
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000091 };
Lang Hames7c8189c2014-03-17 01:22:54 +000092
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000093 char VZeroUpperInserter::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +000094}
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +000095
96FunctionPass *llvm::createX86IssueVZeroUpperPass() {
97 return new VZeroUpperInserter();
98}
99
Lang Hames7c8189c2014-03-17 01:22:54 +0000100const 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
Eli Friedman8f249602011-11-04 23:46:11 +0000109static bool isYmmReg(unsigned Reg) {
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +0000110 return (Reg >= X86::YMM0 && Reg <= X86::YMM15);
Eli Friedman8f249602011-11-04 23:46:11 +0000111}
112
113static bool checkFnHasLiveInYmm(MachineRegisterInfo &MRI) {
114 for (MachineRegisterInfo::livein_iterator I = MRI.livein_begin(),
115 E = MRI.livein_end(); I != E; ++I)
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +0000116 if (isYmmReg(I->first))
Eli Friedman8f249602011-11-04 23:46:11 +0000117 return true;
118
119 return false;
120}
121
Elena Demikhovsky9e0df7c2013-02-13 08:02:04 +0000122static bool clobbersAllYmmRegs(const MachineOperand &MO) {
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +0000123 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
Elena Demikhovsky9e0df7c2013-02-13 08:02:04 +0000124 if (!MO.clobbersPhysReg(reg))
125 return false;
126 }
127 return true;
128}
129
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000130static bool hasYmmReg(MachineInstr &MI) {
131 for (const MachineOperand &MO : MI.operands()) {
132 if (MI.isCall() && MO.isRegMask() && !clobbersAllYmmRegs(MO))
Elena Demikhovsky9e0df7c2013-02-13 08:02:04 +0000133 return true;
Eli Friedman8f249602011-11-04 23:46:11 +0000134 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
Sanjay Patel8bc63b22016-05-20 16:46:01 +0000144/// Check if any YMM register will be clobbered by this instruction.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000145static bool callClobbersAnyYmmReg(MachineInstr &MI) {
146 assert(MI.isCall() && "Can only be called on call instructions.");
147 for (const MachineOperand &MO : MI.operands()) {
Michael Liao14b02842013-12-03 09:17:32 +0000148 if (!MO.isRegMask())
149 continue;
Elena Demikhovsky52e4a0e2014-01-05 10:46:09 +0000150 for (unsigned reg = X86::YMM0; reg <= X86::YMM15; ++reg) {
Michael Liao14b02842013-12-03 09:17:32 +0000151 if (MO.clobbersPhysReg(reg))
152 return true;
153 }
154 }
155 return false;
156}
157
Sanjay Patel8bc63b22016-05-20 16:46:01 +0000158/// Insert a vzeroupper instruction before I.
Lang Hames7c8189c2014-03-17 01:22:54 +0000159void VZeroUpperInserter::insertVZeroUpper(MachineBasicBlock::iterator I,
Sanjay Patel8bc63b22016-05-20 16:46:01 +0000160 MachineBasicBlock &MBB) {
Lang Hames7c8189c2014-03-17 01:22:54 +0000161 DebugLoc dl = I->getDebugLoc();
162 BuildMI(MBB, I, dl, TII->get(X86::VZEROUPPER));
163 ++NumVZU;
164 EverMadeChange = true;
165}
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000166
Sanjay Patel8bc63b22016-05-20 16:46:01 +0000167/// Add MBB to the DirtySuccessors list if it hasn't already been added.
Lang Hames7c8189c2014-03-17 01:22:54 +0000168void VZeroUpperInserter::addDirtySuccessor(MachineBasicBlock &MBB) {
169 if (!BlockStates[MBB.getNumber()].AddedToDirtySuccessors) {
170 DirtySuccessors.push_back(&MBB);
171 BlockStates[MBB.getNumber()].AddedToDirtySuccessors = true;
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000172 }
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000173}
174
Sanjay Patel8bc63b22016-05-20 16:46:01 +0000175/// Loop over all of the instructions in the basic block, inserting vzeroupper
176/// instructions before function calls.
Lang Hames7c8189c2014-03-17 01:22:54 +0000177void VZeroUpperInserter::processBasicBlock(MachineBasicBlock &MBB) {
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000178
Sanjay Patel5496a232016-05-20 17:07:19 +0000179 // Start by assuming that the block is PASS_THROUGH which implies no unguarded
Lang Hames7c8189c2014-03-17 01:22:54 +0000180 // calls.
181 BlockExitState CurState = PASS_THROUGH;
182 BlockStates[MBB.getNumber()].FirstUnguardedCall = MBB.end();
Eli Friedman8f249602011-11-04 23:46:11 +0000183
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000184 for (MachineInstr &MI : MBB) {
Amjad Aboud719325fe12016-03-01 11:32:03 +0000185 // No need for vzeroupper before iret in interrupt handler function,
186 // epilogue will restore YMM registers if needed.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000187 bool IsReturnFromX86INTR = IsX86INTR && MI.isReturn();
188 bool IsControlFlow = MI.isCall() || MI.isReturn();
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000189
Sanjay Patel39553602016-05-25 16:39:47 +0000190 // An existing VZERO* instruction resets the state.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000191 if (MI.getOpcode() == X86::VZEROALL || MI.getOpcode() == X86::VZEROUPPER) {
Sanjay Patel39553602016-05-25 16:39:47 +0000192 CurState = EXITS_CLEAN;
193 continue;
194 }
195
Chad Rosier24c19d22012-08-01 18:39:17 +0000196 // Shortcut: don't need to check regular instructions in dirty state.
Amjad Aboud719325fe12016-03-01 11:32:03 +0000197 if ((!IsControlFlow || IsReturnFromX86INTR) && CurState == EXITS_DIRTY)
Eli Friedman8f249602011-11-04 23:46:11 +0000198 continue;
199
200 if (hasYmmReg(MI)) {
201 // We found a ymm-using instruction; this could be an AVX instruction,
202 // or it could be control flow.
Lang Hames7c8189c2014-03-17 01:22:54 +0000203 CurState = EXITS_DIRTY;
Eli Friedman8f249602011-11-04 23:46:11 +0000204 continue;
205 }
206
207 // Check for control-flow out of the current function (which might
208 // indirectly execute SSE instructions).
Amjad Aboud719325fe12016-03-01 11:32:03 +0000209 if (!IsControlFlow || IsReturnFromX86INTR)
Eli Friedman8f249602011-11-04 23:46:11 +0000210 continue;
211
Michael Liao14b02842013-12-03 09:17:32 +0000212 // If the call won't clobber any YMM register, skip it as well. It usually
213 // happens on helper function calls (such as '_chkstk', '_ftol2') where
214 // standard calling convention is not used (RegMask is not used to mark
Andrea Di Biagio4f8bdcb2015-02-07 13:56:20 +0000215 // register clobbered and register usage (def/imp-def/use) is well-defined
Michael Liao14b02842013-12-03 09:17:32 +0000216 // and explicitly specified.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000217 if (MI.isCall() && !callClobbersAnyYmmReg(MI))
Michael Liao14b02842013-12-03 09:17:32 +0000218 continue;
219
Sanjay Patel5496a232016-05-20 17:07:19 +0000220 // The VZEROUPPER instruction resets the upper 128 bits of all AVX
221 // registers. In addition, the processor changes back to Clean state, after
222 // which execution of SSE instructions or AVX instructions has no transition
223 // penalty. Add the VZEROUPPER instruction before any function call/return
224 // that might execute SSE code.
Eli Friedman8f249602011-11-04 23:46:11 +0000225 // FIXME: In some cases, we may want to move the VZEROUPPER into a
226 // predecessor block.
Lang Hames7c8189c2014-03-17 01:22:54 +0000227 if (CurState == EXITS_DIRTY) {
Eli Friedman8f249602011-11-04 23:46:11 +0000228 // After the inserted VZEROUPPER the state becomes clean again, but
229 // other YMM may appear before other subsequent calls or even before
230 // the end of the BB.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000231 insertVZeroUpper(MI, MBB);
Lang Hames7c8189c2014-03-17 01:22:54 +0000232 CurState = EXITS_CLEAN;
233 } else if (CurState == PASS_THROUGH) {
234 // If this block is currently in pass-through state and we encounter a
235 // call then whether we need a vzeroupper or not depends on whether this
236 // block has successors that exit dirty. Record the location of the call,
237 // and set the state to EXITS_CLEAN, but do not insert the vzeroupper yet.
238 // It will be inserted later if necessary.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000239 BlockStates[MBB.getNumber()].FirstUnguardedCall = MI;
Lang Hames7c8189c2014-03-17 01:22:54 +0000240 CurState = EXITS_CLEAN;
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000241 }
242 }
243
Lang Hames7c8189c2014-03-17 01:22:54 +0000244 DEBUG(dbgs() << "MBB #" << MBB.getNumber() << " exit state: "
245 << getBlockExitStateName(CurState) << '\n');
Eli Friedman8f249602011-11-04 23:46:11 +0000246
Lang Hames7c8189c2014-03-17 01:22:54 +0000247 if (CurState == EXITS_DIRTY)
248 for (MachineBasicBlock::succ_iterator SI = MBB.succ_begin(),
249 SE = MBB.succ_end();
250 SI != SE; ++SI)
251 addDirtySuccessor(**SI);
Eli Friedman8f249602011-11-04 23:46:11 +0000252
Lang Hames7c8189c2014-03-17 01:22:54 +0000253 BlockStates[MBB.getNumber()].ExitState = CurState;
254}
Eli Friedman8f249602011-11-04 23:46:11 +0000255
Sanjay Patel8bc63b22016-05-20 16:46:01 +0000256/// Loop over all of the basic blocks, inserting vzeroupper instructions before
257/// function calls.
Lang Hames7c8189c2014-03-17 01:22:54 +0000258bool VZeroUpperInserter::runOnMachineFunction(MachineFunction &MF) {
Eric Christopher05b81972015-02-02 17:38:43 +0000259 const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
Yunzhong Gao0de36ec2016-02-12 23:37:57 +0000260 if (!ST.hasAVX() || ST.hasAVX512() || ST.hasFastPartialYMMWrite())
Lang Hames7c8189c2014-03-17 01:22:54 +0000261 return false;
Eric Christopher05b81972015-02-02 17:38:43 +0000262 TII = ST.getInstrInfo();
Lang Hames7c8189c2014-03-17 01:22:54 +0000263 MachineRegisterInfo &MRI = MF.getRegInfo();
264 EverMadeChange = false;
Amjad Aboud719325fe12016-03-01 11:32:03 +0000265 IsX86INTR = MF.getFunction()->getCallingConv() == CallingConv::X86_INTR;
Lang Hames7c8189c2014-03-17 01:22:54 +0000266
Matthias Braunada0adf2015-01-08 00:33:48 +0000267 bool FnHasLiveInYmm = checkFnHasLiveInYmm(MRI);
268
Lang Hames7c8189c2014-03-17 01:22:54 +0000269 // Fast check: if the function doesn't use any ymm registers, we don't need
270 // to insert any VZEROUPPER instructions. This is constant-time, so it is
271 // cheap in the common case of no ymm use.
Matthias Braunada0adf2015-01-08 00:33:48 +0000272 bool YMMUsed = FnHasLiveInYmm;
273 if (!YMMUsed) {
274 const TargetRegisterClass *RC = &X86::VR256RegClass;
275 for (TargetRegisterClass::iterator i = RC->begin(), e = RC->end(); i != e;
276 i++) {
277 if (!MRI.reg_nodbg_empty(*i)) {
278 YMMUsed = true;
279 break;
280 }
Lang Hames7c8189c2014-03-17 01:22:54 +0000281 }
282 }
283 if (!YMMUsed) {
284 return false;
285 }
286
287 assert(BlockStates.empty() && DirtySuccessors.empty() &&
288 "X86VZeroUpper state should be clear");
289 BlockStates.resize(MF.getNumBlockIDs());
290
291 // Process all blocks. This will compute block exit states, record the first
292 // unguarded call in each block, and add successors of dirty blocks to the
293 // DirtySuccessors list.
Sanjay Patelfbca70d2015-05-05 21:20:52 +0000294 for (MachineBasicBlock &MBB : MF)
295 processBasicBlock(MBB);
Lang Hames7c8189c2014-03-17 01:22:54 +0000296
Sanjay Patel5496a232016-05-20 17:07:19 +0000297 // If any YMM regs are live-in to this function, add the entry block to the
Lang Hames7c8189c2014-03-17 01:22:54 +0000298 // DirtySuccessors list
Matthias Braunada0adf2015-01-08 00:33:48 +0000299 if (FnHasLiveInYmm)
Lang Hames7c8189c2014-03-17 01:22:54 +0000300 addDirtySuccessor(MF.front());
301
Sanjay Patel8099fb7e2016-05-23 18:01:20 +0000302 // Re-visit all blocks that are successors of EXITS_DIRTY blocks. Add
Lang Hames7c8189c2014-03-17 01:22:54 +0000303 // vzeroupper instructions to unguarded calls, and propagate EXITS_DIRTY
304 // through PASS_THROUGH blocks.
305 while (!DirtySuccessors.empty()) {
306 MachineBasicBlock &MBB = *DirtySuccessors.back();
307 DirtySuccessors.pop_back();
308 BlockState &BBState = BlockStates[MBB.getNumber()];
309
310 // MBB is a successor of a dirty block, so its first call needs to be
311 // guarded.
312 if (BBState.FirstUnguardedCall != MBB.end())
313 insertVZeroUpper(BBState.FirstUnguardedCall, MBB);
314
Sanjay Patel5496a232016-05-20 17:07:19 +0000315 // If this successor was a pass-through block, then it is now dirty. Its
Lang Hames7c8189c2014-03-17 01:22:54 +0000316 // successors need to be added to the worklist (if they haven't been
317 // already).
318 if (BBState.ExitState == PASS_THROUGH) {
319 DEBUG(dbgs() << "MBB #" << MBB.getNumber()
320 << " was Pass-through, is now Dirty-out.\n");
Sanjay Patel13a0d492016-05-23 18:00:50 +0000321 for (MachineBasicBlock *Succ : MBB.successors())
322 addDirtySuccessor(*Succ);
Lang Hames7c8189c2014-03-17 01:22:54 +0000323 }
324 }
325
326 BlockStates.clear();
327 return EverMadeChange;
Bruno Cardoso Lopes2a3ffb52011-08-23 01:14:17 +0000328}