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   /// RAII struct to temporarily change an RTL function's linkage to external.
1764   /// This prevents it from being mistakenly removed by other optimizations.
1765   struct ExternalizationRAII {
1766     ExternalizationRAII(OMPInformationCache &OMPInfoCache,
1767                         RuntimeFunction RFKind)
1768         : OMPInfoCache(OMPInfoCache),
1769           Declaration(OMPInfoCache.RFIs[RFKind].Declaration) {
1770       if (!Declaration)
1771         return;
1772 
1773       LinkageType = Declaration->getLinkage();
1774       Declaration->setLinkage(GlobalValue::ExternalLinkage);
1775     }
1776 
1777     ~ExternalizationRAII() {
1778       if (!Declaration)
1779         return;
1780 
1781       Declaration->setLinkage(LinkageType);
1782     }
1783 
1784     OMPInformationCache &OMPInfoCache;
1785     Function *Declaration;
1786     GlobalValue::LinkageTypes LinkageType;
1787   };
1788 
1789   /// The underlying module.
1790   Module &M;
1791 
1792   /// The SCC we are operating on.
1793   SmallVectorImpl<Function *> &SCC;
1794 
1795   /// Callback to update the call graph, the first argument is a removed call,
1796   /// the second an optional replacement call.
1797   CallGraphUpdater &CGUpdater;
1798 
1799   /// Callback to get an OptimizationRemarkEmitter from a Function *
1800   OptimizationRemarkGetter OREGetter;
1801 
1802   /// OpenMP-specific information cache. Also Used for Attributor runs.
1803   OMPInformationCache &OMPInfoCache;
1804 
1805   /// Attributor instance.
1806   Attributor &A;
1807 
1808   /// Helper function to run Attributor on SCC.
1809   bool runAttributor(bool IsModulePass) {
1810     if (SCC.empty())
1811       return false;
1812 
1813     // Temporarily make these function have external linkage so the Attributor
1814     // doesn't remove them when we try to look them up later.
1815     ExternalizationRAII Parallel(OMPInfoCache, OMPRTL___kmpc_kernel_parallel);
1816     ExternalizationRAII EndParallel(OMPInfoCache,
1817                                     OMPRTL___kmpc_kernel_end_parallel);
1818     ExternalizationRAII BarrierSPMD(OMPInfoCache,
1819                                     OMPRTL___kmpc_barrier_simple_spmd);
1820 
1821     registerAAs(IsModulePass);
1822 
1823     ChangeStatus Changed = A.run();
1824 
1825     LLVM_DEBUG(dbgs() << "[Attributor] Done with " << SCC.size()
1826                       << " functions, result: " << Changed << ".\n");
1827 
1828     return Changed == ChangeStatus::CHANGED;
1829   }
1830 
1831   /// Populate the Attributor with abstract attribute opportunities in the
1832   /// function.
1833   void registerAAs(bool IsModulePass);
1834 };
1835 
1836 Kernel OpenMPOpt::getUniqueKernelFor(Function &F) {
1837   if (!OMPInfoCache.ModuleSlice.count(&F))
1838     return nullptr;
1839 
1840   // Use a scope to keep the lifetime of the CachedKernel short.
1841   {
1842     Optional<Kernel> &CachedKernel = UniqueKernelMap[&F];
1843     if (CachedKernel)
1844       return *CachedKernel;
1845 
1846     // TODO: We should use an AA to create an (optimistic and callback
1847     //       call-aware) call graph. For now we stick to simple patterns that
1848     //       are less powerful, basically the worst fixpoint.
1849     if (isKernel(F)) {
1850       CachedKernel = Kernel(&F);
1851       return *CachedKernel;
1852     }
1853 
1854     CachedKernel = nullptr;
1855     if (!F.hasLocalLinkage()) {
1856 
1857       // See https://openmp.llvm.org/remarks/OptimizationRemarks.html
1858       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
1859         return ORA << "Potentially unknown OpenMP target region caller.";
1860       };
1861       emitRemark<OptimizationRemarkAnalysis>(&F, "OMP100", Remark);
1862 
1863       return nullptr;
1864     }
1865   }
1866 
1867   auto GetUniqueKernelForUse = [&](const Use &U) -> Kernel {
1868     if (auto *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
1869       // Allow use in equality comparisons.
1870       if (Cmp->isEquality())
1871         return getUniqueKernelFor(*Cmp);
1872       return nullptr;
1873     }
1874     if (auto *CB = dyn_cast<CallBase>(U.getUser())) {
1875       // Allow direct calls.
1876       if (CB->isCallee(&U))
1877         return getUniqueKernelFor(*CB);
1878 
1879       OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI =
1880           OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
1881       // Allow the use in __kmpc_parallel_51 calls.
1882       if (OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI))
1883         return getUniqueKernelFor(*CB);
1884       return nullptr;
1885     }
1886     // Disallow every other use.
1887     return nullptr;
1888   };
1889 
1890   // TODO: In the future we want to track more than just a unique kernel.
1891   SmallPtrSet<Kernel, 2> PotentialKernels;
1892   OMPInformationCache::foreachUse(F, [&](const Use &U) {
1893     PotentialKernels.insert(GetUniqueKernelForUse(U));
1894   });
1895 
1896   Kernel K = nullptr;
1897   if (PotentialKernels.size() == 1)
1898     K = *PotentialKernels.begin();
1899 
1900   // Cache the result.
1901   UniqueKernelMap[&F] = K;
1902 
1903   return K;
1904 }
1905 
1906 bool OpenMPOpt::rewriteDeviceCodeStateMachine() {
1907   OMPInformationCache::RuntimeFunctionInfo &KernelParallelRFI =
1908       OMPInfoCache.RFIs[OMPRTL___kmpc_parallel_51];
1909 
1910   bool Changed = false;
1911   if (!KernelParallelRFI)
1912     return Changed;
1913 
1914   for (Function *F : SCC) {
1915 
1916     // Check if the function is a use in a __kmpc_parallel_51 call at
1917     // all.
1918     bool UnknownUse = false;
1919     bool KernelParallelUse = false;
1920     unsigned NumDirectCalls = 0;
1921 
1922     SmallVector<Use *, 2> ToBeReplacedStateMachineUses;
1923     OMPInformationCache::foreachUse(*F, [&](Use &U) {
1924       if (auto *CB = dyn_cast<CallBase>(U.getUser()))
1925         if (CB->isCallee(&U)) {
1926           ++NumDirectCalls;
1927           return;
1928         }
1929 
1930       if (isa<ICmpInst>(U.getUser())) {
1931         ToBeReplacedStateMachineUses.push_back(&U);
1932         return;
1933       }
1934 
1935       // Find wrapper functions that represent parallel kernels.
1936       CallInst *CI =
1937           OpenMPOpt::getCallIfRegularCall(*U.getUser(), &KernelParallelRFI);
1938       const unsigned int WrapperFunctionArgNo = 6;
1939       if (!KernelParallelUse && CI &&
1940           CI->getArgOperandNo(&U) == WrapperFunctionArgNo) {
1941         KernelParallelUse = true;
1942         ToBeReplacedStateMachineUses.push_back(&U);
1943         return;
1944       }
1945       UnknownUse = true;
1946     });
1947 
1948     // Do not emit a remark if we haven't seen a __kmpc_parallel_51
1949     // use.
1950     if (!KernelParallelUse)
1951       continue;
1952 
1953     // If this ever hits, we should investigate.
1954     // TODO: Checking the number of uses is not a necessary restriction and
1955     // should be lifted.
1956     if (UnknownUse || NumDirectCalls != 1 ||
1957         ToBeReplacedStateMachineUses.size() > 2) {
1958       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
1959         return ORA << "Parallel region is used in "
1960                    << (UnknownUse ? "unknown" : "unexpected")
1961                    << " ways. Will not attempt to rewrite the state machine.";
1962       };
1963       emitRemark<OptimizationRemarkAnalysis>(F, "OMP101", Remark);
1964       continue;
1965     }
1966 
1967     // Even if we have __kmpc_parallel_51 calls, we (for now) give
1968     // up if the function is not called from a unique kernel.
1969     Kernel K = getUniqueKernelFor(*F);
1970     if (!K) {
1971       auto Remark = [&](OptimizationRemarkAnalysis ORA) {
1972         return ORA << "Parallel region is not called from a unique kernel. "
1973                       "Will not attempt to rewrite the state machine.";
1974       };
1975       emitRemark<OptimizationRemarkAnalysis>(F, "OMP102", Remark);
1976       continue;
1977     }
1978 
1979     // We now know F is a parallel body function called only from the kernel K.
1980     // We also identified the state machine uses in which we replace the
1981     // function pointer by a new global symbol for identification purposes. This
1982     // ensures only direct calls to the function are left.
1983 
1984     Module &M = *F->getParent();
1985     Type *Int8Ty = Type::getInt8Ty(M.getContext());
1986 
1987     auto *ID = new GlobalVariable(
1988         M, Int8Ty, /* isConstant */ true, GlobalValue::PrivateLinkage,
1989         UndefValue::get(Int8Ty), F->getName() + ".ID");
1990 
1991     for (Use *U : ToBeReplacedStateMachineUses)
1992       U->set(ConstantExpr::getBitCast(ID, U->get()->getType()));
1993 
1994     ++NumOpenMPParallelRegionsReplacedInGPUStateMachine;
1995 
1996     Changed = true;
1997   }
1998 
1999   return Changed;
2000 }
2001 
2002 /// Abstract Attribute for tracking ICV values.
2003 struct AAICVTracker : public StateWrapper<BooleanState, AbstractAttribute> {
2004   using Base = StateWrapper<BooleanState, AbstractAttribute>;
2005   AAICVTracker(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
2006 
2007   void initialize(Attributor &A) override {
2008     Function *F = getAnchorScope();
2009     if (!F || !A.isFunctionIPOAmendable(*F))
2010       indicatePessimisticFixpoint();
2011   }
2012 
2013   /// Returns true if value is assumed to be tracked.
2014   bool isAssumedTracked() const { return getAssumed(); }
2015 
2016   /// Returns true if value is known to be tracked.
2017   bool isKnownTracked() const { return getAssumed(); }
2018 
2019   /// Create an abstract attribute biew for the position \p IRP.
2020   static AAICVTracker &createForPosition(const IRPosition &IRP, Attributor &A);
2021 
2022   /// Return the value with which \p I can be replaced for specific \p ICV.
2023   virtual Optional<Value *> getReplacementValue(InternalControlVar ICV,
2024                                                 const Instruction *I,
2025                                                 Attributor &A) const {
2026     return None;
2027   }
2028 
2029   /// Return an assumed unique ICV value if a single candidate is found. If
2030   /// there cannot be one, return a nullptr. If it is not clear yet, return the
2031   /// Optional::NoneType.
2032   virtual Optional<Value *>
2033   getUniqueReplacementValue(InternalControlVar ICV) const = 0;
2034 
2035   // Currently only nthreads is being tracked.
2036   // this array will only grow with time.
2037   InternalControlVar TrackableICVs[1] = {ICV_nthreads};
2038 
2039   /// See AbstractAttribute::getName()
2040   const std::string getName() const override { return "AAICVTracker"; }
2041 
2042   /// See AbstractAttribute::getIdAddr()
2043   const char *getIdAddr() const override { return &ID; }
2044 
2045   /// This function should return true if the type of the \p AA is AAICVTracker
2046   static bool classof(const AbstractAttribute *AA) {
2047     return (AA->getIdAddr() == &ID);
2048   }
2049 
2050   static const char ID;
2051 };
2052 
2053 struct AAICVTrackerFunction : public AAICVTracker {
2054   AAICVTrackerFunction(const IRPosition &IRP, Attributor &A)
2055       : AAICVTracker(IRP, A) {}
2056 
2057   // FIXME: come up with better string.
2058   const std::string getAsStr() const override { return "ICVTrackerFunction"; }
2059 
2060   // FIXME: come up with some stats.
2061   void trackStatistics() const override {}
2062 
2063   /// We don't manifest anything for this AA.
2064   ChangeStatus manifest(Attributor &A) override {
2065     return ChangeStatus::UNCHANGED;
2066   }
2067 
2068   // Map of ICV to their values at specific program point.
2069   EnumeratedArray<DenseMap<Instruction *, Value *>, InternalControlVar,
2070                   InternalControlVar::ICV___last>
2071       ICVReplacementValuesMap;
2072 
2073   ChangeStatus updateImpl(Attributor &A) override {
2074     ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
2075 
2076     Function *F = getAnchorScope();
2077 
2078     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2079 
2080     for (InternalControlVar ICV : TrackableICVs) {
2081       auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
2082 
2083       auto &ValuesMap = ICVReplacementValuesMap[ICV];
2084       auto TrackValues = [&](Use &U, Function &) {
2085         CallInst *CI = OpenMPOpt::getCallIfRegularCall(U);
2086         if (!CI)
2087           return false;
2088 
2089         // FIXME: handle setters with more that 1 arguments.
2090         /// Track new value.
2091         if (ValuesMap.insert(std::make_pair(CI, CI->getArgOperand(0))).second)
2092           HasChanged = ChangeStatus::CHANGED;
2093 
2094         return false;
2095       };
2096 
2097       auto CallCheck = [&](Instruction &I) {
2098         Optional<Value *> ReplVal = getValueForCall(A, &I, ICV);
2099         if (ReplVal.hasValue() &&
2100             ValuesMap.insert(std::make_pair(&I, *ReplVal)).second)
2101           HasChanged = ChangeStatus::CHANGED;
2102 
2103         return true;
2104       };
2105 
2106       // Track all changes of an ICV.
2107       SetterRFI.foreachUse(TrackValues, F);
2108 
2109       bool UsedAssumedInformation = false;
2110       A.checkForAllInstructions(CallCheck, *this, {Instruction::Call},
2111                                 UsedAssumedInformation,
2112                                 /* CheckBBLivenessOnly */ true);
2113 
2114       /// TODO: Figure out a way to avoid adding entry in
2115       /// ICVReplacementValuesMap
2116       Instruction *Entry = &F->getEntryBlock().front();
2117       if (HasChanged == ChangeStatus::CHANGED && !ValuesMap.count(Entry))
2118         ValuesMap.insert(std::make_pair(Entry, nullptr));
2119     }
2120 
2121     return HasChanged;
2122   }
2123 
2124   /// Hepler to check if \p I is a call and get the value for it if it is
2125   /// unique.
2126   Optional<Value *> getValueForCall(Attributor &A, const Instruction *I,
2127                                     InternalControlVar &ICV) const {
2128 
2129     const auto *CB = dyn_cast<CallBase>(I);
2130     if (!CB || CB->hasFnAttr("no_openmp") ||
2131         CB->hasFnAttr("no_openmp_routines"))
2132       return None;
2133 
2134     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2135     auto &GetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Getter];
2136     auto &SetterRFI = OMPInfoCache.RFIs[OMPInfoCache.ICVs[ICV].Setter];
2137     Function *CalledFunction = CB->getCalledFunction();
2138 
2139     // Indirect call, assume ICV changes.
2140     if (CalledFunction == nullptr)
2141       return nullptr;
2142     if (CalledFunction == GetterRFI.Declaration)
2143       return None;
2144     if (CalledFunction == SetterRFI.Declaration) {
2145       if (ICVReplacementValuesMap[ICV].count(I))
2146         return ICVReplacementValuesMap[ICV].lookup(I);
2147 
2148       return nullptr;
2149     }
2150 
2151     // Since we don't know, assume it changes the ICV.
2152     if (CalledFunction->isDeclaration())
2153       return nullptr;
2154 
2155     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2156         *this, IRPosition::callsite_returned(*CB), DepClassTy::REQUIRED);
2157 
2158     if (ICVTrackingAA.isAssumedTracked())
2159       return ICVTrackingAA.getUniqueReplacementValue(ICV);
2160 
2161     // If we don't know, assume it changes.
2162     return nullptr;
2163   }
2164 
2165   // We don't check unique value for a function, so return None.
2166   Optional<Value *>
2167   getUniqueReplacementValue(InternalControlVar ICV) const override {
2168     return None;
2169   }
2170 
2171   /// Return the value with which \p I can be replaced for specific \p ICV.
2172   Optional<Value *> getReplacementValue(InternalControlVar ICV,
2173                                         const Instruction *I,
2174                                         Attributor &A) const override {
2175     const auto &ValuesMap = ICVReplacementValuesMap[ICV];
2176     if (ValuesMap.count(I))
2177       return ValuesMap.lookup(I);
2178 
2179     SmallVector<const Instruction *, 16> Worklist;
2180     SmallPtrSet<const Instruction *, 16> Visited;
2181     Worklist.push_back(I);
2182 
2183     Optional<Value *> ReplVal;
2184 
2185     while (!Worklist.empty()) {
2186       const Instruction *CurrInst = Worklist.pop_back_val();
2187       if (!Visited.insert(CurrInst).second)
2188         continue;
2189 
2190       const BasicBlock *CurrBB = CurrInst->getParent();
2191 
2192       // Go up and look for all potential setters/calls that might change the
2193       // ICV.
2194       while ((CurrInst = CurrInst->getPrevNode())) {
2195         if (ValuesMap.count(CurrInst)) {
2196           Optional<Value *> NewReplVal = ValuesMap.lookup(CurrInst);
2197           // Unknown value, track new.
2198           if (!ReplVal.hasValue()) {
2199             ReplVal = NewReplVal;
2200             break;
2201           }
2202 
2203           // If we found a new value, we can't know the icv value anymore.
2204           if (NewReplVal.hasValue())
2205             if (ReplVal != NewReplVal)
2206               return nullptr;
2207 
2208           break;
2209         }
2210 
2211         Optional<Value *> NewReplVal = getValueForCall(A, CurrInst, ICV);
2212         if (!NewReplVal.hasValue())
2213           continue;
2214 
2215         // Unknown value, track new.
2216         if (!ReplVal.hasValue()) {
2217           ReplVal = NewReplVal;
2218           break;
2219         }
2220 
2221         // if (NewReplVal.hasValue())
2222         // We found a new value, we can't know the icv value anymore.
2223         if (ReplVal != NewReplVal)
2224           return nullptr;
2225       }
2226 
2227       // If we are in the same BB and we have a value, we are done.
2228       if (CurrBB == I->getParent() && ReplVal.hasValue())
2229         return ReplVal;
2230 
2231       // Go through all predecessors and add terminators for analysis.
2232       for (const BasicBlock *Pred : predecessors(CurrBB))
2233         if (const Instruction *Terminator = Pred->getTerminator())
2234           Worklist.push_back(Terminator);
2235     }
2236 
2237     return ReplVal;
2238   }
2239 };
2240 
2241 struct AAICVTrackerFunctionReturned : AAICVTracker {
2242   AAICVTrackerFunctionReturned(const IRPosition &IRP, Attributor &A)
2243       : AAICVTracker(IRP, A) {}
2244 
2245   // FIXME: come up with better string.
2246   const std::string getAsStr() const override {
2247     return "ICVTrackerFunctionReturned";
2248   }
2249 
2250   // FIXME: come up with some stats.
2251   void trackStatistics() const override {}
2252 
2253   /// We don't manifest anything for this AA.
2254   ChangeStatus manifest(Attributor &A) override {
2255     return ChangeStatus::UNCHANGED;
2256   }
2257 
2258   // Map of ICV to their values at specific program point.
2259   EnumeratedArray<Optional<Value *>, InternalControlVar,
2260                   InternalControlVar::ICV___last>
2261       ICVReplacementValuesMap;
2262 
2263   /// Return the value with which \p I can be replaced for specific \p ICV.
2264   Optional<Value *>
2265   getUniqueReplacementValue(InternalControlVar ICV) const override {
2266     return ICVReplacementValuesMap[ICV];
2267   }
2268 
2269   ChangeStatus updateImpl(Attributor &A) override {
2270     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2271     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2272         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
2273 
2274     if (!ICVTrackingAA.isAssumedTracked())
2275       return indicatePessimisticFixpoint();
2276 
2277     for (InternalControlVar ICV : TrackableICVs) {
2278       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
2279       Optional<Value *> UniqueICVValue;
2280 
2281       auto CheckReturnInst = [&](Instruction &I) {
2282         Optional<Value *> NewReplVal =
2283             ICVTrackingAA.getReplacementValue(ICV, &I, A);
2284 
2285         // If we found a second ICV value there is no unique returned value.
2286         if (UniqueICVValue.hasValue() && UniqueICVValue != NewReplVal)
2287           return false;
2288 
2289         UniqueICVValue = NewReplVal;
2290 
2291         return true;
2292       };
2293 
2294       bool UsedAssumedInformation = false;
2295       if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret},
2296                                      UsedAssumedInformation,
2297                                      /* CheckBBLivenessOnly */ true))
2298         UniqueICVValue = nullptr;
2299 
2300       if (UniqueICVValue == ReplVal)
2301         continue;
2302 
2303       ReplVal = UniqueICVValue;
2304       Changed = ChangeStatus::CHANGED;
2305     }
2306 
2307     return Changed;
2308   }
2309 };
2310 
2311 struct AAICVTrackerCallSite : AAICVTracker {
2312   AAICVTrackerCallSite(const IRPosition &IRP, Attributor &A)
2313       : AAICVTracker(IRP, A) {}
2314 
2315   void initialize(Attributor &A) override {
2316     Function *F = getAnchorScope();
2317     if (!F || !A.isFunctionIPOAmendable(*F))
2318       indicatePessimisticFixpoint();
2319 
2320     // We only initialize this AA for getters, so we need to know which ICV it
2321     // gets.
2322     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2323     for (InternalControlVar ICV : TrackableICVs) {
2324       auto ICVInfo = OMPInfoCache.ICVs[ICV];
2325       auto &Getter = OMPInfoCache.RFIs[ICVInfo.Getter];
2326       if (Getter.Declaration == getAssociatedFunction()) {
2327         AssociatedICV = ICVInfo.Kind;
2328         return;
2329       }
2330     }
2331 
2332     /// Unknown ICV.
2333     indicatePessimisticFixpoint();
2334   }
2335 
2336   ChangeStatus manifest(Attributor &A) override {
2337     if (!ReplVal.hasValue() || !ReplVal.getValue())
2338       return ChangeStatus::UNCHANGED;
2339 
2340     A.changeValueAfterManifest(*getCtxI(), **ReplVal);
2341     A.deleteAfterManifest(*getCtxI());
2342 
2343     return ChangeStatus::CHANGED;
2344   }
2345 
2346   // FIXME: come up with better string.
2347   const std::string getAsStr() const override { return "ICVTrackerCallSite"; }
2348 
2349   // FIXME: come up with some stats.
2350   void trackStatistics() const override {}
2351 
2352   InternalControlVar AssociatedICV;
2353   Optional<Value *> ReplVal;
2354 
2355   ChangeStatus updateImpl(Attributor &A) override {
2356     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2357         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
2358 
2359     // We don't have any information, so we assume it changes the ICV.
2360     if (!ICVTrackingAA.isAssumedTracked())
2361       return indicatePessimisticFixpoint();
2362 
2363     Optional<Value *> NewReplVal =
2364         ICVTrackingAA.getReplacementValue(AssociatedICV, getCtxI(), A);
2365 
2366     if (ReplVal == NewReplVal)
2367       return ChangeStatus::UNCHANGED;
2368 
2369     ReplVal = NewReplVal;
2370     return ChangeStatus::CHANGED;
2371   }
2372 
2373   // Return the value with which associated value can be replaced for specific
2374   // \p ICV.
2375   Optional<Value *>
2376   getUniqueReplacementValue(InternalControlVar ICV) const override {
2377     return ReplVal;
2378   }
2379 };
2380 
2381 struct AAICVTrackerCallSiteReturned : AAICVTracker {
2382   AAICVTrackerCallSiteReturned(const IRPosition &IRP, Attributor &A)
2383       : AAICVTracker(IRP, A) {}
2384 
2385   // FIXME: come up with better string.
2386   const std::string getAsStr() const override {
2387     return "ICVTrackerCallSiteReturned";
2388   }
2389 
2390   // FIXME: come up with some stats.
2391   void trackStatistics() const override {}
2392 
2393   /// We don't manifest anything for this AA.
2394   ChangeStatus manifest(Attributor &A) override {
2395     return ChangeStatus::UNCHANGED;
2396   }
2397 
2398   // Map of ICV to their values at specific program point.
2399   EnumeratedArray<Optional<Value *>, InternalControlVar,
2400                   InternalControlVar::ICV___last>
2401       ICVReplacementValuesMap;
2402 
2403   /// Return the value with which associated value can be replaced for specific
2404   /// \p ICV.
2405   Optional<Value *>
2406   getUniqueReplacementValue(InternalControlVar ICV) const override {
2407     return ICVReplacementValuesMap[ICV];
2408   }
2409 
2410   ChangeStatus updateImpl(Attributor &A) override {
2411     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2412     const auto &ICVTrackingAA = A.getAAFor<AAICVTracker>(
2413         *this, IRPosition::returned(*getAssociatedFunction()),
2414         DepClassTy::REQUIRED);
2415 
2416     // We don't have any information, so we assume it changes the ICV.
2417     if (!ICVTrackingAA.isAssumedTracked())
2418       return indicatePessimisticFixpoint();
2419 
2420     for (InternalControlVar ICV : TrackableICVs) {
2421       Optional<Value *> &ReplVal = ICVReplacementValuesMap[ICV];
2422       Optional<Value *> NewReplVal =
2423           ICVTrackingAA.getUniqueReplacementValue(ICV);
2424 
2425       if (ReplVal == NewReplVal)
2426         continue;
2427 
2428       ReplVal = NewReplVal;
2429       Changed = ChangeStatus::CHANGED;
2430     }
2431     return Changed;
2432   }
2433 };
2434 
2435 struct AAExecutionDomainFunction : public AAExecutionDomain {
2436   AAExecutionDomainFunction(const IRPosition &IRP, Attributor &A)
2437       : AAExecutionDomain(IRP, A) {}
2438 
2439   const std::string getAsStr() const override {
2440     return "[AAExecutionDomain] " + std::to_string(SingleThreadedBBs.size()) +
2441            "/" + std::to_string(NumBBs) + " BBs thread 0 only.";
2442   }
2443 
2444   /// See AbstractAttribute::trackStatistics().
2445   void trackStatistics() const override {}
2446 
2447   void initialize(Attributor &A) override {
2448     Function *F = getAnchorScope();
2449     for (const auto &BB : *F)
2450       SingleThreadedBBs.insert(&BB);
2451     NumBBs = SingleThreadedBBs.size();
2452   }
2453 
2454   ChangeStatus manifest(Attributor &A) override {
2455     LLVM_DEBUG({
2456       for (const BasicBlock *BB : SingleThreadedBBs)
2457         dbgs() << TAG << " Basic block @" << getAnchorScope()->getName() << " "
2458                << BB->getName() << " is executed by a single thread.\n";
2459     });
2460     return ChangeStatus::UNCHANGED;
2461   }
2462 
2463   ChangeStatus updateImpl(Attributor &A) override;
2464 
2465   /// Check if an instruction is executed by a single thread.
2466   bool isExecutedByInitialThreadOnly(const Instruction &I) const override {
2467     return isExecutedByInitialThreadOnly(*I.getParent());
2468   }
2469 
2470   bool isExecutedByInitialThreadOnly(const BasicBlock &BB) const override {
2471     return isValidState() && SingleThreadedBBs.contains(&BB);
2472   }
2473 
2474   /// Set of basic blocks that are executed by a single thread.
2475   DenseSet<const BasicBlock *> SingleThreadedBBs;
2476 
2477   /// Total number of basic blocks in this function.
2478   long unsigned NumBBs;
2479 };
2480 
2481 ChangeStatus AAExecutionDomainFunction::updateImpl(Attributor &A) {
2482   Function *F = getAnchorScope();
2483   ReversePostOrderTraversal<Function *> RPOT(F);
2484   auto NumSingleThreadedBBs = SingleThreadedBBs.size();
2485 
2486   bool AllCallSitesKnown;
2487   auto PredForCallSite = [&](AbstractCallSite ACS) {
2488     const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>(
2489         *this, IRPosition::function(*ACS.getInstruction()->getFunction()),
2490         DepClassTy::REQUIRED);
2491     return ACS.isDirectCall() &&
2492            ExecutionDomainAA.isExecutedByInitialThreadOnly(
2493                *ACS.getInstruction());
2494   };
2495 
2496   if (!A.checkForAllCallSites(PredForCallSite, *this,
2497                               /* RequiresAllCallSites */ true,
2498                               AllCallSitesKnown))
2499     SingleThreadedBBs.erase(&F->getEntryBlock());
2500 
2501   auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2502   auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
2503 
2504   // Check if the edge into the successor block compares the __kmpc_target_init
2505   // result with -1. If we are in non-SPMD-mode that signals only the main
2506   // thread will execute the edge.
2507   auto IsInitialThreadOnly = [&](BranchInst *Edge, BasicBlock *SuccessorBB) {
2508     if (!Edge || !Edge->isConditional())
2509       return false;
2510     if (Edge->getSuccessor(0) != SuccessorBB)
2511       return false;
2512 
2513     auto *Cmp = dyn_cast<CmpInst>(Edge->getCondition());
2514     if (!Cmp || !Cmp->isTrueWhenEqual() || !Cmp->isEquality())
2515       return false;
2516 
2517     ConstantInt *C = dyn_cast<ConstantInt>(Cmp->getOperand(1));
2518     if (!C)
2519       return false;
2520 
2521     // Match:  -1 == __kmpc_target_init (for non-SPMD kernels only!)
2522     if (C->isAllOnesValue()) {
2523       auto *CB = dyn_cast<CallBase>(Cmp->getOperand(0));
2524       CB = CB ? OpenMPOpt::getCallIfRegularCall(*CB, &RFI) : nullptr;
2525       if (!CB)
2526         return false;
2527       const int InitIsSPMDArgNo = 1;
2528       auto *IsSPMDModeCI =
2529           dyn_cast<ConstantInt>(CB->getOperand(InitIsSPMDArgNo));
2530       return IsSPMDModeCI && IsSPMDModeCI->isZero();
2531     }
2532 
2533     return false;
2534   };
2535 
2536   // Merge all the predecessor states into the current basic block. A basic
2537   // block is executed by a single thread if all of its predecessors are.
2538   auto MergePredecessorStates = [&](BasicBlock *BB) {
2539     if (pred_begin(BB) == pred_end(BB))
2540       return SingleThreadedBBs.contains(BB);
2541 
2542     bool IsInitialThread = true;
2543     for (auto PredBB = pred_begin(BB), PredEndBB = pred_end(BB);
2544          PredBB != PredEndBB; ++PredBB) {
2545       if (!IsInitialThreadOnly(dyn_cast<BranchInst>((*PredBB)->getTerminator()),
2546                                BB))
2547         IsInitialThread &= SingleThreadedBBs.contains(*PredBB);
2548     }
2549 
2550     return IsInitialThread;
2551   };
2552 
2553   for (auto *BB : RPOT) {
2554     if (!MergePredecessorStates(BB))
2555       SingleThreadedBBs.erase(BB);
2556   }
2557 
2558   return (NumSingleThreadedBBs == SingleThreadedBBs.size())
2559              ? ChangeStatus::UNCHANGED
2560              : ChangeStatus::CHANGED;
2561 }
2562 
2563 /// Try to replace memory allocation calls called by a single thread with a
2564 /// static buffer of shared memory.
2565 struct AAHeapToShared : public StateWrapper<BooleanState, AbstractAttribute> {
2566   using Base = StateWrapper<BooleanState, AbstractAttribute>;
2567   AAHeapToShared(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
2568 
2569   /// Create an abstract attribute view for the position \p IRP.
2570   static AAHeapToShared &createForPosition(const IRPosition &IRP,
2571                                            Attributor &A);
2572 
2573   /// Returns true if HeapToShared conversion is assumed to be possible.
2574   virtual bool isAssumedHeapToShared(CallBase &CB) const = 0;
2575 
2576   /// Returns true if HeapToShared conversion is assumed and the CB is a
2577   /// callsite to a free operation to be removed.
2578   virtual bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const = 0;
2579 
2580   /// See AbstractAttribute::getName().
2581   const std::string getName() const override { return "AAHeapToShared"; }
2582 
2583   /// See AbstractAttribute::getIdAddr().
2584   const char *getIdAddr() const override { return &ID; }
2585 
2586   /// This function should return true if the type of the \p AA is
2587   /// AAHeapToShared.
2588   static bool classof(const AbstractAttribute *AA) {
2589     return (AA->getIdAddr() == &ID);
2590   }
2591 
2592   /// Unique ID (due to the unique address)
2593   static const char ID;
2594 };
2595 
2596 struct AAHeapToSharedFunction : public AAHeapToShared {
2597   AAHeapToSharedFunction(const IRPosition &IRP, Attributor &A)
2598       : AAHeapToShared(IRP, A) {}
2599 
2600   const std::string getAsStr() const override {
2601     return "[AAHeapToShared] " + std::to_string(MallocCalls.size()) +
2602            " malloc calls eligible.";
2603   }
2604 
2605   /// See AbstractAttribute::trackStatistics().
2606   void trackStatistics() const override {}
2607 
2608   /// This functions finds free calls that will be removed by the
2609   /// HeapToShared transformation.
2610   void findPotentialRemovedFreeCalls(Attributor &A) {
2611     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2612     auto &FreeRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared];
2613 
2614     PotentialRemovedFreeCalls.clear();
2615     // Update free call users of found malloc calls.
2616     for (CallBase *CB : MallocCalls) {
2617       SmallVector<CallBase *, 4> FreeCalls;
2618       for (auto *U : CB->users()) {
2619         CallBase *C = dyn_cast<CallBase>(U);
2620         if (C && C->getCalledFunction() == FreeRFI.Declaration)
2621           FreeCalls.push_back(C);
2622       }
2623 
2624       if (FreeCalls.size() != 1)
2625         continue;
2626 
2627       PotentialRemovedFreeCalls.insert(FreeCalls.front());
2628     }
2629   }
2630 
2631   void initialize(Attributor &A) override {
2632     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2633     auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
2634 
2635     for (User *U : RFI.Declaration->users())
2636       if (CallBase *CB = dyn_cast<CallBase>(U))
2637         MallocCalls.insert(CB);
2638 
2639     findPotentialRemovedFreeCalls(A);
2640   }
2641 
2642   bool isAssumedHeapToShared(CallBase &CB) const override {
2643     return isValidState() && MallocCalls.count(&CB);
2644   }
2645 
2646   bool isAssumedHeapToSharedRemovedFree(CallBase &CB) const override {
2647     return isValidState() && PotentialRemovedFreeCalls.count(&CB);
2648   }
2649 
2650   ChangeStatus manifest(Attributor &A) override {
2651     if (MallocCalls.empty())
2652       return ChangeStatus::UNCHANGED;
2653 
2654     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2655     auto &FreeCall = OMPInfoCache.RFIs[OMPRTL___kmpc_free_shared];
2656 
2657     Function *F = getAnchorScope();
2658     auto *HS = A.lookupAAFor<AAHeapToStack>(IRPosition::function(*F), this,
2659                                             DepClassTy::OPTIONAL);
2660 
2661     ChangeStatus Changed = ChangeStatus::UNCHANGED;
2662     for (CallBase *CB : MallocCalls) {
2663       // Skip replacing this if HeapToStack has already claimed it.
2664       if (HS && HS->isAssumedHeapToStack(*CB))
2665         continue;
2666 
2667       // Find the unique free call to remove it.
2668       SmallVector<CallBase *, 4> FreeCalls;
2669       for (auto *U : CB->users()) {
2670         CallBase *C = dyn_cast<CallBase>(U);
2671         if (C && C->getCalledFunction() == FreeCall.Declaration)
2672           FreeCalls.push_back(C);
2673       }
2674       if (FreeCalls.size() != 1)
2675         continue;
2676 
2677       ConstantInt *AllocSize = dyn_cast<ConstantInt>(CB->getArgOperand(0));
2678 
2679       LLVM_DEBUG(dbgs() << TAG << "Replace globalization call in "
2680                         << CB->getCaller()->getName() << " with "
2681                         << AllocSize->getZExtValue()
2682                         << " bytes of shared memory\n");
2683 
2684       // Create a new shared memory buffer of the same size as the allocation
2685       // and replace all the uses of the original allocation with it.
2686       Module *M = CB->getModule();
2687       Type *Int8Ty = Type::getInt8Ty(M->getContext());
2688       Type *Int8ArrTy = ArrayType::get(Int8Ty, AllocSize->getZExtValue());
2689       auto *SharedMem = new GlobalVariable(
2690           *M, Int8ArrTy, /* IsConstant */ false, GlobalValue::InternalLinkage,
2691           UndefValue::get(Int8ArrTy), CB->getName(), nullptr,
2692           GlobalValue::NotThreadLocal,
2693           static_cast<unsigned>(AddressSpace::Shared));
2694       auto *NewBuffer =
2695           ConstantExpr::getPointerCast(SharedMem, Int8Ty->getPointerTo());
2696 
2697       auto Remark = [&](OptimizationRemark OR) {
2698         return OR << "Replaced globalized variable with "
2699                   << ore::NV("SharedMemory", AllocSize->getZExtValue())
2700                   << ((AllocSize->getZExtValue() != 1) ? " bytes " : " byte ")
2701                   << "of shared memory.";
2702       };
2703       A.emitRemark<OptimizationRemark>(CB, "OMP111", Remark);
2704 
2705       SharedMem->setAlignment(MaybeAlign(32));
2706 
2707       A.changeValueAfterManifest(*CB, *NewBuffer);
2708       A.deleteAfterManifest(*CB);
2709       A.deleteAfterManifest(*FreeCalls.front());
2710 
2711       NumBytesMovedToSharedMemory += AllocSize->getZExtValue();
2712       Changed = ChangeStatus::CHANGED;
2713     }
2714 
2715     return Changed;
2716   }
2717 
2718   ChangeStatus updateImpl(Attributor &A) override {
2719     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2720     auto &RFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
2721     Function *F = getAnchorScope();
2722 
2723     auto NumMallocCalls = MallocCalls.size();
2724 
2725     // Only consider malloc calls executed by a single thread with a constant.
2726     for (User *U : RFI.Declaration->users()) {
2727       const auto &ED = A.getAAFor<AAExecutionDomain>(
2728           *this, IRPosition::function(*F), DepClassTy::REQUIRED);
2729       if (CallBase *CB = dyn_cast<CallBase>(U))
2730         if (!dyn_cast<ConstantInt>(CB->getArgOperand(0)) ||
2731             !ED.isExecutedByInitialThreadOnly(*CB))
2732           MallocCalls.erase(CB);
2733     }
2734 
2735     findPotentialRemovedFreeCalls(A);
2736 
2737     if (NumMallocCalls != MallocCalls.size())
2738       return ChangeStatus::CHANGED;
2739 
2740     return ChangeStatus::UNCHANGED;
2741   }
2742 
2743   /// Collection of all malloc calls in a function.
2744   SmallPtrSet<CallBase *, 4> MallocCalls;
2745   /// Collection of potentially removed free calls in a function.
2746   SmallPtrSet<CallBase *, 4> PotentialRemovedFreeCalls;
2747 };
2748 
2749 struct AAKernelInfo : public StateWrapper<KernelInfoState, AbstractAttribute> {
2750   using Base = StateWrapper<KernelInfoState, AbstractAttribute>;
2751   AAKernelInfo(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
2752 
2753   /// Statistics are tracked as part of manifest for now.
2754   void trackStatistics() const override {}
2755 
2756   /// See AbstractAttribute::getAsStr()
2757   const std::string getAsStr() const override {
2758     if (!isValidState())
2759       return "<invalid>";
2760     return std::string(SPMDCompatibilityTracker.isAssumed() ? "SPMD"
2761                                                             : "generic") +
2762            std::string(SPMDCompatibilityTracker.isAtFixpoint() ? " [FIX]"
2763                                                                : "") +
2764            std::string(" #PRs: ") +
2765            std::to_string(ReachedKnownParallelRegions.size()) +
2766            ", #Unknown PRs: " +
2767            std::to_string(ReachedUnknownParallelRegions.size());
2768   }
2769 
2770   /// Create an abstract attribute biew for the position \p IRP.
2771   static AAKernelInfo &createForPosition(const IRPosition &IRP, Attributor &A);
2772 
2773   /// See AbstractAttribute::getName()
2774   const std::string getName() const override { return "AAKernelInfo"; }
2775 
2776   /// See AbstractAttribute::getIdAddr()
2777   const char *getIdAddr() const override { return &ID; }
2778 
2779   /// This function should return true if the type of the \p AA is AAKernelInfo
2780   static bool classof(const AbstractAttribute *AA) {
2781     return (AA->getIdAddr() == &ID);
2782   }
2783 
2784   static const char ID;
2785 };
2786 
2787 /// The function kernel info abstract attribute, basically, what can we say
2788 /// about a function with regards to the KernelInfoState.
2789 struct AAKernelInfoFunction : AAKernelInfo {
2790   AAKernelInfoFunction(const IRPosition &IRP, Attributor &A)
2791       : AAKernelInfo(IRP, A) {}
2792 
2793   /// See AbstractAttribute::initialize(...).
2794   void initialize(Attributor &A) override {
2795     // This is a high-level transform that might change the constant arguments
2796     // of the init and dinit calls. We need to tell the Attributor about this
2797     // to avoid other parts using the current constant value for simpliication.
2798     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2799 
2800     Function *Fn = getAnchorScope();
2801     if (!OMPInfoCache.Kernels.count(Fn))
2802       return;
2803 
2804     // Add itself to the reaching kernel and set IsKernelEntry.
2805     ReachingKernelEntries.insert(Fn);
2806     IsKernelEntry = true;
2807 
2808     OMPInformationCache::RuntimeFunctionInfo &InitRFI =
2809         OMPInfoCache.RFIs[OMPRTL___kmpc_target_init];
2810     OMPInformationCache::RuntimeFunctionInfo &DeinitRFI =
2811         OMPInfoCache.RFIs[OMPRTL___kmpc_target_deinit];
2812 
2813     // For kernels we perform more initialization work, first we find the init
2814     // and deinit calls.
2815     auto StoreCallBase = [](Use &U,
2816                             OMPInformationCache::RuntimeFunctionInfo &RFI,
2817                             CallBase *&Storage) {
2818       CallBase *CB = OpenMPOpt::getCallIfRegularCall(U, &RFI);
2819       assert(CB &&
2820              "Unexpected use of __kmpc_target_init or __kmpc_target_deinit!");
2821       assert(!Storage &&
2822              "Multiple uses of __kmpc_target_init or __kmpc_target_deinit!");
2823       Storage = CB;
2824       return false;
2825     };
2826     InitRFI.foreachUse(
2827         [&](Use &U, Function &) {
2828           StoreCallBase(U, InitRFI, KernelInitCB);
2829           return false;
2830         },
2831         Fn);
2832     DeinitRFI.foreachUse(
2833         [&](Use &U, Function &) {
2834           StoreCallBase(U, DeinitRFI, KernelDeinitCB);
2835           return false;
2836         },
2837         Fn);
2838 
2839     assert((KernelInitCB && KernelDeinitCB) &&
2840            "Kernel without __kmpc_target_init or __kmpc_target_deinit!");
2841 
2842     // For kernels we might need to initialize/finalize the IsSPMD state and
2843     // we need to register a simplification callback so that the Attributor
2844     // knows the constant arguments to __kmpc_target_init and
2845     // __kmpc_target_deinit might actually change.
2846 
2847     Attributor::SimplifictionCallbackTy StateMachineSimplifyCB =
2848         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2849             bool &UsedAssumedInformation) -> Optional<Value *> {
2850       // IRP represents the "use generic state machine" argument of an
2851       // __kmpc_target_init call. We will answer this one with the internal
2852       // state. As long as we are not in an invalid state, we will create a
2853       // custom state machine so the value should be a `i1 false`. If we are
2854       // in an invalid state, we won't change the value that is in the IR.
2855       if (!isValidState())
2856         return nullptr;
2857       if (AA)
2858         A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2859       UsedAssumedInformation = !isAtFixpoint();
2860       auto *FalseVal =
2861           ConstantInt::getBool(IRP.getAnchorValue().getContext(), 0);
2862       return FalseVal;
2863     };
2864 
2865     Attributor::SimplifictionCallbackTy IsSPMDModeSimplifyCB =
2866         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2867             bool &UsedAssumedInformation) -> Optional<Value *> {
2868       // IRP represents the "SPMDCompatibilityTracker" argument of an
2869       // __kmpc_target_init or
2870       // __kmpc_target_deinit call. We will answer this one with the internal
2871       // state.
2872       if (!SPMDCompatibilityTracker.isValidState())
2873         return nullptr;
2874       if (!SPMDCompatibilityTracker.isAtFixpoint()) {
2875         if (AA)
2876           A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2877         UsedAssumedInformation = true;
2878       } else {
2879         UsedAssumedInformation = false;
2880       }
2881       auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(),
2882                                        SPMDCompatibilityTracker.isAssumed());
2883       return Val;
2884     };
2885 
2886     Attributor::SimplifictionCallbackTy IsGenericModeSimplifyCB =
2887         [&](const IRPosition &IRP, const AbstractAttribute *AA,
2888             bool &UsedAssumedInformation) -> Optional<Value *> {
2889       // IRP represents the "RequiresFullRuntime" argument of an
2890       // __kmpc_target_init or __kmpc_target_deinit call. We will answer this
2891       // one with the internal state of the SPMDCompatibilityTracker, so if
2892       // generic then true, if SPMD then false.
2893       if (!SPMDCompatibilityTracker.isValidState())
2894         return nullptr;
2895       if (!SPMDCompatibilityTracker.isAtFixpoint()) {
2896         if (AA)
2897           A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
2898         UsedAssumedInformation = true;
2899       } else {
2900         UsedAssumedInformation = false;
2901       }
2902       auto *Val = ConstantInt::getBool(IRP.getAnchorValue().getContext(),
2903                                        !SPMDCompatibilityTracker.isAssumed());
2904       return Val;
2905     };
2906 
2907     constexpr const int InitIsSPMDArgNo = 1;
2908     constexpr const int DeinitIsSPMDArgNo = 1;
2909     constexpr const int InitUseStateMachineArgNo = 2;
2910     constexpr const int InitRequiresFullRuntimeArgNo = 3;
2911     constexpr const int DeinitRequiresFullRuntimeArgNo = 2;
2912     A.registerSimplificationCallback(
2913         IRPosition::callsite_argument(*KernelInitCB, InitUseStateMachineArgNo),
2914         StateMachineSimplifyCB);
2915     A.registerSimplificationCallback(
2916         IRPosition::callsite_argument(*KernelInitCB, InitIsSPMDArgNo),
2917         IsSPMDModeSimplifyCB);
2918     A.registerSimplificationCallback(
2919         IRPosition::callsite_argument(*KernelDeinitCB, DeinitIsSPMDArgNo),
2920         IsSPMDModeSimplifyCB);
2921     A.registerSimplificationCallback(
2922         IRPosition::callsite_argument(*KernelInitCB,
2923                                       InitRequiresFullRuntimeArgNo),
2924         IsGenericModeSimplifyCB);
2925     A.registerSimplificationCallback(
2926         IRPosition::callsite_argument(*KernelDeinitCB,
2927                                       DeinitRequiresFullRuntimeArgNo),
2928         IsGenericModeSimplifyCB);
2929 
2930     // Check if we know we are in SPMD-mode already.
2931     ConstantInt *IsSPMDArg =
2932         dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitIsSPMDArgNo));
2933     if (IsSPMDArg && !IsSPMDArg->isZero())
2934       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
2935   }
2936 
2937   /// Modify the IR based on the KernelInfoState as the fixpoint iteration is
2938   /// finished now.
2939   ChangeStatus manifest(Attributor &A) override {
2940     // If we are not looking at a kernel with __kmpc_target_init and
2941     // __kmpc_target_deinit call we cannot actually manifest the information.
2942     if (!KernelInitCB || !KernelDeinitCB)
2943       return ChangeStatus::UNCHANGED;
2944 
2945     // Known SPMD-mode kernels need no manifest changes.
2946     if (SPMDCompatibilityTracker.isKnown())
2947       return ChangeStatus::UNCHANGED;
2948 
2949     // If we can we change the execution mode to SPMD-mode otherwise we build a
2950     // custom state machine.
2951     if (!changeToSPMDMode(A))
2952       buildCustomStateMachine(A);
2953 
2954     return ChangeStatus::CHANGED;
2955   }
2956 
2957   bool changeToSPMDMode(Attributor &A) {
2958     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
2959 
2960     if (!SPMDCompatibilityTracker.isAssumed()) {
2961       for (Instruction *NonCompatibleI : SPMDCompatibilityTracker) {
2962         if (!NonCompatibleI)
2963           continue;
2964 
2965         // Skip diagnostics on calls to known OpenMP runtime functions for now.
2966         if (auto *CB = dyn_cast<CallBase>(NonCompatibleI))
2967           if (OMPInfoCache.RTLFunctions.contains(CB->getCalledFunction()))
2968             continue;
2969 
2970         auto Remark = [&](OptimizationRemarkAnalysis ORA) {
2971           ORA << "Value has potential side effects preventing SPMD-mode "
2972                  "execution";
2973           if (isa<CallBase>(NonCompatibleI)) {
2974             ORA << ". Add `__attribute__((assume(\"ompx_spmd_amenable\")))` to "
2975                    "the called function to override";
2976           }
2977           return ORA << ".";
2978         };
2979         A.emitRemark<OptimizationRemarkAnalysis>(NonCompatibleI, "OMP121",
2980                                                  Remark);
2981 
2982         LLVM_DEBUG(dbgs() << TAG << "SPMD-incompatible side-effect: "
2983                           << *NonCompatibleI << "\n");
2984       }
2985 
2986       return false;
2987     }
2988 
2989     // Adjust the global exec mode flag that tells the runtime what mode this
2990     // kernel is executed in.
2991     Function *Kernel = getAnchorScope();
2992     GlobalVariable *ExecMode = Kernel->getParent()->getGlobalVariable(
2993         (Kernel->getName() + "_exec_mode").str());
2994     assert(ExecMode && "Kernel without exec mode?");
2995     assert(ExecMode->getInitializer() &&
2996            ExecMode->getInitializer()->isOneValue() &&
2997            "Initially non-SPMD kernel has SPMD exec mode!");
2998 
2999     // Set the global exec mode flag to indicate SPMD-Generic mode.
3000     constexpr int SPMDGeneric = 2;
3001     if (!ExecMode->getInitializer()->isZeroValue())
3002       ExecMode->setInitializer(
3003           ConstantInt::get(ExecMode->getInitializer()->getType(), SPMDGeneric));
3004 
3005     // Next rewrite the init and deinit calls to indicate we use SPMD-mode now.
3006     const int InitIsSPMDArgNo = 1;
3007     const int DeinitIsSPMDArgNo = 1;
3008     const int InitUseStateMachineArgNo = 2;
3009     const int InitRequiresFullRuntimeArgNo = 3;
3010     const int DeinitRequiresFullRuntimeArgNo = 2;
3011 
3012     auto &Ctx = getAnchorValue().getContext();
3013     A.changeUseAfterManifest(KernelInitCB->getArgOperandUse(InitIsSPMDArgNo),
3014                              *ConstantInt::getBool(Ctx, 1));
3015     A.changeUseAfterManifest(
3016         KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo),
3017         *ConstantInt::getBool(Ctx, 0));
3018     A.changeUseAfterManifest(
3019         KernelDeinitCB->getArgOperandUse(DeinitIsSPMDArgNo),
3020         *ConstantInt::getBool(Ctx, 1));
3021     A.changeUseAfterManifest(
3022         KernelInitCB->getArgOperandUse(InitRequiresFullRuntimeArgNo),
3023         *ConstantInt::getBool(Ctx, 0));
3024     A.changeUseAfterManifest(
3025         KernelDeinitCB->getArgOperandUse(DeinitRequiresFullRuntimeArgNo),
3026         *ConstantInt::getBool(Ctx, 0));
3027 
3028     ++NumOpenMPTargetRegionKernelsSPMD;
3029 
3030     auto Remark = [&](OptimizationRemark OR) {
3031       return OR << "Transformed generic-mode kernel to SPMD-mode.";
3032     };
3033     A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP120", Remark);
3034     return true;
3035   };
3036 
3037   ChangeStatus buildCustomStateMachine(Attributor &A) {
3038     assert(ReachedKnownParallelRegions.isValidState() &&
3039            "Custom state machine with invalid parallel region states?");
3040 
3041     const int InitIsSPMDArgNo = 1;
3042     const int InitUseStateMachineArgNo = 2;
3043 
3044     // Check if the current configuration is non-SPMD and generic state machine.
3045     // If we already have SPMD mode or a custom state machine we do not need to
3046     // go any further. If it is anything but a constant something is weird and
3047     // we give up.
3048     ConstantInt *UseStateMachine = dyn_cast<ConstantInt>(
3049         KernelInitCB->getArgOperand(InitUseStateMachineArgNo));
3050     ConstantInt *IsSPMD =
3051         dyn_cast<ConstantInt>(KernelInitCB->getArgOperand(InitIsSPMDArgNo));
3052 
3053     // If we are stuck with generic mode, try to create a custom device (=GPU)
3054     // state machine which is specialized for the parallel regions that are
3055     // reachable by the kernel.
3056     if (!UseStateMachine || UseStateMachine->isZero() || !IsSPMD ||
3057         !IsSPMD->isZero())
3058       return ChangeStatus::UNCHANGED;
3059 
3060     // If not SPMD mode, indicate we use a custom state machine now.
3061     auto &Ctx = getAnchorValue().getContext();
3062     auto *FalseVal = ConstantInt::getBool(Ctx, 0);
3063     A.changeUseAfterManifest(
3064         KernelInitCB->getArgOperandUse(InitUseStateMachineArgNo), *FalseVal);
3065 
3066     // If we don't actually need a state machine we are done here. This can
3067     // happen if there simply are no parallel regions. In the resulting kernel
3068     // all worker threads will simply exit right away, leaving the main thread
3069     // to do the work alone.
3070     if (ReachedKnownParallelRegions.empty() &&
3071         ReachedUnknownParallelRegions.empty()) {
3072       ++NumOpenMPTargetRegionKernelsWithoutStateMachine;
3073 
3074       auto Remark = [&](OptimizationRemark OR) {
3075         return OR << "Removing unused state machine from generic-mode kernel.";
3076       };
3077       A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP130", Remark);
3078 
3079       return ChangeStatus::CHANGED;
3080     }
3081 
3082     // Keep track in the statistics of our new shiny custom state machine.
3083     if (ReachedUnknownParallelRegions.empty()) {
3084       ++NumOpenMPTargetRegionKernelsCustomStateMachineWithoutFallback;
3085 
3086       auto Remark = [&](OptimizationRemark OR) {
3087         return OR << "Rewriting generic-mode kernel with a customized state "
3088                      "machine.";
3089       };
3090       A.emitRemark<OptimizationRemark>(KernelInitCB, "OMP131", Remark);
3091     } else {
3092       ++NumOpenMPTargetRegionKernelsCustomStateMachineWithFallback;
3093 
3094       auto Remark = [&](OptimizationRemarkAnalysis OR) {
3095         return OR << "Generic-mode kernel is executed with a customized state "
3096                      "machine that requires a fallback.";
3097       };
3098       A.emitRemark<OptimizationRemarkAnalysis>(KernelInitCB, "OMP132", Remark);
3099 
3100       // Tell the user why we ended up with a fallback.
3101       for (CallBase *UnknownParallelRegionCB : ReachedUnknownParallelRegions) {
3102         if (!UnknownParallelRegionCB)
3103           continue;
3104         auto Remark = [&](OptimizationRemarkAnalysis ORA) {
3105           return ORA << "Call may contain unknown parallel regions. Use "
3106                      << "`__attribute__((assume(\"omp_no_parallelism\")))` to "
3107                         "override.";
3108         };
3109         A.emitRemark<OptimizationRemarkAnalysis>(UnknownParallelRegionCB,
3110                                                  "OMP133", Remark);
3111       }
3112     }
3113 
3114     // Create all the blocks:
3115     //
3116     //                       InitCB = __kmpc_target_init(...)
3117     //                       bool IsWorker = InitCB >= 0;
3118     //                       if (IsWorker) {
3119     // SMBeginBB:               __kmpc_barrier_simple_spmd(...);
3120     //                         void *WorkFn;
3121     //                         bool Active = __kmpc_kernel_parallel(&WorkFn);
3122     //                         if (!WorkFn) return;
3123     // SMIsActiveCheckBB:       if (Active) {
3124     // SMIfCascadeCurrentBB:      if      (WorkFn == <ParFn0>)
3125     //                              ParFn0(...);
3126     // SMIfCascadeCurrentBB:      else if (WorkFn == <ParFn1>)
3127     //                              ParFn1(...);
3128     //                            ...
3129     // SMIfCascadeCurrentBB:      else
3130     //                              ((WorkFnTy*)WorkFn)(...);
3131     // SMEndParallelBB:           __kmpc_kernel_end_parallel(...);
3132     //                          }
3133     // SMDoneBB:                __kmpc_barrier_simple_spmd(...);
3134     //                          goto SMBeginBB;
3135     //                       }
3136     // UserCodeEntryBB:      // user code
3137     //                       __kmpc_target_deinit(...)
3138     //
3139     Function *Kernel = getAssociatedFunction();
3140     assert(Kernel && "Expected an associated function!");
3141 
3142     BasicBlock *InitBB = KernelInitCB->getParent();
3143     BasicBlock *UserCodeEntryBB = InitBB->splitBasicBlock(
3144         KernelInitCB->getNextNode(), "thread.user_code.check");
3145     BasicBlock *StateMachineBeginBB = BasicBlock::Create(
3146         Ctx, "worker_state_machine.begin", Kernel, UserCodeEntryBB);
3147     BasicBlock *StateMachineFinishedBB = BasicBlock::Create(
3148         Ctx, "worker_state_machine.finished", Kernel, UserCodeEntryBB);
3149     BasicBlock *StateMachineIsActiveCheckBB = BasicBlock::Create(
3150         Ctx, "worker_state_machine.is_active.check", Kernel, UserCodeEntryBB);
3151     BasicBlock *StateMachineIfCascadeCurrentBB =
3152         BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check",
3153                            Kernel, UserCodeEntryBB);
3154     BasicBlock *StateMachineEndParallelBB =
3155         BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.end",
3156                            Kernel, UserCodeEntryBB);
3157     BasicBlock *StateMachineDoneBarrierBB = BasicBlock::Create(
3158         Ctx, "worker_state_machine.done.barrier", Kernel, UserCodeEntryBB);
3159     A.registerManifestAddedBasicBlock(*InitBB);
3160     A.registerManifestAddedBasicBlock(*UserCodeEntryBB);
3161     A.registerManifestAddedBasicBlock(*StateMachineBeginBB);
3162     A.registerManifestAddedBasicBlock(*StateMachineFinishedBB);
3163     A.registerManifestAddedBasicBlock(*StateMachineIsActiveCheckBB);
3164     A.registerManifestAddedBasicBlock(*StateMachineIfCascadeCurrentBB);
3165     A.registerManifestAddedBasicBlock(*StateMachineEndParallelBB);
3166     A.registerManifestAddedBasicBlock(*StateMachineDoneBarrierBB);
3167 
3168     const DebugLoc &DLoc = KernelInitCB->getDebugLoc();
3169     ReturnInst::Create(Ctx, StateMachineFinishedBB)->setDebugLoc(DLoc);
3170 
3171     InitBB->getTerminator()->eraseFromParent();
3172     Instruction *IsWorker =
3173         ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_NE, KernelInitCB,
3174                          ConstantInt::get(KernelInitCB->getType(), -1),
3175                          "thread.is_worker", InitBB);
3176     IsWorker->setDebugLoc(DLoc);
3177     BranchInst::Create(StateMachineBeginBB, UserCodeEntryBB, IsWorker, InitBB);
3178 
3179     // Create local storage for the work function pointer.
3180     Type *VoidPtrTy = Type::getInt8PtrTy(Ctx);
3181     AllocaInst *WorkFnAI = new AllocaInst(VoidPtrTy, 0, "worker.work_fn.addr",
3182                                           &Kernel->getEntryBlock().front());
3183     WorkFnAI->setDebugLoc(DLoc);
3184 
3185     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3186     OMPInfoCache.OMPBuilder.updateToLocation(
3187         OpenMPIRBuilder::LocationDescription(
3188             IRBuilder<>::InsertPoint(StateMachineBeginBB,
3189                                      StateMachineBeginBB->end()),
3190             DLoc));
3191 
3192     Value *Ident = KernelInitCB->getArgOperand(0);
3193     Value *GTid = KernelInitCB;
3194 
3195     Module &M = *Kernel->getParent();
3196     FunctionCallee BarrierFn =
3197         OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3198             M, OMPRTL___kmpc_barrier_simple_spmd);
3199     CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineBeginBB)
3200         ->setDebugLoc(DLoc);
3201 
3202     FunctionCallee KernelParallelFn =
3203         OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3204             M, OMPRTL___kmpc_kernel_parallel);
3205     Instruction *IsActiveWorker = CallInst::Create(
3206         KernelParallelFn, {WorkFnAI}, "worker.is_active", StateMachineBeginBB);
3207     IsActiveWorker->setDebugLoc(DLoc);
3208     Instruction *WorkFn = new LoadInst(VoidPtrTy, WorkFnAI, "worker.work_fn",
3209                                        StateMachineBeginBB);
3210     WorkFn->setDebugLoc(DLoc);
3211 
3212     FunctionType *ParallelRegionFnTy = FunctionType::get(
3213         Type::getVoidTy(Ctx), {Type::getInt16Ty(Ctx), Type::getInt32Ty(Ctx)},
3214         false);
3215     Value *WorkFnCast = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
3216         WorkFn, ParallelRegionFnTy->getPointerTo(), "worker.work_fn.addr_cast",
3217         StateMachineBeginBB);
3218 
3219     Instruction *IsDone =
3220         ICmpInst::Create(ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFn,
3221                          Constant::getNullValue(VoidPtrTy), "worker.is_done",
3222                          StateMachineBeginBB);
3223     IsDone->setDebugLoc(DLoc);
3224     BranchInst::Create(StateMachineFinishedBB, StateMachineIsActiveCheckBB,
3225                        IsDone, StateMachineBeginBB)
3226         ->setDebugLoc(DLoc);
3227 
3228     BranchInst::Create(StateMachineIfCascadeCurrentBB,
3229                        StateMachineDoneBarrierBB, IsActiveWorker,
3230                        StateMachineIsActiveCheckBB)
3231         ->setDebugLoc(DLoc);
3232 
3233     Value *ZeroArg =
3234         Constant::getNullValue(ParallelRegionFnTy->getParamType(0));
3235 
3236     // Now that we have most of the CFG skeleton it is time for the if-cascade
3237     // that checks the function pointer we got from the runtime against the
3238     // parallel regions we expect, if there are any.
3239     for (int i = 0, e = ReachedKnownParallelRegions.size(); i < e; ++i) {
3240       auto *ParallelRegion = ReachedKnownParallelRegions[i];
3241       BasicBlock *PRExecuteBB = BasicBlock::Create(
3242           Ctx, "worker_state_machine.parallel_region.execute", Kernel,
3243           StateMachineEndParallelBB);
3244       CallInst::Create(ParallelRegion, {ZeroArg, GTid}, "", PRExecuteBB)
3245           ->setDebugLoc(DLoc);
3246       BranchInst::Create(StateMachineEndParallelBB, PRExecuteBB)
3247           ->setDebugLoc(DLoc);
3248 
3249       BasicBlock *PRNextBB =
3250           BasicBlock::Create(Ctx, "worker_state_machine.parallel_region.check",
3251                              Kernel, StateMachineEndParallelBB);
3252 
3253       // Check if we need to compare the pointer at all or if we can just
3254       // call the parallel region function.
3255       Value *IsPR;
3256       if (i + 1 < e || !ReachedUnknownParallelRegions.empty()) {
3257         Instruction *CmpI = ICmpInst::Create(
3258             ICmpInst::ICmp, llvm::CmpInst::ICMP_EQ, WorkFnCast, ParallelRegion,
3259             "worker.check_parallel_region", StateMachineIfCascadeCurrentBB);
3260         CmpI->setDebugLoc(DLoc);
3261         IsPR = CmpI;
3262       } else {
3263         IsPR = ConstantInt::getTrue(Ctx);
3264       }
3265 
3266       BranchInst::Create(PRExecuteBB, PRNextBB, IsPR,
3267                          StateMachineIfCascadeCurrentBB)
3268           ->setDebugLoc(DLoc);
3269       StateMachineIfCascadeCurrentBB = PRNextBB;
3270     }
3271 
3272     // At the end of the if-cascade we place the indirect function pointer call
3273     // in case we might need it, that is if there can be parallel regions we
3274     // have not handled in the if-cascade above.
3275     if (!ReachedUnknownParallelRegions.empty()) {
3276       StateMachineIfCascadeCurrentBB->setName(
3277           "worker_state_machine.parallel_region.fallback.execute");
3278       CallInst::Create(ParallelRegionFnTy, WorkFnCast, {ZeroArg, GTid}, "",
3279                        StateMachineIfCascadeCurrentBB)
3280           ->setDebugLoc(DLoc);
3281     }
3282     BranchInst::Create(StateMachineEndParallelBB,
3283                        StateMachineIfCascadeCurrentBB)
3284         ->setDebugLoc(DLoc);
3285 
3286     CallInst::Create(OMPInfoCache.OMPBuilder.getOrCreateRuntimeFunction(
3287                          M, OMPRTL___kmpc_kernel_end_parallel),
3288                      {}, "", StateMachineEndParallelBB)
3289         ->setDebugLoc(DLoc);
3290     BranchInst::Create(StateMachineDoneBarrierBB, StateMachineEndParallelBB)
3291         ->setDebugLoc(DLoc);
3292 
3293     CallInst::Create(BarrierFn, {Ident, GTid}, "", StateMachineDoneBarrierBB)
3294         ->setDebugLoc(DLoc);
3295     BranchInst::Create(StateMachineBeginBB, StateMachineDoneBarrierBB)
3296         ->setDebugLoc(DLoc);
3297 
3298     return ChangeStatus::CHANGED;
3299   }
3300 
3301   /// Fixpoint iteration update function. Will be called every time a dependence
3302   /// changed its state (and in the beginning).
3303   ChangeStatus updateImpl(Attributor &A) override {
3304     KernelInfoState StateBefore = getState();
3305 
3306     // Callback to check a read/write instruction.
3307     auto CheckRWInst = [&](Instruction &I) {
3308       // We handle calls later.
3309       if (isa<CallBase>(I))
3310         return true;
3311       // We only care about write effects.
3312       if (!I.mayWriteToMemory())
3313         return true;
3314       if (auto *SI = dyn_cast<StoreInst>(&I)) {
3315         SmallVector<const Value *> Objects;
3316         getUnderlyingObjects(SI->getPointerOperand(), Objects);
3317         if (llvm::all_of(Objects,
3318                          [](const Value *Obj) { return isa<AllocaInst>(Obj); }))
3319           return true;
3320       }
3321       // For now we give up on everything but stores.
3322       SPMDCompatibilityTracker.insert(&I);
3323       return true;
3324     };
3325 
3326     bool UsedAssumedInformationInCheckRWInst = false;
3327     if (!SPMDCompatibilityTracker.isAtFixpoint())
3328       if (!A.checkForAllReadWriteInstructions(
3329               CheckRWInst, *this, UsedAssumedInformationInCheckRWInst))
3330         SPMDCompatibilityTracker.indicatePessimisticFixpoint();
3331 
3332     if (!IsKernelEntry)
3333       updateReachingKernelEntries(A);
3334 
3335     // Callback to check a call instruction.
3336     bool AllSPMDStatesWereFixed = true;
3337     auto CheckCallInst = [&](Instruction &I) {
3338       auto &CB = cast<CallBase>(I);
3339       auto &CBAA = A.getAAFor<AAKernelInfo>(
3340           *this, IRPosition::callsite_function(CB), DepClassTy::OPTIONAL);
3341       getState() ^= CBAA.getState();
3342       AllSPMDStatesWereFixed &= CBAA.SPMDCompatibilityTracker.isAtFixpoint();
3343       return true;
3344     };
3345 
3346     bool UsedAssumedInformationInCheckCallInst = false;
3347     if (!A.checkForAllCallLikeInstructions(
3348             CheckCallInst, *this, UsedAssumedInformationInCheckCallInst))
3349       return indicatePessimisticFixpoint();
3350 
3351     // If we haven't used any assumed information for the SPMD state we can fix
3352     // it.
3353     if (!UsedAssumedInformationInCheckRWInst &&
3354         !UsedAssumedInformationInCheckCallInst && AllSPMDStatesWereFixed)
3355       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
3356 
3357     return StateBefore == getState() ? ChangeStatus::UNCHANGED
3358                                      : ChangeStatus::CHANGED;
3359   }
3360 
3361 private:
3362   /// Update info regarding reaching kernels.
3363   void updateReachingKernelEntries(Attributor &A) {
3364     auto PredCallSite = [&](AbstractCallSite ACS) {
3365       Function *Caller = ACS.getInstruction()->getFunction();
3366 
3367       assert(Caller && "Caller is nullptr");
3368 
3369       auto &CAA = A.getOrCreateAAFor<AAKernelInfo>(
3370           IRPosition::function(*Caller), this, DepClassTy::REQUIRED);
3371       if (CAA.ReachingKernelEntries.isValidState()) {
3372         ReachingKernelEntries ^= CAA.ReachingKernelEntries;
3373         return true;
3374       }
3375 
3376       // We lost track of the caller of the associated function, any kernel
3377       // could reach now.
3378       ReachingKernelEntries.indicatePessimisticFixpoint();
3379 
3380       return true;
3381     };
3382 
3383     bool AllCallSitesKnown;
3384     if (!A.checkForAllCallSites(PredCallSite, *this,
3385                                 true /* RequireAllCallSites */,
3386                                 AllCallSitesKnown))
3387       ReachingKernelEntries.indicatePessimisticFixpoint();
3388   }
3389 };
3390 
3391 /// The call site kernel info abstract attribute, basically, what can we say
3392 /// about a call site with regards to the KernelInfoState. For now this simply
3393 /// forwards the information from the callee.
3394 struct AAKernelInfoCallSite : AAKernelInfo {
3395   AAKernelInfoCallSite(const IRPosition &IRP, Attributor &A)
3396       : AAKernelInfo(IRP, A) {}
3397 
3398   /// See AbstractAttribute::initialize(...).
3399   void initialize(Attributor &A) override {
3400     AAKernelInfo::initialize(A);
3401 
3402     CallBase &CB = cast<CallBase>(getAssociatedValue());
3403     Function *Callee = getAssociatedFunction();
3404 
3405     // Helper to lookup an assumption string.
3406     auto HasAssumption = [](Function *Fn, StringRef AssumptionStr) {
3407       return Fn && hasAssumption(*Fn, AssumptionStr);
3408     };
3409 
3410     // Check for SPMD-mode assumptions.
3411     if (HasAssumption(Callee, "ompx_spmd_amenable"))
3412       SPMDCompatibilityTracker.indicateOptimisticFixpoint();
3413 
3414     // First weed out calls we do not care about, that is readonly/readnone
3415     // calls, intrinsics, and "no_openmp" calls. Neither of these can reach a
3416     // parallel region or anything else we are looking for.
3417     if (!CB.mayWriteToMemory() || isa<IntrinsicInst>(CB)) {
3418       indicateOptimisticFixpoint();
3419       return;
3420     }
3421 
3422     // Next we check if we know the callee. If it is a known OpenMP function
3423     // we will handle them explicitly in the switch below. If it is not, we
3424     // will use an AAKernelInfo object on the callee to gather information and
3425     // merge that into the current state. The latter happens in the updateImpl.
3426     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3427     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee);
3428     if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) {
3429       // Unknown caller or declarations are not analyzable, we give up.
3430       if (!Callee || !A.isFunctionIPOAmendable(*Callee)) {
3431 
3432         // Unknown callees might contain parallel regions, except if they have
3433         // an appropriate assumption attached.
3434         if (!(HasAssumption(Callee, "omp_no_openmp") ||
3435               HasAssumption(Callee, "omp_no_parallelism")))
3436           ReachedUnknownParallelRegions.insert(&CB);
3437 
3438         // If SPMDCompatibilityTracker is not fixed, we need to give up on the
3439         // idea we can run something unknown in SPMD-mode.
3440         if (!SPMDCompatibilityTracker.isAtFixpoint())
3441           SPMDCompatibilityTracker.insert(&CB);
3442 
3443         // We have updated the state for this unknown call properly, there won't
3444         // be any change so we indicate a fixpoint.
3445         indicateOptimisticFixpoint();
3446       }
3447       // If the callee is known and can be used in IPO, we will update the state
3448       // based on the callee state in updateImpl.
3449       return;
3450     }
3451 
3452     const unsigned int WrapperFunctionArgNo = 6;
3453     RuntimeFunction RF = It->getSecond();
3454     switch (RF) {
3455     // All the functions we know are compatible with SPMD mode.
3456     case OMPRTL___kmpc_is_spmd_exec_mode:
3457     case OMPRTL___kmpc_for_static_fini:
3458     case OMPRTL___kmpc_global_thread_num:
3459     case OMPRTL___kmpc_single:
3460     case OMPRTL___kmpc_end_single:
3461     case OMPRTL___kmpc_master:
3462     case OMPRTL___kmpc_end_master:
3463     case OMPRTL___kmpc_barrier:
3464       break;
3465     case OMPRTL___kmpc_for_static_init_4:
3466     case OMPRTL___kmpc_for_static_init_4u:
3467     case OMPRTL___kmpc_for_static_init_8:
3468     case OMPRTL___kmpc_for_static_init_8u: {
3469       // Check the schedule and allow static schedule in SPMD mode.
3470       unsigned ScheduleArgOpNo = 2;
3471       auto *ScheduleTypeCI =
3472           dyn_cast<ConstantInt>(CB.getArgOperand(ScheduleArgOpNo));
3473       unsigned ScheduleTypeVal =
3474           ScheduleTypeCI ? ScheduleTypeCI->getZExtValue() : 0;
3475       switch (OMPScheduleType(ScheduleTypeVal)) {
3476       case OMPScheduleType::Static:
3477       case OMPScheduleType::StaticChunked:
3478       case OMPScheduleType::Distribute:
3479       case OMPScheduleType::DistributeChunked:
3480         break;
3481       default:
3482         SPMDCompatibilityTracker.insert(&CB);
3483         break;
3484       };
3485     } break;
3486     case OMPRTL___kmpc_target_init:
3487       KernelInitCB = &CB;
3488       break;
3489     case OMPRTL___kmpc_target_deinit:
3490       KernelDeinitCB = &CB;
3491       break;
3492     case OMPRTL___kmpc_parallel_51:
3493       if (auto *ParallelRegion = dyn_cast<Function>(
3494               CB.getArgOperand(WrapperFunctionArgNo)->stripPointerCasts())) {
3495         ReachedKnownParallelRegions.insert(ParallelRegion);
3496         break;
3497       }
3498       // The condition above should usually get the parallel region function
3499       // pointer and record it. In the off chance it doesn't we assume the
3500       // worst.
3501       ReachedUnknownParallelRegions.insert(&CB);
3502       break;
3503     case OMPRTL___kmpc_omp_task:
3504       // We do not look into tasks right now, just give up.
3505       SPMDCompatibilityTracker.insert(&CB);
3506       ReachedUnknownParallelRegions.insert(&CB);
3507       break;
3508     case OMPRTL___kmpc_alloc_shared:
3509     case OMPRTL___kmpc_free_shared:
3510       // Return without setting a fixpoint, to be resolved in updateImpl.
3511       return;
3512     default:
3513       // Unknown OpenMP runtime calls cannot be executed in SPMD-mode,
3514       // generally.
3515       SPMDCompatibilityTracker.insert(&CB);
3516       break;
3517     }
3518     // All other OpenMP runtime calls will not reach parallel regions so they
3519     // can be safely ignored for now. Since it is a known OpenMP runtime call we
3520     // have now modeled all effects and there is no need for any update.
3521     indicateOptimisticFixpoint();
3522   }
3523 
3524   ChangeStatus updateImpl(Attributor &A) override {
3525     // TODO: Once we have call site specific value information we can provide
3526     //       call site specific liveness information and then it makes
3527     //       sense to specialize attributes for call sites arguments instead of
3528     //       redirecting requests to the callee argument.
3529     Function *F = getAssociatedFunction();
3530 
3531     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3532     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(F);
3533 
3534     // If F is not a runtime function, propagate the AAKernelInfo of the callee.
3535     if (It == OMPInfoCache.RuntimeFunctionIDMap.end()) {
3536       const IRPosition &FnPos = IRPosition::function(*F);
3537       auto &FnAA = A.getAAFor<AAKernelInfo>(*this, FnPos, DepClassTy::REQUIRED);
3538       if (getState() == FnAA.getState())
3539         return ChangeStatus::UNCHANGED;
3540       getState() = FnAA.getState();
3541       return ChangeStatus::CHANGED;
3542     }
3543 
3544     // F is a runtime function that allocates or frees memory, check
3545     // AAHeapToStack and AAHeapToShared.
3546     KernelInfoState StateBefore = getState();
3547     assert((It->getSecond() == OMPRTL___kmpc_alloc_shared ||
3548             It->getSecond() == OMPRTL___kmpc_free_shared) &&
3549            "Expected a __kmpc_alloc_shared or __kmpc_free_shared runtime call");
3550 
3551     CallBase &CB = cast<CallBase>(getAssociatedValue());
3552 
3553     auto &HeapToStackAA = A.getAAFor<AAHeapToStack>(
3554         *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL);
3555     auto &HeapToSharedAA = A.getAAFor<AAHeapToShared>(
3556         *this, IRPosition::function(*CB.getCaller()), DepClassTy::OPTIONAL);
3557 
3558     RuntimeFunction RF = It->getSecond();
3559 
3560     switch (RF) {
3561     // If neither HeapToStack nor HeapToShared assume the call is removed,
3562     // assume SPMD incompatibility.
3563     case OMPRTL___kmpc_alloc_shared:
3564       if (!HeapToStackAA.isAssumedHeapToStack(CB) &&
3565           !HeapToSharedAA.isAssumedHeapToShared(CB))
3566         SPMDCompatibilityTracker.insert(&CB);
3567       break;
3568     case OMPRTL___kmpc_free_shared:
3569       if (!HeapToStackAA.isAssumedHeapToStackRemovedFree(CB) &&
3570           !HeapToSharedAA.isAssumedHeapToSharedRemovedFree(CB))
3571         SPMDCompatibilityTracker.insert(&CB);
3572       break;
3573     default:
3574       SPMDCompatibilityTracker.insert(&CB);
3575     }
3576 
3577     return StateBefore == getState() ? ChangeStatus::UNCHANGED
3578                                      : ChangeStatus::CHANGED;
3579   }
3580 };
3581 
3582 struct AAFoldRuntimeCall
3583     : public StateWrapper<BooleanState, AbstractAttribute> {
3584   using Base = StateWrapper<BooleanState, AbstractAttribute>;
3585 
3586   AAFoldRuntimeCall(const IRPosition &IRP, Attributor &A) : Base(IRP) {}
3587 
3588   /// Statistics are tracked as part of manifest for now.
3589   void trackStatistics() const override {}
3590 
3591   /// Create an abstract attribute biew for the position \p IRP.
3592   static AAFoldRuntimeCall &createForPosition(const IRPosition &IRP,
3593                                               Attributor &A);
3594 
3595   /// See AbstractAttribute::getName()
3596   const std::string getName() const override { return "AAFoldRuntimeCall"; }
3597 
3598   /// See AbstractAttribute::getIdAddr()
3599   const char *getIdAddr() const override { return &ID; }
3600 
3601   /// This function should return true if the type of the \p AA is
3602   /// AAFoldRuntimeCall
3603   static bool classof(const AbstractAttribute *AA) {
3604     return (AA->getIdAddr() == &ID);
3605   }
3606 
3607   static const char ID;
3608 };
3609 
3610 struct AAFoldRuntimeCallCallSiteReturned : AAFoldRuntimeCall {
3611   AAFoldRuntimeCallCallSiteReturned(const IRPosition &IRP, Attributor &A)
3612       : AAFoldRuntimeCall(IRP, A) {}
3613 
3614   /// See AbstractAttribute::getAsStr()
3615   const std::string getAsStr() const override {
3616     if (!isValidState())
3617       return "<invalid>";
3618 
3619     std::string Str("simplified value: ");
3620 
3621     if (!SimplifiedValue.hasValue())
3622       return Str + std::string("none");
3623 
3624     if (!SimplifiedValue.getValue())
3625       return Str + std::string("nullptr");
3626 
3627     if (ConstantInt *CI = dyn_cast<ConstantInt>(SimplifiedValue.getValue()))
3628       return Str + std::to_string(CI->getSExtValue());
3629 
3630     return Str + std::string("unknown");
3631   }
3632 
3633   void initialize(Attributor &A) override {
3634     Function *Callee = getAssociatedFunction();
3635 
3636     auto &OMPInfoCache = static_cast<OMPInformationCache &>(A.getInfoCache());
3637     const auto &It = OMPInfoCache.RuntimeFunctionIDMap.find(Callee);
3638     assert(It != OMPInfoCache.RuntimeFunctionIDMap.end() &&
3639            "Expected a known OpenMP runtime function");
3640 
3641     RFKind = It->getSecond();
3642 
3643     CallBase &CB = cast<CallBase>(getAssociatedValue());
3644     A.registerSimplificationCallback(
3645         IRPosition::callsite_returned(CB),
3646         [&](const IRPosition &IRP, const AbstractAttribute *AA,
3647             bool &UsedAssumedInformation) -> Optional<Value *> {
3648           assert((isValidState() || (SimplifiedValue.hasValue() &&
3649                                      SimplifiedValue.getValue() == nullptr)) &&
3650                  "Unexpected invalid state!");
3651 
3652           if (!isAtFixpoint()) {
3653             UsedAssumedInformation = true;
3654             if (AA)
3655               A.recordDependence(*this, *AA, DepClassTy::OPTIONAL);
3656           }
3657           return SimplifiedValue;
3658         });
3659   }
3660 
3661   ChangeStatus updateImpl(Attributor &A) override {
3662     ChangeStatus Changed = ChangeStatus::UNCHANGED;
3663 
3664     switch (RFKind) {
3665     case OMPRTL___kmpc_is_spmd_exec_mode:
3666       Changed |= foldIsSPMDExecMode(A);
3667       break;
3668     case OMPRTL___kmpc_is_generic_main_thread_id:
3669       Changed |= foldIsGenericMainThread(A);
3670       break;
3671     default:
3672       llvm_unreachable("Unhandled OpenMP runtime function!");
3673     }
3674 
3675     return Changed;
3676   }
3677 
3678   ChangeStatus manifest(Attributor &A) override {
3679     ChangeStatus Changed = ChangeStatus::UNCHANGED;
3680 
3681     if (SimplifiedValue.hasValue() && SimplifiedValue.getValue()) {
3682       Instruction &CB = *getCtxI();
3683       A.changeValueAfterManifest(CB, **SimplifiedValue);
3684       A.deleteAfterManifest(CB);
3685 
3686       LLVM_DEBUG(dbgs() << TAG << "Folding runtime call: " << CB << " with "
3687                         << **SimplifiedValue << "\n");
3688 
3689       Changed = ChangeStatus::CHANGED;
3690     }
3691 
3692     return Changed;
3693   }
3694 
3695   ChangeStatus indicatePessimisticFixpoint() override {
3696     SimplifiedValue = nullptr;
3697     return AAFoldRuntimeCall::indicatePessimisticFixpoint();
3698   }
3699 
3700 private:
3701   /// Fold __kmpc_is_spmd_exec_mode into a constant if possible.
3702   ChangeStatus foldIsSPMDExecMode(Attributor &A) {
3703     Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
3704 
3705     unsigned AssumedSPMDCount = 0, KnownSPMDCount = 0;
3706     unsigned AssumedNonSPMDCount = 0, KnownNonSPMDCount = 0;
3707     auto &CallerKernelInfoAA = A.getAAFor<AAKernelInfo>(
3708         *this, IRPosition::function(*getAnchorScope()), DepClassTy::REQUIRED);
3709 
3710     if (!CallerKernelInfoAA.ReachingKernelEntries.isValidState())
3711       return indicatePessimisticFixpoint();
3712 
3713     for (Kernel K : CallerKernelInfoAA.ReachingKernelEntries) {
3714       auto &AA = A.getAAFor<AAKernelInfo>(*this, IRPosition::function(*K),
3715                                           DepClassTy::REQUIRED);
3716 
3717       if (!AA.isValidState()) {
3718         SimplifiedValue = nullptr;
3719         return indicatePessimisticFixpoint();
3720       }
3721 
3722       if (AA.SPMDCompatibilityTracker.isAssumed()) {
3723         if (AA.SPMDCompatibilityTracker.isAtFixpoint())
3724           ++KnownSPMDCount;
3725         else
3726           ++AssumedSPMDCount;
3727       } else {
3728         if (AA.SPMDCompatibilityTracker.isAtFixpoint())
3729           ++KnownNonSPMDCount;
3730         else
3731           ++AssumedNonSPMDCount;
3732       }
3733     }
3734 
3735     if ((AssumedSPMDCount + KnownSPMDCount) &&
3736         (AssumedNonSPMDCount + KnownNonSPMDCount))
3737       return indicatePessimisticFixpoint();
3738 
3739     auto &Ctx = getAnchorValue().getContext();
3740     if (KnownSPMDCount || AssumedSPMDCount) {
3741       assert(KnownNonSPMDCount == 0 && AssumedNonSPMDCount == 0 &&
3742              "Expected only SPMD kernels!");
3743       // All reaching kernels are in SPMD mode. Update all function calls to
3744       // __kmpc_is_spmd_exec_mode to 1.
3745       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true);
3746     } else if (KnownNonSPMDCount || AssumedNonSPMDCount) {
3747       assert(KnownSPMDCount == 0 && AssumedSPMDCount == 0 &&
3748              "Expected only non-SPMD kernels!");
3749       // All reaching kernels are in non-SPMD mode. Update all function
3750       // calls to __kmpc_is_spmd_exec_mode to 0.
3751       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), false);
3752     } else {
3753       // We have empty reaching kernels, therefore we cannot tell if the
3754       // associated call site can be folded. At this moment, SimplifiedValue
3755       // must be none.
3756       assert(!SimplifiedValue.hasValue() && "SimplifiedValue should be none");
3757     }
3758 
3759     return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
3760                                                     : ChangeStatus::CHANGED;
3761   }
3762 
3763   /// Fold __kmpc_is_generic_main_thread_id into a constant if possible.
3764   ChangeStatus foldIsGenericMainThread(Attributor &A) {
3765     Optional<Value *> SimplifiedValueBefore = SimplifiedValue;
3766 
3767     CallBase &CB = cast<CallBase>(getAssociatedValue());
3768     Function *F = CB.getFunction();
3769     const auto &ExecutionDomainAA = A.getAAFor<AAExecutionDomain>(
3770         *this, IRPosition::function(*F), DepClassTy::REQUIRED);
3771 
3772     if (!ExecutionDomainAA.isValidState())
3773       return indicatePessimisticFixpoint();
3774 
3775     auto &Ctx = getAnchorValue().getContext();
3776     if (ExecutionDomainAA.isExecutedByInitialThreadOnly(CB))
3777       SimplifiedValue = ConstantInt::get(Type::getInt8Ty(Ctx), true);
3778     else
3779       return indicatePessimisticFixpoint();
3780 
3781     return SimplifiedValue == SimplifiedValueBefore ? ChangeStatus::UNCHANGED
3782                                                     : ChangeStatus::CHANGED;
3783   }
3784 
3785   /// An optional value the associated value is assumed to fold to. That is, we
3786   /// assume the associated value (which is a call) can be replaced by this
3787   /// simplified value.
3788   Optional<Value *> SimplifiedValue;
3789 
3790   /// The runtime function kind of the callee of the associated call site.
3791   RuntimeFunction RFKind;
3792 };
3793 
3794 } // namespace
3795 
3796 void OpenMPOpt::registerAAs(bool IsModulePass) {
3797   if (SCC.empty())
3798 
3799     return;
3800   if (IsModulePass) {
3801     // Ensure we create the AAKernelInfo AAs first and without triggering an
3802     // update. This will make sure we register all value simplification
3803     // callbacks before any other AA has the chance to create an AAValueSimplify
3804     // or similar.
3805     for (Function *Kernel : OMPInfoCache.Kernels)
3806       A.getOrCreateAAFor<AAKernelInfo>(
3807           IRPosition::function(*Kernel), /* QueryingAA */ nullptr,
3808           DepClassTy::NONE, /* ForceUpdate */ false,
3809           /* UpdateAfterInit */ false);
3810 
3811     auto &IsMainRFI =
3812         OMPInfoCache.RFIs[OMPRTL___kmpc_is_generic_main_thread_id];
3813     IsMainRFI.foreachUse(SCC, [&](Use &U, Function &F) {
3814       CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &IsMainRFI);
3815       if (!CI)
3816         return false;
3817       A.getOrCreateAAFor<AAFoldRuntimeCall>(
3818           IRPosition::callsite_returned(*CI), /* QueryingAA */ nullptr,
3819           DepClassTy::NONE, /* ForceUpdate */ false,
3820           /* UpdateAfterInit */ false);
3821       return false;
3822     });
3823 
3824     auto &IsSPMDRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_is_spmd_exec_mode];
3825     IsSPMDRFI.foreachUse(SCC, [&](Use &U, Function &) {
3826       CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &IsSPMDRFI);
3827       if (!CI)
3828         return false;
3829       A.getOrCreateAAFor<AAFoldRuntimeCall>(
3830           IRPosition::callsite_returned(*CI), /* QueryingAA */ nullptr,
3831           DepClassTy::NONE, /* ForceUpdate */ false,
3832           /* UpdateAfterInit */ false);
3833       return false;
3834     });
3835   }
3836 
3837   // Create CallSite AA for all Getters.
3838   for (int Idx = 0; Idx < OMPInfoCache.ICVs.size() - 1; ++Idx) {
3839     auto ICVInfo = OMPInfoCache.ICVs[static_cast<InternalControlVar>(Idx)];
3840 
3841     auto &GetterRFI = OMPInfoCache.RFIs[ICVInfo.Getter];
3842 
3843     auto CreateAA = [&](Use &U, Function &Caller) {
3844       CallInst *CI = OpenMPOpt::getCallIfRegularCall(U, &GetterRFI);
3845       if (!CI)
3846         return false;
3847 
3848       auto &CB = cast<CallBase>(*CI);
3849 
3850       IRPosition CBPos = IRPosition::callsite_function(CB);
3851       A.getOrCreateAAFor<AAICVTracker>(CBPos);
3852       return false;
3853     };
3854 
3855     GetterRFI.foreachUse(SCC, CreateAA);
3856   }
3857   auto &GlobalizationRFI = OMPInfoCache.RFIs[OMPRTL___kmpc_alloc_shared];
3858   auto CreateAA = [&](Use &U, Function &F) {
3859     A.getOrCreateAAFor<AAHeapToShared>(IRPosition::function(F));
3860     return false;
3861   };
3862   GlobalizationRFI.foreachUse(SCC, CreateAA);
3863 
3864   // Create an ExecutionDomain AA for every function and a HeapToStack AA for
3865   // every function if there is a device kernel.
3866   for (auto *F : SCC) {
3867     if (!F->isDeclaration())
3868       A.getOrCreateAAFor<AAExecutionDomain>(IRPosition::function(*F));
3869     if (isOpenMPDevice(M))
3870       A.getOrCreateAAFor<AAHeapToStack>(IRPosition::function(*F));
3871   }
3872 }
3873 
3874 const char AAICVTracker::ID = 0;
3875 const char AAKernelInfo::ID = 0;
3876 const char AAExecutionDomain::ID = 0;
3877 const char AAHeapToShared::ID = 0;
3878 const char AAFoldRuntimeCall::ID = 0;
3879 
3880 AAICVTracker &AAICVTracker::createForPosition(const IRPosition &IRP,
3881                                               Attributor &A) {
3882   AAICVTracker *AA = nullptr;
3883   switch (IRP.getPositionKind()) {
3884   case IRPosition::IRP_INVALID:
3885   case IRPosition::IRP_FLOAT:
3886   case IRPosition::IRP_ARGUMENT:
3887   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3888     llvm_unreachable("ICVTracker can only be created for function position!");
3889   case IRPosition::IRP_RETURNED:
3890     AA = new (A.Allocator) AAICVTrackerFunctionReturned(IRP, A);
3891     break;
3892   case IRPosition::IRP_CALL_SITE_RETURNED:
3893     AA = new (A.Allocator) AAICVTrackerCallSiteReturned(IRP, A);
3894     break;
3895   case IRPosition::IRP_CALL_SITE:
3896     AA = new (A.Allocator) AAICVTrackerCallSite(IRP, A);
3897     break;
3898   case IRPosition::IRP_FUNCTION:
3899     AA = new (A.Allocator) AAICVTrackerFunction(IRP, A);
3900     break;
3901   }
3902 
3903   return *AA;
3904 }
3905 
3906 AAExecutionDomain &AAExecutionDomain::createForPosition(const IRPosition &IRP,
3907                                                         Attributor &A) {
3908   AAExecutionDomainFunction *AA = nullptr;
3909   switch (IRP.getPositionKind()) {
3910   case IRPosition::IRP_INVALID:
3911   case IRPosition::IRP_FLOAT:
3912   case IRPosition::IRP_ARGUMENT:
3913   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3914   case IRPosition::IRP_RETURNED:
3915   case IRPosition::IRP_CALL_SITE_RETURNED:
3916   case IRPosition::IRP_CALL_SITE:
3917     llvm_unreachable(
3918         "AAExecutionDomain can only be created for function position!");
3919   case IRPosition::IRP_FUNCTION:
3920     AA = new (A.Allocator) AAExecutionDomainFunction(IRP, A);
3921     break;
3922   }
3923 
3924   return *AA;
3925 }
3926 
3927 AAHeapToShared &AAHeapToShared::createForPosition(const IRPosition &IRP,
3928                                                   Attributor &A) {
3929   AAHeapToSharedFunction *AA = nullptr;
3930   switch (IRP.getPositionKind()) {
3931   case IRPosition::IRP_INVALID:
3932   case IRPosition::IRP_FLOAT:
3933   case IRPosition::IRP_ARGUMENT:
3934   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3935   case IRPosition::IRP_RETURNED:
3936   case IRPosition::IRP_CALL_SITE_RETURNED:
3937   case IRPosition::IRP_CALL_SITE:
3938     llvm_unreachable(
3939         "AAHeapToShared can only be created for function position!");
3940   case IRPosition::IRP_FUNCTION:
3941     AA = new (A.Allocator) AAHeapToSharedFunction(IRP, A);
3942     break;
3943   }
3944 
3945   return *AA;
3946 }
3947 
3948 AAKernelInfo &AAKernelInfo::createForPosition(const IRPosition &IRP,
3949                                               Attributor &A) {
3950   AAKernelInfo *AA = nullptr;
3951   switch (IRP.getPositionKind()) {
3952   case IRPosition::IRP_INVALID:
3953   case IRPosition::IRP_FLOAT:
3954   case IRPosition::IRP_ARGUMENT:
3955   case IRPosition::IRP_RETURNED:
3956   case IRPosition::IRP_CALL_SITE_RETURNED:
3957   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3958     llvm_unreachable("KernelInfo can only be created for function position!");
3959   case IRPosition::IRP_CALL_SITE:
3960     AA = new (A.Allocator) AAKernelInfoCallSite(IRP, A);
3961     break;
3962   case IRPosition::IRP_FUNCTION:
3963     AA = new (A.Allocator) AAKernelInfoFunction(IRP, A);
3964     break;
3965   }
3966 
3967   return *AA;
3968 }
3969 
3970 AAFoldRuntimeCall &AAFoldRuntimeCall::createForPosition(const IRPosition &IRP,
3971                                                         Attributor &A) {
3972   AAFoldRuntimeCall *AA = nullptr;
3973   switch (IRP.getPositionKind()) {
3974   case IRPosition::IRP_INVALID:
3975   case IRPosition::IRP_FLOAT:
3976   case IRPosition::IRP_ARGUMENT:
3977   case IRPosition::IRP_RETURNED:
3978   case IRPosition::IRP_FUNCTION:
3979   case IRPosition::IRP_CALL_SITE:
3980   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3981     llvm_unreachable("KernelInfo can only be created for call site position!");
3982   case IRPosition::IRP_CALL_SITE_RETURNED:
3983     AA = new (A.Allocator) AAFoldRuntimeCallCallSiteReturned(IRP, A);
3984     break;
3985   }
3986 
3987   return *AA;
3988 }
3989 
3990 PreservedAnalyses OpenMPOptPass::run(Module &M, ModuleAnalysisManager &AM) {
3991   if (!containsOpenMP(M))
3992     return PreservedAnalyses::all();
3993   if (DisableOpenMPOptimizations)
3994     return PreservedAnalyses::all();
3995 
3996   FunctionAnalysisManager &FAM =
3997       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
3998   KernelSet Kernels = getDeviceKernels(M);
3999 
4000   auto IsCalled = [&](Function &F) {
4001     if (Kernels.contains(&F))
4002       return true;
4003     for (const User *U : F.users())
4004       if (!isa<BlockAddress>(U))
4005         return true;
4006     return false;
4007   };
4008 
4009   auto EmitRemark = [&](Function &F) {
4010     auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4011     ORE.emit([&]() {
4012       OptimizationRemarkAnalysis ORA(DEBUG_TYPE, "OMP140", &F);
4013       return ORA << "Could not internalize function. "
4014                  << "Some optimizations may not be possible.";
4015     });
4016   };
4017 
4018   // Create internal copies of each function if this is a kernel Module. This
4019   // allows iterprocedural passes to see every call edge.
4020   DenseSet<const Function *> InternalizedFuncs;
4021   if (isOpenMPDevice(M))
4022     for (Function &F : M)
4023       if (!F.isDeclaration() && !Kernels.contains(&F) && IsCalled(F) &&
4024           !DisableInternalization) {
4025         if (Attributor::internalizeFunction(F, /* Force */ true)) {
4026           InternalizedFuncs.insert(&F);
4027         } else if (!F.hasLocalLinkage() && !F.hasFnAttribute(Attribute::Cold)) {
4028           EmitRemark(F);
4029         }
4030       }
4031 
4032   // Look at every function in the Module unless it was internalized.
4033   SmallVector<Function *, 16> SCC;
4034   for (Function &F : M)
4035     if (!F.isDeclaration() && !InternalizedFuncs.contains(&F))
4036       SCC.push_back(&F);
4037 
4038   if (SCC.empty())
4039     return PreservedAnalyses::all();
4040 
4041   AnalysisGetter AG(FAM);
4042 
4043   auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
4044     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
4045   };
4046 
4047   BumpPtrAllocator Allocator;
4048   CallGraphUpdater CGUpdater;
4049 
4050   SetVector<Function *> Functions(SCC.begin(), SCC.end());
4051   OMPInformationCache InfoCache(M, AG, Allocator, /*CGSCC*/ Functions, Kernels);
4052 
4053   unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4054   Attributor A(Functions, InfoCache, CGUpdater, nullptr, true, false,
4055                MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4056 
4057   OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4058   bool Changed = OMPOpt.run(true);
4059   if (Changed)
4060     return PreservedAnalyses::none();
4061 
4062   return PreservedAnalyses::all();
4063 }
4064 
4065 PreservedAnalyses OpenMPOptCGSCCPass::run(LazyCallGraph::SCC &C,
4066                                           CGSCCAnalysisManager &AM,
4067                                           LazyCallGraph &CG,
4068                                           CGSCCUpdateResult &UR) {
4069   if (!containsOpenMP(*C.begin()->getFunction().getParent()))
4070     return PreservedAnalyses::all();
4071   if (DisableOpenMPOptimizations)
4072     return PreservedAnalyses::all();
4073 
4074   SmallVector<Function *, 16> SCC;
4075   // If there are kernels in the module, we have to run on all SCC's.
4076   for (LazyCallGraph::Node &N : C) {
4077     Function *Fn = &N.getFunction();
4078     SCC.push_back(Fn);
4079   }
4080 
4081   if (SCC.empty())
4082     return PreservedAnalyses::all();
4083 
4084   Module &M = *C.begin()->getFunction().getParent();
4085 
4086   KernelSet Kernels = getDeviceKernels(M);
4087 
4088   FunctionAnalysisManager &FAM =
4089       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
4090 
4091   AnalysisGetter AG(FAM);
4092 
4093   auto OREGetter = [&FAM](Function *F) -> OptimizationRemarkEmitter & {
4094     return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
4095   };
4096 
4097   BumpPtrAllocator Allocator;
4098   CallGraphUpdater CGUpdater;
4099   CGUpdater.initialize(CG, C, AM, UR);
4100 
4101   SetVector<Function *> Functions(SCC.begin(), SCC.end());
4102   OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG, Allocator,
4103                                 /*CGSCC*/ Functions, Kernels);
4104 
4105   unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4106   Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true,
4107                MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4108 
4109   OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4110   bool Changed = OMPOpt.run(false);
4111   if (Changed)
4112     return PreservedAnalyses::none();
4113 
4114   return PreservedAnalyses::all();
4115 }
4116 
4117 namespace {
4118 
4119 struct OpenMPOptCGSCCLegacyPass : public CallGraphSCCPass {
4120   CallGraphUpdater CGUpdater;
4121   static char ID;
4122 
4123   OpenMPOptCGSCCLegacyPass() : CallGraphSCCPass(ID) {
4124     initializeOpenMPOptCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
4125   }
4126 
4127   void getAnalysisUsage(AnalysisUsage &AU) const override {
4128     CallGraphSCCPass::getAnalysisUsage(AU);
4129   }
4130 
4131   bool runOnSCC(CallGraphSCC &CGSCC) override {
4132     if (!containsOpenMP(CGSCC.getCallGraph().getModule()))
4133       return false;
4134     if (DisableOpenMPOptimizations || skipSCC(CGSCC))
4135       return false;
4136 
4137     SmallVector<Function *, 16> SCC;
4138     // If there are kernels in the module, we have to run on all SCC's.
4139     for (CallGraphNode *CGN : CGSCC) {
4140       Function *Fn = CGN->getFunction();
4141       if (!Fn || Fn->isDeclaration())
4142         continue;
4143       SCC.push_back(Fn);
4144     }
4145 
4146     if (SCC.empty())
4147       return false;
4148 
4149     Module &M = CGSCC.getCallGraph().getModule();
4150     KernelSet Kernels = getDeviceKernels(M);
4151 
4152     CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
4153     CGUpdater.initialize(CG, CGSCC);
4154 
4155     // Maintain a map of functions to avoid rebuilding the ORE
4156     DenseMap<Function *, std::unique_ptr<OptimizationRemarkEmitter>> OREMap;
4157     auto OREGetter = [&OREMap](Function *F) -> OptimizationRemarkEmitter & {
4158       std::unique_ptr<OptimizationRemarkEmitter> &ORE = OREMap[F];
4159       if (!ORE)
4160         ORE = std::make_unique<OptimizationRemarkEmitter>(F);
4161       return *ORE;
4162     };
4163 
4164     AnalysisGetter AG;
4165     SetVector<Function *> Functions(SCC.begin(), SCC.end());
4166     BumpPtrAllocator Allocator;
4167     OMPInformationCache InfoCache(*(Functions.back()->getParent()), AG,
4168                                   Allocator,
4169                                   /*CGSCC*/ Functions, Kernels);
4170 
4171     unsigned MaxFixpointIterations = (isOpenMPDevice(M)) ? 128 : 32;
4172     Attributor A(Functions, InfoCache, CGUpdater, nullptr, false, true,
4173                  MaxFixpointIterations, OREGetter, DEBUG_TYPE);
4174 
4175     OpenMPOpt OMPOpt(SCC, CGUpdater, OREGetter, InfoCache, A);
4176     return OMPOpt.run(false);
4177   }
4178 
4179   bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); }
4180 };
4181 
4182 } // end anonymous namespace
4183 
4184 KernelSet llvm::omp::getDeviceKernels(Module &M) {
4185   // TODO: Create a more cross-platform way of determining device kernels.
4186   NamedMDNode *MD = M.getOrInsertNamedMetadata("nvvm.annotations");
4187   KernelSet Kernels;
4188 
4189   if (!MD)
4190     return Kernels;
4191 
4192   for (auto *Op : MD->operands()) {
4193     if (Op->getNumOperands() < 2)
4194       continue;
4195     MDString *KindID = dyn_cast<MDString>(Op->getOperand(1));
4196     if (!KindID || KindID->getString() != "kernel")
4197       continue;
4198 
4199     Function *KernelFn =
4200         mdconst::dyn_extract_or_null<Function>(Op->getOperand(0));
4201     if (!KernelFn)
4202       continue;
4203 
4204     ++NumOpenMPTargetRegionKernels;
4205 
4206     Kernels.insert(KernelFn);
4207   }
4208 
4209   return Kernels;
4210 }
4211 
4212 bool llvm::omp::containsOpenMP(Module &M) {
4213   Metadata *MD = M.getModuleFlag("openmp");
4214   if (!MD)
4215     return false;
4216 
4217   return true;
4218 }
4219 
4220 bool llvm::omp::isOpenMPDevice(Module &M) {
4221   Metadata *MD = M.getModuleFlag("openmp-device");
4222   if (!MD)
4223     return false;
4224 
4225   return true;
4226 }
4227 
4228 char OpenMPOptCGSCCLegacyPass::ID = 0;
4229 
4230 INITIALIZE_PASS_BEGIN(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc",
4231                       "OpenMP specific optimizations", false, false)
4232 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
4233 INITIALIZE_PASS_END(OpenMPOptCGSCCLegacyPass, "openmp-opt-cgscc",
4234                     "OpenMP specific optimizations", false, false)
4235 
4236 Pass *llvm::createOpenMPOptCGSCCLegacyPass() {
4237   return new OpenMPOptCGSCCLegacyPass();
4238 }
4239