1 //===-- IPO/OpenMPOpt.cpp - Collection of OpenMP specific optimizations ---===//
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 // OpenMP specific optimizations:
10 //
11 // - Deduplication of runtime calls, e.g., omp_get_thread_num.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/IPO/OpenMPOpt.h"
16 
17 #include "llvm/ADT/EnumeratedArray.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Frontend/OpenMP/OMPConstants.h"
22 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
23 #include "llvm/InitializePasses.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Transforms/IPO.h"
26 #include "llvm/Transforms/Utils/CallGraphUpdater.h"
27 
28 using namespace llvm;
29 using namespace omp;
30 using namespace types;
31 
32 #define DEBUG_TYPE "openmp-opt"
33 
34 static cl::opt<bool> DisableOpenMPOptimizations(
35     "openmp-opt-disable", cl::ZeroOrMore,
36     cl::desc("Disable OpenMP specific optimizations."), cl::Hidden,
37     cl::init(false));
38 
39 STATISTIC(NumOpenMPRuntimeCallsDeduplicated,
40           "Number of OpenMP runtime calls deduplicated");
41 STATISTIC(NumOpenMPRuntimeFunctionsIdentified,
42           "Number of OpenMP runtime functions identified");
43 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified,
44           "Number of OpenMP runtime function uses identified");
45 
46 #if !defined(NDEBUG)
47 static constexpr auto TAG = "[" DEBUG_TYPE "]";
48 #endif
49 
50 namespace {
51 struct OpenMPOpt {
52 
53   OpenMPOpt(SmallVectorImpl<Function *> &SCC,
54             SmallPtrSetImpl<Function *> &ModuleSlice,
55             CallGraphUpdater &CGUpdater)
56       : M(*(*SCC.begin())->getParent()), SCC(SCC), ModuleSlice(ModuleSlice),
57         OMPBuilder(M), CGUpdater(CGUpdater) {
58     initializeTypes(M);
59     initializeRuntimeFunctions();
60     OMPBuilder.initialize();
61   }
62 
63   /// Generic information that describes a runtime function
64   struct RuntimeFunctionInfo {
65 
66     /// The kind, as described by the RuntimeFunction enum.
67     RuntimeFunction Kind;
68 
69     /// The name of the function.
70     StringRef Name;
71 
72     /// Flag to indicate a variadic function.
73     bool IsVarArg;
74 
75     /// The return type of the function.
76     Type *ReturnType;
77 
78     /// The argument types of the function.
79     SmallVector<Type *, 8> ArgumentTypes;
80 
81     /// The declaration if available.
82     Function *Declaration = nullptr;
83 
84     /// Uses of this runtime function per function containing the use.
85     using UseVector = SmallVector<Use *, 16>;
86 
87     /// Return the vector of uses in function \p F.
88     UseVector &getOrCreateUseVector(Function *F) {
89       std::unique_ptr<UseVector> &UV = UsesMap[F];
90       if (!UV)
91         UV = std::make_unique<UseVector>();
92       return *UV;
93     }
94 
95     /// Return the vector of uses in function \p F or `nullptr` if there are
96     /// none.
97     const UseVector *getUseVector(Function &F) const {
98       auto I = UsesMap.find(&F);
99       if (I != UsesMap.end())
100         return I->second.get();
101       return nullptr;
102     }
103 
104     /// Return how many functions contain uses of this runtime function.
105     size_t getNumFunctionsWithUses() const { return UsesMap.size(); }
106 
107     /// Return the number of arguments (or the minimal number for variadic
108     /// functions).
109     size_t getNumArgs() const { return ArgumentTypes.size(); }
110 
111     /// Run the callback \p CB on each use and forget the use if the result is
112     /// true. The callback will be fed the function in which the use was
113     /// encountered as second argument.
114     void foreachUse(function_ref<bool(Use &, Function &)> CB) {
115       SmallVector<unsigned, 8> ToBeDeleted;
116       for (auto &It : UsesMap) {
117         ToBeDeleted.clear();
118         unsigned Idx = 0;
119         UseVector &UV = *It.second;
120         for (Use *U : UV) {
121           if (CB(*U, *It.first))
122             ToBeDeleted.push_back(Idx);
123           ++Idx;
124         }
125 
126         // Remove the to-be-deleted indices in reverse order as prior
127         // modifcations will not modify the smaller indices.
128         while (!ToBeDeleted.empty()) {
129           unsigned Idx = ToBeDeleted.pop_back_val();
130           UV[Idx] = UV.back();
131           UV.pop_back();
132         }
133       }
134     }
135 
136   private:
137     /// Map from functions to all uses of this runtime function contained in
138     /// them.
139     DenseMap<Function *, std::unique_ptr<UseVector>> UsesMap;
140   };
141 
142   /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice.
143   bool run() {
144     bool Changed = false;
145 
146     LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size()
147                       << " functions in a slice with " << ModuleSlice.size()
148                       << " functions\n");
149 
150     Changed |= deduplicateRuntimeCalls();
151     Changed |= deleteParallelRegions();
152 
153     return Changed;
154   }
155 
156 private:
157   /// Try to delete parallel regions if possible.
158   bool deleteParallelRegions() {
159     const unsigned CallbackCalleeOperand = 2;
160 
161     RuntimeFunctionInfo &RFI = RFIs[OMPRTL___kmpc_fork_call];
162     if (!RFI.Declaration)
163       return false;
164 
165     bool Changed = false;
166     auto DeleteCallCB = [&](Use &U, Function &) {
167       CallInst *CI = getCallIfRegularCall(U);
168       if (!CI)
169         return false;
170       auto *Fn = dyn_cast<Function>(
171           CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts());
172       if (!Fn)
173         return false;
174       if (!Fn->onlyReadsMemory())
175         return false;
176       if (!Fn->hasFnAttribute(Attribute::WillReturn))
177         return false;
178 
179       LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in "
180                         << CI->getCaller()->getName() << "\n");
181       CGUpdater.removeCallSite(*CI);
182       CI->eraseFromParent();
183       Changed = true;
184       return true;
185     };
186 
187     RFI.foreachUse(DeleteCallCB);
188 
189     return Changed;
190   }
191 
192   /// Try to eliminiate runtime calls by reusing existing ones.
193   bool deduplicateRuntimeCalls() {
194     bool Changed = false;
195 
196     RuntimeFunction DeduplicableRuntimeCallIDs[] = {
197         OMPRTL_omp_get_num_threads,
198         OMPRTL_omp_in_parallel,
199         OMPRTL_omp_get_cancellation,
200         OMPRTL_omp_get_thread_limit,
201         OMPRTL_omp_get_supported_active_levels,
202         OMPRTL_omp_get_level,
203         OMPRTL_omp_get_ancestor_thread_num,
204         OMPRTL_omp_get_team_size,
205         OMPRTL_omp_get_active_level,
206         OMPRTL_omp_in_final,
207         OMPRTL_omp_get_proc_bind,
208         OMPRTL_omp_get_num_places,
209         OMPRTL_omp_get_num_procs,
210         OMPRTL_omp_get_place_num,
211         OMPRTL_omp_get_partition_num_places,
212         OMPRTL_omp_get_partition_place_nums};
213 
214     // Global-tid is handled separatly.
215     SmallSetVector<Value *, 16> GTIdArgs;
216     collectGlobalThreadIdArguments(GTIdArgs);
217     LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size()
218                       << " global thread ID arguments\n");
219 
220     for (Function *F : SCC) {
221       for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs)
222         deduplicateRuntimeCalls(*F, RFIs[DeduplicableRuntimeCallID]);
223 
224       // __kmpc_global_thread_num is special as we can replace it with an
225       // argument in enough cases to make it worth trying.
226       Value *GTIdArg = nullptr;
227       for (Argument &Arg : F->args())
228         if (GTIdArgs.count(&Arg)) {
229           GTIdArg = &Arg;
230           break;
231         }
232       Changed |= deduplicateRuntimeCalls(
233           *F, RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg);
234     }
235 
236     return Changed;
237   }
238 
239   static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent,
240                                     bool GlobalOnly, bool &SingleChoice) {
241     if (CurrentIdent == NextIdent)
242       return CurrentIdent;
243 
244     // TODO: Figure out how to actually combine multiple debug locations. For
245     //       now we just keep an existing one if there is a single choice.
246     if (!GlobalOnly || isa<GlobalValue>(NextIdent)) {
247       SingleChoice = !CurrentIdent;
248       return NextIdent;
249     }
250     return nullptr;
251   }
252 
253   /// Return an `struct ident_t*` value that represents the ones used in the
254   /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not
255   /// return a local `struct ident_t*`. For now, if we cannot find a suitable
256   /// return value we create one from scratch. We also do not yet combine
257   /// information, e.g., the source locations, see combinedIdentStruct.
258   Value *getCombinedIdentFromCallUsesIn(RuntimeFunctionInfo &RFI, Function &F,
259                                         bool GlobalOnly) {
260     bool SingleChoice = true;
261     Value *Ident = nullptr;
262     auto CombineIdentStruct = [&](Use &U, Function &Caller) {
263       CallInst *CI = getCallIfRegularCall(U, &RFI);
264       if (!CI || &F != &Caller)
265         return false;
266       Ident = combinedIdentStruct(Ident, CI->getArgOperand(0),
267                                   /* GlobalOnly */ true, SingleChoice);
268       return false;
269     };
270     RFI.foreachUse(CombineIdentStruct);
271 
272     if (!Ident || !SingleChoice) {
273       // The IRBuilder uses the insertion block to get to the module, this is
274       // unfortunate but we work around it for now.
275       if (!OMPBuilder.getInsertionPoint().getBlock())
276         OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy(
277             &F.getEntryBlock(), F.getEntryBlock().begin()));
278       // Create a fallback location if non was found.
279       // TODO: Use the debug locations of the calls instead.
280       Constant *Loc = OMPBuilder.getOrCreateDefaultSrcLocStr();
281       Ident = OMPBuilder.getOrCreateIdent(Loc);
282     }
283     return Ident;
284   }
285 
286   /// Try to eliminiate calls of \p RFI in \p F by reusing an existing one or
287   /// \p ReplVal if given.
288   bool deduplicateRuntimeCalls(Function &F, RuntimeFunctionInfo &RFI,
289                                Value *ReplVal = nullptr) {
290     auto *UV = RFI.getUseVector(F);
291     if (!UV || UV->size() + (ReplVal != nullptr) < 2)
292       return false;
293 
294     LLVM_DEBUG(dbgs() << TAG << "Deduplicate " << UV->size() << " uses of "
295                       << RFI.Name
296                       << (ReplVal ? " with an existing value\n" : "\n")
297                       << "\n");
298     assert((!ReplVal || (isa<Argument>(ReplVal) &&
299                          cast<Argument>(ReplVal)->getParent() == &F)) &&
300            "Unexpected replacement value!");
301 
302     // TODO: Use dominance to find a good position instead.
303     auto CanBeMoved = [](CallBase &CB) {
304       unsigned NumArgs = CB.getNumArgOperands();
305       if (NumArgs == 0)
306         return true;
307       if (CB.getArgOperand(0)->getType() != IdentPtr)
308         return false;
309       for (unsigned u = 1; u < NumArgs; ++u)
310         if (isa<Instruction>(CB.getArgOperand(u)))
311           return false;
312       return true;
313     };
314 
315     if (!ReplVal) {
316       for (Use *U : *UV)
317         if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) {
318           if (!CanBeMoved(*CI))
319             continue;
320           CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt());
321           ReplVal = CI;
322           break;
323         }
324       if (!ReplVal)
325         return false;
326     }
327 
328     // If we use a call as a replacement value we need to make sure the ident is
329     // valid at the new location. For now we just pick a global one, either
330     // existing and used by one of the calls, or created from scratch.
331     if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) {
332       if (CI->getNumArgOperands() > 0 &&
333           CI->getArgOperand(0)->getType() == IdentPtr) {
334         Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F,
335                                                       /* GlobalOnly */ true);
336         CI->setArgOperand(0, Ident);
337       }
338     }
339 
340     bool Changed = false;
341     auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) {
342       CallInst *CI = getCallIfRegularCall(U, &RFI);
343       if (!CI || CI == ReplVal || &F != &Caller)
344         return false;
345       assert(CI->getCaller() == &F && "Unexpected call!");
346       CGUpdater.removeCallSite(*CI);
347       CI->replaceAllUsesWith(ReplVal);
348       CI->eraseFromParent();
349       ++NumOpenMPRuntimeCallsDeduplicated;
350       Changed = true;
351       return true;
352     };
353     RFI.foreachUse(ReplaceAndDeleteCB);
354 
355     return Changed;
356   }
357 
358   /// Collect arguments that represent the global thread id in \p GTIdArgs.
359   void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> &GTIdArgs) {
360     // TODO: Below we basically perform a fixpoint iteration with a pessimistic
361     //       initialization. We could define an AbstractAttribute instead and
362     //       run the Attributor here once it can be run as an SCC pass.
363 
364     // Helper to check the argument \p ArgNo at all call sites of \p F for
365     // a GTId.
366     auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) {
367       if (!F.hasLocalLinkage())
368         return false;
369       for (Use &U : F.uses()) {
370         if (CallInst *CI = getCallIfRegularCall(U)) {
371           Value *ArgOp = CI->getArgOperand(ArgNo);
372           if (CI == &RefCI || GTIdArgs.count(ArgOp) ||
373               getCallIfRegularCall(*ArgOp,
374                                    &RFIs[OMPRTL___kmpc_global_thread_num]))
375             continue;
376         }
377         return false;
378       }
379       return true;
380     };
381 
382     // Helper to identify uses of a GTId as GTId arguments.
383     auto AddUserArgs = [&](Value &GTId) {
384       for (Use &U : GTId.uses())
385         if (CallInst *CI = dyn_cast<CallInst>(U.getUser()))
386           if (CI->isArgOperand(&U))
387             if (Function *Callee = CI->getCalledFunction())
388               if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI))
389                 GTIdArgs.insert(Callee->getArg(U.getOperandNo()));
390     };
391 
392     // The argument users of __kmpc_global_thread_num calls are GTIds.
393     RuntimeFunctionInfo &GlobThreadNumRFI =
394         RFIs[OMPRTL___kmpc_global_thread_num];
395     GlobThreadNumRFI.foreachUse([&](Use &U, Function &F) {
396       if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI))
397         AddUserArgs(*CI);
398       return false;
399     });
400 
401     // Transitively search for more arguments by looking at the users of the
402     // ones we know already. During the search the GTIdArgs vector is extended
403     // so we cannot cache the size nor can we use a range based for.
404     for (unsigned u = 0; u < GTIdArgs.size(); ++u)
405       AddUserArgs(*GTIdArgs[u]);
406   }
407 
408   /// Return the call if \p U is a callee use in a regular call. If \p RFI is
409   /// given it has to be the callee or a nullptr is returned.
410   CallInst *getCallIfRegularCall(Use &U, RuntimeFunctionInfo *RFI = nullptr) {
411     CallInst *CI = dyn_cast<CallInst>(U.getUser());
412     if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() &&
413         (!RFI || CI->getCalledFunction() == RFI->Declaration))
414       return CI;
415     return nullptr;
416   }
417 
418   /// Return the call if \p V is a regular call. If \p RFI is given it has to be
419   /// the callee or a nullptr is returned.
420   CallInst *getCallIfRegularCall(Value &V, RuntimeFunctionInfo *RFI = nullptr) {
421     CallInst *CI = dyn_cast<CallInst>(&V);
422     if (CI && !CI->hasOperandBundles() &&
423         (!RFI || CI->getCalledFunction() == RFI->Declaration))
424       return CI;
425     return nullptr;
426   }
427 
428   /// Returns true if the function declaration \p F matches the runtime
429   /// function types, that is, return type \p RTFRetType, and argument types
430   /// \p RTFArgTypes.
431   static bool declMatchesRTFTypes(Function *F, Type *RTFRetType,
432                                   SmallVector<Type *, 8> &RTFArgTypes) {
433     // TODO: We should output information to the user (under debug output
434     //       and via remarks).
435 
436     if (!F)
437       return false;
438     if (F->getReturnType() != RTFRetType)
439       return false;
440     if (F->arg_size() != RTFArgTypes.size())
441       return false;
442 
443     auto RTFTyIt = RTFArgTypes.begin();
444     for (Argument &Arg : F->args()) {
445       if (Arg.getType() != *RTFTyIt)
446         return false;
447 
448       ++RTFTyIt;
449     }
450 
451     return true;
452   }
453 
454   /// Helper to initialize all runtime function information for those defined in
455   /// OpenMPKinds.def.
456   void initializeRuntimeFunctions() {
457     // Helper to collect all uses of the decleration in the UsesMap.
458     auto CollectUses = [&](RuntimeFunctionInfo &RFI) {
459       unsigned NumUses = 0;
460       if (!RFI.Declaration)
461         return NumUses;
462       OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration);
463 
464       NumOpenMPRuntimeFunctionsIdentified += 1;
465       NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses();
466 
467       // TODO: We directly convert uses into proper calls and unknown uses.
468       for (Use &U : RFI.Declaration->uses()) {
469         if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) {
470           if (ModuleSlice.count(UserI->getFunction())) {
471             RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U);
472             ++NumUses;
473           }
474         } else {
475           RFI.getOrCreateUseVector(nullptr).push_back(&U);
476           ++NumUses;
477         }
478       }
479       return NumUses;
480     };
481 
482 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...)                     \
483   {                                                                            \
484     SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__});                           \
485     Function *F = M.getFunction(_Name);                                        \
486     if (declMatchesRTFTypes(F, _ReturnType, ArgsTypes)) {                      \
487       auto &RFI = RFIs[_Enum];                                                 \
488       RFI.Kind = _Enum;                                                        \
489       RFI.Name = _Name;                                                        \
490       RFI.IsVarArg = _IsVarArg;                                                \
491       RFI.ReturnType = _ReturnType;                                            \
492       RFI.ArgumentTypes = std::move(ArgsTypes);                                \
493       RFI.Declaration = F;                                                     \
494       unsigned NumUses = CollectUses(RFI);                                     \
495       (void)NumUses;                                                           \
496       LLVM_DEBUG({                                                             \
497         dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not")           \
498                << " found\n";                                                  \
499         if (RFI.Declaration)                                                   \
500           dbgs() << TAG << "-> got " << NumUses << " uses in "                 \
501                  << RFI.getNumFunctionsWithUses()                              \
502                  << " different functions.\n";                                 \
503       });                                                                      \
504     }                                                                          \
505   }
506 #include "llvm/Frontend/OpenMP/OMPKinds.def"
507 
508     // TODO: We should attach the attributes defined in OMPKinds.def.
509   }
510 
511   /// The underyling module.
512   Module &M;
513 
514   /// The SCC we are operating on.
515   SmallVectorImpl<Function *> &SCC;
516 
517   /// The slice of the module we are allowed to look at.
518   SmallPtrSetImpl<Function *> &ModuleSlice;
519 
520   /// An OpenMP-IR-Builder instance
521   OpenMPIRBuilder OMPBuilder;
522 
523   /// Callback to update the call graph, the first argument is a removed call,
524   /// the second an optional replacement call.
525   CallGraphUpdater &CGUpdater;
526 
527   /// Map from runtime function kind to the runtime function description.
528   EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction,
529                   RuntimeFunction::OMPRTL___last>
530       RFIs;
531 };
532 } // namespace
533 
534 PreservedAnalyses OpenMPOptPass::run(LazyCallGraph::SCC &C,
535                                      CGSCCAnalysisManager &AM,
536                                      LazyCallGraph &CG, CGSCCUpdateResult &UR) {
537   if (!containsOpenMP(*C.begin()->getFunction().getParent(), OMPInModule))
538     return PreservedAnalyses::all();
539 
540   if (DisableOpenMPOptimizations)
541     return PreservedAnalyses::all();
542 
543   SmallPtrSet<Function *, 16> ModuleSlice;
544   SmallVector<Function *, 16> SCC;
545   for (LazyCallGraph::Node &N : C) {
546     SCC.push_back(&N.getFunction());
547     ModuleSlice.insert(SCC.back());
548   }
549 
550   if (SCC.empty())
551     return PreservedAnalyses::all();
552 
553   CallGraphUpdater CGUpdater;
554   CGUpdater.initialize(CG, C, AM, UR);
555   // TODO: Compute the module slice we are allowed to look at.
556   OpenMPOpt OMPOpt(SCC, ModuleSlice, CGUpdater);
557   bool Changed = OMPOpt.run();
558   (void)Changed;
559   return PreservedAnalyses::all();
560 }
561 
562 namespace {
563 
564 struct OpenMPOptLegacyPass : public CallGraphSCCPass {
565   CallGraphUpdater CGUpdater;
566   OpenMPInModule OMPInModule;
567   static char ID;
568 
569   OpenMPOptLegacyPass() : CallGraphSCCPass(ID) {
570     initializeOpenMPOptLegacyPassPass(*PassRegistry::getPassRegistry());
571   }
572 
573   void getAnalysisUsage(AnalysisUsage &AU) const override {
574     CallGraphSCCPass::getAnalysisUsage(AU);
575   }
576 
577   bool doInitialization(CallGraph &CG) override {
578     // Disable the pass if there is no OpenMP (runtime call) in the module.
579     containsOpenMP(CG.getModule(), OMPInModule);
580     return false;
581   }
582 
583   bool runOnSCC(CallGraphSCC &CGSCC) override {
584     if (!containsOpenMP(CGSCC.getCallGraph().getModule(), OMPInModule))
585       return false;
586     if (DisableOpenMPOptimizations || skipSCC(CGSCC))
587       return false;
588 
589     SmallPtrSet<Function *, 16> ModuleSlice;
590     SmallVector<Function *, 16> SCC;
591     for (CallGraphNode *CGN : CGSCC)
592       if (Function *Fn = CGN->getFunction())
593         if (!Fn->isDeclaration()) {
594           SCC.push_back(Fn);
595           ModuleSlice.insert(Fn);
596         }
597 
598     if (SCC.empty())
599       return false;
600 
601     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
602     CGUpdater.initialize(CG, CGSCC);
603 
604     // TODO: Compute the module slice we are allowed to look at.
605     OpenMPOpt OMPOpt(SCC, ModuleSlice, CGUpdater);
606     return OMPOpt.run();
607   }
608 
609   bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
610 };
611 
612 } // end anonymous namespace
613 
614 bool llvm::omp::containsOpenMP(Module &M, OpenMPInModule &OMPInModule) {
615   if (OMPInModule.isKnown())
616     return OMPInModule;
617 
618 #define OMP_RTL(_Enum, _Name, ...)                                             \
619   if (M.getFunction(_Name))                                                    \
620     return OMPInModule = true;
621 #include "llvm/Frontend/OpenMP/OMPKinds.def"
622   return OMPInModule = false;
623 }
624 
625 char OpenMPOptLegacyPass::ID = 0;
626 
627 INITIALIZE_PASS_BEGIN(OpenMPOptLegacyPass, "openmpopt",
628                       "OpenMP specific optimizations", false, false)
629 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
630 INITIALIZE_PASS_END(OpenMPOptLegacyPass, "openmpopt",
631                     "OpenMP specific optimizations", false, false)
632 
633 Pass *llvm::createOpenMPOptLegacyPass() { return new OpenMPOptLegacyPass(); }
634