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