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