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