blob: 045a4ed8dcae2c2bed4883c2fda94dcb2fe1ec75 [file] [log] [blame]
Kevin B. Smith6a833502016-02-11 19:43:04 +00001//===-- X86FixupBWInsts.cpp - Fixup Byte or Word instructions -----------===//
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/// \file
10/// This file defines the pass that looks through the machine instructions
11/// late in the compilation, and finds byte or word instructions that
12/// can be profitably replaced with 32 bit instructions that give equivalent
13/// results for the bits of the results that are used. There are two possible
14/// reasons to do this.
15///
16/// One reason is to avoid false-dependences on the upper portions
17/// of the registers. Only instructions that have a destination register
18/// which is not in any of the source registers can be affected by this.
19/// Any instruction where one of the source registers is also the destination
20/// register is unaffected, because it has a true dependence on the source
21/// register already. So, this consideration primarily affects load
22/// instructions and register-to-register moves. It would
23/// seem like cmov(s) would also be affected, but because of the way cmov is
24/// really implemented by most machines as reading both the destination and
25/// and source regsters, and then "merging" the two based on a condition,
26/// it really already should be considered as having a true dependence on the
27/// destination register as well.
28///
29/// The other reason to do this is for potential code size savings. Word
30/// operations need an extra override byte compared to their 32 bit
31/// versions. So this can convert many word operations to their larger
32/// size, saving a byte in encoding. This could introduce partial register
33/// dependences where none existed however. As an example take:
34/// orw ax, $0x1000
35/// addw ax, $3
36/// now if this were to get transformed into
37/// orw ax, $1000
38/// addl eax, $3
39/// because the addl encodes shorter than the addw, this would introduce
40/// a use of a register that was only partially written earlier. On older
41/// Intel processors this can be quite a performance penalty, so this should
42/// probably only be done when it can be proven that a new partial dependence
43/// wouldn't be created, or when your know a newer processor is being
44/// targeted, or when optimizing for minimum code size.
45///
46//===----------------------------------------------------------------------===//
47
48#include "X86.h"
49#include "X86InstrInfo.h"
50#include "X86Subtarget.h"
51#include "llvm/ADT/Statistic.h"
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +000052#include "llvm/CodeGen/LivePhysRegs.h"
Kevin B. Smith6a833502016-02-11 19:43:04 +000053#include "llvm/CodeGen/MachineFunctionPass.h"
54#include "llvm/CodeGen/MachineInstrBuilder.h"
55#include "llvm/CodeGen/MachineLoopInfo.h"
56#include "llvm/CodeGen/MachineRegisterInfo.h"
57#include "llvm/CodeGen/Passes.h"
58#include "llvm/Support/Debug.h"
59#include "llvm/Support/raw_ostream.h"
60#include "llvm/Target/TargetInstrInfo.h"
61using namespace llvm;
62
63#define DEBUG_TYPE "x86-fixup-bw-insts"
64
65// Option to allow this optimization pass to have fine-grained control.
66// This is turned off by default so as not to affect a large number of
67// existing lit tests.
68static cl::opt<bool>
69 FixupBWInsts("fixup-byte-word-insts",
70 cl::desc("Change byte and word instructions to larger sizes"),
Kevin B. Smithe0a6fc32016-04-08 18:58:29 +000071 cl::init(true), cl::Hidden);
Kevin B. Smith6a833502016-02-11 19:43:04 +000072
73namespace {
74class FixupBWInstPass : public MachineFunctionPass {
75 static char ID;
76
77 const char *getPassName() const override {
78 return "X86 Byte/Word Instruction Fixup";
79 }
80
Ahmed Bougacha04200a72016-05-06 17:28:47 +000081 /// Loop over all of the instructions in the basic block replacing applicable
82 /// byte or word instructions with better alternatives.
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +000083 void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
Kevin B. Smith6a833502016-02-11 19:43:04 +000084
Ahmed Bougacha04200a72016-05-06 17:28:47 +000085 /// This sets the \p SuperDestReg to the 32 bit super reg of the original
86 /// destination register of the MachineInstr passed in. It returns true if
87 /// that super register is dead just prior to \p OrigMI, and false if not.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +000088 bool getSuperRegDestIfDead(MachineInstr *OrigMI,
Kevin B. Smith6a833502016-02-11 19:43:04 +000089 unsigned &SuperDestReg) const;
90
Ahmed Bougacha04200a72016-05-06 17:28:47 +000091 /// Change the MachineInstr \p MI into the equivalent extending load to 32 bit
92 /// register if it is safe to do so. Return the replacement instruction if
93 /// OK, otherwise return nullptr.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +000094 MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const;
Kevin B. Smith6a833502016-02-11 19:43:04 +000095
96public:
97 FixupBWInstPass() : MachineFunctionPass(ID) {}
98
99 void getAnalysisUsage(AnalysisUsage &AU) const override {
100 AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to
101 // guide some heuristics.
102 MachineFunctionPass::getAnalysisUsage(AU);
103 }
104
Ahmed Bougacha04200a72016-05-06 17:28:47 +0000105 /// Loop over all of the basic blocks, replacing byte and word instructions by
106 /// equivalent 32 bit instructions where performance or code size can be
107 /// improved.
Kevin B. Smith6a833502016-02-11 19:43:04 +0000108 bool runOnMachineFunction(MachineFunction &MF) override;
109
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000110 MachineFunctionProperties getRequiredProperties() const override {
111 return MachineFunctionProperties().set(
112 MachineFunctionProperties::Property::AllVRegsAllocated);
113 }
114
Kevin B. Smith6a833502016-02-11 19:43:04 +0000115private:
116 MachineFunction *MF;
117
118 /// Machine instruction info used throughout the class.
119 const X86InstrInfo *TII;
120
121 /// Local member for function's OptForSize attribute.
122 bool OptForSize;
123
124 /// Machine loop info used for guiding some heruistics.
125 MachineLoopInfo *MLI;
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000126
127 /// Register Liveness information after the current instruction.
128 LivePhysRegs LiveRegs;
Kevin B. Smith6a833502016-02-11 19:43:04 +0000129};
130char FixupBWInstPass::ID = 0;
131}
132
133FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
134
135bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor2bee5ef2016-04-26 21:44:24 +0000136 if (!FixupBWInsts || skipFunction(*MF.getFunction()))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000137 return false;
138
139 this->MF = &MF;
140 TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
141 OptForSize = MF.getFunction()->optForSize();
142 MLI = &getAnalysis<MachineLoopInfo>();
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000143 LiveRegs.init(&TII->getRegisterInfo());
Kevin B. Smith6a833502016-02-11 19:43:04 +0000144
145 DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
146
147 // Process all basic blocks.
148 for (auto &MBB : MF)
149 processBasicBlock(MF, MBB);
150
151 DEBUG(dbgs() << "End X86FixupBWInsts\n";);
152
153 return true;
154}
155
156// TODO: This method of analysis can miss some legal cases, because the
157// super-register could be live into the address expression for a memory
158// reference for the instruction, and still be killed/last used by the
159// instruction. However, the existing query interfaces don't seem to
160// easily allow that to be checked.
161//
162// What we'd really like to know is whether after OrigMI, the
163// only portion of SuperDestReg that is alive is the portion that
164// was the destination register of OrigMI.
165bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
Kevin B. Smith6a833502016-02-11 19:43:04 +0000166 unsigned &SuperDestReg) const {
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000167 auto *TRI = &TII->getRegisterInfo();
Kevin B. Smith6a833502016-02-11 19:43:04 +0000168
169 unsigned OrigDestReg = OrigMI->getOperand(0).getReg();
170 SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
171
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000172 const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);
173
Kevin B. Smith6a833502016-02-11 19:43:04 +0000174 // Make sure that the sub-register that this instruction has as its
175 // destination is the lowest order sub-register of the super-register.
176 // If it isn't, then the register isn't really dead even if the
177 // super-register is considered dead.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000178 if (SubRegIdx == X86::sub_8bit_hi)
Kevin B. Smith6a833502016-02-11 19:43:04 +0000179 return false;
180
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000181 if (LiveRegs.contains(SuperDestReg))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000182 return false;
183
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000184 if (SubRegIdx == X86::sub_8bit) {
Kevin B. Smith6a833502016-02-11 19:43:04 +0000185 // In the case of byte registers, we also have to check that the upper
186 // byte register is also dead. That is considered to be independent of
187 // whether the super-register is dead.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000188 unsigned UpperByteReg =
189 getX86SubSuperRegister(SuperDestReg, 8, /*High=*/true);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000190
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000191 if (LiveRegs.contains(UpperByteReg))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000192 return false;
193 }
194
195 return true;
196}
197
198MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
Kevin B. Smith6a833502016-02-11 19:43:04 +0000199 MachineInstr *MI) const {
200 unsigned NewDestReg;
201
202 // We are going to try to rewrite this load to a larger zero-extending
203 // load. This is safe if all portions of the 32 bit super-register
204 // of the original destination register, except for the original destination
205 // register are dead. getSuperRegDestIfDead checks that.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000206 if (!getSuperRegDestIfDead(MI, NewDestReg))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000207 return nullptr;
208
209 // Safe to change the instruction.
210 MachineInstrBuilder MIB =
211 BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
212
213 unsigned NumArgs = MI->getNumOperands();
214 for (unsigned i = 1; i < NumArgs; ++i)
215 MIB.addOperand(MI->getOperand(i));
216
217 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
218
219 return MIB;
220}
221
222void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000223 MachineBasicBlock &MBB) {
Kevin B. Smith6a833502016-02-11 19:43:04 +0000224
225 // This algorithm doesn't delete the instructions it is replacing
226 // right away. By leaving the existing instructions in place, the
227 // register liveness information doesn't change, and this makes the
228 // analysis that goes on be better than if the replaced instructions
229 // were immediately removed.
230 //
231 // This algorithm always creates a replacement instruction
232 // and notes that and the original in a data structure, until the
233 // whole BB has been analyzed. This keeps the replacement instructions
234 // from making it seem as if the larger register might be live.
235 SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
236
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000237 // Start computing liveness for this block. We iterate from the end to be able
238 // to update this for each instruction.
239 LiveRegs.clear();
Ahmed Bougacha9a0c9ad2016-04-27 01:51:38 +0000240 // We run after PEI, so we need to AddPristinesAndCSRs.
Matthias Braund1aabb22016-05-03 00:24:32 +0000241 LiveRegs.addLiveOuts(MBB);
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000242
243 for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) {
Kevin B. Smith6a833502016-02-11 19:43:04 +0000244 MachineInstr *NewMI = nullptr;
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000245 MachineInstr *MI = &*I;
Kevin B. Smith6a833502016-02-11 19:43:04 +0000246
247 // See if this is an instruction of the type we are currently looking for.
248 switch (MI->getOpcode()) {
249
250 case X86::MOV8rm:
251 // Only replace 8 bit loads with the zero extending versions if
252 // in an inner most loop and not optimizing for size. This takes
253 // an extra byte to encode, and provides limited performance upside.
254 if (MachineLoop *ML = MLI->getLoopFor(&MBB)) {
255 if (ML->begin() == ML->end() && !OptForSize)
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000256 NewMI = tryReplaceLoad(X86::MOVZX32rm8, MI);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000257 }
258 break;
259
260 case X86::MOV16rm:
261 // Always try to replace 16 bit load with 32 bit zero extending.
262 // Code size is the same, and there is sometimes a perf advantage
263 // from eliminating a false dependence on the upper portion of
264 // the register.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000265 NewMI = tryReplaceLoad(X86::MOVZX32rm16, MI);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000266 break;
267
268 default:
269 // nothing to do here.
270 break;
271 }
272
273 if (NewMI)
274 MIReplacements.push_back(std::make_pair(MI, NewMI));
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000275
276 // We're done with this instruction, update liveness for the next one.
277 LiveRegs.stepBackward(*MI);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000278 }
279
280 while (!MIReplacements.empty()) {
281 MachineInstr *MI = MIReplacements.back().first;
282 MachineInstr *NewMI = MIReplacements.back().second;
283 MIReplacements.pop_back();
284 MBB.insert(MI, NewMI);
285 MBB.erase(MI);
286 }
287}