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