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