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.*", "llvm.fabs", and
1308   // "llvm.copysign".
1309   const StringRef Name = F->getName();
1310   return F->isIntrinsic() &&
1311          (Name.startswith("llvm.sqrt") || Name.startswith("llvm.fabs") ||
1312           Name.startswith("llvm.copysign"));
1313 }
1314 
1315 /// Do not take `Function` as a subtree value.
1316 ///
1317 /// We try to take the reference of all subtree values and pass them along
1318 /// to the kernel from the host. Taking an address of any function and
1319 /// trying to pass along is nonsensical. Only allow `Value`s that are not
1320 /// `Function`s.
1321 static bool isValidSubtreeValue(llvm::Value *V) { return !isa<Function>(V); }
1322 
1323 /// Return `Function`s from `RawSubtreeValues`.
1324 static SetVector<Function *>
1325 getFunctionsFromRawSubtreeValues(SetVector<Value *> RawSubtreeValues) {
1326   SetVector<Function *> SubtreeFunctions;
1327   for (Value *It : RawSubtreeValues) {
1328     Function *F = dyn_cast<Function>(It);
1329     if (F) {
1330       assert(isValidFunctionInKernel(F) && "Code should have bailed out by "
1331                                            "this point if an invalid function "
1332                                            "were present in a kernel.");
1333       SubtreeFunctions.insert(F);
1334     }
1335   }
1336   return SubtreeFunctions;
1337 }
1338 
1339 std::pair<SetVector<Value *>, SetVector<Function *>>
1340 GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
1341   SetVector<Value *> SubtreeValues;
1342   SetVector<const SCEV *> SCEVs;
1343   SetVector<const Loop *> Loops;
1344   SubtreeReferences References = {
1345       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
1346 
1347   for (const auto &I : IDToValue)
1348     SubtreeValues.insert(I.second);
1349 
1350   isl_ast_node_foreach_descendant_top_down(
1351       Kernel->tree, collectReferencesInGPUStmt, &References);
1352 
1353   for (const SCEV *Expr : SCEVs)
1354     findValues(Expr, SE, SubtreeValues);
1355 
1356   for (auto &SAI : S.arrays())
1357     SubtreeValues.remove(SAI->getBasePtr());
1358 
1359   isl_space *Space = S.getParamSpace();
1360   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
1361     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
1362     assert(IDToValue.count(Id));
1363     Value *Val = IDToValue[Id];
1364     SubtreeValues.remove(Val);
1365     isl_id_free(Id);
1366   }
1367   isl_space_free(Space);
1368 
1369   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
1370     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1371     assert(IDToValue.count(Id));
1372     Value *Val = IDToValue[Id];
1373     SubtreeValues.remove(Val);
1374     isl_id_free(Id);
1375   }
1376 
1377   // Note: { ValidSubtreeValues, ValidSubtreeFunctions } partitions
1378   // SubtreeValues. This is important, because we should not lose any
1379   // SubtreeValues in the process of constructing the
1380   // "ValidSubtree{Values, Functions} sets. Nor should the set
1381   // ValidSubtree{Values, Functions} have any common element.
1382   auto ValidSubtreeValuesIt =
1383       make_filter_range(SubtreeValues, isValidSubtreeValue);
1384   SetVector<Value *> ValidSubtreeValues(ValidSubtreeValuesIt.begin(),
1385                                         ValidSubtreeValuesIt.end());
1386   SetVector<Function *> ValidSubtreeFunctions(
1387       getFunctionsFromRawSubtreeValues(SubtreeValues));
1388 
1389   // @see IslNodeBuilder::getReferencesInSubtree
1390   SetVector<Value *> ReplacedValues;
1391   for (Value *V : ValidSubtreeValues) {
1392     auto It = ValueMap.find(V);
1393     if (It == ValueMap.end())
1394       ReplacedValues.insert(V);
1395     else
1396       ReplacedValues.insert(It->second);
1397   }
1398   return std::make_pair(ReplacedValues, ValidSubtreeFunctions);
1399 }
1400 
1401 void GPUNodeBuilder::clearDominators(Function *F) {
1402   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
1403   std::vector<BasicBlock *> Nodes;
1404   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
1405     Nodes.push_back(I->getBlock());
1406 
1407   for (BasicBlock *BB : Nodes)
1408     DT.eraseNode(BB);
1409 }
1410 
1411 void GPUNodeBuilder::clearScalarEvolution(Function *F) {
1412   for (BasicBlock &BB : *F) {
1413     Loop *L = LI.getLoopFor(&BB);
1414     if (L)
1415       SE.forgetLoop(L);
1416   }
1417 }
1418 
1419 void GPUNodeBuilder::clearLoops(Function *F) {
1420   for (BasicBlock &BB : *F) {
1421     Loop *L = LI.getLoopFor(&BB);
1422     if (L)
1423       SE.forgetLoop(L);
1424     LI.removeBlock(&BB);
1425   }
1426 }
1427 
1428 std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
1429   std::vector<Value *> Sizes;
1430   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
1431 
1432   for (long i = 0; i < Kernel->n_grid; i++) {
1433     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
1434     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
1435     Value *Res = ExprBuilder.create(GridSize);
1436     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
1437     Sizes.push_back(Res);
1438   }
1439   isl_ast_build_free(Context);
1440 
1441   for (long i = Kernel->n_grid; i < 3; i++)
1442     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
1443 
1444   return std::make_tuple(Sizes[0], Sizes[1]);
1445 }
1446 
1447 std::tuple<Value *, Value *, Value *>
1448 GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
1449   std::vector<Value *> Sizes;
1450 
1451   for (long i = 0; i < Kernel->n_block; i++) {
1452     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
1453     Sizes.push_back(Res);
1454   }
1455 
1456   for (long i = Kernel->n_block; i < 3; i++)
1457     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
1458 
1459   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
1460 }
1461 
1462 void GPUNodeBuilder::insertStoreParameter(Instruction *Parameters,
1463                                           Instruction *Param, int Index) {
1464   Value *Slot = Builder.CreateGEP(
1465       Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1466   Value *ParamTyped = Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1467   Builder.CreateStore(ParamTyped, Slot);
1468 }
1469 
1470 Value *
1471 GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
1472                                        SetVector<Value *> SubtreeValues) {
1473   const int NumArgs = F->arg_size();
1474   std::vector<int> ArgSizes(NumArgs);
1475 
1476   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(), 2 * NumArgs);
1477 
1478   BasicBlock *EntryBlock =
1479       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
1480   auto AddressSpace = F->getParent()->getDataLayout().getAllocaAddrSpace();
1481   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
1482   Instruction *Parameters = new AllocaInst(
1483       ArrayTy, AddressSpace, Launch + "_params", EntryBlock->getTerminator());
1484 
1485   int Index = 0;
1486   for (long i = 0; i < Prog->n_array; i++) {
1487     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1488       continue;
1489 
1490     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1491     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1492 
1493     ArgSizes[Index] = SAI->getElemSizeInBytes();
1494 
1495     Value *DevArray = nullptr;
1496     if (ManagedMemory) {
1497       DevArray = getOrCreateManagedDeviceArray(
1498           &Prog->array[i], const_cast<ScopArrayInfo *>(SAI));
1499     } else {
1500       DevArray = DeviceAllocations[const_cast<ScopArrayInfo *>(SAI)];
1501       DevArray = createCallGetDevicePtr(DevArray);
1502     }
1503     assert(DevArray != nullptr && "Array to be offloaded to device not "
1504                                   "initialized");
1505     Value *Offset = getArrayOffset(&Prog->array[i]);
1506 
1507     if (Offset) {
1508       DevArray = Builder.CreatePointerCast(
1509           DevArray, SAI->getElementType()->getPointerTo());
1510       DevArray = Builder.CreateGEP(DevArray, Builder.CreateNeg(Offset));
1511       DevArray = Builder.CreatePointerCast(DevArray, Builder.getInt8PtrTy());
1512     }
1513     Value *Slot = Builder.CreateGEP(
1514         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
1515 
1516     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1517       Value *ValPtr = nullptr;
1518       if (ManagedMemory)
1519         ValPtr = DevArray;
1520       else
1521         ValPtr = BlockGen.getOrCreateAlloca(SAI);
1522 
1523       assert(ValPtr != nullptr && "ValPtr that should point to a valid object"
1524                                   " to be stored into Parameters");
1525       Value *ValPtrCast =
1526           Builder.CreatePointerCast(ValPtr, Builder.getInt8PtrTy());
1527       Builder.CreateStore(ValPtrCast, Slot);
1528     } else {
1529       Instruction *Param =
1530           new AllocaInst(Builder.getInt8PtrTy(), AddressSpace,
1531                          Launch + "_param_" + std::to_string(Index),
1532                          EntryBlock->getTerminator());
1533       Builder.CreateStore(DevArray, Param);
1534       Value *ParamTyped =
1535           Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
1536       Builder.CreateStore(ParamTyped, Slot);
1537     }
1538     Index++;
1539   }
1540 
1541   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1542 
1543   for (long i = 0; i < NumHostIters; i++) {
1544     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1545     Value *Val = IDToValue[Id];
1546     isl_id_free(Id);
1547 
1548     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1549 
1550     Instruction *Param =
1551         new AllocaInst(Val->getType(), AddressSpace,
1552                        Launch + "_param_" + std::to_string(Index),
1553                        EntryBlock->getTerminator());
1554     Builder.CreateStore(Val, Param);
1555     insertStoreParameter(Parameters, Param, Index);
1556     Index++;
1557   }
1558 
1559   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1560 
1561   for (long i = 0; i < NumVars; i++) {
1562     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1563     Value *Val = IDToValue[Id];
1564     if (ValueMap.count(Val))
1565       Val = ValueMap[Val];
1566     isl_id_free(Id);
1567 
1568     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1569 
1570     Instruction *Param =
1571         new AllocaInst(Val->getType(), AddressSpace,
1572                        Launch + "_param_" + std::to_string(Index),
1573                        EntryBlock->getTerminator());
1574     Builder.CreateStore(Val, Param);
1575     insertStoreParameter(Parameters, Param, Index);
1576     Index++;
1577   }
1578 
1579   for (auto Val : SubtreeValues) {
1580     ArgSizes[Index] = computeSizeInBytes(Val->getType());
1581 
1582     Instruction *Param =
1583         new AllocaInst(Val->getType(), AddressSpace,
1584                        Launch + "_param_" + std::to_string(Index),
1585                        EntryBlock->getTerminator());
1586     Builder.CreateStore(Val, Param);
1587     insertStoreParameter(Parameters, Param, Index);
1588     Index++;
1589   }
1590 
1591   for (int i = 0; i < NumArgs; i++) {
1592     Value *Val = ConstantInt::get(Builder.getInt32Ty(), ArgSizes[i]);
1593     Instruction *Param =
1594         new AllocaInst(Builder.getInt32Ty(), AddressSpace,
1595                        Launch + "_param_size_" + std::to_string(i),
1596                        EntryBlock->getTerminator());
1597     Builder.CreateStore(Val, Param);
1598     insertStoreParameter(Parameters, Param, Index);
1599     Index++;
1600   }
1601 
1602   auto Location = EntryBlock->getTerminator();
1603   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
1604                          Launch + "_params_i8ptr", Location);
1605 }
1606 
1607 void GPUNodeBuilder::setupKernelSubtreeFunctions(
1608     SetVector<Function *> SubtreeFunctions) {
1609   for (auto Fn : SubtreeFunctions) {
1610     const std::string ClonedFnName = Fn->getName();
1611     Function *Clone = GPUModule->getFunction(ClonedFnName);
1612     if (!Clone)
1613       Clone =
1614           Function::Create(Fn->getFunctionType(), GlobalValue::ExternalLinkage,
1615                            ClonedFnName, GPUModule.get());
1616     assert(Clone && "Expected cloned function to be initialized.");
1617     assert(ValueMap.find(Fn) == ValueMap.end() &&
1618            "Fn already present in ValueMap");
1619     ValueMap[Fn] = Clone;
1620   }
1621 }
1622 void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
1623   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
1624   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
1625   isl_id_free(Id);
1626   isl_ast_node_free(KernelStmt);
1627 
1628   if (Kernel->n_grid > 1)
1629     DeepestParallel =
1630         std::max(DeepestParallel, isl_space_dim(Kernel->space, isl_dim_set));
1631   else
1632     DeepestSequential =
1633         std::max(DeepestSequential, isl_space_dim(Kernel->space, isl_dim_set));
1634 
1635   Value *BlockDimX, *BlockDimY, *BlockDimZ;
1636   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
1637 
1638   SetVector<Value *> SubtreeValues;
1639   SetVector<Function *> SubtreeFunctions;
1640   std::tie(SubtreeValues, SubtreeFunctions) = getReferencesInKernel(Kernel);
1641 
1642   assert(Kernel->tree && "Device AST of kernel node is empty");
1643 
1644   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1645   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1646   ValueMapT HostValueMap = ValueMap;
1647   BlockGenerator::AllocaMapTy HostScalarMap = ScalarMap;
1648   ScalarMap.clear();
1649 
1650   SetVector<const Loop *> Loops;
1651 
1652   // Create for all loops we depend on values that contain the current loop
1653   // iteration. These values are necessary to generate code for SCEVs that
1654   // depend on such loops. As a result we need to pass them to the subfunction.
1655   for (const Loop *L : Loops) {
1656     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1657                                             SE.getUnknown(Builder.getInt64(1)),
1658                                             L, SCEV::FlagAnyWrap);
1659     Value *V = generateSCEV(OuterLIV);
1660     OutsideLoopIterations[L] = SE.getUnknown(V);
1661     SubtreeValues.insert(V);
1662   }
1663 
1664   createKernelFunction(Kernel, SubtreeValues, SubtreeFunctions);
1665   setupKernelSubtreeFunctions(SubtreeFunctions);
1666 
1667   create(isl_ast_node_copy(Kernel->tree));
1668 
1669   finalizeKernelArguments(Kernel);
1670   Function *F = Builder.GetInsertBlock()->getParent();
1671   addCUDAAnnotations(F->getParent(), BlockDimX, BlockDimY, BlockDimZ);
1672   clearDominators(F);
1673   clearScalarEvolution(F);
1674   clearLoops(F);
1675 
1676   IDToValue = HostIDs;
1677 
1678   ValueMap = std::move(HostValueMap);
1679   ScalarMap = std::move(HostScalarMap);
1680   EscapeMap.clear();
1681   IDToSAI.clear();
1682   Annotator.resetAlternativeAliasBases();
1683   for (auto &BasePtr : LocalArrays)
1684     S.invalidateScopArrayInfo(BasePtr, MemoryKind::Array);
1685   LocalArrays.clear();
1686 
1687   std::string ASMString = finalizeKernelFunction();
1688   Builder.SetInsertPoint(&HostInsertPoint);
1689   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
1690 
1691   std::string Name = getKernelFuncName(Kernel->id);
1692   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
1693   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
1694   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
1695 
1696   Value *GridDimX, *GridDimY;
1697   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
1698 
1699   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
1700                          BlockDimZ, Parameters);
1701   createCallFreeKernel(GPUKernel);
1702 
1703   for (auto Id : KernelIds)
1704     isl_id_free(Id);
1705 
1706   KernelIds.clear();
1707 }
1708 
1709 /// Compute the DataLayout string for the NVPTX backend.
1710 ///
1711 /// @param is64Bit Are we looking for a 64 bit architecture?
1712 static std::string computeNVPTXDataLayout(bool is64Bit) {
1713   std::string Ret = "";
1714 
1715   if (!is64Bit) {
1716     Ret += "e-p:32:32:32-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   } else {
1720     Ret += "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:"
1721            "64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:"
1722            "64-v128:128:128-n16:32:64";
1723   }
1724 
1725   return Ret;
1726 }
1727 
1728 Function *
1729 GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1730                                          SetVector<Value *> &SubtreeValues) {
1731   std::vector<Type *> Args;
1732   std::string Identifier = getKernelFuncName(Kernel->id);
1733 
1734   for (long i = 0; i < Prog->n_array; i++) {
1735     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1736       continue;
1737 
1738     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1739       isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1740       const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
1741       Args.push_back(SAI->getElementType());
1742     } else {
1743       static const int UseGlobalMemory = 1;
1744       Args.push_back(Builder.getInt8PtrTy(UseGlobalMemory));
1745     }
1746   }
1747 
1748   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1749 
1750   for (long i = 0; i < NumHostIters; i++)
1751     Args.push_back(Builder.getInt64Ty());
1752 
1753   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1754 
1755   for (long i = 0; i < NumVars; i++) {
1756     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1757     Value *Val = IDToValue[Id];
1758     isl_id_free(Id);
1759     Args.push_back(Val->getType());
1760   }
1761 
1762   for (auto *V : SubtreeValues)
1763     Args.push_back(V->getType());
1764 
1765   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
1766   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
1767                               GPUModule.get());
1768 
1769   switch (Arch) {
1770   case GPUArch::NVPTX64:
1771     FN->setCallingConv(CallingConv::PTX_Kernel);
1772     break;
1773   }
1774 
1775   auto Arg = FN->arg_begin();
1776   for (long i = 0; i < Kernel->n_array; i++) {
1777     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1778       continue;
1779 
1780     Arg->setName(Kernel->array[i].array->name);
1781 
1782     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1783     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1784     Type *EleTy = SAI->getElementType();
1785     Value *Val = &*Arg;
1786     SmallVector<const SCEV *, 4> Sizes;
1787     isl_ast_build *Build =
1788         isl_ast_build_from_context(isl_set_copy(Prog->context));
1789     Sizes.push_back(nullptr);
1790     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1791       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1792           Build, isl_multi_pw_aff_get_pw_aff(Kernel->array[i].array->bound, j));
1793       auto V = ExprBuilder.create(DimSize);
1794       Sizes.push_back(SE.getSCEV(V));
1795     }
1796     const ScopArrayInfo *SAIRep =
1797         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, MemoryKind::Array);
1798     LocalArrays.push_back(Val);
1799 
1800     isl_ast_build_free(Build);
1801     KernelIds.push_back(Id);
1802     IDToSAI[Id] = SAIRep;
1803     Arg++;
1804   }
1805 
1806   for (long i = 0; i < NumHostIters; i++) {
1807     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1808     Arg->setName(isl_id_get_name(Id));
1809     IDToValue[Id] = &*Arg;
1810     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1811     Arg++;
1812   }
1813 
1814   for (long i = 0; i < NumVars; i++) {
1815     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1816     Arg->setName(isl_id_get_name(Id));
1817     Value *Val = IDToValue[Id];
1818     ValueMap[Val] = &*Arg;
1819     IDToValue[Id] = &*Arg;
1820     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1821     Arg++;
1822   }
1823 
1824   for (auto *V : SubtreeValues) {
1825     Arg->setName(V->getName());
1826     ValueMap[V] = &*Arg;
1827     Arg++;
1828   }
1829 
1830   return FN;
1831 }
1832 
1833 void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1834   Intrinsic::ID IntrinsicsBID[2];
1835   Intrinsic::ID IntrinsicsTID[3];
1836 
1837   switch (Arch) {
1838   case GPUArch::NVPTX64:
1839     IntrinsicsBID[0] = Intrinsic::nvvm_read_ptx_sreg_ctaid_x;
1840     IntrinsicsBID[1] = Intrinsic::nvvm_read_ptx_sreg_ctaid_y;
1841 
1842     IntrinsicsTID[0] = Intrinsic::nvvm_read_ptx_sreg_tid_x;
1843     IntrinsicsTID[1] = Intrinsic::nvvm_read_ptx_sreg_tid_y;
1844     IntrinsicsTID[2] = Intrinsic::nvvm_read_ptx_sreg_tid_z;
1845     break;
1846   }
1847 
1848   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1849     std::string Name = isl_id_get_name(Id);
1850     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1851     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1852     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1853     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1854     IDToValue[Id] = Val;
1855     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1856   };
1857 
1858   for (int i = 0; i < Kernel->n_grid; ++i) {
1859     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1860     addId(Id, IntrinsicsBID[i]);
1861   }
1862 
1863   for (int i = 0; i < Kernel->n_block; ++i) {
1864     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1865     addId(Id, IntrinsicsTID[i]);
1866   }
1867 }
1868 
1869 void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
1870   auto Arg = FN->arg_begin();
1871   for (long i = 0; i < Kernel->n_array; i++) {
1872     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1873       continue;
1874 
1875     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1876     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1877     isl_id_free(Id);
1878 
1879     if (SAI->getNumberOfDimensions() > 0) {
1880       Arg++;
1881       continue;
1882     }
1883 
1884     Value *Val = &*Arg;
1885 
1886     if (!gpu_array_is_read_only_scalar(&Prog->array[i])) {
1887       Type *TypePtr = SAI->getElementType()->getPointerTo();
1888       Value *TypedArgPtr = Builder.CreatePointerCast(Val, TypePtr);
1889       Val = Builder.CreateLoad(TypedArgPtr);
1890     }
1891 
1892     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
1893     Builder.CreateStore(Val, Alloca);
1894 
1895     Arg++;
1896   }
1897 }
1898 
1899 void GPUNodeBuilder::finalizeKernelArguments(ppcg_kernel *Kernel) {
1900   auto *FN = Builder.GetInsertBlock()->getParent();
1901   auto Arg = FN->arg_begin();
1902 
1903   bool StoredScalar = false;
1904   for (long i = 0; i < Kernel->n_array; i++) {
1905     if (!ppcg_kernel_requires_array_argument(Kernel, i))
1906       continue;
1907 
1908     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1909     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1910     isl_id_free(Id);
1911 
1912     if (SAI->getNumberOfDimensions() > 0) {
1913       Arg++;
1914       continue;
1915     }
1916 
1917     if (gpu_array_is_read_only_scalar(&Prog->array[i])) {
1918       Arg++;
1919       continue;
1920     }
1921 
1922     Value *Alloca = BlockGen.getOrCreateAlloca(SAI);
1923     Value *ArgPtr = &*Arg;
1924     Type *TypePtr = SAI->getElementType()->getPointerTo();
1925     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
1926     Value *Val = Builder.CreateLoad(Alloca);
1927     Builder.CreateStore(Val, TypedArgPtr);
1928     StoredScalar = true;
1929 
1930     Arg++;
1931   }
1932 
1933   if (StoredScalar)
1934     /// In case more than one thread contains scalar stores, the generated
1935     /// code might be incorrect, if we only store at the end of the kernel.
1936     /// To support this case we need to store these scalars back at each
1937     /// memory store or at least before each kernel barrier.
1938     if (Kernel->n_block != 0 || Kernel->n_grid != 0)
1939       BuildSuccessful = 0;
1940 }
1941 
1942 void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1943   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1944 
1945   for (int i = 0; i < Kernel->n_var; ++i) {
1946     struct ppcg_kernel_var &Var = Kernel->var[i];
1947     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1948     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1949 
1950     Type *ArrayTy = EleTy;
1951     SmallVector<const SCEV *, 4> Sizes;
1952 
1953     Sizes.push_back(nullptr);
1954     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1955       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1956       long Bound = isl_val_get_num_si(Val);
1957       isl_val_free(Val);
1958       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1959     }
1960 
1961     for (int j = Var.array->n_index - 1; j >= 0; --j) {
1962       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1963       long Bound = isl_val_get_num_si(Val);
1964       isl_val_free(Val);
1965       ArrayTy = ArrayType::get(ArrayTy, Bound);
1966     }
1967 
1968     const ScopArrayInfo *SAI;
1969     Value *Allocation;
1970     if (Var.type == ppcg_access_shared) {
1971       auto GlobalVar = new GlobalVariable(
1972           *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name,
1973           nullptr, GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1974       GlobalVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1975       GlobalVar->setInitializer(Constant::getNullValue(ArrayTy));
1976 
1977       Allocation = GlobalVar;
1978     } else if (Var.type == ppcg_access_private) {
1979       Allocation = Builder.CreateAlloca(ArrayTy, 0, "private_array");
1980     } else {
1981       llvm_unreachable("unknown variable type");
1982     }
1983     SAI =
1984         S.getOrCreateScopArrayInfo(Allocation, EleTy, Sizes, MemoryKind::Array);
1985     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1986     IDToValue[Id] = Allocation;
1987     LocalArrays.push_back(Allocation);
1988     KernelIds.push_back(Id);
1989     IDToSAI[Id] = SAI;
1990   }
1991 }
1992 
1993 void GPUNodeBuilder::createKernelFunction(
1994     ppcg_kernel *Kernel, SetVector<Value *> &SubtreeValues,
1995     SetVector<Function *> &SubtreeFunctions) {
1996   std::string Identifier = getKernelFuncName(Kernel->id);
1997   GPUModule.reset(new Module(Identifier, Builder.getContext()));
1998 
1999   switch (Arch) {
2000   case GPUArch::NVPTX64:
2001     if (Runtime == GPURuntime::CUDA)
2002       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
2003     else if (Runtime == GPURuntime::OpenCL)
2004       GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-nvcl"));
2005     GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
2006     break;
2007   }
2008 
2009   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
2010 
2011   BasicBlock *PrevBlock = Builder.GetInsertBlock();
2012   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
2013 
2014   DT.addNewBlock(EntryBlock, PrevBlock);
2015 
2016   Builder.SetInsertPoint(EntryBlock);
2017   Builder.CreateRetVoid();
2018   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
2019 
2020   ScopDetection::markFunctionAsInvalid(FN);
2021 
2022   prepareKernelArguments(Kernel, FN);
2023   createKernelVariables(Kernel, FN);
2024   insertKernelIntrinsics(Kernel);
2025 }
2026 
2027 std::string GPUNodeBuilder::createKernelASM() {
2028   llvm::Triple GPUTriple;
2029 
2030   switch (Arch) {
2031   case GPUArch::NVPTX64:
2032     switch (Runtime) {
2033     case GPURuntime::CUDA:
2034       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-cuda"));
2035       break;
2036     case GPURuntime::OpenCL:
2037       GPUTriple = llvm::Triple(Triple::normalize("nvptx64-nvidia-nvcl"));
2038       break;
2039     }
2040     break;
2041   }
2042 
2043   std::string ErrMsg;
2044   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
2045 
2046   if (!GPUTarget) {
2047     errs() << ErrMsg << "\n";
2048     return "";
2049   }
2050 
2051   TargetOptions Options;
2052   Options.UnsafeFPMath = FastMath;
2053 
2054   std::string subtarget;
2055 
2056   switch (Arch) {
2057   case GPUArch::NVPTX64:
2058     subtarget = CudaVersion;
2059     break;
2060   }
2061 
2062   std::unique_ptr<TargetMachine> TargetM(GPUTarget->createTargetMachine(
2063       GPUTriple.getTriple(), subtarget, "", Options, Optional<Reloc::Model>()));
2064 
2065   SmallString<0> ASMString;
2066   raw_svector_ostream ASMStream(ASMString);
2067   llvm::legacy::PassManager PM;
2068 
2069   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
2070 
2071   if (TargetM->addPassesToEmitFile(
2072           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
2073     errs() << "The target does not support generation of this file type!\n";
2074     return "";
2075   }
2076 
2077   PM.run(*GPUModule);
2078 
2079   return ASMStream.str();
2080 }
2081 
2082 std::string GPUNodeBuilder::finalizeKernelFunction() {
2083 
2084   if (verifyModule(*GPUModule)) {
2085     DEBUG(dbgs() << "verifyModule failed on module:\n";
2086           GPUModule->print(dbgs(), nullptr); dbgs() << "\n";);
2087 
2088     if (FailOnVerifyModuleFailure)
2089       llvm_unreachable("VerifyModule failed.");
2090 
2091     BuildSuccessful = false;
2092     return "";
2093   }
2094 
2095   if (DumpKernelIR)
2096     outs() << *GPUModule << "\n";
2097 
2098   // Optimize module.
2099   llvm::legacy::PassManager OptPasses;
2100   PassManagerBuilder PassBuilder;
2101   PassBuilder.OptLevel = 3;
2102   PassBuilder.SizeLevel = 0;
2103   PassBuilder.populateModulePassManager(OptPasses);
2104   OptPasses.run(*GPUModule);
2105 
2106   std::string Assembly = createKernelASM();
2107 
2108   if (DumpKernelASM)
2109     outs() << Assembly << "\n";
2110 
2111   GPUModule.release();
2112   KernelIDs.clear();
2113 
2114   return Assembly;
2115 }
2116 
2117 namespace {
2118 class PPCGCodeGeneration : public ScopPass {
2119 public:
2120   static char ID;
2121 
2122   GPURuntime Runtime = GPURuntime::CUDA;
2123 
2124   GPUArch Architecture = GPUArch::NVPTX64;
2125 
2126   /// The scop that is currently processed.
2127   Scop *S;
2128 
2129   LoopInfo *LI;
2130   DominatorTree *DT;
2131   ScalarEvolution *SE;
2132   const DataLayout *DL;
2133   RegionInfo *RI;
2134 
2135   PPCGCodeGeneration() : ScopPass(ID) {}
2136 
2137   /// Construct compilation options for PPCG.
2138   ///
2139   /// @returns The compilation options.
2140   ppcg_options *createPPCGOptions() {
2141     auto DebugOptions =
2142         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
2143     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
2144 
2145     DebugOptions->dump_schedule_constraints = false;
2146     DebugOptions->dump_schedule = false;
2147     DebugOptions->dump_final_schedule = false;
2148     DebugOptions->dump_sizes = false;
2149     DebugOptions->verbose = false;
2150 
2151     Options->debug = DebugOptions;
2152 
2153     Options->group_chains = false;
2154     Options->reschedule = true;
2155     Options->scale_tile_loops = false;
2156     Options->wrap = false;
2157 
2158     Options->non_negative_parameters = false;
2159     Options->ctx = nullptr;
2160     Options->sizes = nullptr;
2161 
2162     Options->tile = true;
2163     Options->tile_size = 32;
2164 
2165     Options->isolate_full_tiles = false;
2166 
2167     Options->use_private_memory = PrivateMemory;
2168     Options->use_shared_memory = SharedMemory;
2169     Options->max_shared_memory = 48 * 1024;
2170 
2171     Options->target = PPCG_TARGET_CUDA;
2172     Options->openmp = false;
2173     Options->linearize_device_arrays = true;
2174     Options->allow_gnu_extensions = false;
2175 
2176     Options->unroll_copy_shared = false;
2177     Options->unroll_gpu_tile = false;
2178     Options->live_range_reordering = true;
2179 
2180     Options->live_range_reordering = true;
2181     Options->hybrid = false;
2182     Options->opencl_compiler_options = nullptr;
2183     Options->opencl_use_gpu = false;
2184     Options->opencl_n_include_file = 0;
2185     Options->opencl_include_files = nullptr;
2186     Options->opencl_print_kernel_types = false;
2187     Options->opencl_embed_kernel_code = false;
2188 
2189     Options->save_schedule_file = nullptr;
2190     Options->load_schedule_file = nullptr;
2191 
2192     return Options;
2193   }
2194 
2195   /// Get a tagged access relation containing all accesses of type @p AccessTy.
2196   ///
2197   /// Instead of a normal access of the form:
2198   ///
2199   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
2200   ///
2201   /// a tagged access has the form
2202   ///
2203   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
2204   ///
2205   /// where 'id' is an additional space that references the memory access that
2206   /// triggered the access.
2207   ///
2208   /// @param AccessTy The type of the memory accesses to collect.
2209   ///
2210   /// @return The relation describing all tagged memory accesses.
2211   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
2212     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
2213 
2214     for (auto &Stmt : *S)
2215       for (auto &Acc : Stmt)
2216         if (Acc->getType() == AccessTy) {
2217           isl_map *Relation = Acc->getAccessRelation();
2218           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
2219 
2220           isl_space *Space = isl_map_get_space(Relation);
2221           Space = isl_space_range(Space);
2222           Space = isl_space_from_range(Space);
2223           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
2224           isl_map *Universe = isl_map_universe(Space);
2225           Relation = isl_map_domain_product(Relation, Universe);
2226           Accesses = isl_union_map_add_map(Accesses, Relation);
2227         }
2228 
2229     return Accesses;
2230   }
2231 
2232   /// Get the set of all read accesses, tagged with the access id.
2233   ///
2234   /// @see getTaggedAccesses
2235   isl_union_map *getTaggedReads() {
2236     return getTaggedAccesses(MemoryAccess::READ);
2237   }
2238 
2239   /// Get the set of all may (and must) accesses, tagged with the access id.
2240   ///
2241   /// @see getTaggedAccesses
2242   isl_union_map *getTaggedMayWrites() {
2243     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
2244                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
2245   }
2246 
2247   /// Get the set of all must accesses, tagged with the access id.
2248   ///
2249   /// @see getTaggedAccesses
2250   isl_union_map *getTaggedMustWrites() {
2251     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
2252   }
2253 
2254   /// Collect parameter and array names as isl_ids.
2255   ///
2256   /// To reason about the different parameters and arrays used, ppcg requires
2257   /// a list of all isl_ids in use. As PPCG traditionally performs
2258   /// source-to-source compilation each of these isl_ids is mapped to the
2259   /// expression that represents it. As we do not have a corresponding
2260   /// expression in Polly, we just map each id to a 'zero' expression to match
2261   /// the data format that ppcg expects.
2262   ///
2263   /// @returns Retun a map from collected ids to 'zero' ast expressions.
2264   __isl_give isl_id_to_ast_expr *getNames() {
2265     auto *Names = isl_id_to_ast_expr_alloc(
2266         S->getIslCtx(),
2267         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
2268     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
2269     auto *Space = S->getParamSpace();
2270 
2271     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
2272       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
2273       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2274     }
2275 
2276     for (auto &Array : S->arrays()) {
2277       auto Id = Array->getBasePtrId();
2278       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
2279     }
2280 
2281     isl_space_free(Space);
2282     isl_ast_expr_free(Zero);
2283 
2284     return Names;
2285   }
2286 
2287   /// Create a new PPCG scop from the current scop.
2288   ///
2289   /// The PPCG scop is initialized with data from the current polly::Scop. From
2290   /// this initial data, the data-dependences in the PPCG scop are initialized.
2291   /// We do not use Polly's dependence analysis for now, to ensure we match
2292   /// the PPCG default behaviour more closely.
2293   ///
2294   /// @returns A new ppcg scop.
2295   ppcg_scop *createPPCGScop() {
2296     MustKillsInfo KillsInfo = computeMustKillsInfo(*S);
2297 
2298     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
2299 
2300     PPCGScop->options = createPPCGOptions();
2301     // enable live range reordering
2302     PPCGScop->options->live_range_reordering = 1;
2303 
2304     PPCGScop->start = 0;
2305     PPCGScop->end = 0;
2306 
2307     PPCGScop->context = S->getContext();
2308     PPCGScop->domain = S->getDomains();
2309     // TODO: investigate this further. PPCG calls collect_call_domains.
2310     PPCGScop->call = isl_union_set_from_set(S->getContext());
2311     PPCGScop->tagged_reads = getTaggedReads();
2312     PPCGScop->reads = S->getReads();
2313     PPCGScop->live_in = nullptr;
2314     PPCGScop->tagged_may_writes = getTaggedMayWrites();
2315     PPCGScop->may_writes = S->getWrites();
2316     PPCGScop->tagged_must_writes = getTaggedMustWrites();
2317     PPCGScop->must_writes = S->getMustWrites();
2318     PPCGScop->live_out = nullptr;
2319     PPCGScop->tagged_must_kills = KillsInfo.TaggedMustKills.take();
2320     PPCGScop->must_kills = KillsInfo.MustKills.take();
2321 
2322     PPCGScop->tagger = nullptr;
2323     PPCGScop->independence =
2324         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2325     PPCGScop->dep_flow = nullptr;
2326     PPCGScop->tagged_dep_flow = nullptr;
2327     PPCGScop->dep_false = nullptr;
2328     PPCGScop->dep_forced = nullptr;
2329     PPCGScop->dep_order = nullptr;
2330     PPCGScop->tagged_dep_order = nullptr;
2331 
2332     PPCGScop->schedule = S->getScheduleTree();
2333     // If we have something non-trivial to kill, add it to the schedule
2334     if (KillsInfo.KillsSchedule.get())
2335       PPCGScop->schedule = isl_schedule_sequence(
2336           PPCGScop->schedule, KillsInfo.KillsSchedule.take());
2337 
2338     PPCGScop->names = getNames();
2339     PPCGScop->pet = nullptr;
2340 
2341     compute_tagger(PPCGScop);
2342     compute_dependences(PPCGScop);
2343     eliminate_dead_code(PPCGScop);
2344 
2345     return PPCGScop;
2346   }
2347 
2348   /// Collect the array accesses in a statement.
2349   ///
2350   /// @param Stmt The statement for which to collect the accesses.
2351   ///
2352   /// @returns A list of array accesses.
2353   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
2354     gpu_stmt_access *Accesses = nullptr;
2355 
2356     for (MemoryAccess *Acc : Stmt) {
2357       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
2358       Access->read = Acc->isRead();
2359       Access->write = Acc->isWrite();
2360       Access->access = Acc->getAccessRelation();
2361       isl_space *Space = isl_map_get_space(Access->access);
2362       Space = isl_space_range(Space);
2363       Space = isl_space_from_range(Space);
2364       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
2365       isl_map *Universe = isl_map_universe(Space);
2366       Access->tagged_access =
2367           isl_map_domain_product(Acc->getAccessRelation(), Universe);
2368       Access->exact_write = !Acc->isMayWrite();
2369       Access->ref_id = Acc->getId();
2370       Access->next = Accesses;
2371       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
2372       Accesses = Access;
2373     }
2374 
2375     return Accesses;
2376   }
2377 
2378   /// Collect the list of GPU statements.
2379   ///
2380   /// Each statement has an id, a pointer to the underlying data structure,
2381   /// as well as a list with all memory accesses.
2382   ///
2383   /// TODO: Initialize the list of memory accesses.
2384   ///
2385   /// @returns A linked-list of statements.
2386   gpu_stmt *getStatements() {
2387     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
2388                                        std::distance(S->begin(), S->end()));
2389 
2390     int i = 0;
2391     for (auto &Stmt : *S) {
2392       gpu_stmt *GPUStmt = &Stmts[i];
2393 
2394       GPUStmt->id = Stmt.getDomainId();
2395 
2396       // We use the pet stmt pointer to keep track of the Polly statements.
2397       GPUStmt->stmt = (pet_stmt *)&Stmt;
2398       GPUStmt->accesses = getStmtAccesses(Stmt);
2399       i++;
2400     }
2401 
2402     return Stmts;
2403   }
2404 
2405   /// Derive the extent of an array.
2406   ///
2407   /// The extent of an array is the set of elements that are within the
2408   /// accessed array. For the inner dimensions, the extent constraints are
2409   /// 0 and the size of the corresponding array dimension. For the first
2410   /// (outermost) dimension, the extent constraints are the minimal and maximal
2411   /// subscript value for the first dimension.
2412   ///
2413   /// @param Array The array to derive the extent for.
2414   ///
2415   /// @returns An isl_set describing the extent of the array.
2416   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
2417     unsigned NumDims = Array->getNumberOfDimensions();
2418     isl_union_map *Accesses = S->getAccesses();
2419     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
2420     Accesses = isl_union_map_detect_equalities(Accesses);
2421     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
2422     AccessUSet = isl_union_set_coalesce(AccessUSet);
2423     AccessUSet = isl_union_set_detect_equalities(AccessUSet);
2424     AccessUSet = isl_union_set_coalesce(AccessUSet);
2425 
2426     if (isl_union_set_is_empty(AccessUSet)) {
2427       isl_union_set_free(AccessUSet);
2428       return isl_set_empty(Array->getSpace());
2429     }
2430 
2431     if (Array->getNumberOfDimensions() == 0) {
2432       isl_union_set_free(AccessUSet);
2433       return isl_set_universe(Array->getSpace());
2434     }
2435 
2436     isl_set *AccessSet =
2437         isl_union_set_extract_set(AccessUSet, Array->getSpace());
2438 
2439     isl_union_set_free(AccessUSet);
2440     isl_local_space *LS = isl_local_space_from_space(Array->getSpace());
2441 
2442     isl_pw_aff *Val =
2443         isl_pw_aff_from_aff(isl_aff_var_on_domain(LS, isl_dim_set, 0));
2444 
2445     isl_pw_aff *OuterMin = isl_set_dim_min(isl_set_copy(AccessSet), 0);
2446     isl_pw_aff *OuterMax = isl_set_dim_max(AccessSet, 0);
2447     OuterMin = isl_pw_aff_add_dims(OuterMin, isl_dim_in,
2448                                    isl_pw_aff_dim(Val, isl_dim_in));
2449     OuterMax = isl_pw_aff_add_dims(OuterMax, isl_dim_in,
2450                                    isl_pw_aff_dim(Val, isl_dim_in));
2451     OuterMin =
2452         isl_pw_aff_set_tuple_id(OuterMin, isl_dim_in, Array->getBasePtrId());
2453     OuterMax =
2454         isl_pw_aff_set_tuple_id(OuterMax, isl_dim_in, Array->getBasePtrId());
2455 
2456     isl_set *Extent = isl_set_universe(Array->getSpace());
2457 
2458     Extent = isl_set_intersect(
2459         Extent, isl_pw_aff_le_set(OuterMin, isl_pw_aff_copy(Val)));
2460     Extent = isl_set_intersect(Extent, isl_pw_aff_ge_set(OuterMax, Val));
2461 
2462     for (unsigned i = 1; i < NumDims; ++i)
2463       Extent = isl_set_lower_bound_si(Extent, isl_dim_set, i, 0);
2464 
2465     for (unsigned i = 0; i < NumDims; ++i) {
2466       isl_pw_aff *PwAff =
2467           const_cast<isl_pw_aff *>(Array->getDimensionSizePw(i));
2468 
2469       // isl_pw_aff can be NULL for zero dimension. Only in the case of a
2470       // Fortran array will we have a legitimate dimension.
2471       if (!PwAff) {
2472         assert(i == 0 && "invalid dimension isl_pw_aff for nonzero dimension");
2473         continue;
2474       }
2475 
2476       isl_pw_aff *Val = isl_pw_aff_from_aff(isl_aff_var_on_domain(
2477           isl_local_space_from_space(Array->getSpace()), isl_dim_set, i));
2478       PwAff = isl_pw_aff_add_dims(PwAff, isl_dim_in,
2479                                   isl_pw_aff_dim(Val, isl_dim_in));
2480       PwAff = isl_pw_aff_set_tuple_id(PwAff, isl_dim_in,
2481                                       isl_pw_aff_get_tuple_id(Val, isl_dim_in));
2482       auto *Set = isl_pw_aff_gt_set(PwAff, Val);
2483       Extent = isl_set_intersect(Set, Extent);
2484     }
2485 
2486     return Extent;
2487   }
2488 
2489   /// Derive the bounds of an array.
2490   ///
2491   /// For the first dimension we derive the bound of the array from the extent
2492   /// of this dimension. For inner dimensions we obtain their size directly from
2493   /// ScopArrayInfo.
2494   ///
2495   /// @param PPCGArray The array to compute bounds for.
2496   /// @param Array The polly array from which to take the information.
2497   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
2498     isl_pw_aff_list *BoundsList =
2499         isl_pw_aff_list_alloc(S->getIslCtx(), PPCGArray.n_index);
2500     std::vector<isl::pw_aff> PwAffs;
2501 
2502     isl_space *AlignSpace = S->getParamSpace();
2503     AlignSpace = isl_space_add_dims(AlignSpace, isl_dim_set, 1);
2504 
2505     if (PPCGArray.n_index > 0) {
2506       if (isl_set_is_empty(PPCGArray.extent)) {
2507         isl_set *Dom = isl_set_copy(PPCGArray.extent);
2508         isl_local_space *LS = isl_local_space_from_space(
2509             isl_space_params(isl_set_get_space(Dom)));
2510         isl_set_free(Dom);
2511         isl_pw_aff *Zero = isl_pw_aff_from_aff(isl_aff_zero_on_domain(LS));
2512         Zero = isl_pw_aff_align_params(Zero, isl_space_copy(AlignSpace));
2513         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Zero)));
2514         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Zero);
2515       } else {
2516         isl_set *Dom = isl_set_copy(PPCGArray.extent);
2517         Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
2518         isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
2519         isl_set_free(Dom);
2520         Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
2521         isl_local_space *LS =
2522             isl_local_space_from_space(isl_set_get_space(Dom));
2523         isl_aff *One = isl_aff_zero_on_domain(LS);
2524         One = isl_aff_add_constant_si(One, 1);
2525         Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
2526         Bound = isl_pw_aff_gist(Bound, S->getContext());
2527         Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
2528         PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
2529         BoundsList = isl_pw_aff_list_insert(BoundsList, 0, Bound);
2530       }
2531     }
2532 
2533     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
2534       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
2535       auto LS = isl_pw_aff_get_domain_space(Bound);
2536       auto Aff = isl_multi_aff_zero(LS);
2537       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
2538       Bound = isl_pw_aff_align_params(Bound, isl_space_copy(AlignSpace));
2539       PwAffs.push_back(isl::manage(isl_pw_aff_copy(Bound)));
2540       BoundsList = isl_pw_aff_list_insert(BoundsList, i, Bound);
2541     }
2542 
2543     isl_space_free(AlignSpace);
2544     isl_space *BoundsSpace = isl_set_get_space(PPCGArray.extent);
2545 
2546     assert(BoundsSpace && "Unable to access space of array.");
2547     assert(BoundsList && "Unable to access list of bounds.");
2548 
2549     PPCGArray.bound =
2550         isl_multi_pw_aff_from_pw_aff_list(BoundsSpace, BoundsList);
2551     assert(PPCGArray.bound && "PPCGArray.bound was not constructed correctly.");
2552   }
2553 
2554   /// Create the arrays for @p PPCGProg.
2555   ///
2556   /// @param PPCGProg The program to compute the arrays for.
2557   void createArrays(gpu_prog *PPCGProg) {
2558     int i = 0;
2559     for (auto &Array : S->arrays()) {
2560       std::string TypeName;
2561       raw_string_ostream OS(TypeName);
2562 
2563       OS << *Array->getElementType();
2564       TypeName = OS.str();
2565 
2566       gpu_array_info &PPCGArray = PPCGProg->array[i];
2567 
2568       PPCGArray.space = Array->getSpace();
2569       PPCGArray.type = strdup(TypeName.c_str());
2570       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
2571       PPCGArray.name = strdup(Array->getName().c_str());
2572       PPCGArray.extent = nullptr;
2573       PPCGArray.n_index = Array->getNumberOfDimensions();
2574       PPCGArray.extent = getExtent(Array);
2575       PPCGArray.n_ref = 0;
2576       PPCGArray.refs = nullptr;
2577       PPCGArray.accessed = true;
2578       PPCGArray.read_only_scalar =
2579           Array->isReadOnly() && Array->getNumberOfDimensions() == 0;
2580       PPCGArray.has_compound_element = false;
2581       PPCGArray.local = false;
2582       PPCGArray.declare_local = false;
2583       PPCGArray.global = false;
2584       PPCGArray.linearize = false;
2585       PPCGArray.dep_order = nullptr;
2586       PPCGArray.user = Array;
2587 
2588       PPCGArray.bound = nullptr;
2589       setArrayBounds(PPCGArray, Array);
2590       i++;
2591 
2592       collect_references(PPCGProg, &PPCGArray);
2593     }
2594   }
2595 
2596   /// Create an identity map between the arrays in the scop.
2597   ///
2598   /// @returns An identity map between the arrays in the scop.
2599   isl_union_map *getArrayIdentity() {
2600     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
2601 
2602     for (auto &Array : S->arrays()) {
2603       isl_space *Space = Array->getSpace();
2604       Space = isl_space_map_from_set(Space);
2605       isl_map *Identity = isl_map_identity(Space);
2606       Maps = isl_union_map_add_map(Maps, Identity);
2607     }
2608 
2609     return Maps;
2610   }
2611 
2612   /// Create a default-initialized PPCG GPU program.
2613   ///
2614   /// @returns A new gpu program description.
2615   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
2616 
2617     if (!PPCGScop)
2618       return nullptr;
2619 
2620     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
2621 
2622     PPCGProg->ctx = S->getIslCtx();
2623     PPCGProg->scop = PPCGScop;
2624     PPCGProg->context = isl_set_copy(PPCGScop->context);
2625     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
2626     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
2627     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
2628     PPCGProg->tagged_must_kill =
2629         isl_union_map_copy(PPCGScop->tagged_must_kills);
2630     PPCGProg->to_inner = getArrayIdentity();
2631     PPCGProg->to_outer = getArrayIdentity();
2632     // TODO: verify that this assignment is correct.
2633     PPCGProg->any_to_outer = nullptr;
2634 
2635     // this needs to be set when live range reordering is enabled.
2636     // NOTE: I believe that is conservatively correct. I'm not sure
2637     //       what the semantics of this is.
2638     // Quoting PPCG/gpu.h: "Order dependences on non-scalars."
2639     PPCGProg->array_order =
2640         isl_union_map_empty(isl_set_get_space(PPCGScop->context));
2641     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
2642     PPCGProg->stmts = getStatements();
2643     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
2644     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
2645                                        PPCGProg->n_array);
2646 
2647     createArrays(PPCGProg);
2648 
2649     PPCGProg->may_persist = compute_may_persist(PPCGProg);
2650     return PPCGProg;
2651   }
2652 
2653   struct PrintGPUUserData {
2654     struct cuda_info *CudaInfo;
2655     struct gpu_prog *PPCGProg;
2656     std::vector<ppcg_kernel *> Kernels;
2657   };
2658 
2659   /// Print a user statement node in the host code.
2660   ///
2661   /// We use ppcg's printing facilities to print the actual statement and
2662   /// additionally build up a list of all kernels that are encountered in the
2663   /// host ast.
2664   ///
2665   /// @param P The printer to print to
2666   /// @param Options The printing options to use
2667   /// @param Node The node to print
2668   /// @param User A user pointer to carry additional data. This pointer is
2669   ///             expected to be of type PrintGPUUserData.
2670   ///
2671   /// @returns A printer to which the output has been printed.
2672   static __isl_give isl_printer *
2673   printHostUser(__isl_take isl_printer *P,
2674                 __isl_take isl_ast_print_options *Options,
2675                 __isl_take isl_ast_node *Node, void *User) {
2676     auto Data = (struct PrintGPUUserData *)User;
2677     auto Id = isl_ast_node_get_annotation(Node);
2678 
2679     if (Id) {
2680       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
2681 
2682       // If this is a user statement, format it ourselves as ppcg would
2683       // otherwise try to call pet functionality that is not available in
2684       // Polly.
2685       if (IsUser) {
2686         P = isl_printer_start_line(P);
2687         P = isl_printer_print_ast_node(P, Node);
2688         P = isl_printer_end_line(P);
2689         isl_id_free(Id);
2690         isl_ast_print_options_free(Options);
2691         return P;
2692       }
2693 
2694       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
2695       isl_id_free(Id);
2696       Data->Kernels.push_back(Kernel);
2697     }
2698 
2699     return print_host_user(P, Options, Node, User);
2700   }
2701 
2702   /// Print C code corresponding to the control flow in @p Kernel.
2703   ///
2704   /// @param Kernel The kernel to print
2705   void printKernel(ppcg_kernel *Kernel) {
2706     auto *P = isl_printer_to_str(S->getIslCtx());
2707     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
2708     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
2709     P = isl_ast_node_print(Kernel->tree, P, Options);
2710     char *String = isl_printer_get_str(P);
2711     printf("%s\n", String);
2712     free(String);
2713     isl_printer_free(P);
2714   }
2715 
2716   /// Print C code corresponding to the GPU code described by @p Tree.
2717   ///
2718   /// @param Tree An AST describing GPU code
2719   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
2720   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
2721     auto *P = isl_printer_to_str(S->getIslCtx());
2722     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
2723 
2724     PrintGPUUserData Data;
2725     Data.PPCGProg = PPCGProg;
2726 
2727     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
2728     Options =
2729         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
2730     P = isl_ast_node_print(Tree, P, Options);
2731     char *String = isl_printer_get_str(P);
2732     printf("# host\n");
2733     printf("%s\n", String);
2734     free(String);
2735     isl_printer_free(P);
2736 
2737     for (auto Kernel : Data.Kernels) {
2738       printf("# kernel%d\n", Kernel->id);
2739       printKernel(Kernel);
2740     }
2741   }
2742 
2743   // Generate a GPU program using PPCG.
2744   //
2745   // GPU mapping consists of multiple steps:
2746   //
2747   //  1) Compute new schedule for the program.
2748   //  2) Map schedule to GPU (TODO)
2749   //  3) Generate code for new schedule (TODO)
2750   //
2751   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
2752   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
2753   // strategy directly from this pass.
2754   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
2755 
2756     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
2757 
2758     PPCGGen->ctx = S->getIslCtx();
2759     PPCGGen->options = PPCGScop->options;
2760     PPCGGen->print = nullptr;
2761     PPCGGen->print_user = nullptr;
2762     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
2763     PPCGGen->prog = PPCGProg;
2764     PPCGGen->tree = nullptr;
2765     PPCGGen->types.n = 0;
2766     PPCGGen->types.name = nullptr;
2767     PPCGGen->sizes = nullptr;
2768     PPCGGen->used_sizes = nullptr;
2769     PPCGGen->kernel_id = 0;
2770 
2771     // Set scheduling strategy to same strategy PPCG is using.
2772     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
2773     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
2774     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
2775 
2776     isl_schedule *Schedule = get_schedule(PPCGGen);
2777 
2778     int has_permutable = has_any_permutable_node(Schedule);
2779 
2780     if (!has_permutable || has_permutable < 0) {
2781       Schedule = isl_schedule_free(Schedule);
2782     } else {
2783       Schedule = map_to_device(PPCGGen, Schedule);
2784       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
2785     }
2786 
2787     if (DumpSchedule) {
2788       isl_printer *P = isl_printer_to_str(S->getIslCtx());
2789       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
2790       P = isl_printer_print_str(P, "Schedule\n");
2791       P = isl_printer_print_str(P, "========\n");
2792       if (Schedule)
2793         P = isl_printer_print_schedule(P, Schedule);
2794       else
2795         P = isl_printer_print_str(P, "No schedule found\n");
2796 
2797       printf("%s\n", isl_printer_get_str(P));
2798       isl_printer_free(P);
2799     }
2800 
2801     if (DumpCode) {
2802       printf("Code\n");
2803       printf("====\n");
2804       if (PPCGGen->tree)
2805         printGPUTree(PPCGGen->tree, PPCGProg);
2806       else
2807         printf("No code generated\n");
2808     }
2809 
2810     isl_schedule_free(Schedule);
2811 
2812     return PPCGGen;
2813   }
2814 
2815   /// Free gpu_gen structure.
2816   ///
2817   /// @param PPCGGen The ppcg_gen object to free.
2818   void freePPCGGen(gpu_gen *PPCGGen) {
2819     isl_ast_node_free(PPCGGen->tree);
2820     isl_union_map_free(PPCGGen->sizes);
2821     isl_union_map_free(PPCGGen->used_sizes);
2822     free(PPCGGen);
2823   }
2824 
2825   /// Free the options in the ppcg scop structure.
2826   ///
2827   /// ppcg is not freeing these options for us. To avoid leaks we do this
2828   /// ourselves.
2829   ///
2830   /// @param PPCGScop The scop referencing the options to free.
2831   void freeOptions(ppcg_scop *PPCGScop) {
2832     free(PPCGScop->options->debug);
2833     PPCGScop->options->debug = nullptr;
2834     free(PPCGScop->options);
2835     PPCGScop->options = nullptr;
2836   }
2837 
2838   /// Approximate the number of points in the set.
2839   ///
2840   /// This function returns an ast expression that overapproximates the number
2841   /// of points in an isl set through the rectangular hull surrounding this set.
2842   ///
2843   /// @param Set   The set to count.
2844   /// @param Build The isl ast build object to use for creating the ast
2845   ///              expression.
2846   ///
2847   /// @returns An approximation of the number of points in the set.
2848   __isl_give isl_ast_expr *approxPointsInSet(__isl_take isl_set *Set,
2849                                              __isl_keep isl_ast_build *Build) {
2850 
2851     isl_val *One = isl_val_int_from_si(isl_set_get_ctx(Set), 1);
2852     auto *Expr = isl_ast_expr_from_val(isl_val_copy(One));
2853 
2854     isl_space *Space = isl_set_get_space(Set);
2855     Space = isl_space_params(Space);
2856     auto *Univ = isl_set_universe(Space);
2857     isl_pw_aff *OneAff = isl_pw_aff_val_on_domain(Univ, One);
2858 
2859     for (long i = 0; i < isl_set_dim(Set, isl_dim_set); i++) {
2860       isl_pw_aff *Max = isl_set_dim_max(isl_set_copy(Set), i);
2861       isl_pw_aff *Min = isl_set_dim_min(isl_set_copy(Set), i);
2862       isl_pw_aff *DimSize = isl_pw_aff_sub(Max, Min);
2863       DimSize = isl_pw_aff_add(DimSize, isl_pw_aff_copy(OneAff));
2864       auto DimSizeExpr = isl_ast_build_expr_from_pw_aff(Build, DimSize);
2865       Expr = isl_ast_expr_mul(Expr, DimSizeExpr);
2866     }
2867 
2868     isl_set_free(Set);
2869     isl_pw_aff_free(OneAff);
2870 
2871     return Expr;
2872   }
2873 
2874   /// Approximate a number of dynamic instructions executed by a given
2875   /// statement.
2876   ///
2877   /// @param Stmt  The statement for which to compute the number of dynamic
2878   ///              instructions.
2879   /// @param Build The isl ast build object to use for creating the ast
2880   ///              expression.
2881   /// @returns An approximation of the number of dynamic instructions executed
2882   ///          by @p Stmt.
2883   __isl_give isl_ast_expr *approxDynamicInst(ScopStmt &Stmt,
2884                                              __isl_keep isl_ast_build *Build) {
2885     auto Iterations = approxPointsInSet(Stmt.getDomain(), Build);
2886 
2887     long InstCount = 0;
2888 
2889     if (Stmt.isBlockStmt()) {
2890       auto *BB = Stmt.getBasicBlock();
2891       InstCount = std::distance(BB->begin(), BB->end());
2892     } else {
2893       auto *R = Stmt.getRegion();
2894 
2895       for (auto *BB : R->blocks()) {
2896         InstCount += std::distance(BB->begin(), BB->end());
2897       }
2898     }
2899 
2900     isl_val *InstVal = isl_val_int_from_si(S->getIslCtx(), InstCount);
2901     auto *InstExpr = isl_ast_expr_from_val(InstVal);
2902     return isl_ast_expr_mul(InstExpr, Iterations);
2903   }
2904 
2905   /// Approximate dynamic instructions executed in scop.
2906   ///
2907   /// @param S     The scop for which to approximate dynamic instructions.
2908   /// @param Build The isl ast build object to use for creating the ast
2909   ///              expression.
2910   /// @returns An approximation of the number of dynamic instructions executed
2911   ///          in @p S.
2912   __isl_give isl_ast_expr *
2913   getNumberOfIterations(Scop &S, __isl_keep isl_ast_build *Build) {
2914     isl_ast_expr *Instructions;
2915 
2916     isl_val *Zero = isl_val_int_from_si(S.getIslCtx(), 0);
2917     Instructions = isl_ast_expr_from_val(Zero);
2918 
2919     for (ScopStmt &Stmt : S) {
2920       isl_ast_expr *StmtInstructions = approxDynamicInst(Stmt, Build);
2921       Instructions = isl_ast_expr_add(Instructions, StmtInstructions);
2922     }
2923     return Instructions;
2924   }
2925 
2926   /// Create a check that ensures sufficient compute in scop.
2927   ///
2928   /// @param S     The scop for which to ensure sufficient compute.
2929   /// @param Build The isl ast build object to use for creating the ast
2930   ///              expression.
2931   /// @returns An expression that evaluates to TRUE in case of sufficient
2932   ///          compute and to FALSE, otherwise.
2933   __isl_give isl_ast_expr *
2934   createSufficientComputeCheck(Scop &S, __isl_keep isl_ast_build *Build) {
2935     auto Iterations = getNumberOfIterations(S, Build);
2936     auto *MinComputeVal = isl_val_int_from_si(S.getIslCtx(), MinCompute);
2937     auto *MinComputeExpr = isl_ast_expr_from_val(MinComputeVal);
2938     return isl_ast_expr_ge(Iterations, MinComputeExpr);
2939   }
2940 
2941   /// Check if the basic block contains a function we cannot codegen for GPU
2942   /// kernels.
2943   ///
2944   /// If this basic block does something with a `Function` other than calling
2945   /// a function that we support in a kernel, return true.
2946   bool containsInvalidKernelFunctionInBlock(const BasicBlock *BB) {
2947     for (const Instruction &Inst : *BB) {
2948       const CallInst *Call = dyn_cast<CallInst>(&Inst);
2949       if (Call && isValidFunctionInKernel(Call->getCalledFunction())) {
2950         continue;
2951       }
2952 
2953       for (Value *SrcVal : Inst.operands()) {
2954         PointerType *p = dyn_cast<PointerType>(SrcVal->getType());
2955         if (!p)
2956           continue;
2957         if (isa<FunctionType>(p->getElementType()))
2958           return true;
2959       }
2960     }
2961     return false;
2962   }
2963 
2964   /// Return whether the Scop S uses functions in a way that we do not support.
2965   bool containsInvalidKernelFunction(const Scop &S) {
2966     for (auto &Stmt : S) {
2967       if (Stmt.isBlockStmt()) {
2968         if (containsInvalidKernelFunctionInBlock(Stmt.getBasicBlock()))
2969           return true;
2970       } else {
2971         assert(Stmt.isRegionStmt() &&
2972                "Stmt was neither block nor region statement");
2973         for (const BasicBlock *BB : Stmt.getRegion()->blocks())
2974           if (containsInvalidKernelFunctionInBlock(BB))
2975             return true;
2976       }
2977     }
2978     return false;
2979   }
2980 
2981   /// Generate code for a given GPU AST described by @p Root.
2982   ///
2983   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
2984   /// @param Prog The GPU Program to generate code for.
2985   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
2986     ScopAnnotator Annotator;
2987     Annotator.buildAliasScopes(*S);
2988 
2989     Region *R = &S->getRegion();
2990 
2991     simplifyRegion(R, DT, LI, RI);
2992 
2993     BasicBlock *EnteringBB = R->getEnteringBlock();
2994 
2995     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
2996 
2997     // Only build the run-time condition and parameters _after_ having
2998     // introduced the conditional branch. This is important as the conditional
2999     // branch will guard the original scop from new induction variables that
3000     // the SCEVExpander may introduce while code generating the parameters and
3001     // which may introduce scalar dependences that prevent us from correctly
3002     // code generating this scop.
3003     BBPair StartExitBlocks;
3004     BranchInst *CondBr = nullptr;
3005     std::tie(StartExitBlocks, CondBr) =
3006         executeScopConditionally(*S, Builder.getTrue(), *DT, *RI, *LI);
3007     BasicBlock *StartBlock = std::get<0>(StartExitBlocks);
3008 
3009     assert(CondBr && "CondBr not initialized by executeScopConditionally");
3010 
3011     GPUNodeBuilder NodeBuilder(Builder, Annotator, *DL, *LI, *SE, *DT, *S,
3012                                StartBlock, Prog, Runtime, Architecture);
3013 
3014     // TODO: Handle LICM
3015     auto SplitBlock = StartBlock->getSinglePredecessor();
3016     Builder.SetInsertPoint(SplitBlock->getTerminator());
3017     NodeBuilder.addParameters(S->getContext());
3018 
3019     isl_ast_build *Build = isl_ast_build_alloc(S->getIslCtx());
3020     isl_ast_expr *Condition = IslAst::buildRunCondition(*S, Build);
3021     isl_ast_expr *SufficientCompute = createSufficientComputeCheck(*S, Build);
3022     Condition = isl_ast_expr_and(Condition, SufficientCompute);
3023     isl_ast_build_free(Build);
3024 
3025     // preload invariant loads. Note: This should happen before the RTC
3026     // because the RTC may depend on values that are invariant load hoisted.
3027     NodeBuilder.preloadInvariantLoads();
3028 
3029     Value *RTC = NodeBuilder.createRTC(Condition);
3030     Builder.GetInsertBlock()->getTerminator()->setOperand(0, RTC);
3031 
3032     Builder.SetInsertPoint(&*StartBlock->begin());
3033 
3034     NodeBuilder.create(Root);
3035 
3036     /// In case a sequential kernel has more surrounding loops as any parallel
3037     /// kernel, the SCoP is probably mostly sequential. Hence, there is no
3038     /// point in running it on a GPU.
3039     if (NodeBuilder.DeepestSequential > NodeBuilder.DeepestParallel)
3040       CondBr->setOperand(0, Builder.getFalse());
3041 
3042     if (!NodeBuilder.BuildSuccessful)
3043       CondBr->setOperand(0, Builder.getFalse());
3044   }
3045 
3046   bool runOnScop(Scop &CurrentScop) override {
3047     S = &CurrentScop;
3048     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3049     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3050     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3051     DL = &S->getRegion().getEntry()->getModule()->getDataLayout();
3052     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
3053 
3054     // We currently do not support functions other than intrinsics inside
3055     // kernels, as code generation will need to offload function calls to the
3056     // kernel. This may lead to a kernel trying to call a function on the host.
3057     // This also allows us to prevent codegen from trying to take the
3058     // address of an intrinsic function to send to the kernel.
3059     if (containsInvalidKernelFunction(CurrentScop)) {
3060       DEBUG(
3061           dbgs()
3062               << "Scop contains function which cannot be materialised in a GPU "
3063                  "kernel. Bailing out.\n";);
3064       return false;
3065     }
3066 
3067     auto PPCGScop = createPPCGScop();
3068     auto PPCGProg = createPPCGProg(PPCGScop);
3069     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
3070 
3071     if (PPCGGen->tree) {
3072       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
3073       CurrentScop.markAsToBeSkipped();
3074     }
3075 
3076     freeOptions(PPCGScop);
3077     freePPCGGen(PPCGGen);
3078     gpu_prog_free(PPCGProg);
3079     ppcg_scop_free(PPCGScop);
3080 
3081     return true;
3082   }
3083 
3084   void printScop(raw_ostream &, Scop &) const override {}
3085 
3086   void getAnalysisUsage(AnalysisUsage &AU) const override {
3087     AU.addRequired<DominatorTreeWrapperPass>();
3088     AU.addRequired<RegionInfoPass>();
3089     AU.addRequired<ScalarEvolutionWrapperPass>();
3090     AU.addRequired<ScopDetectionWrapperPass>();
3091     AU.addRequired<ScopInfoRegionPass>();
3092     AU.addRequired<LoopInfoWrapperPass>();
3093 
3094     AU.addPreserved<AAResultsWrapperPass>();
3095     AU.addPreserved<BasicAAWrapperPass>();
3096     AU.addPreserved<LoopInfoWrapperPass>();
3097     AU.addPreserved<DominatorTreeWrapperPass>();
3098     AU.addPreserved<GlobalsAAWrapperPass>();
3099     AU.addPreserved<ScopDetectionWrapperPass>();
3100     AU.addPreserved<ScalarEvolutionWrapperPass>();
3101     AU.addPreserved<SCEVAAWrapperPass>();
3102 
3103     // FIXME: We do not yet add regions for the newly generated code to the
3104     //        region tree.
3105     AU.addPreserved<RegionInfoPass>();
3106     AU.addPreserved<ScopInfoRegionPass>();
3107   }
3108 };
3109 } // namespace
3110 
3111 char PPCGCodeGeneration::ID = 1;
3112 
3113 Pass *polly::createPPCGCodeGenerationPass(GPUArch Arch, GPURuntime Runtime) {
3114   PPCGCodeGeneration *generator = new PPCGCodeGeneration();
3115   generator->Runtime = Runtime;
3116   generator->Architecture = Arch;
3117   return generator;
3118 }
3119 
3120 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
3121                       "Polly - Apply PPCG translation to SCOP", false, false)
3122 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
3123 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
3124 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
3125 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
3126 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
3127 INITIALIZE_PASS_DEPENDENCY(ScopDetectionWrapperPass);
3128 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
3129                     "Polly - Apply PPCG translation to SCOP", false, false)
3130