1 //===-- CodePlacementOpt.cpp - Code Placement pass. -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the pass that optimize code placement and align loop
11 // headers to target specific alignment boundary.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "code-placement"
16 #include "llvm/CodeGen/MachineLoopInfo.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
27 STATISTIC(NumHeaderAligned, "Number of loop header aligned");
28 STATISTIC(NumIntraElim, "Number of intra loop branches eliminated");
29 STATISTIC(NumIntraMoved, "Number of intra loop branches moved");
32 class CodePlacementOpt : public MachineFunctionPass {
33 const MachineLoopInfo *MLI;
34 const TargetInstrInfo *TII;
35 const TargetLowering *TLI;
37 /// ChangedMBBs - BBs which are modified by OptimizeIntraLoopEdges.
38 SmallPtrSet<MachineBasicBlock*, 8> ChangedMBBs;
40 /// UncondJmpMBBs - A list of BBs which are in loops and end with
41 /// unconditional branches.
42 SmallVector<std::pair<MachineBasicBlock*,MachineBasicBlock*>, 4>
45 /// LoopHeaders - A list of BBs which are loop headers.
46 SmallVector<MachineBasicBlock*, 4> LoopHeaders;
50 CodePlacementOpt() : MachineFunctionPass(&ID) {}
52 virtual bool runOnMachineFunction(MachineFunction &MF);
53 virtual const char *getPassName() const {
54 return "Code Placement Optimizater";
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired<MachineLoopInfo>();
59 AU.addPreservedID(MachineDominatorsID);
60 MachineFunctionPass::getAnalysisUsage(AU);
64 bool OptimizeIntraLoopEdges();
65 bool AlignLoops(MachineFunction &MF);
68 char CodePlacementOpt::ID = 0;
69 } // end anonymous namespace
71 FunctionPass *llvm::createCodePlacementOptPass() {
72 return new CodePlacementOpt();
75 /// OptimizeBackEdges - Place loop back edges to move unconditional branches
80 /// <fallthrough to B>
82 /// B: --> loop header
84 /// jcc <cond> C, [exit]
96 /// C: --> new loop header
102 /// jcc <cond> C, [exit]
104 bool CodePlacementOpt::OptimizeIntraLoopEdges() {
105 bool Changed = false;
106 for (unsigned i = 0, e = UncondJmpMBBs.size(); i != e; ++i) {
107 MachineBasicBlock *MBB = UncondJmpMBBs[i].first;
108 MachineBasicBlock *SuccMBB = UncondJmpMBBs[i].second;
109 MachineLoop *L = MLI->getLoopFor(MBB);
110 assert(L && "BB is expected to be in a loop!");
112 if (ChangedMBBs.count(MBB)) {
113 // BB has been modified, re-analyze.
114 MachineBasicBlock *TBB = 0, *FBB = 0;
115 SmallVector<MachineOperand, 4> Cond;
116 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
118 if (MLI->getLoopFor(TBB) != L || TBB->isLandingPad())
122 assert(MLI->getLoopFor(SuccMBB) == L &&
123 "Successor is not in the same loop!");
126 if (MBB->isLayoutSuccessor(SuccMBB)) {
127 // Successor is right after MBB, just eliminate the unconditional jmp.
129 TII->RemoveBranch(*MBB);
130 ChangedMBBs.insert(MBB);
135 // Now check if the predecessor is fallthrough from any BB. If there is,
136 // that BB should be from outside the loop since edge will become a jmp.
137 bool OkToMove = true;
138 MachineBasicBlock *FtMBB = 0, *FtTBB = 0, *FtFBB = 0;
139 SmallVector<MachineOperand, 4> FtCond;
140 for (MachineBasicBlock::pred_iterator PI = SuccMBB->pred_begin(),
141 PE = SuccMBB->pred_end(); PI != PE; ++PI) {
142 MachineBasicBlock *PredMBB = *PI;
143 if (PredMBB->isLayoutSuccessor(SuccMBB)) {
144 if (TII->AnalyzeBranch(*PredMBB, FtTBB, FtFBB, FtCond)) {
151 assert(FtFBB != SuccMBB && "Unexpected control flow!");
157 MachineLoop *PL = MLI->getLoopFor(PredMBB);
158 if (PL && (PL == L || PL->getLoopDepth() >= L->getLoopDepth())) {
168 // Is it profitable? If SuccMBB can fallthrough itself, that can be changed
170 MachineBasicBlock *TBB = 0, *FBB = 0;
171 SmallVector<MachineOperand, 4> Cond;
172 if (TII->AnalyzeBranch(*SuccMBB, TBB, FBB, Cond))
174 if (!TBB && Cond.empty())
175 TBB = next(MachineFunction::iterator(SuccMBB));
176 else if (!FBB && !Cond.empty())
177 FBB = next(MachineFunction::iterator(SuccMBB));
179 // This calculate the cost of the transformation. Also, it finds the *only*
180 // intra-loop edge if there is one.
182 bool HasOneIntraSucc = true;
183 MachineBasicBlock *IntraSucc = 0;
184 for (MachineBasicBlock::succ_iterator SI = SuccMBB->succ_begin(),
185 SE = SuccMBB->succ_end(); SI != SE; ++SI) {
186 MachineBasicBlock *SSMBB = *SI;
187 if (MLI->getLoopFor(SSMBB) == L) {
191 HasOneIntraSucc = false;
194 if (SuccMBB->isLayoutSuccessor(SSMBB))
195 // This will become a jmp.
197 else if (MBB->isLayoutSuccessor(SSMBB)) {
198 // One of the successor will become the new fallthrough.
202 } else if (!FBB && SSMBB == TBB && Cond.empty()) {
205 } else if (!Cond.empty() && !TII->ReverseBranchCondition(Cond)) {
206 assert(SSMBB == TBB);
216 // Now, let's move the successor to below the BB to eliminate the jmp.
217 SuccMBB->moveAfter(MBB);
218 TII->RemoveBranch(*MBB);
219 TII->RemoveBranch(*SuccMBB);
221 TII->InsertBranch(*SuccMBB, TBB, FBB, Cond);
222 ChangedMBBs.insert(MBB);
223 ChangedMBBs.insert(SuccMBB);
225 TII->RemoveBranch(*FtMBB);
226 TII->InsertBranch(*FtMBB, FtTBB, FtFBB, FtCond);
227 ChangedMBBs.insert(FtMBB);
230 // If BB is the loop latch, we may have a new loop headr.
231 if (MBB == L->getLoopLatch()) {
232 assert(MLI->isLoopHeader(SuccMBB) &&
233 "Only succ of loop latch is not the header?");
234 if (HasOneIntraSucc && IntraSucc)
235 std::replace(LoopHeaders.begin(),LoopHeaders.end(), SuccMBB, IntraSucc);
243 /// HeaderShouldBeAligned - Return true if the specified loop header block
244 /// should be aligned. For now, we will not align it if all the predcessors
245 /// (i.e. loop back edges) are laid out above the header. FIXME: Do not
246 /// align small loops.
247 static bool HeaderShouldBeAligned(MachineBasicBlock *MBB) {
248 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
249 PE = MBB->pred_end(); PI != PE; ++PI) {
250 MachineBasicBlock *PredMBB = *PI;
251 if (PredMBB == MBB || PredMBB->getNumber() > MBB->getNumber())
257 /// AlignLoops - Align loop headers to target preferred alignments.
259 bool CodePlacementOpt::AlignLoops(MachineFunction &MF) {
260 const Function *F = MF.getFunction();
261 if (F->hasFnAttr(Attribute::OptimizeForSize))
264 unsigned Align = TLI->getPrefLoopAlignment();
266 return false; // Don't care about loop alignment.
268 // Make sure blocks are numbered in order
271 bool Changed = false;
272 for (unsigned i = 0, e = LoopHeaders.size(); i != e; ++i) {
273 MachineBasicBlock *HeaderMBB = LoopHeaders[i];
274 MachineBasicBlock *PredMBB = prior(MachineFunction::iterator(HeaderMBB));
275 if (MLI->getLoopFor(HeaderMBB) == MLI->getLoopFor(PredMBB))
276 // If previously BB is in the same loop, don't align this BB. We want
277 // to prevent adding noop's inside a loop.
279 if (HeaderShouldBeAligned(HeaderMBB)) {
280 HeaderMBB->setAlignment(Align);
289 bool CodePlacementOpt::runOnMachineFunction(MachineFunction &MF) {
290 MLI = &getAnalysis<MachineLoopInfo>();
292 return false; // No loops.
294 TLI = MF.getTarget().getTargetLowering();
295 TII = MF.getTarget().getInstrInfo();
297 // Analyze the BBs first and keep track of loop headers and BBs that
298 // end with an unconditional jmp to another block in the same loop.
299 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
300 MachineBasicBlock *MBB = I;
301 if (MBB->isLandingPad())
303 MachineLoop *L = MLI->getLoopFor(MBB);
306 if (MLI->isLoopHeader(MBB))
307 LoopHeaders.push_back(MBB);
309 MachineBasicBlock *TBB = 0, *FBB = 0;
310 SmallVector<MachineOperand, 4> Cond;
311 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond) || !Cond.empty())
313 if (MLI->getLoopFor(TBB) == L && !TBB->isLandingPad())
314 UncondJmpMBBs.push_back(std::make_pair(MBB, TBB));
317 bool Changed = OptimizeIntraLoopEdges();
319 Changed |= AlignLoops(MF);
322 UncondJmpMBBs.clear();