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