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