1 //===- RegionPass.cpp - Region Pass and Region Pass Manager ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements RegionPass and RGPassManager. All region optimization
10 // and transformation passes are derived from RegionPass. RGPassManager is
11 // responsible for managing RegionPasses.
12 // Most of this code has been COPIED from LoopPass.cpp
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Analysis/RegionPass.h"
17 #include "llvm/Analysis/RegionInfo.h"
18 #include "llvm/IR/OptBisect.h"
19 #include "llvm/IR/PassTimingInfo.h"
20 #include "llvm/IR/PrintPasses.h"
21 #ifdef EXPENSIVE_CHECKS
22 #include "llvm/IR/StructuralHash.h"
23 #endif
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Timer.h"
26 #include "llvm/Support/raw_ostream.h"
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "regionpassmgr"
31 
32 //===----------------------------------------------------------------------===//
33 // RGPassManager
34 //
35 
36 char RGPassManager::ID = 0;
37 
38 RGPassManager::RGPassManager() : FunctionPass(ID) {
39   RI = nullptr;
40   CurrentRegion = nullptr;
41 }
42 
43 // Recurse through all subregions and all regions  into RQ.
44 static void addRegionIntoQueue(Region &R, std::deque<Region *> &RQ) {
45   RQ.push_back(&R);
46   for (const auto &E : R)
47     addRegionIntoQueue(*E, RQ);
48 }
49 
50 /// Pass Manager itself does not invalidate any analysis info.
51 void RGPassManager::getAnalysisUsage(AnalysisUsage &Info) const {
52   Info.addRequired<RegionInfoPass>();
53   Info.setPreservesAll();
54 }
55 
56 /// run - Execute all of the passes scheduled for execution.  Keep track of
57 /// whether any of the passes modifies the function, and if so, return true.
58 bool RGPassManager::runOnFunction(Function &F) {
59   RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
60   bool Changed = false;
61 
62   // Collect inherited analysis from Module level pass manager.
63   populateInheritedAnalysis(TPM->activeStack);
64 
65   addRegionIntoQueue(*RI->getTopLevelRegion(), RQ);
66 
67   if (RQ.empty()) // No regions, skip calling finalizers
68     return false;
69 
70   // Initialization
71   for (Region *R : RQ) {
72     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
73       RegionPass *RP = (RegionPass *)getContainedPass(Index);
74       Changed |= RP->doInitialization(R, *this);
75     }
76   }
77 
78   // Walk Regions
79   while (!RQ.empty()) {
80 
81     CurrentRegion  = RQ.back();
82 
83     // Run all passes on the current Region.
84     for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
85       RegionPass *P = (RegionPass*)getContainedPass(Index);
86 
87       if (isPassDebuggingExecutionsOrMore()) {
88         dumpPassInfo(P, EXECUTION_MSG, ON_REGION_MSG,
89                      CurrentRegion->getNameStr());
90         dumpRequiredSet(P);
91       }
92 
93       initializeAnalysisImpl(P);
94 
95       bool LocalChanged = false;
96       {
97         PassManagerPrettyStackEntry X(P, *CurrentRegion->getEntry());
98 
99         TimeRegion PassTimer(getPassTimer(P));
100 #ifdef EXPENSIVE_CHECKS
101         uint64_t RefHash = StructuralHash(F);
102 #endif
103         LocalChanged = P->runOnRegion(CurrentRegion, *this);
104 
105 #ifdef EXPENSIVE_CHECKS
106         if (!LocalChanged && (RefHash != StructuralHash(F))) {
107           llvm::errs() << "Pass modifies its input and doesn't report it: "
108                        << P->getPassName() << "\n";
109           llvm_unreachable("Pass modifies its input and doesn't report it");
110         }
111 #endif
112 
113         Changed |= LocalChanged;
114       }
115 
116       if (isPassDebuggingExecutionsOrMore()) {
117         if (LocalChanged)
118           dumpPassInfo(P, MODIFICATION_MSG, ON_REGION_MSG,
119                                       CurrentRegion->getNameStr());
120         dumpPreservedSet(P);
121       }
122 
123       // Manually check that this region is still healthy. This is done
124       // instead of relying on RegionInfo::verifyRegion since RegionInfo
125       // is a function pass and it's really expensive to verify every
126       // Region in the function every time. That level of checking can be
127       // enabled with the -verify-region-info option.
128       {
129         TimeRegion PassTimer(getPassTimer(P));
130         CurrentRegion->verifyRegion();
131       }
132 
133       // Then call the regular verifyAnalysis functions.
134       verifyPreservedAnalysis(P);
135 
136       if (LocalChanged)
137         removeNotPreservedAnalysis(P);
138       recordAvailableAnalysis(P);
139       removeDeadPasses(P,
140                        (!isPassDebuggingExecutionsOrMore())
141                            ? "<deleted>"
142                            : CurrentRegion->getNameStr(),
143                        ON_REGION_MSG);
144     }
145 
146     // Pop the region from queue after running all passes.
147     RQ.pop_back();
148 
149     // Free all region nodes created in region passes.
150     RI->clearNodeCache();
151   }
152 
153   // Finalization
154   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
155     RegionPass *P = (RegionPass*)getContainedPass(Index);
156     Changed |= P->doFinalization();
157   }
158 
159   // Print the region tree after all pass.
160   LLVM_DEBUG(dbgs() << "\nRegion tree of function " << F.getName()
161                     << " after all region Pass:\n";
162              RI->dump(); dbgs() << "\n";);
163 
164   return Changed;
165 }
166 
167 /// Print passes managed by this manager
168 void RGPassManager::dumpPassStructure(unsigned Offset) {
169   errs().indent(Offset*2) << "Region Pass Manager\n";
170   for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) {
171     Pass *P = getContainedPass(Index);
172     P->dumpPassStructure(Offset + 1);
173     dumpLastUses(P, Offset+1);
174   }
175 }
176 
177 namespace {
178 //===----------------------------------------------------------------------===//
179 // PrintRegionPass
180 class PrintRegionPass : public RegionPass {
181 private:
182   std::string Banner;
183   raw_ostream &Out;       // raw_ostream to print on.
184 
185 public:
186   static char ID;
187   PrintRegionPass(const std::string &B, raw_ostream &o)
188       : RegionPass(ID), Banner(B), Out(o) {}
189 
190   void getAnalysisUsage(AnalysisUsage &AU) const override {
191     AU.setPreservesAll();
192   }
193 
194   bool runOnRegion(Region *R, RGPassManager &RGM) override {
195     if (!isFunctionInPrintList(R->getEntry()->getParent()->getName()))
196       return false;
197     Out << Banner;
198     for (const auto *BB : R->blocks()) {
199       if (BB)
200         BB->print(Out);
201       else
202         Out << "Printing <null> Block";
203     }
204 
205     return false;
206   }
207 
208   StringRef getPassName() const override { return "Print Region IR"; }
209 };
210 
211 char PrintRegionPass::ID = 0;
212 }  //end anonymous namespace
213 
214 //===----------------------------------------------------------------------===//
215 // RegionPass
216 
217 // Check if this pass is suitable for the current RGPassManager, if
218 // available. This pass P is not suitable for a RGPassManager if P
219 // is not preserving higher level analysis info used by other
220 // RGPassManager passes. In such case, pop RGPassManager from the
221 // stack. This will force assignPassManager() to create new
222 // LPPassManger as expected.
223 void RegionPass::preparePassManager(PMStack &PMS) {
224 
225   // Find RGPassManager
226   while (!PMS.empty() &&
227          PMS.top()->getPassManagerType() > PMT_RegionPassManager)
228     PMS.pop();
229 
230 
231   // If this pass is destroying high level information that is used
232   // by other passes that are managed by LPM then do not insert
233   // this pass in current LPM. Use new RGPassManager.
234   if (PMS.top()->getPassManagerType() == PMT_RegionPassManager &&
235     !PMS.top()->preserveHigherLevelAnalysis(this))
236     PMS.pop();
237 }
238 
239 /// Assign pass manager to manage this pass.
240 void RegionPass::assignPassManager(PMStack &PMS,
241                                  PassManagerType PreferredType) {
242   // Find RGPassManager
243   while (!PMS.empty() &&
244          PMS.top()->getPassManagerType() > PMT_RegionPassManager)
245     PMS.pop();
246 
247   RGPassManager *RGPM;
248 
249   // Create new Region Pass Manager if it does not exist.
250   if (PMS.top()->getPassManagerType() == PMT_RegionPassManager)
251     RGPM = (RGPassManager*)PMS.top();
252   else {
253 
254     assert (!PMS.empty() && "Unable to create Region Pass Manager");
255     PMDataManager *PMD = PMS.top();
256 
257     // [1] Create new Region Pass Manager
258     RGPM = new RGPassManager();
259     RGPM->populateInheritedAnalysis(PMS);
260 
261     // [2] Set up new manager's top level manager
262     PMTopLevelManager *TPM = PMD->getTopLevelManager();
263     TPM->addIndirectPassManager(RGPM);
264 
265     // [3] Assign manager to manage this new manager. This may create
266     // and push new managers into PMS
267     TPM->schedulePass(RGPM);
268 
269     // [4] Push new manager into PMS
270     PMS.push(RGPM);
271   }
272 
273   RGPM->add(this);
274 }
275 
276 /// Get the printer pass
277 Pass *RegionPass::createPrinterPass(raw_ostream &O,
278                                   const std::string &Banner) const {
279   return new PrintRegionPass(Banner, O);
280 }
281 
282 static std::string getDescription(const Region &R) {
283   return "region";
284 }
285 
286 bool RegionPass::skipRegion(Region &R) const {
287   Function &F = *R.getEntry()->getParent();
288   OptPassGate &Gate = F.getContext().getOptPassGate();
289   if (Gate.isEnabled() && !Gate.shouldRunPass(this, getDescription(R)))
290     return true;
291 
292   if (F.hasOptNone()) {
293     // Report this only once per function.
294     if (R.getEntry() == &F.getEntryBlock())
295       LLVM_DEBUG(dbgs() << "Skipping pass '" << getPassName()
296                         << "' on function " << F.getName() << "\n");
297     return true;
298   }
299   return false;
300 }
301