blob: 163a950d92d32f166d4b98b5063a571e1012feaf [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"
Evan Cheng78e5c112009-11-07 03:52:02 +000025#include "llvm/CodeGen/MachineConstantPool.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000026#include "llvm/CodeGen/MachineDominators.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000028#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000030#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000031#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000032#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000033#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000034#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000035#include "llvm/ADT/DenseMap.h"
Chris Lattnerac695822008-01-04 06:41:45 +000036#include "llvm/ADT/Statistic.h"
Chris Lattnerac695822008-01-04 06:41:45 +000037#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000038#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000039
40using namespace llvm;
41
Bill Wendling041b3f82007-12-08 23:58:46 +000042STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000043STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Bill Wendlingb48519c2007-12-08 01:47:01 +000044
Bill Wendling0f940c92007-12-07 21:42:31 +000045namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000046 class MachineLICM : public MachineFunctionPass {
Evan Cheng78e5c112009-11-07 03:52:02 +000047 MachineConstantPool *MCP;
Bill Wendling9258cd32008-01-02 19:32:43 +000048 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000049 const TargetInstrInfo *TII;
Dan Gohmana8fb3362009-09-25 23:58:45 +000050 const TargetRegisterInfo *TRI;
Dan Gohman45094e32009-09-26 02:34:00 +000051 BitVector AllocatableSet;
Bill Wendling12ebf142007-12-11 19:40:06 +000052
Bill Wendling0f940c92007-12-07 21:42:31 +000053 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000054 AliasAnalysis *AA; // Alias analysis info.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000055 MachineLoopInfo *LI; // Current MachineLoopInfo
56 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling9258cd32008-01-02 19:32:43 +000057 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendling0f940c92007-12-07 21:42:31 +000058
Bill Wendling0f940c92007-12-07 21:42:31 +000059 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000060 bool Changed; // True if a loop is changed.
Evan Cheng777c6b72009-11-03 21:40:02 +000061 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000062 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000063 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000064
Evan Cheng777c6b72009-11-03 21:40:02 +000065 // For each opcode, keep a list of potentail CSE instructions.
66 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Bill Wendling0f940c92007-12-07 21:42:31 +000067 public:
68 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000069 MachineLICM() : MachineFunctionPass(&ID) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000070
71 virtual bool runOnMachineFunction(MachineFunction &MF);
72
Dan Gohman72241702008-12-18 01:37:56 +000073 const char *getPassName() const { return "Machine Instruction LICM"; }
74
Bill Wendling074223a2008-03-10 08:13:01 +000075 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000076 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.setPreservesCFG();
78 AU.addRequired<MachineLoopInfo>();
79 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000080 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000081 AU.addPreserved<MachineLoopInfo>();
82 AU.addPreserved<MachineDominatorTree>();
83 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000084 }
Evan Chengaf6949d2009-02-05 08:45:46 +000085
86 virtual void releaseMemory() {
87 CSEMap.clear();
88 }
89
Bill Wendling0f940c92007-12-07 21:42:31 +000090 private:
Bill Wendling041b3f82007-12-08 23:58:46 +000091 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +000092 /// invariant. I.e., all virtual register operands are defined outside of
93 /// the loop, physical registers aren't accessed (explicitly or implicitly),
94 /// and the instruction is hoistable.
95 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000096 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +000097
Evan Cheng45e94d62009-02-04 09:19:56 +000098 /// IsProfitableToHoist - Return true if it is potentially profitable to
99 /// hoist the given loop invariant.
100 bool IsProfitableToHoist(MachineInstr &MI);
101
Bill Wendling0f940c92007-12-07 21:42:31 +0000102 /// HoistRegion - Walk the specified region of the CFG (defined by all
103 /// blocks dominated by the specified block, and that are in the current
104 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
105 /// visit definitions before uses, allowing us to hoist a loop body in one
106 /// pass without iteration.
107 ///
108 void HoistRegion(MachineDomTreeNode *N);
109
Dan Gohman5c952302009-10-29 17:47:20 +0000110 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
111 /// the load itself could be hoisted. Return the unfolded and hoistable
112 /// load, or null if the load couldn't be unfolded or if it wouldn't
113 /// be hoistable.
114 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
115
Evan Cheng78e5c112009-11-07 03:52:02 +0000116 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
117 /// duplicate of MI. Return this instruction if it's found.
118 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
119 std::vector<const MachineInstr*> &PrevMIs);
120
Evan Cheng9fb744e2009-11-05 00:51:13 +0000121 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
122 /// the preheader that compute the same value. If it's found, do a RAU on
123 /// with the definition of the existing instruction rather than hoisting
124 /// the instruction to the preheader.
125 bool EliminateCSE(MachineInstr *MI,
126 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
127
Bill Wendling0f940c92007-12-07 21:42:31 +0000128 /// Hoist - When an instruction is found to only use loop invariant operands
129 /// that is safe to hoist, this instruction is called to do the dirty work.
130 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000131 void Hoist(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000132
133 /// InitCSEMap - Initialize the CSE map with instructions that are in the
134 /// current loop preheader that may become duplicates of instructions that
135 /// are hoisted out of the loop.
136 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000137 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000138} // end anonymous namespace
139
Dan Gohman844731a2008-05-13 00:00:25 +0000140char MachineLICM::ID = 0;
141static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000142X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000143
Bill Wendling0f940c92007-12-07 21:42:31 +0000144FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
145
Dan Gohmanc475c362009-01-15 22:01:38 +0000146/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
147/// loop that has a preheader.
148static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
149 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
150 if (L->getLoopPreheader())
151 return false;
152 return true;
153}
154
Bill Wendling0f940c92007-12-07 21:42:31 +0000155/// Hoist expressions out of the specified loop. Note, alias info for inner loop
156/// is not preserved so it is not a good idea to run LICM multiple times on one
157/// loop.
158///
159bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000160 DEBUG(errs() << "******** Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000161
Evan Cheng777c6b72009-11-03 21:40:02 +0000162 Changed = FirstInLoop = false;
Evan Cheng78e5c112009-11-07 03:52:02 +0000163 MCP = MF.getConstantPool();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000164 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000165 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000166 TRI = TM->getRegisterInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000167 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000168 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000169
170 // Get our Loop information...
171 LI = &getAnalysis<MachineLoopInfo>();
172 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000173 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000174
Evan Cheng777c6b72009-11-03 21:40:02 +0000175 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000176 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000177
Dan Gohmanc475c362009-01-15 22:01:38 +0000178 // Only visit outer-most preheader-sporting loops.
179 if (!LoopIsOuterMostWithPreheader(CurLoop))
180 continue;
181
182 // Determine the block to which to hoist instructions. If we can't find a
183 // suitable loop preheader, we can't do any hoisting.
184 //
185 // FIXME: We are only hoisting if the basic block coming into this loop
186 // has only one successor. This isn't the case in general because we haven't
187 // broken critical edges or added preheaders.
188 CurPreheader = CurLoop->getLoopPreheader();
189 if (!CurPreheader)
190 continue;
191
Evan Cheng777c6b72009-11-03 21:40:02 +0000192 // CSEMap is initialized for loop header when the first instruction is
193 // being hoisted.
194 FirstInLoop = true;
Dan Gohmanc475c362009-01-15 22:01:38 +0000195 HoistRegion(DT->getNode(CurLoop->getHeader()));
Evan Cheng777c6b72009-11-03 21:40:02 +0000196 CSEMap.clear();
Bill Wendling0f940c92007-12-07 21:42:31 +0000197 }
198
199 return Changed;
200}
201
Bill Wendling0f940c92007-12-07 21:42:31 +0000202/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
203/// dominated by the specified block, and that are in the current loop) in depth
204/// first order w.r.t the DominatorTree. This allows us to visit definitions
205/// before uses, allowing us to hoist a loop body in one pass without iteration.
206///
207void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
208 assert(N != 0 && "Null dominator tree node?");
209 MachineBasicBlock *BB = N->getBlock();
210
211 // If this subregion is not in the top level loop at all, exit.
212 if (!CurLoop->contains(BB)) return;
213
Dan Gohmanc475c362009-01-15 22:01:38 +0000214 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000215 MII = BB->begin(), E = BB->end(); MII != E; ) {
216 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000217 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000218 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000219 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000220
221 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
222
223 for (unsigned I = 0, E = Children.size(); I != E; ++I)
224 HoistRegion(Children[I]);
225}
226
Bill Wendling041b3f82007-12-08 23:58:46 +0000227/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000228/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000229/// loop, physical registers aren't accessed explicitly, and there are no side
230/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000231///
Bill Wendling041b3f82007-12-08 23:58:46 +0000232bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000233 const TargetInstrDesc &TID = I.getDesc();
234
235 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000236 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000237 TID.hasUnmodeledSideEffects())
238 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000239
Chris Lattnera22edc82008-01-10 23:08:24 +0000240 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000241 // Okay, this instruction does a load. As a refinement, we allow the target
242 // to decide whether the loaded value is actually a constant. If so, we can
243 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000244 if (!I.isInvariantLoad(AA))
Chris Lattnera22edc82008-01-10 23:08:24 +0000245 // FIXME: we should be able to sink loads with no other side effects if
246 // there is nothing that can change memory from here until the end of
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000247 // block. This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000248 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000249 }
Bill Wendling074223a2008-03-10 08:13:01 +0000250
Bill Wendling280f4562007-12-18 21:38:04 +0000251 DEBUG({
Bill Wendlingb7a89922009-08-22 20:25:44 +0000252 errs() << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000253 if (I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000254 errs() << " * Instruction has implicit uses:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000255
Dan Gohman6f0d0242008-02-10 18:45:23 +0000256 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000257 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000258 *ImpUses; ++ImpUses)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000259 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000260 }
261
Chris Lattner749c6f62008-01-07 07:27:27 +0000262 if (I.getDesc().getImplicitDefs()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000263 errs() << " * Instruction has implicit defines:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000264
Dan Gohman6f0d0242008-02-10 18:45:23 +0000265 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000266 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000267 *ImpDefs; ++ImpDefs)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000268 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000269 }
Bill Wendling280f4562007-12-18 21:38:04 +0000270 });
271
Bill Wendlingd3361e92008-08-18 00:33:49 +0000272 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000273 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
Bill Wendlingd3361e92008-08-18 00:33:49 +0000274 return false;
275 }
276
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000277 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000278 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
279 const MachineOperand &MO = I.getOperand(i);
280
Dan Gohmand735b802008-10-03 15:45:36 +0000281 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000282 continue;
283
Dan Gohmanc475c362009-01-15 22:01:38 +0000284 unsigned Reg = MO.getReg();
285 if (Reg == 0) continue;
286
287 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000288 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000289 if (MO.isUse()) {
290 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000291 // and we can freely move its uses. Alternatively, if it's allocatable,
292 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000293 if (!RegInfo->def_empty(Reg))
294 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000295 if (AllocatableSet.test(Reg))
296 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000297 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000298 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
299 unsigned AliasReg = *Alias;
300 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000301 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000302 if (AllocatableSet.test(AliasReg))
303 return false;
304 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000305 // Otherwise it's safe to move.
306 continue;
307 } else if (!MO.isDead()) {
308 // A def that isn't dead. We can't move it.
309 return false;
310 }
311 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000312
313 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000314 continue;
315
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000316 assert(RegInfo->getVRegDef(Reg) &&
317 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000318
319 // If the loop contains the definition of an operand, then the instruction
320 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000321 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000322 return false;
323 }
324
325 // If we got this far, the instruction is loop invariant!
326 return true;
327}
328
Evan Chengaf6949d2009-02-05 08:45:46 +0000329
330/// HasPHIUses - Return true if the specified register has any PHI use.
331static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000332 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
333 UE = RegInfo->use_end(); UI != UE; ++UI) {
334 MachineInstr *UseMI = &*UI;
Evan Chengaf6949d2009-02-05 08:45:46 +0000335 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
336 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000337 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000338 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000339}
340
341/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
342/// the given loop invariant.
343bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengefc78392009-02-27 00:02:22 +0000344 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
345 return false;
346
Evan Cheng45e94d62009-02-04 09:19:56 +0000347 // FIXME: For now, only hoist re-materilizable instructions. LICM will
348 // increase register pressure. We want to make sure it doesn't increase
349 // spilling.
Dan Gohmana70dca12009-10-09 23:27:56 +0000350 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng45e94d62009-02-04 09:19:56 +0000351 return false;
352
Evan Chengaf6949d2009-02-05 08:45:46 +0000353 // If result(s) of this instruction is used by PHIs, then don't hoist it.
354 // The presence of joins makes it difficult for current register allocator
355 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000356 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
357 const MachineOperand &MO = MI.getOperand(i);
358 if (!MO.isReg() || !MO.isDef())
359 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000360 if (HasPHIUses(MO.getReg(), RegInfo))
361 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000362 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000363
364 return true;
365}
366
Dan Gohman5c952302009-10-29 17:47:20 +0000367MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
368 // If not, we may be able to unfold a load and hoist that.
369 // First test whether the instruction is loading from an amenable
370 // memory location.
371 if (!MI->getDesc().mayLoad()) return 0;
372 if (!MI->hasOneMemOperand()) return 0;
373 MachineMemOperand *MMO = *MI->memoperands_begin();
374 if (MMO->isVolatile()) return 0;
375 MachineFunction &MF = *MI->getParent()->getParent();
376 if (!MMO->getValue()) return 0;
377 if (const PseudoSourceValue *PSV =
378 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
379 if (!PSV->isConstant(MF.getFrameInfo())) return 0;
380 } else {
381 if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
382 }
383 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000384 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000385 unsigned NewOpc =
386 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
387 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000388 /*UnfoldStore=*/false,
389 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000390 if (NewOpc == 0) return 0;
391 const TargetInstrDesc &TID = TII->get(NewOpc);
392 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000393 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000394 // Ok, we're unfolding. Create a temporary register and do the unfold.
395 unsigned Reg = RegInfo->createVirtualRegister(RC);
396 SmallVector<MachineInstr *, 2> NewMIs;
397 bool Success =
398 TII->unfoldMemoryOperand(MF, MI, Reg,
399 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
400 NewMIs);
401 (void)Success;
402 assert(Success &&
403 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
404 "succeeded!");
405 assert(NewMIs.size() == 2 &&
406 "Unfolded a load into multiple instructions!");
407 MachineBasicBlock *MBB = MI->getParent();
408 MBB->insert(MI, NewMIs[0]);
409 MBB->insert(MI, NewMIs[1]);
410 // If unfolding produced a load that wasn't loop-invariant or profitable to
411 // hoist, discard the new instructions and bail.
412 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
413 NewMIs[0]->eraseFromParent();
414 NewMIs[1]->eraseFromParent();
415 return 0;
416 }
417 // Otherwise we successfully unfolded a load that we can hoist.
418 MI->eraseFromParent();
419 return NewMIs[0];
420}
421
Evan Cheng777c6b72009-11-03 21:40:02 +0000422void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
423 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
424 const MachineInstr *MI = &*I;
425 // FIXME: For now, only hoist re-materilizable instructions. LICM will
426 // increase register pressure. We want to make sure it doesn't increase
427 // spilling.
428 if (TII->isTriviallyReMaterializable(MI, AA)) {
429 unsigned Opcode = MI->getOpcode();
430 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
431 CI = CSEMap.find(Opcode);
432 if (CI != CSEMap.end())
433 CI->second.push_back(MI);
434 else {
435 std::vector<const MachineInstr*> CSEMIs;
436 CSEMIs.push_back(MI);
437 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
438 }
439 }
440 }
441}
442
Evan Cheng78e5c112009-11-07 03:52:02 +0000443const MachineInstr*
444MachineLICM::LookForDuplicate(const MachineInstr *MI,
445 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000446 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
447 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng78e5c112009-11-07 03:52:02 +0000448 if (TII->isIdentical(MI, PrevMI, RegInfo))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000449 return PrevMI;
450 }
451 return 0;
452}
453
454bool MachineLICM::EliminateCSE(MachineInstr *MI,
455 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000456 if (CI == CSEMap.end())
457 return false;
458
459 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
460 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
461 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
462 const MachineOperand &MO = MI->getOperand(i);
463 if (MO.isReg() && MO.isDef())
464 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Evan Cheng9fb744e2009-11-05 00:51:13 +0000465 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000466 MI->eraseFromParent();
467 ++NumCSEed;
468 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000469 }
470 return false;
471}
472
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000473/// Hoist - When an instruction is found to use only loop invariant operands
474/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000475///
Dan Gohman589f1f52009-10-28 03:21:57 +0000476void MachineLICM::Hoist(MachineInstr *MI) {
477 // First check whether we should hoist this instruction.
478 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000479 // If not, try unfolding a hoistable load.
480 MI = ExtractHoistableLoad(MI);
481 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000482 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000483
Dan Gohmanc475c362009-01-15 22:01:38 +0000484 // Now move the instructions to the predecessor, inserting it before any
485 // terminator instructions.
486 DEBUG({
Dan Gohman589f1f52009-10-28 03:21:57 +0000487 errs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000488 if (CurPreheader->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000489 errs() << " to MachineBasicBlock "
490 << CurPreheader->getBasicBlock()->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000491 if (MI->getParent()->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000492 errs() << " from MachineBasicBlock "
Dan Gohman589f1f52009-10-28 03:21:57 +0000493 << MI->getParent()->getBasicBlock()->getName();
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000494 errs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000495 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000496
Evan Cheng777c6b72009-11-03 21:40:02 +0000497 // If this is the first instruction being hoisted to the preheader,
498 // initialize the CSE map with potential common expressions.
499 InitCSEMap(CurPreheader);
500
Evan Chengaf6949d2009-02-05 08:45:46 +0000501 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000502 unsigned Opcode = MI->getOpcode();
503 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
504 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000505 if (!EliminateCSE(MI, CI)) {
506 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000507 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
508
Evan Chengaf6949d2009-02-05 08:45:46 +0000509 // Add to the CSE map.
510 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000511 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000512 else {
513 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000514 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000515 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000516 }
517 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000518
Dan Gohmanc475c362009-01-15 22:01:38 +0000519 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000520 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000521}