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