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