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