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