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