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