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