blob: 1306aa6c83154bef1496e2511f2218f52fca0c7b [file] [log] [blame]
Bill Wendling0f940c92007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling0f940c92007-12-07 21:42:31 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
Dan Gohmanc475c362009-01-15 22:01:38 +000013// This pass does not attempt to throttle itself to limit register pressure.
14// The register allocation phases are expected to perform rematerialization
15// to recover when register pressure is high.
16//
17// This pass is not intended to be a replacement or a complete alternative
18// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19// constructs that are not exposed before lowering and instruction selection.
20//
Bill Wendling0f940c92007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "machine-licm"
Chris Lattnerac695822008-01-04 06:41:45 +000024#include "llvm/CodeGen/Passes.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000025#include "llvm/CodeGen/MachineDominators.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000027#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000031#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000032#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000033#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000034#include "llvm/ADT/DenseMap.h"
Chris Lattnerac695822008-01-04 06:41:45 +000035#include "llvm/ADT/Statistic.h"
Chris Lattnerac695822008-01-04 06:41:45 +000036#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000037#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000038
39using namespace llvm;
40
Bill Wendling041b3f82007-12-08 23:58:46 +000041STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000042STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Bill Wendlingb48519c2007-12-08 01:47:01 +000043
Bill Wendling0f940c92007-12-07 21:42:31 +000044namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000045 class MachineLICM : public MachineFunctionPass {
Bill Wendling9258cd32008-01-02 19:32:43 +000046 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000047 const TargetInstrInfo *TII;
Dan Gohmana8fb3362009-09-25 23:58:45 +000048 const TargetRegisterInfo *TRI;
Dan Gohman45094e32009-09-26 02:34:00 +000049 BitVector AllocatableSet;
Bill Wendling12ebf142007-12-11 19:40:06 +000050
Bill Wendling0f940c92007-12-07 21:42:31 +000051 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000052 AliasAnalysis *AA; // Alias analysis info.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000053 MachineLoopInfo *LI; // Current MachineLoopInfo
54 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling9258cd32008-01-02 19:32:43 +000055 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendling0f940c92007-12-07 21:42:31 +000056
Bill Wendling0f940c92007-12-07 21:42:31 +000057 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000058 bool Changed; // True if a loop is changed.
Evan Cheng777c6b72009-11-03 21:40:02 +000059 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000060 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000061 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000062
Evan Cheng777c6b72009-11-03 21:40:02 +000063 // For each opcode, keep a list of potentail CSE instructions.
64 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Bill Wendling0f940c92007-12-07 21:42:31 +000065 public:
66 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000067 MachineLICM() : MachineFunctionPass(&ID) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000068
69 virtual bool runOnMachineFunction(MachineFunction &MF);
70
Dan Gohman72241702008-12-18 01:37:56 +000071 const char *getPassName() const { return "Machine Instruction LICM"; }
72
Bill Wendling074223a2008-03-10 08:13:01 +000073 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000074 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.setPreservesCFG();
76 AU.addRequired<MachineLoopInfo>();
77 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000078 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000079 AU.addPreserved<MachineLoopInfo>();
80 AU.addPreserved<MachineDominatorTree>();
81 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000082 }
Evan Chengaf6949d2009-02-05 08:45:46 +000083
84 virtual void releaseMemory() {
85 CSEMap.clear();
86 }
87
Bill Wendling0f940c92007-12-07 21:42:31 +000088 private:
Bill Wendling041b3f82007-12-08 23:58:46 +000089 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +000090 /// invariant. I.e., all virtual register operands are defined outside of
91 /// the loop, physical registers aren't accessed (explicitly or implicitly),
92 /// and the instruction is hoistable.
93 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000094 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +000095
Evan Cheng45e94d62009-02-04 09:19:56 +000096 /// IsProfitableToHoist - Return true if it is potentially profitable to
97 /// hoist the given loop invariant.
98 bool IsProfitableToHoist(MachineInstr &MI);
99
Bill Wendling0f940c92007-12-07 21:42:31 +0000100 /// HoistRegion - Walk the specified region of the CFG (defined by all
101 /// blocks dominated by the specified block, and that are in the current
102 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
103 /// visit definitions before uses, allowing us to hoist a loop body in one
104 /// pass without iteration.
105 ///
106 void HoistRegion(MachineDomTreeNode *N);
107
Dan Gohman5c952302009-10-29 17:47:20 +0000108 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
109 /// the load itself could be hoisted. Return the unfolded and hoistable
110 /// load, or null if the load couldn't be unfolded or if it wouldn't
111 /// be hoistable.
112 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
113
Bill Wendling0f940c92007-12-07 21:42:31 +0000114 /// Hoist - When an instruction is found to only use loop invariant operands
115 /// that is safe to hoist, this instruction is called to do the dirty work.
116 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000117 void Hoist(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000118
119 /// InitCSEMap - Initialize the CSE map with instructions that are in the
120 /// current loop preheader that may become duplicates of instructions that
121 /// are hoisted out of the loop.
122 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000123 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000124} // end anonymous namespace
125
Dan Gohman844731a2008-05-13 00:00:25 +0000126char MachineLICM::ID = 0;
127static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000128X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000129
Bill Wendling0f940c92007-12-07 21:42:31 +0000130FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
131
Dan Gohmanc475c362009-01-15 22:01:38 +0000132/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
133/// loop that has a preheader.
134static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
135 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
136 if (L->getLoopPreheader())
137 return false;
138 return true;
139}
140
Bill Wendling0f940c92007-12-07 21:42:31 +0000141/// Hoist expressions out of the specified loop. Note, alias info for inner loop
142/// is not preserved so it is not a good idea to run LICM multiple times on one
143/// loop.
144///
145bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000146 DEBUG(errs() << "******** Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000147
Evan Cheng777c6b72009-11-03 21:40:02 +0000148 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000149 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000150 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000151 TRI = TM->getRegisterInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000152 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000153 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000154
155 // Get our Loop information...
156 LI = &getAnalysis<MachineLoopInfo>();
157 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000158 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000159
Evan Cheng777c6b72009-11-03 21:40:02 +0000160 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000161 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000162
Dan Gohmanc475c362009-01-15 22:01:38 +0000163 // Only visit outer-most preheader-sporting loops.
164 if (!LoopIsOuterMostWithPreheader(CurLoop))
165 continue;
166
167 // Determine the block to which to hoist instructions. If we can't find a
168 // suitable loop preheader, we can't do any hoisting.
169 //
170 // FIXME: We are only hoisting if the basic block coming into this loop
171 // has only one successor. This isn't the case in general because we haven't
172 // broken critical edges or added preheaders.
173 CurPreheader = CurLoop->getLoopPreheader();
174 if (!CurPreheader)
175 continue;
176
Evan Cheng777c6b72009-11-03 21:40:02 +0000177 // CSEMap is initialized for loop header when the first instruction is
178 // being hoisted.
179 FirstInLoop = true;
Dan Gohmanc475c362009-01-15 22:01:38 +0000180 HoistRegion(DT->getNode(CurLoop->getHeader()));
Evan Cheng777c6b72009-11-03 21:40:02 +0000181 CSEMap.clear();
Bill Wendling0f940c92007-12-07 21:42:31 +0000182 }
183
184 return Changed;
185}
186
Bill Wendling0f940c92007-12-07 21:42:31 +0000187/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
188/// dominated by the specified block, and that are in the current loop) in depth
189/// first order w.r.t the DominatorTree. This allows us to visit definitions
190/// before uses, allowing us to hoist a loop body in one pass without iteration.
191///
192void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
193 assert(N != 0 && "Null dominator tree node?");
194 MachineBasicBlock *BB = N->getBlock();
195
196 // If this subregion is not in the top level loop at all, exit.
197 if (!CurLoop->contains(BB)) return;
198
Dan Gohmanc475c362009-01-15 22:01:38 +0000199 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000200 MII = BB->begin(), E = BB->end(); MII != E; ) {
201 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000202 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000203 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000204 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000205
206 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
207
208 for (unsigned I = 0, E = Children.size(); I != E; ++I)
209 HoistRegion(Children[I]);
210}
211
Bill Wendling041b3f82007-12-08 23:58:46 +0000212/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000213/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000214/// loop, physical registers aren't accessed explicitly, and there are no side
215/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000216///
Bill Wendling041b3f82007-12-08 23:58:46 +0000217bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000218 const TargetInstrDesc &TID = I.getDesc();
219
220 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000221 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000222 TID.hasUnmodeledSideEffects())
223 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000224
Chris Lattnera22edc82008-01-10 23:08:24 +0000225 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000226 // Okay, this instruction does a load. As a refinement, we allow the target
227 // to decide whether the loaded value is actually a constant. If so, we can
228 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000229 if (!I.isInvariantLoad(AA))
Chris Lattnera22edc82008-01-10 23:08:24 +0000230 // FIXME: we should be able to sink loads with no other side effects if
231 // there is nothing that can change memory from here until the end of
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000232 // block. This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000233 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000234 }
Bill Wendling074223a2008-03-10 08:13:01 +0000235
Bill Wendling280f4562007-12-18 21:38:04 +0000236 DEBUG({
Bill Wendlingb7a89922009-08-22 20:25:44 +0000237 errs() << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000238 if (I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000239 errs() << " * Instruction has implicit uses:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000240
Dan Gohman6f0d0242008-02-10 18:45:23 +0000241 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000242 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000243 *ImpUses; ++ImpUses)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000244 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000245 }
246
Chris Lattner749c6f62008-01-07 07:27:27 +0000247 if (I.getDesc().getImplicitDefs()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000248 errs() << " * Instruction has implicit defines:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000249
Dan Gohman6f0d0242008-02-10 18:45:23 +0000250 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000251 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000252 *ImpDefs; ++ImpDefs)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000253 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000254 }
Bill Wendling280f4562007-12-18 21:38:04 +0000255 });
256
Bill Wendlingd3361e92008-08-18 00:33:49 +0000257 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000258 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
Bill Wendlingd3361e92008-08-18 00:33:49 +0000259 return false;
260 }
261
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000262 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000263 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
264 const MachineOperand &MO = I.getOperand(i);
265
Dan Gohmand735b802008-10-03 15:45:36 +0000266 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000267 continue;
268
Dan Gohmanc475c362009-01-15 22:01:38 +0000269 unsigned Reg = MO.getReg();
270 if (Reg == 0) continue;
271
272 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000273 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000274 if (MO.isUse()) {
275 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000276 // and we can freely move its uses. Alternatively, if it's allocatable,
277 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000278 if (!RegInfo->def_empty(Reg))
279 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000280 if (AllocatableSet.test(Reg))
281 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000282 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000283 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
284 unsigned AliasReg = *Alias;
285 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000286 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000287 if (AllocatableSet.test(AliasReg))
288 return false;
289 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000290 // Otherwise it's safe to move.
291 continue;
292 } else if (!MO.isDead()) {
293 // A def that isn't dead. We can't move it.
294 return false;
295 }
296 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000297
298 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000299 continue;
300
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000301 assert(RegInfo->getVRegDef(Reg) &&
302 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000303
304 // If the loop contains the definition of an operand, then the instruction
305 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000306 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000307 return false;
308 }
309
310 // If we got this far, the instruction is loop invariant!
311 return true;
312}
313
Evan Chengaf6949d2009-02-05 08:45:46 +0000314
315/// HasPHIUses - Return true if the specified register has any PHI use.
316static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000317 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
318 UE = RegInfo->use_end(); UI != UE; ++UI) {
319 MachineInstr *UseMI = &*UI;
Evan Chengaf6949d2009-02-05 08:45:46 +0000320 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
321 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000322 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000323 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000324}
325
326/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
327/// the given loop invariant.
328bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengefc78392009-02-27 00:02:22 +0000329 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
330 return false;
331
Evan Cheng45e94d62009-02-04 09:19:56 +0000332 // FIXME: For now, only hoist re-materilizable instructions. LICM will
333 // increase register pressure. We want to make sure it doesn't increase
334 // spilling.
Dan Gohmana70dca12009-10-09 23:27:56 +0000335 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng45e94d62009-02-04 09:19:56 +0000336 return false;
337
Evan Chengaf6949d2009-02-05 08:45:46 +0000338 // If result(s) of this instruction is used by PHIs, then don't hoist it.
339 // The presence of joins makes it difficult for current register allocator
340 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000341 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
342 const MachineOperand &MO = MI.getOperand(i);
343 if (!MO.isReg() || !MO.isDef())
344 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000345 if (HasPHIUses(MO.getReg(), RegInfo))
346 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000347 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000348
349 return true;
350}
351
352static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
Evan Chengefc78392009-02-27 00:02:22 +0000353 std::vector<const MachineInstr*> &PrevMIs,
354 MachineRegisterInfo *RegInfo) {
Evan Chengaf6949d2009-02-05 08:45:46 +0000355 unsigned NumOps = MI->getNumOperands();
356 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
357 const MachineInstr *PrevMI = PrevMIs[i];
358 unsigned NumOps2 = PrevMI->getNumOperands();
359 if (NumOps != NumOps2)
360 continue;
361 bool IsSame = true;
362 for (unsigned j = 0; j != NumOps; ++j) {
363 const MachineOperand &MO = MI->getOperand(j);
Evan Chengefc78392009-02-27 00:02:22 +0000364 if (MO.isReg() && MO.isDef()) {
365 if (RegInfo->getRegClass(MO.getReg()) !=
366 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
367 IsSame = false;
368 break;
369 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000370 continue;
Evan Chengefc78392009-02-27 00:02:22 +0000371 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000372 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
373 IsSame = false;
374 break;
375 }
376 }
377 if (IsSame)
378 return PrevMI;
379 }
380 return 0;
Evan Cheng45e94d62009-02-04 09:19:56 +0000381}
382
Dan Gohman5c952302009-10-29 17:47:20 +0000383MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
384 // If not, we may be able to unfold a load and hoist that.
385 // First test whether the instruction is loading from an amenable
386 // memory location.
387 if (!MI->getDesc().mayLoad()) return 0;
388 if (!MI->hasOneMemOperand()) return 0;
389 MachineMemOperand *MMO = *MI->memoperands_begin();
390 if (MMO->isVolatile()) return 0;
391 MachineFunction &MF = *MI->getParent()->getParent();
392 if (!MMO->getValue()) return 0;
393 if (const PseudoSourceValue *PSV =
394 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
395 if (!PSV->isConstant(MF.getFrameInfo())) return 0;
396 } else {
397 if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
398 }
399 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000400 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000401 unsigned NewOpc =
402 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
403 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000404 /*UnfoldStore=*/false,
405 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000406 if (NewOpc == 0) return 0;
407 const TargetInstrDesc &TID = TII->get(NewOpc);
408 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000409 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000410 // Ok, we're unfolding. Create a temporary register and do the unfold.
411 unsigned Reg = RegInfo->createVirtualRegister(RC);
412 SmallVector<MachineInstr *, 2> NewMIs;
413 bool Success =
414 TII->unfoldMemoryOperand(MF, MI, Reg,
415 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
416 NewMIs);
417 (void)Success;
418 assert(Success &&
419 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
420 "succeeded!");
421 assert(NewMIs.size() == 2 &&
422 "Unfolded a load into multiple instructions!");
423 MachineBasicBlock *MBB = MI->getParent();
424 MBB->insert(MI, NewMIs[0]);
425 MBB->insert(MI, NewMIs[1]);
426 // If unfolding produced a load that wasn't loop-invariant or profitable to
427 // hoist, discard the new instructions and bail.
428 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
429 NewMIs[0]->eraseFromParent();
430 NewMIs[1]->eraseFromParent();
431 return 0;
432 }
433 // Otherwise we successfully unfolded a load that we can hoist.
434 MI->eraseFromParent();
435 return NewMIs[0];
436}
437
Evan Cheng777c6b72009-11-03 21:40:02 +0000438void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
439 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
440 const MachineInstr *MI = &*I;
441 // FIXME: For now, only hoist re-materilizable instructions. LICM will
442 // increase register pressure. We want to make sure it doesn't increase
443 // spilling.
444 if (TII->isTriviallyReMaterializable(MI, AA)) {
445 unsigned Opcode = MI->getOpcode();
446 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
447 CI = CSEMap.find(Opcode);
448 if (CI != CSEMap.end())
449 CI->second.push_back(MI);
450 else {
451 std::vector<const MachineInstr*> CSEMIs;
452 CSEMIs.push_back(MI);
453 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
454 }
455 }
456 }
457}
458
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000459/// Hoist - When an instruction is found to use only loop invariant operands
460/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000461///
Dan Gohman589f1f52009-10-28 03:21:57 +0000462void MachineLICM::Hoist(MachineInstr *MI) {
463 // First check whether we should hoist this instruction.
464 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000465 // If not, try unfolding a hoistable load.
466 MI = ExtractHoistableLoad(MI);
467 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000468 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000469
Dan Gohmanc475c362009-01-15 22:01:38 +0000470 // Now move the instructions to the predecessor, inserting it before any
471 // terminator instructions.
472 DEBUG({
Dan Gohman589f1f52009-10-28 03:21:57 +0000473 errs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000474 if (CurPreheader->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000475 errs() << " to MachineBasicBlock "
476 << CurPreheader->getBasicBlock()->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000477 if (MI->getParent()->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000478 errs() << " from MachineBasicBlock "
Dan Gohman589f1f52009-10-28 03:21:57 +0000479 << MI->getParent()->getBasicBlock()->getName();
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000480 errs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000481 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000482
Evan Cheng777c6b72009-11-03 21:40:02 +0000483 // If this is the first instruction being hoisted to the preheader,
484 // initialize the CSE map with potential common expressions.
485 InitCSEMap(CurPreheader);
486
Evan Chengaf6949d2009-02-05 08:45:46 +0000487 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000488 unsigned Opcode = MI->getOpcode();
489 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
490 CI = CSEMap.find(Opcode);
Evan Chengaf6949d2009-02-05 08:45:46 +0000491 bool DoneCSE = false;
492 if (CI != CSEMap.end()) {
Dan Gohman589f1f52009-10-28 03:21:57 +0000493 const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo);
Evan Chengaf6949d2009-02-05 08:45:46 +0000494 if (Dup) {
Dan Gohman589f1f52009-10-28 03:21:57 +0000495 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
496 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
497 const MachineOperand &MO = MI->getOperand(i);
Evan Chengaf6949d2009-02-05 08:45:46 +0000498 if (MO.isReg() && MO.isDef())
499 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
500 }
Dan Gohman589f1f52009-10-28 03:21:57 +0000501 MI->eraseFromParent();
Evan Chengaf6949d2009-02-05 08:45:46 +0000502 DoneCSE = true;
503 ++NumCSEed;
504 }
505 }
506
507 // Otherwise, splice the instruction to the preheader.
508 if (!DoneCSE) {
Evan Cheng777c6b72009-11-03 21:40:02 +0000509 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
510
Evan Chengaf6949d2009-02-05 08:45:46 +0000511 // Add to the CSE map.
512 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000513 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000514 else {
515 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000516 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000517 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000518 }
519 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000520
Dan Gohmanc475c362009-01-15 22:01:38 +0000521 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000522 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000523}