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