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