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