Add C API for thread yielding callback.
[oota-llvm.git] / lib / Analysis / LoopPass.cpp
1 //===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements LoopPass and LPPassManager. All loop optimization
11 // and transformation passes are derived from LoopPass. LPPassManager is
12 // responsible for managing LoopPasses.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Analysis/LoopPass.h"
17 #include "llvm/IR/IRPrintingPasses.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/Timer.h"
21 using namespace llvm;
22
23 #define DEBUG_TYPE "loop-pass-manager"
24
25 namespace {
26
27 /// PrintLoopPass - Print a Function corresponding to a Loop.
28 ///
29 class PrintLoopPass : public LoopPass {
30 private:
31   std::string Banner;
32   raw_ostream &Out;       // raw_ostream to print on.
33
34 public:
35   static char ID;
36   PrintLoopPass(const std::string &B, raw_ostream &o)
37       : LoopPass(ID), Banner(B), Out(o) {}
38
39   void getAnalysisUsage(AnalysisUsage &AU) const override {
40     AU.setPreservesAll();
41   }
42
43   bool runOnLoop(Loop *L, LPPassManager &) override {
44     Out << Banner;
45     for (Loop::block_iterator b = L->block_begin(), be = L->block_end();
46          b != be;
47          ++b) {
48       (*b)->print(Out);
49     }
50     return false;
51   }
52 };
53
54 char PrintLoopPass::ID = 0;
55 }
56
57 //===----------------------------------------------------------------------===//
58 // LPPassManager
59 //
60
61 char LPPassManager::ID = 0;
62
63 LPPassManager::LPPassManager()
64   : FunctionPass(ID), PMDataManager() {
65   skipThisLoop = false;
66   redoThisLoop = false;
67   LI = nullptr;
68   CurrentLoop = nullptr;
69 }
70
71 /// Delete loop from the loop queue and loop hierarchy (LoopInfo).
72 void LPPassManager::deleteLoopFromQueue(Loop *L) {
73
74   LI->updateUnloop(L);
75
76   // If L is current loop then skip rest of the passes and let
77   // runOnFunction remove L from LQ. Otherwise, remove L from LQ now
78   // and continue applying other passes on CurrentLoop.
79   if (CurrentLoop == L)
80     skipThisLoop = true;
81
82   delete L;
83
84   if (skipThisLoop)
85     return;
86
87   for (std::deque<Loop *>::iterator I = LQ.begin(),
88          E = LQ.end(); I != E; ++I) {
89     if (*I == L) {
90       LQ.erase(I);
91       break;
92     }
93   }
94 }
95
96 // Inset loop into loop nest (LoopInfo) and loop queue (LQ).
97 void LPPassManager::insertLoop(Loop *L, Loop *ParentLoop) {
98
99   assert (CurrentLoop != L && "Cannot insert CurrentLoop");
100
101   // Insert into loop nest
102   if (ParentLoop)
103     ParentLoop->addChildLoop(L);
104   else
105     LI->addTopLevelLoop(L);
106
107   insertLoopIntoQueue(L);
108 }
109
110 void LPPassManager::insertLoopIntoQueue(Loop *L) {
111   // Insert L into loop queue
112   if (L == CurrentLoop)
113     redoLoop(L);
114   else if (!L->getParentLoop())
115     // This is top level loop.
116     LQ.push_front(L);
117   else {
118     // Insert L after the parent loop.
119     for (std::deque<Loop *>::iterator I = LQ.begin(),
120            E = LQ.end(); I != E; ++I) {
121       if (*I == L->getParentLoop()) {
122         // deque does not support insert after.
123         ++I;
124         LQ.insert(I, 1, L);
125         break;
126       }
127     }
128   }
129 }
130
131 // Reoptimize this loop. LPPassManager will re-insert this loop into the
132 // queue. This allows LoopPass to change loop nest for the loop. This
133 // utility may send LPPassManager into infinite loops so use caution.
134 void LPPassManager::redoLoop(Loop *L) {
135   assert (CurrentLoop == L && "Can redo only CurrentLoop");
136   redoThisLoop = true;
137 }
138
139 /// cloneBasicBlockSimpleAnalysis - Invoke cloneBasicBlockAnalysis hook for
140 /// all loop passes.
141 void LPPassManager::cloneBasicBlockSimpleAnalysis(BasicBlock *From,
142                                                   BasicBlock *To, Loop *L) {
143   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
144     LoopPass *LP = getContainedPass(Index);
145     LP->cloneBasicBlockAnalysis(From, To, L);
146   }
147 }
148
149 /// deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes.
150 void LPPassManager::deleteSimpleAnalysisValue(Value *V, Loop *L) {
151   if (BasicBlock *BB = dyn_cast<BasicBlock>(V)) {
152     for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;
153          ++BI) {
154       Instruction &I = *BI;
155       deleteSimpleAnalysisValue(&I, L);
156     }
157   }
158   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
159     LoopPass *LP = getContainedPass(Index);
160     LP->deleteAnalysisValue(V, L);
161   }
162 }
163
164
165 // Recurse through all subloops and all loops  into LQ.
166 static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) {
167   LQ.push_back(L);
168   for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I)
169     addLoopIntoQueue(*I, LQ);
170 }
171
172 /// Pass Manager itself does not invalidate any analysis info.
173 void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
174   // LPPassManager needs LoopInfo. In the long term LoopInfo class will
175   // become part of LPPassManager.
176   Info.addRequired<LoopInfo>();
177   Info.setPreservesAll();
178 }
179
180 /// run - Execute all of the passes scheduled for execution.  Keep track of
181 /// whether any of the passes modifies the function, and if so, return true.
182 bool LPPassManager::runOnFunction(Function &F) {
183   LI = &getAnalysis<LoopInfo>();
184   bool Changed = false;
185
186   // Collect inherited analysis from Module level pass manager.
187   populateInheritedAnalysis(TPM->activeStack);
188
189   // Populate the loop queue in reverse program order. There is no clear need to
190   // process sibling loops in either forward or reverse order. There may be some
191   // advantage in deleting uses in a later loop before optimizing the
192   // definitions in an earlier loop. If we find a clear reason to process in
193   // forward order, then a forward variant of LoopPassManager should be created.
194   //
195   // Note that LoopInfo::iterator visits loops in reverse program
196   // order. Here, reverse_iterator gives us a forward order, and the LoopQueue
197   // reverses the order a third time by popping from the back.
198   for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
199     addLoopIntoQueue(*I, LQ);
200
201   if (LQ.empty()) // No loops, skip calling finalizers
202     return false;
203
204   // Initialization
205   for (std::deque<Loop *>::const_iterator I = LQ.begin(), E = LQ.end();
206        I != E; ++I) {
207     Loop *L = *I;
208     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
209       LoopPass *P = getContainedPass(Index);
210       Changed |= P->doInitialization(L, *this);
211     }
212   }
213
214   // Walk Loops
215   while (!LQ.empty()) {
216
217     CurrentLoop  = LQ.back();
218     skipThisLoop = false;
219     redoThisLoop = false;
220
221     // Run all passes on the current Loop.
222     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
223       LoopPass *P = getContainedPass(Index);
224
225       dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG,
226                    CurrentLoop->getHeader()->getName());
227       dumpRequiredSet(P);
228
229       initializeAnalysisImpl(P);
230
231       {
232         PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader());
233         TimeRegion PassTimer(getPassTimer(P));
234
235         Changed |= P->runOnLoop(CurrentLoop, *this);
236       }
237
238       if (Changed)
239         dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG,
240                      skipThisLoop ? "<deleted>" :
241                                     CurrentLoop->getHeader()->getName());
242       dumpPreservedSet(P);
243
244       if (!skipThisLoop) {
245         // Manually check that this loop is still healthy. This is done
246         // instead of relying on LoopInfo::verifyLoop since LoopInfo
247         // is a function pass and it's really expensive to verify every
248         // loop in the function every time. That level of checking can be
249         // enabled with the -verify-loop-info option.
250         {
251           TimeRegion PassTimer(getPassTimer(LI));
252           CurrentLoop->verifyLoop();
253         }
254
255         // Then call the regular verifyAnalysis functions.
256         verifyPreservedAnalysis(P);
257
258         F.getContext().yield();
259       }
260
261       removeNotPreservedAnalysis(P);
262       recordAvailableAnalysis(P);
263       removeDeadPasses(P,
264                        skipThisLoop ? "<deleted>" :
265                                       CurrentLoop->getHeader()->getName(),
266                        ON_LOOP_MSG);
267
268       if (skipThisLoop)
269         // Do not run other passes on this loop.
270         break;
271     }
272
273     // If the loop was deleted, release all the loop passes. This frees up
274     // some memory, and avoids trouble with the pass manager trying to call
275     // verifyAnalysis on them.
276     if (skipThisLoop)
277       for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
278         Pass *P = getContainedPass(Index);
279         freePass(P, "<deleted>", ON_LOOP_MSG);
280       }
281
282     // Pop the loop from queue after running all passes.
283     LQ.pop_back();
284
285     if (redoThisLoop)
286       LQ.push_back(CurrentLoop);
287   }
288
289   // Finalization
290   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
291     LoopPass *P = getContainedPass(Index);
292     Changed |= P->doFinalization();
293   }
294
295   return Changed;
296 }
297
298 /// Print passes managed by this manager
299 void LPPassManager::dumpPassStructure(unsigned Offset) {
300   errs().indent(Offset*2) << "Loop Pass Manager\n";
301   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
302     Pass *P = getContainedPass(Index);
303     P->dumpPassStructure(Offset + 1);
304     dumpLastUses(P, Offset+1);
305   }
306 }
307
308
309 //===----------------------------------------------------------------------===//
310 // LoopPass
311
312 Pass *LoopPass::createPrinterPass(raw_ostream &O,
313                                   const std::string &Banner) const {
314   return new PrintLoopPass(Banner, O);
315 }
316
317 // Check if this pass is suitable for the current LPPassManager, if
318 // available. This pass P is not suitable for a LPPassManager if P
319 // is not preserving higher level analysis info used by other
320 // LPPassManager passes. In such case, pop LPPassManager from the
321 // stack. This will force assignPassManager() to create new
322 // LPPassManger as expected.
323 void LoopPass::preparePassManager(PMStack &PMS) {
324
325   // Find LPPassManager
326   while (!PMS.empty() &&
327          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
328     PMS.pop();
329
330   // If this pass is destroying high level information that is used
331   // by other passes that are managed by LPM then do not insert
332   // this pass in current LPM. Use new LPPassManager.
333   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager &&
334       !PMS.top()->preserveHigherLevelAnalysis(this))
335     PMS.pop();
336 }
337
338 /// Assign pass manager to manage this pass.
339 void LoopPass::assignPassManager(PMStack &PMS,
340                                  PassManagerType PreferredType) {
341   // Find LPPassManager
342   while (!PMS.empty() &&
343          PMS.top()->getPassManagerType() > PMT_LoopPassManager)
344     PMS.pop();
345
346   LPPassManager *LPPM;
347   if (PMS.top()->getPassManagerType() == PMT_LoopPassManager)
348     LPPM = (LPPassManager*)PMS.top();
349   else {
350     // Create new Loop Pass Manager if it does not exist.
351     assert (!PMS.empty() && "Unable to create Loop Pass Manager");
352     PMDataManager *PMD = PMS.top();
353
354     // [1] Create new Loop Pass Manager
355     LPPM = new LPPassManager();
356     LPPM->populateInheritedAnalysis(PMS);
357
358     // [2] Set up new manager's top level manager
359     PMTopLevelManager *TPM = PMD->getTopLevelManager();
360     TPM->addIndirectPassManager(LPPM);
361
362     // [3] Assign manager to manage this new manager. This may create
363     // and push new managers into PMS
364     Pass *P = LPPM->getAsPass();
365     TPM->schedulePass(P);
366
367     // [4] Push new manager into PMS
368     PMS.push(LPPM);
369   }
370
371   LPPM->add(this);
372 }
373
374 // Containing function has Attribute::OptimizeNone and transformation
375 // passes should skip it.
376 bool LoopPass::skipOptnoneFunction(const Loop *L) const {
377   const Function *F = L->getHeader()->getParent();
378   if (F && F->hasFnAttribute(Attribute::OptimizeNone)) {
379     // FIXME: Report this to dbgs() only once per function.
380     DEBUG(dbgs() << "Skipping pass '" << getPassName()
381           << "' in function " << F->getName() << "\n");
382     // FIXME: Delete loop from pass manager's queue?
383     return true;
384   }
385   return false;
386 }