blob: 3f9ee482aecddff4d8c5f1106b36636832b05fef [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"
Evan Cheng87b75ba2009-11-20 19:55:37 +000037#include "llvm/Support/CommandLine.h"
Chris Lattnerac695822008-01-04 06:41:45 +000038#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000040
41using namespace llvm;
42
Evan Cheng87b75ba2009-11-20 19:55:37 +000043static cl::opt<bool> HoistLdConst("licm-const-load",
44 cl::desc("LICM load from constant memory"),
45 cl::init(false), cl::Hidden);
46
Bill Wendling041b3f82007-12-08 23:58:46 +000047STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000048STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Bill Wendlingb48519c2007-12-08 01:47:01 +000049
Bill Wendling0f940c92007-12-07 21:42:31 +000050namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000051 class MachineLICM : public MachineFunctionPass {
Evan Cheng78e5c112009-11-07 03:52:02 +000052 MachineConstantPool *MCP;
Bill Wendling9258cd32008-01-02 19:32:43 +000053 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000054 const TargetInstrInfo *TII;
Dan Gohmana8fb3362009-09-25 23:58:45 +000055 const TargetRegisterInfo *TRI;
Dan Gohman45094e32009-09-26 02:34:00 +000056 BitVector AllocatableSet;
Bill Wendling12ebf142007-12-11 19:40:06 +000057
Bill Wendling0f940c92007-12-07 21:42:31 +000058 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000059 AliasAnalysis *AA; // Alias analysis info.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000060 MachineLoopInfo *LI; // Current MachineLoopInfo
61 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling9258cd32008-01-02 19:32:43 +000062 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendling0f940c92007-12-07 21:42:31 +000063
Bill Wendling0f940c92007-12-07 21:42:31 +000064 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000065 bool Changed; // True if a loop is changed.
Evan Cheng777c6b72009-11-03 21:40:02 +000066 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000067 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000068 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000069
Evan Cheng777c6b72009-11-03 21:40:02 +000070 // For each opcode, keep a list of potentail CSE instructions.
71 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Bill Wendling0f940c92007-12-07 21:42:31 +000072 public:
73 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000074 MachineLICM() : MachineFunctionPass(&ID) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000075
76 virtual bool runOnMachineFunction(MachineFunction &MF);
77
Dan Gohman72241702008-12-18 01:37:56 +000078 const char *getPassName() const { return "Machine Instruction LICM"; }
79
Bill Wendling074223a2008-03-10 08:13:01 +000080 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000081 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.setPreservesCFG();
83 AU.addRequired<MachineLoopInfo>();
84 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000085 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000086 AU.addPreserved<MachineLoopInfo>();
87 AU.addPreserved<MachineDominatorTree>();
88 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000089 }
Evan Chengaf6949d2009-02-05 08:45:46 +000090
91 virtual void releaseMemory() {
92 CSEMap.clear();
93 }
94
Bill Wendling0f940c92007-12-07 21:42:31 +000095 private:
Bill Wendling041b3f82007-12-08 23:58:46 +000096 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +000097 /// invariant. I.e., all virtual register operands are defined outside of
98 /// the loop, physical registers aren't accessed (explicitly or implicitly),
99 /// and the instruction is hoistable.
100 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000101 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000102
Evan Cheng45e94d62009-02-04 09:19:56 +0000103 /// IsProfitableToHoist - Return true if it is potentially profitable to
104 /// hoist the given loop invariant.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000105 bool IsProfitableToHoist(MachineInstr &MI, bool &isConstLd);
Evan Cheng45e94d62009-02-04 09:19:56 +0000106
Bill Wendling0f940c92007-12-07 21:42:31 +0000107 /// HoistRegion - Walk the specified region of the CFG (defined by all
108 /// blocks dominated by the specified block, and that are in the current
109 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
110 /// visit definitions before uses, allowing us to hoist a loop body in one
111 /// pass without iteration.
112 ///
113 void HoistRegion(MachineDomTreeNode *N);
114
Evan Cheng87b75ba2009-11-20 19:55:37 +0000115 /// isLoadFromConstantMemory - Return true if the given instruction is a
116 /// load from constant memory.
117 bool isLoadFromConstantMemory(MachineInstr *MI);
118
Dan Gohman5c952302009-10-29 17:47:20 +0000119 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
120 /// the load itself could be hoisted. Return the unfolded and hoistable
121 /// load, or null if the load couldn't be unfolded or if it wouldn't
122 /// be hoistable.
123 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
124
Evan Cheng78e5c112009-11-07 03:52:02 +0000125 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
126 /// duplicate of MI. Return this instruction if it's found.
127 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
128 std::vector<const MachineInstr*> &PrevMIs);
129
Evan Cheng9fb744e2009-11-05 00:51:13 +0000130 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
131 /// the preheader that compute the same value. If it's found, do a RAU on
132 /// with the definition of the existing instruction rather than hoisting
133 /// the instruction to the preheader.
134 bool EliminateCSE(MachineInstr *MI,
135 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
136
Bill Wendling0f940c92007-12-07 21:42:31 +0000137 /// Hoist - When an instruction is found to only use loop invariant operands
138 /// that is safe to hoist, this instruction is called to do the dirty work.
139 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000140 void Hoist(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000141
142 /// InitCSEMap - Initialize the CSE map with instructions that are in the
143 /// current loop preheader that may become duplicates of instructions that
144 /// are hoisted out of the loop.
145 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000146 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000147} // end anonymous namespace
148
Dan Gohman844731a2008-05-13 00:00:25 +0000149char MachineLICM::ID = 0;
150static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000151X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000152
Bill Wendling0f940c92007-12-07 21:42:31 +0000153FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
154
Dan Gohmanc475c362009-01-15 22:01:38 +0000155/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
156/// loop that has a preheader.
157static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
158 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
159 if (L->getLoopPreheader())
160 return false;
161 return true;
162}
163
Bill Wendling0f940c92007-12-07 21:42:31 +0000164/// Hoist expressions out of the specified loop. Note, alias info for inner loop
165/// is not preserved so it is not a good idea to run LICM multiple times on one
166/// loop.
167///
168bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000169 DEBUG(errs() << "******** Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000170
Evan Cheng777c6b72009-11-03 21:40:02 +0000171 Changed = FirstInLoop = false;
Evan Cheng78e5c112009-11-07 03:52:02 +0000172 MCP = MF.getConstantPool();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000173 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000174 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000175 TRI = TM->getRegisterInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000176 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000177 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000178
179 // Get our Loop information...
180 LI = &getAnalysis<MachineLoopInfo>();
181 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000182 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000183
Evan Cheng777c6b72009-11-03 21:40:02 +0000184 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000185 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000186
Dan Gohmanc475c362009-01-15 22:01:38 +0000187 // Only visit outer-most preheader-sporting loops.
188 if (!LoopIsOuterMostWithPreheader(CurLoop))
189 continue;
190
191 // Determine the block to which to hoist instructions. If we can't find a
192 // suitable loop preheader, we can't do any hoisting.
193 //
194 // FIXME: We are only hoisting if the basic block coming into this loop
195 // has only one successor. This isn't the case in general because we haven't
196 // broken critical edges or added preheaders.
197 CurPreheader = CurLoop->getLoopPreheader();
198 if (!CurPreheader)
199 continue;
200
Evan Cheng777c6b72009-11-03 21:40:02 +0000201 // CSEMap is initialized for loop header when the first instruction is
202 // being hoisted.
203 FirstInLoop = true;
Dan Gohmanc475c362009-01-15 22:01:38 +0000204 HoistRegion(DT->getNode(CurLoop->getHeader()));
Evan Cheng777c6b72009-11-03 21:40:02 +0000205 CSEMap.clear();
Bill Wendling0f940c92007-12-07 21:42:31 +0000206 }
207
208 return Changed;
209}
210
Bill Wendling0f940c92007-12-07 21:42:31 +0000211/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
212/// dominated by the specified block, and that are in the current loop) in depth
213/// first order w.r.t the DominatorTree. This allows us to visit definitions
214/// before uses, allowing us to hoist a loop body in one pass without iteration.
215///
216void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
217 assert(N != 0 && "Null dominator tree node?");
218 MachineBasicBlock *BB = N->getBlock();
219
220 // If this subregion is not in the top level loop at all, exit.
221 if (!CurLoop->contains(BB)) return;
222
Dan Gohmanc475c362009-01-15 22:01:38 +0000223 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000224 MII = BB->begin(), E = BB->end(); MII != E; ) {
225 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000226 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000227 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000228 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000229
230 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
231
232 for (unsigned I = 0, E = Children.size(); I != E; ++I)
233 HoistRegion(Children[I]);
234}
235
Bill Wendling041b3f82007-12-08 23:58:46 +0000236/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000237/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000238/// loop, physical registers aren't accessed explicitly, and there are no side
239/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000240///
Bill Wendling041b3f82007-12-08 23:58:46 +0000241bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000242 const TargetInstrDesc &TID = I.getDesc();
243
244 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000245 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000246 TID.hasUnmodeledSideEffects())
247 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000248
Chris Lattnera22edc82008-01-10 23:08:24 +0000249 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000250 // Okay, this instruction does a load. As a refinement, we allow the target
251 // to decide whether the loaded value is actually a constant. If so, we can
252 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000253 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000254 // FIXME: we should be able to hoist loads with no other side effects if
255 // there are no other instructions which can change memory in this loop.
256 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000257 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000258 }
Bill Wendling074223a2008-03-10 08:13:01 +0000259
Bill Wendling280f4562007-12-18 21:38:04 +0000260 DEBUG({
Bill Wendlingb7a89922009-08-22 20:25:44 +0000261 errs() << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000262 if (I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000263 errs() << " * Instruction has implicit uses:\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 *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000267 *ImpUses; ++ImpUses)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000268 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000269 }
270
Chris Lattner749c6f62008-01-07 07:27:27 +0000271 if (I.getDesc().getImplicitDefs()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000272 errs() << " * Instruction has implicit defines:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000273
Dan Gohman6f0d0242008-02-10 18:45:23 +0000274 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000275 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000276 *ImpDefs; ++ImpDefs)
Bill Wendlingb7a89922009-08-22 20:25:44 +0000277 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000278 }
Bill Wendling280f4562007-12-18 21:38:04 +0000279 });
280
Bill Wendlingd3361e92008-08-18 00:33:49 +0000281 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
Bill Wendlingb7a89922009-08-22 20:25:44 +0000282 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
Bill Wendlingd3361e92008-08-18 00:33:49 +0000283 return false;
284 }
285
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000286 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000287 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
288 const MachineOperand &MO = I.getOperand(i);
289
Dan Gohmand735b802008-10-03 15:45:36 +0000290 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000291 continue;
292
Dan Gohmanc475c362009-01-15 22:01:38 +0000293 unsigned Reg = MO.getReg();
294 if (Reg == 0) continue;
295
296 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000297 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000298 if (MO.isUse()) {
299 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000300 // and we can freely move its uses. Alternatively, if it's allocatable,
301 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000302 if (!RegInfo->def_empty(Reg))
303 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000304 if (AllocatableSet.test(Reg))
305 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000306 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000307 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
308 unsigned AliasReg = *Alias;
309 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000310 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000311 if (AllocatableSet.test(AliasReg))
312 return false;
313 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000314 // Otherwise it's safe to move.
315 continue;
316 } else if (!MO.isDead()) {
317 // A def that isn't dead. We can't move it.
318 return false;
319 }
320 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000321
322 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000323 continue;
324
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000325 assert(RegInfo->getVRegDef(Reg) &&
326 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000327
328 // If the loop contains the definition of an operand, then the instruction
329 // isn't loop invariant.
Bill Wendling9258cd32008-01-02 19:32:43 +0000330 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
Bill Wendling0f940c92007-12-07 21:42:31 +0000331 return false;
332 }
333
334 // If we got this far, the instruction is loop invariant!
335 return true;
336}
337
Evan Chengaf6949d2009-02-05 08:45:46 +0000338
339/// HasPHIUses - Return true if the specified register has any PHI use.
340static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000341 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
342 UE = RegInfo->use_end(); UI != UE; ++UI) {
343 MachineInstr *UseMI = &*UI;
Evan Chengaf6949d2009-02-05 08:45:46 +0000344 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
345 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000346 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000347 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000348}
349
Evan Cheng87b75ba2009-11-20 19:55:37 +0000350/// isLoadFromConstantMemory - Return true if the given instruction is a
351/// load from constant memory. Machine LICM will hoist these even if they are
352/// not re-materializable.
353bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
354 if (!MI->getDesc().mayLoad()) return false;
355 if (!MI->hasOneMemOperand()) return false;
356 MachineMemOperand *MMO = *MI->memoperands_begin();
357 if (MMO->isVolatile()) return false;
358 if (!MMO->getValue()) return false;
359 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
360 if (PSV) {
361 MachineFunction &MF = *MI->getParent()->getParent();
362 return PSV->isConstant(MF.getFrameInfo());
363 } else {
364 return AA->pointsToConstantMemory(MMO->getValue());
365 }
366}
367
Evan Cheng45e94d62009-02-04 09:19:56 +0000368/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
369/// the given loop invariant.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000370bool MachineLICM::IsProfitableToHoist(MachineInstr &MI, bool &isConstLd) {
371 isConstLd = false;
372
Evan Chengefc78392009-02-27 00:02:22 +0000373 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
374 return false;
375
Evan Cheng45e94d62009-02-04 09:19:56 +0000376 // FIXME: For now, only hoist re-materilizable instructions. LICM will
377 // increase register pressure. We want to make sure it doesn't increase
378 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000379 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
380 // these tend to help performance in low register pressure situation. The
381 // trade off is it may cause spill in high pressure situation. It will end up
382 // adding a store in the loop preheader. But the reload is no more expensive.
383 // The side benefit is these loads are frequently CSE'ed.
384 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
385 if (!HoistLdConst || !isLoadFromConstantMemory(&MI))
386 return false;
387 isConstLd = true;
388 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000389
Evan Chengaf6949d2009-02-05 08:45:46 +0000390 // If result(s) of this instruction is used by PHIs, then don't hoist it.
391 // The presence of joins makes it difficult for current register allocator
392 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000393 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
394 const MachineOperand &MO = MI.getOperand(i);
395 if (!MO.isReg() || !MO.isDef())
396 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000397 if (HasPHIUses(MO.getReg(), RegInfo))
398 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000399 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000400
401 return true;
402}
403
Dan Gohman5c952302009-10-29 17:47:20 +0000404MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
405 // If not, we may be able to unfold a load and hoist that.
406 // First test whether the instruction is loading from an amenable
407 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000408 if (!isLoadFromConstantMemory(MI))
409 return 0;
410
Dan Gohman5c952302009-10-29 17:47:20 +0000411 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000412 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000413 unsigned NewOpc =
414 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
415 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000416 /*UnfoldStore=*/false,
417 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000418 if (NewOpc == 0) return 0;
419 const TargetInstrDesc &TID = TII->get(NewOpc);
420 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000421 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000422 // Ok, we're unfolding. Create a temporary register and do the unfold.
423 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000424
425 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000426 SmallVector<MachineInstr *, 2> NewMIs;
427 bool Success =
428 TII->unfoldMemoryOperand(MF, MI, Reg,
429 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
430 NewMIs);
431 (void)Success;
432 assert(Success &&
433 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
434 "succeeded!");
435 assert(NewMIs.size() == 2 &&
436 "Unfolded a load into multiple instructions!");
437 MachineBasicBlock *MBB = MI->getParent();
438 MBB->insert(MI, NewMIs[0]);
439 MBB->insert(MI, NewMIs[1]);
440 // If unfolding produced a load that wasn't loop-invariant or profitable to
441 // hoist, discard the new instructions and bail.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000442 bool isConstLd;
443 if (!IsLoopInvariantInst(*NewMIs[0]) ||
444 !IsProfitableToHoist(*NewMIs[0], isConstLd)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000445 NewMIs[0]->eraseFromParent();
446 NewMIs[1]->eraseFromParent();
447 return 0;
448 }
449 // Otherwise we successfully unfolded a load that we can hoist.
450 MI->eraseFromParent();
451 return NewMIs[0];
452}
453
Evan Cheng777c6b72009-11-03 21:40:02 +0000454void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
455 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
456 const MachineInstr *MI = &*I;
457 // FIXME: For now, only hoist re-materilizable instructions. LICM will
458 // increase register pressure. We want to make sure it doesn't increase
459 // spilling.
460 if (TII->isTriviallyReMaterializable(MI, AA)) {
461 unsigned Opcode = MI->getOpcode();
462 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
463 CI = CSEMap.find(Opcode);
464 if (CI != CSEMap.end())
465 CI->second.push_back(MI);
466 else {
467 std::vector<const MachineInstr*> CSEMIs;
468 CSEMIs.push_back(MI);
469 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
470 }
471 }
472 }
473}
474
Evan Cheng78e5c112009-11-07 03:52:02 +0000475const MachineInstr*
476MachineLICM::LookForDuplicate(const MachineInstr *MI,
477 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000478 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
479 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng78e5c112009-11-07 03:52:02 +0000480 if (TII->isIdentical(MI, PrevMI, RegInfo))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000481 return PrevMI;
482 }
483 return 0;
484}
485
486bool MachineLICM::EliminateCSE(MachineInstr *MI,
487 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000488 if (CI == CSEMap.end())
489 return false;
490
491 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
492 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
493 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
494 const MachineOperand &MO = MI->getOperand(i);
495 if (MO.isReg() && MO.isDef())
496 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Evan Cheng9fb744e2009-11-05 00:51:13 +0000497 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000498 MI->eraseFromParent();
499 ++NumCSEed;
500 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000501 }
502 return false;
503}
504
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000505/// Hoist - When an instruction is found to use only loop invariant operands
506/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000507///
Dan Gohman589f1f52009-10-28 03:21:57 +0000508void MachineLICM::Hoist(MachineInstr *MI) {
509 // First check whether we should hoist this instruction.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000510 bool isConstLd;
511 if (!IsLoopInvariantInst(*MI) ||
512 !IsProfitableToHoist(*MI, isConstLd)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000513 // If not, try unfolding a hoistable load.
514 MI = ExtractHoistableLoad(MI);
515 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000516 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000517
Dan Gohmanc475c362009-01-15 22:01:38 +0000518 // Now move the instructions to the predecessor, inserting it before any
519 // terminator instructions.
520 DEBUG({
Evan Cheng87b75ba2009-11-20 19:55:37 +0000521 errs() << "Hoisting ";
522 if (isConstLd)
523 errs() << "load from constant mem ";
524 errs() << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000525 if (CurPreheader->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000526 errs() << " to MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000527 << CurPreheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000528 if (MI->getParent()->getBasicBlock())
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000529 errs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000530 << MI->getParent()->getName();
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000531 errs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000532 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000533
Evan Cheng777c6b72009-11-03 21:40:02 +0000534 // If this is the first instruction being hoisted to the preheader,
535 // initialize the CSE map with potential common expressions.
536 InitCSEMap(CurPreheader);
537
Evan Chengaf6949d2009-02-05 08:45:46 +0000538 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000539 unsigned Opcode = MI->getOpcode();
540 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
541 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000542 if (!EliminateCSE(MI, CI)) {
543 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000544 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
545
Evan Chengaf6949d2009-02-05 08:45:46 +0000546 // Add to the CSE map.
547 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000548 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000549 else {
550 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000551 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000552 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000553 }
554 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000555
Dan Gohmanc475c362009-01-15 22:01:38 +0000556 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000557 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000558}