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