1 //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
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 // Take a scop created by ScopInfo and map it to GPU code using the ppcg
10 // GPU mapping strategy.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "polly/CodeGen/PPCGCodeGeneration.h"
15 #include "polly/CodeGen/CodeGeneration.h"
16 #include "polly/CodeGen/IslAst.h"
17 #include "polly/CodeGen/IslNodeBuilder.h"
18 #include "polly/CodeGen/PerfMonitor.h"
19 #include "polly/CodeGen/Utils.h"
20 #include "polly/DependenceInfo.h"
21 #include "polly/LinkAllPasses.h"
22 #include "polly/Options.h"
23 #include "polly/ScopDetection.h"
24 #include "polly/ScopInfo.h"
25 #include "polly/Support/SCEVValidator.h"
26 #include "llvm/ADT/PostOrderIterator.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/IR/IntrinsicsNVPTX.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/IRReader/IRReader.h"
32 #include "llvm/InitializePasses.h"
33 #include "llvm/Linker/Linker.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "isl/union_map.h"
40 #include <algorithm>
41 
42 extern "C" {
43 #include "ppcg/cuda.h"
44 #include "ppcg/gpu.h"
45 #include "ppcg/ppcg.h"
46 }
47 
48 #include "llvm/Support/Debug.h"
49 
50 using namespace polly;
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "polly-codegen-ppcg"
54 
55 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
56                                   cl::desc("Dump the computed GPU Schedule"),
57                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
58                                   cl::cat(PollyCategory));
59 
60 static cl::opt<bool>
61     DumpCode("polly-acc-dump-code",
62              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
63              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
64 
65 static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
66                                   cl::desc("Dump the kernel LLVM-IR"),
67                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
68                                   cl::cat(PollyCategory));
69 
70 static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
71                                    cl::desc("Dump the kernel assembly code"),
72                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
73                                    cl::cat(PollyCategory));
74 
75 static cl::opt<bool> FastMath("polly-acc-fastmath",
76                               cl::desc("Allow unsafe math optimizations"),
77                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
78                               cl::cat(PollyCategory));
79 static cl::opt<bool> SharedMemory("polly-acc-use-shared",
80                                   cl::desc("Use shared memory"), cl::Hidden,
81                                   cl::init(false), cl::ZeroOrMore,
82                                   cl::cat(PollyCategory));
83 static cl::opt<bool> PrivateMemory("polly-acc-use-private",
84                                    cl::desc("Use private memory"), cl::Hidden,
85                                    cl::init(false), cl::ZeroOrMore,
86                                    cl::cat(PollyCategory));
87 
88 bool polly::PollyManagedMemory;
89 static cl::opt<bool, true>
90     XManagedMemory("polly-acc-codegen-managed-memory",
91                    cl::desc("Generate Host kernel code assuming"
92                             " that all memory has been"
93                             " declared as managed memory"),
94                    cl::location(PollyManagedMemory), cl::Hidden,
95                    cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
96 
97 static cl::opt<bool>
98     FailOnVerifyModuleFailure("polly-acc-fail-on-verify-module-failure",
99                               cl::desc("Fail and generate a backtrace if"
100                                        " verifyModule fails on the GPU "
101                                        " kernel module."),
102                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
103                               cl::cat(PollyCategory));
104 
105 static cl::opt<std::string> CUDALibDevice(
106     "polly-acc-libdevice", cl::desc("Path to CUDA libdevice"), cl::Hidden,
107     cl::init("/usr/local/cuda/nvvm/libdevice/libdevice.compute_20.10.ll"),
108     cl::ZeroOrMore, cl::cat(PollyCategory));
109 
110 static cl::opt<std::string>
111     CudaVersion("polly-acc-cuda-version",
112                 cl::desc("The CUDA version to compile for"), cl::Hidden,
113                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
114 
115 static cl::opt<int>
116     MinCompute("polly-acc-mincompute",
117                cl::desc("Minimal number of compute statements to run on GPU."),
118                cl::Hidden, cl::init(10 * 512 * 512));
119 
120 GPURuntime polly::GPURuntimeChoice;
121 static cl::opt<GPURuntime, true> XGPURuntimeChoice(
122     "polly-gpu-runtime", cl::desc("The GPU Runtime API to target"),
123     cl::values(clEnumValN(GPURuntime::CUDA, "libcudart",
124                           "use the CUDA Runtime API"),
125                clEnumValN(GPURuntime::OpenCL, "libopencl",
126                           "use the OpenCL Runtime API")),
127     cl::location(polly::GPURuntimeChoice), cl::init(GPURuntime::CUDA),
128     cl::ZeroOrMore, cl::cat(PollyCategory));
129 
130 GPUArch polly::GPUArchChoice;
131 static cl::opt<GPUArch, true>
132     XGPUArchChoice("polly-gpu-arch", cl::desc("The GPU Architecture to target"),
133                    cl::values(clEnumValN(GPUArch::NVPTX64, "nvptx64",
134                                          "target NVIDIA 64-bit architecture"),
135                               clEnumValN(GPUArch::SPIR32, "spir32",
136                                          "target SPIR 32-bit architecture"),
137                               clEnumValN(GPUArch::SPIR64, "spir64",
138                                          "target SPIR 64-bit architecture")),
139                    cl::location(polly::GPUArchChoice),
140                    cl::init(GPUArch::NVPTX64), cl::ZeroOrMore,
141                    cl::cat(PollyCategory));
142 
143 extern bool polly::PerfMonitoring;
144 
145 /// Return  a unique name for a Scop, which is the scop region with the
146 /// function name.
147 std::string getUniqueScopName(const Scop *S) {
148   return "Scop Region: " + S->getNameStr() +
149          " | Function: " + std::string(S->getFunction().getName());
150 }
151 
152 /// Used to store information PPCG wants for kills. This information is
153 /// used by live range reordering.
154 ///
155 /// @see computeLiveRangeReordering
156 /// @see GPUNodeBuilder::createPPCGScop
157 /// @see GPUNodeBuilder::createPPCGProg
158 struct MustKillsInfo {
159   /// Collection of all kill statements that will be sequenced at the end of
160   /// PPCGScop->schedule.
161   ///
162   /// The nodes in `KillsSchedule` will be merged using `isl_schedule_set`
163   /// which merges schedules in *arbitrary* order.
164   /// (we don't care about the order of the kills anyway).
165   isl::schedule KillsSchedule;
166   /// Map from kill statement instances to scalars that need to be
167   /// killed.
168   ///
169   /// We currently derive kill information for:
170   ///  1. phi nodes. PHI nodes are not alive outside the scop and can
171   ///     consequently all be killed.
172   ///  2. Scalar arrays that are not used outside the Scop. This is
173   ///     checked by `isScalarUsesContainedInScop`.
174   /// [params] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
175   isl::union_map TaggedMustKills;
176 
177   /// Tagged must kills stripped of the tags.
178   /// [params] -> { Stmt_phantom[]  -> scalar_to_kill[] }
179   isl::union_map MustKills;
180 
181   MustKillsInfo() : KillsSchedule(nullptr) {}
182 };
183 
184 /// Check if SAI's uses are entirely contained within Scop S.
185 /// If a scalar is used only with a Scop, we are free to kill it, as no data
186 /// can flow in/out of the value any more.
187 /// @see computeMustKillsInfo
188 static bool isScalarUsesContainedInScop(const Scop &S,
189                                         const ScopArrayInfo *SAI) {
190   assert(SAI->isValueKind() && "this function only deals with scalars."
191                                " Dealing with arrays required alias analysis");
192 
193   const Region &R = S.getRegion();
194   for (User *U : SAI->getBasePtr()->users()) {
195     Instruction *I = dyn_cast<Instruction>(U);
196     assert(I && "invalid user of scop array info");
197     if (!R.contains(I))
198       return false;
199   }
200   return true;
201 }
202 
203 /// Compute must-kills needed to enable live range reordering with PPCG.
204 ///
205 /// @params S The Scop to compute live range reordering information
206 /// @returns live range reordering information that can be used to setup
207 /// PPCG.
208 static MustKillsInfo computeMustKillsInfo(const Scop &S) {
209   const isl::space ParamSpace = S.getParamSpace();
210   MustKillsInfo Info;
211 
212   // 1. Collect all ScopArrayInfo that satisfy *any* of the criteria:
213   //      1.1 phi nodes in scop.
214   //      1.2 scalars that are only used within the scop
215   SmallVector<isl::id, 4> KillMemIds;
216   for (ScopArrayInfo *SAI : S.arrays()) {
217     if (SAI->isPHIKind() ||
218         (SAI->isValueKind() && isScalarUsesContainedInScop(S, SAI)))
219       KillMemIds.push_back(isl::manage(SAI->getBasePtrId().release()));
220   }
221 
222   Info.TaggedMustKills = isl::union_map::empty(ParamSpace);
223   Info.MustKills = isl::union_map::empty(ParamSpace);
224 
225   // Initialising KillsSchedule to `isl_set_empty` creates an empty node in the
226   // schedule:
227   //     - filter: "[control] -> { }"
228   // So, we choose to not create this to keep the output a little nicer,
229   // at the cost of some code complexity.
230   Info.KillsSchedule = nullptr;
231 
232   for (isl::id &ToKillId : KillMemIds) {
233     isl::id KillStmtId = isl::id::alloc(
234         S.getIslCtx(),
235         std::string("SKill_phantom_").append(ToKillId.get_name()), nullptr);
236 
237     // NOTE: construction of tagged_must_kill:
238     // 2. We need to construct a map:
239     //     [param] -> { [Stmt_phantom[] -> ref_phantom[]] -> scalar_to_kill[] }
240     // To construct this, we use `isl_map_domain_product` on 2 maps`:
241     // 2a. StmtToScalar:
242     //         [param] -> { Stmt_phantom[] -> scalar_to_kill[] }
243     // 2b. PhantomRefToScalar:
244     //         [param] -> { ref_phantom[] -> scalar_to_kill[] }
245     //
246     // Combining these with `isl_map_domain_product` gives us
247     // TaggedMustKill:
248     //     [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
249 
250     // 2a. [param] -> { Stmt[] -> scalar_to_kill[] }
251     isl::map StmtToScalar = isl::map::universe(ParamSpace);
252     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::in, isl::id(KillStmtId));
253     StmtToScalar = StmtToScalar.set_tuple_id(isl::dim::out, isl::id(ToKillId));
254 
255     isl::id PhantomRefId = isl::id::alloc(
256         S.getIslCtx(), std::string("ref_phantom") + ToKillId.get_name(),
257         nullptr);
258 
259     // 2b. [param] -> { phantom_ref[] -> scalar_to_kill[] }
260     isl::map PhantomRefToScalar = isl::map::universe(ParamSpace);
261     PhantomRefToScalar =
262         PhantomRefToScalar.set_tuple_id(isl::dim::in, PhantomRefId);
263     PhantomRefToScalar =
264         PhantomRefToScalar.set_tuple_id(isl::dim::out, ToKillId);
265 
266     // 2. [param] -> { [Stmt[] -> phantom_ref[]] -> scalar_to_kill[] }
267     isl::map TaggedMustKill = StmtToScalar.domain_product(PhantomRefToScalar);
268     Info.TaggedMustKills = Info.TaggedMustKills.unite(TaggedMustKill);
269 
270     // 2. [param] -> { Stmt[] -> scalar_to_kill[] }
271     Info.MustKills = Info.TaggedMustKills.domain_factor_domain();
272 
273     // 3. Create the kill schedule of the form:
274     //     "[param] -> { Stmt_phantom[] }"
275     // Then add this to Info.KillsSchedule.
276     isl::space KillStmtSpace = ParamSpace;
277     KillStmtSpace = KillStmtSpace.set_tuple_id(isl::dim::set, KillStmtId);
278     isl::union_set KillStmtDomain = isl::set::universe(KillStmtSpace);
279 
280     isl::schedule KillSchedule = isl::schedule::from_domain(KillStmtDomain);
281     if (Info.KillsSchedule)
282       Info.KillsSchedule = isl::manage(
283           isl_schedule_set(Info.KillsSchedule.release(), KillSchedule.copy()));
284     else
285       Info.KillsSchedule = KillSchedule;
286   }
287 
288   return Info;
289 }
290 
291 /// Create the ast expressions for a ScopStmt.
292 ///
293 /// This function is a callback for to generate the ast expressions for each
294 /// of the scheduled ScopStmts.
295 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
296     void *StmtT, __isl_take isl_ast_build *Build_C,
297     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
298                                        isl_id *Id, void *User),
299     void *UserIndex,
300     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
301     void *UserExpr) {
302 
303   ScopStmt *Stmt = (ScopStmt *)StmtT;
304 
305   if (!Stmt || !Build_C)
306     return NULL;
307 
308   isl::ast_build Build = isl::manage_copy(Build_C);
309   isl::ctx Ctx = Build.get_ctx();
310   isl::id_to_ast_expr RefToExpr = isl::id_to_ast_expr::alloc(Ctx, 0);
311 
312   Stmt->setAstBuild(Build);
313 
314   for (MemoryAccess *Acc : *Stmt) {
315     isl::map AddrFunc = Acc->getAddressFunction();
316     AddrFunc = AddrFunc.intersect_domain(Stmt->getDomain());
317 
318     isl::id RefId = Acc->getId();
319     isl::pw_multi_aff PMA = isl::pw_multi_aff::from_map(AddrFunc);
320 
321     isl::multi_pw_aff MPA = isl::multi_pw_aff(PMA);
322     MPA = MPA.coalesce();
323     MPA = isl::manage(FunctionIndex(MPA.release(), RefId.get(), UserIndex));
324 
325     isl::ast_expr Access = Build.access_from(MPA);
326     Access = isl::manage(FunctionExpr(Access.release(), RefId.get(), UserExpr));
327     RefToExpr = RefToExpr.set(RefId, Access);
328   }
329 
330   return RefToExpr.release();
331 }
332 
333 /// Given a LLVM Type, compute its size in bytes,
334 static int computeSizeInBytes(const Type *T) {
335   int bytes = T->getPrimitiveSizeInBits() / 8;
336   if (bytes == 0)
337     bytes = T->getScalarSizeInBits() / 8;
338   return bytes;
339 }
340 
341 /// Generate code for a GPU specific isl AST.
342 ///
343 /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
344 /// generates code for general-purpose AST nodes, with special functionality
345 /// for generating GPU specific user nodes.
346 ///
347 /// @see GPUNodeBuilder::createUser
348 class GPUNodeBuilder : public IslNodeBuilder {
349 public:
350   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator,
351                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
352                  DominatorTree &DT, Scop &S, BasicBlock *StartBlock,
353                  gpu_prog *Prog, GPURuntime Runtime, GPUArch Arch)
354       : IslNodeBuilder(Builder, Annotator, DL, LI, SE, DT, S, StartBlock),
355         Prog(Prog), Runtime(Runtime), Arch(Arch) {
356     getExprBuilder().setIDToSAI(&IDToSAI);
357   }
358 
359   /// Create after-run-time-check initialization code.
360   void initializeAfterRTH();
361 
362   /// Finalize the generated scop.
363   void finalize() override;
364 
365   /// Track if the full build process was successful.
366   ///
367   /// This value is set to false, if throughout the build process an error
368   /// occurred which prevents us from generating valid GPU code.
369   bool BuildSuccessful = true;
370 
371   /// The maximal number of loops surrounding a sequential kernel.
372   unsigned DeepestSequential = 0;
373 
374   /// The maximal number of loops surrounding a parallel kernel.
375   unsigned DeepestParallel = 0;
376 
377   /// Return the name to set for the ptx_kernel.
378   std::string getKernelFuncName(int Kernel_id);
379 
380 private:
381   /// A vector of array base pointers for which a new ScopArrayInfo was created.
382   ///
383   /// This vector is used to delete the ScopArrayInfo when it is not needed any
384   /// more.
385   std::vector<Value *> LocalArrays;
386 
387   /// A map from ScopArrays to their corresponding device allocations.
388   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
389 
390   /// The current GPU context.
391   Value *GPUContext;
392 
393   /// The set of isl_ids allocated in the kernel
394   std::vector<isl_id *> KernelIds;
395 
396   /// A module containing GPU code.
397   ///
398   /// This pointer is only set in case we are currently generating GPU code.
399   std::unique_ptr<Module> GPUModule;
400 
401   /// The GPU program we generate code for.
402   gpu_prog *Prog;
403 
404   /// The GPU Runtime implementation to use (OpenCL or CUDA).
405   GPURuntime Runtime;
406 
407   /// The GPU Architecture to target.
408   GPUArch Arch;
409 
410   /// Class to free isl_ids.
411   class IslIdDeleter {
412   public:
413     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
414   };
415 
416   /// A set containing all isl_ids allocated in a GPU kernel.
417   ///
418   /// By releasing this set all isl_ids will be freed.
419   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
420 
421   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
422 
423   /// Create code for user-defined AST nodes.
424   ///
425   /// These AST nodes can be of type:
426   ///
427   ///   - ScopStmt:      A computational statement (TODO)
428   ///   - Kernel:        A GPU kernel call (TODO)
429   ///   - Data-Transfer: A GPU <-> CPU data-transfer
430   ///   - In-kernel synchronization
431   ///   - In-kernel memory copy statement
432   ///
433   /// @param UserStmt The ast node to generate code for.
434   void createUser(__isl_take isl_ast_node *UserStmt) override;
435 
436   void createFor(__isl_take isl_ast_node *Node) override;
437 
438   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
439 
440   /// Create code for a data transfer statement
441   ///
442   /// @param TransferStmt The data transfer statement.
443   /// @param Direction The direction in which to transfer data.
444   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
445                           enum DataDirection Direction);
446 
447   /// Find llvm::Values referenced in GPU kernel.
448   ///
449   /// @param Kernel The kernel to scan for llvm::Values
450   ///
451   /// @returns A tuple, whose:
452   ///          - First element contains the set of values referenced by the
453   ///            kernel
454   ///          - Second element contains the set of functions referenced by the
455   ///             kernel. All functions in the set satisfy
456   ///             `isValidFunctionInKernel`.
457   ///          - Third element contains loops that have induction variables
458   ///            which are used in the kernel, *and* these loops are *neither*
459   ///            in the scop, nor do they immediately surroung the Scop.
460   ///            See [Code generation of induction variables of loops outside
461   ///            Scops]
462   std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
463              isl::space>
464   getReferencesInKernel(ppcg_kernel *Kernel);
465 
466   /// Compute the sizes of the execution grid for a given kernel.
467   ///
468   /// @param Kernel The kernel to compute grid sizes for.
469   ///
470   /// @returns A tuple with grid sizes for X and Y dimension
471   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
472 
473   /// Get the managed array pointer for sending host pointers to the device.
474   /// \note
475   /// This is to be used only with managed memory
476   Value *getManagedDeviceArray(gpu_array_info *Array, ScopArrayInfo *ArrayInfo);
477 
478   /// Compute the sizes of the thread blocks for a given kernel.
479   ///
480   /// @param Kernel The kernel to compute thread block sizes for.
481   ///
482   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
483   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
484 
485   /// Store a specific kernel launch parameter in the array of kernel launch
486   /// parameters.
487   ///
488   /// @param Parameters The list of parameters in which to store.
489   /// @param Param      The kernel launch parameter to store.
490   /// @param Index      The index in the parameter list, at which to store the
491   ///                   parameter.
492   void insertStoreParameter(Instruction *Parameters, Instruction *Param,
493                             int Index);
494 
495   /// Create kernel launch parameters.
496   ///
497   /// @param Kernel        The kernel to create parameters for.
498   /// @param F             The kernel function that has been created.
499   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
500   ///
501   /// @returns A stack allocated array with pointers to the parameter
502   ///          values that are passed to the kernel.
503   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
504                                 SetVector<Value *> SubtreeValues);
505 
506   /// Create declarations for kernel variable.
507   ///
508   /// This includes shared memory declarations.
509   ///
510   /// @param Kernel        The kernel definition to create variables for.
511   /// @param FN            The function into which to generate the variables.
512   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
513 
514   /// Add CUDA annotations to module.
515   ///
516   /// Add a set of CUDA annotations that declares the maximal block dimensions
517   /// that will be used to execute the CUDA kernel. This allows the NVIDIA
518   /// PTX compiler to bound the number of allocated registers to ensure the
519   /// resulting kernel is known to run with up to as many block dimensions
520   /// as specified here.
521   ///
522   /// @param M         The module to add the annotations to.
523   /// @param BlockDimX The size of block dimension X.
524   /// @param BlockDimY The size of block dimension Y.
525   /// @param BlockDimZ The size of block dimension Z.
526   void addCUDAAnnotations(Module *M, Value *BlockDimX, Value *BlockDimY,
527                           Value *BlockDimZ);
528 
529   /// Create GPU kernel.
530   ///
531   /// Code generate the kernel described by @p KernelStmt.
532   ///
533   /// @param KernelStmt The ast node to generate kernel code for.
534   void createKernel(__isl_take isl_ast_node *KernelStmt);
535 
536   /// Generate code that computes the size of an array.
537   ///
538   /// @param Array The array for which to compute a size.
539   Value *getArraySize(gpu_array_info *Array);
540 
541   /// Generate code to compute the minimal offset at which an array is accessed.
542   ///
543   /// The offset of an array is the minimal array location accessed in a scop.
544   ///
545   /// Example:
546   ///
547   ///   for (long i = 0; i < 100; i++)
548   ///     A[i + 42] += ...
549   ///
550   ///   getArrayOffset(A) results in 42.
551   ///
552   /// @param Array The array for which to compute the offset.
553   /// @returns An llvm::Value that contains the offset of the array.
554   Value *getArrayOffset(gpu_array_info *Array);
555 
556   /// Prepare the kernel arguments for kernel code generation
557   ///
558   /// @param Kernel The kernel to generate code for.
559   /// @param FN     The function created for the kernel.
560   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
561 
562   /// Create kernel function.
563   ///
564   /// Create a kernel function located in a newly created module that can serve
565   /// as target for device code generation. Set the Builder to point to the
566   /// start block of this newly created function.
567   ///
568   /// @param Kernel The kernel to generate code for.
569   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
570   /// @param SubtreeFunctions The set of llvm::Functions referenced by this
571   ///                         kernel.
572   void createKernelFunction(ppcg_kernel *Kernel,
573                             SetVector<Value *> &SubtreeValues,
574                             SetVector<Function *> &SubtreeFunctions);
575 
576   /// Create the declaration of a kernel function.
577   ///
578   /// The kernel function takes as arguments:
579   ///
580   ///   - One i8 pointer for each external array reference used in the kernel.
581   ///   - Host iterators
582   ///   - Parameters
583   ///   - Other LLVM Value references (TODO)
584   ///
585   /// @param Kernel The kernel to generate the function declaration for.
586   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
587   ///
588   /// @returns The newly declared function.
589   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
590                                      SetVector<Value *> &SubtreeValues);
591 
592   /// Insert intrinsic functions to obtain thread and block ids.
593   ///
594   /// @param The kernel to generate the intrinsic functions for.
595   void insertKernelIntrinsics(ppcg_kernel *Kernel);
596 
597   /// Insert function calls to retrieve the SPIR group/local ids.
598   ///
599   /// @param Kernel The kernel to generate the function calls for.
600   /// @param SizeTypeIs64Bit Whether size_t of the openCl device is 64bit.
601   void insertKernelCallsSPIR(ppcg_kernel *Kernel, bool SizeTypeIs64bit);
602 
603   /// Setup the creation of functions referenced by the GPU kernel.
604   ///
605   /// 1. Create new function declarations in GPUModule which are the same as
606   /// SubtreeFunctions.
607   ///
608   /// 2. Populate IslNodeBuilder::ValueMap with mappings from
609   /// old functions (that come from the original module) to new functions
610   /// (that are created within GPUModule). That way, we generate references
611   /// to the correct function (in GPUModule) in BlockGenerator.
612   ///
613   /// @see IslNodeBuilder::ValueMap
614   /// @see BlockGenerator::GlobalMap
615   /// @see BlockGenerator::getNewValue
616   /// @see GPUNodeBuilder::getReferencesInKernel.
617   ///
618   /// @param SubtreeFunctions The set of llvm::Functions referenced by
619   ///                         this kernel.
620   void setupKernelSubtreeFunctions(SetVector<Function *> SubtreeFunctions);
621 
622   /// Create a global-to-shared or shared-to-global copy statement.
623   ///
624   /// @param CopyStmt The copy statement to generate code for
625   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
626 
627   /// Create code for a ScopStmt called in @p Expr.
628   ///
629   /// @param Expr The expression containing the call.
630   /// @param KernelStmt The kernel statement referenced in the call.
631   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
632 
633   /// Create an in-kernel synchronization call.
634   void createKernelSync();
635 
636   /// Create a PTX assembly string for the current GPU kernel.
637   ///
638   /// @returns A string containing the corresponding PTX assembly code.
639   std::string createKernelASM();
640 
641   /// Remove references from the dominator tree to the kernel function @p F.
642   ///
643   /// @param F The function to remove references to.
644   void clearDominators(Function *F);
645 
646   /// Remove references from scalar evolution to the kernel function @p F.
647   ///
648   /// @param F The function to remove references to.
649   void clearScalarEvolution(Function *F);
650 
651   /// Remove references from loop info to the kernel function @p F.
652   ///
653   /// @param F The function to remove references to.
654   void clearLoops(Function *F);
655 
656   /// Check if the scop requires to be linked with CUDA's libdevice.
657   bool requiresCUDALibDevice();
658 
659   /// Link with the NVIDIA libdevice library (if needed and available).
660   void addCUDALibDevice();
661 
662   /// Finalize the generation of the kernel function.
663   ///
664   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
665   /// dump its IR to stderr.
666   ///
667   /// @returns The Assembly string of the kernel.
668   std::string finalizeKernelFunction();
669 
670   /// Finalize the generation of the kernel arguments.
671   ///
672   /// This function ensures that not-read-only scalars used in a kernel are
673   /// stored back to the global memory location they are backed with before
674   /// the kernel terminates.
675   ///
676   /// @params Kernel The kernel to finalize kernel arguments for.
677   void finalizeKernelArguments(ppcg_kernel *Kernel);
678 
679   /// Create code that allocates memory to store arrays on device.
680   void allocateDeviceArrays();
681 
682   /// Create code to prepare the managed device pointers.
683   void prepareManagedDeviceArrays();
684 
685   /// Free all allocated device arrays.
686   void freeDeviceArrays();
687 
688   /// Create a call to initialize the GPU context.
689   ///
690   /// @returns A pointer to the newly initialized context.
691   Value *createCallInitContext();
692 
693   /// Create a call to get the device pointer for a kernel allocation.
694   ///
695   /// @param Allocation The Polly GPU allocation
696   ///
697   /// @returns The device parameter corresponding to this allocation.
698   Value *createCallGetDevicePtr(Value *Allocation);
699 
700   /// Create a call to free the GPU context.
701   ///
702   /// @param Context A pointer to an initialized GPU context.
703   void createCallFreeContext(Value *Context);
704 
705   /// Create a call to allocate memory on the device.
706   ///
707   /// @param Size The size of memory to allocate
708   ///
709   /// @returns A pointer that identifies this allocation.
710   Value *createCallAllocateMemoryForDevice(Value *Size);
711 
712   /// Create a call to free a device array.
713   ///
714   /// @param Array The device array to free.
715   void createCallFreeDeviceMemory(Value *Array);
716 
717   /// Create a call to copy data from host to device.
718   ///
719   /// @param HostPtr A pointer to the host data that should be copied.
720   /// @param DevicePtr A device pointer specifying the location to copy to.
721   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
722                                       Value *Size);
723 
724   /// Create a call to copy data from device to host.
725   ///
726   /// @param DevicePtr A pointer to the device data that should be copied.
727   /// @param HostPtr A host pointer specifying the location to copy to.
728   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
729                                       Value *Size);
730 
731   /// Create a call to synchronize Host & Device.
732   /// \note
733   /// This is to be used only with managed memory.
734   void createCallSynchronizeDevice();
735 
736   /// Create a call to get a kernel from an assembly string.
737   ///
738   /// @param Buffer The string describing the kernel.
739   /// @param Entry  The name of the kernel function to call.
740   ///
741   /// @returns A pointer to a kernel object
742   Value *createCallGetKernel(Value *Buffer, Value *Entry);
743 
744   /// Create a call to free a GPU kernel.
745   ///
746   /// @param GPUKernel THe kernel to free.
747   void createCallFreeKernel(Value *GPUKernel);
748 
749   /// Create a call to launch a GPU kernel.
750   ///
751   /// @param GPUKernel  The kernel to launch.
752   /// @param GridDimX   The size of the first grid dimension.
753   /// @param GridDimY   The size of the second grid dimension.
754   /// @param GridBlockX The size of the first block dimension.
755   /// @param GridBlockY The size of the second block dimension.
756   /// @param GridBlockZ The size of the third block dimension.
757   /// @param Parameters A pointer to an array that contains itself pointers to
758   ///                   the parameter values passed for each kernel argument.
759   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
760                               Value *GridDimY, Value *BlockDimX,
761                               Value *BlockDimY, Value *BlockDimZ,
762                               Value *Parameters);
763 };
764 
765 std::string GPUNodeBuilder::getKernelFuncName(int Kernel_id) {
766   return "FUNC_" + S.getFunction().getName().str() + "_SCOP_" +
767          std::to_string(S.getID()) + "_KERNEL_" + std::to_string(Kernel_id);
768 }
769 
770 void GPUNodeBuilder::initializeAfterRTH() {
771   BasicBlock *NewBB = SplitBlock(Builder.GetInsertBlock(),
772                                  &*Builder.GetInsertPoint(), &DT, &LI);
773   NewBB->setName("polly.acc.initialize");
774   Builder.SetInsertPoint(&NewBB->front());
775 
776   GPUContext = createCallInitContext();
777 
778   if (!PollyManagedMemory)
779     allocateDeviceArrays();
780   else
781     prepareManagedDeviceArrays();
782 }
783 
784 void GPUNodeBuilder::finalize() {
785   if (!PollyManagedMemory)
786     freeDeviceArrays();
787 
788   createCallFreeContext(GPUContext);
789   IslNodeBuilder::finalize();
790 }
791 
792 void GPUNodeBuilder::allocateDeviceArrays() {
793   assert(!PollyManagedMemory &&
794          "Managed memory will directly send host pointers "
795          "to the kernel. There is no need for device arrays");
796   isl_ast_build *Build = isl_ast_build_from_context(S.getContext().release());
797 
798   for (int i = 0; i < Prog->n_array; ++i) {
799     gpu_array_info *Array = &Prog->array[i];
800     auto *ScopArray = (ScopArrayInfo *)Array->user;
801     std::string DevArrayName("p_dev_array_");
802     DevArrayName.append(Array->name);
803 
804     Value *ArraySize = getArraySize(Array);
805     Value *Offset = getArrayOffset(Array);
806     if (Offset)
807       ArraySize = Builder.CreateSub(
808           ArraySize,
809           Builder.CreateMul(Offset,
810                             Builder.getInt64(ScopArray->getElemSizeInBytes())));
811     const SCEV *SizeSCEV = SE.getSCEV(ArraySize);
812     // It makes no sense to have an array of size 0. The CUDA API will
813     // throw an error anyway if we invoke `cuMallocManaged` with size `0`. We
814     // choose to be defensive and catch this at the compile phase. It is
815     // most likely that we are doing something wrong with size computation.
816     if (SizeSCEV->isZero()) {
817       errs() << getUniqueScopName(&S)
818              << " has computed array size 0: " << *ArraySize
819              << " | for array: " << *(ScopArray->getBasePtr())
820              << ". This is illegal, exiting.\n";
821       report_fatal_error("array size was computed to be 0");
822     }
823 
824     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
825     DevArray->setName(DevArrayName);
826     DeviceAllocations[ScopArray] = DevArray;
827   }
828 
829   isl_ast_build_free(Build);
830 }
831 
832 void GPUNodeBuilder::prepareManagedDeviceArrays() {
833   assert(PollyManagedMemory &&
834          "Device array most only be prepared in managed-memory mode");
835   for (int i = 0; i < Prog->n_array; ++i) {
836     gpu_array_info *Array = &Prog->array[i];
837     ScopArrayInfo *ScopArray = (ScopArrayInfo *)Array->user;
838     Value *HostPtr;
839 
840     if (gpu_array_is_scalar(Array))
841       HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
842     else
843       HostPtr = ScopArray->getBasePtr();
844     HostPtr = getLatestValue(HostPtr);
845 
846     Value *Offset = getArrayOffset(Array);
847     if (Offset) {
848       HostPtr = Builder.CreatePointerCast(
849           HostPtr, ScopArray->getElementType()->getPointerTo());
850       HostPtr = Builder.CreateGEP(HostPtr, Offset);
851     }
852 
853     HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
854     DeviceAllocations[ScopArray] = HostPtr;
855   }
856 }
857 
858 void GPUNodeBuilder::addCUDAAnnotations(Module *M, Value *BlockDimX,
859                                         Value *BlockDimY, Value *BlockDimZ) {
860   auto AnnotationNode = M->getOrInsertNamedMetadata("nvvm.annotations");
861 
862   for (auto &F : *M) {
863     if (F.getCallingConv() != CallingConv::PTX_Kernel)
864       continue;
865 
866     Value *V[] = {BlockDimX, BlockDimY, BlockDimZ};
867 
868     Metadata *Elements[] = {
869         ValueAsMetadata::get(&F),   MDString::get(M->getContext(), "maxntidx"),
870         ValueAsMetadata::get(V[0]), MDString::get(M->getContext(), "maxntidy"),
871         ValueAsMetadata::get(V[1]), MDString::get(M->getContext(), "maxntidz"),
872         ValueAsMetadata::get(V[2]),
873     };
874     MDNode *Node = MDNode::get(M->getContext(), Elements);
875     AnnotationNode->addOperand(Node);
876   }
877 }
878 
879 void GPUNodeBuilder::freeDeviceArrays() {
880   assert(!PollyManagedMemory && "Managed memory does not use device arrays");
881   for (auto &Array : DeviceAllocations)
882     createCallFreeDeviceMemory(Array.second);
883 }
884 
885 Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
886   const char *Name = "polly_getKernel";
887   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
888   Function *F = M->getFunction(Name);
889 
890   // If F is not available, declare it.
891   if (!F) {
892     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
893     std::vector<Type *> Args;
894     Args.push_back(Builder.getInt8PtrTy());
895     Args.push_back(Builder.getInt8PtrTy());
896     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
897     F = Function::Create(Ty, Linkage, Name, M);
898   }
899 
900   return Builder.CreateCall(F, {Buffer, Entry});
901 }
902 
903 Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
904   const char *Name = "polly_getDevicePtr";
905   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
906   Function *F = M->getFunction(Name);
907 
908   // If F is not available, declare it.
909   if (!F) {
910     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
911     std::vector<Type *> Args;
912     Args.push_back(Builder.getInt8PtrTy());
913     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
914     F = Function::Create(Ty, Linkage, Name, M);
915   }
916 
917   return Builder.CreateCall(F, {Allocation});
918 }
919 
920 void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
921                                             Value *GridDimY, Value *BlockDimX,
922                                             Value *BlockDimY, Value *BlockDimZ,
923                                             Value *Parameters) {
924   const char *Name = "polly_launchKernel";
925   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
926   Function *F = M->getFunction(Name);
927 
928   // If F is not available, declare it.
929   if (!F) {
930     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
931     std::vector<Type *> Args;
932     Args.push_back(Builder.getInt8PtrTy());
933     Args.push_back(Builder.getInt32Ty());
934     Args.push_back(Builder.getInt32Ty());
935     Args.push_back(Builder.getInt32Ty());
936     Args.push_back(Builder.getInt32Ty());
937     Args.push_back(Builder.getInt32Ty());
938     Args.push_back(Builder.getInt8PtrTy());
939     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
940     F = Function::Create(Ty, Linkage, Name, M);
941   }
942 
943   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
944                          BlockDimZ, Parameters});
945 }
946 
947 void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
948   const char *Name = "polly_freeKernel";
949   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
950   Function *F = M->getFunction(Name);
951 
952   // If F is not available, declare it.
953   if (!F) {
954     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
955     std::vector<Type *> Args;
956     Args.push_back(Builder.getInt8PtrTy());
957     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
958     F = Function::Create(Ty, Linkage, Name, M);
959   }
960 
961   Builder.CreateCall(F, {GPUKernel});
962 }
963 
964 void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
965   assert(!PollyManagedMemory &&
966          "Managed memory does not allocate or free memory "
967          "for device");
968   const char *Name = "polly_freeDeviceMemory";
969   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
970   Function *F = M->getFunction(Name);
971 
972   // If F is not available, declare it.
973   if (!F) {
974     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
975     std::vector<Type *> Args;
976     Args.push_back(Builder.getInt8PtrTy());
977     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
978     F = Function::Create(Ty, Linkage, Name, M);
979   }
980 
981   Builder.CreateCall(F, {Array});
982 }
983 
984 Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
985   assert(!PollyManagedMemory &&
986          "Managed memory does not allocate or free memory "
987          "for device");
988   const char *Name = "polly_allocateMemoryForDevice";
989   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
990   Function *F = M->getFunction(Name);
991 
992   // If F is not available, declare it.
993   if (!F) {
994     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
995     std::vector<Type *> Args;
996     Args.push_back(Builder.getInt64Ty());
997     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
998     F = Function::Create(Ty, Linkage, Name, M);
999   }
1000 
1001   return Builder.CreateCall(F, {Size});
1002 }
1003 
1004 void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
1005                                                     Value *DeviceData,
1006                                                     Value *Size) {
1007   assert(!PollyManagedMemory &&
1008          "Managed memory does not transfer memory between "
1009          "device and host");
1010   const char *Name = "polly_copyFromHostToDevice";
1011   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1012   Function *F = M->getFunction(Name);
1013 
1014   // If F is not available, declare it.
1015   if (!F) {
1016     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1017     std::vector<Type *> Args;
1018     Args.push_back(Builder.getInt8PtrTy());
1019     Args.push_back(Builder.getInt8PtrTy());
1020     Args.push_back(Builder.getInt64Ty());
1021     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1022     F = Function::Create(Ty, Linkage, Name, M);
1023   }
1024 
1025   Builder.CreateCall(F, {HostData, DeviceData, Size});
1026 }
1027 
1028 void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
1029                                                     Value *HostData,
1030                                                     Value *Size) {
1031   assert(!PollyManagedMemory &&
1032          "Managed memory does not transfer memory between "
1033          "device and host");
1034   const char *Name = "polly_copyFromDeviceToHost";
1035   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1036   Function *F = M->getFunction(Name);
1037 
1038   // If F is not available, declare it.
1039   if (!F) {
1040     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1041     std::vector<Type *> Args;
1042     Args.push_back(Builder.getInt8PtrTy());
1043     Args.push_back(Builder.getInt8PtrTy());
1044     Args.push_back(Builder.getInt64Ty());
1045     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1046     F = Function::Create(Ty, Linkage, Name, M);
1047   }
1048 
1049   Builder.CreateCall(F, {DeviceData, HostData, Size});
1050 }
1051 
1052 void GPUNodeBuilder::createCallSynchronizeDevice() {
1053   assert(PollyManagedMemory && "explicit synchronization is only necessary for "
1054                                "managed memory");
1055   const char *Name = "polly_synchronizeDevice";
1056   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1057   Function *F = M->getFunction(Name);
1058 
1059   // If F is not available, declare it.
1060   if (!F) {
1061     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1062     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1063     F = Function::Create(Ty, Linkage, Name, M);
1064   }
1065 
1066   Builder.CreateCall(F);
1067 }
1068 
1069 Value *GPUNodeBuilder::createCallInitContext() {
1070   const char *Name;
1071 
1072   switch (Runtime) {
1073   case GPURuntime::CUDA:
1074     Name = "polly_initContextCUDA";
1075     break;
1076   case GPURuntime::OpenCL:
1077     Name = "polly_initContextCL";
1078     break;
1079   }
1080 
1081   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1082   Function *F = M->getFunction(Name);
1083 
1084   // If F is not available, declare it.
1085   if (!F) {
1086     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1087     std::vector<Type *> Args;
1088     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
1089     F = Function::Create(Ty, Linkage, Name, M);
1090   }
1091 
1092   return Builder.CreateCall(F, {});
1093 }
1094 
1095 void GPUNodeBuilder::createCallFreeContext(Value *Context) {
1096   const char *Name = "polly_freeContext";
1097   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1098   Function *F = M->getFunction(Name);
1099 
1100   // If F is not available, declare it.
1101   if (!F) {
1102     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1103     std::vector<Type *> Args;
1104     Args.push_back(Builder.getInt8PtrTy());
1105     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1106     F = Function::Create(Ty, Linkage, Name, M);
1107   }
1108 
1109   Builder.CreateCall(F, {Context});
1110 }
1111 
1112 /// Check if one string is a prefix of another.
1113 ///
1114 /// @param String The string in which to look for the prefix.
1115 /// @param Prefix The prefix to look for.
1116 static bool isPrefix(std::string String, std::string Prefix) {
1117   return String.find(Prefix) == 0;
1118 }
1119 
1120 Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
1121   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1122   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
1123 
1124   if (!gpu_array_is_scalar(Array)) {
1125     isl::multi_pw_aff ArrayBound = isl::manage_copy(Array->bound);
1126 
1127     isl::pw_aff OffsetDimZero = ArrayBound.get_pw_aff(0);
1128     isl::ast_expr Res = Build.expr_from(OffsetDimZero);
1129 
1130     for (unsigned int i = 1; i < Array->n_index; i++) {
1131       isl::pw_aff Bound_I = ArrayBound.get_pw_aff(i);
1132       isl::ast_expr Expr = Build.expr_from(Bound_I);
1133       Res = Res.mul(Expr);
1134     }
1135 
1136     Value *NumElements = ExprBuilder.create(Res.release());
1137     if (NumElements->getType() != ArraySize->getType())
1138       NumElements = Builder.CreateSExt(NumElements, ArraySize->getType());
1139     ArraySize = Builder.CreateMul(ArraySize, NumElements);
1140   }
1141   return ArraySize;
1142 }
1143 
1144 Value *GPUNodeBuilder::getArrayOffset(gpu_array_info *Array) {
1145   if (gpu_array_is_scalar(Array))
1146     return nullptr;
1147 
1148   isl::ast_build Build = isl::ast_build::from_context(S.getContext());
1149 
1150   isl::set Min = isl::manage_copy(Array->extent).lexmin();
1151 
1152   isl::set ZeroSet = isl::set::universe(Min.get_space());
1153 
1154   for (long i = 0, n = Min.dim(isl::dim::set); i < n; i++)
1155     ZeroSet = ZeroSet.fix_si(isl::dim::set, i, 0);
1156 
1157   if (Min.is_subset(ZeroSet)) {
1158     return nullptr;
1159   }
1160 
1161   isl::ast_expr Result = isl::ast_expr::from_val(isl::val(Min.get_ctx(), 0));
1162 
1163   for (long i = 0, n = Min.dim(isl::dim::set); i < n; i++) {
1164     if (i > 0) {
1165       isl::pw_aff Bound_I =
1166           isl::manage(isl_multi_pw_aff_get_pw_aff(Array->bound, i - 1));
1167       isl::ast_expr BExpr = Build.expr_from(Bound_I);
1168       Result = Result.mul(BExpr);
1169     }
1170     isl::pw_aff DimMin = Min.dim_min(i);
1171     isl::ast_expr MExpr = Build.expr_from(DimMin);
1172     Result = Result.add(MExpr);
1173   }
1174 
1175   return ExprBuilder.create(Result.release());
1176 }
1177 
1178 Value *GPUNodeBuilder::getManagedDeviceArray(gpu_array_info *Array,
1179                                              ScopArrayInfo *ArrayInfo) {
1180   assert(PollyManagedMemory && "Only used when you wish to get a host "
1181                                "pointer for sending data to the kernel, "
1182                                "with managed memory");
1183   std::map<ScopArrayInfo *, Value *>::iterator it;
1184   it = DeviceAllocations.find(ArrayInfo);
1185   assert(it != DeviceAllocations.end() &&
1186          "Device array expected to be available");
1187   return it->second;
1188 }
1189 
1190 void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
1191                                         enum DataDirection Direction) {
1192   assert(!PollyManagedMemory && "Managed memory needs no data transfers");
1193   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
1194   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
1195   isl_id *Id = isl_ast_expr_get_id(Arg);
1196   auto Array = (gpu_array_info *)isl_id_get_user(Id);
1197   auto ScopArray = (ScopArrayInfo *)(Array->user);
1198 
1199   Value *Size = getArraySize(Array);
1200   Value *Offset = getArrayOffset(Array);
1201   Value *DevPtr = DeviceAllocations[ScopArray];
1202 
1203   Value *HostPtr;
1204 
1205   if (gpu_array_is_scalar(Array))
1206     HostPtr = BlockGen.getOrCreateAlloca(ScopArray);
1207   else
1208     HostPtr = ScopArray->getBasePtr();
1209   HostPtr = getLatestValue(HostPtr);
1210 
1211   if (Offset) {
1212     HostPtr = Builder.CreatePointerCast(
1213         HostPtr, ScopArray->getElementType()->getPointerTo());
1214     HostPtr = Builder.CreateGEP(HostPtr, Offset);
1215   }
1216 
1217   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
1218 
1219   if (Offset) {
1220     Size = Builder.CreateSub(
1221         Size, Builder.CreateMul(
1222                   Offset, Builder.getInt64(ScopArray->getElemSizeInBytes())));
1223   }
1224 
1225   if (Direction == HOST_TO_DEVICE)
1226     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
1227   else
1228     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
1229 
1230   isl_id_free(Id);
1231   isl_ast_expr_free(Arg);
1232   isl_ast_expr_free(Expr);
1233   isl_ast_node_free(TransferStmt);
1234 }
1235 
1236 void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
1237   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
1238   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1239   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1240   isl_id_free(Id);
1241   isl_ast_expr_free(StmtExpr);
1242 
1243   const char *Str = isl_id_get_name(Id);
1244   if (!strcmp(Str, "kernel")) {
1245     createKernel(UserStmt);
1246     if (PollyManagedMemory)
1247       createCallSynchronizeDevice();
1248     isl_ast_expr_free(Expr);
1249     return;
1250   }
1251   if (!strcmp(Str, "init_device")) {
1252     initializeAfterRTH();
1253     isl_ast_node_free(UserStmt);
1254     isl_ast_expr_free(Expr);
1255     return;
1256   }
1257   if (!strcmp(Str, "clear_device")) {
1258     finalize();
1259     isl_ast_node_free(UserStmt);
1260     isl_ast_expr_free(Expr);
1261     return;
1262   }
1263   if (isPrefix(Str, "to_device")) {
1264     if (!PollyManagedMemory)
1265       createDataTransfer(UserStmt, HOST_TO_DEVICE);
1266     else
1267       isl_ast_node_free(UserStmt);
1268 
1269     isl_ast_expr_free(Expr);
1270     return;
1271   }
1272 
1273   if (isPrefix(Str, "from_device")) {
1274     if (!PollyManagedMemory) {
1275       createDataTransfer(UserStmt, DEVICE_TO_HOST);
1276     } else {
1277       isl_ast_node_free(UserStmt);
1278     }
1279     isl_ast_expr_free(Expr);
1280     return;
1281   }
1282 
1283   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
1284   struct ppcg_kernel_stmt *KernelStmt =
1285       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
1286   isl_id_free(Anno);
1287 
1288   switch (KernelStmt->type) {
1289   case ppcg_kernel_domain:
1290     createScopStmt(Expr, KernelStmt);
1291     isl_ast_node_free(UserStmt);
1292     return;
1293   case ppcg_kernel_copy:
1294     createKernelCopy(KernelStmt);
1295     isl_ast_expr_free(Expr);
1296     isl_ast_node_free(UserStmt);
1297     return;
1298   case ppcg_kernel_sync:
1299     createKernelSync();
1300     isl_ast_expr_free(Expr);
1301     isl_ast_node_free(UserStmt);
1302     return;
1303   }
1304 
1305   isl_ast_expr_free(Expr);
1306   isl_ast_node_free(UserStmt);
1307 }
1308 
1309 void GPUNodeBuilder::createFor(__isl_take isl_ast_node *Node) {
1310   createForSequential(isl::manage(Node), false);
1311 }
1312 
1313 void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
1314   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
1315   LocalIndex = isl_ast_expr_address_of(LocalIndex);
1316   Value *LocalAddr = ExprBuilder.create(LocalIndex);
1317   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
1318   Index = isl_ast_expr_address_of(Index);
1319   Value *GlobalAddr = ExprBuilder.create(Index);
1320 
1321   if (KernelStmt->u.c.read) {
1322     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
1323     Builder.CreateStore(Load, LocalAddr);
1324   } else {
1325     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
1326     Builder.CreateStore(Load, GlobalAddr);
1327   }
1328 }
1329 
1330 void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
1331                                     ppcg_kernel_stmt *KernelStmt) {
1332   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1333   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
1334 
1335   LoopToScevMapT LTS;
1336   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
1337 
1338   createSubstitutions(Expr, Stmt, LTS);
1339 
1340   if (Stmt->isBlockStmt())
1341     BlockGen.copyStmt(*Stmt, LTS, Indexes);
1342   else
1343     RegionGen.copyStmt(*Stmt, LTS, Indexes);
1344 }
1345 
1346 void GPUNodeBuilder::createKernelSync() {
1347   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1348   const char *SpirName = "__gen_ocl_barrier_global";
1349 
1350   Function *Sync;
1351 
1352   switch (Arch) {
1353   case GPUArch::SPIR64:
1354   case GPUArch::SPIR32:
1355     Sync = M->getFunction(SpirName);
1356 
1357     // If Sync is not available, declare it.
1358     if (!Sync) {
1359       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
1360       std::vector<Type *> Args;
1361       FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
1362       Sync = Function::Create(Ty, Linkage, SpirName, M);
1363       Sync->setCallingConv(CallingConv::SPIR_FUNC);
1364     }
1365     break;
1366   case GPUArch::NVPTX64:
1367     Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
1368     break;
1369   }
1370 
1371   Builder.CreateCall(Sync, {});
1372 }
1373 
1374 /// Collect llvm::Values referenced from @p Node
1375 ///
1376 /// This function only applies to isl_ast_nodes that are user_nodes referring
1377 /// to a ScopStmt. All other node types are ignore.
1378 ///
1379 /// @param Node The node to collect references for.
1380 /// @param User A user pointer used as storage for the data that is collected.
1381 ///
1382 /// @returns isl_bool_true if data could be collected successfully.
1383 isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
1384   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
1385     return isl_bool_true;
1386 
1387   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
1388   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
1389   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
1390   const char *Str = isl_id_get_name(Id);
1391   isl_id_free(Id);
1392   isl_ast_expr_free(StmtExpr);
1393   isl_ast_expr_free(Expr);
1394 
1395   if (!isPrefix(Str, "Stmt"))
1396     return isl_bool_true;
1397 
1398   Id = isl_ast_node_get_annotation(Node);
1399   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
1400   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
1401   isl_id_free(Id);
1402 
1403   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
1404 
1405   return isl_bool_true;
1406 }
1407 
1408 /// A list of functions that are available in NVIDIA's libdevice.
1409 const std::set<std::string> CUDALibDeviceFunctions = {
1410     "exp",      "expf",      "expl",      "cos", "cosf", "sqrt", "sqrtf",
1411     "copysign", "copysignf", "copysignl", "log", "logf", "powi", "powif"};
1412 
1413 // A map from intrinsics to their corresponding libdevice functions.
1414 const std::map<std::string, std::string> IntrinsicToLibdeviceFunc = {
1415     {"llvm.exp.f64", "exp"},
1416     {"llvm.exp.f32", "expf"},
1417     {"llvm.powi.f64", "powi"},
1418     {"llvm.powi.f32", "powif"}};
1419 
1420 /// Return the corresponding CUDA libdevice function name @p Name.
1421 /// Note that this function will try to convert instrinsics in the list
1422 /// IntrinsicToLibdeviceFunc into libdevice functions.
1423 /// This is because some intrinsics such as `exp`
1424 /// are not supported by the NVPTX backend.
1425 /// If this restriction of the backend is lifted, we should refactor our code
1426 /// so that we use intrinsics whenever possible.
1427 ///
1428 /// Return "" if we are not compiling for CUDA.
1429 std::string getCUDALibDeviceFuntion(StringRef NameRef) {
1430   std::string Name = NameRef.str();
1431   auto It = IntrinsicToLibdeviceFunc.find(Name);
1432   if (It != IntrinsicToLibdeviceFunc.end())
1433     return getCUDALibDeviceFuntion(It->second);
1434 
1435   if (CUDALibDeviceFunctions.count(Name))
1436     return ("__nv_" + Name);
1437 
1438   return "";
1439 }
1440 
1441 /// Check if F is a function that we can code-generate in a GPU kernel.
1442 static bool isValidFunctionInKernel(llvm::Function *F, bool AllowLibDevice) {
1443   assert(F && "F is an invalid pointer");
1444   // We string compare against the name of the function to allow
1445   // all variants of the intrinsic "llvm.sqrt.*", "llvm.fabs", and
1446   // "llvm.copysign".
1447   const StringRef Name = F->getName();
1448 
1449   if (AllowLibDevice && getCUDALibDeviceFuntion(Name).length() > 0)
1450     return true;
1451 
1452   return F->isIntrinsic() &&
1453          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
1454           Name.startswith("llvm.copysign"));
1455 }
1456 
1457 /// Do not take `Function` as a subtree value.
1458 ///
1459 /// We try to take the reference of all subtree values and pass them along
1460 /// to the kernel from the host. Taking an address of any function and
1461 /// trying to pass along is nonsensical. Only allow `Value`s that are not
1462 /// `Function`s.
1463 static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1464 
1465 /// Return `Function`s from `RawSubtreeValues`.
1466 static SetVector<Function *>
1467 getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues,
1468                                  bool AllowCUDALibDevice) {
1469   SetVector<Function *> SubtreeFunctions;
1470   for (Value *It : RawSubtreeValues) {
1471     Function *F = dyn_cast<Function>(It);
1472     if (F) {
1473       assert(isValidFunctionInKernel(F, AllowCUDALibDevice) &&
1474              "Code should have bailed out by "
1475              "this point if an invalid function "
1476              "were present in a kernel.");
1477       SubtreeFunctions.insert(F);
1478     }
1479   }
1480   return SubtreeFunctions;
1481 }
1482 
1483 std::tuple<SetVector<Value *>, SetVector<Function *>, SetVector<const Loop *>,
1484            isl::space>
1485 GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1486   SetVector<Value *> SubtreeValues;
1487   SetVector<const SCEV *> SCEVs;
1488   SetVector<const Loop *> Loops;
1489   isl::space ParamSpace = isl::space(S.getIslCtx(), 0, 0).params();
1490   SubtreeReferences References = {
1491       LI,         SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator(),
1492       &ParamSpace};
1493 
1494   for (const auto &I : IDToValue)
1495     SubtreeValues.insert(I.second);
1496 
1497   // NOTE: this is populated in IslNodeBuilder::addParameters
1498   // See [Code generation of induction variables of loops outside Scops].
1499   for (const auto &I : OutsideLoopIterations)
1500     SubtreeValues.insert(cast<SCEVUnknown>(I.second)->getValue());
1501 
1502   isl_ast_node_foreach_descendant_top_down(
1503       Kernel->tree, collectReferencesInGPUStmt, &References);
1504 
1505   for (const SCEV *Expr : SCEVs) {
1506     findValues(Expr, SE, SubtreeValues);
1507     findLoops(Expr, Loops);
1508   }
1509 
1510   Loops.remove_if([this](const Loop *L) {
1511     return S.contains(L) || L->contains(S.getEntry());
1512   });
1513 
1514   for (auto &SAI : S.arrays())
1515     SubtreeValues.remove(SAI->getBasePtr());
1516 
1517   isl_space *Space = S.getParamSpace().release();
1518   for (long i = 0, n = isl_space_dim(Space, isl_dim_param); i < n; i++) {
1519     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1520     assert(IDToValue.count(Id));
1521     Value *Val = IDToValue[Id];
1522     SubtreeValues.remove(Val);
1523     isl_id_free(Id);
1524   }
1525   isl_space_free(Space);
1526 
1527   for (long i = 0, n = isl_space_dim(Kernel->space, isl_dim_set); i < n; i++) {
1528     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1529     assert(IDToValue.count(Id));
1530     Value *Val = IDToValue[Id];
1531     SubtreeValues.remove(Val);
1532     isl_id_free(Id);
1533   }
1534 
1535   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1536   // SubtreeValues. This is important, because we should not lose any
1537   // SubtreeValues in the process of constructing the
1538   // "ValidSubtree{Values, Functions} sets. Nor should the set
1539   // ValidSubtree{Values, Functions} have any common element.
1540   auto ValidSubtreeValuesIt =
1541       make_filter_range(SubtreeValues, isValidSubtreeValue);
1542   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1543                                         ValidSubtreeValuesIt.end());
1544 
1545   bool AllowCUDALibDevice = Arch == GPUArch::NVPTX64;
1546 
1547   SetVector<Function *> ValidSubtreeFunctions(
1548       getFunctionsFromRawSubtreeValues(SubtreeValues, AllowCUDALibDevice));
1549 
1550   // @see IslNodeBuilder::getReferencesInSubtree
1551   SetVector<Value *> ReplacedValues;
1552   for (Value *V : ValidSubtreeValues) {
1553     auto It = ValueMap.find(V);
1554     if (It == ValueMap.end())
1555       ReplacedValues.insert(V);
1556     else
1557       ReplacedValues.insert(It->second);
1558   }
1559   return std::make_tuple(ReplacedValues, ValidSubtreeFunctions, Loops,
1560                          ParamSpace);
1561 }
1562 
1563 void GPUNodeBuilder::clearDominators(Function *F) {
1564   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
1565   std::vector<BasicBlock *> Nodes;
1566   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
1567     Nodes.push_back(I->getBlock());
1568 
1569   for (BasicBlock *BB : Nodes)
1570     DT.eraseNode(BB);
1571 }
1572 
1573 void GPUNodeBuilder::clearScalarEvolution(Function *F) {
1574   for (BasicBlock &BB : *F) {
1575     Loop *L = LI.getLoopFor(&BB);
1576     if (L)
1577       SE.forgetLoop(L);
1578   }
1579 }
1580 
1581 void GPUNodeBuilder::clearLoops(Function *F) {
1582   SmallSet<Loop *, 1> WorkList;
1583   for (BasicBlock &BB : *F) {
1584     Loop *L = LI.getLoopFor(&BB);
1585     if (L)
1586       WorkList.insert(L);
1587   }
1588   for (auto *L : WorkList)
1589     LI.erase(L);
1590 }
1591 
1592 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
1593   std::vector<Value *> Sizes;
1594   isl::ast_build Context = isl::ast_build::from_context(S.getContext());
1595 
1596   isl::multi_pw_aff GridSizePwAffs = isl::manage_copy(Kernel->grid_size);
1597   for (long i = 0; i < Kernel->n_grid; i++) {
1598     isl::pw_aff Size = GridSizePwAffs.get_pw_aff(i);
1599     isl::ast_expr GridSize = Context.expr_from(Size);
1600     Value *Res = ExprBuilder.create(GridSize.release());
1601     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
1602     Sizes.push_back(Res);
1603   }
1604 
1605   for (long i = Kernel->n_grid; i < 3; i++)
1606     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
1607 
1608   return std::make_tuple(Sizes[0], Sizes[1]);
1609 }
1610 
1611 std::tuple<Value *, Value *, Value *>
1612 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
1613   std::vector<Value *> Sizes;
1614 
1615   for (long i = 0; i < Kernel->n_block; i++) {
1616     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
1617     Sizes.push_back(Res);
1618   }
1619 
1620   for (long i = Kernel->n_block; i < 3; i++)
1621     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
1622 
1623   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
1624 }
1625 
1626 void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1627                                           Instruction *Param, int Index) {
1628   Value *Slot = Builder.CreateGEP(
1629       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1630   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1631   Builder.CreateStore(ParamTyped, Slot);
1632 }
1633 
1634 Value *
1635 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
1636                                        SetVector<Value *> SubtreeValues) {
1637   const int NumArgs = F->arg_size();
1638   std::vector<int> ArgSizes(NumArgs);
1639 
1640   // If we are using the OpenCL Runtime, we need to add the kernel argument
1641   // sizes to the end of the launch-parameter list, so OpenCL can determine
1642   // how big the respective kernel arguments are.
1643   // Here we need to reserve adequate space for that.
1644   Type *ArrayTy;
1645   if (Runtime == GPURuntime::OpenCL)
1646     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
1647   else
1648     ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), NumArgs);
1649 
1650   BasicBlock *EntryBlock =
1651       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
1652   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
1653   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
1654   Instruction *Parameters = new AllocaInst(
1655       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
1656 
1657   int Index = 0;
1658   for (long i = 0; i < Prog->n_array; i++) {
1659     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1660       continue;
1661 
1662     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1663     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1664 
1665     if (Runtime == GPURuntime::OpenCL)
1666       ArgSizes[Index] = SAI->getElemSizeInBytes();
1667 
1668     Value *DevArray = nullptr;
1669     if (PollyManagedMemory) {
1670       DevArray = getManagedDeviceArray(&Prog->array[i],
1671                                        const_cast<ScopArrayInfo *>(SAI));
1672     } else {
1673       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
1674       DevArray = createCallGetDevicePtr(DevArray);
1675     }
1676     assert(DevArray != nullptr && "Array to be offloaded to device not "
1677                                   "initialized");
1678     Value *Offset = getArrayOffset(&Prog->array[i]);
1679 
1680     if (Offset) {
1681       DevArray = Builder.CreatePointerCast(
1682           DevArray, SAI->getElementType()->getPointerTo());
1683       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1684       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1685     }
1686     Value *Slot = Builder.CreateGEP(
1687         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1688 
1689     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1690       Value *ValPtr = nullptr;
1691       if (PollyManagedMemory)
1692         ValPtr = DevArray;
1693       else
1694         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1695 
1696       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1697                                   " to be stored into Parameters");
1698       Value *ValPtrCast =
1699           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1700       Builder.CreateStore(ValPtrCast, Slot);
1701     } else {
1702       Instruction *Param =
1703           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
1704                          Launch + "_param_" + std::to_string(Index),
1705                          EntryBlock->getTerminator());
1706       Builder.CreateStore(DevArray, Param);
1707       Value *ParamTyped =
1708           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1709       Builder.CreateStore(ParamTyped, Slot);
1710     }
1711     Index++;
1712   }
1713 
1714   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1715 
1716   for (long i = 0; i < NumHostIters; i++) {
1717     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1718     Value *Val = IDToValue[Id];
1719     isl_id_free(Id);
1720 
1721     if (Runtime == GPURuntime::OpenCL)
1722       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1723 
1724     Instruction *Param =
1725         new AllocaInst(Val->getType(), AddressSpace,
1726                        Launch + "_param_" + std::to_string(Index),
1727                        EntryBlock->getTerminator());
1728     Builder.CreateStore(Val, Param);
1729     insertStoreParameter(Parameters, Param, Index);
1730     Index++;
1731   }
1732 
1733   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1734 
1735   for (long i = 0; i < NumVars; i++) {
1736     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1737     Value *Val = IDToValue[Id];
1738     if (ValueMap.count(Val))
1739       Val = ValueMap[Val];
1740     isl_id_free(Id);
1741 
1742     if (Runtime == GPURuntime::OpenCL)
1743       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1744 
1745     Instruction *Param =
1746         new AllocaInst(Val->getType(), AddressSpace,
1747                        Launch + "_param_" + std::to_string(Index),
1748                        EntryBlock->getTerminator());
1749     Builder.CreateStore(Val, Param);
1750     insertStoreParameter(Parameters, Param, Index);
1751     Index++;
1752   }
1753 
1754   for (auto Val : SubtreeValues) {
1755     if (Runtime == GPURuntime::OpenCL)
1756       ArgSizes[Index] = computeSizeInBytes(Val->getType());
1757 
1758     Instruction *Param =
1759         new AllocaInst(Val->getType(), AddressSpace,
1760                        Launch + "_param_" + std::to_string(Index),
1761                        EntryBlock->getTerminator());
1762     Builder.CreateStore(Val, Param);
1763     insertStoreParameter(Parameters, Param, Index);
1764     Index++;
1765   }
1766 
1767   if (Runtime == GPURuntime::OpenCL) {
1768     for (int i = 0; i < NumArgs; i++) {
1769       Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1770       Instruction *Param =
1771           new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1772                          Launch + "_param_size_" + std::to_string(i),
1773                          EntryBlock->getTerminator());
1774       Builder.CreateStore(Val, Param);
1775       insertStoreParameter(Parameters, Param, Index);
1776       Index++;
1777     }
1778   }
1779 
1780   auto Location = EntryBlock->getTerminator();
1781   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
1782                          Launch + "_params_i8ptr", Location);
1783 }
1784 
1785 void GPUNodeBuilder::setupKernelSubtreeFunctions(
1786     SetVector<Function *> SubtreeFunctions) {
1787   for (auto Fn : SubtreeFunctions) {
1788     const std::string ClonedFnName = Fn->getName().str();
1789     Function *Clone = GPUModule->getFunction(ClonedFnName);
1790     if (!Clone)
1791       Clone =
1792           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1793                            ClonedFnName, GPUModule.get());
1794     assert(Clone && "Expected cloned function to be initialized.");
1795     assert(ValueMap.find(Fn) == ValueMap.end() &&
1796            "Fn already present in ValueMap");
1797     ValueMap[Fn] = Clone;
1798   }
1799 }
1800 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
1801   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
1802   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
1803   isl_id_free(Id);
1804   isl_ast_node_free(KernelStmt);
1805 
1806   if (Kernel->n_grid > 1)
1807     DeepestParallel = std::max(
1808         DeepestParallel, (unsigned)isl_space_dim(Kernel->space, isl_dim_set));
1809   else
1810     DeepestSequential = std::max(
1811         DeepestSequential, (unsigned)isl_space_dim(Kernel->space, isl_dim_set));
1812 
1813   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1814   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1815 
1816   SetVector<Value *> SubtreeValues;
1817   SetVector<Function *> SubtreeFunctions;
1818   SetVector<const Loop *> Loops;
1819   isl::space ParamSpace;
1820   std::tie(SubtreeValues, SubtreeFunctions, Loops, ParamSpace) =
1821       getReferencesInKernel(Kernel);
1822 
1823   // Add parameters that appear only in the access function to the kernel
1824   // space. This is important to make sure that all isl_ids are passed as
1825   // parameters to the kernel, even though we may not have all parameters
1826   // in the context to improve compile time.
1827   Kernel->space = isl_space_align_params(Kernel->space, ParamSpace.release());
1828 
1829   assert(Kernel->tree && "Device AST of kernel node is empty");
1830 
1831   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1832   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1833   ValueMapT HostValueMap = ValueMap;
1834   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1835   ScalarMap.clear();
1836   BlockGenerator::EscapeUsersAllocaMapTy HostEscapeMap = EscapeMap;
1837   EscapeMap.clear();
1838 
1839   // Create for all loops we depend on values that contain the current loop
1840   // iteration. These values are necessary to generate code for SCEVs that
1841   // depend on such loops. As a result we need to pass them to the subfunction.
1842   for (const Loop *L : Loops) {
1843     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1844                                             SE.getUnknown(Builder.getInt64(1)),
1845                                             L, SCEV::FlagAnyWrap);
1846     Value *V = generateSCEV(OuterLIV);
1847     OutsideLoopIterations[L] = SE.getUnknown(V);
1848     SubtreeValues.insert(V);
1849   }
1850 
1851   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1852   setupKernelSubtreeFunctions(SubtreeFunctions);
1853 
1854   create(isl_ast_node_copy(Kernel->tree));
1855 
1856   finalizeKernelArguments(Kernel);
1857   Function *F = Builder.GetInsertBlock()->getParent();
1858   if (Arch == GPUArch::NVPTX64)
1859     addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
1860   clearDominators(F);
1861   clearScalarEvolution(F);
1862   clearLoops(F);
1863 
1864   IDToValue = HostIDs;
1865 
1866   ValueMap = std::move(HostValueMap);
1867   ScalarMap = std::move(HostScalarMap);
1868   EscapeMap = std::move(HostEscapeMap);
1869   IDToSAI.clear();
1870   Annotator.resetAlternativeAliasBases();
1871   for (auto &BasePtr : LocalArrays)
1872     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
1873   LocalArrays.clear();
1874 
1875   std::string ASMString = finalizeKernelFunction();
1876   Builder.SetInsertPoint(&HostInsertPoint);
1877   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
1878 
1879   std::string Name = getKernelFuncName(Kernel->id);
1880   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
1881   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
1882   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
1883 
1884   Value *GridDimX, *GridDimY;
1885   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
1886 
1887   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
1888                          BlockDimZ, Parameters);
1889   createCallFreeKernel(GPUKernel);
1890 
1891   for (auto Id : KernelIds)
1892     isl_id_free(Id);
1893 
1894   KernelIds.clear();
1895 }
1896 
1897 /// Compute the DataLayout string for the NVPTX backend.
1898 ///
1899 /// @param is64Bit Are we looking for a 64 bit architecture?
1900 static std::string computeNVPTXDataLayout(bool is64Bit) {
1901   std::string Ret = "";
1902 
1903   if (!is64Bit) {
1904     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1905            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1906            "64-v128:128:128-n16:32:64";
1907   } else {
1908     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1909            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1910            "64-v128:128:128-n16:32:64";
1911   }
1912 
1913   return Ret;
1914 }
1915 
1916 /// Compute the DataLayout string for a SPIR kernel.
1917 ///
1918 /// @param is64Bit Are we looking for a 64 bit architecture?
1919 static std::string computeSPIRDataLayout(bool is64Bit) {
1920   std::string Ret = "";
1921 
1922   if (!is64Bit) {
1923     Ret += "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1924            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
1925            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
1926            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
1927   } else {
1928     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1929            "64-i128:128:128-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:"
1930            "32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:"
1931            "256:256-v256:256:256-v512:512:512-v1024:1024:1024";
1932   }
1933 
1934   return Ret;
1935 }
1936 
1937 Function *
1938 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1939                                          SetVector<Value *> &SubtreeValues) {
1940   std::vector<Type *> Args;
1941   std::string Identifier = getKernelFuncName(Kernel->id);
1942 
1943   std::vector<Metadata *> MemoryType;
1944 
1945   for (long i = 0; i < Prog->n_array; i++) {
1946     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1947       continue;
1948 
1949     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1950       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1951       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage(Id));
1952       Args.push_back(SAI->getElementType());
1953       MemoryType.push_back(
1954           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1955     } else {
1956       static const int UseGlobalMemory = 1;
1957       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
1958       MemoryType.push_back(
1959           ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 1)));
1960     }
1961   }
1962 
1963   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1964 
1965   for (long i = 0; i < NumHostIters; i++) {
1966     Args.push_back(Builder.getInt64Ty());
1967     MemoryType.push_back(
1968         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1969   }
1970 
1971   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1972 
1973   for (long i = 0; i < NumVars; i++) {
1974     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1975     Value *Val = IDToValue[Id];
1976     isl_id_free(Id);
1977     Args.push_back(Val->getType());
1978     MemoryType.push_back(
1979         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1980   }
1981 
1982   for (auto *V : SubtreeValues) {
1983     Args.push_back(V->getType());
1984     MemoryType.push_back(
1985         ConstantAsMetadata::get(ConstantInt::get(Builder.getInt32Ty(), 0)));
1986   }
1987 
1988   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
1989   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
1990                               GPUModule.get());
1991 
1992   std::vector<Metadata *> EmptyStrings;
1993 
1994   for (unsigned int i = 0; i < MemoryType.size(); i++) {
1995     EmptyStrings.push_back(MDString::get(FN->getContext(), ""));
1996   }
1997 
1998   if (Arch == GPUArch::SPIR32 || Arch == GPUArch::SPIR64) {
1999     FN->setMetadata("kernel_arg_addr_space",
2000                     MDNode::get(FN->getContext(), MemoryType));
2001     FN->setMetadata("kernel_arg_name",
2002                     MDNode::get(FN->getContext(), EmptyStrings));
2003     FN->setMetadata("kernel_arg_access_qual",
2004                     MDNode::get(FN->getContext(), EmptyStrings));
2005     FN->setMetadata("kernel_arg_type",
2006                     MDNode::get(FN->getContext(), EmptyStrings));
2007     FN->setMetadata("kernel_arg_type_qual",
2008                     MDNode::get(FN->getContext(), EmptyStrings));
2009     FN->setMetadata("kernel_arg_base_type",
2010                     MDNode::get(FN->getContext(), EmptyStrings));
2011   }
2012 
2013   switch (Arch) {
2014   case GPUArch::NVPTX64:
2015     FN->setCallingConv(CallingConv::PTX_Kernel);
2016     break;
2017   case GPUArch::SPIR32:
2018   case GPUArch::SPIR64:
2019     FN->setCallingConv(CallingConv::SPIR_KERNEL);
2020     break;
2021   }
2022 
2023   auto Arg = FN->arg_begin();
2024   for (long i = 0; i < Kernel->n_array; i++) {
2025     if (!ppcg_kernel_requires_array_argument(Kernel, i))
2026       continue;
2027 
2028     Arg->setName(Kernel->array[i].array->name);
2029 
2030     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2031     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2032     Type *EleTy = SAI->getElementType();
2033     Value *Val = &*Arg;
2034     SmallVector<const SCEV *, 4> Sizes;
2035     isl_ast_build *Build =
2036         isl_ast_build_from_context(isl_set_copy(Prog->context));
2037     Sizes.push_back(nullptr);
2038     for (long j = 1, n = Kernel->array[i].array->n_index; j < n; j++) {
2039       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
2040           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
2041       auto V = ExprBuilder.create(DimSize);
2042       Sizes.push_back(SE.getSCEV(V));
2043     }
2044     const ScopArrayInfo *SAIRep =
2045         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
2046     LocalArrays.push_back(Val);
2047 
2048     isl_ast_build_free(Build);
2049     KernelIds.push_back(Id);
2050     IDToSAI[Id] = SAIRep;
2051     Arg++;
2052   }
2053 
2054   for (long i = 0; i < NumHostIters; i++) {
2055     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
2056     Arg->setName(isl_id_get_name(Id));
2057     IDToValue[Id] = &*Arg;
2058     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2059     Arg++;
2060   }
2061 
2062   for (long i = 0; i < NumVars; i++) {
2063     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
2064     Arg->setName(isl_id_get_name(Id));
2065     Value *Val = IDToValue[Id];
2066     ValueMap[Val] = &*Arg;
2067     IDToValue[Id] = &*Arg;
2068     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2069     Arg++;
2070   }
2071 
2072   for (auto *V : SubtreeValues) {
2073     Arg->setName(V->getName());
2074     ValueMap[V] = &*Arg;
2075     Arg++;
2076   }
2077 
2078   return FN;
2079 }
2080 
2081 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
2082   Intrinsic::ID IntrinsicsBID[2];
2083   Intrinsic::ID IntrinsicsTID[3];
2084 
2085   switch (Arch) {
2086   case GPUArch::SPIR64:
2087   case GPUArch::SPIR32:
2088     llvm_unreachable("Cannot generate NVVM intrinsics for SPIR");
2089   case GPUArch::NVPTX64:
2090     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
2091     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
2092 
2093     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
2094     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
2095     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
2096     break;
2097   }
2098 
2099   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
2100     std::string Name = isl_id_get_name(Id);
2101     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2102     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
2103     Value *Val = Builder.CreateCall(IntrinsicFn, {});
2104     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2105     IDToValue[Id] = Val;
2106     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2107   };
2108 
2109   for (int i = 0; i < Kernel->n_grid; ++i) {
2110     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
2111     addId(Id, IntrinsicsBID[i]);
2112   }
2113 
2114   for (int i = 0; i < Kernel->n_block; ++i) {
2115     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
2116     addId(Id, IntrinsicsTID[i]);
2117   }
2118 }
2119 
2120 void GPUNodeBuilder::insertKernelCallsSPIR(ppcg_kernel *Kernel,
2121                                            bool SizeTypeIs64bit) {
2122   const char *GroupName[3] = {"__gen_ocl_get_group_id0",
2123                               "__gen_ocl_get_group_id1",
2124                               "__gen_ocl_get_group_id2"};
2125 
2126   const char *LocalName[3] = {"__gen_ocl_get_local_id0",
2127                               "__gen_ocl_get_local_id1",
2128                               "__gen_ocl_get_local_id2"};
2129   IntegerType *SizeT =
2130       SizeTypeIs64bit ? Builder.getInt64Ty() : Builder.getInt32Ty();
2131 
2132   auto createFunc = [this](const char *Name, __isl_take isl_id *Id,
2133                            IntegerType *SizeT) mutable {
2134     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2135     Function *FN = M->getFunction(Name);
2136 
2137     // If FN is not available, declare it.
2138     if (!FN) {
2139       GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
2140       std::vector<Type *> Args;
2141       FunctionType *Ty = FunctionType::get(SizeT, Args, false);
2142       FN = Function::Create(Ty, Linkage, Name, M);
2143       FN->setCallingConv(CallingConv::SPIR_FUNC);
2144     }
2145 
2146     Value *Val = Builder.CreateCall(FN, {});
2147     if (SizeT == Builder.getInt32Ty())
2148       Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
2149     IDToValue[Id] = Val;
2150     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
2151   };
2152 
2153   for (int i = 0; i < Kernel->n_grid; ++i)
2154     createFunc(GroupName[i], isl_id_list_get_id(Kernel->block_ids, i), SizeT);
2155 
2156   for (int i = 0; i < Kernel->n_block; ++i)
2157     createFunc(LocalName[i], isl_id_list_get_id(Kernel->thread_ids, i), SizeT);
2158 }
2159 
2160 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
2161   auto Arg = FN->arg_begin();
2162   for (long i = 0; i < Kernel->n_array; i++) {
2163     if (!ppcg_kernel_requires_array_argument(Kernel, i))
2164       continue;
2165 
2166     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2167     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2168     isl_id_free(Id);
2169 
2170     if (SAI->getNumberOfDimensions() > 0) {
2171       Arg++;
2172       continue;
2173     }
2174 
2175     Value *Val = &*Arg;
2176 
2177     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
2178       Type *TypePtr = SAI->getElementType()->getPointerTo();
2179       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
2180       Val = Builder.CreateLoad(TypedArgPtr);
2181     }
2182 
2183     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
2184     Builder.CreateStore(Val, Alloca);
2185 
2186     Arg++;
2187   }
2188 }
2189 
2190 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
2191   auto *FN = Builder.GetInsertBlock()->getParent();
2192   auto Arg = FN->arg_begin();
2193 
2194   bool StoredScalar = false;
2195   for (long i = 0; i < Kernel->n_array; i++) {
2196     if (!ppcg_kernel_requires_array_argument(Kernel, i))
2197       continue;
2198 
2199     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
2200     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl::manage_copy(Id));
2201     isl_id_free(Id);
2202 
2203     if (SAI->getNumberOfDimensions() > 0) {
2204       Arg++;
2205       continue;
2206     }
2207 
2208     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
2209       Arg++;
2210       continue;
2211     }
2212 
2213     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
2214     Value *ArgPtr = &*Arg;
2215     Type *TypePtr = SAI->getElementType()->getPointerTo();
2216     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
2217     Value *Val = Builder.CreateLoad(Alloca);
2218     Builder.CreateStore(Val, TypedArgPtr);
2219     StoredScalar = true;
2220 
2221     Arg++;
2222   }
2223 
2224   if (StoredScalar) {
2225     /// In case more than one thread contains scalar stores, the generated
2226     /// code might be incorrect, if we only store at the end of the kernel.
2227     /// To support this case we need to store these scalars back at each
2228     /// memory store or at least before each kernel barrier.
2229     if (Kernel->n_block != 0 || Kernel->n_grid != 0) {
2230       BuildSuccessful = 0;
2231       LLVM_DEBUG(
2232           dbgs() << getUniqueScopName(&S)
2233                  << " has a store to a scalar value that"
2234                     " would be undefined to run in parallel. Bailing out.\n";);
2235     }
2236   }
2237 }
2238 
2239 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
2240   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
2241 
2242   for (int i = 0; i < Kernel->n_var; ++i) {
2243     struct ppcg_kernel_var &Var = Kernel->var[i];
2244     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
2245     Type *EleTy = ScopArrayInfo::getFromId(isl::manage(Id))->getElementType();
2246 
2247     Type *ArrayTy = EleTy;
2248     SmallVector<const SCEV *, 4> Sizes;
2249 
2250     Sizes.push_back(nullptr);
2251     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
2252       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2253       long Bound = isl_val_get_num_si(Val);
2254       isl_val_free(Val);
2255       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
2256     }
2257 
2258     for (int j = Var.array->n_index - 1; j >= 0; --j) {
2259       isl_val *Val = isl_vec_get_element_val(Var.size, j);
2260       long Bound = isl_val_get_num_si(Val);
2261       isl_val_free(Val);
2262       ArrayTy = ArrayType::get(ArrayTy, Bound);
2263     }
2264 
2265     const ScopArrayInfo *SAI;
2266     Value *Allocation;
2267     if (Var.type == ppcg_access_shared) {
2268       auto GlobalVar = new GlobalVariable(
2269           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
2270           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
2271       GlobalVar->setAlignment(llvm::Align(EleTy->getPrimitiveSizeInBits() / 8));
2272       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
2273 
2274       Allocation = GlobalVar;
2275     } else if (Var.type == ppcg_access_private) {
2276       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
2277     } else {
2278       llvm_unreachable("unknown variable type");
2279     }
2280     SAI =
2281         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
2282     Id = isl_id_alloc(S.getIslCtx().get(), Var.name, nullptr);
2283     IDToValue[Id] = Allocation;
2284     LocalArrays.push_back(Allocation);
2285     KernelIds.push_back(Id);
2286     IDToSAI[Id] = SAI;
2287   }
2288 }
2289 
2290 void GPUNodeBuilder::createKernelFunction(
2291     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
2292     SetVector<Function *> &SubtreeFunctions) {
2293   std::string Identifier = getKernelFuncName(Kernel->id);
2294   GPUModule.reset(new Module(Identifier, Builder.getContext()));
2295 
2296   switch (Arch) {
2297   case GPUArch::NVPTX64:
2298     if (Runtime == GPURuntime::CUDA)
2299       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
2300     else if (Runtime == GPURuntime::OpenCL)
2301       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
2302     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
2303     break;
2304   case GPUArch::SPIR32:
2305     GPUModule->setTargetTriple(Triple::normalize("spir-unknown-unknown"));
2306     GPUModule->setDataLayout(computeSPIRDataLayout(false /* is64Bit */));
2307     break;
2308   case GPUArch::SPIR64:
2309     GPUModule->setTargetTriple(Triple::normalize("spir64-unknown-unknown"));
2310     GPUModule->setDataLayout(computeSPIRDataLayout(true /* is64Bit */));
2311     break;
2312   }
2313 
2314   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
2315 
2316   BasicBlock *PrevBlock = Builder.GetInsertBlock();
2317   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
2318 
2319   DT.addNewBlock(EntryBlock, PrevBlock);
2320 
2321   Builder.SetInsertPoint(EntryBlock);
2322   Builder.CreateRetVoid();
2323   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2324 
2325   ScopDetection::markFunctionAsInvalid(FN);
2326 
2327   prepareKernelArguments(Kernel, FN);
2328   createKernelVariables(Kernel, FN);
2329 
2330   switch (Arch) {
2331   case GPUArch::NVPTX64:
2332     insertKernelIntrinsics(Kernel);
2333     break;
2334   case GPUArch::SPIR32:
2335     insertKernelCallsSPIR(Kernel, false);
2336     break;
2337   case GPUArch::SPIR64:
2338     insertKernelCallsSPIR(Kernel, true);
2339     break;
2340   }
2341 }
2342 
2343 std::string GPUNodeBuilder::createKernelASM() {
2344   llvm::Triple GPUTriple;
2345 
2346   switch (Arch) {
2347   case GPUArch::NVPTX64:
2348     switch (Runtime) {
2349     case GPURuntime::CUDA:
2350       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
2351       break;
2352     case GPURuntime::OpenCL:
2353       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
2354       break;
2355     }
2356     break;
2357   case GPUArch::SPIR64:
2358   case GPUArch::SPIR32:
2359     std::string SPIRAssembly;
2360     raw_string_ostream IROstream(SPIRAssembly);
2361     IROstream << *GPUModule;
2362     IROstream.flush();
2363     return SPIRAssembly;
2364   }
2365 
2366   std::string ErrMsg;
2367   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
2368 
2369   if (!GPUTarget) {
2370     errs() << ErrMsg << "\n";
2371     return "";
2372   }
2373 
2374   TargetOptions Options;
2375   Options.UnsafeFPMath = FastMath;
2376 
2377   std::string subtarget;
2378 
2379   switch (Arch) {
2380   case GPUArch::NVPTX64:
2381     subtarget = CudaVersion;
2382     break;
2383   case GPUArch::SPIR32:
2384   case GPUArch::SPIR64:
2385     llvm_unreachable("No subtarget for SPIR architecture");
2386   }
2387 
2388   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
2389       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
2390 
2391   SmallString<0> ASMString;
2392   raw_svector_ostream ASMStream(ASMString);
2393   llvm::legacy::PassManager PM;
2394 
2395   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
2396 
2397   if (TargetM->addPassesToEmitFile(PM, ASMStream, nullptr, CGFT_AssemblyFile,
2398                                    true /* verify */)) {
2399     errs() << "The target does not support generation of this file type!\n";
2400     return "";
2401   }
2402 
2403   PM.run(*GPUModule);
2404 
2405   return ASMStream.str().str();
2406 }
2407 
2408 bool GPUNodeBuilder::requiresCUDALibDevice() {
2409   bool RequiresLibDevice = false;
2410   for (Function &F : GPUModule->functions()) {
2411     if (!F.isDeclaration())
2412       continue;
2413 
2414     const std::string CUDALibDeviceFunc = getCUDALibDeviceFuntion(F.getName());
2415     if (CUDALibDeviceFunc.length() != 0) {
2416       // We need to handle the case where a module looks like this:
2417       // @expf(..)
2418       // @llvm.exp.f64(..)
2419       // Both of these functions would be renamed to `__nv_expf`.
2420       //
2421       // So, we must first check for the existence of the libdevice function.
2422       // If this exists, we replace our current function with it.
2423       //
2424       // If it does not exist, we rename the current function to the
2425       // libdevice functiono name.
2426       if (Function *Replacement = F.getParent()->getFunction(CUDALibDeviceFunc))
2427         F.replaceAllUsesWith(Replacement);
2428       else
2429         F.setName(CUDALibDeviceFunc);
2430       RequiresLibDevice = true;
2431     }
2432   }
2433 
2434   return RequiresLibDevice;
2435 }
2436 
2437 void GPUNodeBuilder::addCUDALibDevice() {
2438   if (Arch != GPUArch::NVPTX64)
2439     return;
2440 
2441   if (requiresCUDALibDevice()) {
2442     SMDiagnostic Error;
2443 
2444     errs() << CUDALibDevice << "\n";
2445     auto LibDeviceModule =
2446         parseIRFile(CUDALibDevice, Error, GPUModule->getContext());
2447 
2448     if (!LibDeviceModule) {
2449       BuildSuccessful = false;
2450       report_fatal_error("Could not find or load libdevice. Skipping GPU "
2451                          "kernel generation. Please set -polly-acc-libdevice "
2452                          "accordingly.\n");
2453       return;
2454     }
2455 
2456     Linker L(*GPUModule);
2457 
2458     // Set an nvptx64 target triple to avoid linker warnings. The original
2459     // triple of the libdevice files are nvptx-unknown-unknown.
2460     LibDeviceModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
2461     L.linkInModule(std::move(LibDeviceModule), Linker::LinkOnlyNeeded);
2462   }
2463 }
2464 
2465 std::string GPUNodeBuilder::finalizeKernelFunction() {
2466 
2467   if (verifyModule(*GPUModule)) {
2468     LLVM_DEBUG(dbgs() << "verifyModule failed on module:\n";
2469                GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2470     LLVM_DEBUG(dbgs() << "verifyModule Error:\n";
2471                verifyModule(*GPUModule, &dbgs()););
2472 
2473     if (FailOnVerifyModuleFailure)
2474       llvm_unreachable("VerifyModule failed.");
2475 
2476     BuildSuccessful = false;
2477     return "";
2478   }
2479 
2480   addCUDALibDevice();
2481 
2482   if (DumpKernelIR)
2483     outs() << *GPUModule << "\n";
2484 
2485   if (Arch != GPUArch::SPIR32 && Arch != GPUArch::SPIR64) {
2486     // Optimize module.
2487     llvm::legacy::PassManager OptPasses;
2488     PassManagerBuilder PassBuilder;
2489     PassBuilder.OptLevel = 3;
2490     PassBuilder.SizeLevel = 0;
2491     PassBuilder.populateModulePassManager(OptPasses);
2492     OptPasses.run(*GPUModule);
2493   }
2494 
2495   std::string Assembly = createKernelASM();
2496 
2497   if (DumpKernelASM)
2498     outs() << Assembly << "\n";
2499 
2500   GPUModule.release();
2501   KernelIDs.clear();
2502 
2503   return Assembly;
2504 }
2505 /// Construct an `isl_pw_aff_list` from a vector of `isl_pw_aff`
2506 /// @param PwAffs The list of piecewise affine functions to create an
2507 ///               `isl_pw_aff_list` from. We expect an rvalue ref because
2508 ///               all the isl_pw_aff are used up by this function.
2509 ///
2510 /// @returns  The `isl_pw_aff_list`.
2511 __isl_give isl_pw_aff_list *
2512 createPwAffList(isl_ctx *Context,
2513                 const std::vector<__isl_take isl_pw_aff *> &&PwAffs) {
2514   isl_pw_aff_list *List = isl_pw_aff_list_alloc(Context, PwAffs.size());
2515 
2516   for (unsigned i = 0; i < PwAffs.size(); i++) {
2517     List = isl_pw_aff_list_insert(List, i, PwAffs[i]);
2518   }
2519   return List;
2520 }
2521 
2522 /// Align all the `PwAffs` such that they have the same parameter dimensions.
2523 ///
2524 /// We loop over all `pw_aff` and align all of their spaces together to
2525 /// create a common space for all the `pw_aff`. This common space is the
2526 /// `AlignSpace`. We then align all the `pw_aff` to this space. We start
2527 /// with the given `SeedSpace`.
2528 /// @param PwAffs    The list of piecewise affine functions we want to align.
2529 ///                  This is an rvalue reference because the entire vector is
2530 ///                  used up by the end of the operation.
2531 /// @param SeedSpace The space to start the alignment process with.
2532 /// @returns         A std::pair, whose first element is the aligned space,
2533 ///                  whose second element is the vector of aligned piecewise
2534 ///                  affines.
2535 static std::pair<__isl_give isl_space *, std::vector<__isl_give isl_pw_aff *>>
2536 alignPwAffs(const std::vector<__isl_take isl_pw_aff *> &&PwAffs,
2537             __isl_take isl_space *SeedSpace) {
2538   assert(SeedSpace && "Invalid seed space given.");
2539 
2540   isl_space *AlignSpace = SeedSpace;
2541   for (isl_pw_aff *PwAff : PwAffs) {
2542     isl_space *PwAffSpace = isl_pw_aff_get_domain_space(PwAff);
2543     AlignSpace = isl_space_align_params(AlignSpace, PwAffSpace);
2544   }
2545   std::vector<isl_pw_aff *> AdjustedPwAffs;
2546 
2547   for (unsigned i = 0; i < PwAffs.size(); i++) {
2548     isl_pw_aff *Adjusted = PwAffs[i];
2549     assert(Adjusted && "Invalid pw_aff given.");
2550     Adjusted = isl_pw_aff_align_params(Adjusted, isl_space_copy(AlignSpace));
2551     AdjustedPwAffs.push_back(Adjusted);
2552   }
2553   return std::make_pair(AlignSpace, AdjustedPwAffs);
2554 }
2555 
2556 namespace {
2557 class PPCGCodeGeneration : public ScopPass {
2558 public:
2559   static char ID;
2560 
2561   GPURuntime Runtime = GPURuntime::CUDA;
2562 
2563   GPUArch Architecture = GPUArch::NVPTX64;
2564 
2565   /// The scop that is currently processed.
2566   Scop *S;
2567 
2568   LoopInfo *LI;
2569   DominatorTree *DT;
2570   ScalarEvolution *SE;
2571   const DataLayout *DL;
2572   RegionInfo *RI;
2573 
2574   PPCGCodeGeneration() : ScopPass(ID) {
2575     // Apply defaults.
2576     Runtime = GPURuntimeChoice;
2577     Architecture = GPUArchChoice;
2578   }
2579 
2580   /// Construct compilation options for PPCG.
2581   ///
2582   /// @returns The compilation options.
2583   ppcg_options *createPPCGOptions() {
2584     auto DebugOptions =
2585         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2586     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2587 
2588     DebugOptions->dump_schedule_constraints = false;
2589     DebugOptions->dump_schedule = false;
2590     DebugOptions->dump_final_schedule = false;
2591     DebugOptions->dump_sizes = false;
2592     DebugOptions->verbose = false;
2593 
2594     Options->debug = DebugOptions;
2595 
2596     Options->group_chains = false;
2597     Options->reschedule = true;
2598     Options->scale_tile_loops = false;
2599     Options->wrap = false;
2600 
2601     Options->non_negative_parameters = false;
2602     Options->ctx = nullptr;
2603     Options->sizes = nullptr;
2604 
2605     Options->tile = true;
2606     Options->tile_size = 32;
2607 
2608     Options->isolate_full_tiles = false;
2609 
2610     Options->use_private_memory = PrivateMemory;
2611     Options->use_shared_memory = SharedMemory;
2612     Options->max_shared_memory = 48 * 1024;
2613 
2614     Options->target = PPCG_TARGET_CUDA;
2615     Options->openmp = false;
2616     Options->linearize_device_arrays = true;
2617     Options->allow_gnu_extensions = false;
2618 
2619     Options->unroll_copy_shared = false;
2620     Options->unroll_gpu_tile = false;
2621     Options->live_range_reordering = true;
2622 
2623     Options->live_range_reordering = true;
2624     Options->hybrid = false;
2625     Options->opencl_compiler_options = nullptr;
2626     Options->opencl_use_gpu = false;
2627     Options->opencl_n_include_file = 0;
2628     Options->opencl_include_files = nullptr;
2629     Options->opencl_print_kernel_types = false;
2630     Options->opencl_embed_kernel_code = false;
2631 
2632     Options->save_schedule_file = nullptr;
2633     Options->load_schedule_file = nullptr;
2634 
2635     return Options;
2636   }
2637 
2638   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2639   ///
2640   /// Instead of a normal access of the form:
2641   ///
2642   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2643   ///
2644   /// a tagged access has the form
2645   ///
2646   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2647   ///
2648   /// where 'id' is an additional space that references the memory access that
2649   /// triggered the access.
2650   ///
2651   /// @param AccessTy The type of the memory accesses to collect.
2652   ///
2653   /// @return The relation describing all tagged memory accesses.
2654   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2655     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace().release());
2656 
2657     for (auto &Stmt : *S)
2658       for (auto &Acc : Stmt)
2659         if (Acc->getType() == AccessTy) {
2660           isl_map *Relation = Acc->getAccessRelation().release();
2661           Relation =
2662               isl_map_intersect_domain(Relation, Stmt.getDomain().release());
2663 
2664           isl_space *Space = isl_map_get_space(Relation);
2665           Space = isl_space_range(Space);
2666           Space = isl_space_from_range(Space);
2667           Space =
2668               isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2669           isl_map *Universe = isl_map_universe(Space);
2670           Relation = isl_map_domain_product(Relation, Universe);
2671           Accesses = isl_union_map_add_map(Accesses, Relation);
2672         }
2673 
2674     return Accesses;
2675   }
2676 
2677   /// Get the set of all read accesses, tagged with the access id.
2678   ///
2679   /// @see getTaggedAccesses
2680   isl_union_map *getTaggedReads() {
2681     return getTaggedAccesses(MemoryAccess::READ);
2682   }
2683 
2684   /// Get the set of all may (and must) accesses, tagged with the access id.
2685   ///
2686   /// @see getTaggedAccesses
2687   isl_union_map *getTaggedMayWrites() {
2688     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2689                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2690   }
2691 
2692   /// Get the set of all must accesses, tagged with the access id.
2693   ///
2694   /// @see getTaggedAccesses
2695   isl_union_map *getTaggedMustWrites() {
2696     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2697   }
2698 
2699   /// Collect parameter and array names as isl_ids.
2700   ///
2701   /// To reason about the different parameters and arrays used, ppcg requires
2702   /// a list of all isl_ids in use. As PPCG traditionally performs
2703   /// source-to-source compilation each of these isl_ids is mapped to the
2704   /// expression that represents it. As we do not have a corresponding
2705   /// expression in Polly, we just map each id to a 'zero' expression to match
2706   /// the data format that ppcg expects.
2707   ///
2708   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2709   __isl_give isl_id_to_ast_expr *getNames() {
2710     auto *Names = isl_id_to_ast_expr_alloc(
2711         S->getIslCtx().get(),
2712         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2713     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx().get()));
2714 
2715     for (const SCEV *P : S->parameters()) {
2716       isl_id *Id = S->getIdForParam(P).release();
2717       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2718     }
2719 
2720     for (auto &Array : S->arrays()) {
2721       auto Id = Array->getBasePtrId().release();
2722       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2723     }
2724 
2725     isl_ast_expr_free(Zero);
2726 
2727     return Names;
2728   }
2729 
2730   /// Create a new PPCG scop from the current scop.
2731   ///
2732   /// The PPCG scop is initialized with data from the current polly::Scop. From
2733   /// this initial data, the data-dependences in the PPCG scop are initialized.
2734   /// We do not use Polly's dependence analysis for now, to ensure we match
2735   /// the PPCG default behaviour more closely.
2736   ///
2737   /// @returns A new ppcg scop.
2738   ppcg_scop *createPPCGScop() {
2739     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
2740 
2741     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2742 
2743     PPCGScop->options = createPPCGOptions();
2744     // enable live range reordering
2745     PPCGScop->options->live_range_reordering = 1;
2746 
2747     PPCGScop->start = 0;
2748     PPCGScop->end = 0;
2749 
2750     PPCGScop->context = S->getContext().release();
2751     PPCGScop->domain = S->getDomains().release();
2752     // TODO: investigate this further. PPCG calls collect_call_domains.
2753     PPCGScop->call = isl_union_set_from_set(S->getContext().release());
2754     PPCGScop->tagged_reads = getTaggedReads();
2755     PPCGScop->reads = S->getReads().release();
2756     PPCGScop->live_in = nullptr;
2757     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2758     PPCGScop->may_writes = S->getWrites().release();
2759     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2760     PPCGScop->must_writes = S->getMustWrites().release();
2761     PPCGScop->live_out = nullptr;
2762     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.release();
2763     PPCGScop->must_kills = KillsInfo.MustKills.release();
2764 
2765     PPCGScop->tagger = nullptr;
2766     PPCGScop->independence =
2767         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2768     PPCGScop->dep_flow = nullptr;
2769     PPCGScop->tagged_dep_flow = nullptr;
2770     PPCGScop->dep_false = nullptr;
2771     PPCGScop->dep_forced = nullptr;
2772     PPCGScop->dep_order = nullptr;
2773     PPCGScop->tagged_dep_order = nullptr;
2774 
2775     PPCGScop->schedule = S->getScheduleTree().release();
2776     // If we have something non-trivial to kill, add it to the schedule
2777     if (KillsInfo.KillsSchedule.get())
2778       PPCGScop->schedule = isl_schedule_sequence(
2779           PPCGScop->schedule, KillsInfo.KillsSchedule.release());
2780 
2781     PPCGScop->names = getNames();
2782     PPCGScop->pet = nullptr;
2783 
2784     compute_tagger(PPCGScop);
2785     compute_dependences(PPCGScop);
2786     eliminate_dead_code(PPCGScop);
2787 
2788     return PPCGScop;
2789   }
2790 
2791   /// Collect the array accesses in a statement.
2792   ///
2793   /// @param Stmt The statement for which to collect the accesses.
2794   ///
2795   /// @returns A list of array accesses.
2796   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
2797     gpu_stmt_access *Accesses = nullptr;
2798 
2799     for (MemoryAccess *Acc : Stmt) {
2800       auto Access =
2801           isl_alloc_type(S->getIslCtx().get(), struct gpu_stmt_access);
2802       Access->read = Acc->isRead();
2803       Access->write = Acc->isWrite();
2804       Access->access = Acc->getAccessRelation().release();
2805       isl_space *Space = isl_map_get_space(Access->access);
2806       Space = isl_space_range(Space);
2807       Space = isl_space_from_range(Space);
2808       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId().release());
2809       isl_map *Universe = isl_map_universe(Space);
2810       Access->tagged_access =
2811           isl_map_domain_product(Acc->getAccessRelation().release(), Universe);
2812       Access->exact_write = !Acc->isMayWrite();
2813       Access->ref_id = Acc->getId().release();
2814       Access->next = Accesses;
2815       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
2816       // TODO: Also mark one-element accesses to arrays as fixed-element.
2817       Access->fixed_element =
2818           Acc->isLatestScalarKind() ? isl_bool_true : isl_bool_false;
2819       Accesses = Access;
2820     }
2821 
2822     return Accesses;
2823   }
2824 
2825   /// Collect the list of GPU statements.
2826   ///
2827   /// Each statement has an id, a pointer to the underlying data structure,
2828   /// as well as a list with all memory accesses.
2829   ///
2830   /// TODO: Initialize the list of memory accesses.
2831   ///
2832   /// @returns A linked-list of statements.
2833   gpu_stmt *getStatements() {
2834     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx().get(), struct gpu_stmt,
2835                                        std::distance(S->begin(), S->end()));
2836 
2837     int i = 0;
2838     for (auto &Stmt : *S) {
2839       gpu_stmt *GPUStmt = &Stmts[i];
2840 
2841       GPUStmt->id = Stmt.getDomainId().release();
2842 
2843       // We use the pet stmt pointer to keep track of the Polly statements.
2844       GPUStmt->stmt = (pet_stmt *)&Stmt;
2845       GPUStmt->accesses = getStmtAccesses(Stmt);
2846       i++;
2847     }
2848 
2849     return Stmts;
2850   }
2851 
2852   /// Derive the extent of an array.
2853   ///
2854   /// The extent of an array is the set of elements that are within the
2855   /// accessed array. For the inner dimensions, the extent constraints are
2856   /// 0 and the size of the corresponding array dimension. For the first
2857   /// (outermost) dimension, the extent constraints are the minimal and maximal
2858   /// subscript value for the first dimension.
2859   ///
2860   /// @param Array The array to derive the extent for.
2861   ///
2862   /// @returns An isl_set describing the extent of the array.
2863   isl::set getExtent(ScopArrayInfo *Array) {
2864     unsigned NumDims = Array->getNumberOfDimensions();
2865 
2866     if (Array->getNumberOfDimensions() == 0)
2867       return isl::set::universe(Array->getSpace());
2868 
2869     isl::union_map Accesses = S->getAccesses(Array);
2870     isl::union_set AccessUSet = Accesses.range();
2871     AccessUSet = AccessUSet.coalesce();
2872     AccessUSet = AccessUSet.detect_equalities();
2873     AccessUSet = AccessUSet.coalesce();
2874 
2875     if (AccessUSet.is_empty())
2876       return isl::set::empty(Array->getSpace());
2877 
2878     isl::set AccessSet = AccessUSet.extract_set(Array->getSpace());
2879 
2880     isl::local_space LS = isl::local_space(Array->getSpace());
2881 
2882     isl::pw_aff Val = isl::aff::var_on_domain(LS, isl::dim::set, 0);
2883     isl::pw_aff OuterMin = AccessSet.dim_min(0);
2884     isl::pw_aff OuterMax = AccessSet.dim_max(0);
2885     OuterMin = OuterMin.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2886     OuterMax = OuterMax.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2887     OuterMin = OuterMin.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2888     OuterMax = OuterMax.set_tuple_id(isl::dim::in, Array->getBasePtrId());
2889 
2890     isl::set Extent = isl::set::universe(Array->getSpace());
2891 
2892     Extent = Extent.intersect(OuterMin.le_set(Val));
2893     Extent = Extent.intersect(OuterMax.ge_set(Val));
2894 
2895     for (unsigned i = 1; i < NumDims; ++i)
2896       Extent = Extent.lower_bound_si(isl::dim::set, i, 0);
2897 
2898     for (unsigned i = 0; i < NumDims; ++i) {
2899       isl::pw_aff PwAff = Array->getDimensionSizePw(i);
2900 
2901       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2902       // Fortran array will we have a legitimate dimension.
2903       if (PwAff.is_null()) {
2904         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2905         continue;
2906       }
2907 
2908       isl::pw_aff Val = isl::aff::var_on_domain(
2909           isl::local_space(Array->getSpace()), isl::dim::set, i);
2910       PwAff = PwAff.add_dims(isl::dim::in, Val.dim(isl::dim::in));
2911       PwAff = PwAff.set_tuple_id(isl::dim::in, Val.get_tuple_id(isl::dim::in));
2912       isl::set Set = PwAff.gt_set(Val);
2913       Extent = Set.intersect(Extent);
2914     }
2915 
2916     return Extent;
2917   }
2918 
2919   /// Derive the bounds of an array.
2920   ///
2921   /// For the first dimension we derive the bound of the array from the extent
2922   /// of this dimension. For inner dimensions we obtain their size directly from
2923   /// ScopArrayInfo.
2924   ///
2925   /// @param PPCGArray The array to compute bounds for.
2926   /// @param Array The polly array from which to take the information.
2927   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2928     std::vector<isl_pw_aff *> Bounds;
2929 
2930     if (PPCGArray.n_index > 0) {
2931       if (isl_set_is_empty(PPCGArray.extent)) {
2932         isl_set *Dom = isl_set_copy(PPCGArray.extent);
2933         isl_local_space *LS = isl_local_space_from_space(
2934             isl_space_params(isl_set_get_space(Dom)));
2935         isl_set_free(Dom);
2936         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2937         Bounds.push_back(Zero);
2938       } else {
2939         isl_set *Dom = isl_set_copy(PPCGArray.extent);
2940         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
2941         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
2942         isl_set_free(Dom);
2943         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
2944         isl_local_space *LS =
2945             isl_local_space_from_space(isl_set_get_space(Dom));
2946         isl_aff *One = isl_aff_zero_on_domain(LS);
2947         One = isl_aff_add_constant_si(One, 1);
2948         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
2949         Bound = isl_pw_aff_gist(Bound, S->getContext().release());
2950         Bounds.push_back(Bound);
2951       }
2952     }
2953 
2954     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
2955       isl_pw_aff *Bound = Array->getDimensionSizePw(i).release();
2956       auto LS = isl_pw_aff_get_domain_space(Bound);
2957       auto Aff = isl_multi_aff_zero(LS);
2958 
2959       // We need types to work out, which is why we perform this weird dance
2960       // with `Aff` and `Bound`. Consider this example:
2961 
2962       // LS: [p] -> { [] }
2963       // Zero: [p] -> { [] } | Implicitly, is [p] -> { ~ -> [] }.
2964       // This `~` is used to denote a "null space" (which is different from
2965       // a *zero dimensional* space), which is something that ISL does not
2966       // show you when pretty printing.
2967 
2968       // Bound: [p] -> { [] -> [(10p)] } | Here, the [] is a *zero dimensional*
2969       // space, not a "null space" which does not exist at all.
2970 
2971       // When we pullback (precompose) `Bound` with `Zero`, we get:
2972       // Bound . Zero =
2973       //     ([p] -> { [] -> [(10p)] }) . ([p] -> {~ -> [] }) =
2974       //     [p] -> { ~ -> [(10p)] } =
2975       //     [p] -> [(10p)] (as ISL pretty prints it)
2976       // Bound Pullback: [p] -> { [(10p)] }
2977 
2978       // We want this kind of an expression for Bound, without a
2979       // zero dimensional input, but with a "null space" input for the types
2980       // to work out later on, as far as I (Siddharth Bhat) understand.
2981       // I was unable to find a reference to this in the ISL manual.
2982       // References: Tobias Grosser.
2983 
2984       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2985       Bounds.push_back(Bound);
2986     }
2987 
2988     /// To construct a `isl_multi_pw_aff`, we need all the indivisual `pw_aff`
2989     /// to have the same parameter dimensions. So, we need to align them to an
2990     /// appropriate space.
2991     /// Scop::Context is _not_ an appropriate space, because when we have
2992     /// `-polly-ignore-parameter-bounds` enabled, the Scop::Context does not
2993     /// contain all parameter dimensions.
2994     /// So, use the helper `alignPwAffs` to align all the `isl_pw_aff` together.
2995     isl_space *SeedAlignSpace = S->getParamSpace().release();
2996     SeedAlignSpace = isl_space_add_dims(SeedAlignSpace, isl_dim_set, 1);
2997 
2998     isl_space *AlignSpace = nullptr;
2999     std::vector<isl_pw_aff *> AlignedBounds;
3000     std::tie(AlignSpace, AlignedBounds) =
3001         alignPwAffs(std::move(Bounds), SeedAlignSpace);
3002 
3003     assert(AlignSpace && "alignPwAffs did not initialise AlignSpace");
3004 
3005     isl_pw_aff_list *BoundsList =
3006         createPwAffList(S->getIslCtx().get(), std::move(AlignedBounds));
3007 
3008     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
3009     BoundsSpace = isl_space_align_params(BoundsSpace, AlignSpace);
3010 
3011     assert(BoundsSpace && "Unable to access space of array.");
3012     assert(BoundsList && "Unable to access list of bounds.");
3013 
3014     PPCGArray.bound =
3015         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
3016     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
3017   }
3018 
3019   /// Create the arrays for @p PPCGProg.
3020   ///
3021   /// @param PPCGProg The program to compute the arrays for.
3022   void createArrays(gpu_prog *PPCGProg,
3023                     const SmallVector<ScopArrayInfo *, 4> &ValidSAIs) {
3024     int i = 0;
3025     for (auto &Array : ValidSAIs) {
3026       std::string TypeName;
3027       raw_string_ostream OS(TypeName);
3028 
3029       OS << *Array->getElementType();
3030       TypeName = OS.str();
3031 
3032       gpu_array_info &PPCGArray = PPCGProg->array[i];
3033 
3034       PPCGArray.space = Array->getSpace().release();
3035       PPCGArray.type = strdup(TypeName.c_str());
3036       PPCGArray.size = DL->getTypeAllocSize(Array->getElementType());
3037       PPCGArray.name = strdup(Array->getName().c_str());
3038       PPCGArray.extent = nullptr;
3039       PPCGArray.n_index = Array->getNumberOfDimensions();
3040       PPCGArray.extent = getExtent(Array).release();
3041       PPCGArray.n_ref = 0;
3042       PPCGArray.refs = nullptr;
3043       PPCGArray.accessed = true;
3044       PPCGArray.read_only_scalar =
3045           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
3046       PPCGArray.has_compound_element = false;
3047       PPCGArray.local = false;
3048       PPCGArray.declare_local = false;
3049       PPCGArray.global = false;
3050       PPCGArray.linearize = false;
3051       PPCGArray.dep_order = nullptr;
3052       PPCGArray.user = Array;
3053 
3054       PPCGArray.bound = nullptr;
3055       setArrayBounds(PPCGArray, Array);
3056       i++;
3057 
3058       collect_references(PPCGProg, &PPCGArray);
3059       PPCGArray.only_fixed_element = only_fixed_element_accessed(&PPCGArray);
3060     }
3061   }
3062 
3063   /// Create an identity map between the arrays in the scop.
3064   ///
3065   /// @returns An identity map between the arrays in the scop.
3066   isl_union_map *getArrayIdentity() {
3067     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace().release());
3068 
3069     for (auto &Array : S->arrays()) {
3070       isl_space *Space = Array->getSpace().release();
3071       Space = isl_space_map_from_set(Space);
3072       isl_map *Identity = isl_map_identity(Space);
3073       Maps = isl_union_map_add_map(Maps, Identity);
3074     }
3075 
3076     return Maps;
3077   }
3078 
3079   /// Create a default-initialized PPCG GPU program.
3080   ///
3081   /// @returns A new gpu program description.
3082   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
3083 
3084     if (!PPCGScop)
3085       return nullptr;
3086 
3087     auto PPCGProg = isl_calloc_type(S->getIslCtx().get(), struct gpu_prog);
3088 
3089     PPCGProg->ctx = S->getIslCtx().get();
3090     PPCGProg->scop = PPCGScop;
3091     PPCGProg->context = isl_set_copy(PPCGScop->context);
3092     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
3093     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
3094     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
3095     PPCGProg->tagged_must_kill =
3096         isl_union_map_copy(PPCGScop->tagged_must_kills);
3097     PPCGProg->to_inner = getArrayIdentity();
3098     PPCGProg->to_outer = getArrayIdentity();
3099     // TODO: verify that this assignment is correct.
3100     PPCGProg->any_to_outer = nullptr;
3101     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
3102     PPCGProg->stmts = getStatements();
3103 
3104     // Only consider arrays that have a non-empty extent.
3105     // Otherwise, this will cause us to consider the following kinds of
3106     // empty arrays:
3107     //     1. Invariant loads that are represented by SAI objects.
3108     //     2. Arrays with statically known zero size.
3109     auto ValidSAIsRange =
3110         make_filter_range(S->arrays(), [this](ScopArrayInfo *SAI) -> bool {
3111           return !getExtent(SAI).is_empty();
3112         });
3113     SmallVector<ScopArrayInfo *, 4> ValidSAIs(ValidSAIsRange.begin(),
3114                                               ValidSAIsRange.end());
3115 
3116     PPCGProg->n_array =
3117         ValidSAIs.size(); // std::distance(S->array_begin(), S->array_end());
3118     PPCGProg->array = isl_calloc_array(
3119         S->getIslCtx().get(), struct gpu_array_info, PPCGProg->n_array);
3120 
3121     createArrays(PPCGProg, ValidSAIs);
3122 
3123     PPCGProg->array_order = nullptr;
3124     collect_order_dependences(PPCGProg);
3125 
3126     PPCGProg->may_persist = compute_may_persist(PPCGProg);
3127     return PPCGProg;
3128   }
3129 
3130   struct PrintGPUUserData {
3131     struct cuda_info *CudaInfo;
3132     struct gpu_prog *PPCGProg;
3133     std::vector<ppcg_kernel *> Kernels;
3134   };
3135 
3136   /// Print a user statement node in the host code.
3137   ///
3138   /// We use ppcg's printing facilities to print the actual statement and
3139   /// additionally build up a list of all kernels that are encountered in the
3140   /// host ast.
3141   ///
3142   /// @param P The printer to print to
3143   /// @param Options The printing options to use
3144   /// @param Node The node to print
3145   /// @param User A user pointer to carry additional data. This pointer is
3146   ///             expected to be of type PrintGPUUserData.
3147   ///
3148   /// @returns A printer to which the output has been printed.
3149   static __isl_give isl_printer *
3150   printHostUser(__isl_take isl_printer *P,
3151                 __isl_take isl_ast_print_options *Options,
3152                 __isl_take isl_ast_node *Node, void *User) {
3153     auto Data = (struct PrintGPUUserData *)User;
3154     auto Id = isl_ast_node_get_annotation(Node);
3155 
3156     if (Id) {
3157       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
3158 
3159       // If this is a user statement, format it ourselves as ppcg would
3160       // otherwise try to call pet functionality that is not available in
3161       // Polly.
3162       if (IsUser) {
3163         P = isl_printer_start_line(P);
3164         P = isl_printer_print_ast_node(P, Node);
3165         P = isl_printer_end_line(P);
3166         isl_id_free(Id);
3167         isl_ast_print_options_free(Options);
3168         return P;
3169       }
3170 
3171       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
3172       isl_id_free(Id);
3173       Data->Kernels.push_back(Kernel);
3174     }
3175 
3176     return print_host_user(P, Options, Node, User);
3177   }
3178 
3179   /// Print C code corresponding to the control flow in @p Kernel.
3180   ///
3181   /// @param Kernel The kernel to print
3182   void printKernel(ppcg_kernel *Kernel) {
3183     auto *P = isl_printer_to_str(S->getIslCtx().get());
3184     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
3185     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
3186     P = isl_ast_node_print(Kernel->tree, P, Options);
3187     char *String = isl_printer_get_str(P);
3188     outs() << String << "\n";
3189     free(String);
3190     isl_printer_free(P);
3191   }
3192 
3193   /// Print C code corresponding to the GPU code described by @p Tree.
3194   ///
3195   /// @param Tree An AST describing GPU code
3196   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
3197   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
3198     auto *P = isl_printer_to_str(S->getIslCtx().get());
3199     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
3200 
3201     PrintGPUUserData Data;
3202     Data.PPCGProg = PPCGProg;
3203 
3204     auto *Options = isl_ast_print_options_alloc(S->getIslCtx().get());
3205     Options =
3206         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
3207     P = isl_ast_node_print(Tree, P, Options);
3208     char *String = isl_printer_get_str(P);
3209     outs() << "# host\n";
3210     outs() << String << "\n";
3211     free(String);
3212     isl_printer_free(P);
3213 
3214     for (auto Kernel : Data.Kernels) {
3215       outs() << "# kernel" << Kernel->id << "\n";
3216       printKernel(Kernel);
3217     }
3218   }
3219 
3220   // Generate a GPU program using PPCG.
3221   //
3222   // GPU mapping consists of multiple steps:
3223   //
3224   //  1) Compute new schedule for the program.
3225   //  2) Map schedule to GPU (TODO)
3226   //  3) Generate code for new schedule (TODO)
3227   //
3228   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
3229   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
3230   // strategy directly from this pass.
3231   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
3232 
3233     auto PPCGGen = isl_calloc_type(S->getIslCtx().get(), struct gpu_gen);
3234 
3235     PPCGGen->ctx = S->getIslCtx().get();
3236     PPCGGen->options = PPCGScop->options;
3237     PPCGGen->print = nullptr;
3238     PPCGGen->print_user = nullptr;
3239     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
3240     PPCGGen->prog = PPCGProg;
3241     PPCGGen->tree = nullptr;
3242     PPCGGen->types.n = 0;
3243     PPCGGen->types.name = nullptr;
3244     PPCGGen->sizes = nullptr;
3245     PPCGGen->used_sizes = nullptr;
3246     PPCGGen->kernel_id = 0;
3247 
3248     // Set scheduling strategy to same strategy PPCG is using.
3249     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
3250     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
3251     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
3252 
3253     isl_schedule *Schedule = get_schedule(PPCGGen);
3254 
3255     int has_permutable = has_any_permutable_node(Schedule);
3256 
3257     Schedule =
3258         isl_schedule_align_params(Schedule, S->getFullParamSpace().release());
3259 
3260     if (!has_permutable || has_permutable < 0) {
3261       Schedule = isl_schedule_free(Schedule);
3262       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3263                         << " does not have permutable bands. Bailing out\n";);
3264     } else {
3265       const bool CreateTransferToFromDevice = !PollyManagedMemory;
3266       Schedule = map_to_device(PPCGGen, Schedule, CreateTransferToFromDevice);
3267       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
3268     }
3269 
3270     if (DumpSchedule) {
3271       isl_printer *P = isl_printer_to_str(S->getIslCtx().get());
3272       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
3273       P = isl_printer_print_str(P, "Schedule\n");
3274       P = isl_printer_print_str(P, "========\n");
3275       if (Schedule)
3276         P = isl_printer_print_schedule(P, Schedule);
3277       else
3278         P = isl_printer_print_str(P, "No schedule found\n");
3279 
3280       outs() << isl_printer_get_str(P) << "\n";
3281       isl_printer_free(P);
3282     }
3283 
3284     if (DumpCode) {
3285       outs() << "Code\n";
3286       outs() << "====\n";
3287       if (PPCGGen->tree)
3288         printGPUTree(PPCGGen->tree, PPCGProg);
3289       else
3290         outs() << "No code generated\n";
3291     }
3292 
3293     isl_schedule_free(Schedule);
3294 
3295     return PPCGGen;
3296   }
3297 
3298   /// Free gpu_gen structure.
3299   ///
3300   /// @param PPCGGen The ppcg_gen object to free.
3301   void freePPCGGen(gpu_gen *PPCGGen) {
3302     isl_ast_node_free(PPCGGen->tree);
3303     isl_union_map_free(PPCGGen->sizes);
3304     isl_union_map_free(PPCGGen->used_sizes);
3305     free(PPCGGen);
3306   }
3307 
3308   /// Free the options in the ppcg scop structure.
3309   ///
3310   /// ppcg is not freeing these options for us. To avoid leaks we do this
3311   /// ourselves.
3312   ///
3313   /// @param PPCGScop The scop referencing the options to free.
3314   void freeOptions(ppcg_scop *PPCGScop) {
3315     free(PPCGScop->options->debug);
3316     PPCGScop->options->debug = nullptr;
3317     free(PPCGScop->options);
3318     PPCGScop->options = nullptr;
3319   }
3320 
3321   /// Approximate the number of points in the set.
3322   ///
3323   /// This function returns an ast expression that overapproximates the number
3324   /// of points in an isl set through the rectangular hull surrounding this set.
3325   ///
3326   /// @param Set   The set to count.
3327   /// @param Build The isl ast build object to use for creating the ast
3328   ///              expression.
3329   ///
3330   /// @returns An approximation of the number of points in the set.
3331   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
3332                                              __isl_keep isl_ast_build *Build) {
3333 
3334     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
3335     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
3336 
3337     isl_space *Space = isl_set_get_space(Set);
3338     Space = isl_space_params(Space);
3339     auto *Univ = isl_set_universe(Space);
3340     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
3341 
3342     for (long i = 0, n = isl_set_dim(Set, isl_dim_set); i < n; i++) {
3343       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
3344       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
3345       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
3346       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
3347       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
3348       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
3349     }
3350 
3351     isl_set_free(Set);
3352     isl_pw_aff_free(OneAff);
3353 
3354     return Expr;
3355   }
3356 
3357   /// Approximate a number of dynamic instructions executed by a given
3358   /// statement.
3359   ///
3360   /// @param Stmt  The statement for which to compute the number of dynamic
3361   ///              instructions.
3362   /// @param Build The isl ast build object to use for creating the ast
3363   ///              expression.
3364   /// @returns An approximation of the number of dynamic instructions executed
3365   ///          by @p Stmt.
3366   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
3367                                              __isl_keep isl_ast_build *Build) {
3368     auto Iterations = approxPointsInSet(Stmt.getDomain().release(), Build);
3369 
3370     long InstCount = 0;
3371 
3372     if (Stmt.isBlockStmt()) {
3373       auto *BB = Stmt.getBasicBlock();
3374       InstCount = std::distance(BB->begin(), BB->end());
3375     } else {
3376       auto *R = Stmt.getRegion();
3377 
3378       for (auto *BB : R->blocks()) {
3379         InstCount += std::distance(BB->begin(), BB->end());
3380       }
3381     }
3382 
3383     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx().get(), InstCount);
3384     auto *InstExpr = isl_ast_expr_from_val(InstVal);
3385     return isl_ast_expr_mul(InstExpr, Iterations);
3386   }
3387 
3388   /// Approximate dynamic instructions executed in scop.
3389   ///
3390   /// @param S     The scop for which to approximate dynamic instructions.
3391   /// @param Build The isl ast build object to use for creating the ast
3392   ///              expression.
3393   /// @returns An approximation of the number of dynamic instructions executed
3394   ///          in @p S.
3395   __isl_give isl_ast_expr *
3396   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
3397     isl_ast_expr *Instructions;
3398 
3399     isl_val *Zero = isl_val_int_from_si(S.getIslCtx().get(), 0);
3400     Instructions = isl_ast_expr_from_val(Zero);
3401 
3402     for (ScopStmt &Stmt : S) {
3403       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
3404       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
3405     }
3406     return Instructions;
3407   }
3408 
3409   /// Create a check that ensures sufficient compute in scop.
3410   ///
3411   /// @param S     The scop for which to ensure sufficient compute.
3412   /// @param Build The isl ast build object to use for creating the ast
3413   ///              expression.
3414   /// @returns An expression that evaluates to TRUE in case of sufficient
3415   ///          compute and to FALSE, otherwise.
3416   __isl_give isl_ast_expr *
3417   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
3418     auto Iterations = getNumberOfIterations(S, Build);
3419     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx().get(), MinCompute);
3420     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
3421     return isl_ast_expr_ge(Iterations, MinComputeExpr);
3422   }
3423 
3424   /// Check if the basic block contains a function we cannot codegen for GPU
3425   /// kernels.
3426   ///
3427   /// If this basic block does something with a `Function` other than calling
3428   /// a function that we support in a kernel, return true.
3429   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB,
3430                                             bool AllowCUDALibDevice) {
3431     for (const Instruction &Inst : *BB) {
3432       const CallInst *Call = dyn_cast<CallInst>(&Inst);
3433       if (Call && isValidFunctionInKernel(Call->getCalledFunction(),
3434                                           AllowCUDALibDevice))
3435         continue;
3436 
3437       for (Value *Op : Inst.operands())
3438         // Look for (<func-type>*) among operands of Inst
3439         if (auto PtrTy = dyn_cast<PointerType>(Op->getType())) {
3440           if (isa<FunctionType>(PtrTy->getElementType())) {
3441             LLVM_DEBUG(dbgs()
3442                        << Inst << " has illegal use of function in kernel.\n");
3443             return true;
3444           }
3445         }
3446     }
3447     return false;
3448   }
3449 
3450   /// Return whether the Scop S uses functions in a way that we do not support.
3451   bool containsInvalidKernelFunction(const Scop &S, bool AllowCUDALibDevice) {
3452     for (auto &Stmt : S) {
3453       if (Stmt.isBlockStmt()) {
3454         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock(),
3455                                                  AllowCUDALibDevice))
3456           return true;
3457       } else {
3458         assert(Stmt.isRegionStmt() &&
3459                "Stmt was neither block nor region statement");
3460         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
3461           if (containsInvalidKernelFunctionInBlock(BB, AllowCUDALibDevice))
3462             return true;
3463       }
3464     }
3465     return false;
3466   }
3467 
3468   /// Generate code for a given GPU AST described by @p Root.
3469   ///
3470   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
3471   /// @param Prog The GPU Program to generate code for.
3472   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
3473     ScopAnnotator Annotator;
3474     Annotator.buildAliasScopes(*S);
3475 
3476     Region *R = &S->getRegion();
3477 
3478     simplifyRegion(R, DT, LI, RI);
3479 
3480     BasicBlock *EnteringBB = R->getEnteringBlock();
3481 
3482     PollyIRBuilder Builder(EnteringBB->getContext(), ConstantFolder(),
3483                            IRInserter(Annotator));
3484     Builder.SetInsertPoint(EnteringBB->getTerminator());
3485 
3486     // Only build the run-time condition and parameters _after_ having
3487     // introduced the conditional branch. This is important as the conditional
3488     // branch will guard the original scop from new induction variables that
3489     // the SCEVExpander may introduce while code generating the parameters and
3490     // which may introduce scalar dependences that prevent us from correctly
3491     // code generating this scop.
3492     BBPair StartExitBlocks;
3493     BranchInst *CondBr = nullptr;
3494     std::tie(StartExitBlocks, CondBr) =
3495         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3496     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
3497 
3498     assert(CondBr && "CondBr not initialized by executeScopConditionally");
3499 
3500     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
3501                                StartBlock, Prog, Runtime, Architecture);
3502 
3503     // TODO: Handle LICM
3504     auto SplitBlock = StartBlock->getSinglePredecessor();
3505     Builder.SetInsertPoint(SplitBlock->getTerminator());
3506 
3507     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx().get());
3508     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
3509     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
3510     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3511     isl_ast_build_free(Build);
3512 
3513     // preload invariant loads. Note: This should happen before the RTC
3514     // because the RTC may depend on values that are invariant load hoisted.
3515     if (!NodeBuilder.preloadInvariantLoads()) {
3516       // Patch the introduced branch condition to ensure that we always execute
3517       // the original SCoP.
3518       auto *FalseI1 = Builder.getFalse();
3519       auto *SplitBBTerm = Builder.GetInsertBlock()->getTerminator();
3520       SplitBBTerm->setOperand(0, FalseI1);
3521 
3522       LLVM_DEBUG(dbgs() << "preloading invariant loads failed in function: " +
3523                                S->getFunction().getName() +
3524                                " | Scop Region: " + S->getNameStr());
3525       // adjust the dominator tree accordingly.
3526       auto *ExitingBlock = StartBlock->getUniqueSuccessor();
3527       assert(ExitingBlock);
3528       auto *MergeBlock = ExitingBlock->getUniqueSuccessor();
3529       assert(MergeBlock);
3530       polly::markBlockUnreachable(*StartBlock, Builder);
3531       polly::markBlockUnreachable(*ExitingBlock, Builder);
3532       auto *ExitingBB = S->getExitingBlock();
3533       assert(ExitingBB);
3534 
3535       DT->changeImmediateDominator(MergeBlock, ExitingBB);
3536       DT->eraseNode(ExitingBlock);
3537       isl_ast_expr_free(Condition);
3538       isl_ast_node_free(Root);
3539     } else {
3540 
3541       if (polly::PerfMonitoring) {
3542         PerfMonitor P(*S, EnteringBB->getParent()->getParent());
3543         P.initialize();
3544         P.insertRegionStart(SplitBlock->getTerminator());
3545 
3546         // TODO: actually think if this is the correct exiting block to place
3547         // the `end` performance marker. Invariant load hoisting changes
3548         // the CFG in a way that I do not precisely understand, so I
3549         // (Siddharth<[email protected]>) should come back to this and
3550         // think about which exiting block to use.
3551         auto *ExitingBlock = StartBlock->getUniqueSuccessor();
3552         assert(ExitingBlock);
3553         BasicBlock *MergeBlock = ExitingBlock->getUniqueSuccessor();
3554         P.insertRegionEnd(MergeBlock->getTerminator());
3555       }
3556 
3557       NodeBuilder.addParameters(S->getContext().release());
3558       Value *RTC = NodeBuilder.createRTC(Condition);
3559       Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3560 
3561       Builder.SetInsertPoint(&*StartBlock->begin());
3562 
3563       NodeBuilder.create(Root);
3564     }
3565 
3566     /// In case a sequential kernel has more surrounding loops as any parallel
3567     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3568     /// point in running it on a GPU.
3569     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
3570       CondBr->setOperand(0, Builder.getFalse());
3571 
3572     if (!NodeBuilder.BuildSuccessful)
3573       CondBr->setOperand(0, Builder.getFalse());
3574   }
3575 
3576   bool runOnScop(Scop &CurrentScop) override {
3577     S = &CurrentScop;
3578     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3579     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3580     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3581     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
3582     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3583 
3584     LLVM_DEBUG(dbgs() << "PPCGCodeGen running on : " << getUniqueScopName(S)
3585                       << " | loop depth: " << S->getMaxLoopDepth() << "\n");
3586 
3587     // We currently do not support functions other than intrinsics inside
3588     // kernels, as code generation will need to offload function calls to the
3589     // kernel. This may lead to a kernel trying to call a function on the host.
3590     // This also allows us to prevent codegen from trying to take the
3591     // address of an intrinsic function to send to the kernel.
3592     if (containsInvalidKernelFunction(CurrentScop,
3593                                       Architecture == GPUArch::NVPTX64)) {
3594       LLVM_DEBUG(
3595           dbgs() << getUniqueScopName(S)
3596                  << " contains function which cannot be materialised in a GPU "
3597                     "kernel. Bailing out.\n";);
3598       return false;
3599     }
3600 
3601     auto PPCGScop = createPPCGScop();
3602     auto PPCGProg = createPPCGProg(PPCGScop);
3603     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
3604 
3605     if (PPCGGen->tree) {
3606       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
3607       CurrentScop.markAsToBeSkipped();
3608     } else {
3609       LLVM_DEBUG(dbgs() << getUniqueScopName(S)
3610                         << " has empty PPCGGen->tree. Bailing out.\n");
3611     }
3612 
3613     freeOptions(PPCGScop);
3614     freePPCGGen(PPCGGen);
3615     gpu_prog_free(PPCGProg);
3616     ppcg_scop_free(PPCGScop);
3617 
3618     return true;
3619   }
3620 
3621   void printScop(raw_ostream &, Scop &) const override {}
3622 
3623   void getAnalysisUsage(AnalysisUsage &AU) const override {
3624     ScopPass::getAnalysisUsage(AU);
3625 
3626     AU.addRequired<DominatorTreeWrapperPass>();
3627     AU.addRequired<RegionInfoPass>();
3628     AU.addRequired<ScalarEvolutionWrapperPass>();
3629     AU.addRequired<ScopDetectionWrapperPass>();
3630     AU.addRequired<ScopInfoRegionPass>();
3631     AU.addRequired<LoopInfoWrapperPass>();
3632 
3633     // FIXME: We do not yet add regions for the newly generated code to the
3634     //        region tree.
3635   }
3636 };
3637 } // namespace
3638 
3639 char PPCGCodeGeneration::ID = 1;
3640 
3641 Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
3642   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
3643   generator->Runtime = Runtime;
3644   generator->Architecture = Arch;
3645   return generator;
3646 }
3647 
3648 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
3649                       "Polly - Apply PPCG translation to SCOP", false, false)
3650 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
3651 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
3652 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
3653 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
3654 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
3655 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
3656 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
3657                     "Polly - Apply PPCG translation to SCOP", false, false)
3658