blob: de3ab273b39a5303a4ff34c16f1d8b641ee834d2 [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
Evan Cheng9fb744e2009-11-05 00:51:13 +0000114 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
115 /// the preheader that compute the same value. If it's found, do a RAU on
116 /// with the definition of the existing instruction rather than hoisting
117 /// the instruction to the preheader.
118 bool EliminateCSE(MachineInstr *MI,
119 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
120
Bill Wendling0f940c92007-12-07 21:42:31 +0000121 /// Hoist - When an instruction is found to only use loop invariant operands
122 /// that is safe to hoist, this instruction is called to do the dirty work.
123 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000124 void Hoist(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000125
126 /// InitCSEMap - Initialize the CSE map with instructions that are in the
127 /// current loop preheader that may become duplicates of instructions that
128 /// are hoisted out of the loop.
129 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000130 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000131} // end anonymous namespace
132
Dan Gohman844731a2008-05-13 00:00:25 +0000133char MachineLICM::ID = 0;
134static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000135X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000136
Bill Wendling0f940c92007-12-07 21:42:31 +0000137FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
138
Dan Gohmanc475c362009-01-15 22:01:38 +0000139/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
140/// loop that has a preheader.
141static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
142 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
143 if (L->getLoopPreheader())
144 return false;
145 return true;
146}
147
Bill Wendling0f940c92007-12-07 21:42:31 +0000148/// Hoist expressions out of the specified loop. Note, alias info for inner loop
149/// is not preserved so it is not a good idea to run LICM multiple times on one
150/// loop.
151///
152bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000153 DEBUG(errs() << "******** Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000154
Evan Cheng777c6b72009-11-03 21:40:02 +0000155 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000156 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000157 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000158 TRI = TM->getRegisterInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000159 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000160 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000161
162 // Get our Loop information...
163 LI = &getAnalysis<MachineLoopInfo>();
164 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000165 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000166
Evan Cheng777c6b72009-11-03 21:40:02 +0000167 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000168 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000169
Dan Gohmanc475c362009-01-15 22:01:38 +0000170 // Only visit outer-most preheader-sporting loops.
171 if (!LoopIsOuterMostWithPreheader(CurLoop))
172 continue;
173
174 // Determine the block to which to hoist instructions. If we can't find a
175 // suitable loop preheader, we can't do any hoisting.
176 //
177 // FIXME: We are only hoisting if the basic block coming into this loop
178 // has only one successor. This isn't the case in general because we haven't
179 // broken critical edges or added preheaders.
180 CurPreheader = CurLoop->getLoopPreheader();
181 if (!CurPreheader)
182 continue;
183
Evan Cheng777c6b72009-11-03 21:40:02 +0000184 // CSEMap is initialized for loop header when the first instruction is
185 // being hoisted.
186 FirstInLoop = true;
Dan Gohmanc475c362009-01-15 22:01:38 +0000187 HoistRegion(DT->getNode(CurLoop->getHeader()));
Evan Cheng777c6b72009-11-03 21:40:02 +0000188 CSEMap.clear();
Bill Wendling0f940c92007-12-07 21:42:31 +0000189 }
190
191 return Changed;
192}
193
Bill Wendling0f940c92007-12-07 21:42:31 +0000194/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
195/// dominated by the specified block, and that are in the current loop) in depth
196/// first order w.r.t the DominatorTree. This allows us to visit definitions
197/// before uses, allowing us to hoist a loop body in one pass without iteration.
198///
199void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
200 assert(N != 0 && "Null dominator tree node?");
201 MachineBasicBlock *BB = N->getBlock();
202
203 // If this subregion is not in the top level loop at all, exit.
204 if (!CurLoop->contains(BB)) return;
205
Dan Gohmanc475c362009-01-15 22:01:38 +0000206 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000207 MII = BB->begin(), E = BB->end(); MII != E; ) {
208 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000209 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000210 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000211 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000212
213 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
214
215 for (unsigned I = 0, E = Children.size(); I != E; ++I)
216 HoistRegion(Children[I]);
217}
218
Bill Wendling041b3f82007-12-08 23:58:46 +0000219/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000220/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000221/// loop, physical registers aren't accessed explicitly, and there are no side
222/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000223///
Bill Wendling041b3f82007-12-08 23:58:46 +0000224bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000225 const TargetInstrDesc &TID = I.getDesc();
226
227 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000228 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000229 TID.hasUnmodeledSideEffects())
230 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000231
Chris Lattnera22edc82008-01-10 23:08:24 +0000232 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000233 // Okay, this instruction does a load. As a refinement, we allow the target
234 // to decide whether the loaded value is actually a constant. If so, we can
235 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000236 if (!I.isInvariantLoad(AA))
Chris Lattnera22edc82008-01-10 23:08:24 +0000237 // FIXME: we should be able to sink loads with no other side effects if
238 // there is nothing that can change memory from here until the end of
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000239 // block. This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000240 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000241 }
Bill Wendling074223a2008-03-10 08:13:01 +0000242
Bill Wendling280f4562007-12-18 21:38:04 +0000243 DEBUG({
Bill Wendlingb7a89922009-08-22 20:25:44 +0000244 errs() << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000245 if (I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000246 errs() << " * Instruction has implicit uses:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000247
Dan Gohman6f0d0242008-02-10 18:45:23 +0000248 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000249 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000250 *ImpUses; ++ImpUses)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000251 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000252 }
253
Chris Lattner749c6f62008-01-07 07:27:27 +0000254 if (I.getDesc().getImplicitDefs()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000255 errs() << " * Instruction has implicit defines:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000256
Dan Gohman6f0d0242008-02-10 18:45:23 +0000257 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000258 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000259 *ImpDefs; ++ImpDefs)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000260 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000261 }
Bill Wendling280f4562007-12-18 21:38:04 +0000262 });
263
Bill Wendlingd3361e92008-08-18 00:33:49 +0000264 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000265 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
Bill Wendlingd3361e92008-08-18 00:33:49 +0000266 return false;
267 }
268
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000269 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000270 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
271 const MachineOperand &MO = I.getOperand(i);
272
Dan Gohmand735b802008-10-03 15:45:36 +0000273 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000274 continue;
275
Dan Gohmanc475c362009-01-15 22:01:38 +0000276 unsigned Reg = MO.getReg();
277 if (Reg == 0) continue;
278
279 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000280 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000281 if (MO.isUse()) {
282 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000283 // and we can freely move its uses. Alternatively, if it's allocatable,
284 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000285 if (!RegInfo->def_empty(Reg))
286 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000287 if (AllocatableSet.test(Reg))
288 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000289 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000290 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
291 unsigned AliasReg = *Alias;
292 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000293 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000294 if (AllocatableSet.test(AliasReg))
295 return false;
296 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000297 // Otherwise it's safe to move.
298 continue;
299 } else if (!MO.isDead()) {
300 // A def that isn't dead. We can't move it.
301 return false;
302 }
303 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000304
305 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000306 continue;
307
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000308 assert(RegInfo->getVRegDef(Reg) &&
309 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000310
311 // If the loop contains the definition of an operand, then the instruction
312 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000313 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000314 return false;
315 }
316
317 // If we got this far, the instruction is loop invariant!
318 return true;
319}
320
Evan Chengaf6949d2009-02-05 08:45:46 +0000321
322/// HasPHIUses - Return true if the specified register has any PHI use.
323static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000324 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
325 UE = RegInfo->use_end(); UI != UE; ++UI) {
326 MachineInstr *UseMI = &*UI;
Evan Chengaf6949d2009-02-05 08:45:46 +0000327 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
328 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000329 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000330 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000331}
332
333/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
334/// the given loop invariant.
335bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengefc78392009-02-27 00:02:22 +0000336 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
337 return false;
338
Evan Cheng45e94d62009-02-04 09:19:56 +0000339 // FIXME: For now, only hoist re-materilizable instructions. LICM will
340 // increase register pressure. We want to make sure it doesn't increase
341 // spilling.
Dan Gohmana70dca12009-10-09 23:27:56 +0000342 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng45e94d62009-02-04 09:19:56 +0000343 return false;
344
Evan Chengaf6949d2009-02-05 08:45:46 +0000345 // If result(s) of this instruction is used by PHIs, then don't hoist it.
346 // The presence of joins makes it difficult for current register allocator
347 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000348 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
349 const MachineOperand &MO = MI.getOperand(i);
350 if (!MO.isReg() || !MO.isDef())
351 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000352 if (HasPHIUses(MO.getReg(), RegInfo))
353 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000354 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000355
356 return true;
357}
358
Dan Gohman5c952302009-10-29 17:47:20 +0000359MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
360 // If not, we may be able to unfold a load and hoist that.
361 // First test whether the instruction is loading from an amenable
362 // memory location.
363 if (!MI->getDesc().mayLoad()) return 0;
364 if (!MI->hasOneMemOperand()) return 0;
365 MachineMemOperand *MMO = *MI->memoperands_begin();
366 if (MMO->isVolatile()) return 0;
367 MachineFunction &MF = *MI->getParent()->getParent();
368 if (!MMO->getValue()) return 0;
369 if (const PseudoSourceValue *PSV =
370 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
371 if (!PSV->isConstant(MF.getFrameInfo())) return 0;
372 } else {
373 if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
374 }
375 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000376 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000377 unsigned NewOpc =
378 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
379 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000380 /*UnfoldStore=*/false,
381 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000382 if (NewOpc == 0) return 0;
383 const TargetInstrDesc &TID = TII->get(NewOpc);
384 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000385 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000386 // Ok, we're unfolding. Create a temporary register and do the unfold.
387 unsigned Reg = RegInfo->createVirtualRegister(RC);
388 SmallVector<MachineInstr *, 2> NewMIs;
389 bool Success =
390 TII->unfoldMemoryOperand(MF, MI, Reg,
391 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
392 NewMIs);
393 (void)Success;
394 assert(Success &&
395 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
396 "succeeded!");
397 assert(NewMIs.size() == 2 &&
398 "Unfolded a load into multiple instructions!");
399 MachineBasicBlock *MBB = MI->getParent();
400 MBB->insert(MI, NewMIs[0]);
401 MBB->insert(MI, NewMIs[1]);
402 // If unfolding produced a load that wasn't loop-invariant or profitable to
403 // hoist, discard the new instructions and bail.
404 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
405 NewMIs[0]->eraseFromParent();
406 NewMIs[1]->eraseFromParent();
407 return 0;
408 }
409 // Otherwise we successfully unfolded a load that we can hoist.
410 MI->eraseFromParent();
411 return NewMIs[0];
412}
413
Evan Cheng777c6b72009-11-03 21:40:02 +0000414void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
415 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
416 const MachineInstr *MI = &*I;
417 // FIXME: For now, only hoist re-materilizable instructions. LICM will
418 // increase register pressure. We want to make sure it doesn't increase
419 // spilling.
420 if (TII->isTriviallyReMaterializable(MI, AA)) {
421 unsigned Opcode = MI->getOpcode();
422 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
423 CI = CSEMap.find(Opcode);
424 if (CI != CSEMap.end())
425 CI->second.push_back(MI);
426 else {
427 std::vector<const MachineInstr*> CSEMIs;
428 CSEMIs.push_back(MI);
429 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
430 }
431 }
432 }
433}
434
Evan Cheng9fb744e2009-11-05 00:51:13 +0000435static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
436 std::vector<const MachineInstr*> &PrevMIs,
437 MachineRegisterInfo *RegInfo) {
438 unsigned NumOps = MI->getNumOperands();
439 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
440 const MachineInstr *PrevMI = PrevMIs[i];
441 unsigned NumOps2 = PrevMI->getNumOperands();
442 if (NumOps != NumOps2)
443 continue;
444 bool IsSame = true;
445 for (unsigned j = 0; j != NumOps; ++j) {
446 const MachineOperand &MO = MI->getOperand(j);
447 if (MO.isReg() && MO.isDef()) {
448 if (RegInfo->getRegClass(MO.getReg()) !=
449 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
450 IsSame = false;
451 break;
452 }
453 continue;
454 }
455 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
456 IsSame = false;
457 break;
458 }
459 }
460 if (IsSame)
461 return PrevMI;
462 }
463 return 0;
464}
465
466bool MachineLICM::EliminateCSE(MachineInstr *MI,
467 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
468 if (CI != CSEMap.end()) {
469 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo)) {
470 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
471 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
472 const MachineOperand &MO = MI->getOperand(i);
473 if (MO.isReg() && MO.isDef())
474 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
475 }
476 MI->eraseFromParent();
477 ++NumCSEed;
478 return true;
479 }
480 }
481 return false;
482}
483
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000484/// Hoist - When an instruction is found to use only loop invariant operands
485/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000486///
Dan Gohman589f1f52009-10-28 03:21:57 +0000487void MachineLICM::Hoist(MachineInstr *MI) {
488 // First check whether we should hoist this instruction.
489 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000490 // If not, try unfolding a hoistable load.
491 MI = ExtractHoistableLoad(MI);
492 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000493 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000494
Dan Gohmanc475c362009-01-15 22:01:38 +0000495 // Now move the instructions to the predecessor, inserting it before any
496 // terminator instructions.
497 DEBUG({
Dan Gohman589f1f52009-10-28 03:21:57 +0000498 errs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000499 if (CurPreheader->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000500 errs() << " to MachineBasicBlock "
501 << CurPreheader->getBasicBlock()->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000502 if (MI->getParent()->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000503 errs() << " from MachineBasicBlock "
Dan Gohman589f1f52009-10-28 03:21:57 +0000504 << MI->getParent()->getBasicBlock()->getName();
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000505 errs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000506 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000507
Evan Cheng777c6b72009-11-03 21:40:02 +0000508 // If this is the first instruction being hoisted to the preheader,
509 // initialize the CSE map with potential common expressions.
510 InitCSEMap(CurPreheader);
511
Evan Chengaf6949d2009-02-05 08:45:46 +0000512 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000513 unsigned Opcode = MI->getOpcode();
514 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
515 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000516 if (!EliminateCSE(MI, CI)) {
517 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000518 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
519
Evan Chengaf6949d2009-02-05 08:45:46 +0000520 // Add to the CSE map.
521 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000522 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000523 else {
524 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000525 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000526 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000527 }
528 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000529
Dan Gohmanc475c362009-01-15 22:01:38 +0000530 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000531 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000532}