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