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