blob: db67c714c36e2cb93a923a63dd5fcc183057899c [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.
Evan Cheng4038f9c2010-04-08 01:03:47 +000060 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000061 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.
65 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000066 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000067
Evan Chengd94671a2010-04-07 00:41:17 +000068 BitVector AllocatableSet;
69
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;
Evan Chengd94671a2010-04-07 00:41:17 +000072
Bill Wendling0f940c92007-12-07 21:42:31 +000073 public:
74 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000075 MachineLICM() :
76 MachineFunctionPass(&ID), PreRegAlloc(true) {}
77
78 explicit MachineLICM(bool PreRA) :
79 MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000080
81 virtual bool runOnMachineFunction(MachineFunction &MF);
82
Dan Gohman72241702008-12-18 01:37:56 +000083 const char *getPassName() const { return "Machine Instruction LICM"; }
84
Bill Wendling074223a2008-03-10 08:13:01 +000085 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000086 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.setPreservesCFG();
88 AU.addRequired<MachineLoopInfo>();
89 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000090 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000091 AU.addPreserved<MachineLoopInfo>();
92 AU.addPreserved<MachineDominatorTree>();
93 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000094 }
Evan Chengaf6949d2009-02-05 08:45:46 +000095
96 virtual void releaseMemory() {
97 CSEMap.clear();
98 }
99
Bill Wendling0f940c92007-12-07 21:42:31 +0000100 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000101 /// CandidateInfo - Keep track of information about hoisting candidates.
102 struct CandidateInfo {
103 MachineInstr *MI;
104 int FI;
105 unsigned Def;
106 CandidateInfo(MachineInstr *mi, int fi, unsigned def)
107 : MI(mi), FI(fi), Def(def) {}
108 };
109
110 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
111 /// invariants out to the preheader.
112 void HoistRegionPostRA(MachineDomTreeNode *N);
113
114 /// HoistPostRA - When an instruction is found to only use loop invariant
115 /// operands that is safe to hoist, this instruction is called to do the
116 /// dirty work.
117 void HoistPostRA(MachineInstr *MI, unsigned Def);
118
119 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
120 /// gather register def and frame object update information.
121 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
122 SmallSet<int, 32> &StoredFIs,
123 SmallVector<CandidateInfo, 32> &Candidates);
124
125 /// AddToLiveIns - Add 'Reg' to the livein sets of BBs in the backedge path
126 /// from MBB to LoopHeader (inclusive).
127 void AddToLiveIns(unsigned Reg,
128 MachineBasicBlock *MBB, MachineBasicBlock *LoopHeader);
129
Bill Wendling041b3f82007-12-08 23:58:46 +0000130 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000131 /// invariant. I.e., all virtual register operands are defined outside of
132 /// the loop, physical registers aren't accessed (explicitly or implicitly),
133 /// and the instruction is hoistable.
134 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000135 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000136
Evan Cheng45e94d62009-02-04 09:19:56 +0000137 /// IsProfitableToHoist - Return true if it is potentially profitable to
138 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000139 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000140
Bill Wendling0f940c92007-12-07 21:42:31 +0000141 /// HoistRegion - Walk the specified region of the CFG (defined by all
142 /// blocks dominated by the specified block, and that are in the current
143 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
144 /// visit definitions before uses, allowing us to hoist a loop body in one
145 /// pass without iteration.
146 ///
147 void HoistRegion(MachineDomTreeNode *N);
148
Evan Cheng87b75ba2009-11-20 19:55:37 +0000149 /// isLoadFromConstantMemory - Return true if the given instruction is a
150 /// load from constant memory.
151 bool isLoadFromConstantMemory(MachineInstr *MI);
152
Dan Gohman5c952302009-10-29 17:47:20 +0000153 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
154 /// the load itself could be hoisted. Return the unfolded and hoistable
155 /// load, or null if the load couldn't be unfolded or if it wouldn't
156 /// be hoistable.
157 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
158
Evan Cheng78e5c112009-11-07 03:52:02 +0000159 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
160 /// duplicate of MI. Return this instruction if it's found.
161 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
162 std::vector<const MachineInstr*> &PrevMIs);
163
Evan Cheng9fb744e2009-11-05 00:51:13 +0000164 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
165 /// the preheader that compute the same value. If it's found, do a RAU on
166 /// with the definition of the existing instruction rather than hoisting
167 /// the instruction to the preheader.
168 bool EliminateCSE(MachineInstr *MI,
169 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
170
Bill Wendling0f940c92007-12-07 21:42:31 +0000171 /// Hoist - When an instruction is found to only use loop invariant operands
172 /// that is safe to hoist, this instruction is called to do the dirty work.
173 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000174 void Hoist(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000175
176 /// InitCSEMap - Initialize the CSE map with instructions that are in the
177 /// current loop preheader that may become duplicates of instructions that
178 /// are hoisted out of the loop.
179 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000180 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000181} // end anonymous namespace
182
Dan Gohman844731a2008-05-13 00:00:25 +0000183char MachineLICM::ID = 0;
184static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000185X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000186
Evan Chengd94671a2010-04-07 00:41:17 +0000187FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
188 return new MachineLICM(PreRegAlloc);
189}
Bill Wendling0f940c92007-12-07 21:42:31 +0000190
Dan Gohmanc475c362009-01-15 22:01:38 +0000191/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
192/// loop that has a preheader.
193static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
194 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
195 if (L->getLoopPreheader())
196 return false;
197 return true;
198}
199
Bill Wendling0f940c92007-12-07 21:42:31 +0000200bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000201 if (PreRegAlloc)
202 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
203 else
204 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000205
Evan Cheng4038f9c2010-04-08 01:03:47 +0000206 Changed = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000207 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000208 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000209 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000210 MFI = MF.getFrameInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000211 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000212 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000213
214 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000215 MLI = &getAnalysis<MachineLoopInfo>();
216 DT = &getAnalysis<MachineDominatorTree>();
217 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000218
Evan Cheng4038f9c2010-04-08 01:03:47 +0000219 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I){
Bill Wendlinga17ad592007-12-11 22:22:22 +0000220 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000221
Evan Cheng4038f9c2010-04-08 01:03:47 +0000222 // If this is done before regalloc, only visit outer-most preheader-sporting
223 // loops.
224 if (PreRegAlloc && !LoopIsOuterMostWithPreheader(CurLoop))
Dan Gohmanc475c362009-01-15 22:01:38 +0000225 continue;
226
227 // Determine the block to which to hoist instructions. If we can't find a
228 // suitable loop preheader, we can't do any hoisting.
229 //
230 // FIXME: We are only hoisting if the basic block coming into this loop
231 // has only one successor. This isn't the case in general because we haven't
232 // broken critical edges or added preheaders.
233 CurPreheader = CurLoop->getLoopPreheader();
234 if (!CurPreheader)
235 continue;
236
Evan Cheng777c6b72009-11-03 21:40:02 +0000237 // CSEMap is initialized for loop header when the first instruction is
238 // being hoisted.
Evan Chengd94671a2010-04-07 00:41:17 +0000239 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
240 if (!PreRegAlloc)
241 HoistRegionPostRA(N);
242 else {
243 HoistRegion(N);
244 CSEMap.clear();
245 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000246 }
247
248 return Changed;
249}
250
Evan Cheng4038f9c2010-04-08 01:03:47 +0000251/// InstructionStoresToFI - Return true if instruction stores to the
252/// specified frame.
253static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
254 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
255 oe = MI->memoperands_end(); o != oe; ++o) {
256 if (!(*o)->isStore() || !(*o)->getValue())
257 continue;
258 if (const FixedStackPseudoSourceValue *Value =
259 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
260 if (Value->getFrameIndex() == FI)
261 return true;
262 }
263 }
264 return false;
265}
266
267/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
268/// gather register def and frame object update information.
269void MachineLICM::ProcessMI(MachineInstr *MI,
270 unsigned *PhysRegDefs,
271 SmallSet<int, 32> &StoredFIs,
272 SmallVector<CandidateInfo, 32> &Candidates) {
273 bool RuledOut = false;
274 unsigned Def = 0;
275 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
276 const MachineOperand &MO = MI->getOperand(i);
277 if (MO.isFI()) {
278 // Remember if the instruction stores to the frame index.
279 int FI = MO.getIndex();
280 if (!StoredFIs.count(FI) &&
281 MFI->isSpillSlotObjectIndex(FI) &&
282 InstructionStoresToFI(MI, FI))
283 StoredFIs.insert(FI);
284 continue;
285 }
286
287 if (!MO.isReg())
288 continue;
289 unsigned Reg = MO.getReg();
290 if (!Reg)
291 continue;
292 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
293 "Not expecting virtual register!");
294
295 if (!MO.isDef())
296 continue;
297
298 if (MO.isImplicit()) {
299 ++PhysRegDefs[Reg];
300 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
301 ++PhysRegDefs[*AS];
302 if (!MO.isDead())
303 // Non-dead implicit def? This cannot be hoisted.
304 RuledOut = true;
305 // No need to check if a dead implicit def is also defined by
306 // another instruction.
307 continue;
308 }
309
310 // FIXME: For now, avoid instructions with multiple defs, unless
311 // it's a dead implicit def.
312 if (Def)
313 RuledOut = true;
314 else
315 Def = Reg;
316
317 // If we have already seen another instruction that defines the same
318 // register, then this is not safe.
319 if (++PhysRegDefs[Reg] > 1)
320 // MI defined register is seen defined by another instruction in
321 // the loop, it cannot be a LICM candidate.
322 RuledOut = true;
323 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
324 if (++PhysRegDefs[*AS] > 1)
325 RuledOut = true;
326 }
327
328 // FIXME: Only consider reloads for now. We should be able to handle
329 // remats which does not have register operands.
330 if (Def && !RuledOut) {
331 int FI;
332 if (TII->isLoadFromStackSlot(MI, FI) &&
333 MFI->isSpillSlotObjectIndex(FI))
334 Candidates.push_back(CandidateInfo(MI, FI, Def));
335 }
336}
337
338/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
339/// invariants out to the preheader.
Evan Chengd94671a2010-04-07 00:41:17 +0000340void MachineLICM::HoistRegionPostRA(MachineDomTreeNode *N) {
341 assert(N != 0 && "Null dominator tree node?");
342
343 unsigned NumRegs = TRI->getNumRegs();
344 unsigned *PhysRegDefs = new unsigned[NumRegs];
345 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
346
Evan Cheng4038f9c2010-04-08 01:03:47 +0000347 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000348 SmallSet<int, 32> StoredFIs;
349
350 // Walk the entire region, count number of defs for each register, and
351 // return potential LICM candidates.
352 SmallVector<MachineDomTreeNode*, 8> WorkList;
353 WorkList.push_back(N);
354 do {
355 N = WorkList.pop_back_val();
356 MachineBasicBlock *BB = N->getBlock();
357
Evan Cheng4038f9c2010-04-08 01:03:47 +0000358 if (!CurLoop->contains(MLI->getLoopFor(BB)))
Evan Chengd94671a2010-04-07 00:41:17 +0000359 continue;
360 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000361 // FIXME: That means a reload that're reused in successor block(s) will not
362 // be LICM'ed.
Evan Chengd94671a2010-04-07 00:41:17 +0000363 for (MachineBasicBlock::const_livein_iterator I = BB->livein_begin(),
364 E = BB->livein_end(); I != E; ++I) {
365 unsigned Reg = *I;
366 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000367 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
368 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000369 }
370
371 for (MachineBasicBlock::iterator
372 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000373 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000374 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000375 }
376
377 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
378 for (unsigned I = 0, E = Children.size(); I != E; ++I)
379 WorkList.push_back(Children[I]);
380 } while (!WorkList.empty());
381
382 // Now evaluate whether the potential candidates qualify.
383 // 1. Check if the candidate defined register is defined by another
384 // instruction in the loop.
385 // 2. If the candidate is a load from stack slot (always true for now),
386 // check if the slot is stored anywhere in the loop.
387 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng4038f9c2010-04-08 01:03:47 +0000388 if (StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000389 continue;
390
Evan Cheng4038f9c2010-04-08 01:03:47 +0000391 if (PhysRegDefs[Candidates[i].Def] == 1)
392 HoistPostRA(Candidates[i].MI, Candidates[i].Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000393 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000394
395 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000396}
397
Evan Cheng4038f9c2010-04-08 01:03:47 +0000398/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
399/// backedge path from MBB to LoopHeader.
400void MachineLICM::AddToLiveIns(unsigned Reg, MachineBasicBlock *MBB,
401 MachineBasicBlock *LoopHeader) {
402 SmallPtrSet<MachineBasicBlock*, 4> Visited;
403 SmallVector<MachineBasicBlock*, 4> WorkList;
404 WorkList.push_back(MBB);
405 do {
406 MBB = WorkList.pop_back_val();
407 if (!Visited.insert(MBB))
408 continue;
409 MBB->addLiveIn(Reg);
410 if (MBB == LoopHeader)
411 continue;
412 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
413 E = MBB->pred_end(); PI != E; ++PI)
414 WorkList.push_back(*PI);
415 } while (!WorkList.empty());
416}
417
418/// HoistPostRA - When an instruction is found to only use loop invariant
419/// operands that is safe to hoist, this instruction is called to do the
420/// dirty work.
421void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Evan Chengd94671a2010-04-07 00:41:17 +0000422 // Now move the instructions to the predecessor, inserting it before any
423 // terminator instructions.
424 DEBUG({
425 dbgs() << "Hoisting " << *MI;
426 if (CurPreheader->getBasicBlock())
427 dbgs() << " to MachineBasicBlock "
428 << CurPreheader->getName();
429 if (MI->getParent()->getBasicBlock())
430 dbgs() << " from MachineBasicBlock "
431 << MI->getParent()->getName();
432 dbgs() << "\n";
433 });
434
435 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000436 MachineBasicBlock *MBB = MI->getParent();
437 CurPreheader->splice(CurPreheader->getFirstTerminator(), MBB, MI);
438
439 // Add register to livein list to BBs in the path from loop header to original
440 // BB. Note, currently it's not necessary to worry about adding it to all BB's
441 // with uses. Reload that're reused in successor block(s) are not being
442 // hoisted.
443 AddToLiveIns(Def, MBB, CurLoop->getHeader());
Evan Chengd94671a2010-04-07 00:41:17 +0000444
445 ++NumPostRAHoisted;
446 Changed = true;
447}
448
Bill Wendling0f940c92007-12-07 21:42:31 +0000449/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
450/// dominated by the specified block, and that are in the current loop) in depth
451/// first order w.r.t the DominatorTree. This allows us to visit definitions
452/// before uses, allowing us to hoist a loop body in one pass without iteration.
453///
454void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
455 assert(N != 0 && "Null dominator tree node?");
456 MachineBasicBlock *BB = N->getBlock();
457
458 // If this subregion is not in the top level loop at all, exit.
459 if (!CurLoop->contains(BB)) return;
460
Dan Gohmanc475c362009-01-15 22:01:38 +0000461 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000462 MII = BB->begin(), E = BB->end(); MII != E; ) {
463 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000464 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000465 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000466 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000467
468 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Bill Wendling0f940c92007-12-07 21:42:31 +0000469 for (unsigned I = 0, E = Children.size(); I != E; ++I)
470 HoistRegion(Children[I]);
471}
472
Bill Wendling041b3f82007-12-08 23:58:46 +0000473/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000474/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000475/// loop, physical registers aren't accessed explicitly, and there are no side
476/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000477///
Bill Wendling041b3f82007-12-08 23:58:46 +0000478bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000479 const TargetInstrDesc &TID = I.getDesc();
480
481 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000482 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000483 TID.hasUnmodeledSideEffects())
484 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000485
Chris Lattnera22edc82008-01-10 23:08:24 +0000486 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000487 // Okay, this instruction does a load. As a refinement, we allow the target
488 // to decide whether the loaded value is actually a constant. If so, we can
489 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000490 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000491 // FIXME: we should be able to hoist loads with no other side effects if
492 // there are no other instructions which can change memory in this loop.
493 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000494 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000495 }
Bill Wendling074223a2008-03-10 08:13:01 +0000496
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000497 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000498 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
499 const MachineOperand &MO = I.getOperand(i);
500
Dan Gohmand735b802008-10-03 15:45:36 +0000501 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000502 continue;
503
Dan Gohmanc475c362009-01-15 22:01:38 +0000504 unsigned Reg = MO.getReg();
505 if (Reg == 0) continue;
506
507 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000508 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000509 if (MO.isUse()) {
510 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000511 // and we can freely move its uses. Alternatively, if it's allocatable,
512 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000513 if (!RegInfo->def_empty(Reg))
514 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000515 if (AllocatableSet.test(Reg))
516 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000517 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000518 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
519 unsigned AliasReg = *Alias;
520 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000521 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000522 if (AllocatableSet.test(AliasReg))
523 return false;
524 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000525 // Otherwise it's safe to move.
526 continue;
527 } else if (!MO.isDead()) {
528 // A def that isn't dead. We can't move it.
529 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000530 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
531 // If the reg is live into the loop, we can't hoist an instruction
532 // which would clobber it.
533 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000534 }
535 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000536
537 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000538 continue;
539
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000540 assert(RegInfo->getVRegDef(Reg) &&
541 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000542
543 // If the loop contains the definition of an operand, then the instruction
544 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000545 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000546 return false;
547 }
548
549 // If we got this far, the instruction is loop invariant!
550 return true;
551}
552
Evan Chengaf6949d2009-02-05 08:45:46 +0000553
554/// HasPHIUses - Return true if the specified register has any PHI use.
555static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000556 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
557 UE = RegInfo->use_end(); UI != UE; ++UI) {
558 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000559 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000560 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000561 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000562 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000563}
564
Evan Cheng87b75ba2009-11-20 19:55:37 +0000565/// isLoadFromConstantMemory - Return true if the given instruction is a
566/// load from constant memory. Machine LICM will hoist these even if they are
567/// not re-materializable.
568bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
569 if (!MI->getDesc().mayLoad()) return false;
570 if (!MI->hasOneMemOperand()) return false;
571 MachineMemOperand *MMO = *MI->memoperands_begin();
572 if (MMO->isVolatile()) return false;
573 if (!MMO->getValue()) return false;
574 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
575 if (PSV) {
576 MachineFunction &MF = *MI->getParent()->getParent();
577 return PSV->isConstant(MF.getFrameInfo());
578 } else {
579 return AA->pointsToConstantMemory(MMO->getValue());
580 }
581}
582
Evan Cheng45e94d62009-02-04 09:19:56 +0000583/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
584/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000585bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Chris Lattner518bb532010-02-09 19:54:29 +0000586 if (MI.isImplicitDef())
Evan Chengefc78392009-02-27 00:02:22 +0000587 return false;
588
Evan Cheng45e94d62009-02-04 09:19:56 +0000589 // FIXME: For now, only hoist re-materilizable instructions. LICM will
590 // increase register pressure. We want to make sure it doesn't increase
591 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000592 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
593 // these tend to help performance in low register pressure situation. The
594 // trade off is it may cause spill in high pressure situation. It will end up
595 // adding a store in the loop preheader. But the reload is no more expensive.
596 // The side benefit is these loads are frequently CSE'ed.
597 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000598 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000599 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000600 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000601
Evan Chengaf6949d2009-02-05 08:45:46 +0000602 // If result(s) of this instruction is used by PHIs, then don't hoist it.
603 // The presence of joins makes it difficult for current register allocator
604 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000605 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
606 const MachineOperand &MO = MI.getOperand(i);
607 if (!MO.isReg() || !MO.isDef())
608 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000609 if (HasPHIUses(MO.getReg(), RegInfo))
610 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000611 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000612
613 return true;
614}
615
Dan Gohman5c952302009-10-29 17:47:20 +0000616MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
617 // If not, we may be able to unfold a load and hoist that.
618 // First test whether the instruction is loading from an amenable
619 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000620 if (!isLoadFromConstantMemory(MI))
621 return 0;
622
Dan Gohman5c952302009-10-29 17:47:20 +0000623 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000624 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000625 unsigned NewOpc =
626 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
627 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000628 /*UnfoldStore=*/false,
629 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000630 if (NewOpc == 0) return 0;
631 const TargetInstrDesc &TID = TII->get(NewOpc);
632 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000633 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000634 // Ok, we're unfolding. Create a temporary register and do the unfold.
635 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000636
637 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000638 SmallVector<MachineInstr *, 2> NewMIs;
639 bool Success =
640 TII->unfoldMemoryOperand(MF, MI, Reg,
641 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
642 NewMIs);
643 (void)Success;
644 assert(Success &&
645 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
646 "succeeded!");
647 assert(NewMIs.size() == 2 &&
648 "Unfolded a load into multiple instructions!");
649 MachineBasicBlock *MBB = MI->getParent();
650 MBB->insert(MI, NewMIs[0]);
651 MBB->insert(MI, NewMIs[1]);
652 // If unfolding produced a load that wasn't loop-invariant or profitable to
653 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000654 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000655 NewMIs[0]->eraseFromParent();
656 NewMIs[1]->eraseFromParent();
657 return 0;
658 }
659 // Otherwise we successfully unfolded a load that we can hoist.
660 MI->eraseFromParent();
661 return NewMIs[0];
662}
663
Evan Cheng777c6b72009-11-03 21:40:02 +0000664void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
665 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
666 const MachineInstr *MI = &*I;
667 // FIXME: For now, only hoist re-materilizable instructions. LICM will
668 // increase register pressure. We want to make sure it doesn't increase
669 // spilling.
670 if (TII->isTriviallyReMaterializable(MI, AA)) {
671 unsigned Opcode = MI->getOpcode();
672 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
673 CI = CSEMap.find(Opcode);
674 if (CI != CSEMap.end())
675 CI->second.push_back(MI);
676 else {
677 std::vector<const MachineInstr*> CSEMIs;
678 CSEMIs.push_back(MI);
679 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
680 }
681 }
682 }
683}
684
Evan Cheng78e5c112009-11-07 03:52:02 +0000685const MachineInstr*
686MachineLICM::LookForDuplicate(const MachineInstr *MI,
687 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000688 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
689 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000690 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000691 return PrevMI;
692 }
693 return 0;
694}
695
696bool MachineLICM::EliminateCSE(MachineInstr *MI,
697 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000698 if (CI == CSEMap.end())
699 return false;
700
701 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000702 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000703
704 // Replace virtual registers defined by MI by their counterparts defined
705 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000706 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
707 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000708
709 // Physical registers may not differ here.
710 assert((!MO.isReg() || MO.getReg() == 0 ||
711 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
712 MO.getReg() == Dup->getOperand(i).getReg()) &&
713 "Instructions with different phys regs are not identical!");
714
715 if (MO.isReg() && MO.isDef() &&
716 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
Evan Cheng78e5c112009-11-07 03:52:02 +0000717 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Evan Cheng9fb744e2009-11-05 00:51:13 +0000718 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000719 MI->eraseFromParent();
720 ++NumCSEed;
721 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000722 }
723 return false;
724}
725
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000726/// Hoist - When an instruction is found to use only loop invariant operands
727/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000728///
Dan Gohman589f1f52009-10-28 03:21:57 +0000729void MachineLICM::Hoist(MachineInstr *MI) {
730 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +0000731 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000732 // If not, try unfolding a hoistable load.
733 MI = ExtractHoistableLoad(MI);
734 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000735 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000736
Dan Gohmanc475c362009-01-15 22:01:38 +0000737 // Now move the instructions to the predecessor, inserting it before any
738 // terminator instructions.
739 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000740 dbgs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000741 if (CurPreheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000742 dbgs() << " to MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000743 << CurPreheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000744 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000745 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000746 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +0000747 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000748 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000749
Evan Cheng777c6b72009-11-03 21:40:02 +0000750 // If this is the first instruction being hoisted to the preheader,
751 // initialize the CSE map with potential common expressions.
752 InitCSEMap(CurPreheader);
753
Evan Chengaf6949d2009-02-05 08:45:46 +0000754 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000755 unsigned Opcode = MI->getOpcode();
756 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
757 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000758 if (!EliminateCSE(MI, CI)) {
759 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000760 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
761
Evan Chengaf6949d2009-02-05 08:45:46 +0000762 // Add to the CSE map.
763 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000764 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000765 else {
766 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000767 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000768 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000769 }
770 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000771
Dan Gohmanc475c362009-01-15 22:01:38 +0000772 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000773 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000774}