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