blob: ad152824c1827c14d8313fe58b0767e873c5e6f7 [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
Ahmed Bougacha068ac4a2016-05-07 01:11:10 +000063#define FIXUPBW_DESC "X86 Byte/Word Instruction Fixup"
64#define FIXUPBW_NAME "x86-fixup-bw-insts"
65
66#define DEBUG_TYPE FIXUPBW_NAME
Kevin B. Smith6a833502016-02-11 19:43:04 +000067
68// Option to allow this optimization pass to have fine-grained control.
69// This is turned off by default so as not to affect a large number of
70// existing lit tests.
71static cl::opt<bool>
72 FixupBWInsts("fixup-byte-word-insts",
73 cl::desc("Change byte and word instructions to larger sizes"),
Kevin B. Smithe0a6fc32016-04-08 18:58:29 +000074 cl::init(true), cl::Hidden);
Kevin B. Smith6a833502016-02-11 19:43:04 +000075
76namespace {
77class FixupBWInstPass : public MachineFunctionPass {
Ahmed Bougacha04200a72016-05-06 17:28:47 +000078 /// Loop over all of the instructions in the basic block replacing applicable
79 /// byte or word instructions with better alternatives.
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +000080 void processBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB);
Kevin B. Smith6a833502016-02-11 19:43:04 +000081
Ahmed Bougacha04200a72016-05-06 17:28:47 +000082 /// This sets the \p SuperDestReg to the 32 bit super reg of the original
83 /// destination register of the MachineInstr passed in. It returns true if
84 /// that super register is dead just prior to \p OrigMI, and false if not.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +000085 bool getSuperRegDestIfDead(MachineInstr *OrigMI,
Kevin B. Smith6a833502016-02-11 19:43:04 +000086 unsigned &SuperDestReg) const;
87
Ahmed Bougacha04200a72016-05-06 17:28:47 +000088 /// Change the MachineInstr \p MI into the equivalent extending load to 32 bit
89 /// register if it is safe to do so. Return the replacement instruction if
90 /// OK, otherwise return nullptr.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +000091 MachineInstr *tryReplaceLoad(unsigned New32BitOpcode, MachineInstr *MI) const;
Kevin B. Smith6a833502016-02-11 19:43:04 +000092
93public:
Ahmed Bougacha068ac4a2016-05-07 01:11:10 +000094 static char ID;
95
96 const char *getPassName() const override {
97 return FIXUPBW_DESC;
98 }
99
100 FixupBWInstPass() : MachineFunctionPass(ID) {
101 initializeFixupBWInstPassPass(*PassRegistry::getPassRegistry());
102 }
Kevin B. Smith6a833502016-02-11 19:43:04 +0000103
104 void getAnalysisUsage(AnalysisUsage &AU) const override {
105 AU.addRequired<MachineLoopInfo>(); // Machine loop info is used to
106 // guide some heuristics.
107 MachineFunctionPass::getAnalysisUsage(AU);
108 }
109
Ahmed Bougacha04200a72016-05-06 17:28:47 +0000110 /// Loop over all of the basic blocks, replacing byte and word instructions by
111 /// equivalent 32 bit instructions where performance or code size can be
112 /// improved.
Kevin B. Smith6a833502016-02-11 19:43:04 +0000113 bool runOnMachineFunction(MachineFunction &MF) override;
114
Derek Schuff1dbf7a52016-04-04 17:09:25 +0000115 MachineFunctionProperties getRequiredProperties() const override {
116 return MachineFunctionProperties().set(
117 MachineFunctionProperties::Property::AllVRegsAllocated);
118 }
119
Kevin B. Smith6a833502016-02-11 19:43:04 +0000120private:
121 MachineFunction *MF;
122
123 /// Machine instruction info used throughout the class.
124 const X86InstrInfo *TII;
125
126 /// Local member for function's OptForSize attribute.
127 bool OptForSize;
128
129 /// Machine loop info used for guiding some heruistics.
130 MachineLoopInfo *MLI;
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000131
132 /// Register Liveness information after the current instruction.
133 LivePhysRegs LiveRegs;
Kevin B. Smith6a833502016-02-11 19:43:04 +0000134};
135char FixupBWInstPass::ID = 0;
136}
137
Ahmed Bougacha068ac4a2016-05-07 01:11:10 +0000138INITIALIZE_PASS(FixupBWInstPass, FIXUPBW_NAME, FIXUPBW_DESC, false, false)
139
Kevin B. Smith6a833502016-02-11 19:43:04 +0000140FunctionPass *llvm::createX86FixupBWInsts() { return new FixupBWInstPass(); }
141
142bool FixupBWInstPass::runOnMachineFunction(MachineFunction &MF) {
Andrew Kaylor2bee5ef2016-04-26 21:44:24 +0000143 if (!FixupBWInsts || skipFunction(*MF.getFunction()))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000144 return false;
145
146 this->MF = &MF;
147 TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
148 OptForSize = MF.getFunction()->optForSize();
149 MLI = &getAnalysis<MachineLoopInfo>();
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000150 LiveRegs.init(&TII->getRegisterInfo());
Kevin B. Smith6a833502016-02-11 19:43:04 +0000151
152 DEBUG(dbgs() << "Start X86FixupBWInsts\n";);
153
154 // Process all basic blocks.
155 for (auto &MBB : MF)
156 processBasicBlock(MF, MBB);
157
158 DEBUG(dbgs() << "End X86FixupBWInsts\n";);
159
160 return true;
161}
162
163// TODO: This method of analysis can miss some legal cases, because the
164// super-register could be live into the address expression for a memory
165// reference for the instruction, and still be killed/last used by the
166// instruction. However, the existing query interfaces don't seem to
167// easily allow that to be checked.
168//
169// What we'd really like to know is whether after OrigMI, the
170// only portion of SuperDestReg that is alive is the portion that
171// was the destination register of OrigMI.
172bool FixupBWInstPass::getSuperRegDestIfDead(MachineInstr *OrigMI,
Kevin B. Smith6a833502016-02-11 19:43:04 +0000173 unsigned &SuperDestReg) const {
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000174 auto *TRI = &TII->getRegisterInfo();
Kevin B. Smith6a833502016-02-11 19:43:04 +0000175
176 unsigned OrigDestReg = OrigMI->getOperand(0).getReg();
177 SuperDestReg = getX86SubSuperRegister(OrigDestReg, 32);
178
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000179 const auto SubRegIdx = TRI->getSubRegIndex(SuperDestReg, OrigDestReg);
180
Kevin B. Smith6a833502016-02-11 19:43:04 +0000181 // Make sure that the sub-register that this instruction has as its
182 // destination is the lowest order sub-register of the super-register.
183 // If it isn't, then the register isn't really dead even if the
184 // super-register is considered dead.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000185 if (SubRegIdx == X86::sub_8bit_hi)
Kevin B. Smith6a833502016-02-11 19:43:04 +0000186 return false;
187
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000188 if (LiveRegs.contains(SuperDestReg))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000189 return false;
190
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000191 if (SubRegIdx == X86::sub_8bit) {
Kevin B. Smith6a833502016-02-11 19:43:04 +0000192 // In the case of byte registers, we also have to check that the upper
193 // byte register is also dead. That is considered to be independent of
194 // whether the super-register is dead.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000195 unsigned UpperByteReg =
196 getX86SubSuperRegister(SuperDestReg, 8, /*High=*/true);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000197
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000198 if (LiveRegs.contains(UpperByteReg))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000199 return false;
200 }
201
202 return true;
203}
204
205MachineInstr *FixupBWInstPass::tryReplaceLoad(unsigned New32BitOpcode,
Kevin B. Smith6a833502016-02-11 19:43:04 +0000206 MachineInstr *MI) const {
207 unsigned NewDestReg;
208
209 // We are going to try to rewrite this load to a larger zero-extending
210 // load. This is safe if all portions of the 32 bit super-register
211 // of the original destination register, except for the original destination
212 // register are dead. getSuperRegDestIfDead checks that.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000213 if (!getSuperRegDestIfDead(MI, NewDestReg))
Kevin B. Smith6a833502016-02-11 19:43:04 +0000214 return nullptr;
215
216 // Safe to change the instruction.
217 MachineInstrBuilder MIB =
218 BuildMI(*MF, MI->getDebugLoc(), TII->get(New32BitOpcode), NewDestReg);
219
220 unsigned NumArgs = MI->getNumOperands();
221 for (unsigned i = 1; i < NumArgs; ++i)
222 MIB.addOperand(MI->getOperand(i));
223
224 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
225
226 return MIB;
227}
228
229void FixupBWInstPass::processBasicBlock(MachineFunction &MF,
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000230 MachineBasicBlock &MBB) {
Kevin B. Smith6a833502016-02-11 19:43:04 +0000231
232 // This algorithm doesn't delete the instructions it is replacing
233 // right away. By leaving the existing instructions in place, the
234 // register liveness information doesn't change, and this makes the
235 // analysis that goes on be better than if the replaced instructions
236 // were immediately removed.
237 //
238 // This algorithm always creates a replacement instruction
239 // and notes that and the original in a data structure, until the
240 // whole BB has been analyzed. This keeps the replacement instructions
241 // from making it seem as if the larger register might be live.
242 SmallVector<std::pair<MachineInstr *, MachineInstr *>, 8> MIReplacements;
243
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000244 // Start computing liveness for this block. We iterate from the end to be able
245 // to update this for each instruction.
246 LiveRegs.clear();
Ahmed Bougacha9a0c9ad2016-04-27 01:51:38 +0000247 // We run after PEI, so we need to AddPristinesAndCSRs.
Matthias Braund1aabb22016-05-03 00:24:32 +0000248 LiveRegs.addLiveOuts(MBB);
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000249
250 for (auto I = MBB.rbegin(); I != MBB.rend(); ++I) {
Kevin B. Smith6a833502016-02-11 19:43:04 +0000251 MachineInstr *NewMI = nullptr;
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000252 MachineInstr *MI = &*I;
Kevin B. Smith6a833502016-02-11 19:43:04 +0000253
254 // See if this is an instruction of the type we are currently looking for.
255 switch (MI->getOpcode()) {
256
257 case X86::MOV8rm:
258 // Only replace 8 bit loads with the zero extending versions if
259 // in an inner most loop and not optimizing for size. This takes
260 // an extra byte to encode, and provides limited performance upside.
261 if (MachineLoop *ML = MLI->getLoopFor(&MBB)) {
262 if (ML->begin() == ML->end() && !OptForSize)
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000263 NewMI = tryReplaceLoad(X86::MOVZX32rm8, MI);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000264 }
265 break;
266
267 case X86::MOV16rm:
268 // Always try to replace 16 bit load with 32 bit zero extending.
269 // Code size is the same, and there is sometimes a perf advantage
270 // from eliminating a false dependence on the upper portion of
271 // the register.
Ahmed Bougachacfd9e552016-05-06 17:28:42 +0000272 NewMI = tryReplaceLoad(X86::MOVZX32rm16, MI);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000273 break;
274
275 default:
276 // nothing to do here.
277 break;
278 }
279
280 if (NewMI)
281 MIReplacements.push_back(std::make_pair(MI, NewMI));
Ahmed Bougacha5cf735a2016-04-26 00:00:48 +0000282
283 // We're done with this instruction, update liveness for the next one.
284 LiveRegs.stepBackward(*MI);
Kevin B. Smith6a833502016-02-11 19:43:04 +0000285 }
286
287 while (!MIReplacements.empty()) {
288 MachineInstr *MI = MIReplacements.back().first;
289 MachineInstr *NewMI = MIReplacements.back().second;
290 MIReplacements.pop_back();
291 MBB.insert(MI, NewMI);
292 MBB.erase(MI);
293 }
294}