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