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 // - Replacing globalized device memory with stack memory.
13 // - Replacing globalized device memory with shared memory.
14 // - Parallel region merging.
15 // - Transforming generic-mode device kernels to SPMD mode.
16 // - Specializing the state machine for generic-mode device kernels.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "llvm/Transforms/IPO/OpenMPOpt.h"
21 
22 #include "llvm/ADT/EnumeratedArray.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/Analysis/CallGraphSCCPass.h"
27 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Frontend/OpenMP/OMPConstants.h"
30 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
31 #include "llvm/IR/Assumptions.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/Instruction.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Transforms/IPO.h"
39 #include "llvm/Transforms/IPO/Attributor.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/Transforms/Utils/CallGraphUpdater.h"
42 #include "llvm/Transforms/Utils/CodeExtractor.h"
43 
44 using namespace llvm;
45 using namespace omp;
46 
47 #define DEBUG_TYPE "openmp-opt"
48 
49 static cl::opt<bool> DisableOpenMPOptimizations(
50     "openmp-opt-disable", cl::ZeroOrMore,
51     cl::desc("Disable OpenMP specific optimizations."), cl::Hidden,
52     cl::init(false));
53 
54 static cl::opt<bool> EnableParallelRegionMerging(
55     "openmp-opt-enable-merging", cl::ZeroOrMore,
56     cl::desc("Enable the OpenMP region merging optimization."), cl::Hidden,
57     cl::init(false));
58 
59 static cl::opt<bool>
60     DisableInternalization("openmp-opt-disable-internalization", cl::ZeroOrMore,
61                            cl::desc("Disable function internalization."),
62                            cl::Hidden, cl::init(false));
63 
64 static cl::opt<bool> PrintICVValues("openmp-print-icv-values", cl::init(false),
65                                     cl::Hidden);
66 static cl::opt<bool> PrintOpenMPKernels("openmp-print-gpu-kernels",
67                                         cl::init(false), cl::Hidden);
68 
69 static cl::opt<bool> HideMemoryTransferLatency(
70     "openmp-hide-memory-transfer-latency",
71     cl::desc("[WIP] Tries to hide the latency of host to device memory"
72              " transfers"),
73     cl::Hidden, cl::init(false));
74 
75 static cl::opt<bool> DisableOpenMPOptDeglobalization(
76     "openmp-opt-disable-deglobalization", cl::ZeroOrMore,
77     cl::desc("Disable OpenMP optimizations involving deglobalization."),
78     cl::Hidden, cl::init(false));
79 
80 static cl::opt<bool> DisableOpenMPOptSPMDization(
81     "openmp-opt-disable-spmdization", cl::ZeroOrMore,
82     cl::desc("Disable OpenMP optimizations involving SPMD-ization."),
83     cl::Hidden, cl::init(false));
84 
85 static cl::opt<bool> DisableOpenMPOptFolding(
86     "openmp-opt-disable-folding", cl::ZeroOrMore,
87     cl::desc("Disable OpenMP optimizations involving folding."), cl::Hidden,
88     cl::init(false));
89 
90 static cl::opt<bool> DisableOpenMPOptStateMachineRewrite(
91     "openmp-opt-disable-state-machine-rewrite", cl::ZeroOrMore,
92     cl::desc("Disable OpenMP optimizations that replace the state machine."),
93     cl::Hidden, cl::init(false));
94 
95 STATISTIC(NumOpenMPRuntimeCallsDeduplicated,
96           "Number of OpenMP runtime calls deduplicated");
97 STATISTIC(NumOpenMPParallelRegionsDeleted,
98           "Number of OpenMP parallel regions deleted");
99 STATISTIC(NumOpenMPRuntimeFunctionsIdentified,
100           "Number of OpenMP runtime functions identified");
101 STATISTIC(NumOpenMPRuntimeFunctionUsesIdentified,
102           "Number of OpenMP runtime function uses identified");
103 STATISTIC(NumOpenMPTargetRegionKernels,
104           "Number of OpenMP target region entry points (=kernels) identified");
105 STATISTIC(NumOpenMPTargetRegionKernelsSPMD,
106           "Number of OpenMP target region entry points (=kernels) executed in "
107           "SPMD-mode instead of generic-mode");
108 STATISTIC(NumOpenMPTargetRegionKernelsWithoutStateMachine,
109           "Number of OpenMP target region entry points (=kernels) executed in "
110           "generic-mode without a state machines");
111 STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback,
112           "Number of OpenMP target region entry points (=kernels) executed in "
113           "generic-mode with customized state machines with fallback");
114 STATISTIC(NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback,
115           "Number of OpenMP target region entry points (=kernels) executed in "
116           "generic-mode with customized state machines without fallback");
117 STATISTIC(
118     NumOpenMPParallelRegionsReplacedInGPUStateMachine,
119     "Number of OpenMP parallel regions replaced with ID in GPU state machines");
120 STATISTIC(NumOpenMPParallelRegionsMerged,
121           "Number of OpenMP parallel regions merged");
122 STATISTIC(NumBytesMovedToSharedMemory,
123           "Amount of memory pushed to shared memory");
124 
125 #if !defined(NDEBUG)
126 static constexpr auto TAG = "[" DEBUG_TYPE "]";
127 #endif
128 
129 namespace {
130 
131 enum class AddressSpace : unsigned {
132   Generic = 0,
133   Global = 1,
134   Shared = 3,
135   Constant = 4,
136   Local = 5,
137 };
138 
139 struct AAHeapToShared;
140 
141 struct AAICVTracker;
142 
143 /// OpenMP specific information. For now, stores RFIs and ICVs also needed for
144 /// Attributor runs.
145 struct OMPInformationCache : public InformationCache {
146   OMPInformationCache(Module &M, AnalysisGetter &AG,
147                       BumpPtrAllocator &Allocator, SetVector<Function *> &CGSCC,
148                       SmallPtrSetImpl<Kernel> &Kernels)
149       : InformationCache(M, AG, Allocator, &CGSCC), OMPBuilder(M),
150         Kernels(Kernels) {
151 
152     OMPBuilder.initialize();
153     initializeRuntimeFunctions();
154     initializeInternalControlVars();
155   }
156 
157   /// Generic information that describes an internal control variable.
158   struct InternalControlVarInfo {
159     /// The kind, as described by InternalControlVar enum.
160     InternalControlVar Kind;
161 
162     /// The name of the ICV.
163     StringRef Name;
164 
165     /// Environment variable associated with this ICV.
166     StringRef EnvVarName;
167 
168     /// Initial value kind.
169     ICVInitValue InitKind;
170 
171     /// Initial value.
172     ConstantInt *InitValue;
173 
174     /// Setter RTL function associated with this ICV.
175     RuntimeFunction Setter;
176 
177     /// Getter RTL function associated with this ICV.
178     RuntimeFunction Getter;
179 
180     /// RTL Function corresponding to the override clause of this ICV
181     RuntimeFunction Clause;
182   };
183 
184   /// Generic information that describes a runtime function
185   struct RuntimeFunctionInfo {
186 
187     /// The kind, as described by the RuntimeFunction enum.
188     RuntimeFunction Kind;
189 
190     /// The name of the function.
191     StringRef Name;
192 
193     /// Flag to indicate a variadic function.
194     bool IsVarArg;
195 
196     /// The return type of the function.
197     Type *ReturnType;
198 
199     /// The argument types of the function.
200     SmallVector<Type *, 8> ArgumentTypes;
201 
202     /// The declaration if available.
203     Function *Declaration = nullptr;
204 
205     /// Uses of this runtime function per function containing the use.
206     using UseVector = SmallVector<Use *, 16>;
207 
208     /// Clear UsesMap for runtime function.
209     void clearUsesMap() { UsesMap.clear(); }
210 
211     /// Boolean conversion that is true if the runtime function was found.
212     operator bool() const { return Declaration; }
213 
214     /// Return the vector of uses in function \p F.
215     UseVector &getOrCreateUseVector(Function *F) {
216       std::shared_ptr<UseVector> &UV = UsesMap[F];
217       if (!UV)
218         UV = std::make_shared<UseVector>();
219       return *UV;
220     }
221 
222     /// Return the vector of uses in function \p F or `nullptr` if there are
223     /// none.
224     const UseVector *getUseVector(Function &F) const {
225       auto I = UsesMap.find(&F);
226       if (I != UsesMap.end())
227         return I->second.get();
228       return nullptr;
229     }
230 
231     /// Return how many functions contain uses of this runtime function.
232     size_t getNumFunctionsWithUses() const { return UsesMap.size(); }
233 
234     /// Return the number of arguments (or the minimal number for variadic
235     /// functions).
236     size_t getNumArgs() const { return ArgumentTypes.size(); }
237 
238     /// Run the callback \p CB on each use and forget the use if the result is
239     /// true. The callback will be fed the function in which the use was
240     /// encountered as second argument.
241     void foreachUse(SmallVectorImpl<Function *> &SCC,
242                     function_ref<bool(Use &, Function &)> CB) {
243       for (Function *F : SCC)
244         foreachUse(CB, F);
245     }
246 
247     /// Run the callback \p CB on each use within the function \p F and forget
248     /// the use if the result is true.
249     void foreachUse(function_ref<bool(Use &, Function &)> CB, Function *F) {
250       SmallVector<unsigned, 8> ToBeDeleted;
251       ToBeDeleted.clear();
252 
253       unsigned Idx = 0;
254       UseVector &UV = getOrCreateUseVector(F);
255 
256       for (Use *U : UV) {
257         if (CB(*U, *F))
258           ToBeDeleted.push_back(Idx);
259         ++Idx;
260       }
261 
262       // Remove the to-be-deleted indices in reverse order as prior
263       // modifications will not modify the smaller indices.
264       while (!ToBeDeleted.empty()) {
265         unsigned Idx = ToBeDeleted.pop_back_val();
266         UV[Idx] = UV.back();
267         UV.pop_back();
268       }
269     }
270 
271   private:
272     /// Map from functions to all uses of this runtime function contained in
273     /// them.
274     DenseMap<Function *, std::shared_ptr<UseVector>> UsesMap;
275 
276   public:
277     /// Iterators for the uses of this runtime function.
278     decltype(UsesMap)::iterator begin() { return UsesMap.begin(); }
279     decltype(UsesMap)::iterator end() { return UsesMap.end(); }
280   };
281 
282   /// An OpenMP-IR-Builder instance
283   OpenMPIRBuilder OMPBuilder;
284 
285   /// Map from runtime function kind to the runtime function description.
286   EnumeratedArray<RuntimeFunctionInfo, RuntimeFunction,
287                   RuntimeFunction::OMPRTL___last>
288       RFIs;
289 
290   /// Map from function declarations/definitions to their runtime enum type.
291   DenseMap<Function *, RuntimeFunction> RuntimeFunctionIDMap;
292 
293   /// Map from ICV kind to the ICV description.
294   EnumeratedArray<InternalControlVarInfo, InternalControlVar,
295                   InternalControlVar::ICV___last>
296       ICVs;
297 
298   /// Helper to initialize all internal control variable information for those
299   /// defined in OMPKinds.def.
300   void initializeInternalControlVars() {
301 #define ICV_RT_SET(_Name, RTL)                                                 \
302   {                                                                            \
303     auto &ICV = ICVs[_Name];                                                   \
304     ICV.Setter = RTL;                                                          \
305   }
306 #define ICV_RT_GET(Name, RTL)                                                  \
307   {                                                                            \
308     auto &ICV = ICVs[Name];                                                    \
309     ICV.Getter = RTL;                                                          \
310   }
311 #define ICV_DATA_ENV(Enum, _Name, _EnvVarName, Init)                           \
312   {                                                                            \
313     auto &ICV = ICVs[Enum];                                                    \
314     ICV.Name = _Name;                                                          \
315     ICV.Kind = Enum;                                                           \
316     ICV.InitKind = Init;                                                       \
317     ICV.EnvVarName = _EnvVarName;                                              \
318     switch (ICV.InitKind) {                                                    \
319     case ICV_IMPLEMENTATION_DEFINED:                                           \
320       ICV.InitValue = nullptr;                                                 \
321       break;                                                                   \
322     case ICV_ZERO:                                                             \
323       ICV.InitValue = ConstantInt::get(                                        \
324           Type::getInt32Ty(OMPBuilder.Int32->getContext()), 0);                \
325       break;                                                                   \
326     case ICV_FALSE:                                                            \
327       ICV.InitValue = ConstantInt::getFalse(OMPBuilder.Int1->getContext());    \
328       break;                                                                   \
329     case ICV_LAST:                                                             \
330       break;                                                                   \
331     }                                                                          \
332   }
333 #include "llvm/Frontend/OpenMP/OMPKinds.def"
334   }
335 
336   /// Returns true if the function declaration \p F matches the runtime
337   /// function types, that is, return type \p RTFRetType, and argument types
338   /// \p RTFArgTypes.
339   static bool declMatchesRTFTypes(Function *F, Type *RTFRetType,
340                                   SmallVector<Type *, 8> &RTFArgTypes) {
341     // TODO: We should output information to the user (under debug output
342     //       and via remarks).
343 
344     if (!F)
345       return false;
346     if (F->getReturnType() != RTFRetType)
347       return false;
348     if (F->arg_size() != RTFArgTypes.size())
349       return false;
350 
351     auto RTFTyIt = RTFArgTypes.begin();
352     for (Argument &Arg : F->args()) {
353       if (Arg.getType() != *RTFTyIt)
354         return false;
355 
356       ++RTFTyIt;
357     }
358 
359     return true;
360   }
361 
362   // Helper to collect all uses of the declaration in the UsesMap.
363   unsigned collectUses(RuntimeFunctionInfo &RFI, bool CollectStats = true) {
364     unsigned NumUses = 0;
365     if (!RFI.Declaration)
366       return NumUses;
367     OMPBuilder.addAttributes(RFI.Kind, *RFI.Declaration);
368 
369     if (CollectStats) {
370       NumOpenMPRuntimeFunctionsIdentified += 1;
371       NumOpenMPRuntimeFunctionUsesIdentified += RFI.Declaration->getNumUses();
372     }
373 
374     // TODO: We directly convert uses into proper calls and unknown uses.
375     for (Use &U : RFI.Declaration->uses()) {
376       if (Instruction *UserI = dyn_cast<Instruction>(U.getUser())) {
377         if (ModuleSlice.count(UserI->getFunction())) {
378           RFI.getOrCreateUseVector(UserI->getFunction()).push_back(&U);
379           ++NumUses;
380         }
381       } else {
382         RFI.getOrCreateUseVector(nullptr).push_back(&U);
383         ++NumUses;
384       }
385     }
386     return NumUses;
387   }
388 
389   // Helper function to recollect uses of a runtime function.
390   void recollectUsesForFunction(RuntimeFunction RTF) {
391     auto &RFI = RFIs[RTF];
392     RFI.clearUsesMap();
393     collectUses(RFI, /*CollectStats*/ false);
394   }
395 
396   // Helper function to recollect uses of all runtime functions.
397   void recollectUses() {
398     for (int Idx = 0; Idx < RFIs.size(); ++Idx)
399       recollectUsesForFunction(static_cast<RuntimeFunction>(Idx));
400   }
401 
402   /// Helper to initialize all runtime function information for those defined
403   /// in OpenMPKinds.def.
404   void initializeRuntimeFunctions() {
405     Module &M = *((*ModuleSlice.begin())->getParent());
406 
407     // Helper macros for handling __VA_ARGS__ in OMP_RTL
408 #define OMP_TYPE(VarName, ...)                                                 \
409   Type *VarName = OMPBuilder.VarName;                                          \
410   (void)VarName;
411 
412 #define OMP_ARRAY_TYPE(VarName, ...)                                           \
413   ArrayType *VarName##Ty = OMPBuilder.VarName##Ty;                             \
414   (void)VarName##Ty;                                                           \
415   PointerType *VarName##PtrTy = OMPBuilder.VarName##PtrTy;                     \
416   (void)VarName##PtrTy;
417 
418 #define OMP_FUNCTION_TYPE(VarName, ...)                                        \
419   FunctionType *VarName = OMPBuilder.VarName;                                  \
420   (void)VarName;                                                               \
421   PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr;                         \
422   (void)VarName##Ptr;
423 
424 #define OMP_STRUCT_TYPE(VarName, ...)                                          \
425   StructType *VarName = OMPBuilder.VarName;                                    \
426   (void)VarName;                                                               \
427   PointerType *VarName##Ptr = OMPBuilder.VarName##Ptr;                         \
428   (void)VarName##Ptr;
429 
430 #define OMP_RTL(_Enum, _Name, _IsVarArg, _ReturnType, ...)                     \
431   {                                                                            \
432     SmallVector<Type *, 8> ArgsTypes({__VA_ARGS__});                           \
433     Function *F = M.getFunction(_Name);                                        \
434     RTLFunctions.insert(F);                                                    \
435     if (declMatchesRTFTypes(F, OMPBuilder._ReturnType, ArgsTypes)) {           \
436       RuntimeFunctionIDMap[F] = _Enum;                                         \
437       F->removeFnAttr(Attribute::NoInline);                                    \
438       auto &RFI = RFIs[_Enum];                                                 \
439       RFI.Kind = _Enum;                                                        \
440       RFI.Name = _Name;                                                        \
441       RFI.IsVarArg = _IsVarArg;                                                \
442       RFI.ReturnType = OMPBuilder._ReturnType;                                 \
443       RFI.ArgumentTypes = std::move(ArgsTypes);                                \
444       RFI.Declaration = F;                                                     \
445       unsigned NumUses = collectUses(RFI);                                     \
446       (void)NumUses;                                                           \
447       LLVM_DEBUG({                                                             \
448         dbgs() << TAG << RFI.Name << (RFI.Declaration ? "" : " not")           \
449                << " found\n";                                                  \
450         if (RFI.Declaration)                                                   \
451           dbgs() << TAG << "-> got " << NumUses << " uses in "                 \
452                  << RFI.getNumFunctionsWithUses()                              \
453                  << " different functions.\n";                                 \
454       });                                                                      \
455     }                                                                          \
456   }
457 #include "llvm/Frontend/OpenMP/OMPKinds.def"
458 
459     // TODO: We should attach the attributes defined in OMPKinds.def.
460   }
461 
462   /// Collection of known kernels (\see Kernel) in the module.
463   SmallPtrSetImpl<Kernel> &Kernels;
464 
465   /// Collection of known OpenMP runtime functions..
466   DenseSet<const Function *> RTLFunctions;
467 };
468 
469 template <typename Ty, bool InsertInvalidates = true>
470 struct BooleanStateWithSetVector : public BooleanState {
471   bool contains(const Ty &Elem) const { return Set.contains(Elem); }
472   bool insert(const Ty &Elem) {
473     if (InsertInvalidates)
474       BooleanState::indicatePessimisticFixpoint();
475     return Set.insert(Elem);
476   }
477 
478   const Ty &operator[](int Idx) const { return Set[Idx]; }
479   bool operator==(const BooleanStateWithSetVector &RHS) const {
480     return BooleanState::operator==(RHS) && Set == RHS.Set;
481   }
482   bool operator!=(const BooleanStateWithSetVector &RHS) const {
483     return !(*this == RHS);
484   }
485 
486   bool empty() const { return Set.empty(); }
487   size_t size() const { return Set.size(); }
488 
489   /// "Clamp" this state with \p RHS.
490   BooleanStateWithSetVector &operator^=(const BooleanStateWithSetVector &RHS) {
491     BooleanState::operator^=(RHS);
492     Set.insert(RHS.Set.begin(), RHS.Set.end());
493     return *this;
494   }
495 
496 private:
497   /// A set to keep track of elements.
498   SetVector<Ty> Set;
499 
500 public:
501   typename decltype(Set)::iterator begin() { return Set.begin(); }
502   typename decltype(Set)::iterator end() { return Set.end(); }
503   typename decltype(Set)::const_iterator begin() const { return Set.begin(); }
504   typename decltype(Set)::const_iterator end() const { return Set.end(); }
505 };
506 
507 template <typename Ty, bool InsertInvalidates = true>
508 using BooleanStateWithPtrSetVector =
509     BooleanStateWithSetVector<Ty *, InsertInvalidates>;
510 
511 struct KernelInfoState : AbstractState {
512   /// Flag to track if we reached a fixpoint.
513   bool IsAtFixpoint = false;
514 
515   /// The parallel regions (identified by the outlined parallel functions) that
516   /// can be reached from the associated function.
517   BooleanStateWithPtrSetVector<Function, /* InsertInvalidates */ false>
518       ReachedKnownParallelRegions;
519 
520   /// State to track what parallel region we might reach.
521   BooleanStateWithPtrSetVector<CallBase> ReachedUnknownParallelRegions;
522 
523   /// State to track if we are in SPMD-mode, assumed or know, and why we decided
524   /// we cannot be. If it is assumed, then RequiresFullRuntime should also be
525   /// false.
526   BooleanStateWithPtrSetVector<Instruction> SPMDCompatibilityTracker;
527 
528   /// The __kmpc_target_init call in this kernel, if any. If we find more than
529   /// one we abort as the kernel is malformed.
530   CallBase *KernelInitCB = nullptr;
531 
532   /// The __kmpc_target_deinit call in this kernel, if any. If we find more than
533   /// one we abort as the kernel is malformed.
534   CallBase *KernelDeinitCB = nullptr;
535 
536   /// Flag to indicate if the associated function is a kernel entry.
537   bool IsKernelEntry = false;
538 
539   /// State to track what kernel entries can reach the associated function.
540   BooleanStateWithPtrSetVector<Function, false> ReachingKernelEntries;
541 
542   /// State to indicate if we can track parallel level of the associated
543   /// function. We will give up tracking if we encounter unknown caller or the
544   /// caller is __kmpc_parallel_51.
545   BooleanStateWithSetVector<uint8_t> ParallelLevels;
546 
547   /// Abstract State interface
548   ///{
549 
550   KernelInfoState() {}
551   KernelInfoState(bool BestState) {
552     if (!BestState)
553       indicatePessimisticFixpoint();
554   }
555 
556   /// See AbstractState::isValidState(...)
557   bool isValidState() const override { return true; }
558 
559   /// See AbstractState::isAtFixpoint(...)
560   bool isAtFixpoint() const override { return IsAtFixpoint; }
561 
562   /// See AbstractState::indicatePessimisticFixpoint(...)
563   ChangeStatus indicatePessimisticFixpoint() override {
564     IsAtFixpoint = true;
565     SPMDCompatibilityTracker.indicatePessimisticFixpoint();
566     ReachedUnknownParallelRegions.indicatePessimisticFixpoint();
567     return ChangeStatus::CHANGED;
568   }
569 
570   /// See AbstractState::indicateOptimisticFixpoint(...)
571   ChangeStatus indicateOptimisticFixpoint() override {
572     IsAtFixpoint = true;
573     return ChangeStatus::UNCHANGED;
574   }
575 
576   /// Return the assumed state
577   KernelInfoState &getAssumed() { return *this; }
578   const KernelInfoState &getAssumed() const { return *this; }
579 
580   bool operator==(const KernelInfoState &RHS) const {
581     if (SPMDCompatibilityTracker != RHS.SPMDCompatibilityTracker)
582       return false;
583     if (ReachedKnownParallelRegions != RHS.ReachedKnownParallelRegions)
584       return false;
585     if (ReachedUnknownParallelRegions != RHS.ReachedUnknownParallelRegions)
586       return false;
587     if (ReachingKernelEntries != RHS.ReachingKernelEntries)
588       return false;
589     return true;
590   }
591 
592   /// Return empty set as the best state of potential values.
593   static KernelInfoState getBestState() { return KernelInfoState(true); }
594 
595   static KernelInfoState getBestState(KernelInfoState &KIS) {
596     return getBestState();
597   }
598 
599   /// Return full set as the worst state of potential values.
600   static KernelInfoState getWorstState() { return KernelInfoState(false); }
601 
602   /// "Clamp" this state with \p KIS.
603   KernelInfoState operator^=(const KernelInfoState &KIS) {
604     // Do not merge two different _init and _deinit call sites.
605     if (KIS.KernelInitCB) {
606       if (KernelInitCB && KernelInitCB != KIS.KernelInitCB)
607         indicatePessimisticFixpoint();
608       KernelInitCB = KIS.KernelInitCB;
609     }
610     if (KIS.KernelDeinitCB) {
611       if (KernelDeinitCB && KernelDeinitCB != KIS.KernelDeinitCB)
612         indicatePessimisticFixpoint();
613       KernelDeinitCB = KIS.KernelDeinitCB;
614     }
615     SPMDCompatibilityTracker ^= KIS.SPMDCompatibilityTracker;
616     ReachedKnownParallelRegions ^= KIS.ReachedKnownParallelRegions;
617     ReachedUnknownParallelRegions ^= KIS.ReachedUnknownParallelRegions;
618     return *this;
619   }
620 
621   KernelInfoState operator&=(const KernelInfoState &KIS) {
622     return (*this ^= KIS);
623   }
624 
625   ///}
626 };
627 
628 /// Used to map the values physically (in the IR) stored in an offload
629 /// array, to a vector in memory.
630 struct OffloadArray {
631   /// Physical array (in the IR).
632   AllocaInst *Array = nullptr;
633   /// Mapped values.
634   SmallVector<Value *, 8> StoredValues;
635   /// Last stores made in the offload array.
636   SmallVector<StoreInst *, 8> LastAccesses;
637 
638   OffloadArray() = default;
639 
640   /// Initializes the OffloadArray with the values stored in \p Array before
641   /// instruction \p Before is reached. Returns false if the initialization
642   /// fails.
643   /// This MUST be used immediately after the construction of the object.
644   bool initialize(AllocaInst &Array, Instruction &Before) {
645     if (!Array.getAllocatedType()->isArrayTy())
646       return false;
647 
648     if (!getValues(Array, Before))
649       return false;
650 
651     this->Array = &Array;
652     return true;
653   }
654 
655   static const unsigned DeviceIDArgNum = 1;
656   static const unsigned BasePtrsArgNum = 3;
657   static const unsigned PtrsArgNum = 4;
658   static const unsigned SizesArgNum = 5;
659 
660 private:
661   /// Traverses the BasicBlock where \p Array is, collecting the stores made to
662   /// \p Array, leaving StoredValues with the values stored before the
663   /// instruction \p Before is reached.
664   bool getValues(AllocaInst &Array, Instruction &Before) {
665     // Initialize container.
666     const uint64_t NumValues = Array.getAllocatedType()->getArrayNumElements();
667     StoredValues.assign(NumValues, nullptr);
668     LastAccesses.assign(NumValues, nullptr);
669 
670     // TODO: This assumes the instruction \p Before is in the same
671     //  BasicBlock as Array. Make it general, for any control flow graph.
672     BasicBlock *BB = Array.getParent();
673     if (BB != Before.getParent())
674       return false;
675 
676     const DataLayout &DL = Array.getModule()->getDataLayout();
677     const unsigned int PointerSize = DL.getPointerSize();
678 
679     for (Instruction &I : *BB) {
680       if (&I == &Before)
681         break;
682 
683       if (!isa<StoreInst>(&I))
684         continue;
685 
686       auto *S = cast<StoreInst>(&I);
687       int64_t Offset = -1;
688       auto *Dst =
689           GetPointerBaseWithConstantOffset(S->getPointerOperand(), Offset, DL);
690       if (Dst == &Array) {
691         int64_t Idx = Offset / PointerSize;
692         StoredValues[Idx] = getUnderlyingObject(S->getValueOperand());
693         LastAccesses[Idx] = S;
694       }
695     }
696 
697     return isFilled();
698   }
699 
700   /// Returns true if all values in StoredValues and
701   /// LastAccesses are not nullptrs.
702   bool isFilled() {
703     const unsigned NumValues = StoredValues.size();
704     for (unsigned I = 0; I < NumValues; ++I) {
705       if (!StoredValues[I] || !LastAccesses[I])
706         return false;
707     }
708 
709     return true;
710   }
711 };
712 
713 struct OpenMPOpt {
714 
715   using OptimizationRemarkGetter =
716       function_ref<OptimizationRemarkEmitter &(Function *)>;
717 
718   OpenMPOpt(SmallVectorImpl<Function *> &SCC, CallGraphUpdater &CGUpdater,
719             OptimizationRemarkGetter OREGetter,
720             OMPInformationCache &OMPInfoCache, Attributor &A)
721       : M(*(*SCC.begin())->getParent()), SCC(SCC), CGUpdater(CGUpdater),
722         OREGetter(OREGetter), OMPInfoCache(OMPInfoCache), A(A) {}
723 
724   /// Check if any remarks are enabled for openmp-opt
725   bool remarksEnabled() {
726     auto &Ctx = M.getContext();
727     return Ctx.getDiagHandlerPtr()->isAnyRemarkEnabled(DEBUG_TYPE);
728   }
729 
730   /// Run all OpenMP optimizations on the underlying SCC/ModuleSlice.
731   bool run(bool IsModulePass) {
732     if (SCC.empty())
733       return false;
734 
735     bool Changed = false;
736 
737     LLVM_DEBUG(dbgs() << TAG << "Run on SCC with " << SCC.size()
738                       << " functions in a slice with "
739                       << OMPInfoCache.ModuleSlice.size() << " functions\n");
740 
741     if (IsModulePass) {
742       Changed |= runAttributor(IsModulePass);
743 
744       // Recollect uses, in case Attributor deleted any.
745       OMPInfoCache.recollectUses();
746 
747       // TODO: This should be folded into buildCustomStateMachine.
748       Changed |= rewriteDeviceCodeStateMachine();
749 
750       if (remarksEnabled())
751         analysisGlobalization();
752     } else {
753       if (PrintICVValues)
754         printICVs();
755       if (PrintOpenMPKernels)
756         printKernels();
757 
758       Changed |= runAttributor(IsModulePass);
759 
760       // Recollect uses, in case Attributor deleted any.
761       OMPInfoCache.recollectUses();
762 
763       Changed |= deleteParallelRegions();
764 
765       if (HideMemoryTransferLatency)
766         Changed |= hideMemTransfersLatency();
767       Changed |= deduplicateRuntimeCalls();
768       if (EnableParallelRegionMerging) {
769         if (mergeParallelRegions()) {
770           deduplicateRuntimeCalls();
771           Changed = true;
772         }
773       }
774     }
775 
776     return Changed;
777   }
778 
779   /// Print initial ICV values for testing.
780   /// FIXME: This should be done from the Attributor once it is added.
781   void printICVs() const {
782     InternalControlVar ICVs[] = {ICV_nthreads, ICV_active_levels, ICV_cancel,
783                                  ICV_proc_bind};
784 
785     for (Function *F : OMPInfoCache.ModuleSlice) {
786       for (auto ICV : ICVs) {
787         auto ICVInfo = OMPInfoCache.ICVs[ICV];
788         auto Remark = [&](OptimizationRemarkAnalysis ORA) {
789           return ORA << "OpenMP ICV " << ore::NV("OpenMPICV", ICVInfo.Name)
790                      << " Value: "
791                      << (ICVInfo.InitValue
792                              ? toString(ICVInfo.InitValue->getValue(), 10, true)
793                              : "IMPLEMENTATION_DEFINED");
794         };
795 
796         emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPICVTracker", Remark);
797       }
798     }
799   }
800 
801   /// Print OpenMP GPU kernels for testing.
802   void printKernels() const {
803     for (Function *F : SCC) {
804       if (!OMPInfoCache.Kernels.count(F))
805         continue;
806 
807       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
808         return ORA << "OpenMP GPU kernel "
809                    << ore::NV("OpenMPGPUKernel", F->getName()) << "\n";
810       };
811 
812       emitRemark<OptimizationRemarkAnalysis>(F, "OpenMPGPU", Remark);
813     }
814   }
815 
816   /// Return the call if \p U is a callee use in a regular call. If \p RFI is
817   /// given it has to be the callee or a nullptr is returned.
818   static CallInst *getCallIfRegularCall(
819       Use &U, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) {
820     CallInst *CI = dyn_cast<CallInst>(U.getUser());
821     if (CI && CI->isCallee(&U) && !CI->hasOperandBundles() &&
822         (!RFI ||
823          (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration)))
824       return CI;
825     return nullptr;
826   }
827 
828   /// Return the call if \p V is a regular call. If \p RFI is given it has to be
829   /// the callee or a nullptr is returned.
830   static CallInst *getCallIfRegularCall(
831       Value &V, OMPInformationCache::RuntimeFunctionInfo *RFI = nullptr) {
832     CallInst *CI = dyn_cast<CallInst>(&V);
833     if (CI && !CI->hasOperandBundles() &&
834         (!RFI ||
835          (RFI->Declaration && CI->getCalledFunction() == RFI->Declaration)))
836       return CI;
837     return nullptr;
838   }
839 
840 private:
841   /// Merge parallel regions when it is safe.
842   bool mergeParallelRegions() {
843     const unsigned CallbackCalleeOperand = 2;
844     const unsigned CallbackFirstArgOperand = 3;
845     using InsertPointTy = OpenMPIRBuilder::InsertPointTy;
846 
847     // Check if there are any __kmpc_fork_call calls to merge.
848     OMPInformationCache::RuntimeFunctionInfo &RFI =
849         OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call];
850 
851     if (!RFI.Declaration)
852       return false;
853 
854     // Unmergable calls that prevent merging a parallel region.
855     OMPInformationCache::RuntimeFunctionInfo UnmergableCallsInfo[] = {
856         OMPInfoCache.RFIs[OMPRTL___kmpc_push_proc_bind],
857         OMPInfoCache.RFIs[OMPRTL___kmpc_push_num_threads],
858     };
859 
860     bool Changed = false;
861     LoopInfo *LI = nullptr;
862     DominatorTree *DT = nullptr;
863 
864     SmallDenseMap<BasicBlock *, SmallPtrSet<Instruction *, 4>> BB2PRMap;
865 
866     BasicBlock *StartBB = nullptr, *EndBB = nullptr;
867     auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
868                          BasicBlock &ContinuationIP) {
869       BasicBlock *CGStartBB = CodeGenIP.getBlock();
870       BasicBlock *CGEndBB =
871           SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI);
872       assert(StartBB != nullptr && "StartBB should not be null");
873       CGStartBB->getTerminator()->setSuccessor(0, StartBB);
874       assert(EndBB != nullptr && "EndBB should not be null");
875       EndBB->getTerminator()->setSuccessor(0, CGEndBB);
876     };
877 
878     auto PrivCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &,
879                       Value &Inner, Value *&ReplacementValue) -> InsertPointTy {
880       ReplacementValue = &Inner;
881       return CodeGenIP;
882     };
883 
884     auto FiniCB = [&](InsertPointTy CodeGenIP) {};
885 
886     /// Create a sequential execution region within a merged parallel region,
887     /// encapsulated in a master construct with a barrier for synchronization.
888     auto CreateSequentialRegion = [&](Function *OuterFn,
889                                       BasicBlock *OuterPredBB,
890                                       Instruction *SeqStartI,
891                                       Instruction *SeqEndI) {
892       // Isolate the instructions of the sequential region to a separate
893       // block.
894       BasicBlock *ParentBB = SeqStartI->getParent();
895       BasicBlock *SeqEndBB =
896           SplitBlock(ParentBB, SeqEndI->getNextNode(), DT, LI);
897       BasicBlock *SeqAfterBB =
898           SplitBlock(SeqEndBB, &*SeqEndBB->getFirstInsertionPt(), DT, LI);
899       BasicBlock *SeqStartBB =
900           SplitBlock(ParentBB, SeqStartI, DT, LI, nullptr, "seq.par.merged");
901 
902       assert(ParentBB->getUniqueSuccessor() == SeqStartBB &&
903              "Expected a different CFG");
904       const DebugLoc DL = ParentBB->getTerminator()->getDebugLoc();
905       ParentBB->getTerminator()->eraseFromParent();
906 
907       auto BodyGenCB = [&](InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
908                            BasicBlock &ContinuationIP) {
909         BasicBlock *CGStartBB = CodeGenIP.getBlock();
910         BasicBlock *CGEndBB =
911             SplitBlock(CGStartBB, &*CodeGenIP.getPoint(), DT, LI);
912         assert(SeqStartBB != nullptr && "SeqStartBB should not be null");
913         CGStartBB->getTerminator()->setSuccessor(0, SeqStartBB);
914         assert(SeqEndBB != nullptr && "SeqEndBB should not be null");
915         SeqEndBB->getTerminator()->setSuccessor(0, CGEndBB);
916       };
917       auto FiniCB = [&](InsertPointTy CodeGenIP) {};
918 
919       // Find outputs from the sequential region to outside users and
920       // broadcast their values to them.
921       for (Instruction &I : *SeqStartBB) {
922         SmallPtrSet<Instruction *, 4> OutsideUsers;
923         for (User *Usr : I.users()) {
924           Instruction &UsrI = *cast<Instruction>(Usr);
925           // Ignore outputs to LT intrinsics, code extraction for the merged
926           // parallel region will fix them.
927           if (UsrI.isLifetimeStartOrEnd())
928             continue;
929 
930           if (UsrI.getParent() != SeqStartBB)
931             OutsideUsers.insert(&UsrI);
932         }
933 
934         if (OutsideUsers.empty())
935           continue;
936 
937         // Emit an alloca in the outer region to store the broadcasted
938         // value.
939         const DataLayout &DL = M.getDataLayout();
940         AllocaInst *AllocaI = new AllocaInst(
941             I.getType(), DL.getAllocaAddrSpace(), nullptr,
942             I.getName() + ".seq.output.alloc", &OuterFn->front().front());
943 
944         // Emit a store instruction in the sequential BB to update the
945         // value.
946         new StoreInst(&I, AllocaI, SeqStartBB->getTerminator());
947 
948         // Emit a load instruction and replace the use of the output value
949         // with it.
950         for (Instruction *UsrI : OutsideUsers) {
951           LoadInst *LoadI = new LoadInst(
952               I.getType(), AllocaI, I.getName() + ".seq.output.load", UsrI);
953           UsrI->replaceUsesOfWith(&I, LoadI);
954         }
955       }
956 
957       OpenMPIRBuilder::LocationDescription Loc(
958           InsertPointTy(ParentBB, ParentBB->end()), DL);
959       InsertPointTy SeqAfterIP =
960           OMPInfoCache.OMPBuilder.createMaster(Loc, BodyGenCB, FiniCB);
961 
962       OMPInfoCache.OMPBuilder.createBarrier(SeqAfterIP, OMPD_parallel);
963 
964       BranchInst::Create(SeqAfterBB, SeqAfterIP.getBlock());
965 
966       LLVM_DEBUG(dbgs() << TAG << "After sequential inlining " << *OuterFn
967                         << "\n");
968     };
969 
970     // Helper to merge the __kmpc_fork_call calls in MergableCIs. They are all
971     // contained in BB and only separated by instructions that can be
972     // redundantly executed in parallel. The block BB is split before the first
973     // call (in MergableCIs) and after the last so the entire region we merge
974     // into a single parallel region is contained in a single basic block
975     // without any other instructions. We use the OpenMPIRBuilder to outline
976     // that block and call the resulting function via __kmpc_fork_call.
977     auto Merge = [&](SmallVectorImpl<CallInst *> &MergableCIs, BasicBlock *BB) {
978       // TODO: Change the interface to allow single CIs expanded, e.g, to
979       // include an outer loop.
980       assert(MergableCIs.size() > 1 && "Assumed multiple mergable CIs");
981 
982       auto Remark = [&](OptimizationRemark OR) {
983         OR << "Parallel region merged with parallel region"
984            << (MergableCIs.size() > 2 ? "s" : "") << " at ";
985         for (auto *CI : llvm::drop_begin(MergableCIs)) {
986           OR << ore::NV("OpenMPParallelMerge", CI->getDebugLoc());
987           if (CI != MergableCIs.back())
988             OR << ", ";
989         }
990         return OR << ".";
991       };
992 
993       emitRemark<OptimizationRemark>(MergableCIs.front(), "OMP150", Remark);
994 
995       Function *OriginalFn = BB->getParent();
996       LLVM_DEBUG(dbgs() << TAG << "Merge " << MergableCIs.size()
997                         << " parallel regions in " << OriginalFn->getName()
998                         << "\n");
999 
1000       // Isolate the calls to merge in a separate block.
1001       EndBB = SplitBlock(BB, MergableCIs.back()->getNextNode(), DT, LI);
1002       BasicBlock *AfterBB =
1003           SplitBlock(EndBB, &*EndBB->getFirstInsertionPt(), DT, LI);
1004       StartBB = SplitBlock(BB, MergableCIs.front(), DT, LI, nullptr,
1005                            "omp.par.merged");
1006 
1007       assert(BB->getUniqueSuccessor() == StartBB && "Expected a different CFG");
1008       const DebugLoc DL = BB->getTerminator()->getDebugLoc();
1009       BB->getTerminator()->eraseFromParent();
1010 
1011       // Create sequential regions for sequential instructions that are
1012       // in-between mergable parallel regions.
1013       for (auto *It = MergableCIs.begin(), *End = MergableCIs.end() - 1;
1014            It != End; ++It) {
1015         Instruction *ForkCI = *It;
1016         Instruction *NextForkCI = *(It + 1);
1017 
1018         // Continue if there are not in-between instructions.
1019         if (ForkCI->getNextNode() == NextForkCI)
1020           continue;
1021 
1022         CreateSequentialRegion(OriginalFn, BB, ForkCI->getNextNode(),
1023                                NextForkCI->getPrevNode());
1024       }
1025 
1026       OpenMPIRBuilder::LocationDescription Loc(InsertPointTy(BB, BB->end()),
1027                                                DL);
1028       IRBuilder<>::InsertPoint AllocaIP(
1029           &OriginalFn->getEntryBlock(),
1030           OriginalFn->getEntryBlock().getFirstInsertionPt());
1031       // Create the merged parallel region with default proc binding, to
1032       // avoid overriding binding settings, and without explicit cancellation.
1033       InsertPointTy AfterIP = OMPInfoCache.OMPBuilder.createParallel(
1034           Loc, AllocaIP, BodyGenCB, PrivCB, FiniCB, nullptr, nullptr,
1035           OMP_PROC_BIND_default, /* IsCancellable */ false);
1036       BranchInst::Create(AfterBB, AfterIP.getBlock());
1037 
1038       // Perform the actual outlining.
1039       OMPInfoCache.OMPBuilder.finalize(OriginalFn,
1040                                        /* AllowExtractorSinking */ true);
1041 
1042       Function *OutlinedFn = MergableCIs.front()->getCaller();
1043 
1044       // Replace the __kmpc_fork_call calls with direct calls to the outlined
1045       // callbacks.
1046       SmallVector<Value *, 8> Args;
1047       for (auto *CI : MergableCIs) {
1048         Value *Callee =
1049             CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts();
1050         FunctionType *FT =
1051             cast<FunctionType>(Callee->getType()->getPointerElementType());
1052         Args.clear();
1053         Args.push_back(OutlinedFn->getArg(0));
1054         Args.push_back(OutlinedFn->getArg(1));
1055         for (unsigned U = CallbackFirstArgOperand, E = CI->getNumArgOperands();
1056              U < E; ++U)
1057           Args.push_back(CI->getArgOperand(U));
1058 
1059         CallInst *NewCI = CallInst::Create(FT, Callee, Args, "", CI);
1060         if (CI->getDebugLoc())
1061           NewCI->setDebugLoc(CI->getDebugLoc());
1062 
1063         // Forward parameter attributes from the callback to the callee.
1064         for (unsigned U = CallbackFirstArgOperand, E = CI->getNumArgOperands();
1065              U < E; ++U)
1066           for (const Attribute &A : CI->getAttributes().getParamAttributes(U))
1067             NewCI->addParamAttr(
1068                 U - (CallbackFirstArgOperand - CallbackCalleeOperand), A);
1069 
1070         // Emit an explicit barrier to replace the implicit fork-join barrier.
1071         if (CI != MergableCIs.back()) {
1072           // TODO: Remove barrier if the merged parallel region includes the
1073           // 'nowait' clause.
1074           OMPInfoCache.OMPBuilder.createBarrier(
1075               InsertPointTy(NewCI->getParent(),
1076                             NewCI->getNextNode()->getIterator()),
1077               OMPD_parallel);
1078         }
1079 
1080         CI->eraseFromParent();
1081       }
1082 
1083       assert(OutlinedFn != OriginalFn && "Outlining failed");
1084       CGUpdater.registerOutlinedFunction(*OriginalFn, *OutlinedFn);
1085       CGUpdater.reanalyzeFunction(*OriginalFn);
1086 
1087       NumOpenMPParallelRegionsMerged += MergableCIs.size();
1088 
1089       return true;
1090     };
1091 
1092     // Helper function that identifes sequences of
1093     // __kmpc_fork_call uses in a basic block.
1094     auto DetectPRsCB = [&](Use &U, Function &F) {
1095       CallInst *CI = getCallIfRegularCall(U, &RFI);
1096       BB2PRMap[CI->getParent()].insert(CI);
1097 
1098       return false;
1099     };
1100 
1101     BB2PRMap.clear();
1102     RFI.foreachUse(SCC, DetectPRsCB);
1103     SmallVector<SmallVector<CallInst *, 4>, 4> MergableCIsVector;
1104     // Find mergable parallel regions within a basic block that are
1105     // safe to merge, that is any in-between instructions can safely
1106     // execute in parallel after merging.
1107     // TODO: support merging across basic-blocks.
1108     for (auto &It : BB2PRMap) {
1109       auto &CIs = It.getSecond();
1110       if (CIs.size() < 2)
1111         continue;
1112 
1113       BasicBlock *BB = It.getFirst();
1114       SmallVector<CallInst *, 4> MergableCIs;
1115 
1116       /// Returns true if the instruction is mergable, false otherwise.
1117       /// A terminator instruction is unmergable by definition since merging
1118       /// works within a BB. Instructions before the mergable region are
1119       /// mergable if they are not calls to OpenMP runtime functions that may
1120       /// set different execution parameters for subsequent parallel regions.
1121       /// Instructions in-between parallel regions are mergable if they are not
1122       /// calls to any non-intrinsic function since that may call a non-mergable
1123       /// OpenMP runtime function.
1124       auto IsMergable = [&](Instruction &I, bool IsBeforeMergableRegion) {
1125         // We do not merge across BBs, hence return false (unmergable) if the
1126         // instruction is a terminator.
1127         if (I.isTerminator())
1128           return false;
1129 
1130         if (!isa<CallInst>(&I))
1131           return true;
1132 
1133         CallInst *CI = cast<CallInst>(&I);
1134         if (IsBeforeMergableRegion) {
1135           Function *CalledFunction = CI->getCalledFunction();
1136           if (!CalledFunction)
1137             return false;
1138           // Return false (unmergable) if the call before the parallel
1139           // region calls an explicit affinity (proc_bind) or number of
1140           // threads (num_threads) compiler-generated function. Those settings
1141           // may be incompatible with following parallel regions.
1142           // TODO: ICV tracking to detect compatibility.
1143           for (const auto &RFI : UnmergableCallsInfo) {
1144             if (CalledFunction == RFI.Declaration)
1145               return false;
1146           }
1147         } else {
1148           // Return false (unmergable) if there is a call instruction
1149           // in-between parallel regions when it is not an intrinsic. It
1150           // may call an unmergable OpenMP runtime function in its callpath.
1151           // TODO: Keep track of possible OpenMP calls in the callpath.
1152           if (!isa<IntrinsicInst>(CI))
1153             return false;
1154         }
1155 
1156         return true;
1157       };
1158       // Find maximal number of parallel region CIs that are safe to merge.
1159       for (auto It = BB->begin(), End = BB->end(); It != End;) {
1160         Instruction &I = *It;
1161         ++It;
1162 
1163         if (CIs.count(&I)) {
1164           MergableCIs.push_back(cast<CallInst>(&I));
1165           continue;
1166         }
1167 
1168         // Continue expanding if the instruction is mergable.
1169         if (IsMergable(I, MergableCIs.empty()))
1170           continue;
1171 
1172         // Forward the instruction iterator to skip the next parallel region
1173         // since there is an unmergable instruction which can affect it.
1174         for (; It != End; ++It) {
1175           Instruction &SkipI = *It;
1176           if (CIs.count(&SkipI)) {
1177             LLVM_DEBUG(dbgs() << TAG << "Skip parallel region " << SkipI
1178                               << " due to " << I << "\n");
1179             ++It;
1180             break;
1181           }
1182         }
1183 
1184         // Store mergable regions found.
1185         if (MergableCIs.size() > 1) {
1186           MergableCIsVector.push_back(MergableCIs);
1187           LLVM_DEBUG(dbgs() << TAG << "Found " << MergableCIs.size()
1188                             << " parallel regions in block " << BB->getName()
1189                             << " of function " << BB->getParent()->getName()
1190                             << "\n";);
1191         }
1192 
1193         MergableCIs.clear();
1194       }
1195 
1196       if (!MergableCIsVector.empty()) {
1197         Changed = true;
1198 
1199         for (auto &MergableCIs : MergableCIsVector)
1200           Merge(MergableCIs, BB);
1201         MergableCIsVector.clear();
1202       }
1203     }
1204 
1205     if (Changed) {
1206       /// Re-collect use for fork calls, emitted barrier calls, and
1207       /// any emitted master/end_master calls.
1208       OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_fork_call);
1209       OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_barrier);
1210       OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_master);
1211       OMPInfoCache.recollectUsesForFunction(OMPRTL___kmpc_end_master);
1212     }
1213 
1214     return Changed;
1215   }
1216 
1217   /// Try to delete parallel regions if possible.
1218   bool deleteParallelRegions() {
1219     const unsigned CallbackCalleeOperand = 2;
1220 
1221     OMPInformationCache::RuntimeFunctionInfo &RFI =
1222         OMPInfoCache.RFIs[OMPRTL___kmpc_fork_call];
1223 
1224     if (!RFI.Declaration)
1225       return false;
1226 
1227     bool Changed = false;
1228     auto DeleteCallCB = [&](Use &U, Function &) {
1229       CallInst *CI = getCallIfRegularCall(U);
1230       if (!CI)
1231         return false;
1232       auto *Fn = dyn_cast<Function>(
1233           CI->getArgOperand(CallbackCalleeOperand)->stripPointerCasts());
1234       if (!Fn)
1235         return false;
1236       if (!Fn->onlyReadsMemory())
1237         return false;
1238       if (!Fn->hasFnAttribute(Attribute::WillReturn))
1239         return false;
1240 
1241       LLVM_DEBUG(dbgs() << TAG << "Delete read-only parallel region in "
1242                         << CI->getCaller()->getName() << "\n");
1243 
1244       auto Remark = [&](OptimizationRemark OR) {
1245         return OR << "Removing parallel region with no side-effects.";
1246       };
1247       emitRemark<OptimizationRemark>(CI, "OMP160", Remark);
1248 
1249       CGUpdater.removeCallSite(*CI);
1250       CI->eraseFromParent();
1251       Changed = true;
1252       ++NumOpenMPParallelRegionsDeleted;
1253       return true;
1254     };
1255 
1256     RFI.foreachUse(SCC, DeleteCallCB);
1257 
1258     return Changed;
1259   }
1260 
1261   /// Try to eliminate runtime calls by reusing existing ones.
1262   bool deduplicateRuntimeCalls() {
1263     bool Changed = false;
1264 
1265     RuntimeFunction DeduplicableRuntimeCallIDs[] = {
1266         OMPRTL_omp_get_num_threads,
1267         OMPRTL_omp_in_parallel,
1268         OMPRTL_omp_get_cancellation,
1269         OMPRTL_omp_get_thread_limit,
1270         OMPRTL_omp_get_supported_active_levels,
1271         OMPRTL_omp_get_level,
1272         OMPRTL_omp_get_ancestor_thread_num,
1273         OMPRTL_omp_get_team_size,
1274         OMPRTL_omp_get_active_level,
1275         OMPRTL_omp_in_final,
1276         OMPRTL_omp_get_proc_bind,
1277         OMPRTL_omp_get_num_places,
1278         OMPRTL_omp_get_num_procs,
1279         OMPRTL_omp_get_place_num,
1280         OMPRTL_omp_get_partition_num_places,
1281         OMPRTL_omp_get_partition_place_nums};
1282 
1283     // Global-tid is handled separately.
1284     SmallSetVector<Value *, 16> GTIdArgs;
1285     collectGlobalThreadIdArguments(GTIdArgs);
1286     LLVM_DEBUG(dbgs() << TAG << "Found " << GTIdArgs.size()
1287                       << " global thread ID arguments\n");
1288 
1289     for (Function *F : SCC) {
1290       for (auto DeduplicableRuntimeCallID : DeduplicableRuntimeCallIDs)
1291         Changed |= deduplicateRuntimeCalls(
1292             *F, OMPInfoCache.RFIs[DeduplicableRuntimeCallID]);
1293 
1294       // __kmpc_global_thread_num is special as we can replace it with an
1295       // argument in enough cases to make it worth trying.
1296       Value *GTIdArg = nullptr;
1297       for (Argument &Arg : F->args())
1298         if (GTIdArgs.count(&Arg)) {
1299           GTIdArg = &Arg;
1300           break;
1301         }
1302       Changed |= deduplicateRuntimeCalls(
1303           *F, OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num], GTIdArg);
1304     }
1305 
1306     return Changed;
1307   }
1308 
1309   /// Tries to hide the latency of runtime calls that involve host to
1310   /// device memory transfers by splitting them into their "issue" and "wait"
1311   /// versions. The "issue" is moved upwards as much as possible. The "wait" is
1312   /// moved downards as much as possible. The "issue" issues the memory transfer
1313   /// asynchronously, returning a handle. The "wait" waits in the returned
1314   /// handle for the memory transfer to finish.
1315   bool hideMemTransfersLatency() {
1316     auto &RFI = OMPInfoCache.RFIs[OMPRTL___tgt_target_data_begin_mapper];
1317     bool Changed = false;
1318     auto SplitMemTransfers = [&](Use &U, Function &Decl) {
1319       auto *RTCall = getCallIfRegularCall(U, &RFI);
1320       if (!RTCall)
1321         return false;
1322 
1323       OffloadArray OffloadArrays[3];
1324       if (!getValuesInOffloadArrays(*RTCall, OffloadArrays))
1325         return false;
1326 
1327       LLVM_DEBUG(dumpValuesInOffloadArrays(OffloadArrays));
1328 
1329       // TODO: Check if can be moved upwards.
1330       bool WasSplit = false;
1331       Instruction *WaitMovementPoint = canBeMovedDownwards(*RTCall);
1332       if (WaitMovementPoint)
1333         WasSplit = splitTargetDataBeginRTC(*RTCall, *WaitMovementPoint);
1334 
1335       Changed |= WasSplit;
1336       return WasSplit;
1337     };
1338     RFI.foreachUse(SCC, SplitMemTransfers);
1339 
1340     return Changed;
1341   }
1342 
1343   void analysisGlobalization() {
1344     auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
1345 
1346     auto CheckGlobalization = [&](Use &U, Function &Decl) {
1347       if (CallInst *CI = getCallIfRegularCall(U, &RFI)) {
1348         auto Remark = [&](OptimizationRemarkMissed ORM) {
1349           return ORM
1350                  << "Found thread data sharing on the GPU. "
1351                  << "Expect degraded performance due to data globalization.";
1352         };
1353         emitRemark<OptimizationRemarkMissed>(CI, "OMP112", Remark);
1354       }
1355 
1356       return false;
1357     };
1358 
1359     RFI.foreachUse(SCC, CheckGlobalization);
1360   }
1361 
1362   /// Maps the values stored in the offload arrays passed as arguments to
1363   /// \p RuntimeCall into the offload arrays in \p OAs.
1364   bool getValuesInOffloadArrays(CallInst &RuntimeCall,
1365                                 MutableArrayRef<OffloadArray> OAs) {
1366     assert(OAs.size() == 3 && "Need space for three offload arrays!");
1367 
1368     // A runtime call that involves memory offloading looks something like:
1369     // call void @__tgt_target_data_begin_mapper(arg0, arg1,
1370     //   i8** %offload_baseptrs, i8** %offload_ptrs, i64* %offload_sizes,
1371     // ...)
1372     // So, the idea is to access the allocas that allocate space for these
1373     // offload arrays, offload_baseptrs, offload_ptrs, offload_sizes.
1374     // Therefore:
1375     // i8** %offload_baseptrs.
1376     Value *BasePtrsArg =
1377         RuntimeCall.getArgOperand(OffloadArray::BasePtrsArgNum);
1378     // i8** %offload_ptrs.
1379     Value *PtrsArg = RuntimeCall.getArgOperand(OffloadArray::PtrsArgNum);
1380     // i8** %offload_sizes.
1381     Value *SizesArg = RuntimeCall.getArgOperand(OffloadArray::SizesArgNum);
1382 
1383     // Get values stored in **offload_baseptrs.
1384     auto *V = getUnderlyingObject(BasePtrsArg);
1385     if (!isa<AllocaInst>(V))
1386       return false;
1387     auto *BasePtrsArray = cast<AllocaInst>(V);
1388     if (!OAs[0].initialize(*BasePtrsArray, RuntimeCall))
1389       return false;
1390 
1391     // Get values stored in **offload_baseptrs.
1392     V = getUnderlyingObject(PtrsArg);
1393     if (!isa<AllocaInst>(V))
1394       return false;
1395     auto *PtrsArray = cast<AllocaInst>(V);
1396     if (!OAs[1].initialize(*PtrsArray, RuntimeCall))
1397       return false;
1398 
1399     // Get values stored in **offload_sizes.
1400     V = getUnderlyingObject(SizesArg);
1401     // If it's a [constant] global array don't analyze it.
1402     if (isa<GlobalValue>(V))
1403       return isa<Constant>(V);
1404     if (!isa<AllocaInst>(V))
1405       return false;
1406 
1407     auto *SizesArray = cast<AllocaInst>(V);
1408     if (!OAs[2].initialize(*SizesArray, RuntimeCall))
1409       return false;
1410 
1411     return true;
1412   }
1413 
1414   /// Prints the values in the OffloadArrays \p OAs using LLVM_DEBUG.
1415   /// For now this is a way to test that the function getValuesInOffloadArrays
1416   /// is working properly.
1417   /// TODO: Move this to a unittest when unittests are available for OpenMPOpt.
1418   void dumpValuesInOffloadArrays(ArrayRef<OffloadArray> OAs) {
1419     assert(OAs.size() == 3 && "There are three offload arrays to debug!");
1420 
1421     LLVM_DEBUG(dbgs() << TAG << " Successfully got offload values:\n");
1422     std::string ValuesStr;
1423     raw_string_ostream Printer(ValuesStr);
1424     std::string Separator = " --- ";
1425 
1426     for (auto *BP : OAs[0].StoredValues) {
1427       BP->print(Printer);
1428       Printer << Separator;
1429     }
1430     LLVM_DEBUG(dbgs() << "\t\toffload_baseptrs: " << Printer.str() << "\n");
1431     ValuesStr.clear();
1432 
1433     for (auto *P : OAs[1].StoredValues) {
1434       P->print(Printer);
1435       Printer << Separator;
1436     }
1437     LLVM_DEBUG(dbgs() << "\t\toffload_ptrs: " << Printer.str() << "\n");
1438     ValuesStr.clear();
1439 
1440     for (auto *S : OAs[2].StoredValues) {
1441       S->print(Printer);
1442       Printer << Separator;
1443     }
1444     LLVM_DEBUG(dbgs() << "\t\toffload_sizes: " << Printer.str() << "\n");
1445   }
1446 
1447   /// Returns the instruction where the "wait" counterpart \p RuntimeCall can be
1448   /// moved. Returns nullptr if the movement is not possible, or not worth it.
1449   Instruction *canBeMovedDownwards(CallInst &RuntimeCall) {
1450     // FIXME: This traverses only the BasicBlock where RuntimeCall is.
1451     //  Make it traverse the CFG.
1452 
1453     Instruction *CurrentI = &RuntimeCall;
1454     bool IsWorthIt = false;
1455     while ((CurrentI = CurrentI->getNextNode())) {
1456 
1457       // TODO: Once we detect the regions to be offloaded we should use the
1458       //  alias analysis manager to check if CurrentI may modify one of
1459       //  the offloaded regions.
1460       if (CurrentI->mayHaveSideEffects() || CurrentI->mayReadFromMemory()) {
1461         if (IsWorthIt)
1462           return CurrentI;
1463 
1464         return nullptr;
1465       }
1466 
1467       // FIXME: For now if we move it over anything without side effect
1468       //  is worth it.
1469       IsWorthIt = true;
1470     }
1471 
1472     // Return end of BasicBlock.
1473     return RuntimeCall.getParent()->getTerminator();
1474   }
1475 
1476   /// Splits \p RuntimeCall into its "issue" and "wait" counterparts.
1477   bool splitTargetDataBeginRTC(CallInst &RuntimeCall,
1478                                Instruction &WaitMovementPoint) {
1479     // Create stack allocated handle (__tgt_async_info) at the beginning of the
1480     // function. Used for storing information of the async transfer, allowing to
1481     // wait on it later.
1482     auto &IRBuilder = OMPInfoCache.OMPBuilder;
1483     auto *F = RuntimeCall.getCaller();
1484     Instruction *FirstInst = &(F->getEntryBlock().front());
1485     AllocaInst *Handle = new AllocaInst(
1486         IRBuilder.AsyncInfo, F->getAddressSpace(), "handle", FirstInst);
1487 
1488     // Add "issue" runtime call declaration:
1489     // declare %struct.tgt_async_info @__tgt_target_data_begin_issue(i64, i32,
1490     //   i8**, i8**, i64*, i64*)
1491     FunctionCallee IssueDecl = IRBuilder.getOrCreateRuntimeFunction(
1492         M, OMPRTL___tgt_target_data_begin_mapper_issue);
1493 
1494     // Change RuntimeCall call site for its asynchronous version.
1495     SmallVector<Value *, 16> Args;
1496     for (auto &Arg : RuntimeCall.args())
1497       Args.push_back(Arg.get());
1498     Args.push_back(Handle);
1499 
1500     CallInst *IssueCallsite =
1501         CallInst::Create(IssueDecl, Args, /*NameStr=*/"", &RuntimeCall);
1502     RuntimeCall.eraseFromParent();
1503 
1504     // Add "wait" runtime call declaration:
1505     // declare void @__tgt_target_data_begin_wait(i64, %struct.__tgt_async_info)
1506     FunctionCallee WaitDecl = IRBuilder.getOrCreateRuntimeFunction(
1507         M, OMPRTL___tgt_target_data_begin_mapper_wait);
1508 
1509     Value *WaitParams[2] = {
1510         IssueCallsite->getArgOperand(
1511             OffloadArray::DeviceIDArgNum), // device_id.
1512         Handle                             // handle to wait on.
1513     };
1514     CallInst::Create(WaitDecl, WaitParams, /*NameStr=*/"", &WaitMovementPoint);
1515 
1516     return true;
1517   }
1518 
1519   static Value *combinedIdentStruct(Value *CurrentIdent, Value *NextIdent,
1520                                     bool GlobalOnly, bool &SingleChoice) {
1521     if (CurrentIdent == NextIdent)
1522       return CurrentIdent;
1523 
1524     // TODO: Figure out how to actually combine multiple debug locations. For
1525     //       now we just keep an existing one if there is a single choice.
1526     if (!GlobalOnly || isa<GlobalValue>(NextIdent)) {
1527       SingleChoice = !CurrentIdent;
1528       return NextIdent;
1529     }
1530     return nullptr;
1531   }
1532 
1533   /// Return an `struct ident_t*` value that represents the ones used in the
1534   /// calls of \p RFI inside of \p F. If \p GlobalOnly is true, we will not
1535   /// return a local `struct ident_t*`. For now, if we cannot find a suitable
1536   /// return value we create one from scratch. We also do not yet combine
1537   /// information, e.g., the source locations, see combinedIdentStruct.
1538   Value *
1539   getCombinedIdentFromCallUsesIn(OMPInformationCache::RuntimeFunctionInfo &RFI,
1540                                  Function &F, bool GlobalOnly) {
1541     bool SingleChoice = true;
1542     Value *Ident = nullptr;
1543     auto CombineIdentStruct = [&](Use &U, Function &Caller) {
1544       CallInst *CI = getCallIfRegularCall(U, &RFI);
1545       if (!CI || &F != &Caller)
1546         return false;
1547       Ident = combinedIdentStruct(Ident, CI->getArgOperand(0),
1548                                   /* GlobalOnly */ true, SingleChoice);
1549       return false;
1550     };
1551     RFI.foreachUse(SCC, CombineIdentStruct);
1552 
1553     if (!Ident || !SingleChoice) {
1554       // The IRBuilder uses the insertion block to get to the module, this is
1555       // unfortunate but we work around it for now.
1556       if (!OMPInfoCache.OMPBuilder.getInsertionPoint().getBlock())
1557         OMPInfoCache.OMPBuilder.updateToLocation(OpenMPIRBuilder::InsertPointTy(
1558             &F.getEntryBlock(), F.getEntryBlock().begin()));
1559       // Create a fallback location if non was found.
1560       // TODO: Use the debug locations of the calls instead.
1561       Constant *Loc = OMPInfoCache.OMPBuilder.getOrCreateDefaultSrcLocStr();
1562       Ident = OMPInfoCache.OMPBuilder.getOrCreateIdent(Loc);
1563     }
1564     return Ident;
1565   }
1566 
1567   /// Try to eliminate calls of \p RFI in \p F by reusing an existing one or
1568   /// \p ReplVal if given.
1569   bool deduplicateRuntimeCalls(Function &F,
1570                                OMPInformationCache::RuntimeFunctionInfo &RFI,
1571                                Value *ReplVal = nullptr) {
1572     auto *UV = RFI.getUseVector(F);
1573     if (!UV || UV->size() + (ReplVal != nullptr) < 2)
1574       return false;
1575 
1576     LLVM_DEBUG(
1577         dbgs() << TAG << "Deduplicate " << UV->size() << " uses of " << RFI.Name
1578                << (ReplVal ? " with an existing value\n" : "\n") << "\n");
1579 
1580     assert((!ReplVal || (isa<Argument>(ReplVal) &&
1581                          cast<Argument>(ReplVal)->getParent() == &F)) &&
1582            "Unexpected replacement value!");
1583 
1584     // TODO: Use dominance to find a good position instead.
1585     auto CanBeMoved = [this](CallBase &CB) {
1586       unsigned NumArgs = CB.getNumArgOperands();
1587       if (NumArgs == 0)
1588         return true;
1589       if (CB.getArgOperand(0)->getType() != OMPInfoCache.OMPBuilder.IdentPtr)
1590         return false;
1591       for (unsigned u = 1; u < NumArgs; ++u)
1592         if (isa<Instruction>(CB.getArgOperand(u)))
1593           return false;
1594       return true;
1595     };
1596 
1597     if (!ReplVal) {
1598       for (Use *U : *UV)
1599         if (CallInst *CI = getCallIfRegularCall(*U, &RFI)) {
1600           if (!CanBeMoved(*CI))
1601             continue;
1602 
1603           // If the function is a kernel, dedup will move
1604           // the runtime call right after the kernel init callsite. Otherwise,
1605           // it will move it to the beginning of the caller function.
1606           if (isKernel(F)) {
1607             auto &KernelInitRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
1608             auto *KernelInitUV = KernelInitRFI.getUseVector(F);
1609 
1610             if (KernelInitUV->empty())
1611               continue;
1612 
1613             assert(KernelInitUV->size() == 1 &&
1614                    "Expected a single __kmpc_target_init in kernel\n");
1615 
1616             CallInst *KernelInitCI =
1617                 getCallIfRegularCall(*KernelInitUV->front(), &KernelInitRFI);
1618             assert(KernelInitCI &&
1619                    "Expected a call to __kmpc_target_init in kernel\n");
1620 
1621             CI->moveAfter(KernelInitCI);
1622           } else
1623             CI->moveBefore(&*F.getEntryBlock().getFirstInsertionPt());
1624           ReplVal = CI;
1625           break;
1626         }
1627       if (!ReplVal)
1628         return false;
1629     }
1630 
1631     // If we use a call as a replacement value we need to make sure the ident is
1632     // valid at the new location. For now we just pick a global one, either
1633     // existing and used by one of the calls, or created from scratch.
1634     if (CallBase *CI = dyn_cast<CallBase>(ReplVal)) {
1635       if (CI->getNumArgOperands() > 0 &&
1636           CI->getArgOperand(0)->getType() == OMPInfoCache.OMPBuilder.IdentPtr) {
1637         Value *Ident = getCombinedIdentFromCallUsesIn(RFI, F,
1638                                                       /* GlobalOnly */ true);
1639         CI->setArgOperand(0, Ident);
1640       }
1641     }
1642 
1643     bool Changed = false;
1644     auto ReplaceAndDeleteCB = [&](Use &U, Function &Caller) {
1645       CallInst *CI = getCallIfRegularCall(U, &RFI);
1646       if (!CI || CI == ReplVal || &F != &Caller)
1647         return false;
1648       assert(CI->getCaller() == &F && "Unexpected call!");
1649 
1650       auto Remark = [&](OptimizationRemark OR) {
1651         return OR << "OpenMP runtime call "
1652                   << ore::NV("OpenMPOptRuntime", RFI.Name) << " deduplicated.";
1653       };
1654       if (CI->getDebugLoc())
1655         emitRemark<OptimizationRemark>(CI, "OMP170", Remark);
1656       else
1657         emitRemark<OptimizationRemark>(&F, "OMP170", Remark);
1658 
1659       CGUpdater.removeCallSite(*CI);
1660       CI->replaceAllUsesWith(ReplVal);
1661       CI->eraseFromParent();
1662       ++NumOpenMPRuntimeCallsDeduplicated;
1663       Changed = true;
1664       return true;
1665     };
1666     RFI.foreachUse(SCC, ReplaceAndDeleteCB);
1667 
1668     return Changed;
1669   }
1670 
1671   /// Collect arguments that represent the global thread id in \p GTIdArgs.
1672   void collectGlobalThreadIdArguments(SmallSetVector<Value *, 16> &GTIdArgs) {
1673     // TODO: Below we basically perform a fixpoint iteration with a pessimistic
1674     //       initialization. We could define an AbstractAttribute instead and
1675     //       run the Attributor here once it can be run as an SCC pass.
1676 
1677     // Helper to check the argument \p ArgNo at all call sites of \p F for
1678     // a GTId.
1679     auto CallArgOpIsGTId = [&](Function &F, unsigned ArgNo, CallInst &RefCI) {
1680       if (!F.hasLocalLinkage())
1681         return false;
1682       for (Use &U : F.uses()) {
1683         if (CallInst *CI = getCallIfRegularCall(U)) {
1684           Value *ArgOp = CI->getArgOperand(ArgNo);
1685           if (CI == &RefCI || GTIdArgs.count(ArgOp) ||
1686               getCallIfRegularCall(
1687                   *ArgOp, &OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num]))
1688             continue;
1689         }
1690         return false;
1691       }
1692       return true;
1693     };
1694 
1695     // Helper to identify uses of a GTId as GTId arguments.
1696     auto AddUserArgs = [&](Value &GTId) {
1697       for (Use &U : GTId.uses())
1698         if (CallInst *CI = dyn_cast<CallInst>(U.getUser()))
1699           if (CI->isArgOperand(&U))
1700             if (Function *Callee = CI->getCalledFunction())
1701               if (CallArgOpIsGTId(*Callee, U.getOperandNo(), *CI))
1702                 GTIdArgs.insert(Callee->getArg(U.getOperandNo()));
1703     };
1704 
1705     // The argument users of __kmpc_global_thread_num calls are GTIds.
1706     OMPInformationCache::RuntimeFunctionInfo &GlobThreadNumRFI =
1707         OMPInfoCache.RFIs[OMPRTL___kmpc_global_thread_num];
1708 
1709     GlobThreadNumRFI.foreachUse(SCC, [&](Use &U, Function &F) {
1710       if (CallInst *CI = getCallIfRegularCall(U, &GlobThreadNumRFI))
1711         AddUserArgs(*CI);
1712       return false;
1713     });
1714 
1715     // Transitively search for more arguments by looking at the users of the
1716     // ones we know already. During the search the GTIdArgs vector is extended
1717     // so we cannot cache the size nor can we use a range based for.
1718     for (unsigned u = 0; u < GTIdArgs.size(); ++u)
1719       AddUserArgs(*GTIdArgs[u]);
1720   }
1721 
1722   /// Kernel (=GPU) optimizations and utility functions
1723   ///
1724   ///{{
1725 
1726   /// Check if \p F is a kernel, hence entry point for target offloading.
1727   bool isKernel(Function &F) { return OMPInfoCache.Kernels.count(&F); }
1728 
1729   /// Cache to remember the unique kernel for a function.
1730   DenseMap<Function *, Optional<Kernel>> UniqueKernelMap;
1731 
1732   /// Find the unique kernel that will execute \p F, if any.
1733   Kernel getUniqueKernelFor(Function &F);
1734 
1735   /// Find the unique kernel that will execute \p I, if any.
1736   Kernel getUniqueKernelFor(Instruction &I) {
1737     return getUniqueKernelFor(*I.getFunction());
1738   }
1739 
1740   /// Rewrite the device (=GPU) code state machine create in non-SPMD mode in
1741   /// the cases we can avoid taking the address of a function.
1742   bool rewriteDeviceCodeStateMachine();
1743 
1744   ///
1745   ///}}
1746 
1747   /// Emit a remark generically
1748   ///
1749   /// This template function can be used to generically emit a remark. The
1750   /// RemarkKind should be one of the following:
1751   ///   - OptimizationRemark to indicate a successful optimization attempt
1752   ///   - OptimizationRemarkMissed to report a failed optimization attempt
1753   ///   - OptimizationRemarkAnalysis to provide additional information about an
1754   ///     optimization attempt
1755   ///
1756   /// The remark is built using a callback function provided by the caller that
1757   /// takes a RemarkKind as input and returns a RemarkKind.
1758   template <typename RemarkKind, typename RemarkCallBack>
1759   void emitRemark(Instruction *I, StringRef RemarkName,
1760                   RemarkCallBack &&RemarkCB) const {
1761     Function *F = I->getParent()->getParent();
1762     auto &ORE = OREGetter(F);
1763 
1764     if (RemarkName.startswith("OMP"))
1765       ORE.emit([&]() {
1766         return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I))
1767                << " [" << RemarkName << "]";
1768       });
1769     else
1770       ORE.emit(
1771           [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, I)); });
1772   }
1773 
1774   /// Emit a remark on a function.
1775   template <typename RemarkKind, typename RemarkCallBack>
1776   void emitRemark(Function *F, StringRef RemarkName,
1777                   RemarkCallBack &&RemarkCB) const {
1778     auto &ORE = OREGetter(F);
1779 
1780     if (RemarkName.startswith("OMP"))
1781       ORE.emit([&]() {
1782         return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F))
1783                << " [" << RemarkName << "]";
1784       });
1785     else
1786       ORE.emit(
1787           [&]() { return RemarkCB(RemarkKind(DEBUG_TYPE, RemarkName, F)); });
1788   }
1789 
1790   /// RAII struct to temporarily change an RTL function's linkage to external.
1791   /// This prevents it from being mistakenly removed by other optimizations.
1792   struct ExternalizationRAII {
1793     ExternalizationRAII(OMPInformationCache &OMPInfoCache,
1794                         RuntimeFunction RFKind)
1795         : Declaration(OMPInfoCache.RFIs[RFKind].Declaration) {
1796       if (!Declaration)
1797         return;
1798 
1799       LinkageType = Declaration->getLinkage();
1800       Declaration->setLinkage(GlobalValue::ExternalLinkage);
1801     }
1802 
1803     ~ExternalizationRAII() {
1804       if (!Declaration)
1805         return;
1806 
1807       Declaration->setLinkage(LinkageType);
1808     }
1809 
1810     Function *Declaration;
1811     GlobalValue::LinkageTypes LinkageType;
1812   };
1813 
1814   /// The underlying module.
1815   Module &M;
1816 
1817   /// The SCC we are operating on.
1818   SmallVectorImpl<Function *> &SCC;
1819 
1820   /// Callback to update the call graph, the first argument is a removed call,
1821   /// the second an optional replacement call.
1822   CallGraphUpdater &CGUpdater;
1823 
1824   /// Callback to get an OptimizationRemarkEmitter from a Function *
1825   OptimizationRemarkGetter OREGetter;
1826 
1827   /// OpenMP-specific information cache. Also Used for Attributor runs.
1828   OMPInformationCache &OMPInfoCache;
1829 
1830   /// Attributor instance.
1831   Attributor &A;
1832 
1833   /// Helper function to run Attributor on SCC.
1834   bool runAttributor(bool IsModulePass) {
1835     if (SCC.empty())
1836       return false;
1837 
1838     // Temporarily make these function have external linkage so the Attributor
1839     // doesn't remove them when we try to look them up later.
1840     ExternalizationRAII Parallel(OMPInfoCache, OMPRTL___kmpc_kernel_parallel);
1841     ExternalizationRAII EndParallel(OMPInfoCache,
1842                                     OMPRTL___kmpc_kernel_end_parallel);
1843     ExternalizationRAII BarrierSPMD(OMPInfoCache,
1844                                     OMPRTL___kmpc_barrier_simple_spmd);
1845 
1846     registerAAs(IsModulePass);
1847 
1848     ChangeStatus Changed = A.run();
1849 
1850     LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size()
1851                       << " functions, result: " << Changed << ".\n");
1852 
1853     return Changed == ChangeStatus::CHANGED;
1854   }
1855 
1856   void registerFoldRuntimeCall(RuntimeFunction RF);
1857 
1858   /// Populate the Attributor with abstract attribute opportunities in the
1859   /// function.
1860   void registerAAs(bool IsModulePass);
1861 };
1862 
1863 Kernel OpenMPOpt::getUniqueKernelFor(Function &F) {
1864   if (!OMPInfoCache.ModuleSlice.count(&F))
1865     return nullptr;
1866 
1867   // Use a scope to keep the lifetime of the CachedKernel short.
1868   {
1869     Optional<Kernel> &CachedKernel = UniqueKernelMap[&F];
1870     if (CachedKernel)
1871       return *CachedKernel;
1872 
1873     // TODO: We should use an AA to create an (optimistic and callback
1874     //       call-aware) call graph. For now we stick to simple patterns that
1875     //       are less powerful, basically the worst fixpoint.
1876     if (isKernel(F)) {
1877       CachedKernel = Kernel(&F);
1878       return *CachedKernel;
1879     }
1880 
1881     CachedKernel = nullptr;
1882     if (!F.hasLocalLinkage()) {
1883 
1884       // See https://openmp.llvm.org/remarks/OptimizationRemarks.html
1885       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
1886         return ORA << "Potentially unknown OpenMP target region caller.";
1887       };
1888       emitRemark<OptimizationRemarkAnalysis>(&F, "OMP100", Remark);
1889 
1890       return nullptr;
1891     }
1892   }
1893 
1894   auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel {
1895     if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
1896       // Allow use in equality comparisons.
1897       if (Cmp->isEquality())
1898         return getUniqueKernelFor(*Cmp);
1899       return nullptr;
1900     }
1901     if (auto *CB = dyn_cast<CallBase>(U.getUser())) {
1902       // Allow direct calls.
1903       if (CB->isCallee(&U))
1904         return getUniqueKernelFor(*CB);
1905 
1906       OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI =
1907           OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
1908       // Allow the use in __kmpc_parallel_51 calls.
1909       if (OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI))
1910         return getUniqueKernelFor(*CB);
1911       return nullptr;
1912     }
1913     // Disallow every other use.
1914     return nullptr;
1915   };
1916 
1917   // TODO: In the future we want to track more than just a unique kernel.
1918   SmallPtrSet<Kernel, 2> PotentialKernels;
1919   OMPInformationCache::foreachUse(F, [&](const Use &U) {
1920     PotentialKernels.insert(GetUniqueKernelForUse(U));
1921   });
1922 
1923   Kernel K = nullptr;
1924   if (PotentialKernels.size() == 1)
1925     K = *PotentialKernels.begin();
1926 
1927   // Cache the result.
1928   UniqueKernelMap[&F] = K;
1929 
1930   return K;
1931 }
1932 
1933 bool OpenMPOpt::rewriteDeviceCodeStateMachine() {
1934   OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI =
1935       OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
1936 
1937   bool Changed = false;
1938   if (!KernelParallelRFI)
1939     return Changed;
1940 
1941   // If we have disabled state machine changes, exit
1942   if (DisableOpenMPOptStateMachineRewrite)
1943     return Changed;
1944 
1945   for (Function *F : SCC) {
1946 
1947     // Check if the function is a use in a __kmpc_parallel_51 call at
1948     // all.
1949     bool UnknownUse = false;
1950     bool KernelParallelUse = false;
1951     unsigned NumDirectCalls = 0;
1952 
1953     SmallVector<Use *, 2> ToBeReplacedStateMachineUses;
1954     OMPInformationCache::foreachUse(*F, [&](Use &U) {
1955       if (auto *CB = dyn_cast<CallBase>(U.getUser()))
1956         if (CB->isCallee(&U)) {
1957           ++NumDirectCalls;
1958           return;
1959         }
1960 
1961       if (isa<ICmpInst>(U.getUser())) {
1962         ToBeReplacedStateMachineUses.push_back(&U);
1963         return;
1964       }
1965 
1966       // Find wrapper functions that represent parallel kernels.
1967       CallInst *CI =
1968           OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI);
1969       const unsigned int WrapperFunctionArgNo = 6;
1970       if (!KernelParallelUse && CI &&
1971           CI->getArgOperandNo(&U) == WrapperFunctionArgNo) {
1972         KernelParallelUse = true;
1973         ToBeReplacedStateMachineUses.push_back(&U);
1974         return;
1975       }
1976       UnknownUse = true;
1977     });
1978 
1979     // Do not emit a remark if we haven't seen a __kmpc_parallel_51
1980     // use.
1981     if (!KernelParallelUse)
1982       continue;
1983 
1984     // If this ever hits, we should investigate.
1985     // TODO: Checking the number of uses is not a necessary restriction and
1986     // should be lifted.
1987     if (UnknownUse || NumDirectCalls != 1 ||
1988         ToBeReplacedStateMachineUses.size() > 2) {
1989       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
1990         return ORA << "Parallel region is used in "
1991                    << (UnknownUse ? "unknown" : "unexpected")
1992                    << " ways. Will not attempt to rewrite the state machine.";
1993       };
1994       emitRemark<OptimizationRemarkAnalysis>(F, "OMP101", Remark);
1995       continue;
1996     }
1997 
1998     // Even if we have __kmpc_parallel_51 calls, we (for now) give
1999     // up if the function is not called from a unique kernel.
2000     Kernel K = getUniqueKernelFor(*F);
2001     if (!K) {
2002       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
2003         return ORA << "Parallel region is not called from a unique kernel. "
2004                       "Will not attempt to rewrite the state machine.";
2005       };
2006       emitRemark<OptimizationRemarkAnalysis>(F, "OMP102", Remark);
2007       continue;
2008     }
2009 
2010     // We now know F is a parallel body function called only from the kernel K.
2011     // We also identified the state machine uses in which we replace the
2012     // function pointer by a new global symbol for identification purposes. This
2013     // ensures only direct calls to the function are left.
2014 
2015     Module &M = *F->getParent();
2016     Type *Int8Ty = Type::getInt8Ty(M.getContext());
2017 
2018     auto *ID = new GlobalVariable(
2019         M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage,
2020         UndefValue::get(Int8Ty), F->getName() + ".ID");
2021 
2022     for (Use *U : ToBeReplacedStateMachineUses)
2023       U->set(ConstantExpr::getBitCast(ID, U->get()->getType()));
2024 
2025     ++NumOpenMPParallelRegionsReplacedInGPUStateMachine;
2026 
2027     Changed = true;
2028   }
2029 
2030   return Changed;
2031 }
2032 
2033 /// Abstract Attribute for tracking ICV values.
2034 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> {
2035   using Base = StateWrapper<BooleanState, AbstractAttribute>;
2036   AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
2037 
2038   void initialize(Attributor &A) override {
2039     Function *F = getAnchorScope();
2040     if (!F || !A.isFunctionIPOAmendable(*F))
2041       indicatePessimisticFixpoint();
2042   }
2043 
2044   /// Returns true if value is assumed to be tracked.
2045   bool isAssumedTracked() const { return getAssumed(); }
2046 
2047   /// Returns true if value is known to be tracked.
2048   bool isKnownTracked() const { return getAssumed(); }
2049 
2050   /// Create an abstract attribute biew for the position \p IRP.
2051   static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A);
2052 
2053   /// Return the value with which \p I can be replaced for specific \p ICV.
2054   virtual Optional<Value *> getReplacementValue(InternalControlVar ICV,
2055                                                 const Instruction *I,
2056                                                 Attributor &A) const {
2057     return None;
2058   }
2059 
2060   /// Return an assumed unique ICV value if a single candidate is found. If
2061   /// there cannot be one, return a nullptr. If it is not clear yet, return the
2062   /// Optional::NoneType.
2063   virtual Optional<Value *>
2064   getUniqueReplacementValue(InternalControlVar ICV) const = 0;
2065 
2066   // Currently only nthreads is being tracked.
2067   // this array will only grow with time.
2068   InternalControlVar TrackableICVs[1] = {ICV_nthreads};
2069 
2070   /// See AbstractAttribute::getName()
2071   const std::string getName() const override { return "AAICVTracker"; }
2072 
2073   /// See AbstractAttribute::getIdAddr()
2074   const char *getIdAddr() const override { return &ID; }
2075 
2076   /// This function should return true if the type of the \p AA is AAICVTracker
2077   static bool classof(const AbstractAttribute *AA) {
2078     return (AA->getIdAddr() == &ID);
2079   }
2080 
2081   static const char ID;
2082 };
2083 
2084 struct AAICVTrackerFunction : public AAICVTracker {
2085   AAICVTrackerFunction(const IRPosition &IRP, Attributor &A)
2086       : AAICVTracker(IRP, A) {}
2087 
2088   // FIXME: come up with better string.
2089   const std::string getAsStr() const override { return "ICVTrackerFunction"; }
2090 
2091   // FIXME: come up with some stats.
2092   void trackStatistics() const override {}
2093 
2094   /// We don't manifest anything for this AA.
2095   ChangeStatus manifest(Attributor &A) override {
2096     return ChangeStatus::UNCHANGED;
2097   }
2098 
2099   // Map of ICV to their values at specific program point.
2100   EnumeratedArray<DenseMap<Instruction *, Value *>, InternalControlVar,
2101                   InternalControlVar::ICV___last>
2102       ICVReplacementValuesMap;
2103 
2104   ChangeStatus updateImpl(Attributor &A) override {
2105     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
2106 
2107     Function *F = getAnchorScope();
2108 
2109     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2110 
2111     for (InternalControlVar ICV : TrackableICVs) {
2112       auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
2113 
2114       auto &ValuesMap = ICVReplacementValuesMap[ICV];
2115       auto TrackValues = [&](Use &U, Function &) {
2116         CallInst *CI = OpenMPOpt::getCallIfRegularCall(U);
2117         if (!CI)
2118           return false;
2119 
2120         // FIXME: handle setters with more that 1 arguments.
2121         /// Track new value.
2122         if (ValuesMap.insert(std::make_pair(CI, CI->getArgOperand(0))).second)
2123           HasChanged = ChangeStatus::CHANGED;
2124 
2125         return false;
2126       };
2127 
2128       auto CallCheck = [&](Instruction &I) {
2129         Optional<Value *> ReplVal = getValueForCall(A, &I, ICV);
2130         if (ReplVal.hasValue() &&
2131             ValuesMap.insert(std::make_pair(&I, *ReplVal)).second)
2132           HasChanged = ChangeStatus::CHANGED;
2133 
2134         return true;
2135       };
2136 
2137       // Track all changes of an ICV.
2138       SetterRFI.foreachUse(TrackValues, F);
2139 
2140       bool UsedAssumedInformation = false;
2141       A.checkForAllInstructions(CallCheck, *this, {Instruction::Call},
2142                                 UsedAssumedInformation,
2143                                 /* CheckBBLivenessOnly */ true);
2144 
2145       /// TODO: Figure out a way to avoid adding entry in
2146       /// ICVReplacementValuesMap
2147       Instruction *Entry = &F->getEntryBlock().front();
2148       if (HasChanged == ChangeStatus::CHANGED && !ValuesMap.count(Entry))
2149         ValuesMap.insert(std::make_pair(Entry, nullptr));
2150     }
2151 
2152     return HasChanged;
2153   }
2154 
2155   /// Hepler to check if \p I is a call and get the value for it if it is
2156   /// unique.
2157   Optional<Value *> getValueForCall(Attributor &A, const Instruction *I,
2158                                     InternalControlVar &ICV) const {
2159 
2160     const auto *CB = dyn_cast<CallBase>(I);
2161     if (!CB || CB->hasFnAttr("no_openmp") ||
2162         CB->hasFnAttr("no_openmp_routines"))
2163       return None;
2164 
2165     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2166     auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter];
2167     auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
2168     Function *CalledFunction = CB->getCalledFunction();
2169 
2170     // Indirect call, assume ICV changes.
2171     if (CalledFunction == nullptr)
2172       return nullptr;
2173     if (CalledFunction == GetterRFI.Declaration)
2174       return None;
2175     if (CalledFunction == SetterRFI.Declaration) {
2176       if (ICVReplacementValuesMap[ICV].count(I))
2177         return ICVReplacementValuesMap[ICV].lookup(I);
2178 
2179       return nullptr;
2180     }
2181 
2182     // Since we don't know, assume it changes the ICV.
2183     if (CalledFunction->isDeclaration())
2184       return nullptr;
2185 
2186     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2187         *this, IRPosition::callsite_returned(*CB), DepClassTy::REQUIRED);
2188 
2189     if (ICVTrackingAA.isAssumedTracked())
2190       return ICVTrackingAA.getUniqueReplacementValue(ICV);
2191 
2192     // If we don't know, assume it changes.
2193     return nullptr;
2194   }
2195 
2196   // We don't check unique value for a function, so return None.
2197   Optional<Value *>
2198   getUniqueReplacementValue(InternalControlVar ICV) const override {
2199     return None;
2200   }
2201 
2202   /// Return the value with which \p I can be replaced for specific \p ICV.
2203   Optional<Value *> getReplacementValue(InternalControlVar ICV,
2204                                         const Instruction *I,
2205                                         Attributor &A) const override {
2206     const auto &ValuesMap = ICVReplacementValuesMap[ICV];
2207     if (ValuesMap.count(I))
2208       return ValuesMap.lookup(I);
2209 
2210     SmallVector<const Instruction *, 16> Worklist;
2211     SmallPtrSet<const Instruction *, 16> Visited;
2212     Worklist.push_back(I);
2213 
2214     Optional<Value *> ReplVal;
2215 
2216     while (!Worklist.empty()) {
2217       const Instruction *CurrInst = Worklist.pop_back_val();
2218       if (!Visited.insert(CurrInst).second)
2219         continue;
2220 
2221       const BasicBlock *CurrBB = CurrInst->getParent();
2222 
2223       // Go up and look for all potential setters/calls that might change the
2224       // ICV.
2225       while ((CurrInst = CurrInst->getPrevNode())) {
2226         if (ValuesMap.count(CurrInst)) {
2227           Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst);
2228           // Unknown value, track new.
2229           if (!ReplVal.hasValue()) {
2230             ReplVal = NewReplVal;
2231             break;
2232           }
2233 
2234           // If we found a new value, we can't know the icv value anymore.
2235           if (NewReplVal.hasValue())
2236             if (ReplVal != NewReplVal)
2237               return nullptr;
2238 
2239           break;
2240         }
2241 
2242         Optional<Value *> NewReplVal = getValueForCall(A, CurrInst, ICV);
2243         if (!NewReplVal.hasValue())
2244           continue;
2245 
2246         // Unknown value, track new.
2247         if (!ReplVal.hasValue()) {
2248           ReplVal = NewReplVal;
2249           break;
2250         }
2251 
2252         // if (NewReplVal.hasValue())
2253         // We found a new value, we can't know the icv value anymore.
2254         if (ReplVal != NewReplVal)
2255           return nullptr;
2256       }
2257 
2258       // If we are in the same BB and we have a value, we are done.
2259       if (CurrBB == I->getParent() && ReplVal.hasValue())
2260         return ReplVal;
2261 
2262       // Go through all predecessors and add terminators for analysis.
2263       for (const BasicBlock *Pred : predecessors(CurrBB))
2264         if (const Instruction *Terminator = Pred->getTerminator())
2265           Worklist.push_back(Terminator);
2266     }
2267 
2268     return ReplVal;
2269   }
2270 };
2271 
2272 struct AAICVTrackerFunctionReturned : AAICVTracker {
2273   AAICVTrackerFunctionReturned(const IRPosition &IRP, Attributor &A)
2274       : AAICVTracker(IRP, A) {}
2275 
2276   // FIXME: come up with better string.
2277   const std::string getAsStr() const override {
2278     return "ICVTrackerFunctionReturned";
2279   }
2280 
2281   // FIXME: come up with some stats.
2282   void trackStatistics() const override {}
2283 
2284   /// We don't manifest anything for this AA.
2285   ChangeStatus manifest(Attributor &A) override {
2286     return ChangeStatus::UNCHANGED;
2287   }
2288 
2289   // Map of ICV to their values at specific program point.
2290   EnumeratedArray<Optional<Value *>, InternalControlVar,
2291                   InternalControlVar::ICV___last>
2292       ICVReplacementValuesMap;
2293 
2294   /// Return the value with which \p I can be replaced for specific \p ICV.
2295   Optional<Value *>
2296   getUniqueReplacementValue(InternalControlVar ICV) const override {
2297     return ICVReplacementValuesMap[ICV];
2298   }
2299 
2300   ChangeStatus updateImpl(Attributor &A) override {
2301     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2302     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2303         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
2304 
2305     if (!ICVTrackingAA.isAssumedTracked())
2306       return indicatePessimisticFixpoint();
2307 
2308     for (InternalControlVar ICV : TrackableICVs) {
2309       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
2310       Optional<Value *> UniqueICVValue;
2311 
2312       auto CheckReturnInst = [&](Instruction &I) {
2313         Optional<Value *> NewReplVal =
2314             ICVTrackingAA.getReplacementValue(ICV, &I, A);
2315 
2316         // If we found a second ICV value there is no unique returned value.
2317         if (UniqueICVValue.hasValue() && UniqueICVValue != NewReplVal)
2318           return false;
2319 
2320         UniqueICVValue = NewReplVal;
2321 
2322         return true;
2323       };
2324 
2325       bool UsedAssumedInformation = false;
2326       if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret},
2327                                      UsedAssumedInformation,
2328                                      /* CheckBBLivenessOnly */ true))
2329         UniqueICVValue = nullptr;
2330 
2331       if (UniqueICVValue == ReplVal)
2332         continue;
2333 
2334       ReplVal = UniqueICVValue;
2335       Changed = ChangeStatus::CHANGED;
2336     }
2337 
2338     return Changed;
2339   }
2340 };
2341 
2342 struct AAICVTrackerCallSite : AAICVTracker {
2343   AAICVTrackerCallSite(const IRPosition &IRP, Attributor &A)
2344       : AAICVTracker(IRP, A) {}
2345 
2346   void initialize(Attributor &A) override {
2347     Function *F = getAnchorScope();
2348     if (!F || !A.isFunctionIPOAmendable(*F))
2349       indicatePessimisticFixpoint();
2350 
2351     // We only initialize this AA for getters, so we need to know which ICV it
2352     // gets.
2353     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2354     for (InternalControlVar ICV : TrackableICVs) {
2355       auto ICVInfo = OMPInfoCache.ICVs[ICV];
2356       auto &Getter = OMPInfoCache.RFIs[ICVInfo.Getter];
2357       if (Getter.Declaration == getAssociatedFunction()) {
2358         AssociatedICV = ICVInfo.Kind;
2359         return;
2360       }
2361     }
2362 
2363     /// Unknown ICV.
2364     indicatePessimisticFixpoint();
2365   }
2366 
2367   ChangeStatus manifest(Attributor &A) override {
2368     if (!ReplVal.hasValue() || !ReplVal.getValue())
2369       return ChangeStatus::UNCHANGED;
2370 
2371     A.changeValueAfterManifest(*getCtxI(), **ReplVal);
2372     A.deleteAfterManifest(*getCtxI());
2373 
2374     return ChangeStatus::CHANGED;
2375   }
2376 
2377   // FIXME: come up with better string.
2378   const std::string getAsStr() const override { return "ICVTrackerCallSite"; }
2379 
2380   // FIXME: come up with some stats.
2381   void trackStatistics() const override {}
2382 
2383   InternalControlVar AssociatedICV;
2384   Optional<Value *> ReplVal;
2385 
2386   ChangeStatus updateImpl(Attributor &A) override {
2387     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2388         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
2389 
2390     // We don't have any information, so we assume it changes the ICV.
2391     if (!ICVTrackingAA.isAssumedTracked())
2392       return indicatePessimisticFixpoint();
2393 
2394     Optional<Value *> NewReplVal =
2395         ICVTrackingAA.getReplacementValue(AssociatedICV, getCtxI(), A);
2396 
2397     if (ReplVal == NewReplVal)
2398       return ChangeStatus::UNCHANGED;
2399 
2400     ReplVal = NewReplVal;
2401     return ChangeStatus::CHANGED;
2402   }
2403 
2404   // Return the value with which associated value can be replaced for specific
2405   // \p ICV.
2406   Optional<Value *>
2407   getUniqueReplacementValue(InternalControlVar ICV) const override {
2408     return ReplVal;
2409   }
2410 };
2411 
2412 struct AAICVTrackerCallSiteReturned : AAICVTracker {
2413   AAICVTrackerCallSiteReturned(const IRPosition &IRP, Attributor &A)
2414       : AAICVTracker(IRP, A) {}
2415 
2416   // FIXME: come up with better string.
2417   const std::string getAsStr() const override {
2418     return "ICVTrackerCallSiteReturned";
2419   }
2420 
2421   // FIXME: come up with some stats.
2422   void trackStatistics() const override {}
2423 
2424   /// We don't manifest anything for this AA.
2425   ChangeStatus manifest(Attributor &A) override {
2426     return ChangeStatus::UNCHANGED;
2427   }
2428 
2429   // Map of ICV to their values at specific program point.
2430   EnumeratedArray<Optional<Value *>, InternalControlVar,
2431                   InternalControlVar::ICV___last>
2432       ICVReplacementValuesMap;
2433 
2434   /// Return the value with which associated value can be replaced for specific
2435   /// \p ICV.
2436   Optional<Value *>
2437   getUniqueReplacementValue(InternalControlVar ICV) const override {
2438     return ICVReplacementValuesMap[ICV];
2439   }
2440 
2441   ChangeStatus updateImpl(Attributor &A) override {
2442     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2443     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2444         *this, IRPosition::returned(*getAssociatedFunction()),
2445         DepClassTy::REQUIRED);
2446 
2447     // We don't have any information, so we assume it changes the ICV.
2448     if (!ICVTrackingAA.isAssumedTracked())
2449       return indicatePessimisticFixpoint();
2450 
2451     for (InternalControlVar ICV : TrackableICVs) {
2452       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
2453       Optional<Value *> NewReplVal =
2454           ICVTrackingAA.getUniqueReplacementValue(ICV);
2455 
2456       if (ReplVal == NewReplVal)
2457         continue;
2458 
2459       ReplVal = NewReplVal;
2460       Changed = ChangeStatus::CHANGED;
2461     }
2462     return Changed;
2463   }
2464 };
2465 
2466 struct AAExecutionDomainFunction : public AAExecutionDomain {
2467   AAExecutionDomainFunction(const IRPosition &IRP, Attributor &A)
2468       : AAExecutionDomain(IRP, A) {}
2469 
2470   const std::string getAsStr() const override {
2471     return "[AAExecutionDomain] " + std::to_string(SingleThreadedBBs.size()) +
2472            "/" + std::to_string(NumBBs) + " BBs thread 0 only.";
2473   }
2474 
2475   /// See AbstractAttribute::trackStatistics().
2476   void trackStatistics() const override {}
2477 
2478   void initialize(Attributor &A) override {
2479     Function *F = getAnchorScope();
2480     for (const auto &BB : *F)
2481       SingleThreadedBBs.insert(&BB);
2482     NumBBs = SingleThreadedBBs.size();
2483   }
2484 
2485   ChangeStatus manifest(Attributor &A) override {
2486     LLVM_DEBUG({
2487       for (const BasicBlock *BB : SingleThreadedBBs)
2488         dbgs() << TAG << " Basic block @" << getAnchorScope()->getName() << " "
2489                << BB->getName() << " is executed by a single thread.\n";
2490     });
2491     return ChangeStatus::UNCHANGED;
2492   }
2493 
2494   ChangeStatus updateImpl(Attributor &A) override;
2495 
2496   /// Check if an instruction is executed by a single thread.
2497   bool isExecutedByInitialThreadOnly(const Instruction &I) const override {
2498     return isExecutedByInitialThreadOnly(*I.getParent());
2499   }
2500 
2501   bool isExecutedByInitialThreadOnly(const BasicBlock &BB) const override {
2502     return isValidState() && SingleThreadedBBs.contains(&BB);
2503   }
2504 
2505   /// Set of basic blocks that are executed by a single thread.
2506   DenseSet<const BasicBlock *> SingleThreadedBBs;
2507 
2508   /// Total number of basic blocks in this function.
2509   long unsigned NumBBs;
2510 };
2511 
2512 ChangeStatus AAExecutionDomainFunction::updateImpl(Attributor &A) {
2513   Function *F = getAnchorScope();
2514   ReversePostOrderTraversal<Function *> RPOT(F);
2515   auto NumSingleThreadedBBs = SingleThreadedBBs.size();
2516 
2517   bool AllCallSitesKnown;
2518   auto PredForCallSite = [&](AbstractCallSite ACS) {
2519     const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>(
2520         *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
2521         DepClassTy::REQUIRED);
2522     return ACS.isDirectCall() &&
2523            ExecutionDomainAA.isExecutedByInitialThreadOnly(
2524                *ACS.getInstruction());
2525   };
2526 
2527   if (!A.checkForAllCallSites(PredForCallSite, *this,
2528                               /* RequiresAllCallSites */ true,
2529                               AllCallSitesKnown))
2530     SingleThreadedBBs.erase(&F->getEntryBlock());
2531 
2532   auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2533   auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
2534 
2535   // Check if the edge into the successor block compares the __kmpc_target_init
2536   // result with -1. If we are in non-SPMD-mode that signals only the main
2537   // thread will execute the edge.
2538   auto IsInitialThreadOnly = [&](BranchInst *Edge, BasicBlock *SuccessorBB) {
2539     if (!Edge || !Edge->isConditional())
2540       return false;
2541     if (Edge->getSuccessor(0) != SuccessorBB)
2542       return false;
2543 
2544     auto *Cmp = dyn_cast<CmpInst>(Edge->getCondition());
2545     if (!Cmp || !Cmp->isTrueWhenEqual() || !Cmp->isEquality())
2546       return false;
2547 
2548     ConstantInt *C = dyn_cast<ConstantInt>(Cmp->getOperand(1));
2549     if (!C)
2550       return false;
2551 
2552     // Match:  -1 == __kmpc_target_init (for non-SPMD kernels only!)
2553     if (C->isAllOnesValue()) {
2554       auto *CB = dyn_cast<CallBase>(Cmp->getOperand(0));
2555       CB = CB ? OpenMPOpt::getCallIfRegularCall(*CB, &RFI) : nullptr;
2556       if (!CB)
2557         return false;
2558       const int InitIsSPMDArgNo = 1;
2559       auto *IsSPMDModeCI =
2560           dyn_cast<ConstantInt>(CB->getOperand(InitIsSPMDArgNo));
2561       return IsSPMDModeCI && IsSPMDModeCI->isZero();
2562     }
2563 
2564     return false;
2565   };
2566 
2567   // Merge all the predecessor states into the current basic block. A basic
2568   // block is executed by a single thread if all of its predecessors are.
2569   auto MergePredecessorStates = [&](BasicBlock *BB) {
2570     if (pred_begin(BB) == pred_end(BB))
2571       return SingleThreadedBBs.contains(BB);
2572 
2573     bool IsInitialThread = true;
2574     for (auto PredBB = pred_begin(BB), PredEndBB = pred_end(BB);
2575          PredBB != PredEndBB; ++PredBB) {
2576       if (!IsInitialThreadOnly(dyn_cast<BranchInst>((*PredBB)->getTerminator()),
2577                                BB))
2578         IsInitialThread &= SingleThreadedBBs.contains(*PredBB);
2579     }
2580 
2581     return IsInitialThread;
2582   };
2583 
2584   for (auto *BB : RPOT) {
2585     if (!MergePredecessorStates(BB))
2586       SingleThreadedBBs.erase(BB);
2587   }
2588 
2589   return (NumSingleThreadedBBs == SingleThreadedBBs.size())
2590              ? ChangeStatus::UNCHANGED
2591              : ChangeStatus::CHANGED;
2592 }
2593 
2594 /// Try to replace memory allocation calls called by a single thread with a
2595 /// static buffer of shared memory.
2596 struct AAHeapToShared : public StateWrapper<BooleanState, AbstractAttribute> {
2597   using Base = StateWrapper<BooleanState, AbstractAttribute>;
2598   AAHeapToShared(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
2599 
2600   /// Create an abstract attribute view for the position \p IRP.
2601   static AAHeapToShared &createForPosition(const IRPosition &IRP,
2602                                            Attributor &A);
2603 
2604   /// Returns true if HeapToShared conversion is assumed to be possible.
2605   virtual bool isAssumedHeapToShared(CallBase &CB) const = 0;
2606 
2607   /// Returns true if HeapToShared conversion is assumed and the CB is a
2608   /// callsite to a free operation to be removed.
2609   virtual bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const = 0;
2610 
2611   /// See AbstractAttribute::getName().
2612   const std::string getName() const override { return "AAHeapToShared"; }
2613 
2614   /// See AbstractAttribute::getIdAddr().
2615   const char *getIdAddr() const override { return &ID; }
2616 
2617   /// This function should return true if the type of the \p AA is
2618   /// AAHeapToShared.
2619   static bool classof(const AbstractAttribute *AA) {
2620     return (AA->getIdAddr() == &ID);
2621   }
2622 
2623   /// Unique ID (due to the unique address)
2624   static const char ID;
2625 };
2626 
2627 struct AAHeapToSharedFunction : public AAHeapToShared {
2628   AAHeapToSharedFunction(const IRPosition &IRP, Attributor &A)
2629       : AAHeapToShared(IRP, A) {}
2630 
2631   const std::string getAsStr() const override {
2632     return "[AAHeapToShared] " + std::to_string(MallocCalls.size()) +
2633            " malloc calls eligible.";
2634   }
2635 
2636   /// See AbstractAttribute::trackStatistics().
2637   void trackStatistics() const override {}
2638 
2639   /// This functions finds free calls that will be removed by the
2640   /// HeapToShared transformation.
2641   void findPotentialRemovedFreeCalls(Attributor &A) {
2642     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2643     auto &FreeRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared];
2644 
2645     PotentialRemovedFreeCalls.clear();
2646     // Update free call users of found malloc calls.
2647     for (CallBase *CB : MallocCalls) {
2648       SmallVector<CallBase *, 4> FreeCalls;
2649       for (auto *U : CB->users()) {
2650         CallBase *C = dyn_cast<CallBase>(U);
2651         if (C && C->getCalledFunction() == FreeRFI.Declaration)
2652           FreeCalls.push_back(C);
2653       }
2654 
2655       if (FreeCalls.size() != 1)
2656         continue;
2657 
2658       PotentialRemovedFreeCalls.insert(FreeCalls.front());
2659     }
2660   }
2661 
2662   void initialize(Attributor &A) override {
2663     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2664     auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
2665 
2666     for (User *U : RFI.Declaration->users())
2667       if (CallBase *CB = dyn_cast<CallBase>(U))
2668         MallocCalls.insert(CB);
2669 
2670     findPotentialRemovedFreeCalls(A);
2671   }
2672 
2673   bool isAssumedHeapToShared(CallBase &CB) const override {
2674     return isValidState() && MallocCalls.count(&CB);
2675   }
2676 
2677   bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const override {
2678     return isValidState() && PotentialRemovedFreeCalls.count(&CB);
2679   }
2680 
2681   ChangeStatus manifest(Attributor &A) override {
2682     if (MallocCalls.empty())
2683       return ChangeStatus::UNCHANGED;
2684 
2685     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2686     auto &FreeCall = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared];
2687 
2688     Function *F = getAnchorScope();
2689     auto *HS = A.lookupAAFor<AAHeapToStack>(IRPosition::function(*F), this,
2690                                             DepClassTy::OPTIONAL);
2691 
2692     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2693     for (CallBase *CB : MallocCalls) {
2694       // Skip replacing this if HeapToStack has already claimed it.
2695       if (HS && HS->isAssumedHeapToStack(*CB))
2696         continue;
2697 
2698       // Find the unique free call to remove it.
2699       SmallVector<CallBase *, 4> FreeCalls;
2700       for (auto *U : CB->users()) {
2701         CallBase *C = dyn_cast<CallBase>(U);
2702         if (C && C->getCalledFunction() == FreeCall.Declaration)
2703           FreeCalls.push_back(C);
2704       }
2705       if (FreeCalls.size() != 1)
2706         continue;
2707 
2708       ConstantInt *AllocSize = dyn_cast<ConstantInt>(CB->getArgOperand(0));
2709 
2710       LLVM_DEBUG(dbgs() << TAG << "Replace globalization call in "
2711                         << CB->getCaller()->getName() << " with "
2712                         << AllocSize->getZExtValue()
2713                         << " bytes of shared memory\n");
2714 
2715       // Create a new shared memory buffer of the same size as the allocation
2716       // and replace all the uses of the original allocation with it.
2717       Module *M = CB->getModule();
2718       Type *Int8Ty = Type::getInt8Ty(M->getContext());
2719       Type *Int8ArrTy = ArrayType::get(Int8Ty, AllocSize->getZExtValue());
2720       auto *SharedMem = new GlobalVariable(
2721           *M, Int8ArrTy, /* IsConstant */ false, GlobalValue::InternalLinkage,
2722           UndefValue::get(Int8ArrTy), CB->getName(), nullptr,
2723           GlobalValue::NotThreadLocal,
2724           static_cast<unsigned>(AddressSpace::Shared));
2725       auto *NewBuffer =
2726           ConstantExpr::getPointerCast(SharedMem, Int8Ty->getPointerTo());
2727 
2728       auto Remark = [&](OptimizationRemark OR) {
2729         return OR << "Replaced globalized variable with "
2730                   << ore::NV("SharedMemory", AllocSize->getZExtValue())
2731                   << ((AllocSize->getZExtValue() != 1) ? " bytes " : " byte ")
2732                   << "of shared memory.";
2733       };
2734       A.emitRemark<OptimizationRemark>(CB, "OMP111", Remark);
2735 
2736       SharedMem->setAlignment(MaybeAlign(32));
2737 
2738       A.changeValueAfterManifest(*CB, *NewBuffer);
2739       A.deleteAfterManifest(*CB);
2740       A.deleteAfterManifest(*FreeCalls.front());
2741 
2742       NumBytesMovedToSharedMemory += AllocSize->getZExtValue();
2743       Changed = ChangeStatus::CHANGED;
2744     }
2745 
2746     return Changed;
2747   }
2748 
2749   ChangeStatus updateImpl(Attributor &A) override {
2750     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2751     auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
2752     Function *F = getAnchorScope();
2753 
2754     auto NumMallocCalls = MallocCalls.size();
2755 
2756     // Only consider malloc calls executed by a single thread with a constant.
2757     for (User *U : RFI.Declaration->users()) {
2758       const auto &ED = A.getAAFor<AAExecutionDomain>(
2759           *this, IRPosition::function(*F), DepClassTy::REQUIRED);
2760       if (CallBase *CB = dyn_cast<CallBase>(U))
2761         if (!dyn_cast<ConstantInt>(CB->getArgOperand(0)) ||
2762             !ED.isExecutedByInitialThreadOnly(*CB))
2763           MallocCalls.erase(CB);
2764     }
2765 
2766     findPotentialRemovedFreeCalls(A);
2767 
2768     if (NumMallocCalls != MallocCalls.size())
2769       return ChangeStatus::CHANGED;
2770 
2771     return ChangeStatus::UNCHANGED;
2772   }
2773 
2774   /// Collection of all malloc calls in a function.
2775   SmallPtrSet<CallBase *, 4> MallocCalls;
2776   /// Collection of potentially removed free calls in a function.
2777   SmallPtrSet<CallBase *, 4> PotentialRemovedFreeCalls;
2778 };
2779 
2780 struct AAKernelInfo : public StateWrapper<KernelInfoState, AbstractAttribute> {
2781   using Base = StateWrapper<KernelInfoState, AbstractAttribute>;
2782   AAKernelInfo(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
2783 
2784   /// Statistics are tracked as part of manifest for now.
2785   void trackStatistics() const override {}
2786 
2787   /// See AbstractAttribute::getAsStr()
2788   const std::string getAsStr() const override {
2789     if (!isValidState())
2790       return "<invalid>";
2791     return std::string(SPMDCompatibilityTracker.isAssumed() ? "SPMD"
2792                                                             : "generic") +
2793            std::string(SPMDCompatibilityTracker.isAtFixpoint() ? " [FIX]"
2794                                                                : "") +
2795            std::string(" #PRs: ") +
2796            std::to_string(ReachedKnownParallelRegions.size()) +
2797            ", #Unknown PRs: " +
2798            std::to_string(ReachedUnknownParallelRegions.size());
2799   }
2800 
2801   /// Create an abstract attribute biew for the position \p IRP.
2802   static AAKernelInfo &createForPosition(const IRPosition &IRP, Attributor &A);
2803 
2804   /// See AbstractAttribute::getName()
2805   const std::string getName() const override { return "AAKernelInfo"; }
2806 
2807   /// See AbstractAttribute::getIdAddr()
2808   const char *getIdAddr() const override { return &ID; }
2809 
2810   /// This function should return true if the type of the \p AA is AAKernelInfo
2811   static bool classof(const AbstractAttribute *AA) {
2812     return (AA->getIdAddr() == &ID);
2813   }
2814 
2815   static const char ID;
2816 };
2817 
2818 /// The function kernel info abstract attribute, basically, what can we say
2819 /// about a function with regards to the KernelInfoState.
2820 struct AAKernelInfoFunction : AAKernelInfo {
2821   AAKernelInfoFunction(const IRPosition &IRP, Attributor &A)
2822       : AAKernelInfo(IRP, A) {}
2823 
2824   /// See AbstractAttribute::initialize(...).
2825   void initialize(Attributor &A) override {
2826     // This is a high-level transform that might change the constant arguments
2827     // of the init and dinit calls. We need to tell the Attributor about this
2828     // to avoid other parts using the current constant value for simpliication.
2829     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2830 
2831     Function *Fn = getAnchorScope();
2832     if (!OMPInfoCache.Kernels.count(Fn))
2833       return;
2834 
2835     // Add itself to the reaching kernel and set IsKernelEntry.
2836     ReachingKernelEntries.insert(Fn);
2837     IsKernelEntry = true;
2838 
2839     OMPInformationCache::RuntimeFunctionInfo &InitRFI =
2840         OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
2841     OMPInformationCache::RuntimeFunctionInfo &DeinitRFI =
2842         OMPInfoCache.RFIs[OMPRTL___kmpc_target_deinit];
2843 
2844     // For kernels we perform more initialization work, first we find the init
2845     // and deinit calls.
2846     auto StoreCallBase = [](Use &U,
2847                             OMPInformationCache::RuntimeFunctionInfo &RFI,
2848                             CallBase *&Storage) {
2849       CallBase *CB = OpenMPOpt::getCallIfRegularCall(U, &RFI);
2850       assert(CB &&
2851              "Unexpected use of __kmpc_target_init or __kmpc_target_deinit!");
2852       assert(!Storage &&
2853              "Multiple uses of __kmpc_target_init or __kmpc_target_deinit!");
2854       Storage = CB;
2855       return false;
2856     };
2857     InitRFI.foreachUse(
2858         [&](Use &U, Function &) {
2859           StoreCallBase(U, InitRFI, KernelInitCB);
2860           return false;
2861         },
2862         Fn);
2863     DeinitRFI.foreachUse(
2864         [&](Use &U, Function &) {
2865           StoreCallBase(U, DeinitRFI, KernelDeinitCB);
2866           return false;
2867         },
2868         Fn);
2869 
2870     assert((KernelInitCB && KernelDeinitCB) &&
2871            "Kernel without __kmpc_target_init or __kmpc_target_deinit!");
2872 
2873     // For kernels we might need to initialize/finalize the IsSPMD state and
2874     // we need to register a simplification callback so that the Attributor
2875     // knows the constant arguments to __kmpc_target_init and
2876     // __kmpc_target_deinit might actually change.
2877 
2878     Attributor::SimplifictionCallbackTy StateMachineSimplifyCB =
2879         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2880             bool &UsedAssumedInformation) -> Optional<Value *> {
2881       // IRP represents the "use generic state machine" argument of an
2882       // __kmpc_target_init call. We will answer this one with the internal
2883       // state. As long as we are not in an invalid state, we will create a
2884       // custom state machine so the value should be a `i1 false`. If we are
2885       // in an invalid state, we won't change the value that is in the IR.
2886       if (!isValidState())
2887         return nullptr;
2888       if (AA)
2889         A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2890       UsedAssumedInformation = !isAtFixpoint();
2891       auto *FalseVal =
2892           ConstantInt::getBool(IRP.getAnchorValue().getContext(), 0);
2893       return FalseVal;
2894     };
2895 
2896     Attributor::SimplifictionCallbackTy IsSPMDModeSimplifyCB =
2897         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2898             bool &UsedAssumedInformation) -> Optional<Value *> {
2899       // IRP represents the "SPMDCompatibilityTracker" argument of an
2900       // __kmpc_target_init or
2901       // __kmpc_target_deinit call. We will answer this one with the internal
2902       // state.
2903       if (!SPMDCompatibilityTracker.isValidState())
2904         return nullptr;
2905       if (!SPMDCompatibilityTracker.isAtFixpoint()) {
2906         if (AA)
2907           A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2908         UsedAssumedInformation = true;
2909       } else {
2910         UsedAssumedInformation = false;
2911       }
2912       auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(),
2913                                        SPMDCompatibilityTracker.isAssumed());
2914       return Val;
2915     };
2916 
2917     Attributor::SimplifictionCallbackTy IsGenericModeSimplifyCB =
2918         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2919             bool &UsedAssumedInformation) -> Optional<Value *> {
2920       // IRP represents the "RequiresFullRuntime" argument of an
2921       // __kmpc_target_init or __kmpc_target_deinit call. We will answer this
2922       // one with the internal state of the SPMDCompatibilityTracker, so if
2923       // generic then true, if SPMD then false.
2924       if (!SPMDCompatibilityTracker.isValidState())
2925         return nullptr;
2926       if (!SPMDCompatibilityTracker.isAtFixpoint()) {
2927         if (AA)
2928           A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2929         UsedAssumedInformation = true;
2930       } else {
2931         UsedAssumedInformation = false;
2932       }
2933       auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(),
2934                                        !SPMDCompatibilityTracker.isAssumed());
2935       return Val;
2936     };
2937 
2938     constexpr const int InitIsSPMDArgNo = 1;
2939     constexpr const int DeinitIsSPMDArgNo = 1;
2940     constexpr const int InitUseStateMachineArgNo = 2;
2941     constexpr const int InitRequiresFullRuntimeArgNo = 3;
2942     constexpr const int DeinitRequiresFullRuntimeArgNo = 2;
2943     A.registerSimplificationCallback(
2944         IRPosition::callsite_argument(*KernelInitCB, InitUseStateMachineArgNo),
2945         StateMachineSimplifyCB);
2946     A.registerSimplificationCallback(
2947         IRPosition::callsite_argument(*KernelInitCB, InitIsSPMDArgNo),
2948         IsSPMDModeSimplifyCB);
2949     A.registerSimplificationCallback(
2950         IRPosition::callsite_argument(*KernelDeinitCB, DeinitIsSPMDArgNo),
2951         IsSPMDModeSimplifyCB);
2952     A.registerSimplificationCallback(
2953         IRPosition::callsite_argument(*KernelInitCB,
2954                                       InitRequiresFullRuntimeArgNo),
2955         IsGenericModeSimplifyCB);
2956     A.registerSimplificationCallback(
2957         IRPosition::callsite_argument(*KernelDeinitCB,
2958                                       DeinitRequiresFullRuntimeArgNo),
2959         IsGenericModeSimplifyCB);
2960 
2961     // Check if we know we are in SPMD-mode already.
2962     ConstantInt *IsSPMDArg =
2963         dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitIsSPMDArgNo));
2964     if (IsSPMDArg && !IsSPMDArg->isZero())
2965       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
2966   }
2967 
2968   /// Modify the IR based on the KernelInfoState as the fixpoint iteration is
2969   /// finished now.
2970   ChangeStatus manifest(Attributor &A) override {
2971     // If we are not looking at a kernel with __kmpc_target_init and
2972     // __kmpc_target_deinit call we cannot actually manifest the information.
2973     if (!KernelInitCB || !KernelDeinitCB)
2974       return ChangeStatus::UNCHANGED;
2975 
2976     // Known SPMD-mode kernels need no manifest changes.
2977     if (SPMDCompatibilityTracker.isKnown())
2978       return ChangeStatus::UNCHANGED;
2979 
2980     // If we can we change the execution mode to SPMD-mode otherwise we build a
2981     // custom state machine.
2982     if (!changeToSPMDMode(A))
2983       buildCustomStateMachine(A);
2984 
2985     return ChangeStatus::CHANGED;
2986   }
2987 
2988   bool changeToSPMDMode(Attributor &A) {
2989     // If we have disabled SPMD-ization, stop
2990     if (DisableOpenMPOptSPMDization)
2991       indicatePessimisticFixpoint();
2992 
2993     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2994 
2995     if (!SPMDCompatibilityTracker.isAssumed()) {
2996       for (Instruction *NonCompatibleI : SPMDCompatibilityTracker) {
2997         if (!NonCompatibleI)
2998           continue;
2999 
3000         // Skip diagnostics on calls to known OpenMP runtime functions for now.
3001         if (auto *CB = dyn_cast<CallBase>(NonCompatibleI))
3002           if (OMPInfoCache.RTLFunctions.contains(CB->getCalledFunction()))
3003             continue;
3004 
3005         auto Remark = [&](OptimizationRemarkAnalysis ORA) {
3006           ORA << "Value has potential side effects preventing SPMD-mode "
3007                  "execution";
3008           if (isa<CallBase>(NonCompatibleI)) {
3009             ORA << ". Add `__attribute__((assume(\"ompx_spmd_amenable\")))` to "
3010                    "the called function to override";
3011           }
3012           return ORA << ".";
3013         };
3014         A.emitRemark<OptimizationRemarkAnalysis>(NonCompatibleI, "OMP121",
3015                                                  Remark);
3016 
3017         LLVM_DEBUG(dbgs() << TAG << "SPMD-incompatible side-effect: "
3018                           << *NonCompatibleI << "\n");
3019       }
3020 
3021       return false;
3022     }
3023 
3024     // Adjust the global exec mode flag that tells the runtime what mode this
3025     // kernel is executed in.
3026     Function *Kernel = getAnchorScope();
3027     GlobalVariable *ExecMode = Kernel->getParent()->getGlobalVariable(
3028         (Kernel->getName() + "_exec_mode").str());
3029     assert(ExecMode && "Kernel without exec mode?");
3030     assert(ExecMode->getInitializer() &&
3031            ExecMode->getInitializer()->isOneValue() &&
3032            "Initially non-SPMD kernel has SPMD exec mode!");
3033 
3034     // Set the global exec mode flag to indicate SPMD-Generic mode.
3035     constexpr int SPMDGeneric = 2;
3036     if (!ExecMode->getInitializer()->isZeroValue())
3037       ExecMode->setInitializer(
3038           ConstantInt::get(ExecMode->getInitializer()->getType(), SPMDGeneric));
3039 
3040     // Next rewrite the init and deinit calls to indicate we use SPMD-mode now.
3041     const int InitIsSPMDArgNo = 1;
3042     const int DeinitIsSPMDArgNo = 1;
3043     const int InitUseStateMachineArgNo = 2;
3044     const int InitRequiresFullRuntimeArgNo = 3;
3045     const int DeinitRequiresFullRuntimeArgNo = 2;
3046 
3047     auto &Ctx = getAnchorValue().getContext();
3048     A.changeUseAfterManifest(KernelInitCB->getArgOperandUse(InitIsSPMDArgNo),
3049                              *ConstantInt::getBool(Ctx, 1));
3050     A.changeUseAfterManifest(
3051         KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo),
3052         *ConstantInt::getBool(Ctx, 0));
3053     A.changeUseAfterManifest(
3054         KernelDeinitCB->getArgOperandUse(DeinitIsSPMDArgNo),
3055         *ConstantInt::getBool(Ctx, 1));
3056     A.changeUseAfterManifest(
3057         KernelInitCB->getArgOperandUse(InitRequiresFullRuntimeArgNo),
3058         *ConstantInt::getBool(Ctx, 0));
3059     A.changeUseAfterManifest(
3060         KernelDeinitCB->getArgOperandUse(DeinitRequiresFullRuntimeArgNo),
3061         *ConstantInt::getBool(Ctx, 0));
3062 
3063     ++NumOpenMPTargetRegionKernelsSPMD;
3064 
3065     auto Remark = [&](OptimizationRemark OR) {
3066       return OR << "Transformed generic-mode kernel to SPMD-mode.";
3067     };
3068     A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP120", Remark);
3069     return true;
3070   };
3071 
3072   ChangeStatus buildCustomStateMachine(Attributor &A) {
3073     // If we have disabled state machine rewrites, don't make a custom one
3074     if (DisableOpenMPOptStateMachineRewrite)
3075       return indicatePessimisticFixpoint();
3076 
3077     assert(ReachedKnownParallelRegions.isValidState() &&
3078            "Custom state machine with invalid parallel region states?");
3079 
3080     const int InitIsSPMDArgNo = 1;
3081     const int InitUseStateMachineArgNo = 2;
3082 
3083     // Check if the current configuration is non-SPMD and generic state machine.
3084     // If we already have SPMD mode or a custom state machine we do not need to
3085     // go any further. If it is anything but a constant something is weird and
3086     // we give up.
3087     ConstantInt *UseStateMachine = dyn_cast<ConstantInt>(
3088         KernelInitCB->getArgOperand(InitUseStateMachineArgNo));
3089     ConstantInt *IsSPMD =
3090         dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitIsSPMDArgNo));
3091 
3092     // If we are stuck with generic mode, try to create a custom device (=GPU)
3093     // state machine which is specialized for the parallel regions that are
3094     // reachable by the kernel.
3095     if (!UseStateMachine || UseStateMachine->isZero() || !IsSPMD ||
3096         !IsSPMD->isZero())
3097       return ChangeStatus::UNCHANGED;
3098 
3099     // If not SPMD mode, indicate we use a custom state machine now.
3100     auto &Ctx = getAnchorValue().getContext();
3101     auto *FalseVal = ConstantInt::getBool(Ctx, 0);
3102     A.changeUseAfterManifest(
3103         KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo), *FalseVal);
3104 
3105     // If we don't actually need a state machine we are done here. This can
3106     // happen if there simply are no parallel regions. In the resulting kernel
3107     // all worker threads will simply exit right away, leaving the main thread
3108     // to do the work alone.
3109     if (ReachedKnownParallelRegions.empty() &&
3110         ReachedUnknownParallelRegions.empty()) {
3111       ++NumOpenMPTargetRegionKernelsWithoutStateMachine;
3112 
3113       auto Remark = [&](OptimizationRemark OR) {
3114         return OR << "Removing unused state machine from generic-mode kernel.";
3115       };
3116       A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP130", Remark);
3117 
3118       return ChangeStatus::CHANGED;
3119     }
3120 
3121     // Keep track in the statistics of our new shiny custom state machine.
3122     if (ReachedUnknownParallelRegions.empty()) {
3123       ++NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback;
3124 
3125       auto Remark = [&](OptimizationRemark OR) {
3126         return OR << "Rewriting generic-mode kernel with a customized state "
3127                      "machine.";
3128       };
3129       A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP131", Remark);
3130     } else {
3131       ++NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback;
3132 
3133       auto Remark = [&](OptimizationRemarkAnalysis OR) {
3134         return OR << "Generic-mode kernel is executed with a customized state "
3135                      "machine that requires a fallback.";
3136       };
3137       A.emitRemark<OptimizationRemarkAnalysis>(KernelInitCB, "OMP132", Remark);
3138 
3139       // Tell the user why we ended up with a fallback.
3140       for (CallBase *UnknownParallelRegionCB : ReachedUnknownParallelRegions) {
3141         if (!UnknownParallelRegionCB)
3142           continue;
3143         auto Remark = [&](OptimizationRemarkAnalysis ORA) {
3144           return ORA << "Call may contain unknown parallel regions. Use "
3145                      << "`__attribute__((assume(\"omp_no_parallelism\")))` to "
3146                         "override.";
3147         };
3148         A.emitRemark<OptimizationRemarkAnalysis>(UnknownParallelRegionCB,
3149                                                  "OMP133", Remark);
3150       }
3151     }
3152 
3153     // Create all the blocks:
3154     //
3155     //                       InitCB = __kmpc_target_init(...)
3156     //                       bool IsWorker = InitCB >= 0;
3157     //                       if (IsWorker) {
3158     // SMBeginBB:               __kmpc_barrier_simple_spmd(...);
3159     //                         void *WorkFn;
3160     //                         bool Active = __kmpc_kernel_parallel(&WorkFn);
3161     //                         if (!WorkFn) return;
3162     // SMIsActiveCheckBB:       if (Active) {
3163     // SMIfCascadeCurrentBB:      if      (WorkFn == <ParFn0>)
3164     //                              ParFn0(...);
3165     // SMIfCascadeCurrentBB:      else if (WorkFn == <ParFn1>)
3166     //                              ParFn1(...);
3167     //                            ...
3168     // SMIfCascadeCurrentBB:      else
3169     //                              ((WorkFnTy*)WorkFn)(...);
3170     // SMEndParallelBB:           __kmpc_kernel_end_parallel(...);
3171     //                          }
3172     // SMDoneBB:                __kmpc_barrier_simple_spmd(...);
3173     //                          goto SMBeginBB;
3174     //                       }
3175     // UserCodeEntryBB:      // user code
3176     //                       __kmpc_target_deinit(...)
3177     //
3178     Function *Kernel = getAssociatedFunction();
3179     assert(Kernel && "Expected an associated function!");
3180 
3181     BasicBlock *InitBB = KernelInitCB->getParent();
3182     BasicBlock *UserCodeEntryBB = InitBB->splitBasicBlock(
3183         KernelInitCB->getNextNode(), "thread.user_code.check");
3184     BasicBlock *StateMachineBeginBB = BasicBlock::Create(
3185         Ctx, "worker_state_machine.begin", Kernel, UserCodeEntryBB);
3186     BasicBlock *StateMachineFinishedBB = BasicBlock::Create(
3187         Ctx, "worker_state_machine.finished", Kernel, UserCodeEntryBB);
3188     BasicBlock *StateMachineIsActiveCheckBB = BasicBlock::Create(
3189         Ctx, "worker_state_machine.is_active.check", Kernel, UserCodeEntryBB);
3190     BasicBlock *StateMachineIfCascadeCurrentBB =
3191         BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check",
3192                            Kernel, UserCodeEntryBB);
3193     BasicBlock *StateMachineEndParallelBB =
3194         BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.end",
3195                            Kernel, UserCodeEntryBB);
3196     BasicBlock *StateMachineDoneBarrierBB = BasicBlock::Create(
3197         Ctx, "worker_state_machine.done.barrier", Kernel, UserCodeEntryBB);
3198     A.registerManifestAddedBasicBlock(*InitBB);
3199     A.registerManifestAddedBasicBlock(*UserCodeEntryBB);
3200     A.registerManifestAddedBasicBlock(*StateMachineBeginBB);
3201     A.registerManifestAddedBasicBlock(*StateMachineFinishedBB);
3202     A.registerManifestAddedBasicBlock(*StateMachineIsActiveCheckBB);
3203     A.registerManifestAddedBasicBlock(*StateMachineIfCascadeCurrentBB);
3204     A.registerManifestAddedBasicBlock(*StateMachineEndParallelBB);
3205     A.registerManifestAddedBasicBlock(*StateMachineDoneBarrierBB);
3206 
3207     const DebugLoc &DLoc = KernelInitCB->getDebugLoc();
3208     ReturnInst::Create(Ctx, StateMachineFinishedBB)->setDebugLoc(DLoc);
3209 
3210     InitBB->getTerminator()->eraseFromParent();
3211     Instruction *IsWorker =
3212         ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_NE, KernelInitCB,
3213                          ConstantInt::get(KernelInitCB->getType(), -1),
3214                          "thread.is_worker", InitBB);
3215     IsWorker->setDebugLoc(DLoc);
3216     BranchInst::Create(StateMachineBeginBB, UserCodeEntryBB, IsWorker, InitBB);
3217 
3218     // Create local storage for the work function pointer.
3219     Type *VoidPtrTy = Type::getInt8PtrTy(Ctx);
3220     AllocaInst *WorkFnAI = new AllocaInst(VoidPtrTy, 0, "worker.work_fn.addr",
3221                                           &Kernel->getEntryBlock().front());
3222     WorkFnAI->setDebugLoc(DLoc);
3223 
3224     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3225     OMPInfoCache.OMPBuilder.updateToLocation(
3226         OpenMPIRBuilder::LocationDescription(
3227             IRBuilder<>::InsertPoint(StateMachineBeginBB,
3228                                      StateMachineBeginBB->end()),
3229             DLoc));
3230 
3231     Value *Ident = KernelInitCB->getArgOperand(0);
3232     Value *GTid = KernelInitCB;
3233 
3234     Module &M = *Kernel->getParent();
3235     FunctionCallee BarrierFn =
3236         OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3237             M, OMPRTL___kmpc_barrier_simple_spmd);
3238     CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineBeginBB)
3239         ->setDebugLoc(DLoc);
3240 
3241     FunctionCallee KernelParallelFn =
3242         OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3243             M, OMPRTL___kmpc_kernel_parallel);
3244     Instruction *IsActiveWorker = CallInst::Create(
3245         KernelParallelFn, {WorkFnAI}, "worker.is_active", StateMachineBeginBB);
3246     IsActiveWorker->setDebugLoc(DLoc);
3247     Instruction *WorkFn = new LoadInst(VoidPtrTy, WorkFnAI, "worker.work_fn",
3248                                        StateMachineBeginBB);
3249     WorkFn->setDebugLoc(DLoc);
3250 
3251     FunctionType *ParallelRegionFnTy = FunctionType::get(
3252         Type::getVoidTy(Ctx), {Type::getInt16Ty(Ctx), Type::getInt32Ty(Ctx)},
3253         false);
3254     Value *WorkFnCast = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
3255         WorkFn, ParallelRegionFnTy->getPointerTo(), "worker.work_fn.addr_cast",
3256         StateMachineBeginBB);
3257 
3258     Instruction *IsDone =
3259         ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFn,
3260                          Constant::getNullValue(VoidPtrTy), "worker.is_done",
3261                          StateMachineBeginBB);
3262     IsDone->setDebugLoc(DLoc);
3263     BranchInst::Create(StateMachineFinishedBB, StateMachineIsActiveCheckBB,
3264                        IsDone, StateMachineBeginBB)
3265         ->setDebugLoc(DLoc);
3266 
3267     BranchInst::Create(StateMachineIfCascadeCurrentBB,
3268                        StateMachineDoneBarrierBB, IsActiveWorker,
3269                        StateMachineIsActiveCheckBB)
3270         ->setDebugLoc(DLoc);
3271 
3272     Value *ZeroArg =
3273         Constant::getNullValue(ParallelRegionFnTy->getParamType(0));
3274 
3275     // Now that we have most of the CFG skeleton it is time for the if-cascade
3276     // that checks the function pointer we got from the runtime against the
3277     // parallel regions we expect, if there are any.
3278     for (int i = 0, e = ReachedKnownParallelRegions.size(); i < e; ++i) {
3279       auto *ParallelRegion = ReachedKnownParallelRegions[i];
3280       BasicBlock *PRExecuteBB = BasicBlock::Create(
3281           Ctx, "worker_state_machine.parallel_region.execute", Kernel,
3282           StateMachineEndParallelBB);
3283       CallInst::Create(ParallelRegion, {ZeroArg, GTid}, "", PRExecuteBB)
3284           ->setDebugLoc(DLoc);
3285       BranchInst::Create(StateMachineEndParallelBB, PRExecuteBB)
3286           ->setDebugLoc(DLoc);
3287 
3288       BasicBlock *PRNextBB =
3289           BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check",
3290                              Kernel, StateMachineEndParallelBB);
3291 
3292       // Check if we need to compare the pointer at all or if we can just
3293       // call the parallel region function.
3294       Value *IsPR;
3295       if (i + 1 < e || !ReachedUnknownParallelRegions.empty()) {
3296         Instruction *CmpI = ICmpInst::Create(
3297             ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFnCast, ParallelRegion,
3298             "worker.check_parallel_region", StateMachineIfCascadeCurrentBB);
3299         CmpI->setDebugLoc(DLoc);
3300         IsPR = CmpI;
3301       } else {
3302         IsPR = ConstantInt::getTrue(Ctx);
3303       }
3304 
3305       BranchInst::Create(PRExecuteBB, PRNextBB, IsPR,
3306                          StateMachineIfCascadeCurrentBB)
3307           ->setDebugLoc(DLoc);
3308       StateMachineIfCascadeCurrentBB = PRNextBB;
3309     }
3310 
3311     // At the end of the if-cascade we place the indirect function pointer call
3312     // in case we might need it, that is if there can be parallel regions we
3313     // have not handled in the if-cascade above.
3314     if (!ReachedUnknownParallelRegions.empty()) {
3315       StateMachineIfCascadeCurrentBB->setName(
3316           "worker_state_machine.parallel_region.fallback.execute");
3317       CallInst::Create(ParallelRegionFnTy, WorkFnCast, {ZeroArg, GTid}, "",
3318                        StateMachineIfCascadeCurrentBB)
3319           ->setDebugLoc(DLoc);
3320     }
3321     BranchInst::Create(StateMachineEndParallelBB,
3322                        StateMachineIfCascadeCurrentBB)
3323         ->setDebugLoc(DLoc);
3324 
3325     CallInst::Create(OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3326                          M, OMPRTL___kmpc_kernel_end_parallel),
3327                      {}, "", StateMachineEndParallelBB)
3328         ->setDebugLoc(DLoc);
3329     BranchInst::Create(StateMachineDoneBarrierBB, StateMachineEndParallelBB)
3330         ->setDebugLoc(DLoc);
3331 
3332     CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineDoneBarrierBB)
3333         ->setDebugLoc(DLoc);
3334     BranchInst::Create(StateMachineBeginBB, StateMachineDoneBarrierBB)
3335         ->setDebugLoc(DLoc);
3336 
3337     return ChangeStatus::CHANGED;
3338   }
3339 
3340   /// Fixpoint iteration update function. Will be called every time a dependence
3341   /// changed its state (and in the beginning).
3342   ChangeStatus updateImpl(Attributor &A) override {
3343     KernelInfoState StateBefore = getState();
3344 
3345     // Callback to check a read/write instruction.
3346     auto CheckRWInst = [&](Instruction &I) {
3347       // We handle calls later.
3348       if (isa<CallBase>(I))
3349         return true;
3350       // We only care about write effects.
3351       if (!I.mayWriteToMemory())
3352         return true;
3353       if (auto *SI = dyn_cast<StoreInst>(&I)) {
3354         SmallVector<const Value *> Objects;
3355         getUnderlyingObjects(SI->getPointerOperand(), Objects);
3356         if (llvm::all_of(Objects,
3357                          [](const Value *Obj) { return isa<AllocaInst>(Obj); }))
3358           return true;
3359       }
3360       // For now we give up on everything but stores.
3361       SPMDCompatibilityTracker.insert(&I);
3362       return true;
3363     };
3364 
3365     bool UsedAssumedInformationInCheckRWInst = false;
3366     if (!SPMDCompatibilityTracker.isAtFixpoint())
3367       if (!A.checkForAllReadWriteInstructions(
3368               CheckRWInst, *this, UsedAssumedInformationInCheckRWInst))
3369         SPMDCompatibilityTracker.indicatePessimisticFixpoint();
3370 
3371     if (!IsKernelEntry) {
3372       updateReachingKernelEntries(A);
3373       updateParallelLevels(A);
3374     }
3375 
3376     // Callback to check a call instruction.
3377     bool AllSPMDStatesWereFixed = true;
3378     auto CheckCallInst = [&](Instruction &I) {
3379       auto &CB = cast<CallBase>(I);
3380       auto &CBAA = A.getAAFor<AAKernelInfo>(
3381           *this, IRPosition::callsite_function(CB), DepClassTy::OPTIONAL);
3382       getState() ^= CBAA.getState();
3383       AllSPMDStatesWereFixed &= CBAA.SPMDCompatibilityTracker.isAtFixpoint();
3384       return true;
3385     };
3386 
3387     bool UsedAssumedInformationInCheckCallInst = false;
3388     if (!A.checkForAllCallLikeInstructions(
3389             CheckCallInst, *this, UsedAssumedInformationInCheckCallInst))
3390       return indicatePessimisticFixpoint();
3391 
3392     // If we haven't used any assumed information for the SPMD state we can fix
3393     // it.
3394     if (!UsedAssumedInformationInCheckRWInst &&
3395         !UsedAssumedInformationInCheckCallInst && AllSPMDStatesWereFixed)
3396       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
3397 
3398     return StateBefore == getState() ? ChangeStatus::UNCHANGED
3399                                      : ChangeStatus::CHANGED;
3400   }
3401 
3402 private:
3403   /// Update info regarding reaching kernels.
3404   void updateReachingKernelEntries(Attributor &A) {
3405     auto PredCallSite = [&](AbstractCallSite ACS) {
3406       Function *Caller = ACS.getInstruction()->getFunction();
3407 
3408       assert(Caller && "Caller is nullptr");
3409 
3410       auto &CAA = A.getOrCreateAAFor<AAKernelInfo>(
3411           IRPosition::function(*Caller), this, DepClassTy::REQUIRED);
3412       if (CAA.ReachingKernelEntries.isValidState()) {
3413         ReachingKernelEntries ^= CAA.ReachingKernelEntries;
3414         return true;
3415       }
3416 
3417       // We lost track of the caller of the associated function, any kernel
3418       // could reach now.
3419       ReachingKernelEntries.indicatePessimisticFixpoint();
3420 
3421       return true;
3422     };
3423 
3424     bool AllCallSitesKnown;
3425     if (!A.checkForAllCallSites(PredCallSite, *this,
3426                                 true /* RequireAllCallSites */,
3427                                 AllCallSitesKnown))
3428       ReachingKernelEntries.indicatePessimisticFixpoint();
3429   }
3430 
3431   /// Update info regarding parallel levels.
3432   void updateParallelLevels(Attributor &A) {
3433     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3434     OMPInformationCache::RuntimeFunctionInfo &Parallel51RFI =
3435         OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
3436 
3437     auto PredCallSite = [&](AbstractCallSite ACS) {
3438       Function *Caller = ACS.getInstruction()->getFunction();
3439 
3440       assert(Caller && "Caller is nullptr");
3441 
3442       auto &CAA =
3443           A.getOrCreateAAFor<AAKernelInfo>(IRPosition::function(*Caller));
3444       if (CAA.ParallelLevels.isValidState()) {
3445         // Any function that is called by `__kmpc_parallel_51` will not be
3446         // folded as the parallel level in the function is updated. In order to
3447         // get it right, all the analysis would depend on the implentation. That
3448         // said, if in the future any change to the implementation, the analysis
3449         // could be wrong. As a consequence, we are just conservative here.
3450         if (Caller == Parallel51RFI.Declaration) {
3451           ParallelLevels.indicatePessimisticFixpoint();
3452           return true;
3453         }
3454 
3455         ParallelLevels ^= CAA.ParallelLevels;
3456 
3457         return true;
3458       }
3459 
3460       // We lost track of the caller of the associated function, any kernel
3461       // could reach now.
3462       ParallelLevels.indicatePessimisticFixpoint();
3463 
3464       return true;
3465     };
3466 
3467     bool AllCallSitesKnown = true;
3468     if (!A.checkForAllCallSites(PredCallSite, *this,
3469                                 true /* RequireAllCallSites */,
3470                                 AllCallSitesKnown))
3471       ParallelLevels.indicatePessimisticFixpoint();
3472   }
3473 };
3474 
3475 /// The call site kernel info abstract attribute, basically, what can we say
3476 /// about a call site with regards to the KernelInfoState. For now this simply
3477 /// forwards the information from the callee.
3478 struct AAKernelInfoCallSite : AAKernelInfo {
3479   AAKernelInfoCallSite(const IRPosition &IRP, Attributor &A)
3480       : AAKernelInfo(IRP, A) {}
3481 
3482   /// See AbstractAttribute::initialize(...).
3483   void initialize(Attributor &A) override {
3484     AAKernelInfo::initialize(A);
3485 
3486     CallBase &CB = cast<CallBase>(getAssociatedValue());
3487     Function *Callee = getAssociatedFunction();
3488 
3489     // Helper to lookup an assumption string.
3490     auto HasAssumption = [](Function *Fn, StringRef AssumptionStr) {
3491       return Fn && hasAssumption(*Fn, AssumptionStr);
3492     };
3493 
3494     // Check for SPMD-mode assumptions.
3495     if (HasAssumption(Callee, "ompx_spmd_amenable"))
3496       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
3497 
3498     // First weed out calls we do not care about, that is readonly/readnone
3499     // calls, intrinsics, and "no_openmp" calls. Neither of these can reach a
3500     // parallel region or anything else we are looking for.
3501     if (!CB.mayWriteToMemory() || isa<IntrinsicInst>(CB)) {
3502       indicateOptimisticFixpoint();
3503       return;
3504     }
3505 
3506     // Next we check if we know the callee. If it is a known OpenMP function
3507     // we will handle them explicitly in the switch below. If it is not, we
3508     // will use an AAKernelInfo object on the callee to gather information and
3509     // merge that into the current state. The latter happens in the updateImpl.
3510     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3511     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee);
3512     if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) {
3513       // Unknown caller or declarations are not analyzable, we give up.
3514       if (!Callee || !A.isFunctionIPOAmendable(*Callee)) {
3515 
3516         // Unknown callees might contain parallel regions, except if they have
3517         // an appropriate assumption attached.
3518         if (!(HasAssumption(Callee, "omp_no_openmp") ||
3519               HasAssumption(Callee, "omp_no_parallelism")))
3520           ReachedUnknownParallelRegions.insert(&CB);
3521 
3522         // If SPMDCompatibilityTracker is not fixed, we need to give up on the
3523         // idea we can run something unknown in SPMD-mode.
3524         if (!SPMDCompatibilityTracker.isAtFixpoint())
3525           SPMDCompatibilityTracker.insert(&CB);
3526 
3527         // We have updated the state for this unknown call properly, there won't
3528         // be any change so we indicate a fixpoint.
3529         indicateOptimisticFixpoint();
3530       }
3531       // If the callee is known and can be used in IPO, we will update the state
3532       // based on the callee state in updateImpl.
3533       return;
3534     }
3535 
3536     const unsigned int WrapperFunctionArgNo = 6;
3537     RuntimeFunction RF = It->getSecond();
3538     switch (RF) {
3539     // All the functions we know are compatible with SPMD mode.
3540     case OMPRTL___kmpc_is_spmd_exec_mode:
3541     case OMPRTL___kmpc_for_static_fini:
3542     case OMPRTL___kmpc_global_thread_num:
3543     case OMPRTL___kmpc_get_hardware_num_threads_in_block:
3544     case OMPRTL___kmpc_get_hardware_num_blocks:
3545     case OMPRTL___kmpc_single:
3546     case OMPRTL___kmpc_end_single:
3547     case OMPRTL___kmpc_master:
3548     case OMPRTL___kmpc_end_master:
3549     case OMPRTL___kmpc_barrier:
3550       break;
3551     case OMPRTL___kmpc_for_static_init_4:
3552     case OMPRTL___kmpc_for_static_init_4u:
3553     case OMPRTL___kmpc_for_static_init_8:
3554     case OMPRTL___kmpc_for_static_init_8u: {
3555       // Check the schedule and allow static schedule in SPMD mode.
3556       unsigned ScheduleArgOpNo = 2;
3557       auto *ScheduleTypeCI =
3558           dyn_cast<ConstantInt>(CB.getArgOperand(ScheduleArgOpNo));
3559       unsigned ScheduleTypeVal =
3560           ScheduleTypeCI ? ScheduleTypeCI->getZExtValue() : 0;
3561       switch (OMPScheduleType(ScheduleTypeVal)) {
3562       case OMPScheduleType::Static:
3563       case OMPScheduleType::StaticChunked:
3564       case OMPScheduleType::Distribute:
3565       case OMPScheduleType::DistributeChunked:
3566         break;
3567       default:
3568         SPMDCompatibilityTracker.insert(&CB);
3569         break;
3570       };
3571     } break;
3572     case OMPRTL___kmpc_target_init:
3573       KernelInitCB = &CB;
3574       break;
3575     case OMPRTL___kmpc_target_deinit:
3576       KernelDeinitCB = &CB;
3577       break;
3578     case OMPRTL___kmpc_parallel_51:
3579       if (auto *ParallelRegion = dyn_cast<Function>(
3580               CB.getArgOperand(WrapperFunctionArgNo)->stripPointerCasts())) {
3581         ReachedKnownParallelRegions.insert(ParallelRegion);
3582         break;
3583       }
3584       // The condition above should usually get the parallel region function
3585       // pointer and record it. In the off chance it doesn't we assume the
3586       // worst.
3587       ReachedUnknownParallelRegions.insert(&CB);
3588       break;
3589     case OMPRTL___kmpc_omp_task:
3590       // We do not look into tasks right now, just give up.
3591       SPMDCompatibilityTracker.insert(&CB);
3592       ReachedUnknownParallelRegions.insert(&CB);
3593       break;
3594     case OMPRTL___kmpc_alloc_shared:
3595     case OMPRTL___kmpc_free_shared:
3596       // Return without setting a fixpoint, to be resolved in updateImpl.
3597       return;
3598     default:
3599       // Unknown OpenMP runtime calls cannot be executed in SPMD-mode,
3600       // generally.
3601       SPMDCompatibilityTracker.insert(&CB);
3602       break;
3603     }
3604     // All other OpenMP runtime calls will not reach parallel regions so they
3605     // can be safely ignored for now. Since it is a known OpenMP runtime call we
3606     // have now modeled all effects and there is no need for any update.
3607     indicateOptimisticFixpoint();
3608   }
3609 
3610   ChangeStatus updateImpl(Attributor &A) override {
3611     // TODO: Once we have call site specific value information we can provide
3612     //       call site specific liveness information and then it makes
3613     //       sense to specialize attributes for call sites arguments instead of
3614     //       redirecting requests to the callee argument.
3615     Function *F = getAssociatedFunction();
3616 
3617     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3618     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(F);
3619 
3620     // If F is not a runtime function, propagate the AAKernelInfo of the callee.
3621     if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) {
3622       const IRPosition &FnPos = IRPosition::function(*F);
3623       auto &FnAA = A.getAAFor<AAKernelInfo>(*this, FnPos, DepClassTy::REQUIRED);
3624       if (getState() == FnAA.getState())
3625         return ChangeStatus::UNCHANGED;
3626       getState() = FnAA.getState();
3627       return ChangeStatus::CHANGED;
3628     }
3629 
3630     // F is a runtime function that allocates or frees memory, check
3631     // AAHeapToStack and AAHeapToShared.
3632     KernelInfoState StateBefore = getState();
3633     assert((It->getSecond() == OMPRTL___kmpc_alloc_shared ||
3634             It->getSecond() == OMPRTL___kmpc_free_shared) &&
3635            "Expected a __kmpc_alloc_shared or __kmpc_free_shared runtime call");
3636 
3637     CallBase &CB = cast<CallBase>(getAssociatedValue());
3638 
3639     auto &HeapToStackAA = A.getAAFor<AAHeapToStack>(
3640         *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL);
3641     auto &HeapToSharedAA = A.getAAFor<AAHeapToShared>(
3642         *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL);
3643 
3644     RuntimeFunction RF = It->getSecond();
3645 
3646     switch (RF) {
3647     // If neither HeapToStack nor HeapToShared assume the call is removed,
3648     // assume SPMD incompatibility.
3649     case OMPRTL___kmpc_alloc_shared:
3650       if (!HeapToStackAA.isAssumedHeapToStack(CB) &&
3651           !HeapToSharedAA.isAssumedHeapToShared(CB))
3652         SPMDCompatibilityTracker.insert(&CB);
3653       break;
3654     case OMPRTL___kmpc_free_shared:
3655       if (!HeapToStackAA.isAssumedHeapToStackRemovedFree(CB) &&
3656           !HeapToSharedAA.isAssumedHeapToSharedRemovedFree(CB))
3657         SPMDCompatibilityTracker.insert(&CB);
3658       break;
3659     default:
3660       SPMDCompatibilityTracker.insert(&CB);
3661     }
3662 
3663     return StateBefore == getState() ? ChangeStatus::UNCHANGED
3664                                      : ChangeStatus::CHANGED;
3665   }
3666 };
3667 
3668 struct AAFoldRuntimeCall
3669     : public StateWrapper<BooleanState, AbstractAttribute> {
3670   using Base = StateWrapper<BooleanState, AbstractAttribute>;
3671 
3672   AAFoldRuntimeCall(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
3673 
3674   /// Statistics are tracked as part of manifest for now.
3675   void trackStatistics() const override {}
3676 
3677   /// Create an abstract attribute biew for the position \p IRP.
3678   static AAFoldRuntimeCall &createForPosition(const IRPosition &IRP,
3679                                               Attributor &A);
3680 
3681   /// See AbstractAttribute::getName()
3682   const std::string getName() const override { return "AAFoldRuntimeCall"; }
3683 
3684   /// See AbstractAttribute::getIdAddr()
3685   const char *getIdAddr() const override { return &ID; }
3686 
3687   /// This function should return true if the type of the \p AA is
3688   /// AAFoldRuntimeCall
3689   static bool classof(const AbstractAttribute *AA) {
3690     return (AA->getIdAddr() == &ID);
3691   }
3692 
3693   static const char ID;
3694 };
3695 
3696 struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall {
3697   AAFoldRuntimeCallCallSiteReturned(const IRPosition &IRP, Attributor &A)
3698       : AAFoldRuntimeCall(IRP, A) {}
3699 
3700   /// See AbstractAttribute::getAsStr()
3701   const std::string getAsStr() const override {
3702     if (!isValidState())
3703       return "<invalid>";
3704 
3705     std::string Str("simplified value: ");
3706 
3707     if (!SimplifiedValue.hasValue())
3708       return Str + std::string("none");
3709 
3710     if (!SimplifiedValue.getValue())
3711       return Str + std::string("nullptr");
3712 
3713     if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.getValue()))
3714       return Str + std::to_string(CI->getSExtValue());
3715 
3716     return Str + std::string("unknown");
3717   }
3718 
3719   void initialize(Attributor &A) override {
3720     if (DisableOpenMPOptFolding)
3721       indicatePessimisticFixpoint();
3722 
3723     Function *Callee = getAssociatedFunction();
3724 
3725     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3726     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee);
3727     assert(It != OMPInfoCache.RuntimeFunctionIDMap.end() &&
3728            "Expected a known OpenMP runtime function");
3729 
3730     RFKind = It->getSecond();
3731 
3732     CallBase &CB = cast<CallBase>(getAssociatedValue());
3733     A.registerSimplificationCallback(
3734         IRPosition::callsite_returned(CB),
3735         [&](const IRPosition &IRP, const AbstractAttribute *AA,
3736             bool &UsedAssumedInformation) -> Optional<Value *> {
3737           assert((isValidState() || (SimplifiedValue.hasValue() &&
3738                                      SimplifiedValue.getValue() == nullptr)) &&
3739                  "Unexpected invalid state!");
3740 
3741           if (!isAtFixpoint()) {
3742             UsedAssumedInformation = true;
3743             if (AA)
3744               A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
3745           }
3746           return SimplifiedValue;
3747         });
3748   }
3749 
3750   ChangeStatus updateImpl(Attributor &A) override {
3751     ChangeStatus Changed = ChangeStatus::UNCHANGED;
3752     switch (RFKind) {
3753     case OMPRTL___kmpc_is_spmd_exec_mode:
3754       Changed |= foldIsSPMDExecMode(A);
3755       break;
3756     case OMPRTL___kmpc_is_generic_main_thread_id:
3757       Changed |= foldIsGenericMainThread(A);
3758       break;
3759     case OMPRTL___kmpc_parallel_level:
3760       Changed |= foldParallelLevel(A);
3761       break;
3762     case OMPRTL___kmpc_get_hardware_num_threads_in_block:
3763       Changed = Changed | foldKernelFnAttribute(A, "omp_target_thread_limit");
3764       break;
3765     case OMPRTL___kmpc_get_hardware_num_blocks:
3766       Changed = Changed | foldKernelFnAttribute(A, "omp_target_num_teams");
3767       break;
3768     default:
3769       llvm_unreachable("Unhandled OpenMP runtime function!");
3770     }
3771 
3772     return Changed;
3773   }
3774 
3775   ChangeStatus manifest(Attributor &A) override {
3776     ChangeStatus Changed = ChangeStatus::UNCHANGED;
3777 
3778     if (SimplifiedValue.hasValue() && SimplifiedValue.getValue()) {
3779       Instruction &CB = *getCtxI();
3780       A.changeValueAfterManifest(CB, **SimplifiedValue);
3781       A.deleteAfterManifest(CB);
3782 
3783       LLVM_DEBUG(dbgs() << TAG << "Folding runtime call: " << CB << " with "
3784                         << **SimplifiedValue << "\n");
3785 
3786       Changed = ChangeStatus::CHANGED;
3787     }
3788 
3789     return Changed;
3790   }
3791 
3792   ChangeStatus indicatePessimisticFixpoint() override {
3793     SimplifiedValue = nullptr;
3794     return AAFoldRuntimeCall::indicatePessimisticFixpoint();
3795   }
3796 
3797 private:
3798   /// Fold __kmpc_is_spmd_exec_mode into a constant if possible.
3799   ChangeStatus foldIsSPMDExecMode(Attributor &A) {
3800     Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
3801 
3802     unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0;
3803     unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0;
3804     auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>(
3805         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
3806 
3807     if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState())
3808       return indicatePessimisticFixpoint();
3809 
3810     for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) {
3811       auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K),
3812                                           DepClassTy::REQUIRED);
3813 
3814       if (!AA.isValidState()) {
3815         SimplifiedValue = nullptr;
3816         return indicatePessimisticFixpoint();
3817       }
3818 
3819       if (AA.SPMDCompatibilityTracker.isAssumed()) {
3820         if (AA.SPMDCompatibilityTracker.isAtFixpoint())
3821           ++KnownSPMDCount;
3822         else
3823           ++AssumedSPMDCount;
3824       } else {
3825         if (AA.SPMDCompatibilityTracker.isAtFixpoint())
3826           ++KnownNonSPMDCount;
3827         else
3828           ++AssumedNonSPMDCount;
3829       }
3830     }
3831 
3832     if ((AssumedSPMDCount + KnownSPMDCount) &&
3833         (AssumedNonSPMDCount + KnownNonSPMDCount))
3834       return indicatePessimisticFixpoint();
3835 
3836     auto &Ctx = getAnchorValue().getContext();
3837     if (KnownSPMDCount || AssumedSPMDCount) {
3838       assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 &&
3839              "Expected only SPMD kernels!");
3840       // All reaching kernels are in SPMD mode. Update all function calls to
3841       // __kmpc_is_spmd_exec_mode to 1.
3842       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true);
3843     } else if (KnownNonSPMDCount || AssumedNonSPMDCount) {
3844       assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 &&
3845              "Expected only non-SPMD kernels!");
3846       // All reaching kernels are in non-SPMD mode. Update all function
3847       // calls to __kmpc_is_spmd_exec_mode to 0.
3848       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), false);
3849     } else {
3850       // We have empty reaching kernels, therefore we cannot tell if the
3851       // associated call site can be folded. At this moment, SimplifiedValue
3852       // must be none.
3853       assert(!SimplifiedValue.hasValue() && "SimplifiedValue should be none");
3854     }
3855 
3856     return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
3857                                                     : ChangeStatus::CHANGED;
3858   }
3859 
3860   /// Fold __kmpc_is_generic_main_thread_id into a constant if possible.
3861   ChangeStatus foldIsGenericMainThread(Attributor &A) {
3862     Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
3863 
3864     CallBase &CB = cast<CallBase>(getAssociatedValue());
3865     Function *F = CB.getFunction();
3866     const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>(
3867         *this, IRPosition::function(*F), DepClassTy::REQUIRED);
3868 
3869     if (!ExecutionDomainAA.isValidState())
3870       return indicatePessimisticFixpoint();
3871 
3872     auto &Ctx = getAnchorValue().getContext();
3873     if (ExecutionDomainAA.isExecutedByInitialThreadOnly(CB))
3874       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true);
3875     else
3876       return indicatePessimisticFixpoint();
3877 
3878     return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
3879                                                     : ChangeStatus::CHANGED;
3880   }
3881 
3882   /// Fold __kmpc_parallel_level into a constant if possible.
3883   ChangeStatus foldParallelLevel(Attributor &A) {
3884     Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
3885 
3886     auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>(
3887         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
3888 
3889     if (!CallerKernelInfoAA.ParallelLevels.isValidState())
3890       return indicatePessimisticFixpoint();
3891 
3892     if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState())
3893       return indicatePessimisticFixpoint();
3894 
3895     if (CallerKernelInfoAA.ReachingKernelEntries.empty()) {
3896       assert(!SimplifiedValue.hasValue() &&
3897              "SimplifiedValue should keep none at this point");
3898       return ChangeStatus::UNCHANGED;
3899     }
3900 
3901     unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0;
3902     unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0;
3903     for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) {
3904       auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K),
3905                                           DepClassTy::REQUIRED);
3906       if (!AA.SPMDCompatibilityTracker.isValidState())
3907         return indicatePessimisticFixpoint();
3908 
3909       if (AA.SPMDCompatibilityTracker.isAssumed()) {
3910         if (AA.SPMDCompatibilityTracker.isAtFixpoint())
3911           ++KnownSPMDCount;
3912         else
3913           ++AssumedSPMDCount;
3914       } else {
3915         if (AA.SPMDCompatibilityTracker.isAtFixpoint())
3916           ++KnownNonSPMDCount;
3917         else
3918           ++AssumedNonSPMDCount;
3919       }
3920     }
3921 
3922     if ((AssumedSPMDCount + KnownSPMDCount) &&
3923         (AssumedNonSPMDCount + KnownNonSPMDCount))
3924       return indicatePessimisticFixpoint();
3925 
3926     auto &Ctx = getAnchorValue().getContext();
3927     // If the caller can only be reached by SPMD kernel entries, the parallel
3928     // level is 1. Similarly, if the caller can only be reached by non-SPMD
3929     // kernel entries, it is 0.
3930     if (AssumedSPMDCount || KnownSPMDCount) {
3931       assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 &&
3932              "Expected only SPMD kernels!");
3933       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), 1);
3934     } else {
3935       assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 &&
3936              "Expected only non-SPMD kernels!");
3937       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), 0);
3938     }
3939     return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
3940                                                     : ChangeStatus::CHANGED;
3941   }
3942 
3943   ChangeStatus foldKernelFnAttribute(Attributor &A, llvm::StringRef Attr) {
3944     // Specialize only if all the calls agree with the attribute constant value
3945     int32_t CurrentAttrValue = -1;
3946     Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
3947 
3948     auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>(
3949         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
3950 
3951     if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState())
3952       return indicatePessimisticFixpoint();
3953 
3954     // Iterate over the kernels that reach this function
3955     for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) {
3956       int32_t NextAttrVal = -1;
3957       if (K->hasFnAttribute(Attr))
3958         NextAttrVal =
3959             std::stoi(K->getFnAttribute(Attr).getValueAsString().str());
3960 
3961       if (NextAttrVal == -1 ||
3962           (CurrentAttrValue != -1 && CurrentAttrValue != NextAttrVal))
3963         return indicatePessimisticFixpoint();
3964       CurrentAttrValue = NextAttrVal;
3965     }
3966 
3967     if (CurrentAttrValue != -1) {
3968       auto &Ctx = getAnchorValue().getContext();
3969       SimplifiedValue =
3970           ConstantInt::get(Type::getInt32Ty(Ctx), CurrentAttrValue);
3971     }
3972     return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
3973                                                     : ChangeStatus::CHANGED;
3974   }
3975 
3976   /// An optional value the associated value is assumed to fold to. That is, we
3977   /// assume the associated value (which is a call) can be replaced by this
3978   /// simplified value.
3979   Optional<Value *> SimplifiedValue;
3980 
3981   /// The runtime function kind of the callee of the associated call site.
3982   RuntimeFunction RFKind;
3983 };
3984 
3985 } // namespace
3986 
3987 /// Register folding callsite
3988 void OpenMPOpt::registerFoldRuntimeCall(RuntimeFunction RF) {
3989   auto &RFI = OMPInfoCache.RFIs[RF];
3990   RFI.foreachUse(SCC, [&](Use &U, Function &F) {
3991     CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &RFI);
3992     if (!CI)
3993       return false;
3994     A.getOrCreateAAFor<AAFoldRuntimeCall>(
3995         IRPosition::callsite_returned(*CI), /* QueryingAA */ nullptr,
3996         DepClassTy::NONE, /* ForceUpdate */ false,
3997         /* UpdateAfterInit */ false);
3998     return false;
3999   });
4000 }
4001 
4002 void OpenMPOpt::registerAAs(bool IsModulePass) {
4003   if (SCC.empty())
4004 
4005     return;
4006   if (IsModulePass) {
4007     // Ensure we create the AAKernelInfo AAs first and without triggering an
4008     // update. This will make sure we register all value simplification
4009     // callbacks before any other AA has the chance to create an AAValueSimplify
4010     // or similar.
4011     for (Function *Kernel : OMPInfoCache.Kernels)
4012       A.getOrCreateAAFor<AAKernelInfo>(
4013           IRPosition::function(*Kernel), /* QueryingAA */ nullptr,
4014           DepClassTy::NONE, /* ForceUpdate */ false,
4015           /* UpdateAfterInit */ false);
4016 
4017 
4018     registerFoldRuntimeCall(OMPRTL___kmpc_is_generic_main_thread_id);
4019     registerFoldRuntimeCall(OMPRTL___kmpc_is_spmd_exec_mode);
4020     registerFoldRuntimeCall(OMPRTL___kmpc_parallel_level);
4021     registerFoldRuntimeCall(OMPRTL___kmpc_get_hardware_num_threads_in_block);
4022     registerFoldRuntimeCall(OMPRTL___kmpc_get_hardware_num_blocks);
4023   }
4024 
4025   // Create CallSite AA for all Getters.
4026   for (int Idx = 0; Idx < OMPInfoCache.ICVs.size() - 1; ++Idx) {
4027     auto ICVInfo = OMPInfoCache.ICVs[static_cast<InternalControlVar>(Idx)];
4028 
4029     auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter];
4030 
4031     auto CreateAA = [&](Use &U, Function &Caller) {
4032       CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI);
4033       if (!CI)
4034         return false;
4035 
4036       auto &CB = cast<CallBase>(*CI);
4037 
4038       IRPosition CBPos = IRPosition::callsite_function(CB);
4039       A.getOrCreateAAFor<AAICVTracker>(CBPos);
4040       return false;
4041     };
4042 
4043     GetterRFI.foreachUse(SCC, CreateAA);
4044   }
4045   auto &GlobalizationRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
4046   auto CreateAA = [&](Use &U, Function &F) {
4047     A.getOrCreateAAFor<AAHeapToShared>(IRPosition::function(F));
4048     return false;
4049   };
4050   if (!DisableOpenMPOptDeglobalization)
4051     GlobalizationRFI.foreachUse(SCC, CreateAA);
4052 
4053   // Create an ExecutionDomain AA for every function and a HeapToStack AA for
4054   // every function if there is a device kernel.
4055   if (!isOpenMPDevice(M))
4056     return;
4057 
4058   for (auto *F : SCC) {
4059     if (F->isDeclaration())
4060       continue;
4061 
4062     A.getOrCreateAAFor<AAExecutionDomain>(IRPosition::function(*F));
4063     if (!DisableOpenMPOptDeglobalization)
4064       A.getOrCreateAAFor<AAHeapToStack>(IRPosition::function(*F));
4065 
4066     for (auto &I : instructions(*F)) {
4067       if (auto *LI = dyn_cast<LoadInst>(&I)) {
4068         bool UsedAssumedInformation = false;
4069         A.getAssumedSimplified(IRPosition::value(*LI), /* AA */ nullptr,
4070                                UsedAssumedInformation);
4071       }
4072     }
4073   }
4074 }
4075 
4076 const char AAICVTracker::ID = 0;
4077 const char AAKernelInfo::ID = 0;
4078 const char AAExecutionDomain::ID = 0;
4079 const char AAHeapToShared::ID = 0;
4080 const char AAFoldRuntimeCall::ID = 0;
4081 
4082 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP,
4083                                               Attributor &A) {
4084   AAICVTracker *AA = nullptr;
4085   switch (IRP.getPositionKind()) {
4086   case IRPosition::IRP_INVALID:
4087   case IRPosition::IRP_FLOAT:
4088   case IRPosition::IRP_ARGUMENT:
4089   case IRPosition::IRP_CALL_SITE_ARGUMENT:
4090     llvm_unreachable("ICVTracker can only be created for function position!");
4091   case IRPosition::IRP_RETURNED:
4092     AA = new (A.Allocator) AAICVTrackerFunctionReturned(IRP, A);
4093     break;
4094   case IRPosition::IRP_CALL_SITE_RETURNED:
4095     AA = new (A.Allocator) AAICVTrackerCallSiteReturned(IRP, A);
4096     break;
4097   case IRPosition::IRP_CALL_SITE:
4098     AA = new (A.Allocator) AAICVTrackerCallSite(IRP, A);
4099     break;
4100   case IRPosition::IRP_FUNCTION:
4101     AA = new (A.Allocator) AAICVTrackerFunction(IRP, A);
4102     break;
4103   }
4104 
4105   return *AA;
4106 }
4107 
4108 AAExecutionDomain &AAExecutionDomain::createForPosition(const IRPosition &IRP,
4109                                                         Attributor &A) {
4110   AAExecutionDomainFunction *AA = nullptr;
4111   switch (IRP.getPositionKind()) {
4112   case IRPosition::IRP_INVALID:
4113   case IRPosition::IRP_FLOAT:
4114   case IRPosition::IRP_ARGUMENT:
4115   case IRPosition::IRP_CALL_SITE_ARGUMENT:
4116   case IRPosition::IRP_RETURNED:
4117   case IRPosition::IRP_CALL_SITE_RETURNED:
4118   case IRPosition::IRP_CALL_SITE:
4119     llvm_unreachable(
4120         "AAExecutionDomain can only be created for function position!");
4121   case IRPosition::IRP_FUNCTION:
4122     AA = new (A.Allocator) AAExecutionDomainFunction(IRP, A);
4123     break;
4124   }
4125 
4126   return *AA;
4127 }
4128 
4129 AAHeapToShared &AAHeapToShared::createForPosition(const IRPosition &IRP,
4130                                                   Attributor &A) {
4131   AAHeapToSharedFunction *AA = nullptr;
4132   switch (IRP.getPositionKind()) {
4133   case IRPosition::IRP_INVALID:
4134   case IRPosition::IRP_FLOAT:
4135   case IRPosition::IRP_ARGUMENT:
4136   case IRPosition::IRP_CALL_SITE_ARGUMENT:
4137   case IRPosition::IRP_RETURNED:
4138   case IRPosition::IRP_CALL_SITE_RETURNED:
4139   case IRPosition::IRP_CALL_SITE:
4140     llvm_unreachable(
4141         "AAHeapToShared can only be created for function position!");
4142   case IRPosition::IRP_FUNCTION:
4143     AA = new (A.Allocator) AAHeapToSharedFunction(IRP, A);
4144     break;
4145   }
4146 
4147   return *AA;
4148 }
4149 
4150 AAKernelInfo &AAKernelInfo::createForPosition(const IRPosition &IRP,
4151                                               Attributor &A) {
4152   AAKernelInfo *AA = nullptr;
4153   switch (IRP.getPositionKind()) {
4154   case IRPosition::IRP_INVALID:
4155   case IRPosition::IRP_FLOAT:
4156   case IRPosition::IRP_ARGUMENT:
4157   case IRPosition::IRP_RETURNED:
4158   case IRPosition::IRP_CALL_SITE_RETURNED:
4159   case IRPosition::IRP_CALL_SITE_ARGUMENT:
4160     llvm_unreachable("KernelInfo can only be created for function position!");
4161   case IRPosition::IRP_CALL_SITE:
4162     AA = new (A.Allocator) AAKernelInfoCallSite(IRP, A);
4163     break;
4164   case IRPosition::IRP_FUNCTION:
4165     AA = new (A.Allocator) AAKernelInfoFunction(IRP, A);
4166     break;
4167   }
4168 
4169   return *AA;
4170 }
4171 
4172 AAFoldRuntimeCall &AAFoldRuntimeCall::createForPosition(const IRPosition &IRP,
4173                                                         Attributor &A) {
4174   AAFoldRuntimeCall *AA = nullptr;
4175   switch (IRP.getPositionKind()) {
4176   case IRPosition::IRP_INVALID:
4177   case IRPosition::IRP_FLOAT:
4178   case IRPosition::IRP_ARGUMENT:
4179   case IRPosition::IRP_RETURNED:
4180   case IRPosition::IRP_FUNCTION:
4181   case IRPosition::IRP_CALL_SITE:
4182   case IRPosition::IRP_CALL_SITE_ARGUMENT:
4183     llvm_unreachable("KernelInfo can only be created for call site position!");
4184   case IRPosition::IRP_CALL_SITE_RETURNED:
4185     AA = new (A.Allocator) AAFoldRuntimeCallCallSiteReturned(IRP, A);
4186     break;
4187   }
4188 
4189   return *AA;
4190 }
4191 
4192 PreservedAnalyses OpenMPOptPass::run(Module &M, ModuleAnalysisManager &AM) {
4193   if (!containsOpenMP(M))
4194     return PreservedAnalyses::all();
4195   if (DisableOpenMPOptimizations)
4196     return PreservedAnalyses::all();
4197 
4198   FunctionAnalysisManager &FAM =
4199       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
4200   KernelSet Kernels = getDeviceKernels(M);
4201 
4202   auto IsCalled = [&](Function &F) {
4203     if (Kernels.contains(&F))
4204       return true;
4205     for (const User *U : F.users())
4206       if (!isa<BlockAddress>(U))
4207         return true;
4208     return false;
4209   };
4210 
4211   auto EmitRemark = [&](Function &F) {
4212     auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4213     ORE.emit([&]() {
4214       OptimizationRemarkAnalysis ORA(DEBUG_TYPE, "OMP140", &F);
4215       return ORA << "Could not internalize function. "
4216                  << "Some optimizations may not be possible. [OMP140]";
4217     });
4218   };
4219 
4220   // Create internal copies of each function if this is a kernel Module. This
4221   // allows iterprocedural passes to see every call edge.
4222   DenseMap<Function *, Function *> InternalizedMap;
4223   if (isOpenMPDevice(M)) {
4224     SmallPtrSet<Function *, 16> InternalizeFns;
4225     for (Function &F : M)
4226       if (!F.isDeclaration() && !Kernels.contains(&F) && IsCalled(F) &&
4227           !DisableInternalization) {
4228         if (Attributor::isInternalizable(F)) {
4229           InternalizeFns.insert(&F);
4230         } else if (!F.hasLocalLinkage() && !F.hasFnAttribute(Attribute::Cold)) {
4231           EmitRemark(F);
4232         }
4233       }
4234 
4235     Attributor::internalizeFunctions(InternalizeFns, InternalizedMap);
4236   }
4237 
4238   // Look at every function in the Module unless it was internalized.
4239   SmallVector<Function *, 16> SCC;
4240   for (Function &F : M)
4241     if (!F.isDeclaration() && !InternalizedMap.lookup(&F))
4242       SCC.push_back(&F);
4243 
4244   if (SCC.empty())
4245     return PreservedAnalyses::all();
4246 
4247   AnalysisGetter AG(FAM);
4248 
4249   auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
4250     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
4251   };
4252 
4253   BumpPtrAllocator Allocator;
4254   CallGraphUpdater CGUpdater;
4255 
4256   SetVector<Function *> Functions(SCC.begin(), SCC.end());
4257   OMPInformationCache InfoCache(M, AG, Allocator, /*CGSCC*/ Functions, Kernels);
4258 
4259   unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4260   Attributor A(Functions, InfoCache, CGUpdater, nullptr, true, false,
4261                MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4262 
4263   OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4264   bool Changed = OMPOpt.run(true);
4265   if (Changed)
4266     return PreservedAnalyses::none();
4267 
4268   return PreservedAnalyses::all();
4269 }
4270 
4271 PreservedAnalyses OpenMPOptCGSCCPass::run(LazyCallGraph::SCC &C,
4272                                           CGSCCAnalysisManager &AM,
4273                                           LazyCallGraph &CG,
4274                                           CGSCCUpdateResult &UR) {
4275   if (!containsOpenMP(*C.begin()->getFunction().getParent()))
4276     return PreservedAnalyses::all();
4277   if (DisableOpenMPOptimizations)
4278     return PreservedAnalyses::all();
4279 
4280   SmallVector<Function *, 16> SCC;
4281   // If there are kernels in the module, we have to run on all SCC's.
4282   for (LazyCallGraph::Node &N : C) {
4283     Function *Fn = &N.getFunction();
4284     SCC.push_back(Fn);
4285   }
4286 
4287   if (SCC.empty())
4288     return PreservedAnalyses::all();
4289 
4290   Module &M = *C.begin()->getFunction().getParent();
4291 
4292   KernelSet Kernels = getDeviceKernels(M);
4293 
4294   FunctionAnalysisManager &FAM =
4295       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
4296 
4297   AnalysisGetter AG(FAM);
4298 
4299   auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
4300     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
4301   };
4302 
4303   BumpPtrAllocator Allocator;
4304   CallGraphUpdater CGUpdater;
4305   CGUpdater.initialize(CG, C, AM, UR);
4306 
4307   SetVector<Function *> Functions(SCC.begin(), SCC.end());
4308   OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator,
4309                                 /*CGSCC*/ Functions, Kernels);
4310 
4311   unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4312   Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true,
4313                MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4314 
4315   OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4316   bool Changed = OMPOpt.run(false);
4317   if (Changed)
4318     return PreservedAnalyses::none();
4319 
4320   return PreservedAnalyses::all();
4321 }
4322 
4323 namespace {
4324 
4325 struct OpenMPOptCGSCCLegacyPass : public CallGraphSCCPass {
4326   CallGraphUpdater CGUpdater;
4327   static char ID;
4328 
4329   OpenMPOptCGSCCLegacyPass() : CallGraphSCCPass(ID) {
4330     initializeOpenMPOptCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
4331   }
4332 
4333   void getAnalysisUsage(AnalysisUsage &AU) const override {
4334     CallGraphSCCPass::getAnalysisUsage(AU);
4335   }
4336 
4337   bool runOnSCC(CallGraphSCC &CGSCC) override {
4338     if (!containsOpenMP(CGSCC.getCallGraph().getModule()))
4339       return false;
4340     if (DisableOpenMPOptimizations || skipSCC(CGSCC))
4341       return false;
4342 
4343     SmallVector<Function *, 16> SCC;
4344     // If there are kernels in the module, we have to run on all SCC's.
4345     for (CallGraphNode *CGN : CGSCC) {
4346       Function *Fn = CGN->getFunction();
4347       if (!Fn || Fn->isDeclaration())
4348         continue;
4349       SCC.push_back(Fn);
4350     }
4351 
4352     if (SCC.empty())
4353       return false;
4354 
4355     Module &M = CGSCC.getCallGraph().getModule();
4356     KernelSet Kernels = getDeviceKernels(M);
4357 
4358     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
4359     CGUpdater.initialize(CG, CGSCC);
4360 
4361     // Maintain a map of functions to avoid rebuilding the ORE
4362     DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap;
4363     auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & {
4364       std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F];
4365       if (!ORE)
4366         ORE = std::make_unique<OptimizationRemarkEmitter>(F);
4367       return *ORE;
4368     };
4369 
4370     AnalysisGetter AG;
4371     SetVector<Function *> Functions(SCC.begin(), SCC.end());
4372     BumpPtrAllocator Allocator;
4373     OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG,
4374                                   Allocator,
4375                                   /*CGSCC*/ Functions, Kernels);
4376 
4377     unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4378     Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true,
4379                  MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4380 
4381     OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4382     return OMPOpt.run(false);
4383   }
4384 
4385   bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
4386 };
4387 
4388 } // end anonymous namespace
4389 
4390 KernelSet llvm::omp::getDeviceKernels(Module &M) {
4391   // TODO: Create a more cross-platform way of determining device kernels.
4392   NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
4393   KernelSet Kernels;
4394 
4395   if (!MD)
4396     return Kernels;
4397 
4398   for (auto *Op : MD->operands()) {
4399     if (Op->getNumOperands() < 2)
4400       continue;
4401     MDString *KindID = dyn_cast<MDString>(Op->getOperand(1));
4402     if (!KindID || KindID->getString() != "kernel")
4403       continue;
4404 
4405     Function *KernelFn =
4406         mdconst::dyn_extract_or_null<Function>(Op->getOperand(0));
4407     if (!KernelFn)
4408       continue;
4409 
4410     ++NumOpenMPTargetRegionKernels;
4411 
4412     Kernels.insert(KernelFn);
4413   }
4414 
4415   return Kernels;
4416 }
4417 
4418 bool llvm::omp::containsOpenMP(Module &M) {
4419   Metadata *MD = M.getModuleFlag("openmp");
4420   if (!MD)
4421     return false;
4422 
4423   return true;
4424 }
4425 
4426 bool llvm::omp::isOpenMPDevice(Module &M) {
4427   Metadata *MD = M.getModuleFlag("openmp-device");
4428   if (!MD)
4429     return false;
4430 
4431   return true;
4432 }
4433 
4434 char OpenMPOptCGSCCLegacyPass::ID = 0;
4435 
4436 INITIALIZE_PASS_BEGIN(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc",
4437                       "OpenMP specific optimizations", false, false)
4438 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
4439 INITIALIZE_PASS_END(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc",
4440                     "OpenMP specific optimizations", false, false)
4441 
4442 Pass *llvm::createOpenMPOptCGSCCLegacyPass() {
4443   return new OpenMPOptCGSCCLegacyPass();
4444 }
4445