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