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