blob: 607e8f15bc0f89bd2e029a17e0226202ae43817b [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"
Evan Cheng0e673912010-10-14 01:16:09 +000031#include "llvm/Target/TargetLowering.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000032#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000033#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng0e673912010-10-14 01:16:09 +000034#include "llvm/Target/TargetInstrItineraries.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000035#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000036#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000037#include "llvm/ADT/DenseMap.h"
Evan Chengd94671a2010-04-07 00:41:17 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattnerac695822008-01-04 06:41:45 +000039#include "llvm/ADT/Statistic.h"
Evan Cheng0e673912010-10-14 01:16:09 +000040#include "llvm/Support/CommandLine.h"
Chris Lattnerac695822008-01-04 06:41:45 +000041#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000042#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000043
44using namespace llvm;
45
Evan Cheng0e673912010-10-14 01:16:09 +000046static cl::opt<bool>
47TrackRegPressure("rp-aware-machine-licm",
48 cl::desc("Register pressure aware machine LICM"),
49 cl::init(false), cl::Hidden);
50
Evan Cheng03a9fdf2010-10-16 02:20:26 +000051STATISTIC(NumHoisted,
52 "Number of machine instructions hoisted out of loops");
53STATISTIC(NumLowRP,
54 "Number of instructions hoisted in low reg pressure situation");
55STATISTIC(NumHighLatency,
56 "Number of high latency instructions hoisted");
57STATISTIC(NumCSEed,
58 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000059STATISTIC(NumPostRAHoisted,
60 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000061
Bill Wendling0f940c92007-12-07 21:42:31 +000062namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000063 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000064 bool PreRegAlloc;
65
Bill Wendling9258cd32008-01-02 19:32:43 +000066 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000067 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000068 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000069 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000070 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000071 MachineRegisterInfo *MRI;
72 const InstrItineraryData *InstrItins;
Bill Wendling12ebf142007-12-11 19:40:06 +000073
Bill Wendling0f940c92007-12-07 21:42:31 +000074 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000075 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000076 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000077 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000078
Bill Wendling0f940c92007-12-07 21:42:31 +000079 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000080 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000081 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000082 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000083 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000084
Evan Chengd94671a2010-04-07 00:41:17 +000085 BitVector AllocatableSet;
86
Evan Cheng0e673912010-10-14 01:16:09 +000087 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000088 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000089 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000090
91 // Register pressure "limit" per register class. If the pressure
92 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000093 SmallVector<unsigned, 8> RegLimit;
94
Evan Cheng03a9fdf2010-10-16 02:20:26 +000095 // Register pressure on path leading from loop preheader to current BB.
96 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
97
Dale Johannesenc46a5f22010-07-29 17:45:24 +000098 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000099 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +0000100
Bill Wendling0f940c92007-12-07 21:42:31 +0000101 public:
102 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +0000103 MachineLICM() :
Owen Anderson90c579d2010-08-06 18:33:48 +0000104 MachineFunctionPass(ID), PreRegAlloc(true) {}
Evan Chengd94671a2010-04-07 00:41:17 +0000105
106 explicit MachineLICM(bool PreRA) :
Owen Anderson90c579d2010-08-06 18:33:48 +0000107 MachineFunctionPass(ID), PreRegAlloc(PreRA) {}
Bill Wendling0f940c92007-12-07 21:42:31 +0000108
109 virtual bool runOnMachineFunction(MachineFunction &MF);
110
Dan Gohman72241702008-12-18 01:37:56 +0000111 const char *getPassName() const { return "Machine Instruction LICM"; }
112
Bill Wendling0f940c92007-12-07 21:42:31 +0000113 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
114 AU.setPreservesCFG();
115 AU.addRequired<MachineLoopInfo>();
116 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000117 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000118 AU.addPreserved<MachineLoopInfo>();
119 AU.addPreserved<MachineDominatorTree>();
120 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000121 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000122
123 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000124 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000125 RegPressure.clear();
126 RegLimit.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000127 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
128 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
129 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000130 CSEMap.clear();
131 }
132
Bill Wendling0f940c92007-12-07 21:42:31 +0000133 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000134 /// CandidateInfo - Keep track of information about hoisting candidates.
135 struct CandidateInfo {
136 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000137 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000138 int FI;
139 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
140 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000141 };
142
143 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
144 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000145 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000146
147 /// HoistPostRA - When an instruction is found to only use loop invariant
148 /// operands that is safe to hoist, this instruction is called to do the
149 /// dirty work.
150 void HoistPostRA(MachineInstr *MI, unsigned Def);
151
152 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
153 /// gather register def and frame object update information.
154 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
155 SmallSet<int, 32> &StoredFIs,
156 SmallVector<CandidateInfo, 32> &Candidates);
157
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000158 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
159 /// current loop.
160 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000161
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000162 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000163 /// candidate for LICM. e.g. If the instruction is a call, then it's
164 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000165 bool IsLICMCandidate(MachineInstr &I);
166
Bill Wendling041b3f82007-12-08 23:58:46 +0000167 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000168 /// invariant. I.e., all virtual register operands are defined outside of
169 /// the loop, physical registers aren't accessed (explicitly or implicitly),
170 /// and the instruction is hoistable.
171 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000172 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000173
Evan Cheng0e673912010-10-14 01:16:09 +0000174 /// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
175 /// and an use in the current loop.
176 int ComputeOperandLatency(MachineInstr &MI, unsigned DefIdx, unsigned Reg);
177
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000178 /// IncreaseHighRegPressure - Visit BBs from preheader to current BB, check
179 /// if hoisting an instruction of the given cost matrix can cause high
180 /// register pressure.
181 bool IncreaseHighRegPressure(DenseMap<unsigned, int> &Cost);
182
Evan Cheng45e94d62009-02-04 09:19:56 +0000183 /// IsProfitableToHoist - Return true if it is potentially profitable to
184 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000185 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000186
Bill Wendling0f940c92007-12-07 21:42:31 +0000187 /// HoistRegion - Walk the specified region of the CFG (defined by all
188 /// blocks dominated by the specified block, and that are in the current
189 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
190 /// visit definitions before uses, allowing us to hoist a loop body in one
191 /// pass without iteration.
192 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000193 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000194
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000195 /// InitRegPressure - Find all virtual register references that are liveout
196 /// of the preheader to initialize the starting "register pressure". Note
197 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000198 void InitRegPressure(MachineBasicBlock *BB);
199
200 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
201 /// register pressure before and after executing a specifi instruction.
202 void UpdateRegPressureBefore(const MachineInstr *MI);
203 void UpdateRegPressureAfter(const MachineInstr *MI);
204
Evan Cheng87b75ba2009-11-20 19:55:37 +0000205 /// isLoadFromConstantMemory - Return true if the given instruction is a
206 /// load from constant memory.
207 bool isLoadFromConstantMemory(MachineInstr *MI);
208
Dan Gohman5c952302009-10-29 17:47:20 +0000209 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
210 /// the load itself could be hoisted. Return the unfolded and hoistable
211 /// load, or null if the load couldn't be unfolded or if it wouldn't
212 /// be hoistable.
213 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
214
Evan Cheng78e5c112009-11-07 03:52:02 +0000215 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
216 /// duplicate of MI. Return this instruction if it's found.
217 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
218 std::vector<const MachineInstr*> &PrevMIs);
219
Evan Cheng9fb744e2009-11-05 00:51:13 +0000220 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
221 /// the preheader that compute the same value. If it's found, do a RAU on
222 /// with the definition of the existing instruction rather than hoisting
223 /// the instruction to the preheader.
224 bool EliminateCSE(MachineInstr *MI,
225 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
226
Bill Wendling0f940c92007-12-07 21:42:31 +0000227 /// Hoist - When an instruction is found to only use loop invariant operands
228 /// that is safe to hoist, this instruction is called to do the dirty work.
229 ///
Evan Cheng0e673912010-10-14 01:16:09 +0000230 void Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000231
232 /// InitCSEMap - Initialize the CSE map with instructions that are in the
233 /// current loop preheader that may become duplicates of instructions that
234 /// are hoisted out of the loop.
235 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000236
237 /// getCurPreheader - Get the preheader for the current loop, splitting
238 /// a critical edge if needed.
239 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000240 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000241} // end anonymous namespace
242
Dan Gohman844731a2008-05-13 00:00:25 +0000243char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000244INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
245 "Machine Loop Invariant Code Motion", false, false)
246INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
247INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
248INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
249INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000250 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000251
Evan Chengd94671a2010-04-07 00:41:17 +0000252FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
253 return new MachineLICM(PreRegAlloc);
254}
Bill Wendling0f940c92007-12-07 21:42:31 +0000255
Dan Gohman853d3fb2010-06-22 17:25:57 +0000256/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
257/// loop that has a unique predecessor.
258static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000259 // Check whether this loop even has a unique predecessor.
260 if (!CurLoop->getLoopPredecessor())
261 return false;
262 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000263 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000264 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000265 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000266 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000267 return true;
268}
269
Bill Wendling0f940c92007-12-07 21:42:31 +0000270bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000271 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000272 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000273 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000274 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
275 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000276
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000277 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000278 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000279 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000280 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000281 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000282 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000283 MRI = &MF.getRegInfo();
284 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000285 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000286
Evan Cheng0e673912010-10-14 01:16:09 +0000287 if (PreRegAlloc) {
288 // Estimate register pressure during pre-regalloc pass.
289 unsigned NumRC = TRI->getNumRegClasses();
290 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000291 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000292 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000293 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
294 E = TRI->regclass_end(); I != E; ++I)
295 RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
296 }
297
Bill Wendling0f940c92007-12-07 21:42:31 +0000298 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000299 MLI = &getAnalysis<MachineLoopInfo>();
300 DT = &getAnalysis<MachineDominatorTree>();
301 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000302
Dan Gohmanaa742602010-07-09 18:49:45 +0000303 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
304 while (!Worklist.empty()) {
305 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000306 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000307
Evan Cheng4038f9c2010-04-08 01:03:47 +0000308 // If this is done before regalloc, only visit outer-most preheader-sporting
309 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000310 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
311 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000312 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000313 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000314
Evan Chengd94671a2010-04-07 00:41:17 +0000315 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000316 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000317 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000318 // CSEMap is initialized for loop header when the first instruction is
319 // being hoisted.
320 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000321 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000322 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000323 CSEMap.clear();
324 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000325 }
326
327 return Changed;
328}
329
Evan Cheng4038f9c2010-04-08 01:03:47 +0000330/// InstructionStoresToFI - Return true if instruction stores to the
331/// specified frame.
332static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
333 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
334 oe = MI->memoperands_end(); o != oe; ++o) {
335 if (!(*o)->isStore() || !(*o)->getValue())
336 continue;
337 if (const FixedStackPseudoSourceValue *Value =
338 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
339 if (Value->getFrameIndex() == FI)
340 return true;
341 }
342 }
343 return false;
344}
345
346/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
347/// gather register def and frame object update information.
348void MachineLICM::ProcessMI(MachineInstr *MI,
349 unsigned *PhysRegDefs,
350 SmallSet<int, 32> &StoredFIs,
351 SmallVector<CandidateInfo, 32> &Candidates) {
352 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000353 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000354 unsigned Def = 0;
355 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
356 const MachineOperand &MO = MI->getOperand(i);
357 if (MO.isFI()) {
358 // Remember if the instruction stores to the frame index.
359 int FI = MO.getIndex();
360 if (!StoredFIs.count(FI) &&
361 MFI->isSpillSlotObjectIndex(FI) &&
362 InstructionStoresToFI(MI, FI))
363 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000364 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000365 continue;
366 }
367
368 if (!MO.isReg())
369 continue;
370 unsigned Reg = MO.getReg();
371 if (!Reg)
372 continue;
373 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
374 "Not expecting virtual register!");
375
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000376 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000377 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000378 // If it's using a non-loop-invariant register, then it's obviously not
379 // safe to hoist.
380 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000381 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000382 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000383
384 if (MO.isImplicit()) {
385 ++PhysRegDefs[Reg];
386 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
387 ++PhysRegDefs[*AS];
388 if (!MO.isDead())
389 // Non-dead implicit def? This cannot be hoisted.
390 RuledOut = true;
391 // No need to check if a dead implicit def is also defined by
392 // another instruction.
393 continue;
394 }
395
396 // FIXME: For now, avoid instructions with multiple defs, unless
397 // it's a dead implicit def.
398 if (Def)
399 RuledOut = true;
400 else
401 Def = Reg;
402
403 // If we have already seen another instruction that defines the same
404 // register, then this is not safe.
405 if (++PhysRegDefs[Reg] > 1)
406 // MI defined register is seen defined by another instruction in
407 // the loop, it cannot be a LICM candidate.
408 RuledOut = true;
409 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
410 if (++PhysRegDefs[*AS] > 1)
411 RuledOut = true;
412 }
413
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000414 // Only consider reloads for now and remats which do not have register
415 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000416 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000417 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000418 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000419 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
420 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000421 }
422}
423
424/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
425/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000426void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000427 unsigned NumRegs = TRI->getNumRegs();
428 unsigned *PhysRegDefs = new unsigned[NumRegs];
429 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
430
Evan Cheng4038f9c2010-04-08 01:03:47 +0000431 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000432 SmallSet<int, 32> StoredFIs;
433
434 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000435 // collect potential LICM candidates.
436 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
437 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
438 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000439 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000440 // FIXME: That means a reload that're reused in successor block(s) will not
441 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000442 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000443 E = BB->livein_end(); I != E; ++I) {
444 unsigned Reg = *I;
445 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000446 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
447 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000448 }
449
450 for (MachineBasicBlock::iterator
451 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000452 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000453 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000454 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000455 }
Evan Chengd94671a2010-04-07 00:41:17 +0000456
457 // Now evaluate whether the potential candidates qualify.
458 // 1. Check if the candidate defined register is defined by another
459 // instruction in the loop.
460 // 2. If the candidate is a load from stack slot (always true for now),
461 // check if the slot is stored anywhere in the loop.
462 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000463 if (Candidates[i].FI != INT_MIN &&
464 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000465 continue;
466
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000467 if (PhysRegDefs[Candidates[i].Def] == 1) {
468 bool Safe = true;
469 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000470 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
471 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000472 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000473 continue;
474 if (PhysRegDefs[MO.getReg()]) {
475 // If it's using a non-loop-invariant register, then it's obviously
476 // not safe to hoist.
477 Safe = false;
478 break;
479 }
480 }
481 if (Safe)
482 HoistPostRA(MI, Candidates[i].Def);
483 }
Evan Chengd94671a2010-04-07 00:41:17 +0000484 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000485
486 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000487}
488
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000489/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
490/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000491void MachineLICM::AddToLiveIns(unsigned Reg) {
492 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000493 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
494 MachineBasicBlock *BB = Blocks[i];
495 if (!BB->isLiveIn(Reg))
496 BB->addLiveIn(Reg);
497 for (MachineBasicBlock::iterator
498 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
499 MachineInstr *MI = &*MII;
500 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
501 MachineOperand &MO = MI->getOperand(i);
502 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
503 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
504 MO.setIsKill(false);
505 }
506 }
507 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000508}
509
510/// HoistPostRA - When an instruction is found to only use loop invariant
511/// operands that is safe to hoist, this instruction is called to do the
512/// dirty work.
513void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000514 MachineBasicBlock *Preheader = getCurPreheader();
515 if (!Preheader) return;
516
Evan Chengd94671a2010-04-07 00:41:17 +0000517 // Now move the instructions to the predecessor, inserting it before any
518 // terminator instructions.
519 DEBUG({
520 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000521 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000522 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000523 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000524 if (MI->getParent()->getBasicBlock())
525 dbgs() << " from MachineBasicBlock "
526 << MI->getParent()->getName();
527 dbgs() << "\n";
528 });
529
530 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000531 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000532 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000533
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000534 // Add register to livein list to all the BBs in the current loop since a
535 // loop invariant must be kept live throughout the whole loop. This is
536 // important to ensure later passes do not scavenge the def register.
537 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000538
539 ++NumPostRAHoisted;
540 Changed = true;
541}
542
Bill Wendling0f940c92007-12-07 21:42:31 +0000543/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
544/// dominated by the specified block, and that are in the current loop) in depth
545/// first order w.r.t the DominatorTree. This allows us to visit definitions
546/// before uses, allowing us to hoist a loop body in one pass without iteration.
547///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000548void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000549 assert(N != 0 && "Null dominator tree node?");
550 MachineBasicBlock *BB = N->getBlock();
551
552 // If this subregion is not in the top level loop at all, exit.
553 if (!CurLoop->contains(BB)) return;
554
Evan Cheng0e673912010-10-14 01:16:09 +0000555 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000556 if (!Preheader)
557 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000558
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000559 if (TrackRegPressure) {
560 if (IsHeader) {
561 // Compute registers which are liveout of preheader.
562 RegSeen.clear();
563 BackTrace.clear();
564 InitRegPressure(Preheader);
Evan Cheng0e673912010-10-14 01:16:09 +0000565 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000566
567 // Remember livein register pressure.
568 BackTrace.push_back(RegPressure);
569 }
570
571 for (MachineBasicBlock::iterator
572 MII = BB->begin(), E = BB->end(); MII != E; ) {
573 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
574 MachineInstr *MI = &*MII;
575
576 if (TrackRegPressure)
577 UpdateRegPressureBefore(MI);
578 Hoist(MI, Preheader);
579 if (TrackRegPressure)
580 UpdateRegPressureAfter(MI);
581
582 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000583 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000584
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000585 // Don't hoist things out of a large switch statement. This often causes
586 // code to be hoisted that wasn't going to be executed, and increases
587 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000588 if (BB->succ_size() < 25) {
589 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000590 for (unsigned I = 0, E = Children.size(); I != E; ++I)
591 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000592 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000593
594 if (TrackRegPressure)
595 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000596}
597
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000598/// InitRegPressure - Find all virtual register references that are liveout of
599/// the preheader to initialize the starting "register pressure". Note this
600/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000601void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000602 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000603
Evan Cheng0e673912010-10-14 01:16:09 +0000604 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
605 MII != E; ++MII) {
606 MachineInstr *MI = &*MII;
607 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
608 const MachineOperand &MO = MI->getOperand(i);
609 if (!MO.isReg() || MO.isImplicit())
610 continue;
611 unsigned Reg = MO.getReg();
612 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
613 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000614
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000615 bool isNew = !RegSeen.insert(Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000616 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
617 EVT VT = *RC->vt_begin();
618 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000619 if (MO.isDef())
620 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
621 else {
622 if (isNew && !MO.isKill())
623 // Haven't seen this, it must be a livein.
624 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
625 else if (!isNew && MO.isKill())
626 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
627 }
Evan Cheng0e673912010-10-14 01:16:09 +0000628 }
629 }
630}
631
632/// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
633/// register pressure before and after executing a specifi instruction.
634void MachineLICM::UpdateRegPressureBefore(const MachineInstr *MI) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000635 bool NoImpact = MI->isImplicitDef() || MI->isPHI();
Evan Cheng0e673912010-10-14 01:16:09 +0000636
637 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
638 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000639 if (!MO.isReg() || MO.isImplicit() || !MO.isUse())
Evan Cheng0e673912010-10-14 01:16:09 +0000640 continue;
641 unsigned Reg = MO.getReg();
642 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
643 continue;
644
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000645 bool isNew = !RegSeen.insert(Reg);
646 if (NoImpact)
647 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000648
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000649 if (!isNew && MO.isKill()) {
650 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
651 EVT VT = *RC->vt_begin();
652 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
653 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
654
655 assert(RCCost <= RegPressure[RCId]);
656 RegPressure[RCId] -= RCCost;
657 }
Evan Cheng0e673912010-10-14 01:16:09 +0000658 }
659}
660
661void MachineLICM::UpdateRegPressureAfter(const MachineInstr *MI) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000662 bool NoImpact = MI->isImplicitDef() || MI->isPHI();
Evan Cheng0e673912010-10-14 01:16:09 +0000663
664 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
665 const MachineOperand &MO = MI->getOperand(i);
666 if (!MO.isReg() || MO.isImplicit() || !MO.isDef())
667 continue;
668 unsigned Reg = MO.getReg();
669 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
670 continue;
671
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000672 RegSeen.insert(Reg);
673 if (NoImpact)
674 continue;
675
Evan Cheng0e673912010-10-14 01:16:09 +0000676 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
677 EVT VT = *RC->vt_begin();
678 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
679 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
680 RegPressure[RCId] += RCCost;
681 }
682}
683
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000684/// IsLICMCandidate - Returns true if the instruction may be a suitable
685/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
686/// not safe to hoist it.
687bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000688 // Check if it's safe to move the instruction.
689 bool DontMoveAcrossStore = true;
690 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000691 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000692
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000693 return true;
694}
695
696/// IsLoopInvariantInst - Returns true if the instruction is loop
697/// invariant. I.e., all virtual register operands are defined outside of the
698/// loop, physical registers aren't accessed explicitly, and there are no side
699/// effects that aren't captured by the operands or other flags.
700///
701bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
702 if (!IsLICMCandidate(I))
703 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000704
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000705 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000706 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
707 const MachineOperand &MO = I.getOperand(i);
708
Dan Gohmand735b802008-10-03 15:45:36 +0000709 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000710 continue;
711
Dan Gohmanc475c362009-01-15 22:01:38 +0000712 unsigned Reg = MO.getReg();
713 if (Reg == 0) continue;
714
715 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000716 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000717 if (MO.isUse()) {
718 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000719 // and we can freely move its uses. Alternatively, if it's allocatable,
720 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000721 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000722 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000723 if (AllocatableSet.test(Reg))
724 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000725 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000726 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
727 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000728 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000729 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000730 if (AllocatableSet.test(AliasReg))
731 return false;
732 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000733 // Otherwise it's safe to move.
734 continue;
735 } else if (!MO.isDead()) {
736 // A def that isn't dead. We can't move it.
737 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000738 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
739 // If the reg is live into the loop, we can't hoist an instruction
740 // which would clobber it.
741 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000742 }
743 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000744
745 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000746 continue;
747
Evan Cheng0e673912010-10-14 01:16:09 +0000748 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000749 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000750
751 // If the loop contains the definition of an operand, then the instruction
752 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000753 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000754 return false;
755 }
756
757 // If we got this far, the instruction is loop invariant!
758 return true;
759}
760
Evan Chengaf6949d2009-02-05 08:45:46 +0000761
762/// HasPHIUses - Return true if the specified register has any PHI use.
Evan Cheng0e673912010-10-14 01:16:09 +0000763static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
764 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
765 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000766 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000767 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000768 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000769 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000770 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000771}
772
Evan Cheng87b75ba2009-11-20 19:55:37 +0000773/// isLoadFromConstantMemory - Return true if the given instruction is a
774/// load from constant memory. Machine LICM will hoist these even if they are
775/// not re-materializable.
776bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
777 if (!MI->getDesc().mayLoad()) return false;
778 if (!MI->hasOneMemOperand()) return false;
779 MachineMemOperand *MMO = *MI->memoperands_begin();
780 if (MMO->isVolatile()) return false;
781 if (!MMO->getValue()) return false;
782 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
783 if (PSV) {
784 MachineFunction &MF = *MI->getParent()->getParent();
785 return PSV->isConstant(MF.getFrameInfo());
786 } else {
787 return AA->pointsToConstantMemory(MMO->getValue());
788 }
789}
790
Evan Cheng0e673912010-10-14 01:16:09 +0000791/// ComputeOperandLatency - Compute operand latency between a def of 'Reg'
792/// and an use in the current loop.
793int MachineLICM::ComputeOperandLatency(MachineInstr &MI,
794 unsigned DefIdx, unsigned Reg) {
795 if (MRI->use_nodbg_empty(Reg))
796 // No use? Return arbitrary large number!
797 return 300;
798
799 int Latency = -1;
800 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
801 E = MRI->use_nodbg_end(); I != E; ++I) {
802 MachineInstr *UseMI = &*I;
803 if (!CurLoop->contains(UseMI->getParent()))
804 continue;
805 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
806 const MachineOperand &MO = UseMI->getOperand(i);
807 if (!MO.isReg() || !MO.isUse())
808 continue;
809 unsigned MOReg = MO.getReg();
810 if (MOReg != Reg)
811 continue;
812
813 int UseCycle = TII->getOperandLatency(InstrItins, &MI, DefIdx, UseMI, i);
814 Latency = std::max(Latency, UseCycle);
815 }
816
817 if (Latency != -1)
818 break;
819 }
820
821 if (Latency == -1)
822 Latency = InstrItins->getOperandCycle(MI.getDesc().getSchedClass(), DefIdx);
823
824 return Latency;
825}
826
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000827/// IncreaseHighRegPressure - Visit BBs from preheader to current BB, check
828/// if hoisting an instruction of the given cost matrix can cause high
829/// register pressure.
830bool MachineLICM::IncreaseHighRegPressure(DenseMap<unsigned, int> &Cost) {
831 for (unsigned i = BackTrace.size(); i != 0; --i) {
832 bool AnyIncrease = false;
833 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
834 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
835 CI != CE; ++CI) {
836 if (CI->second <= 0)
837 continue;
838 AnyIncrease = true;
839 unsigned RCId = CI->first;
840 if (RP[RCId] + CI->second >= RegLimit[RCId])
841 return true;
842 }
843
844 if (!AnyIncrease)
845 // Hoisting the instruction doesn't increase register pressure.
846 return false;
847 }
848
849 return false;
850}
851
Evan Cheng45e94d62009-02-04 09:19:56 +0000852/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
853/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000854bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000855 if (MI.isImplicitDef())
856 return true;
857
Evan Cheng45e94d62009-02-04 09:19:56 +0000858 // FIXME: For now, only hoist re-materilizable instructions. LICM will
859 // increase register pressure. We want to make sure it doesn't increase
860 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000861 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
862 // these tend to help performance in low register pressure situation. The
863 // trade off is it may cause spill in high pressure situation. It will end up
864 // adding a store in the loop preheader. But the reload is no more expensive.
865 // The side benefit is these loads are frequently CSE'ed.
Evan Cheng0e673912010-10-14 01:16:09 +0000866 if (!TrackRegPressure || MI.getDesc().isAsCheapAsAMove()) {
867 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
868 !isLoadFromConstantMemory(&MI))
869 return false;
870 } else {
871 // In low register pressure situation, we can be more aggressive about
872 // hoisting. Also, favors hoisting long latency instructions even in
873 // moderately high pressure situation.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000874 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000875 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
876 const MachineOperand &MO = MI.getOperand(i);
877 if (!MO.isReg() || MO.isImplicit())
878 continue;
879 unsigned Reg = MO.getReg();
880 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
881 continue;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000882 if (MO.isDef()) {
Evan Cheng0e673912010-10-14 01:16:09 +0000883 if (InstrItins && !InstrItins->isEmpty()) {
884 int Cycle = ComputeOperandLatency(MI, i, Reg);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000885 if (Cycle > 3) {
Evan Cheng0e673912010-10-14 01:16:09 +0000886 // FIXME: Target specific high latency limit?
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000887 ++NumHighLatency;
Evan Cheng0e673912010-10-14 01:16:09 +0000888 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000889 }
Evan Cheng0e673912010-10-14 01:16:09 +0000890 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000891
892 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
893 EVT VT = *RC->vt_begin();
894 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
895 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
896 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
897 // If the instruction is not register pressure neutrail (or better),
898 // check if hoisting it will cause high register pressure in BB's
899 // leading up to this point.
900 if (CI != Cost.end())
901 CI->second += RCCost;
902 else
903 Cost.insert(std::make_pair(RCId, RCCost));
904 } else if (MO.isKill()) {
905 // Is a virtual register use is a kill, hoisting it out of the loop
906 // may actually reduce register pressure or be register pressure
907 // neutral
908 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
909 EVT VT = *RC->vt_begin();
910 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
911 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
912 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
913 if (CI != Cost.end())
914 CI->second -= RCCost;
915 else
916 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +0000917 }
918 }
919
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000920 // Visit BBs from preheader to current BB, if hoisting this doesn't cause
921 // high register pressure, then it's safe to proceed.
922 if (!IncreaseHighRegPressure(Cost)) {
923 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +0000924 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000925 }
Evan Cheng0e673912010-10-14 01:16:09 +0000926
927 // High register pressure situation, only hoist if the instruction is going to
928 // be remat'ed.
929 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
930 !isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000931 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000932 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000933
Evan Chengaf6949d2009-02-05 08:45:46 +0000934 // If result(s) of this instruction is used by PHIs, then don't hoist it.
935 // The presence of joins makes it difficult for current register allocator
936 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000937 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
938 const MachineOperand &MO = MI.getOperand(i);
939 if (!MO.isReg() || !MO.isDef())
940 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000941 if (HasPHIUses(MO.getReg(), MRI))
Evan Chengaf6949d2009-02-05 08:45:46 +0000942 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000943 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000944
945 return true;
946}
947
Dan Gohman5c952302009-10-29 17:47:20 +0000948MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +0000949 // Don't unfold simple loads.
950 if (MI->getDesc().canFoldAsLoad())
951 return 0;
952
Dan Gohman5c952302009-10-29 17:47:20 +0000953 // If not, we may be able to unfold a load and hoist that.
954 // First test whether the instruction is loading from an amenable
955 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000956 if (!isLoadFromConstantMemory(MI))
957 return 0;
958
Dan Gohman5c952302009-10-29 17:47:20 +0000959 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000960 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000961 unsigned NewOpc =
962 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
963 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000964 /*UnfoldStore=*/false,
965 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000966 if (NewOpc == 0) return 0;
967 const TargetInstrDesc &TID = TII->get(NewOpc);
968 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000969 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000970 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +0000971 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000972
973 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000974 SmallVector<MachineInstr *, 2> NewMIs;
975 bool Success =
976 TII->unfoldMemoryOperand(MF, MI, Reg,
977 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
978 NewMIs);
979 (void)Success;
980 assert(Success &&
981 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
982 "succeeded!");
983 assert(NewMIs.size() == 2 &&
984 "Unfolded a load into multiple instructions!");
985 MachineBasicBlock *MBB = MI->getParent();
986 MBB->insert(MI, NewMIs[0]);
987 MBB->insert(MI, NewMIs[1]);
988 // If unfolding produced a load that wasn't loop-invariant or profitable to
989 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000990 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000991 NewMIs[0]->eraseFromParent();
992 NewMIs[1]->eraseFromParent();
993 return 0;
994 }
995 // Otherwise we successfully unfolded a load that we can hoist.
996 MI->eraseFromParent();
997 return NewMIs[0];
998}
999
Evan Cheng777c6b72009-11-03 21:40:02 +00001000void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1001 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1002 const MachineInstr *MI = &*I;
1003 // FIXME: For now, only hoist re-materilizable instructions. LICM will
1004 // increase register pressure. We want to make sure it doesn't increase
1005 // spilling.
1006 if (TII->isTriviallyReMaterializable(MI, AA)) {
1007 unsigned Opcode = MI->getOpcode();
1008 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1009 CI = CSEMap.find(Opcode);
1010 if (CI != CSEMap.end())
1011 CI->second.push_back(MI);
1012 else {
1013 std::vector<const MachineInstr*> CSEMIs;
1014 CSEMIs.push_back(MI);
1015 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1016 }
1017 }
1018 }
1019}
1020
Evan Cheng78e5c112009-11-07 03:52:02 +00001021const MachineInstr*
1022MachineLICM::LookForDuplicate(const MachineInstr *MI,
1023 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001024 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1025 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +00001026 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001027 return PrevMI;
1028 }
1029 return 0;
1030}
1031
1032bool MachineLICM::EliminateCSE(MachineInstr *MI,
1033 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001034 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1035 // the undef property onto uses.
1036 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001037 return false;
1038
1039 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001040 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001041
1042 // Replace virtual registers defined by MI by their counterparts defined
1043 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001044 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1045 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001046
1047 // Physical registers may not differ here.
1048 assert((!MO.isReg() || MO.getReg() == 0 ||
1049 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1050 MO.getReg() == Dup->getOperand(i).getReg()) &&
1051 "Instructions with different phys regs are not identical!");
1052
1053 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001054 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001055 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1056 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001057 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001058 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001059 MI->eraseFromParent();
1060 ++NumCSEed;
1061 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001062 }
1063 return false;
1064}
1065
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001066/// Hoist - When an instruction is found to use only loop invariant operands
1067/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001068///
Evan Cheng0e673912010-10-14 01:16:09 +00001069void MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001070 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001071 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001072 // If not, try unfolding a hoistable load.
1073 MI = ExtractHoistableLoad(MI);
1074 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +00001075 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001076
Dan Gohmanc475c362009-01-15 22:01:38 +00001077 // Now move the instructions to the predecessor, inserting it before any
1078 // terminator instructions.
1079 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001080 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001081 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001082 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001083 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001084 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001085 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001086 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001087 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001088 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001089
Evan Cheng777c6b72009-11-03 21:40:02 +00001090 // If this is the first instruction being hoisted to the preheader,
1091 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001092 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001093 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001094 FirstInLoop = false;
1095 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001096
Evan Chengaf6949d2009-02-05 08:45:46 +00001097 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001098 unsigned Opcode = MI->getOpcode();
1099 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1100 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001101 if (!EliminateCSE(MI, CI)) {
1102 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001103 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001104
Dan Gohmane6cd7572010-05-13 20:34:42 +00001105 // Clear the kill flags of any register this instruction defines,
1106 // since they may need to be live throughout the entire loop
1107 // rather than just live for part of it.
1108 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1109 MachineOperand &MO = MI->getOperand(i);
1110 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001111 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001112 }
1113
Evan Chengaf6949d2009-02-05 08:45:46 +00001114 // Add to the CSE map.
1115 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001116 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001117 else {
1118 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001119 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001120 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001121 }
1122 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001123
Dan Gohmanc475c362009-01-15 22:01:38 +00001124 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001125 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001126}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001127
1128MachineBasicBlock *MachineLICM::getCurPreheader() {
1129 // Determine the block to which to hoist instructions. If we can't find a
1130 // suitable loop predecessor, we can't do any hoisting.
1131
1132 // If we've tried to get a preheader and failed, don't try again.
1133 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1134 return 0;
1135
1136 if (!CurPreheader) {
1137 CurPreheader = CurLoop->getLoopPreheader();
1138 if (!CurPreheader) {
1139 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1140 if (!Pred) {
1141 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1142 return 0;
1143 }
1144
1145 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1146 if (!CurPreheader) {
1147 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1148 return 0;
1149 }
1150 }
1151 }
1152 return CurPreheader;
1153}