blob: 35cd6d6421528b0e3966751f09d2486dd86c21bd [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"
Evan Chengd94671a2010-04-07 00:41:17 +000026#include "llvm/CodeGen/MachineFrameInfo.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"
Evan Chengd94671a2010-04-07 00:41:17 +000036#include "llvm/ADT/SmallSet.h"
Chris Lattnerac695822008-01-04 06:41:45 +000037#include "llvm/ADT/Statistic.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
Bill Wendling041b3f82007-12-08 23:58:46 +000043STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000044STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000045STATISTIC(NumPostRAHoisted,
46 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000047
Bill Wendling0f940c92007-12-07 21:42:31 +000048namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000049 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000050 bool PreRegAlloc;
51
Bill Wendling9258cd32008-01-02 19:32:43 +000052 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000053 const TargetInstrInfo *TII;
Dan Gohmana8fb3362009-09-25 23:58:45 +000054 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000055 const MachineFrameInfo *MFI;
56 MachineRegisterInfo *RegInfo;
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 Wendling0f940c92007-12-07 21:42:31 +000062
Bill Wendling0f940c92007-12-07 21:42:31 +000063 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000064 bool Changed; // True if a loop is changed.
Evan Cheng777c6b72009-11-03 21:40:02 +000065 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000066 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000067 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000068
Evan Chengd94671a2010-04-07 00:41:17 +000069 BitVector AllocatableSet;
70
Evan Cheng777c6b72009-11-03 21:40:02 +000071 // For each opcode, keep a list of potentail CSE instructions.
72 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000073
Bill Wendling0f940c92007-12-07 21:42:31 +000074 public:
75 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000076 MachineLICM() :
77 MachineFunctionPass(&ID), PreRegAlloc(true) {}
78
79 explicit MachineLICM(bool PreRA) :
80 MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000081
82 virtual bool runOnMachineFunction(MachineFunction &MF);
83
Dan Gohman72241702008-12-18 01:37:56 +000084 const char *getPassName() const { return "Machine Instruction LICM"; }
85
Bill Wendling074223a2008-03-10 08:13:01 +000086 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000087 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.setPreservesCFG();
89 AU.addRequired<MachineLoopInfo>();
90 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000091 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000092 AU.addPreserved<MachineLoopInfo>();
93 AU.addPreserved<MachineDominatorTree>();
94 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000095 }
Evan Chengaf6949d2009-02-05 08:45:46 +000096
97 virtual void releaseMemory() {
98 CSEMap.clear();
99 }
100
Bill Wendling0f940c92007-12-07 21:42:31 +0000101 private:
Bill Wendling041b3f82007-12-08 23:58:46 +0000102 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000103 /// invariant. I.e., all virtual register operands are defined outside of
104 /// the loop, physical registers aren't accessed (explicitly or implicitly),
105 /// and the instruction is hoistable.
106 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000107 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000108
Evan Cheng45e94d62009-02-04 09:19:56 +0000109 /// IsProfitableToHoist - Return true if it is potentially profitable to
110 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000111 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000112
Bill Wendling0f940c92007-12-07 21:42:31 +0000113 /// HoistRegion - Walk the specified region of the CFG (defined by all
114 /// blocks dominated by the specified block, and that are in the current
115 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
116 /// visit definitions before uses, allowing us to hoist a loop body in one
117 /// pass without iteration.
118 ///
119 void HoistRegion(MachineDomTreeNode *N);
Evan Chengd94671a2010-04-07 00:41:17 +0000120 void HoistRegionPostRA(MachineDomTreeNode *N);
Bill Wendling0f940c92007-12-07 21:42:31 +0000121
Evan Cheng87b75ba2009-11-20 19:55:37 +0000122 /// isLoadFromConstantMemory - Return true if the given instruction is a
123 /// load from constant memory.
124 bool isLoadFromConstantMemory(MachineInstr *MI);
125
Dan Gohman5c952302009-10-29 17:47:20 +0000126 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
127 /// the load itself could be hoisted. Return the unfolded and hoistable
128 /// load, or null if the load couldn't be unfolded or if it wouldn't
129 /// be hoistable.
130 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
131
Evan Cheng78e5c112009-11-07 03:52:02 +0000132 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
133 /// duplicate of MI. Return this instruction if it's found.
134 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
135 std::vector<const MachineInstr*> &PrevMIs);
136
Evan Cheng9fb744e2009-11-05 00:51:13 +0000137 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
138 /// the preheader that compute the same value. If it's found, do a RAU on
139 /// with the definition of the existing instruction rather than hoisting
140 /// the instruction to the preheader.
141 bool EliminateCSE(MachineInstr *MI,
142 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
143
Bill Wendling0f940c92007-12-07 21:42:31 +0000144 /// Hoist - When an instruction is found to only use loop invariant operands
145 /// that is safe to hoist, this instruction is called to do the dirty work.
146 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000147 void Hoist(MachineInstr *MI);
Evan Chengd94671a2010-04-07 00:41:17 +0000148 void HoistPostRA(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000149
150 /// InitCSEMap - Initialize the CSE map with instructions that are in the
151 /// current loop preheader that may become duplicates of instructions that
152 /// are hoisted out of the loop.
153 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000154 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000155} // end anonymous namespace
156
Dan Gohman844731a2008-05-13 00:00:25 +0000157char MachineLICM::ID = 0;
158static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000159X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000160
Evan Chengd94671a2010-04-07 00:41:17 +0000161FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
162 return new MachineLICM(PreRegAlloc);
163}
Bill Wendling0f940c92007-12-07 21:42:31 +0000164
Dan Gohmanc475c362009-01-15 22:01:38 +0000165/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
166/// loop that has a preheader.
167static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
168 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
169 if (L->getLoopPreheader())
170 return false;
171 return true;
172}
173
Bill Wendling0f940c92007-12-07 21:42:31 +0000174/// Hoist expressions out of the specified loop. Note, alias info for inner loop
175/// is not preserved so it is not a good idea to run LICM multiple times on one
176/// loop.
177///
178bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000179 if (PreRegAlloc)
180 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
181 else
182 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000183
Evan Cheng777c6b72009-11-03 21:40:02 +0000184 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000185 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000186 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000187 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000188 MFI = MF.getFrameInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000189 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000190 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000191
192 // Get our Loop information...
193 LI = &getAnalysis<MachineLoopInfo>();
194 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000195 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000196
Evan Cheng777c6b72009-11-03 21:40:02 +0000197 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000198 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000199
Dan Gohmanc475c362009-01-15 22:01:38 +0000200 // Only visit outer-most preheader-sporting loops.
201 if (!LoopIsOuterMostWithPreheader(CurLoop))
202 continue;
203
204 // Determine the block to which to hoist instructions. If we can't find a
205 // suitable loop preheader, we can't do any hoisting.
206 //
207 // FIXME: We are only hoisting if the basic block coming into this loop
208 // has only one successor. This isn't the case in general because we haven't
209 // broken critical edges or added preheaders.
210 CurPreheader = CurLoop->getLoopPreheader();
211 if (!CurPreheader)
212 continue;
213
Evan Cheng777c6b72009-11-03 21:40:02 +0000214 // CSEMap is initialized for loop header when the first instruction is
215 // being hoisted.
216 FirstInLoop = true;
Evan Chengd94671a2010-04-07 00:41:17 +0000217 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
218 if (!PreRegAlloc)
219 HoistRegionPostRA(N);
220 else {
221 HoistRegion(N);
222 CSEMap.clear();
223 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000224 }
225
226 return Changed;
227}
228
Evan Chengd94671a2010-04-07 00:41:17 +0000229void MachineLICM::HoistRegionPostRA(MachineDomTreeNode *N) {
230 assert(N != 0 && "Null dominator tree node?");
231
232 unsigned NumRegs = TRI->getNumRegs();
233 unsigned *PhysRegDefs = new unsigned[NumRegs];
234 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
235
236 SmallVector<std::pair<MachineInstr*, int>, 32> Candidates;
237 SmallSet<int, 32> StoredFIs;
238
239 // Walk the entire region, count number of defs for each register, and
240 // return potential LICM candidates.
241 SmallVector<MachineDomTreeNode*, 8> WorkList;
242 WorkList.push_back(N);
243 do {
244 N = WorkList.pop_back_val();
245 MachineBasicBlock *BB = N->getBlock();
246
247 if (!CurLoop->contains(BB))
248 continue;
249 // Conservatively treat live-in's as an external def.
250 for (MachineBasicBlock::const_livein_iterator I = BB->livein_begin(),
251 E = BB->livein_end(); I != E; ++I) {
252 unsigned Reg = *I;
253 ++PhysRegDefs[Reg];
254 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
255 ++PhysRegDefs[*SR];
256 }
257
258 for (MachineBasicBlock::iterator
259 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
260 bool RuledOut = false;
261 bool SeenDef = false;
262 MachineInstr *MI = &*MII;
263 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
264 const MachineOperand &MO = MI->getOperand(i);
265 if (!MO.isReg())
266 continue;
267 unsigned Reg = MO.getReg();
268 if (!Reg)
269 continue;
270 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
271 "Not expecting virtual register!");
272
273 if (MO.isDef()) {
274 SeenDef = true;
275 if (++PhysRegDefs[Reg] > 1)
276 // MI defined register is seen defined by another instruction in
277 // the loop, it cannot be a LICM candidate.
278 RuledOut = true;
279 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
280 if (++PhysRegDefs[*SR] > 1)
281 RuledOut = true;
282 }
283 }
284
285 // FIXME: Only consider reloads for now.
286 bool SkipCheck = false;
287 int FI;
288 if (SeenDef && !RuledOut) {
289 if (TII->isLoadFromStackSlot(MI, FI) &&
290 MFI->isSpillSlotObjectIndex(FI)) {
291 Candidates.push_back(std::make_pair(MI, FI));
292 SkipCheck = true;
293 }
294 }
295
296 // If MI is a store to a stack slot, remember the slot. An instruction
297 // loads from this slot cannot be a LICM candidate.
298 if (SkipCheck && TII->isStoreToStackSlot(MI, FI))
299 StoredFIs.insert(FI);
300 }
301
302 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
303 for (unsigned I = 0, E = Children.size(); I != E; ++I)
304 WorkList.push_back(Children[I]);
305 } while (!WorkList.empty());
306
307 // Now evaluate whether the potential candidates qualify.
308 // 1. Check if the candidate defined register is defined by another
309 // instruction in the loop.
310 // 2. If the candidate is a load from stack slot (always true for now),
311 // check if the slot is stored anywhere in the loop.
312 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
313 bool Safe = true;
314 int FI = Candidates[i].second;
315 if (StoredFIs.count(FI))
316 continue;
317
318 MachineInstr *MI = Candidates[i].first;
319 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
320 const MachineOperand &MO = MI->getOperand(j);
321 if (!MO.isReg())
322 continue;
323 unsigned Reg = MO.getReg();
324 if (!Reg)
325 continue;
326 if (MO.isDef() && PhysRegDefs[Reg] > 1) {
327 Safe = false;
328 break;
329 }
330 }
331
332 if (Safe)
333 HoistPostRA(MI);
334 }
335}
336
337void MachineLICM::HoistPostRA(MachineInstr *MI) {
338 // Now move the instructions to the predecessor, inserting it before any
339 // terminator instructions.
340 DEBUG({
341 dbgs() << "Hoisting " << *MI;
342 if (CurPreheader->getBasicBlock())
343 dbgs() << " to MachineBasicBlock "
344 << CurPreheader->getName();
345 if (MI->getParent()->getBasicBlock())
346 dbgs() << " from MachineBasicBlock "
347 << MI->getParent()->getName();
348 dbgs() << "\n";
349 });
350
351 // Splice the instruction to the preheader.
352 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
353
354 ++NumPostRAHoisted;
355 Changed = true;
356}
357
Bill Wendling0f940c92007-12-07 21:42:31 +0000358/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
359/// dominated by the specified block, and that are in the current loop) in depth
360/// first order w.r.t the DominatorTree. This allows us to visit definitions
361/// before uses, allowing us to hoist a loop body in one pass without iteration.
362///
363void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
364 assert(N != 0 && "Null dominator tree node?");
365 MachineBasicBlock *BB = N->getBlock();
366
367 // If this subregion is not in the top level loop at all, exit.
368 if (!CurLoop->contains(BB)) return;
369
Dan Gohmanc475c362009-01-15 22:01:38 +0000370 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000371 MII = BB->begin(), E = BB->end(); MII != E; ) {
372 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000373 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000374 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000375 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000376
377 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Bill Wendling0f940c92007-12-07 21:42:31 +0000378 for (unsigned I = 0, E = Children.size(); I != E; ++I)
379 HoistRegion(Children[I]);
380}
381
Bill Wendling041b3f82007-12-08 23:58:46 +0000382/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000383/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000384/// loop, physical registers aren't accessed explicitly, and there are no side
385/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000386///
Bill Wendling041b3f82007-12-08 23:58:46 +0000387bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000388 const TargetInstrDesc &TID = I.getDesc();
389
390 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000391 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000392 TID.hasUnmodeledSideEffects())
393 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000394
Chris Lattnera22edc82008-01-10 23:08:24 +0000395 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000396 // Okay, this instruction does a load. As a refinement, we allow the target
397 // to decide whether the loaded value is actually a constant. If so, we can
398 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000399 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000400 // FIXME: we should be able to hoist loads with no other side effects if
401 // there are no other instructions which can change memory in this loop.
402 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000403 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000404 }
Bill Wendling074223a2008-03-10 08:13:01 +0000405
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000406 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000407 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
408 const MachineOperand &MO = I.getOperand(i);
409
Dan Gohmand735b802008-10-03 15:45:36 +0000410 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000411 continue;
412
Dan Gohmanc475c362009-01-15 22:01:38 +0000413 unsigned Reg = MO.getReg();
414 if (Reg == 0) continue;
415
416 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000417 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000418 if (MO.isUse()) {
419 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000420 // and we can freely move its uses. Alternatively, if it's allocatable,
421 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000422 if (!RegInfo->def_empty(Reg))
423 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000424 if (AllocatableSet.test(Reg))
425 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000426 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000427 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
428 unsigned AliasReg = *Alias;
429 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000430 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000431 if (AllocatableSet.test(AliasReg))
432 return false;
433 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000434 // Otherwise it's safe to move.
435 continue;
436 } else if (!MO.isDead()) {
437 // A def that isn't dead. We can't move it.
438 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000439 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
440 // If the reg is live into the loop, we can't hoist an instruction
441 // which would clobber it.
442 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000443 }
444 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000445
446 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000447 continue;
448
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000449 assert(RegInfo->getVRegDef(Reg) &&
450 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000451
452 // If the loop contains the definition of an operand, then the instruction
453 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000454 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000455 return false;
456 }
457
458 // If we got this far, the instruction is loop invariant!
459 return true;
460}
461
Evan Chengaf6949d2009-02-05 08:45:46 +0000462
463/// HasPHIUses - Return true if the specified register has any PHI use.
464static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000465 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
466 UE = RegInfo->use_end(); UI != UE; ++UI) {
467 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000468 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000469 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000470 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000471 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000472}
473
Evan Cheng87b75ba2009-11-20 19:55:37 +0000474/// isLoadFromConstantMemory - Return true if the given instruction is a
475/// load from constant memory. Machine LICM will hoist these even if they are
476/// not re-materializable.
477bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
478 if (!MI->getDesc().mayLoad()) return false;
479 if (!MI->hasOneMemOperand()) return false;
480 MachineMemOperand *MMO = *MI->memoperands_begin();
481 if (MMO->isVolatile()) return false;
482 if (!MMO->getValue()) return false;
483 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
484 if (PSV) {
485 MachineFunction &MF = *MI->getParent()->getParent();
486 return PSV->isConstant(MF.getFrameInfo());
487 } else {
488 return AA->pointsToConstantMemory(MMO->getValue());
489 }
490}
491
Evan Cheng45e94d62009-02-04 09:19:56 +0000492/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
493/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000494bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Chris Lattner518bb532010-02-09 19:54:29 +0000495 if (MI.isImplicitDef())
Evan Chengefc78392009-02-27 00:02:22 +0000496 return false;
497
Evan Cheng45e94d62009-02-04 09:19:56 +0000498 // FIXME: For now, only hoist re-materilizable instructions. LICM will
499 // increase register pressure. We want to make sure it doesn't increase
500 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000501 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
502 // these tend to help performance in low register pressure situation. The
503 // trade off is it may cause spill in high pressure situation. It will end up
504 // adding a store in the loop preheader. But the reload is no more expensive.
505 // The side benefit is these loads are frequently CSE'ed.
506 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000507 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000508 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000509 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000510
Evan Chengaf6949d2009-02-05 08:45:46 +0000511 // If result(s) of this instruction is used by PHIs, then don't hoist it.
512 // The presence of joins makes it difficult for current register allocator
513 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000514 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
515 const MachineOperand &MO = MI.getOperand(i);
516 if (!MO.isReg() || !MO.isDef())
517 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000518 if (HasPHIUses(MO.getReg(), RegInfo))
519 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000520 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000521
522 return true;
523}
524
Dan Gohman5c952302009-10-29 17:47:20 +0000525MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
526 // If not, we may be able to unfold a load and hoist that.
527 // First test whether the instruction is loading from an amenable
528 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000529 if (!isLoadFromConstantMemory(MI))
530 return 0;
531
Dan Gohman5c952302009-10-29 17:47:20 +0000532 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000533 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000534 unsigned NewOpc =
535 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
536 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000537 /*UnfoldStore=*/false,
538 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000539 if (NewOpc == 0) return 0;
540 const TargetInstrDesc &TID = TII->get(NewOpc);
541 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000542 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000543 // Ok, we're unfolding. Create a temporary register and do the unfold.
544 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000545
546 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000547 SmallVector<MachineInstr *, 2> NewMIs;
548 bool Success =
549 TII->unfoldMemoryOperand(MF, MI, Reg,
550 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
551 NewMIs);
552 (void)Success;
553 assert(Success &&
554 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
555 "succeeded!");
556 assert(NewMIs.size() == 2 &&
557 "Unfolded a load into multiple instructions!");
558 MachineBasicBlock *MBB = MI->getParent();
559 MBB->insert(MI, NewMIs[0]);
560 MBB->insert(MI, NewMIs[1]);
561 // If unfolding produced a load that wasn't loop-invariant or profitable to
562 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000563 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000564 NewMIs[0]->eraseFromParent();
565 NewMIs[1]->eraseFromParent();
566 return 0;
567 }
568 // Otherwise we successfully unfolded a load that we can hoist.
569 MI->eraseFromParent();
570 return NewMIs[0];
571}
572
Evan Cheng777c6b72009-11-03 21:40:02 +0000573void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
574 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
575 const MachineInstr *MI = &*I;
576 // FIXME: For now, only hoist re-materilizable instructions. LICM will
577 // increase register pressure. We want to make sure it doesn't increase
578 // spilling.
579 if (TII->isTriviallyReMaterializable(MI, AA)) {
580 unsigned Opcode = MI->getOpcode();
581 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
582 CI = CSEMap.find(Opcode);
583 if (CI != CSEMap.end())
584 CI->second.push_back(MI);
585 else {
586 std::vector<const MachineInstr*> CSEMIs;
587 CSEMIs.push_back(MI);
588 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
589 }
590 }
591 }
592}
593
Evan Cheng78e5c112009-11-07 03:52:02 +0000594const MachineInstr*
595MachineLICM::LookForDuplicate(const MachineInstr *MI,
596 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000597 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
598 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000599 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000600 return PrevMI;
601 }
602 return 0;
603}
604
605bool MachineLICM::EliminateCSE(MachineInstr *MI,
606 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000607 if (CI == CSEMap.end())
608 return false;
609
610 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000611 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000612
613 // Replace virtual registers defined by MI by their counterparts defined
614 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000615 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
616 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000617
618 // Physical registers may not differ here.
619 assert((!MO.isReg() || MO.getReg() == 0 ||
620 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
621 MO.getReg() == Dup->getOperand(i).getReg()) &&
622 "Instructions with different phys regs are not identical!");
623
624 if (MO.isReg() && MO.isDef() &&
625 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
Evan Cheng78e5c112009-11-07 03:52:02 +0000626 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Evan Cheng9fb744e2009-11-05 00:51:13 +0000627 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000628 MI->eraseFromParent();
629 ++NumCSEed;
630 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000631 }
632 return false;
633}
634
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000635/// Hoist - When an instruction is found to use only loop invariant operands
636/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000637///
Dan Gohman589f1f52009-10-28 03:21:57 +0000638void MachineLICM::Hoist(MachineInstr *MI) {
639 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +0000640 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000641 // If not, try unfolding a hoistable load.
642 MI = ExtractHoistableLoad(MI);
643 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000644 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000645
Dan Gohmanc475c362009-01-15 22:01:38 +0000646 // Now move the instructions to the predecessor, inserting it before any
647 // terminator instructions.
648 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000649 dbgs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000650 if (CurPreheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000651 dbgs() << " to MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000652 << CurPreheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000653 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000654 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000655 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +0000656 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000657 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000658
Evan Cheng777c6b72009-11-03 21:40:02 +0000659 // If this is the first instruction being hoisted to the preheader,
660 // initialize the CSE map with potential common expressions.
661 InitCSEMap(CurPreheader);
662
Evan Chengaf6949d2009-02-05 08:45:46 +0000663 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000664 unsigned Opcode = MI->getOpcode();
665 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
666 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000667 if (!EliminateCSE(MI, CI)) {
668 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000669 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
670
Evan Chengaf6949d2009-02-05 08:45:46 +0000671 // Add to the CSE map.
672 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000673 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000674 else {
675 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000676 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000677 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000678 }
679 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000680
Dan Gohmanc475c362009-01-15 22:01:38 +0000681 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000682 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000683}