19dfe4e7cSTobias Grosser //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
29dfe4e7cSTobias Grosser //
39dfe4e7cSTobias Grosser //                     The LLVM Compiler Infrastructure
49dfe4e7cSTobias Grosser //
59dfe4e7cSTobias Grosser // This file is distributed under the University of Illinois Open Source
69dfe4e7cSTobias Grosser // License. See LICENSE.TXT for details.
79dfe4e7cSTobias Grosser //
89dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
99dfe4e7cSTobias Grosser //
109dfe4e7cSTobias Grosser // Take a scop created by ScopInfo and map it to GPU code using the ppcg
119dfe4e7cSTobias Grosser // GPU mapping strategy.
129dfe4e7cSTobias Grosser //
139dfe4e7cSTobias Grosser //===----------------------------------------------------------------------===//
149dfe4e7cSTobias Grosser 
159dfe4e7cSTobias Grosser #include "polly/CodeGen/IslNodeBuilder.h"
1638fc0aedSTobias Grosser #include "polly/CodeGen/Utils.h"
179dfe4e7cSTobias Grosser #include "polly/DependenceInfo.h"
189dfe4e7cSTobias Grosser #include "polly/LinkAllPasses.h"
19f384594dSTobias Grosser #include "polly/Options.h"
20629109b6STobias Grosser #include "polly/ScopDetection.h"
219dfe4e7cSTobias Grosser #include "polly/ScopInfo.h"
22edb885cbSTobias Grosser #include "polly/Support/SCEVValidator.h"
2374dc3cb4STobias Grosser #include "llvm/ADT/PostOrderIterator.h"
249dfe4e7cSTobias Grosser #include "llvm/Analysis/AliasAnalysis.h"
259dfe4e7cSTobias Grosser #include "llvm/Analysis/BasicAliasAnalysis.h"
269dfe4e7cSTobias Grosser #include "llvm/Analysis/GlobalsModRef.h"
279dfe4e7cSTobias Grosser #include "llvm/Analysis/PostDominators.h"
289dfe4e7cSTobias Grosser #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
2974dc3cb4STobias Grosser #include "llvm/Analysis/TargetLibraryInfo.h"
3074dc3cb4STobias Grosser #include "llvm/Analysis/TargetTransformInfo.h"
3174dc3cb4STobias Grosser #include "llvm/IR/LegacyPassManager.h"
32e1a98343STobias Grosser #include "llvm/IR/Verifier.h"
3374dc3cb4STobias Grosser #include "llvm/Support/TargetRegistry.h"
3474dc3cb4STobias Grosser #include "llvm/Support/TargetSelect.h"
3574dc3cb4STobias Grosser #include "llvm/Target/TargetMachine.h"
369a18d559STobias Grosser #include "llvm/Transforms/IPO/PassManagerBuilder.h"
379dfe4e7cSTobias Grosser 
38f384594dSTobias Grosser #include "isl/union_map.h"
39f384594dSTobias Grosser 
40e938517eSTobias Grosser extern "C" {
41a56f8f8eSTobias Grosser #include "ppcg/cuda.h"
42a56f8f8eSTobias Grosser #include "ppcg/gpu.h"
43a56f8f8eSTobias Grosser #include "ppcg/gpu_print.h"
44a56f8f8eSTobias Grosser #include "ppcg/ppcg.h"
45a56f8f8eSTobias Grosser #include "ppcg/schedule.h"
46e938517eSTobias Grosser }
47e938517eSTobias Grosser 
489dfe4e7cSTobias Grosser #include "llvm/Support/Debug.h"
499dfe4e7cSTobias Grosser 
509dfe4e7cSTobias Grosser using namespace polly;
519dfe4e7cSTobias Grosser using namespace llvm;
529dfe4e7cSTobias Grosser 
539dfe4e7cSTobias Grosser #define DEBUG_TYPE "polly-codegen-ppcg"
549dfe4e7cSTobias Grosser 
55f384594dSTobias Grosser static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
56f384594dSTobias Grosser                                   cl::desc("Dump the computed GPU Schedule"),
57681bd568STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
58f384594dSTobias Grosser                                   cl::cat(PollyCategory));
5969b46751STobias Grosser 
6069b46751STobias Grosser static cl::opt<bool>
6169b46751STobias Grosser     DumpCode("polly-acc-dump-code",
6269b46751STobias Grosser              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
6369b46751STobias Grosser              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
6469b46751STobias Grosser 
6532837fe3STobias Grosser static cl::opt<bool> DumpKernelIR("polly-acc-dump-kernel-ir",
6632837fe3STobias Grosser                                   cl::desc("Dump the kernel LLVM-IR"),
6732837fe3STobias Grosser                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
6832837fe3STobias Grosser                                   cl::cat(PollyCategory));
6932837fe3STobias Grosser 
7074dc3cb4STobias Grosser static cl::opt<bool> DumpKernelASM("polly-acc-dump-kernel-asm",
7174dc3cb4STobias Grosser                                    cl::desc("Dump the kernel assembly code"),
7274dc3cb4STobias Grosser                                    cl::Hidden, cl::init(false), cl::ZeroOrMore,
7374dc3cb4STobias Grosser                                    cl::cat(PollyCategory));
7474dc3cb4STobias Grosser 
7574dc3cb4STobias Grosser static cl::opt<bool> FastMath("polly-acc-fastmath",
7674dc3cb4STobias Grosser                               cl::desc("Allow unsafe math optimizations"),
7774dc3cb4STobias Grosser                               cl::Hidden, cl::init(false), cl::ZeroOrMore,
7874dc3cb4STobias Grosser                               cl::cat(PollyCategory));
79*b513b491STobias Grosser static cl::opt<bool> SharedMemory("polly-acc-use-shared",
80*b513b491STobias Grosser                                   cl::desc("Use shared memory"), cl::Hidden,
81*b513b491STobias Grosser                                   cl::init(false), cl::ZeroOrMore,
82*b513b491STobias Grosser                                   cl::cat(PollyCategory));
8374dc3cb4STobias Grosser 
8474dc3cb4STobias Grosser static cl::opt<std::string>
8574dc3cb4STobias Grosser     CudaVersion("polly-acc-cuda-version",
8674dc3cb4STobias Grosser                 cl::desc("The CUDA version to compile for"), cl::Hidden,
8774dc3cb4STobias Grosser                 cl::init("sm_30"), cl::ZeroOrMore, cl::cat(PollyCategory));
8874dc3cb4STobias Grosser 
8960c60025STobias Grosser /// Create the ast expressions for a ScopStmt.
9060c60025STobias Grosser ///
9160c60025STobias Grosser /// This function is a callback for to generate the ast expressions for each
9260c60025STobias Grosser /// of the scheduled ScopStmts.
9360c60025STobias Grosser static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
94edb885cbSTobias Grosser     void *StmtT, isl_ast_build *Build,
9560c60025STobias Grosser     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
9660c60025STobias Grosser                                        isl_id *Id, void *User),
9760c60025STobias Grosser     void *UserIndex,
9860c60025STobias Grosser     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
99edb885cbSTobias Grosser     void *UserExpr) {
10060c60025STobias Grosser 
101edb885cbSTobias Grosser   ScopStmt *Stmt = (ScopStmt *)StmtT;
10260c60025STobias Grosser 
103edb885cbSTobias Grosser   isl_ctx *Ctx;
104edb885cbSTobias Grosser 
105edb885cbSTobias Grosser   if (!Stmt || !Build)
106edb885cbSTobias Grosser     return NULL;
107edb885cbSTobias Grosser 
108edb885cbSTobias Grosser   Ctx = isl_ast_build_get_ctx(Build);
109edb885cbSTobias Grosser   isl_id_to_ast_expr *RefToExpr = isl_id_to_ast_expr_alloc(Ctx, 0);
110edb885cbSTobias Grosser 
111edb885cbSTobias Grosser   for (MemoryAccess *Acc : *Stmt) {
112edb885cbSTobias Grosser     isl_map *AddrFunc = Acc->getAddressFunction();
113edb885cbSTobias Grosser     AddrFunc = isl_map_intersect_domain(AddrFunc, Stmt->getDomain());
114edb885cbSTobias Grosser     isl_id *RefId = Acc->getId();
115edb885cbSTobias Grosser     isl_pw_multi_aff *PMA = isl_pw_multi_aff_from_map(AddrFunc);
116edb885cbSTobias Grosser     isl_multi_pw_aff *MPA = isl_multi_pw_aff_from_pw_multi_aff(PMA);
117edb885cbSTobias Grosser     MPA = isl_multi_pw_aff_coalesce(MPA);
118edb885cbSTobias Grosser     MPA = FunctionIndex(MPA, RefId, UserIndex);
119edb885cbSTobias Grosser     isl_ast_expr *Access = isl_ast_build_access_from_multi_pw_aff(Build, MPA);
120edb885cbSTobias Grosser     Access = FunctionExpr(Access, RefId, UserExpr);
121edb885cbSTobias Grosser     RefToExpr = isl_id_to_ast_expr_set(RefToExpr, RefId, Access);
122edb885cbSTobias Grosser   }
123edb885cbSTobias Grosser 
124edb885cbSTobias Grosser   return RefToExpr;
12560c60025STobias Grosser }
126f384594dSTobias Grosser 
12738fc0aedSTobias Grosser /// Generate code for a GPU specific isl AST.
12838fc0aedSTobias Grosser ///
12938fc0aedSTobias Grosser /// The GPUNodeBuilder augments the general existing IslNodeBuilder, which
13038fc0aedSTobias Grosser /// generates code for general-prupose AST nodes, with special functionality
13138fc0aedSTobias Grosser /// for generating GPU specific user nodes.
13238fc0aedSTobias Grosser ///
13338fc0aedSTobias Grosser /// @see GPUNodeBuilder::createUser
13438fc0aedSTobias Grosser class GPUNodeBuilder : public IslNodeBuilder {
13538fc0aedSTobias Grosser public:
13638fc0aedSTobias Grosser   GPUNodeBuilder(PollyIRBuilder &Builder, ScopAnnotator &Annotator, Pass *P,
13738fc0aedSTobias Grosser                  const DataLayout &DL, LoopInfo &LI, ScalarEvolution &SE,
13832837fe3STobias Grosser                  DominatorTree &DT, Scop &S, gpu_prog *Prog)
139edb885cbSTobias Grosser       : IslNodeBuilder(Builder, Annotator, P, DL, LI, SE, DT, S), Prog(Prog) {
140edb885cbSTobias Grosser     getExprBuilder().setIDToSAI(&IDToSAI);
141edb885cbSTobias Grosser   }
14238fc0aedSTobias Grosser 
143fa7b0802STobias Grosser   /// Create after-run-time-check initialization code.
144fa7b0802STobias Grosser   void initializeAfterRTH();
145fa7b0802STobias Grosser 
146fa7b0802STobias Grosser   /// Finalize the generated scop.
147fa7b0802STobias Grosser   virtual void finalize();
148fa7b0802STobias Grosser 
14938fc0aedSTobias Grosser private:
15074dc3cb4STobias Grosser   /// A vector of array base pointers for which a new ScopArrayInfo was created.
15174dc3cb4STobias Grosser   ///
15274dc3cb4STobias Grosser   /// This vector is used to delete the ScopArrayInfo when it is not needed any
15374dc3cb4STobias Grosser   /// more.
15474dc3cb4STobias Grosser   std::vector<Value *> LocalArrays;
15574dc3cb4STobias Grosser 
15613c78e4dSTobias Grosser   /// A map from ScopArrays to their corresponding device allocations.
15713c78e4dSTobias Grosser   std::map<ScopArrayInfo *, Value *> DeviceAllocations;
1587287aeddSTobias Grosser 
159fa7b0802STobias Grosser   /// The current GPU context.
160fa7b0802STobias Grosser   Value *GPUContext;
161fa7b0802STobias Grosser 
162*b513b491STobias Grosser   /// The set of isl_ids allocated in the kernel
163*b513b491STobias Grosser   std::vector<isl_id *> KernelIds;
164*b513b491STobias Grosser 
16532837fe3STobias Grosser   /// A module containing GPU code.
16632837fe3STobias Grosser   ///
16732837fe3STobias Grosser   /// This pointer is only set in case we are currently generating GPU code.
16832837fe3STobias Grosser   std::unique_ptr<Module> GPUModule;
16932837fe3STobias Grosser 
17032837fe3STobias Grosser   /// The GPU program we generate code for.
17132837fe3STobias Grosser   gpu_prog *Prog;
17232837fe3STobias Grosser 
173472f9654STobias Grosser   /// Class to free isl_ids.
174472f9654STobias Grosser   class IslIdDeleter {
175472f9654STobias Grosser   public:
176472f9654STobias Grosser     void operator()(__isl_take isl_id *Id) { isl_id_free(Id); };
177472f9654STobias Grosser   };
178472f9654STobias Grosser 
179472f9654STobias Grosser   /// A set containing all isl_ids allocated in a GPU kernel.
180472f9654STobias Grosser   ///
181472f9654STobias Grosser   /// By releasing this set all isl_ids will be freed.
182472f9654STobias Grosser   std::set<std::unique_ptr<isl_id, IslIdDeleter>> KernelIDs;
183472f9654STobias Grosser 
184edb885cbSTobias Grosser   IslExprBuilder::IDToScopArrayInfoTy IDToSAI;
185edb885cbSTobias Grosser 
18638fc0aedSTobias Grosser   /// Create code for user-defined AST nodes.
18738fc0aedSTobias Grosser   ///
18838fc0aedSTobias Grosser   /// These AST nodes can be of type:
18938fc0aedSTobias Grosser   ///
19038fc0aedSTobias Grosser   ///   - ScopStmt:      A computational statement (TODO)
19138fc0aedSTobias Grosser   ///   - Kernel:        A GPU kernel call (TODO)
19213c78e4dSTobias Grosser   ///   - Data-Transfer: A GPU <-> CPU data-transfer
1935260c041STobias Grosser   ///   - In-kernel synchronization
1945260c041STobias Grosser   ///   - In-kernel memory copy statement
19538fc0aedSTobias Grosser   ///
1961fb9b64dSTobias Grosser   /// @param UserStmt The ast node to generate code for.
1971fb9b64dSTobias Grosser   virtual void createUser(__isl_take isl_ast_node *UserStmt);
19832837fe3STobias Grosser 
19913c78e4dSTobias Grosser   enum DataDirection { HOST_TO_DEVICE, DEVICE_TO_HOST };
20013c78e4dSTobias Grosser 
20113c78e4dSTobias Grosser   /// Create code for a data transfer statement
20213c78e4dSTobias Grosser   ///
20313c78e4dSTobias Grosser   /// @param TransferStmt The data transfer statement.
20413c78e4dSTobias Grosser   /// @param Direction The direction in which to transfer data.
20513c78e4dSTobias Grosser   void createDataTransfer(__isl_take isl_ast_node *TransferStmt,
20613c78e4dSTobias Grosser                           enum DataDirection Direction);
20713c78e4dSTobias Grosser 
208edb885cbSTobias Grosser   /// Find llvm::Values referenced in GPU kernel.
209edb885cbSTobias Grosser   ///
210edb885cbSTobias Grosser   /// @param Kernel The kernel to scan for llvm::Values
211edb885cbSTobias Grosser   ///
212edb885cbSTobias Grosser   /// @returns A set of values referenced by the kernel.
213edb885cbSTobias Grosser   SetVector<Value *> getReferencesInKernel(ppcg_kernel *Kernel);
214edb885cbSTobias Grosser 
21579a947c2STobias Grosser   /// Compute the sizes of the execution grid for a given kernel.
21679a947c2STobias Grosser   ///
21779a947c2STobias Grosser   /// @param Kernel The kernel to compute grid sizes for.
21879a947c2STobias Grosser   ///
21979a947c2STobias Grosser   /// @returns A tuple with grid sizes for X and Y dimension
22079a947c2STobias Grosser   std::tuple<Value *, Value *> getGridSizes(ppcg_kernel *Kernel);
22179a947c2STobias Grosser 
22279a947c2STobias Grosser   /// Compute the sizes of the thread blocks for a given kernel.
22379a947c2STobias Grosser   ///
22479a947c2STobias Grosser   /// @param Kernel The kernel to compute thread block sizes for.
22579a947c2STobias Grosser   ///
22679a947c2STobias Grosser   /// @returns A tuple with thread block sizes for X, Y, and Z dimensions.
22779a947c2STobias Grosser   std::tuple<Value *, Value *, Value *> getBlockSizes(ppcg_kernel *Kernel);
22879a947c2STobias Grosser 
22979a947c2STobias Grosser   /// Create kernel launch parameters.
23079a947c2STobias Grosser   ///
23179a947c2STobias Grosser   /// @param Kernel        The kernel to create parameters for.
23279a947c2STobias Grosser   /// @param F             The kernel function that has been created.
23357693272STobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
23479a947c2STobias Grosser   ///
23579a947c2STobias Grosser   /// @returns A stack allocated array with pointers to the parameter
23679a947c2STobias Grosser   ///          values that are passed to the kernel.
23757693272STobias Grosser   Value *createLaunchParameters(ppcg_kernel *Kernel, Function *F,
23857693272STobias Grosser                                 SetVector<Value *> SubtreeValues);
23979a947c2STobias Grosser 
240*b513b491STobias Grosser   /// Create declarations for kernel variable.
241*b513b491STobias Grosser   ///
242*b513b491STobias Grosser   /// This includes shared memory declarations.
243*b513b491STobias Grosser   ///
244*b513b491STobias Grosser   /// @param Kernel        The kernel definition to create variables for.
245*b513b491STobias Grosser   /// @param FN            The function into which to generate the variables.
246*b513b491STobias Grosser   void createKernelVariables(ppcg_kernel *Kernel, Function *FN);
247*b513b491STobias Grosser 
24832837fe3STobias Grosser   /// Create GPU kernel.
24932837fe3STobias Grosser   ///
25032837fe3STobias Grosser   /// Code generate the kernel described by @p KernelStmt.
25132837fe3STobias Grosser   ///
25232837fe3STobias Grosser   /// @param KernelStmt The ast node to generate kernel code for.
25332837fe3STobias Grosser   void createKernel(__isl_take isl_ast_node *KernelStmt);
25432837fe3STobias Grosser 
25513c78e4dSTobias Grosser   /// Generate code that computes the size of an array.
25613c78e4dSTobias Grosser   ///
25713c78e4dSTobias Grosser   /// @param Array The array for which to compute a size.
25813c78e4dSTobias Grosser   Value *getArraySize(gpu_array_info *Array);
25913c78e4dSTobias Grosser 
26000bb5a99STobias Grosser   /// Prepare the kernel arguments for kernel code generation
26100bb5a99STobias Grosser   ///
26200bb5a99STobias Grosser   /// @param Kernel The kernel to generate code for.
26300bb5a99STobias Grosser   /// @param FN     The function created for the kernel.
26400bb5a99STobias Grosser   void prepareKernelArguments(ppcg_kernel *Kernel, Function *FN);
26500bb5a99STobias Grosser 
26632837fe3STobias Grosser   /// Create kernel function.
26732837fe3STobias Grosser   ///
26832837fe3STobias Grosser   /// Create a kernel function located in a newly created module that can serve
26932837fe3STobias Grosser   /// as target for device code generation. Set the Builder to point to the
27032837fe3STobias Grosser   /// start block of this newly created function.
27132837fe3STobias Grosser   ///
27232837fe3STobias Grosser   /// @param Kernel The kernel to generate code for.
273edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
274edb885cbSTobias Grosser   void createKernelFunction(ppcg_kernel *Kernel,
275edb885cbSTobias Grosser                             SetVector<Value *> &SubtreeValues);
27632837fe3STobias Grosser 
27732837fe3STobias Grosser   /// Create the declaration of a kernel function.
27832837fe3STobias Grosser   ///
27932837fe3STobias Grosser   /// The kernel function takes as arguments:
28032837fe3STobias Grosser   ///
28132837fe3STobias Grosser   ///   - One i8 pointer for each external array reference used in the kernel.
282f6044bd0STobias Grosser   ///   - Host iterators
283c84a1995STobias Grosser   ///   - Parameters
28432837fe3STobias Grosser   ///   - Other LLVM Value references (TODO)
28532837fe3STobias Grosser   ///
28632837fe3STobias Grosser   /// @param Kernel The kernel to generate the function declaration for.
287edb885cbSTobias Grosser   /// @param SubtreeValues The set of llvm::Values referenced by this kernel.
288edb885cbSTobias Grosser   ///
28932837fe3STobias Grosser   /// @returns The newly declared function.
290edb885cbSTobias Grosser   Function *createKernelFunctionDecl(ppcg_kernel *Kernel,
291edb885cbSTobias Grosser                                      SetVector<Value *> &SubtreeValues);
29232837fe3STobias Grosser 
293472f9654STobias Grosser   /// Insert intrinsic functions to obtain thread and block ids.
294472f9654STobias Grosser   ///
295472f9654STobias Grosser   /// @param The kernel to generate the intrinsic functions for.
296472f9654STobias Grosser   void insertKernelIntrinsics(ppcg_kernel *Kernel);
297472f9654STobias Grosser 
298*b513b491STobias Grosser   /// Create a global-to-shared or shared-to-global copy statement.
299*b513b491STobias Grosser   ///
300*b513b491STobias Grosser   /// @param CopyStmt The copy statement to generate code for
301*b513b491STobias Grosser   void createKernelCopy(ppcg_kernel_stmt *CopyStmt);
302*b513b491STobias Grosser 
303edb885cbSTobias Grosser   /// Create code for a ScopStmt called in @p Expr.
304edb885cbSTobias Grosser   ///
305edb885cbSTobias Grosser   /// @param Expr The expression containing the call.
306edb885cbSTobias Grosser   /// @param KernelStmt The kernel statement referenced in the call.
307edb885cbSTobias Grosser   void createScopStmt(isl_ast_expr *Expr, ppcg_kernel_stmt *KernelStmt);
308edb885cbSTobias Grosser 
3095260c041STobias Grosser   /// Create an in-kernel synchronization call.
3105260c041STobias Grosser   void createKernelSync();
3115260c041STobias Grosser 
31274dc3cb4STobias Grosser   /// Create a PTX assembly string for the current GPU kernel.
31374dc3cb4STobias Grosser   ///
31474dc3cb4STobias Grosser   /// @returns A string containing the corresponding PTX assembly code.
31574dc3cb4STobias Grosser   std::string createKernelASM();
31674dc3cb4STobias Grosser 
31774dc3cb4STobias Grosser   /// Remove references from the dominator tree to the kernel function @p F.
31874dc3cb4STobias Grosser   ///
31974dc3cb4STobias Grosser   /// @param F The function to remove references to.
32074dc3cb4STobias Grosser   void clearDominators(Function *F);
32174dc3cb4STobias Grosser 
32274dc3cb4STobias Grosser   /// Remove references from scalar evolution to the kernel function @p F.
32374dc3cb4STobias Grosser   ///
32474dc3cb4STobias Grosser   /// @param F The function to remove references to.
32574dc3cb4STobias Grosser   void clearScalarEvolution(Function *F);
32674dc3cb4STobias Grosser 
32774dc3cb4STobias Grosser   /// Remove references from loop info to the kernel function @p F.
32874dc3cb4STobias Grosser   ///
32974dc3cb4STobias Grosser   /// @param F The function to remove references to.
33074dc3cb4STobias Grosser   void clearLoops(Function *F);
33174dc3cb4STobias Grosser 
33232837fe3STobias Grosser   /// Finalize the generation of the kernel function.
33332837fe3STobias Grosser   ///
33432837fe3STobias Grosser   /// Free the LLVM-IR module corresponding to the kernel and -- if requested --
33532837fe3STobias Grosser   /// dump its IR to stderr.
33657793596STobias Grosser   ///
33757793596STobias Grosser   /// @returns The Assembly string of the kernel.
33857793596STobias Grosser   std::string finalizeKernelFunction();
339fa7b0802STobias Grosser 
3407287aeddSTobias Grosser   /// Create code that allocates memory to store arrays on device.
341fa7b0802STobias Grosser   void allocateDeviceArrays();
342fa7b0802STobias Grosser 
3437287aeddSTobias Grosser   /// Free all allocated device arrays.
3447287aeddSTobias Grosser   void freeDeviceArrays();
3457287aeddSTobias Grosser 
346fa7b0802STobias Grosser   /// Create a call to initialize the GPU context.
347fa7b0802STobias Grosser   ///
348fa7b0802STobias Grosser   /// @returns A pointer to the newly initialized context.
349fa7b0802STobias Grosser   Value *createCallInitContext();
350fa7b0802STobias Grosser 
35179a947c2STobias Grosser   /// Create a call to get the device pointer for a kernel allocation.
35279a947c2STobias Grosser   ///
35379a947c2STobias Grosser   /// @param Allocation The Polly GPU allocation
35479a947c2STobias Grosser   ///
35579a947c2STobias Grosser   /// @returns The device parameter corresponding to this allocation.
35679a947c2STobias Grosser   Value *createCallGetDevicePtr(Value *Allocation);
35779a947c2STobias Grosser 
358fa7b0802STobias Grosser   /// Create a call to free the GPU context.
359fa7b0802STobias Grosser   ///
360fa7b0802STobias Grosser   /// @param Context A pointer to an initialized GPU context.
361fa7b0802STobias Grosser   void createCallFreeContext(Value *Context);
362fa7b0802STobias Grosser 
3637287aeddSTobias Grosser   /// Create a call to allocate memory on the device.
3647287aeddSTobias Grosser   ///
3657287aeddSTobias Grosser   /// @param Size The size of memory to allocate
3667287aeddSTobias Grosser   ///
3677287aeddSTobias Grosser   /// @returns A pointer that identifies this allocation.
368fa7b0802STobias Grosser   Value *createCallAllocateMemoryForDevice(Value *Size);
3697287aeddSTobias Grosser 
3707287aeddSTobias Grosser   /// Create a call to free a device array.
3717287aeddSTobias Grosser   ///
3727287aeddSTobias Grosser   /// @param Array The device array to free.
3737287aeddSTobias Grosser   void createCallFreeDeviceMemory(Value *Array);
37413c78e4dSTobias Grosser 
37513c78e4dSTobias Grosser   /// Create a call to copy data from host to device.
37613c78e4dSTobias Grosser   ///
37713c78e4dSTobias Grosser   /// @param HostPtr A pointer to the host data that should be copied.
37813c78e4dSTobias Grosser   /// @param DevicePtr A device pointer specifying the location to copy to.
37913c78e4dSTobias Grosser   void createCallCopyFromHostToDevice(Value *HostPtr, Value *DevicePtr,
38013c78e4dSTobias Grosser                                       Value *Size);
38113c78e4dSTobias Grosser 
38213c78e4dSTobias Grosser   /// Create a call to copy data from device to host.
38313c78e4dSTobias Grosser   ///
38413c78e4dSTobias Grosser   /// @param DevicePtr A pointer to the device data that should be copied.
38513c78e4dSTobias Grosser   /// @param HostPtr A host pointer specifying the location to copy to.
38613c78e4dSTobias Grosser   void createCallCopyFromDeviceToHost(Value *DevicePtr, Value *HostPtr,
38713c78e4dSTobias Grosser                                       Value *Size);
38857793596STobias Grosser 
38957793596STobias Grosser   /// Create a call to get a kernel from an assembly string.
39057793596STobias Grosser   ///
39157793596STobias Grosser   /// @param Buffer The string describing the kernel.
39257793596STobias Grosser   /// @param Entry  The name of the kernel function to call.
39357793596STobias Grosser   ///
39457793596STobias Grosser   /// @returns A pointer to a kernel object
39557793596STobias Grosser   Value *createCallGetKernel(Value *Buffer, Value *Entry);
39657793596STobias Grosser 
39757793596STobias Grosser   /// Create a call to free a GPU kernel.
39857793596STobias Grosser   ///
39957793596STobias Grosser   /// @param GPUKernel THe kernel to free.
40057793596STobias Grosser   void createCallFreeKernel(Value *GPUKernel);
40179a947c2STobias Grosser 
40279a947c2STobias Grosser   /// Create a call to launch a GPU kernel.
40379a947c2STobias Grosser   ///
40479a947c2STobias Grosser   /// @param GPUKernel  The kernel to launch.
40579a947c2STobias Grosser   /// @param GridDimX   The size of the first grid dimension.
40679a947c2STobias Grosser   /// @param GridDimY   The size of the second grid dimension.
40779a947c2STobias Grosser   /// @param GridBlockX The size of the first block dimension.
40879a947c2STobias Grosser   /// @param GridBlockY The size of the second block dimension.
40979a947c2STobias Grosser   /// @param GridBlockZ The size of the third block dimension.
41079a947c2STobias Grosser   /// @param Paramters  A pointer to an array that contains itself pointers to
41179a947c2STobias Grosser   ///                   the parameter values passed for each kernel argument.
41279a947c2STobias Grosser   void createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
41379a947c2STobias Grosser                               Value *GridDimY, Value *BlockDimX,
41479a947c2STobias Grosser                               Value *BlockDimY, Value *BlockDimZ,
41579a947c2STobias Grosser                               Value *Parameters);
4161fb9b64dSTobias Grosser };
4171fb9b64dSTobias Grosser 
418fa7b0802STobias Grosser void GPUNodeBuilder::initializeAfterRTH() {
419fa7b0802STobias Grosser   GPUContext = createCallInitContext();
420fa7b0802STobias Grosser   allocateDeviceArrays();
421fa7b0802STobias Grosser }
422fa7b0802STobias Grosser 
423fa7b0802STobias Grosser void GPUNodeBuilder::finalize() {
4247287aeddSTobias Grosser   freeDeviceArrays();
425fa7b0802STobias Grosser   createCallFreeContext(GPUContext);
426fa7b0802STobias Grosser   IslNodeBuilder::finalize();
427fa7b0802STobias Grosser }
428fa7b0802STobias Grosser 
429fa7b0802STobias Grosser void GPUNodeBuilder::allocateDeviceArrays() {
430fa7b0802STobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
431fa7b0802STobias Grosser 
432fa7b0802STobias Grosser   for (int i = 0; i < Prog->n_array; ++i) {
433fa7b0802STobias Grosser     gpu_array_info *Array = &Prog->array[i];
43413c78e4dSTobias Grosser     auto *ScopArray = (ScopArrayInfo *)Array->user;
4357287aeddSTobias Grosser     std::string DevArrayName("p_dev_array_");
4367287aeddSTobias Grosser     DevArrayName.append(Array->name);
437fa7b0802STobias Grosser 
43813c78e4dSTobias Grosser     Value *ArraySize = getArraySize(Array);
4397287aeddSTobias Grosser     Value *DevArray = createCallAllocateMemoryForDevice(ArraySize);
4407287aeddSTobias Grosser     DevArray->setName(DevArrayName);
44113c78e4dSTobias Grosser     DeviceAllocations[ScopArray] = DevArray;
442fa7b0802STobias Grosser   }
443fa7b0802STobias Grosser 
444fa7b0802STobias Grosser   isl_ast_build_free(Build);
445fa7b0802STobias Grosser }
446fa7b0802STobias Grosser 
4477287aeddSTobias Grosser void GPUNodeBuilder::freeDeviceArrays() {
44813c78e4dSTobias Grosser   for (auto &Array : DeviceAllocations)
44913c78e4dSTobias Grosser     createCallFreeDeviceMemory(Array.second);
4507287aeddSTobias Grosser }
4517287aeddSTobias Grosser 
45257793596STobias Grosser Value *GPUNodeBuilder::createCallGetKernel(Value *Buffer, Value *Entry) {
45357793596STobias Grosser   const char *Name = "polly_getKernel";
45457793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
45557793596STobias Grosser   Function *F = M->getFunction(Name);
45657793596STobias Grosser 
45757793596STobias Grosser   // If F is not available, declare it.
45857793596STobias Grosser   if (!F) {
45957793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
46057793596STobias Grosser     std::vector<Type *> Args;
46157793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
46257793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
46357793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
46457793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
46557793596STobias Grosser   }
46657793596STobias Grosser 
46757793596STobias Grosser   return Builder.CreateCall(F, {Buffer, Entry});
46857793596STobias Grosser }
46957793596STobias Grosser 
47079a947c2STobias Grosser Value *GPUNodeBuilder::createCallGetDevicePtr(Value *Allocation) {
47179a947c2STobias Grosser   const char *Name = "polly_getDevicePtr";
47279a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
47379a947c2STobias Grosser   Function *F = M->getFunction(Name);
47479a947c2STobias Grosser 
47579a947c2STobias Grosser   // If F is not available, declare it.
47679a947c2STobias Grosser   if (!F) {
47779a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
47879a947c2STobias Grosser     std::vector<Type *> Args;
47979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
48079a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
48179a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
48279a947c2STobias Grosser   }
48379a947c2STobias Grosser 
48479a947c2STobias Grosser   return Builder.CreateCall(F, {Allocation});
48579a947c2STobias Grosser }
48679a947c2STobias Grosser 
48779a947c2STobias Grosser void GPUNodeBuilder::createCallLaunchKernel(Value *GPUKernel, Value *GridDimX,
48879a947c2STobias Grosser                                             Value *GridDimY, Value *BlockDimX,
48979a947c2STobias Grosser                                             Value *BlockDimY, Value *BlockDimZ,
49079a947c2STobias Grosser                                             Value *Parameters) {
49179a947c2STobias Grosser   const char *Name = "polly_launchKernel";
49279a947c2STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
49379a947c2STobias Grosser   Function *F = M->getFunction(Name);
49479a947c2STobias Grosser 
49579a947c2STobias Grosser   // If F is not available, declare it.
49679a947c2STobias Grosser   if (!F) {
49779a947c2STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
49879a947c2STobias Grosser     std::vector<Type *> Args;
49979a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
50079a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
50179a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
50279a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
50379a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
50479a947c2STobias Grosser     Args.push_back(Builder.getInt32Ty());
50579a947c2STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
50679a947c2STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
50779a947c2STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
50879a947c2STobias Grosser   }
50979a947c2STobias Grosser 
51079a947c2STobias Grosser   Builder.CreateCall(F, {GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
51179a947c2STobias Grosser                          BlockDimZ, Parameters});
51279a947c2STobias Grosser }
51379a947c2STobias Grosser 
51457793596STobias Grosser void GPUNodeBuilder::createCallFreeKernel(Value *GPUKernel) {
51557793596STobias Grosser   const char *Name = "polly_freeKernel";
51657793596STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
51757793596STobias Grosser   Function *F = M->getFunction(Name);
51857793596STobias Grosser 
51957793596STobias Grosser   // If F is not available, declare it.
52057793596STobias Grosser   if (!F) {
52157793596STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
52257793596STobias Grosser     std::vector<Type *> Args;
52357793596STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
52457793596STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
52557793596STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
52657793596STobias Grosser   }
52757793596STobias Grosser 
52857793596STobias Grosser   Builder.CreateCall(F, {GPUKernel});
52957793596STobias Grosser }
53057793596STobias Grosser 
5317287aeddSTobias Grosser void GPUNodeBuilder::createCallFreeDeviceMemory(Value *Array) {
5327287aeddSTobias Grosser   const char *Name = "polly_freeDeviceMemory";
5337287aeddSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
5347287aeddSTobias Grosser   Function *F = M->getFunction(Name);
5357287aeddSTobias Grosser 
5367287aeddSTobias Grosser   // If F is not available, declare it.
5377287aeddSTobias Grosser   if (!F) {
5387287aeddSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
5397287aeddSTobias Grosser     std::vector<Type *> Args;
5407287aeddSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
5417287aeddSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
5427287aeddSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
5437287aeddSTobias Grosser   }
5447287aeddSTobias Grosser 
5457287aeddSTobias Grosser   Builder.CreateCall(F, {Array});
5467287aeddSTobias Grosser }
5477287aeddSTobias Grosser 
548fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallAllocateMemoryForDevice(Value *Size) {
549fa7b0802STobias Grosser   const char *Name = "polly_allocateMemoryForDevice";
550fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
551fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
552fa7b0802STobias Grosser 
553fa7b0802STobias Grosser   // If F is not available, declare it.
554fa7b0802STobias Grosser   if (!F) {
555fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
556fa7b0802STobias Grosser     std::vector<Type *> Args;
557fa7b0802STobias Grosser     Args.push_back(Builder.getInt64Ty());
558fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
559fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
560fa7b0802STobias Grosser   }
561fa7b0802STobias Grosser 
562fa7b0802STobias Grosser   return Builder.CreateCall(F, {Size});
563fa7b0802STobias Grosser }
564fa7b0802STobias Grosser 
56513c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromHostToDevice(Value *HostData,
56613c78e4dSTobias Grosser                                                     Value *DeviceData,
56713c78e4dSTobias Grosser                                                     Value *Size) {
56813c78e4dSTobias Grosser   const char *Name = "polly_copyFromHostToDevice";
56913c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
57013c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
57113c78e4dSTobias Grosser 
57213c78e4dSTobias Grosser   // If F is not available, declare it.
57313c78e4dSTobias Grosser   if (!F) {
57413c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
57513c78e4dSTobias Grosser     std::vector<Type *> Args;
57613c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
57813c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
57913c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
58013c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
58113c78e4dSTobias Grosser   }
58213c78e4dSTobias Grosser 
58313c78e4dSTobias Grosser   Builder.CreateCall(F, {HostData, DeviceData, Size});
58413c78e4dSTobias Grosser }
58513c78e4dSTobias Grosser 
58613c78e4dSTobias Grosser void GPUNodeBuilder::createCallCopyFromDeviceToHost(Value *DeviceData,
58713c78e4dSTobias Grosser                                                     Value *HostData,
58813c78e4dSTobias Grosser                                                     Value *Size) {
58913c78e4dSTobias Grosser   const char *Name = "polly_copyFromDeviceToHost";
59013c78e4dSTobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
59113c78e4dSTobias Grosser   Function *F = M->getFunction(Name);
59213c78e4dSTobias Grosser 
59313c78e4dSTobias Grosser   // If F is not available, declare it.
59413c78e4dSTobias Grosser   if (!F) {
59513c78e4dSTobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
59613c78e4dSTobias Grosser     std::vector<Type *> Args;
59713c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
59813c78e4dSTobias Grosser     Args.push_back(Builder.getInt8PtrTy());
59913c78e4dSTobias Grosser     Args.push_back(Builder.getInt64Ty());
60013c78e4dSTobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
60113c78e4dSTobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
60213c78e4dSTobias Grosser   }
60313c78e4dSTobias Grosser 
60413c78e4dSTobias Grosser   Builder.CreateCall(F, {DeviceData, HostData, Size});
60513c78e4dSTobias Grosser }
60613c78e4dSTobias Grosser 
607fa7b0802STobias Grosser Value *GPUNodeBuilder::createCallInitContext() {
608fa7b0802STobias Grosser   const char *Name = "polly_initContext";
609fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
610fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
611fa7b0802STobias Grosser 
612fa7b0802STobias Grosser   // If F is not available, declare it.
613fa7b0802STobias Grosser   if (!F) {
614fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
615fa7b0802STobias Grosser     std::vector<Type *> Args;
616fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getInt8PtrTy(), Args, false);
617fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
618fa7b0802STobias Grosser   }
619fa7b0802STobias Grosser 
620fa7b0802STobias Grosser   return Builder.CreateCall(F, {});
621fa7b0802STobias Grosser }
622fa7b0802STobias Grosser 
623fa7b0802STobias Grosser void GPUNodeBuilder::createCallFreeContext(Value *Context) {
624fa7b0802STobias Grosser   const char *Name = "polly_freeContext";
625fa7b0802STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
626fa7b0802STobias Grosser   Function *F = M->getFunction(Name);
627fa7b0802STobias Grosser 
628fa7b0802STobias Grosser   // If F is not available, declare it.
629fa7b0802STobias Grosser   if (!F) {
630fa7b0802STobias Grosser     GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
631fa7b0802STobias Grosser     std::vector<Type *> Args;
632fa7b0802STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
633fa7b0802STobias Grosser     FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Args, false);
634fa7b0802STobias Grosser     F = Function::Create(Ty, Linkage, Name, M);
635fa7b0802STobias Grosser   }
636fa7b0802STobias Grosser 
637fa7b0802STobias Grosser   Builder.CreateCall(F, {Context});
638fa7b0802STobias Grosser }
639fa7b0802STobias Grosser 
6405260c041STobias Grosser /// Check if one string is a prefix of another.
6415260c041STobias Grosser ///
6425260c041STobias Grosser /// @param String The string in which to look for the prefix.
6435260c041STobias Grosser /// @param Prefix The prefix to look for.
6445260c041STobias Grosser static bool isPrefix(std::string String, std::string Prefix) {
6455260c041STobias Grosser   return String.find(Prefix) == 0;
6465260c041STobias Grosser }
6475260c041STobias Grosser 
64813c78e4dSTobias Grosser Value *GPUNodeBuilder::getArraySize(gpu_array_info *Array) {
64913c78e4dSTobias Grosser   isl_ast_build *Build = isl_ast_build_from_context(S.getContext());
65013c78e4dSTobias Grosser   Value *ArraySize = ConstantInt::get(Builder.getInt64Ty(), Array->size);
65113c78e4dSTobias Grosser 
65213c78e4dSTobias Grosser   if (!gpu_array_is_scalar(Array)) {
65313c78e4dSTobias Grosser     auto OffsetDimZero = isl_pw_aff_copy(Array->bound[0]);
65413c78e4dSTobias Grosser     isl_ast_expr *Res = isl_ast_build_expr_from_pw_aff(Build, OffsetDimZero);
65513c78e4dSTobias Grosser 
65613c78e4dSTobias Grosser     for (unsigned int i = 1; i < Array->n_index; i++) {
65713c78e4dSTobias Grosser       isl_pw_aff *Bound_I = isl_pw_aff_copy(Array->bound[i]);
65813c78e4dSTobias Grosser       isl_ast_expr *Expr = isl_ast_build_expr_from_pw_aff(Build, Bound_I);
65913c78e4dSTobias Grosser       Res = isl_ast_expr_mul(Res, Expr);
66013c78e4dSTobias Grosser     }
66113c78e4dSTobias Grosser 
66213c78e4dSTobias Grosser     Value *NumElements = ExprBuilder.create(Res);
66313c78e4dSTobias Grosser     ArraySize = Builder.CreateMul(ArraySize, NumElements);
66413c78e4dSTobias Grosser   }
66513c78e4dSTobias Grosser   isl_ast_build_free(Build);
66613c78e4dSTobias Grosser   return ArraySize;
66713c78e4dSTobias Grosser }
66813c78e4dSTobias Grosser 
66913c78e4dSTobias Grosser void GPUNodeBuilder::createDataTransfer(__isl_take isl_ast_node *TransferStmt,
67013c78e4dSTobias Grosser                                         enum DataDirection Direction) {
67113c78e4dSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(TransferStmt);
67213c78e4dSTobias Grosser   isl_ast_expr *Arg = isl_ast_expr_get_op_arg(Expr, 0);
67313c78e4dSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(Arg);
67413c78e4dSTobias Grosser   auto Array = (gpu_array_info *)isl_id_get_user(Id);
67513c78e4dSTobias Grosser   auto ScopArray = (ScopArrayInfo *)(Array->user);
67613c78e4dSTobias Grosser 
67713c78e4dSTobias Grosser   Value *Size = getArraySize(Array);
67813c78e4dSTobias Grosser   Value *HostPtr = ScopArray->getBasePtr();
67913c78e4dSTobias Grosser 
68013c78e4dSTobias Grosser   Value *DevPtr = DeviceAllocations[ScopArray];
68113c78e4dSTobias Grosser 
68213c78e4dSTobias Grosser   if (gpu_array_is_scalar(Array)) {
68313c78e4dSTobias Grosser     HostPtr = Builder.CreateAlloca(ScopArray->getElementType());
68413c78e4dSTobias Grosser     Builder.CreateStore(ScopArray->getBasePtr(), HostPtr);
68513c78e4dSTobias Grosser   }
68613c78e4dSTobias Grosser 
68713c78e4dSTobias Grosser   HostPtr = Builder.CreatePointerCast(HostPtr, Builder.getInt8PtrTy());
68813c78e4dSTobias Grosser 
68913c78e4dSTobias Grosser   if (Direction == HOST_TO_DEVICE)
69013c78e4dSTobias Grosser     createCallCopyFromHostToDevice(HostPtr, DevPtr, Size);
69113c78e4dSTobias Grosser   else
69213c78e4dSTobias Grosser     createCallCopyFromDeviceToHost(DevPtr, HostPtr, Size);
69313c78e4dSTobias Grosser 
69413c78e4dSTobias Grosser   isl_id_free(Id);
69513c78e4dSTobias Grosser   isl_ast_expr_free(Arg);
69613c78e4dSTobias Grosser   isl_ast_expr_free(Expr);
69713c78e4dSTobias Grosser   isl_ast_node_free(TransferStmt);
69813c78e4dSTobias Grosser }
69913c78e4dSTobias Grosser 
7001fb9b64dSTobias Grosser void GPUNodeBuilder::createUser(__isl_take isl_ast_node *UserStmt) {
70132837fe3STobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(UserStmt);
70232837fe3STobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
70332837fe3STobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
70432837fe3STobias Grosser   isl_id_free(Id);
70532837fe3STobias Grosser   isl_ast_expr_free(StmtExpr);
70632837fe3STobias Grosser 
70732837fe3STobias Grosser   const char *Str = isl_id_get_name(Id);
70832837fe3STobias Grosser   if (!strcmp(Str, "kernel")) {
70932837fe3STobias Grosser     createKernel(UserStmt);
71032837fe3STobias Grosser     isl_ast_expr_free(Expr);
71132837fe3STobias Grosser     return;
71232837fe3STobias Grosser   }
71332837fe3STobias Grosser 
71413c78e4dSTobias Grosser   if (isPrefix(Str, "to_device")) {
71513c78e4dSTobias Grosser     createDataTransfer(UserStmt, HOST_TO_DEVICE);
71632837fe3STobias Grosser     isl_ast_expr_free(Expr);
71713c78e4dSTobias Grosser     return;
71813c78e4dSTobias Grosser   }
71913c78e4dSTobias Grosser 
72013c78e4dSTobias Grosser   if (isPrefix(Str, "from_device")) {
72113c78e4dSTobias Grosser     createDataTransfer(UserStmt, DEVICE_TO_HOST);
72213c78e4dSTobias Grosser     isl_ast_expr_free(Expr);
72338fc0aedSTobias Grosser     return;
72438fc0aedSTobias Grosser   }
72538fc0aedSTobias Grosser 
7265260c041STobias Grosser   isl_id *Anno = isl_ast_node_get_annotation(UserStmt);
7275260c041STobias Grosser   struct ppcg_kernel_stmt *KernelStmt =
7285260c041STobias Grosser       (struct ppcg_kernel_stmt *)isl_id_get_user(Anno);
7295260c041STobias Grosser   isl_id_free(Anno);
7305260c041STobias Grosser 
7315260c041STobias Grosser   switch (KernelStmt->type) {
7325260c041STobias Grosser   case ppcg_kernel_domain:
733edb885cbSTobias Grosser     createScopStmt(Expr, KernelStmt);
7345260c041STobias Grosser     isl_ast_node_free(UserStmt);
7355260c041STobias Grosser     return;
7365260c041STobias Grosser   case ppcg_kernel_copy:
737*b513b491STobias Grosser     createKernelCopy(KernelStmt);
7385260c041STobias Grosser     isl_ast_expr_free(Expr);
7395260c041STobias Grosser     isl_ast_node_free(UserStmt);
7405260c041STobias Grosser     return;
7415260c041STobias Grosser   case ppcg_kernel_sync:
7425260c041STobias Grosser     createKernelSync();
7435260c041STobias Grosser     isl_ast_expr_free(Expr);
7445260c041STobias Grosser     isl_ast_node_free(UserStmt);
7455260c041STobias Grosser     return;
7465260c041STobias Grosser   }
7475260c041STobias Grosser 
7485260c041STobias Grosser   isl_ast_expr_free(Expr);
7495260c041STobias Grosser   isl_ast_node_free(UserStmt);
7505260c041STobias Grosser   return;
7515260c041STobias Grosser }
752*b513b491STobias Grosser void GPUNodeBuilder::createKernelCopy(ppcg_kernel_stmt *KernelStmt) {
753*b513b491STobias Grosser   isl_ast_expr *LocalIndex = isl_ast_expr_copy(KernelStmt->u.c.local_index);
754*b513b491STobias Grosser   LocalIndex = isl_ast_expr_address_of(LocalIndex);
755*b513b491STobias Grosser   Value *LocalAddr = ExprBuilder.create(LocalIndex);
756*b513b491STobias Grosser   isl_ast_expr *Index = isl_ast_expr_copy(KernelStmt->u.c.index);
757*b513b491STobias Grosser   Index = isl_ast_expr_address_of(Index);
758*b513b491STobias Grosser   Value *GlobalAddr = ExprBuilder.create(Index);
759*b513b491STobias Grosser 
760*b513b491STobias Grosser   if (KernelStmt->u.c.read) {
761*b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(GlobalAddr, "shared.read");
762*b513b491STobias Grosser     Builder.CreateStore(Load, LocalAddr);
763*b513b491STobias Grosser   } else {
764*b513b491STobias Grosser     LoadInst *Load = Builder.CreateLoad(LocalAddr, "shared.write");
765*b513b491STobias Grosser     Builder.CreateStore(Load, GlobalAddr);
766*b513b491STobias Grosser   }
767*b513b491STobias Grosser }
7685260c041STobias Grosser 
769edb885cbSTobias Grosser void GPUNodeBuilder::createScopStmt(isl_ast_expr *Expr,
770edb885cbSTobias Grosser                                     ppcg_kernel_stmt *KernelStmt) {
771edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
772edb885cbSTobias Grosser   isl_id_to_ast_expr *Indexes = KernelStmt->u.d.ref2expr;
773edb885cbSTobias Grosser 
774edb885cbSTobias Grosser   LoopToScevMapT LTS;
775edb885cbSTobias Grosser   LTS.insert(OutsideLoopIterations.begin(), OutsideLoopIterations.end());
776edb885cbSTobias Grosser 
777edb885cbSTobias Grosser   createSubstitutions(Expr, Stmt, LTS);
778edb885cbSTobias Grosser 
779edb885cbSTobias Grosser   if (Stmt->isBlockStmt())
780edb885cbSTobias Grosser     BlockGen.copyStmt(*Stmt, LTS, Indexes);
781edb885cbSTobias Grosser   else
782edb885cbSTobias Grosser     assert(0 && "Region statement not supported\n");
783edb885cbSTobias Grosser }
784edb885cbSTobias Grosser 
7855260c041STobias Grosser void GPUNodeBuilder::createKernelSync() {
7865260c041STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7875260c041STobias Grosser   auto *Sync = Intrinsic::getDeclaration(M, Intrinsic::nvvm_barrier0);
7885260c041STobias Grosser   Builder.CreateCall(Sync, {});
7895260c041STobias Grosser }
7905260c041STobias Grosser 
791edb885cbSTobias Grosser /// Collect llvm::Values referenced from @p Node
792edb885cbSTobias Grosser ///
793edb885cbSTobias Grosser /// This function only applies to isl_ast_nodes that are user_nodes referring
794edb885cbSTobias Grosser /// to a ScopStmt. All other node types are ignore.
795edb885cbSTobias Grosser ///
796edb885cbSTobias Grosser /// @param Node The node to collect references for.
797edb885cbSTobias Grosser /// @param User A user pointer used as storage for the data that is collected.
798edb885cbSTobias Grosser ///
799edb885cbSTobias Grosser /// @returns isl_bool_true if data could be collected successfully.
800edb885cbSTobias Grosser isl_bool collectReferencesInGPUStmt(__isl_keep isl_ast_node *Node, void *User) {
801edb885cbSTobias Grosser   if (isl_ast_node_get_type(Node) != isl_ast_node_user)
802edb885cbSTobias Grosser     return isl_bool_true;
803edb885cbSTobias Grosser 
804edb885cbSTobias Grosser   isl_ast_expr *Expr = isl_ast_node_user_get_expr(Node);
805edb885cbSTobias Grosser   isl_ast_expr *StmtExpr = isl_ast_expr_get_op_arg(Expr, 0);
806edb885cbSTobias Grosser   isl_id *Id = isl_ast_expr_get_id(StmtExpr);
807edb885cbSTobias Grosser   const char *Str = isl_id_get_name(Id);
808edb885cbSTobias Grosser   isl_id_free(Id);
809edb885cbSTobias Grosser   isl_ast_expr_free(StmtExpr);
810edb885cbSTobias Grosser   isl_ast_expr_free(Expr);
811edb885cbSTobias Grosser 
812edb885cbSTobias Grosser   if (!isPrefix(Str, "Stmt"))
813edb885cbSTobias Grosser     return isl_bool_true;
814edb885cbSTobias Grosser 
815edb885cbSTobias Grosser   Id = isl_ast_node_get_annotation(Node);
816edb885cbSTobias Grosser   auto *KernelStmt = (ppcg_kernel_stmt *)isl_id_get_user(Id);
817edb885cbSTobias Grosser   auto Stmt = (ScopStmt *)KernelStmt->u.d.stmt->stmt;
818edb885cbSTobias Grosser   isl_id_free(Id);
819edb885cbSTobias Grosser 
82000bb5a99STobias Grosser   addReferencesFromStmt(Stmt, User, false /* CreateScalarRefs */);
821edb885cbSTobias Grosser 
822edb885cbSTobias Grosser   return isl_bool_true;
823edb885cbSTobias Grosser }
824edb885cbSTobias Grosser 
825edb885cbSTobias Grosser SetVector<Value *> GPUNodeBuilder::getReferencesInKernel(ppcg_kernel *Kernel) {
826edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues;
827edb885cbSTobias Grosser   SetVector<const SCEV *> SCEVs;
828edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
829edb885cbSTobias Grosser   SubtreeReferences References = {
830edb885cbSTobias Grosser       LI, SE, S, ValueMap, SubtreeValues, SCEVs, getBlockGenerator()};
831edb885cbSTobias Grosser 
832edb885cbSTobias Grosser   for (const auto &I : IDToValue)
833edb885cbSTobias Grosser     SubtreeValues.insert(I.second);
834edb885cbSTobias Grosser 
835edb885cbSTobias Grosser   isl_ast_node_foreach_descendant_top_down(
836edb885cbSTobias Grosser       Kernel->tree, collectReferencesInGPUStmt, &References);
837edb885cbSTobias Grosser 
838edb885cbSTobias Grosser   for (const SCEV *Expr : SCEVs)
839edb885cbSTobias Grosser     findValues(Expr, SE, SubtreeValues);
840edb885cbSTobias Grosser 
841edb885cbSTobias Grosser   for (auto &SAI : S.arrays())
842d7754a12SRoman Gareev     SubtreeValues.remove(SAI->getBasePtr());
843edb885cbSTobias Grosser 
844edb885cbSTobias Grosser   isl_space *Space = S.getParamSpace();
845edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
846edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
847edb885cbSTobias Grosser     assert(IDToValue.count(Id));
848edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
849edb885cbSTobias Grosser     SubtreeValues.remove(Val);
850edb885cbSTobias Grosser     isl_id_free(Id);
851edb885cbSTobias Grosser   }
852edb885cbSTobias Grosser   isl_space_free(Space);
853edb885cbSTobias Grosser 
854edb885cbSTobias Grosser   for (long i = 0; i < isl_space_dim(Kernel->space, isl_dim_set); i++) {
855edb885cbSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
856edb885cbSTobias Grosser     assert(IDToValue.count(Id));
857edb885cbSTobias Grosser     Value *Val = IDToValue[Id];
858edb885cbSTobias Grosser     SubtreeValues.remove(Val);
859edb885cbSTobias Grosser     isl_id_free(Id);
860edb885cbSTobias Grosser   }
861edb885cbSTobias Grosser 
862edb885cbSTobias Grosser   return SubtreeValues;
863edb885cbSTobias Grosser }
864edb885cbSTobias Grosser 
86574dc3cb4STobias Grosser void GPUNodeBuilder::clearDominators(Function *F) {
86674dc3cb4STobias Grosser   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
86774dc3cb4STobias Grosser   std::vector<BasicBlock *> Nodes;
86874dc3cb4STobias Grosser   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
86974dc3cb4STobias Grosser     Nodes.push_back(I->getBlock());
87074dc3cb4STobias Grosser 
87174dc3cb4STobias Grosser   for (BasicBlock *BB : Nodes)
87274dc3cb4STobias Grosser     DT.eraseNode(BB);
87374dc3cb4STobias Grosser }
87474dc3cb4STobias Grosser 
87574dc3cb4STobias Grosser void GPUNodeBuilder::clearScalarEvolution(Function *F) {
87674dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
87774dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
87874dc3cb4STobias Grosser     if (L)
87974dc3cb4STobias Grosser       SE.forgetLoop(L);
88074dc3cb4STobias Grosser   }
88174dc3cb4STobias Grosser }
88274dc3cb4STobias Grosser 
88374dc3cb4STobias Grosser void GPUNodeBuilder::clearLoops(Function *F) {
88474dc3cb4STobias Grosser   for (BasicBlock &BB : *F) {
88574dc3cb4STobias Grosser     Loop *L = LI.getLoopFor(&BB);
88674dc3cb4STobias Grosser     if (L)
88774dc3cb4STobias Grosser       SE.forgetLoop(L);
88874dc3cb4STobias Grosser     LI.removeBlock(&BB);
88974dc3cb4STobias Grosser   }
89074dc3cb4STobias Grosser }
89174dc3cb4STobias Grosser 
89279a947c2STobias Grosser std::tuple<Value *, Value *> GPUNodeBuilder::getGridSizes(ppcg_kernel *Kernel) {
89379a947c2STobias Grosser   std::vector<Value *> Sizes;
89479a947c2STobias Grosser   isl_ast_build *Context = isl_ast_build_from_context(S.getContext());
89579a947c2STobias Grosser 
89679a947c2STobias Grosser   for (long i = 0; i < Kernel->n_grid; i++) {
89779a947c2STobias Grosser     isl_pw_aff *Size = isl_multi_pw_aff_get_pw_aff(Kernel->grid_size, i);
89879a947c2STobias Grosser     isl_ast_expr *GridSize = isl_ast_build_expr_from_pw_aff(Context, Size);
89979a947c2STobias Grosser     Value *Res = ExprBuilder.create(GridSize);
90079a947c2STobias Grosser     Res = Builder.CreateTrunc(Res, Builder.getInt32Ty());
90179a947c2STobias Grosser     Sizes.push_back(Res);
90279a947c2STobias Grosser   }
90379a947c2STobias Grosser   isl_ast_build_free(Context);
90479a947c2STobias Grosser 
90579a947c2STobias Grosser   for (long i = Kernel->n_grid; i < 3; i++)
90679a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
90779a947c2STobias Grosser 
90879a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1]);
90979a947c2STobias Grosser }
91079a947c2STobias Grosser 
91179a947c2STobias Grosser std::tuple<Value *, Value *, Value *>
91279a947c2STobias Grosser GPUNodeBuilder::getBlockSizes(ppcg_kernel *Kernel) {
91379a947c2STobias Grosser   std::vector<Value *> Sizes;
91479a947c2STobias Grosser 
91579a947c2STobias Grosser   for (long i = 0; i < Kernel->n_block; i++) {
91679a947c2STobias Grosser     Value *Res = ConstantInt::get(Builder.getInt32Ty(), Kernel->block_dim[i]);
91779a947c2STobias Grosser     Sizes.push_back(Res);
91879a947c2STobias Grosser   }
91979a947c2STobias Grosser 
92079a947c2STobias Grosser   for (long i = Kernel->n_block; i < 3; i++)
92179a947c2STobias Grosser     Sizes.push_back(ConstantInt::get(Builder.getInt32Ty(), 1));
92279a947c2STobias Grosser 
92379a947c2STobias Grosser   return std::make_tuple(Sizes[0], Sizes[1], Sizes[2]);
92479a947c2STobias Grosser }
92579a947c2STobias Grosser 
92657693272STobias Grosser Value *
92757693272STobias Grosser GPUNodeBuilder::createLaunchParameters(ppcg_kernel *Kernel, Function *F,
92857693272STobias Grosser                                        SetVector<Value *> SubtreeValues) {
9294e18d71cSTobias Grosser   Type *ArrayTy = ArrayType::get(Builder.getInt8PtrTy(),
9304e18d71cSTobias Grosser                                  std::distance(F->arg_begin(), F->arg_end()));
93179a947c2STobias Grosser 
93279a947c2STobias Grosser   BasicBlock *EntryBlock =
93379a947c2STobias Grosser       &Builder.GetInsertBlock()->getParent()->getEntryBlock();
93479a947c2STobias Grosser   std::string Launch = "polly_launch_" + std::to_string(Kernel->id);
93579a947c2STobias Grosser   Instruction *Parameters =
93679a947c2STobias Grosser       new AllocaInst(ArrayTy, Launch + "_params", EntryBlock->getTerminator());
93779a947c2STobias Grosser 
93879a947c2STobias Grosser   int Index = 0;
93979a947c2STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
94079a947c2STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
94179a947c2STobias Grosser       continue;
94279a947c2STobias Grosser 
94379a947c2STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
94479a947c2STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(Id);
94579a947c2STobias Grosser 
94679a947c2STobias Grosser     Value *DevArray = DeviceAllocations[(ScopArrayInfo *)SAI];
94779a947c2STobias Grosser     DevArray = createCallGetDevicePtr(DevArray);
94879a947c2STobias Grosser     Instruction *Param = new AllocaInst(
94979a947c2STobias Grosser         Builder.getInt8PtrTy(), Launch + "_param_" + std::to_string(Index),
95079a947c2STobias Grosser         EntryBlock->getTerminator());
95179a947c2STobias Grosser     Builder.CreateStore(DevArray, Param);
95244143bb9STobias Grosser     Value *Slot = Builder.CreateGEP(
95344143bb9STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
95479a947c2STobias Grosser     Value *ParamTyped =
95579a947c2STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
95679a947c2STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
95779a947c2STobias Grosser     Index++;
95879a947c2STobias Grosser   }
95979a947c2STobias Grosser 
960a490147cSTobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
961a490147cSTobias Grosser 
962a490147cSTobias Grosser   for (long i = 0; i < NumHostIters; i++) {
963a490147cSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
964a490147cSTobias Grosser     Value *Val = IDToValue[Id];
965a490147cSTobias Grosser     isl_id_free(Id);
966a490147cSTobias Grosser     Instruction *Param = new AllocaInst(
967a490147cSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
968a490147cSTobias Grosser         EntryBlock->getTerminator());
969a490147cSTobias Grosser     Builder.CreateStore(Val, Param);
970a490147cSTobias Grosser     Value *Slot = Builder.CreateGEP(
971a490147cSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
972a490147cSTobias Grosser     Value *ParamTyped =
973a490147cSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
974a490147cSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
975a490147cSTobias Grosser     Index++;
976a490147cSTobias Grosser   }
977a490147cSTobias Grosser 
978d8b94bcaSTobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
979d8b94bcaSTobias Grosser 
980d8b94bcaSTobias Grosser   for (long i = 0; i < NumVars; i++) {
981d8b94bcaSTobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
982d8b94bcaSTobias Grosser     Value *Val = IDToValue[Id];
983d8b94bcaSTobias Grosser     isl_id_free(Id);
984d8b94bcaSTobias Grosser     Instruction *Param = new AllocaInst(
985d8b94bcaSTobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
986d8b94bcaSTobias Grosser         EntryBlock->getTerminator());
987d8b94bcaSTobias Grosser     Builder.CreateStore(Val, Param);
988d8b94bcaSTobias Grosser     Value *Slot = Builder.CreateGEP(
989d8b94bcaSTobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
990d8b94bcaSTobias Grosser     Value *ParamTyped =
991d8b94bcaSTobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
992d8b94bcaSTobias Grosser     Builder.CreateStore(ParamTyped, Slot);
993d8b94bcaSTobias Grosser     Index++;
994d8b94bcaSTobias Grosser   }
995d8b94bcaSTobias Grosser 
99657693272STobias Grosser   for (auto Val : SubtreeValues) {
99757693272STobias Grosser     Instruction *Param = new AllocaInst(
99857693272STobias Grosser         Val->getType(), Launch + "_param_" + std::to_string(Index),
99957693272STobias Grosser         EntryBlock->getTerminator());
100057693272STobias Grosser     Builder.CreateStore(Val, Param);
100157693272STobias Grosser     Value *Slot = Builder.CreateGEP(
100257693272STobias Grosser         Parameters, {Builder.getInt64(0), Builder.getInt64(Index)});
100357693272STobias Grosser     Value *ParamTyped =
100457693272STobias Grosser         Builder.CreatePointerCast(Param, Builder.getInt8PtrTy());
100557693272STobias Grosser     Builder.CreateStore(ParamTyped, Slot);
100657693272STobias Grosser     Index++;
100757693272STobias Grosser   }
100857693272STobias Grosser 
100979a947c2STobias Grosser   auto Location = EntryBlock->getTerminator();
101079a947c2STobias Grosser   return new BitCastInst(Parameters, Builder.getInt8PtrTy(),
101179a947c2STobias Grosser                          Launch + "_params_i8ptr", Location);
101279a947c2STobias Grosser }
101379a947c2STobias Grosser 
101432837fe3STobias Grosser void GPUNodeBuilder::createKernel(__isl_take isl_ast_node *KernelStmt) {
101532837fe3STobias Grosser   isl_id *Id = isl_ast_node_get_annotation(KernelStmt);
101632837fe3STobias Grosser   ppcg_kernel *Kernel = (ppcg_kernel *)isl_id_get_user(Id);
101732837fe3STobias Grosser   isl_id_free(Id);
101832837fe3STobias Grosser   isl_ast_node_free(KernelStmt);
101932837fe3STobias Grosser 
1020edb885cbSTobias Grosser   SetVector<Value *> SubtreeValues = getReferencesInKernel(Kernel);
1021edb885cbSTobias Grosser 
102232837fe3STobias Grosser   assert(Kernel->tree && "Device AST of kernel node is empty");
102332837fe3STobias Grosser 
102432837fe3STobias Grosser   Instruction &HostInsertPoint = *Builder.GetInsertPoint();
1025472f9654STobias Grosser   IslExprBuilder::IDToValueTy HostIDs = IDToValue;
1026edb885cbSTobias Grosser   ValueMapT HostValueMap = ValueMap;
102732837fe3STobias Grosser 
1028edb885cbSTobias Grosser   SetVector<const Loop *> Loops;
1029edb885cbSTobias Grosser 
1030edb885cbSTobias Grosser   // Create for all loops we depend on values that contain the current loop
1031edb885cbSTobias Grosser   // iteration. These values are necessary to generate code for SCEVs that
1032edb885cbSTobias Grosser   // depend on such loops. As a result we need to pass them to the subfunction.
1033edb885cbSTobias Grosser   for (const Loop *L : Loops) {
1034edb885cbSTobias Grosser     const SCEV *OuterLIV = SE.getAddRecExpr(SE.getUnknown(Builder.getInt64(0)),
1035edb885cbSTobias Grosser                                             SE.getUnknown(Builder.getInt64(1)),
1036edb885cbSTobias Grosser                                             L, SCEV::FlagAnyWrap);
1037edb885cbSTobias Grosser     Value *V = generateSCEV(OuterLIV);
1038edb885cbSTobias Grosser     OutsideLoopIterations[L] = SE.getUnknown(V);
1039edb885cbSTobias Grosser     SubtreeValues.insert(V);
1040edb885cbSTobias Grosser   }
1041edb885cbSTobias Grosser 
1042edb885cbSTobias Grosser   createKernelFunction(Kernel, SubtreeValues);
104332837fe3STobias Grosser 
104459ab0705STobias Grosser   create(isl_ast_node_copy(Kernel->tree));
104559ab0705STobias Grosser 
104674dc3cb4STobias Grosser   Function *F = Builder.GetInsertBlock()->getParent();
104774dc3cb4STobias Grosser   clearDominators(F);
104874dc3cb4STobias Grosser   clearScalarEvolution(F);
104974dc3cb4STobias Grosser   clearLoops(F);
105074dc3cb4STobias Grosser 
105132837fe3STobias Grosser   Builder.SetInsertPoint(&HostInsertPoint);
1052472f9654STobias Grosser   IDToValue = HostIDs;
105332837fe3STobias Grosser 
1054edb885cbSTobias Grosser   ValueMap = HostValueMap;
1055edb885cbSTobias Grosser   ScalarMap.clear();
1056edb885cbSTobias Grosser   PHIOpMap.clear();
1057edb885cbSTobias Grosser   EscapeMap.clear();
1058edb885cbSTobias Grosser   IDToSAI.clear();
105974dc3cb4STobias Grosser   Annotator.resetAlternativeAliasBases();
106074dc3cb4STobias Grosser   for (auto &BasePtr : LocalArrays)
106174dc3cb4STobias Grosser     S.invalidateScopArrayInfo(BasePtr, ScopArrayInfo::MK_Array);
106274dc3cb4STobias Grosser   LocalArrays.clear();
1063edb885cbSTobias Grosser 
106457693272STobias Grosser   Value *Parameters = createLaunchParameters(Kernel, F, SubtreeValues);
106579a947c2STobias Grosser 
106657793596STobias Grosser   std::string ASMString = finalizeKernelFunction();
106757793596STobias Grosser   std::string Name = "kernel_" + std::to_string(Kernel->id);
106857793596STobias Grosser   Value *KernelString = Builder.CreateGlobalStringPtr(ASMString, Name);
106957793596STobias Grosser   Value *NameString = Builder.CreateGlobalStringPtr(Name, Name + "_name");
107057793596STobias Grosser   Value *GPUKernel = createCallGetKernel(KernelString, NameString);
107179a947c2STobias Grosser 
107279a947c2STobias Grosser   Value *GridDimX, *GridDimY;
107379a947c2STobias Grosser   std::tie(GridDimX, GridDimY) = getGridSizes(Kernel);
107479a947c2STobias Grosser 
107579a947c2STobias Grosser   Value *BlockDimX, *BlockDimY, *BlockDimZ;
107679a947c2STobias Grosser   std::tie(BlockDimX, BlockDimY, BlockDimZ) = getBlockSizes(Kernel);
107779a947c2STobias Grosser 
107879a947c2STobias Grosser   createCallLaunchKernel(GPUKernel, GridDimX, GridDimY, BlockDimX, BlockDimY,
107979a947c2STobias Grosser                          BlockDimZ, Parameters);
108057793596STobias Grosser   createCallFreeKernel(GPUKernel);
1081*b513b491STobias Grosser 
1082*b513b491STobias Grosser   for (auto Id : KernelIds)
1083*b513b491STobias Grosser     isl_id_free(Id);
1084*b513b491STobias Grosser 
1085*b513b491STobias Grosser   KernelIds.clear();
108632837fe3STobias Grosser }
108732837fe3STobias Grosser 
108832837fe3STobias Grosser /// Compute the DataLayout string for the NVPTX backend.
108932837fe3STobias Grosser ///
109032837fe3STobias Grosser /// @param is64Bit Are we looking for a 64 bit architecture?
109132837fe3STobias Grosser static std::string computeNVPTXDataLayout(bool is64Bit) {
109232837fe3STobias Grosser   std::string Ret = "e";
109332837fe3STobias Grosser 
109432837fe3STobias Grosser   if (!is64Bit)
109532837fe3STobias Grosser     Ret += "-p:32:32";
109632837fe3STobias Grosser 
109732837fe3STobias Grosser   Ret += "-i64:64-v16:16-v32:32-n16:32:64";
109832837fe3STobias Grosser 
109932837fe3STobias Grosser   return Ret;
110032837fe3STobias Grosser }
110132837fe3STobias Grosser 
1102edb885cbSTobias Grosser Function *
1103edb885cbSTobias Grosser GPUNodeBuilder::createKernelFunctionDecl(ppcg_kernel *Kernel,
1104edb885cbSTobias Grosser                                          SetVector<Value *> &SubtreeValues) {
110532837fe3STobias Grosser   std::vector<Type *> Args;
110632837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
110732837fe3STobias Grosser 
110832837fe3STobias Grosser   for (long i = 0; i < Prog->n_array; i++) {
110932837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
111032837fe3STobias Grosser       continue;
111132837fe3STobias Grosser 
111232837fe3STobias Grosser     Args.push_back(Builder.getInt8PtrTy());
111332837fe3STobias Grosser   }
111432837fe3STobias Grosser 
1115f6044bd0STobias Grosser   int NumHostIters = isl_space_dim(Kernel->space, isl_dim_set);
1116f6044bd0STobias Grosser 
1117f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++)
1118f6044bd0STobias Grosser     Args.push_back(Builder.getInt64Ty());
1119f6044bd0STobias Grosser 
1120c84a1995STobias Grosser   int NumVars = isl_space_dim(Kernel->space, isl_dim_param);
1121c84a1995STobias Grosser 
1122c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++)
1123c84a1995STobias Grosser     Args.push_back(Builder.getInt64Ty());
1124c84a1995STobias Grosser 
1125edb885cbSTobias Grosser   for (auto *V : SubtreeValues)
1126edb885cbSTobias Grosser     Args.push_back(V->getType());
1127edb885cbSTobias Grosser 
112832837fe3STobias Grosser   auto *FT = FunctionType::get(Builder.getVoidTy(), Args, false);
112932837fe3STobias Grosser   auto *FN = Function::Create(FT, Function::ExternalLinkage, Identifier,
113032837fe3STobias Grosser                               GPUModule.get());
113132837fe3STobias Grosser   FN->setCallingConv(CallingConv::PTX_Kernel);
113232837fe3STobias Grosser 
113332837fe3STobias Grosser   auto Arg = FN->arg_begin();
113432837fe3STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
113532837fe3STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
113632837fe3STobias Grosser       continue;
113732837fe3STobias Grosser 
1138edb885cbSTobias Grosser     Arg->setName(Kernel->array[i].array->name);
1139edb885cbSTobias Grosser 
1140edb885cbSTobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
1141edb885cbSTobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
1142edb885cbSTobias Grosser     Type *EleTy = SAI->getElementType();
1143edb885cbSTobias Grosser     Value *Val = &*Arg;
1144edb885cbSTobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1145edb885cbSTobias Grosser     isl_ast_build *Build =
1146edb885cbSTobias Grosser         isl_ast_build_from_context(isl_set_copy(Prog->context));
1147edb885cbSTobias Grosser     for (long j = 1; j < Kernel->array[i].array->n_index; j++) {
1148edb885cbSTobias Grosser       isl_ast_expr *DimSize = isl_ast_build_expr_from_pw_aff(
1149edb885cbSTobias Grosser           Build, isl_pw_aff_copy(Kernel->array[i].array->bound[j]));
1150edb885cbSTobias Grosser       auto V = ExprBuilder.create(DimSize);
1151edb885cbSTobias Grosser       Sizes.push_back(SE.getSCEV(V));
1152edb885cbSTobias Grosser     }
1153edb885cbSTobias Grosser     const ScopArrayInfo *SAIRep =
1154edb885cbSTobias Grosser         S.getOrCreateScopArrayInfo(Val, EleTy, Sizes, ScopArrayInfo::MK_Array);
115574dc3cb4STobias Grosser     LocalArrays.push_back(Val);
1156edb885cbSTobias Grosser 
1157edb885cbSTobias Grosser     isl_ast_build_free(Build);
1158*b513b491STobias Grosser     KernelIds.push_back(Id);
1159edb885cbSTobias Grosser     IDToSAI[Id] = SAIRep;
116032837fe3STobias Grosser     Arg++;
116132837fe3STobias Grosser   }
116232837fe3STobias Grosser 
1163f6044bd0STobias Grosser   for (long i = 0; i < NumHostIters; i++) {
1164f6044bd0STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_set, i);
1165f6044bd0STobias Grosser     Arg->setName(isl_id_get_name(Id));
1166f6044bd0STobias Grosser     IDToValue[Id] = &*Arg;
1167f6044bd0STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1168f6044bd0STobias Grosser     Arg++;
1169f6044bd0STobias Grosser   }
1170f6044bd0STobias Grosser 
1171c84a1995STobias Grosser   for (long i = 0; i < NumVars; i++) {
1172c84a1995STobias Grosser     isl_id *Id = isl_space_get_dim_id(Kernel->space, isl_dim_param, i);
1173c84a1995STobias Grosser     Arg->setName(isl_id_get_name(Id));
1174c84a1995STobias Grosser     IDToValue[Id] = &*Arg;
1175c84a1995STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1176c84a1995STobias Grosser     Arg++;
1177c84a1995STobias Grosser   }
1178c84a1995STobias Grosser 
1179edb885cbSTobias Grosser   for (auto *V : SubtreeValues) {
1180edb885cbSTobias Grosser     Arg->setName(V->getName());
1181edb885cbSTobias Grosser     ValueMap[V] = &*Arg;
1182edb885cbSTobias Grosser     Arg++;
1183edb885cbSTobias Grosser   }
1184edb885cbSTobias Grosser 
118532837fe3STobias Grosser   return FN;
118632837fe3STobias Grosser }
118732837fe3STobias Grosser 
1188472f9654STobias Grosser void GPUNodeBuilder::insertKernelIntrinsics(ppcg_kernel *Kernel) {
1189472f9654STobias Grosser   Intrinsic::ID IntrinsicsBID[] = {Intrinsic::nvvm_read_ptx_sreg_ctaid_x,
1190472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_ctaid_y};
1191472f9654STobias Grosser 
1192472f9654STobias Grosser   Intrinsic::ID IntrinsicsTID[] = {Intrinsic::nvvm_read_ptx_sreg_tid_x,
1193472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_y,
1194472f9654STobias Grosser                                    Intrinsic::nvvm_read_ptx_sreg_tid_z};
1195472f9654STobias Grosser 
1196472f9654STobias Grosser   auto addId = [this](__isl_take isl_id *Id, Intrinsic::ID Intr) mutable {
1197472f9654STobias Grosser     std::string Name = isl_id_get_name(Id);
1198472f9654STobias Grosser     Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1199472f9654STobias Grosser     Function *IntrinsicFn = Intrinsic::getDeclaration(M, Intr);
1200472f9654STobias Grosser     Value *Val = Builder.CreateCall(IntrinsicFn, {});
1201472f9654STobias Grosser     Val = Builder.CreateIntCast(Val, Builder.getInt64Ty(), false, Name);
1202472f9654STobias Grosser     IDToValue[Id] = Val;
1203472f9654STobias Grosser     KernelIDs.insert(std::unique_ptr<isl_id, IslIdDeleter>(Id));
1204472f9654STobias Grosser   };
1205472f9654STobias Grosser 
1206472f9654STobias Grosser   for (int i = 0; i < Kernel->n_grid; ++i) {
1207472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->block_ids, i);
1208472f9654STobias Grosser     addId(Id, IntrinsicsBID[i]);
1209472f9654STobias Grosser   }
1210472f9654STobias Grosser 
1211472f9654STobias Grosser   for (int i = 0; i < Kernel->n_block; ++i) {
1212472f9654STobias Grosser     isl_id *Id = isl_id_list_get_id(Kernel->thread_ids, i);
1213472f9654STobias Grosser     addId(Id, IntrinsicsTID[i]);
1214472f9654STobias Grosser   }
1215472f9654STobias Grosser }
1216472f9654STobias Grosser 
121700bb5a99STobias Grosser void GPUNodeBuilder::prepareKernelArguments(ppcg_kernel *Kernel, Function *FN) {
121800bb5a99STobias Grosser   auto Arg = FN->arg_begin();
121900bb5a99STobias Grosser   for (long i = 0; i < Kernel->n_array; i++) {
122000bb5a99STobias Grosser     if (!ppcg_kernel_requires_array_argument(Kernel, i))
122100bb5a99STobias Grosser       continue;
122200bb5a99STobias Grosser 
122300bb5a99STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Prog->array[i].space, isl_dim_set);
122400bb5a99STobias Grosser     const ScopArrayInfo *SAI = ScopArrayInfo::getFromId(isl_id_copy(Id));
122500bb5a99STobias Grosser     isl_id_free(Id);
122600bb5a99STobias Grosser 
122700bb5a99STobias Grosser     if (SAI->getNumberOfDimensions() > 0) {
122800bb5a99STobias Grosser       Arg++;
122900bb5a99STobias Grosser       continue;
123000bb5a99STobias Grosser     }
123100bb5a99STobias Grosser 
123200bb5a99STobias Grosser     Value *Alloca = BlockGen.getOrCreateScalarAlloca(SAI->getBasePtr());
123300bb5a99STobias Grosser     Value *ArgPtr = &*Arg;
123400bb5a99STobias Grosser     Type *TypePtr = SAI->getElementType()->getPointerTo();
123500bb5a99STobias Grosser     Value *TypedArgPtr = Builder.CreatePointerCast(ArgPtr, TypePtr);
123600bb5a99STobias Grosser     Value *Val = Builder.CreateLoad(TypedArgPtr);
123700bb5a99STobias Grosser     Builder.CreateStore(Val, Alloca);
123800bb5a99STobias Grosser 
123900bb5a99STobias Grosser     Arg++;
124000bb5a99STobias Grosser   }
124100bb5a99STobias Grosser }
124200bb5a99STobias Grosser 
1243*b513b491STobias Grosser void GPUNodeBuilder::createKernelVariables(ppcg_kernel *Kernel, Function *FN) {
1244*b513b491STobias Grosser   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1245*b513b491STobias Grosser 
1246*b513b491STobias Grosser   for (int i = 0; i < Kernel->n_var; ++i) {
1247*b513b491STobias Grosser     struct ppcg_kernel_var &Var = Kernel->var[i];
1248*b513b491STobias Grosser     isl_id *Id = isl_space_get_tuple_id(Var.array->space, isl_dim_set);
1249*b513b491STobias Grosser     Type *EleTy = ScopArrayInfo::getFromId(Id)->getElementType();
1250*b513b491STobias Grosser 
1251*b513b491STobias Grosser     SmallVector<const SCEV *, 4> Sizes;
1252*b513b491STobias Grosser     isl_val *V0 = isl_vec_get_element_val(Var.size, 0);
1253*b513b491STobias Grosser     long Bound = isl_val_get_num_si(V0);
1254*b513b491STobias Grosser     isl_val_free(V0);
1255*b513b491STobias Grosser     Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1256*b513b491STobias Grosser 
1257*b513b491STobias Grosser     ArrayType *ArrayTy = ArrayType::get(EleTy, Bound);
1258*b513b491STobias Grosser     for (unsigned int j = 1; j < Var.array->n_index; ++j) {
1259*b513b491STobias Grosser       isl_val *Val = isl_vec_get_element_val(Var.size, j);
1260*b513b491STobias Grosser       Bound = isl_val_get_num_si(Val);
1261*b513b491STobias Grosser       isl_val_free(Val);
1262*b513b491STobias Grosser       Sizes.push_back(S.getSE()->getConstant(Builder.getInt64Ty(), Bound));
1263*b513b491STobias Grosser       ArrayTy = ArrayType::get(ArrayTy, Bound);
1264*b513b491STobias Grosser     }
1265*b513b491STobias Grosser 
1266*b513b491STobias Grosser     assert(Var.type == ppcg_access_shared && "Only shared memory supported");
1267*b513b491STobias Grosser 
1268*b513b491STobias Grosser     GlobalVariable *SharedVar = new GlobalVariable(
1269*b513b491STobias Grosser         *M, ArrayTy, false, GlobalValue::InternalLinkage, 0, Var.name, nullptr,
1270*b513b491STobias Grosser         GlobalValue::ThreadLocalMode::NotThreadLocal, 3);
1271*b513b491STobias Grosser     SharedVar->setAlignment(EleTy->getPrimitiveSizeInBits() / 8);
1272*b513b491STobias Grosser     ConstantAggregateZero *Zero = ConstantAggregateZero::get(ArrayTy);
1273*b513b491STobias Grosser     SharedVar->setInitializer(Zero);
1274*b513b491STobias Grosser 
1275*b513b491STobias Grosser     Id = isl_id_alloc(S.getIslCtx(), Var.name, nullptr);
1276*b513b491STobias Grosser     IDToValue[Id] = SharedVar;
1277*b513b491STobias Grosser     const ScopArrayInfo *SAI = S.getOrCreateScopArrayInfo(
1278*b513b491STobias Grosser         SharedVar, EleTy, Sizes, ScopArrayInfo::MK_Array);
1279*b513b491STobias Grosser     LocalArrays.push_back(SharedVar);
1280*b513b491STobias Grosser     KernelIds.push_back(Id);
1281*b513b491STobias Grosser     IDToSAI[Id] = SAI;
1282*b513b491STobias Grosser   }
1283*b513b491STobias Grosser }
1284*b513b491STobias Grosser 
1285edb885cbSTobias Grosser void GPUNodeBuilder::createKernelFunction(ppcg_kernel *Kernel,
1286edb885cbSTobias Grosser                                           SetVector<Value *> &SubtreeValues) {
128732837fe3STobias Grosser 
128832837fe3STobias Grosser   std::string Identifier = "kernel_" + std::to_string(Kernel->id);
128932837fe3STobias Grosser   GPUModule.reset(new Module(Identifier, Builder.getContext()));
129032837fe3STobias Grosser   GPUModule->setTargetTriple(Triple::normalize("nvptx64-nvidia-cuda"));
129132837fe3STobias Grosser   GPUModule->setDataLayout(computeNVPTXDataLayout(true /* is64Bit */));
129232837fe3STobias Grosser 
1293edb885cbSTobias Grosser   Function *FN = createKernelFunctionDecl(Kernel, SubtreeValues);
129432837fe3STobias Grosser 
129559ab0705STobias Grosser   BasicBlock *PrevBlock = Builder.GetInsertBlock();
129632837fe3STobias Grosser   auto EntryBlock = BasicBlock::Create(Builder.getContext(), "entry", FN);
129732837fe3STobias Grosser 
129859ab0705STobias Grosser   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
129959ab0705STobias Grosser   DT.addNewBlock(EntryBlock, PrevBlock);
130059ab0705STobias Grosser 
130132837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock);
130232837fe3STobias Grosser   Builder.CreateRetVoid();
130332837fe3STobias Grosser   Builder.SetInsertPoint(EntryBlock, EntryBlock->begin());
1304472f9654STobias Grosser 
1305629109b6STobias Grosser   ScopDetection::markFunctionAsInvalid(FN);
1306629109b6STobias Grosser 
130700bb5a99STobias Grosser   prepareKernelArguments(Kernel, FN);
1308*b513b491STobias Grosser   createKernelVariables(Kernel, FN);
1309472f9654STobias Grosser   insertKernelIntrinsics(Kernel);
131032837fe3STobias Grosser }
131132837fe3STobias Grosser 
131274dc3cb4STobias Grosser std::string GPUNodeBuilder::createKernelASM() {
131374dc3cb4STobias Grosser   llvm::Triple GPUTriple(Triple::normalize("nvptx64-nvidia-cuda"));
131474dc3cb4STobias Grosser   std::string ErrMsg;
131574dc3cb4STobias Grosser   auto GPUTarget = TargetRegistry::lookupTarget(GPUTriple.getTriple(), ErrMsg);
131674dc3cb4STobias Grosser 
131774dc3cb4STobias Grosser   if (!GPUTarget) {
131874dc3cb4STobias Grosser     errs() << ErrMsg << "\n";
131974dc3cb4STobias Grosser     return "";
132074dc3cb4STobias Grosser   }
132174dc3cb4STobias Grosser 
132274dc3cb4STobias Grosser   TargetOptions Options;
132374dc3cb4STobias Grosser   Options.UnsafeFPMath = FastMath;
132474dc3cb4STobias Grosser   std::unique_ptr<TargetMachine> TargetM(
132574dc3cb4STobias Grosser       GPUTarget->createTargetMachine(GPUTriple.getTriple(), CudaVersion, "",
132674dc3cb4STobias Grosser                                      Options, Optional<Reloc::Model>()));
132774dc3cb4STobias Grosser 
132874dc3cb4STobias Grosser   SmallString<0> ASMString;
132974dc3cb4STobias Grosser   raw_svector_ostream ASMStream(ASMString);
133074dc3cb4STobias Grosser   llvm::legacy::PassManager PM;
133174dc3cb4STobias Grosser 
133274dc3cb4STobias Grosser   PM.add(createTargetTransformInfoWrapperPass(TargetM->getTargetIRAnalysis()));
133374dc3cb4STobias Grosser 
133474dc3cb4STobias Grosser   if (TargetM->addPassesToEmitFile(
133574dc3cb4STobias Grosser           PM, ASMStream, TargetMachine::CGFT_AssemblyFile, true /* verify */)) {
133674dc3cb4STobias Grosser     errs() << "The target does not support generation of this file type!\n";
133774dc3cb4STobias Grosser     return "";
133874dc3cb4STobias Grosser   }
133974dc3cb4STobias Grosser 
134074dc3cb4STobias Grosser   PM.run(*GPUModule);
134174dc3cb4STobias Grosser 
134274dc3cb4STobias Grosser   return ASMStream.str();
134374dc3cb4STobias Grosser }
134474dc3cb4STobias Grosser 
134557793596STobias Grosser std::string GPUNodeBuilder::finalizeKernelFunction() {
1346e1a98343STobias Grosser   // Verify module.
1347e1a98343STobias Grosser   llvm::legacy::PassManager Passes;
1348e1a98343STobias Grosser   Passes.add(createVerifierPass());
1349e1a98343STobias Grosser   Passes.run(*GPUModule);
135032837fe3STobias Grosser 
135132837fe3STobias Grosser   if (DumpKernelIR)
135232837fe3STobias Grosser     outs() << *GPUModule << "\n";
135332837fe3STobias Grosser 
13549a18d559STobias Grosser   // Optimize module.
13559a18d559STobias Grosser   llvm::legacy::PassManager OptPasses;
13569a18d559STobias Grosser   PassManagerBuilder PassBuilder;
13579a18d559STobias Grosser   PassBuilder.OptLevel = 3;
13589a18d559STobias Grosser   PassBuilder.SizeLevel = 0;
13599a18d559STobias Grosser   PassBuilder.populateModulePassManager(OptPasses);
13609a18d559STobias Grosser   OptPasses.run(*GPUModule);
13619a18d559STobias Grosser 
136274dc3cb4STobias Grosser   std::string Assembly = createKernelASM();
136374dc3cb4STobias Grosser 
136474dc3cb4STobias Grosser   if (DumpKernelASM)
136574dc3cb4STobias Grosser     outs() << Assembly << "\n";
136674dc3cb4STobias Grosser 
136732837fe3STobias Grosser   GPUModule.release();
1368472f9654STobias Grosser   KernelIDs.clear();
136957793596STobias Grosser 
137057793596STobias Grosser   return Assembly;
137132837fe3STobias Grosser }
137232837fe3STobias Grosser 
13739dfe4e7cSTobias Grosser namespace {
13749dfe4e7cSTobias Grosser class PPCGCodeGeneration : public ScopPass {
13759dfe4e7cSTobias Grosser public:
13769dfe4e7cSTobias Grosser   static char ID;
13779dfe4e7cSTobias Grosser 
1378e938517eSTobias Grosser   /// The scop that is currently processed.
1379e938517eSTobias Grosser   Scop *S;
1380e938517eSTobias Grosser 
138138fc0aedSTobias Grosser   LoopInfo *LI;
138238fc0aedSTobias Grosser   DominatorTree *DT;
138338fc0aedSTobias Grosser   ScalarEvolution *SE;
138438fc0aedSTobias Grosser   const DataLayout *DL;
138538fc0aedSTobias Grosser   RegionInfo *RI;
138638fc0aedSTobias Grosser 
13879dfe4e7cSTobias Grosser   PPCGCodeGeneration() : ScopPass(ID) {}
13889dfe4e7cSTobias Grosser 
1389e938517eSTobias Grosser   /// Construct compilation options for PPCG.
1390e938517eSTobias Grosser   ///
1391e938517eSTobias Grosser   /// @returns The compilation options.
1392e938517eSTobias Grosser   ppcg_options *createPPCGOptions() {
1393e938517eSTobias Grosser     auto DebugOptions =
1394e938517eSTobias Grosser         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
1395e938517eSTobias Grosser     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
1396e938517eSTobias Grosser 
1397e938517eSTobias Grosser     DebugOptions->dump_schedule_constraints = false;
1398e938517eSTobias Grosser     DebugOptions->dump_schedule = false;
1399e938517eSTobias Grosser     DebugOptions->dump_final_schedule = false;
1400e938517eSTobias Grosser     DebugOptions->dump_sizes = false;
1401e938517eSTobias Grosser 
1402e938517eSTobias Grosser     Options->debug = DebugOptions;
1403e938517eSTobias Grosser 
1404e938517eSTobias Grosser     Options->reschedule = true;
1405e938517eSTobias Grosser     Options->scale_tile_loops = false;
1406e938517eSTobias Grosser     Options->wrap = false;
1407e938517eSTobias Grosser 
1408e938517eSTobias Grosser     Options->non_negative_parameters = false;
1409e938517eSTobias Grosser     Options->ctx = nullptr;
1410e938517eSTobias Grosser     Options->sizes = nullptr;
1411e938517eSTobias Grosser 
14124eaedde5STobias Grosser     Options->tile_size = 32;
14134eaedde5STobias Grosser 
1414e938517eSTobias Grosser     Options->use_private_memory = false;
1415*b513b491STobias Grosser     Options->use_shared_memory = SharedMemory;
1416*b513b491STobias Grosser     Options->max_shared_memory = 48 * 1024;
1417e938517eSTobias Grosser 
1418e938517eSTobias Grosser     Options->target = PPCG_TARGET_CUDA;
1419e938517eSTobias Grosser     Options->openmp = false;
1420e938517eSTobias Grosser     Options->linearize_device_arrays = true;
1421e938517eSTobias Grosser     Options->live_range_reordering = false;
1422e938517eSTobias Grosser 
1423e938517eSTobias Grosser     Options->opencl_compiler_options = nullptr;
1424e938517eSTobias Grosser     Options->opencl_use_gpu = false;
1425e938517eSTobias Grosser     Options->opencl_n_include_file = 0;
1426e938517eSTobias Grosser     Options->opencl_include_files = nullptr;
1427e938517eSTobias Grosser     Options->opencl_print_kernel_types = false;
1428e938517eSTobias Grosser     Options->opencl_embed_kernel_code = false;
1429e938517eSTobias Grosser 
1430e938517eSTobias Grosser     Options->save_schedule_file = nullptr;
1431e938517eSTobias Grosser     Options->load_schedule_file = nullptr;
1432e938517eSTobias Grosser 
1433e938517eSTobias Grosser     return Options;
1434e938517eSTobias Grosser   }
1435e938517eSTobias Grosser 
1436f384594dSTobias Grosser   /// Get a tagged access relation containing all accesses of type @p AccessTy.
1437f384594dSTobias Grosser   ///
1438f384594dSTobias Grosser   /// Instead of a normal access of the form:
1439f384594dSTobias Grosser   ///
1440f384594dSTobias Grosser   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
1441f384594dSTobias Grosser   ///
1442f384594dSTobias Grosser   /// a tagged access has the form
1443f384594dSTobias Grosser   ///
1444f384594dSTobias Grosser   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
1445f384594dSTobias Grosser   ///
1446f384594dSTobias Grosser   /// where 'id' is an additional space that references the memory access that
1447f384594dSTobias Grosser   /// triggered the access.
1448f384594dSTobias Grosser   ///
1449f384594dSTobias Grosser   /// @param AccessTy The type of the memory accesses to collect.
1450f384594dSTobias Grosser   ///
1451f384594dSTobias Grosser   /// @return The relation describing all tagged memory accesses.
1452f384594dSTobias Grosser   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
1453f384594dSTobias Grosser     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
1454f384594dSTobias Grosser 
1455f384594dSTobias Grosser     for (auto &Stmt : *S)
1456f384594dSTobias Grosser       for (auto &Acc : Stmt)
1457f384594dSTobias Grosser         if (Acc->getType() == AccessTy) {
1458f384594dSTobias Grosser           isl_map *Relation = Acc->getAccessRelation();
1459f384594dSTobias Grosser           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
1460f384594dSTobias Grosser 
1461f384594dSTobias Grosser           isl_space *Space = isl_map_get_space(Relation);
1462f384594dSTobias Grosser           Space = isl_space_range(Space);
1463f384594dSTobias Grosser           Space = isl_space_from_range(Space);
14646293ba69STobias Grosser           Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
1465f384594dSTobias Grosser           isl_map *Universe = isl_map_universe(Space);
1466f384594dSTobias Grosser           Relation = isl_map_domain_product(Relation, Universe);
1467f384594dSTobias Grosser           Accesses = isl_union_map_add_map(Accesses, Relation);
1468f384594dSTobias Grosser         }
1469f384594dSTobias Grosser 
1470f384594dSTobias Grosser     return Accesses;
1471f384594dSTobias Grosser   }
1472f384594dSTobias Grosser 
1473f384594dSTobias Grosser   /// Get the set of all read accesses, tagged with the access id.
1474f384594dSTobias Grosser   ///
1475f384594dSTobias Grosser   /// @see getTaggedAccesses
1476f384594dSTobias Grosser   isl_union_map *getTaggedReads() {
1477f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::READ);
1478f384594dSTobias Grosser   }
1479f384594dSTobias Grosser 
1480f384594dSTobias Grosser   /// Get the set of all may (and must) accesses, tagged with the access id.
1481f384594dSTobias Grosser   ///
1482f384594dSTobias Grosser   /// @see getTaggedAccesses
1483f384594dSTobias Grosser   isl_union_map *getTaggedMayWrites() {
1484f384594dSTobias Grosser     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
1485f384594dSTobias Grosser                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
1486f384594dSTobias Grosser   }
1487f384594dSTobias Grosser 
1488f384594dSTobias Grosser   /// Get the set of all must accesses, tagged with the access id.
1489f384594dSTobias Grosser   ///
1490f384594dSTobias Grosser   /// @see getTaggedAccesses
1491f384594dSTobias Grosser   isl_union_map *getTaggedMustWrites() {
1492f384594dSTobias Grosser     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
1493f384594dSTobias Grosser   }
1494f384594dSTobias Grosser 
1495aef5196fSTobias Grosser   /// Collect parameter and array names as isl_ids.
1496aef5196fSTobias Grosser   ///
1497aef5196fSTobias Grosser   /// To reason about the different parameters and arrays used, ppcg requires
1498aef5196fSTobias Grosser   /// a list of all isl_ids in use. As PPCG traditionally performs
1499aef5196fSTobias Grosser   /// source-to-source compilation each of these isl_ids is mapped to the
1500aef5196fSTobias Grosser   /// expression that represents it. As we do not have a corresponding
1501aef5196fSTobias Grosser   /// expression in Polly, we just map each id to a 'zero' expression to match
1502aef5196fSTobias Grosser   /// the data format that ppcg expects.
1503aef5196fSTobias Grosser   ///
1504aef5196fSTobias Grosser   /// @returns Retun a map from collected ids to 'zero' ast expressions.
1505aef5196fSTobias Grosser   __isl_give isl_id_to_ast_expr *getNames() {
1506aef5196fSTobias Grosser     auto *Names = isl_id_to_ast_expr_alloc(
1507bd81a7eeSTobias Grosser         S->getIslCtx(),
1508bd81a7eeSTobias Grosser         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
1509aef5196fSTobias Grosser     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
1510aef5196fSTobias Grosser     auto *Space = S->getParamSpace();
1511aef5196fSTobias Grosser 
1512aef5196fSTobias Grosser     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
1513aef5196fSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
1514aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1515aef5196fSTobias Grosser     }
1516aef5196fSTobias Grosser 
1517aef5196fSTobias Grosser     for (auto &Array : S->arrays()) {
1518d7754a12SRoman Gareev       auto Id = Array->getBasePtrId();
1519aef5196fSTobias Grosser       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
1520aef5196fSTobias Grosser     }
1521aef5196fSTobias Grosser 
1522aef5196fSTobias Grosser     isl_space_free(Space);
1523aef5196fSTobias Grosser     isl_ast_expr_free(Zero);
1524aef5196fSTobias Grosser 
1525aef5196fSTobias Grosser     return Names;
1526aef5196fSTobias Grosser   }
1527aef5196fSTobias Grosser 
1528e938517eSTobias Grosser   /// Create a new PPCG scop from the current scop.
1529e938517eSTobias Grosser   ///
1530f384594dSTobias Grosser   /// The PPCG scop is initialized with data from the current polly::Scop. From
1531f384594dSTobias Grosser   /// this initial data, the data-dependences in the PPCG scop are initialized.
1532f384594dSTobias Grosser   /// We do not use Polly's dependence analysis for now, to ensure we match
1533f384594dSTobias Grosser   /// the PPCG default behaviour more closely.
1534e938517eSTobias Grosser   ///
1535e938517eSTobias Grosser   /// @returns A new ppcg scop.
1536e938517eSTobias Grosser   ppcg_scop *createPPCGScop() {
1537e938517eSTobias Grosser     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
1538e938517eSTobias Grosser 
1539e938517eSTobias Grosser     PPCGScop->options = createPPCGOptions();
1540e938517eSTobias Grosser 
1541e938517eSTobias Grosser     PPCGScop->start = 0;
1542e938517eSTobias Grosser     PPCGScop->end = 0;
1543e938517eSTobias Grosser 
1544f384594dSTobias Grosser     PPCGScop->context = S->getContext();
1545f384594dSTobias Grosser     PPCGScop->domain = S->getDomains();
1546e938517eSTobias Grosser     PPCGScop->call = nullptr;
1547f384594dSTobias Grosser     PPCGScop->tagged_reads = getTaggedReads();
1548f384594dSTobias Grosser     PPCGScop->reads = S->getReads();
1549e938517eSTobias Grosser     PPCGScop->live_in = nullptr;
1550f384594dSTobias Grosser     PPCGScop->tagged_may_writes = getTaggedMayWrites();
1551f384594dSTobias Grosser     PPCGScop->may_writes = S->getWrites();
1552f384594dSTobias Grosser     PPCGScop->tagged_must_writes = getTaggedMustWrites();
1553f384594dSTobias Grosser     PPCGScop->must_writes = S->getMustWrites();
1554e938517eSTobias Grosser     PPCGScop->live_out = nullptr;
1555f384594dSTobias Grosser     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
1556e938517eSTobias Grosser     PPCGScop->tagger = nullptr;
1557e938517eSTobias Grosser 
1558e938517eSTobias Grosser     PPCGScop->independence = nullptr;
1559e938517eSTobias Grosser     PPCGScop->dep_flow = nullptr;
1560e938517eSTobias Grosser     PPCGScop->tagged_dep_flow = nullptr;
1561e938517eSTobias Grosser     PPCGScop->dep_false = nullptr;
1562e938517eSTobias Grosser     PPCGScop->dep_forced = nullptr;
1563e938517eSTobias Grosser     PPCGScop->dep_order = nullptr;
1564e938517eSTobias Grosser     PPCGScop->tagged_dep_order = nullptr;
1565e938517eSTobias Grosser 
1566f384594dSTobias Grosser     PPCGScop->schedule = S->getScheduleTree();
1567aef5196fSTobias Grosser     PPCGScop->names = getNames();
1568e938517eSTobias Grosser 
1569e938517eSTobias Grosser     PPCGScop->pet = nullptr;
1570e938517eSTobias Grosser 
1571f384594dSTobias Grosser     compute_tagger(PPCGScop);
1572f384594dSTobias Grosser     compute_dependences(PPCGScop);
1573f384594dSTobias Grosser 
1574e938517eSTobias Grosser     return PPCGScop;
1575e938517eSTobias Grosser   }
1576e938517eSTobias Grosser 
157760f63b49STobias Grosser   /// Collect the array acesses in a statement.
157860f63b49STobias Grosser   ///
157960f63b49STobias Grosser   /// @param Stmt The statement for which to collect the accesses.
158060f63b49STobias Grosser   ///
158160f63b49STobias Grosser   /// @returns A list of array accesses.
158260f63b49STobias Grosser   gpu_stmt_access *getStmtAccesses(ScopStmt &Stmt) {
158360f63b49STobias Grosser     gpu_stmt_access *Accesses = nullptr;
158460f63b49STobias Grosser 
158560f63b49STobias Grosser     for (MemoryAccess *Acc : Stmt) {
158660f63b49STobias Grosser       auto Access = isl_alloc_type(S->getIslCtx(), struct gpu_stmt_access);
158760f63b49STobias Grosser       Access->read = Acc->isRead();
158860f63b49STobias Grosser       Access->write = Acc->isWrite();
158960f63b49STobias Grosser       Access->access = Acc->getAccessRelation();
159060f63b49STobias Grosser       isl_space *Space = isl_map_get_space(Access->access);
159160f63b49STobias Grosser       Space = isl_space_range(Space);
159260f63b49STobias Grosser       Space = isl_space_from_range(Space);
15936293ba69STobias Grosser       Space = isl_space_set_tuple_id(Space, isl_dim_in, Acc->getId());
159460f63b49STobias Grosser       isl_map *Universe = isl_map_universe(Space);
159560f63b49STobias Grosser       Access->tagged_access =
159660f63b49STobias Grosser           isl_map_domain_product(Acc->getAccessRelation(), Universe);
1597*b513b491STobias Grosser       Access->exact_write = !Acc->isMayWrite();
159860f63b49STobias Grosser       Access->ref_id = Acc->getId();
159960f63b49STobias Grosser       Access->next = Accesses;
1600*b513b491STobias Grosser       Access->n_index = Acc->getScopArrayInfo()->getNumberOfDimensions();
160160f63b49STobias Grosser       Accesses = Access;
160260f63b49STobias Grosser     }
160360f63b49STobias Grosser 
160460f63b49STobias Grosser     return Accesses;
160560f63b49STobias Grosser   }
160660f63b49STobias Grosser 
160769b46751STobias Grosser   /// Collect the list of GPU statements.
160869b46751STobias Grosser   ///
160969b46751STobias Grosser   /// Each statement has an id, a pointer to the underlying data structure,
161069b46751STobias Grosser   /// as well as a list with all memory accesses.
161169b46751STobias Grosser   ///
161269b46751STobias Grosser   /// TODO: Initialize the list of memory accesses.
161369b46751STobias Grosser   ///
161469b46751STobias Grosser   /// @returns A linked-list of statements.
161569b46751STobias Grosser   gpu_stmt *getStatements() {
161669b46751STobias Grosser     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
161769b46751STobias Grosser                                        std::distance(S->begin(), S->end()));
161869b46751STobias Grosser 
161969b46751STobias Grosser     int i = 0;
162069b46751STobias Grosser     for (auto &Stmt : *S) {
162169b46751STobias Grosser       gpu_stmt *GPUStmt = &Stmts[i];
162269b46751STobias Grosser 
162369b46751STobias Grosser       GPUStmt->id = Stmt.getDomainId();
162469b46751STobias Grosser 
162569b46751STobias Grosser       // We use the pet stmt pointer to keep track of the Polly statements.
162669b46751STobias Grosser       GPUStmt->stmt = (pet_stmt *)&Stmt;
162760f63b49STobias Grosser       GPUStmt->accesses = getStmtAccesses(Stmt);
162869b46751STobias Grosser       i++;
162969b46751STobias Grosser     }
163069b46751STobias Grosser 
163169b46751STobias Grosser     return Stmts;
163269b46751STobias Grosser   }
163369b46751STobias Grosser 
163460f63b49STobias Grosser   /// Derive the extent of an array.
163560f63b49STobias Grosser   ///
163660f63b49STobias Grosser   /// The extent of an array is defined by the set of memory locations for
163760f63b49STobias Grosser   /// which a memory access in the iteration domain exists.
163860f63b49STobias Grosser   ///
163960f63b49STobias Grosser   /// @param Array The array to derive the extent for.
164060f63b49STobias Grosser   ///
164160f63b49STobias Grosser   /// @returns An isl_set describing the extent of the array.
164260f63b49STobias Grosser   __isl_give isl_set *getExtent(ScopArrayInfo *Array) {
164360f63b49STobias Grosser     isl_union_map *Accesses = S->getAccesses();
164460f63b49STobias Grosser     Accesses = isl_union_map_intersect_domain(Accesses, S->getDomains());
164560f63b49STobias Grosser     isl_union_set *AccessUSet = isl_union_map_range(Accesses);
164660f63b49STobias Grosser     isl_set *AccessSet =
164760f63b49STobias Grosser         isl_union_set_extract_set(AccessUSet, Array->getSpace());
164860f63b49STobias Grosser     isl_union_set_free(AccessUSet);
164960f63b49STobias Grosser 
165060f63b49STobias Grosser     return AccessSet;
165160f63b49STobias Grosser   }
165260f63b49STobias Grosser 
165360f63b49STobias Grosser   /// Derive the bounds of an array.
165460f63b49STobias Grosser   ///
165560f63b49STobias Grosser   /// For the first dimension we derive the bound of the array from the extent
165660f63b49STobias Grosser   /// of this dimension. For inner dimensions we obtain their size directly from
165760f63b49STobias Grosser   /// ScopArrayInfo.
165860f63b49STobias Grosser   ///
165960f63b49STobias Grosser   /// @param PPCGArray The array to compute bounds for.
166060f63b49STobias Grosser   /// @param Array The polly array from which to take the information.
166160f63b49STobias Grosser   void setArrayBounds(gpu_array_info &PPCGArray, ScopArrayInfo *Array) {
166260f63b49STobias Grosser     if (PPCGArray.n_index > 0) {
166360f63b49STobias Grosser       isl_set *Dom = isl_set_copy(PPCGArray.extent);
166460f63b49STobias Grosser       Dom = isl_set_project_out(Dom, isl_dim_set, 1, PPCGArray.n_index - 1);
166560f63b49STobias Grosser       isl_pw_aff *Bound = isl_set_dim_max(isl_set_copy(Dom), 0);
166660f63b49STobias Grosser       isl_set_free(Dom);
166760f63b49STobias Grosser       Dom = isl_pw_aff_domain(isl_pw_aff_copy(Bound));
166860f63b49STobias Grosser       isl_local_space *LS = isl_local_space_from_space(isl_set_get_space(Dom));
166960f63b49STobias Grosser       isl_aff *One = isl_aff_zero_on_domain(LS);
167060f63b49STobias Grosser       One = isl_aff_add_constant_si(One, 1);
167160f63b49STobias Grosser       Bound = isl_pw_aff_add(Bound, isl_pw_aff_alloc(Dom, One));
167260f63b49STobias Grosser       Bound = isl_pw_aff_gist(Bound, S->getContext());
167360f63b49STobias Grosser       PPCGArray.bound[0] = Bound;
167460f63b49STobias Grosser     }
167560f63b49STobias Grosser 
167660f63b49STobias Grosser     for (unsigned i = 1; i < PPCGArray.n_index; ++i) {
167760f63b49STobias Grosser       isl_pw_aff *Bound = Array->getDimensionSizePw(i);
167860f63b49STobias Grosser       auto LS = isl_pw_aff_get_domain_space(Bound);
167960f63b49STobias Grosser       auto Aff = isl_multi_aff_zero(LS);
168060f63b49STobias Grosser       Bound = isl_pw_aff_pullback_multi_aff(Bound, Aff);
168160f63b49STobias Grosser       PPCGArray.bound[i] = Bound;
168260f63b49STobias Grosser     }
168360f63b49STobias Grosser   }
168460f63b49STobias Grosser 
168560f63b49STobias Grosser   /// Create the arrays for @p PPCGProg.
168660f63b49STobias Grosser   ///
168760f63b49STobias Grosser   /// @param PPCGProg The program to compute the arrays for.
168860f63b49STobias Grosser   void createArrays(gpu_prog *PPCGProg) {
168960f63b49STobias Grosser     int i = 0;
1690d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
169160f63b49STobias Grosser       std::string TypeName;
169260f63b49STobias Grosser       raw_string_ostream OS(TypeName);
169360f63b49STobias Grosser 
169460f63b49STobias Grosser       OS << *Array->getElementType();
169560f63b49STobias Grosser       TypeName = OS.str();
169660f63b49STobias Grosser 
169760f63b49STobias Grosser       gpu_array_info &PPCGArray = PPCGProg->array[i];
169860f63b49STobias Grosser 
169960f63b49STobias Grosser       PPCGArray.space = Array->getSpace();
170060f63b49STobias Grosser       PPCGArray.type = strdup(TypeName.c_str());
170160f63b49STobias Grosser       PPCGArray.size = Array->getElementType()->getPrimitiveSizeInBits() / 8;
170260f63b49STobias Grosser       PPCGArray.name = strdup(Array->getName().c_str());
170360f63b49STobias Grosser       PPCGArray.extent = nullptr;
170460f63b49STobias Grosser       PPCGArray.n_index = Array->getNumberOfDimensions();
170560f63b49STobias Grosser       PPCGArray.bound =
170660f63b49STobias Grosser           isl_alloc_array(S->getIslCtx(), isl_pw_aff *, PPCGArray.n_index);
170760f63b49STobias Grosser       PPCGArray.extent = getExtent(Array);
170860f63b49STobias Grosser       PPCGArray.n_ref = 0;
170960f63b49STobias Grosser       PPCGArray.refs = nullptr;
171060f63b49STobias Grosser       PPCGArray.accessed = true;
171160f63b49STobias Grosser       PPCGArray.read_only_scalar = false;
171260f63b49STobias Grosser       PPCGArray.has_compound_element = false;
171360f63b49STobias Grosser       PPCGArray.local = false;
171460f63b49STobias Grosser       PPCGArray.declare_local = false;
171560f63b49STobias Grosser       PPCGArray.global = false;
171660f63b49STobias Grosser       PPCGArray.linearize = false;
171760f63b49STobias Grosser       PPCGArray.dep_order = nullptr;
171813c78e4dSTobias Grosser       PPCGArray.user = Array;
171960f63b49STobias Grosser 
172060f63b49STobias Grosser       setArrayBounds(PPCGArray, Array);
17212d010dafSTobias Grosser       i++;
1722b9fc860aSTobias Grosser 
1723b9fc860aSTobias Grosser       collect_references(PPCGProg, &PPCGArray);
172460f63b49STobias Grosser     }
172560f63b49STobias Grosser   }
172660f63b49STobias Grosser 
172760f63b49STobias Grosser   /// Create an identity map between the arrays in the scop.
172860f63b49STobias Grosser   ///
172960f63b49STobias Grosser   /// @returns An identity map between the arrays in the scop.
173060f63b49STobias Grosser   isl_union_map *getArrayIdentity() {
173160f63b49STobias Grosser     isl_union_map *Maps = isl_union_map_empty(S->getParamSpace());
173260f63b49STobias Grosser 
1733d7754a12SRoman Gareev     for (auto &Array : S->arrays()) {
173460f63b49STobias Grosser       isl_space *Space = Array->getSpace();
173560f63b49STobias Grosser       Space = isl_space_map_from_set(Space);
173660f63b49STobias Grosser       isl_map *Identity = isl_map_identity(Space);
173760f63b49STobias Grosser       Maps = isl_union_map_add_map(Maps, Identity);
173860f63b49STobias Grosser     }
173960f63b49STobias Grosser 
174060f63b49STobias Grosser     return Maps;
174160f63b49STobias Grosser   }
174260f63b49STobias Grosser 
1743e938517eSTobias Grosser   /// Create a default-initialized PPCG GPU program.
1744e938517eSTobias Grosser   ///
1745e938517eSTobias Grosser   /// @returns A new gpu grogram description.
1746e938517eSTobias Grosser   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
1747e938517eSTobias Grosser 
1748e938517eSTobias Grosser     if (!PPCGScop)
1749e938517eSTobias Grosser       return nullptr;
1750e938517eSTobias Grosser 
1751e938517eSTobias Grosser     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
1752e938517eSTobias Grosser 
1753e938517eSTobias Grosser     PPCGProg->ctx = S->getIslCtx();
1754e938517eSTobias Grosser     PPCGProg->scop = PPCGScop;
1755aef5196fSTobias Grosser     PPCGProg->context = isl_set_copy(PPCGScop->context);
175660f63b49STobias Grosser     PPCGProg->read = isl_union_map_copy(PPCGScop->reads);
175760f63b49STobias Grosser     PPCGProg->may_write = isl_union_map_copy(PPCGScop->may_writes);
175860f63b49STobias Grosser     PPCGProg->must_write = isl_union_map_copy(PPCGScop->must_writes);
175960f63b49STobias Grosser     PPCGProg->tagged_must_kill =
176060f63b49STobias Grosser         isl_union_map_copy(PPCGScop->tagged_must_kills);
176160f63b49STobias Grosser     PPCGProg->to_inner = getArrayIdentity();
176260f63b49STobias Grosser     PPCGProg->to_outer = getArrayIdentity();
176360f63b49STobias Grosser     PPCGProg->may_persist = compute_may_persist(PPCGProg);
1764e938517eSTobias Grosser     PPCGProg->any_to_outer = nullptr;
1765e938517eSTobias Grosser     PPCGProg->array_order = nullptr;
176669b46751STobias Grosser     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
176769b46751STobias Grosser     PPCGProg->stmts = getStatements();
176860f63b49STobias Grosser     PPCGProg->n_array = std::distance(S->array_begin(), S->array_end());
176960f63b49STobias Grosser     PPCGProg->array = isl_calloc_array(S->getIslCtx(), struct gpu_array_info,
177060f63b49STobias Grosser                                        PPCGProg->n_array);
177160f63b49STobias Grosser 
177260f63b49STobias Grosser     createArrays(PPCGProg);
1773e938517eSTobias Grosser 
1774e938517eSTobias Grosser     return PPCGProg;
1775e938517eSTobias Grosser   }
1776e938517eSTobias Grosser 
177769b46751STobias Grosser   struct PrintGPUUserData {
177869b46751STobias Grosser     struct cuda_info *CudaInfo;
177969b46751STobias Grosser     struct gpu_prog *PPCGProg;
178069b46751STobias Grosser     std::vector<ppcg_kernel *> Kernels;
178169b46751STobias Grosser   };
178269b46751STobias Grosser 
178369b46751STobias Grosser   /// Print a user statement node in the host code.
178469b46751STobias Grosser   ///
178569b46751STobias Grosser   /// We use ppcg's printing facilities to print the actual statement and
178669b46751STobias Grosser   /// additionally build up a list of all kernels that are encountered in the
178769b46751STobias Grosser   /// host ast.
178869b46751STobias Grosser   ///
178969b46751STobias Grosser   /// @param P The printer to print to
179069b46751STobias Grosser   /// @param Options The printing options to use
179169b46751STobias Grosser   /// @param Node The node to print
179269b46751STobias Grosser   /// @param User A user pointer to carry additional data. This pointer is
179369b46751STobias Grosser   ///             expected to be of type PrintGPUUserData.
179469b46751STobias Grosser   ///
179569b46751STobias Grosser   /// @returns A printer to which the output has been printed.
179669b46751STobias Grosser   static __isl_give isl_printer *
179769b46751STobias Grosser   printHostUser(__isl_take isl_printer *P,
179869b46751STobias Grosser                 __isl_take isl_ast_print_options *Options,
179969b46751STobias Grosser                 __isl_take isl_ast_node *Node, void *User) {
180069b46751STobias Grosser     auto Data = (struct PrintGPUUserData *)User;
180169b46751STobias Grosser     auto Id = isl_ast_node_get_annotation(Node);
180269b46751STobias Grosser 
180369b46751STobias Grosser     if (Id) {
180420251734STobias Grosser       bool IsUser = !strcmp(isl_id_get_name(Id), "user");
180520251734STobias Grosser 
180620251734STobias Grosser       // If this is a user statement, format it ourselves as ppcg would
180720251734STobias Grosser       // otherwise try to call pet functionality that is not available in
180820251734STobias Grosser       // Polly.
180920251734STobias Grosser       if (IsUser) {
181020251734STobias Grosser         P = isl_printer_start_line(P);
181120251734STobias Grosser         P = isl_printer_print_ast_node(P, Node);
181220251734STobias Grosser         P = isl_printer_end_line(P);
181320251734STobias Grosser         isl_id_free(Id);
181420251734STobias Grosser         isl_ast_print_options_free(Options);
181520251734STobias Grosser         return P;
181620251734STobias Grosser       }
181720251734STobias Grosser 
181869b46751STobias Grosser       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
181969b46751STobias Grosser       isl_id_free(Id);
182069b46751STobias Grosser       Data->Kernels.push_back(Kernel);
182169b46751STobias Grosser     }
182269b46751STobias Grosser 
182369b46751STobias Grosser     return print_host_user(P, Options, Node, User);
182469b46751STobias Grosser   }
182569b46751STobias Grosser 
182669b46751STobias Grosser   /// Print C code corresponding to the control flow in @p Kernel.
182769b46751STobias Grosser   ///
182869b46751STobias Grosser   /// @param Kernel The kernel to print
182969b46751STobias Grosser   void printKernel(ppcg_kernel *Kernel) {
183069b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
183169b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
183269b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
183369b46751STobias Grosser     P = isl_ast_node_print(Kernel->tree, P, Options);
183469b46751STobias Grosser     char *String = isl_printer_get_str(P);
183569b46751STobias Grosser     printf("%s\n", String);
183669b46751STobias Grosser     free(String);
183769b46751STobias Grosser     isl_printer_free(P);
183869b46751STobias Grosser   }
183969b46751STobias Grosser 
184069b46751STobias Grosser   /// Print C code corresponding to the GPU code described by @p Tree.
184169b46751STobias Grosser   ///
184269b46751STobias Grosser   /// @param Tree An AST describing GPU code
184369b46751STobias Grosser   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
184469b46751STobias Grosser   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
184569b46751STobias Grosser     auto *P = isl_printer_to_str(S->getIslCtx());
184669b46751STobias Grosser     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
184769b46751STobias Grosser 
184869b46751STobias Grosser     PrintGPUUserData Data;
184969b46751STobias Grosser     Data.PPCGProg = PPCGProg;
185069b46751STobias Grosser 
185169b46751STobias Grosser     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
185269b46751STobias Grosser     Options =
185369b46751STobias Grosser         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
185469b46751STobias Grosser     P = isl_ast_node_print(Tree, P, Options);
185569b46751STobias Grosser     char *String = isl_printer_get_str(P);
185669b46751STobias Grosser     printf("# host\n");
185769b46751STobias Grosser     printf("%s\n", String);
185869b46751STobias Grosser     free(String);
185969b46751STobias Grosser     isl_printer_free(P);
186069b46751STobias Grosser 
186169b46751STobias Grosser     for (auto Kernel : Data.Kernels) {
186269b46751STobias Grosser       printf("# kernel%d\n", Kernel->id);
186369b46751STobias Grosser       printKernel(Kernel);
186469b46751STobias Grosser     }
186569b46751STobias Grosser   }
186669b46751STobias Grosser 
1867f384594dSTobias Grosser   // Generate a GPU program using PPCG.
1868f384594dSTobias Grosser   //
1869f384594dSTobias Grosser   // GPU mapping consists of multiple steps:
1870f384594dSTobias Grosser   //
1871f384594dSTobias Grosser   //  1) Compute new schedule for the program.
1872f384594dSTobias Grosser   //  2) Map schedule to GPU (TODO)
1873f384594dSTobias Grosser   //  3) Generate code for new schedule (TODO)
1874f384594dSTobias Grosser   //
1875f384594dSTobias Grosser   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
1876f384594dSTobias Grosser   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
1877f384594dSTobias Grosser   // strategy directly from this pass.
1878f384594dSTobias Grosser   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
1879f384594dSTobias Grosser 
1880f384594dSTobias Grosser     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
1881f384594dSTobias Grosser 
1882f384594dSTobias Grosser     PPCGGen->ctx = S->getIslCtx();
1883f384594dSTobias Grosser     PPCGGen->options = PPCGScop->options;
1884f384594dSTobias Grosser     PPCGGen->print = nullptr;
1885f384594dSTobias Grosser     PPCGGen->print_user = nullptr;
188660c60025STobias Grosser     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
1887f384594dSTobias Grosser     PPCGGen->prog = PPCGProg;
1888f384594dSTobias Grosser     PPCGGen->tree = nullptr;
1889f384594dSTobias Grosser     PPCGGen->types.n = 0;
1890f384594dSTobias Grosser     PPCGGen->types.name = nullptr;
1891f384594dSTobias Grosser     PPCGGen->sizes = nullptr;
1892f384594dSTobias Grosser     PPCGGen->used_sizes = nullptr;
1893f384594dSTobias Grosser     PPCGGen->kernel_id = 0;
1894f384594dSTobias Grosser 
1895f384594dSTobias Grosser     // Set scheduling strategy to same strategy PPCG is using.
1896f384594dSTobias Grosser     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
1897f384594dSTobias Grosser     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
18982341fe9eSTobias Grosser     isl_options_set_schedule_whole_component(PPCGGen->ctx, false);
1899f384594dSTobias Grosser 
1900f384594dSTobias Grosser     isl_schedule *Schedule = get_schedule(PPCGGen);
1901f384594dSTobias Grosser 
1902aef5196fSTobias Grosser     int has_permutable = has_any_permutable_node(Schedule);
1903aef5196fSTobias Grosser 
190469b46751STobias Grosser     if (!has_permutable || has_permutable < 0) {
1905aef5196fSTobias Grosser       Schedule = isl_schedule_free(Schedule);
190669b46751STobias Grosser     } else {
1907aef5196fSTobias Grosser       Schedule = map_to_device(PPCGGen, Schedule);
190869b46751STobias Grosser       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
190969b46751STobias Grosser     }
1910aef5196fSTobias Grosser 
1911f384594dSTobias Grosser     if (DumpSchedule) {
1912f384594dSTobias Grosser       isl_printer *P = isl_printer_to_str(S->getIslCtx());
1913f384594dSTobias Grosser       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
1914f384594dSTobias Grosser       P = isl_printer_print_str(P, "Schedule\n");
1915f384594dSTobias Grosser       P = isl_printer_print_str(P, "========\n");
1916f384594dSTobias Grosser       if (Schedule)
1917f384594dSTobias Grosser         P = isl_printer_print_schedule(P, Schedule);
1918f384594dSTobias Grosser       else
1919f384594dSTobias Grosser         P = isl_printer_print_str(P, "No schedule found\n");
1920f384594dSTobias Grosser 
1921f384594dSTobias Grosser       printf("%s\n", isl_printer_get_str(P));
1922f384594dSTobias Grosser       isl_printer_free(P);
1923f384594dSTobias Grosser     }
1924f384594dSTobias Grosser 
192569b46751STobias Grosser     if (DumpCode) {
192669b46751STobias Grosser       printf("Code\n");
192769b46751STobias Grosser       printf("====\n");
192869b46751STobias Grosser       if (PPCGGen->tree)
192969b46751STobias Grosser         printGPUTree(PPCGGen->tree, PPCGProg);
193069b46751STobias Grosser       else
193169b46751STobias Grosser         printf("No code generated\n");
193269b46751STobias Grosser     }
193369b46751STobias Grosser 
1934f384594dSTobias Grosser     isl_schedule_free(Schedule);
1935f384594dSTobias Grosser 
1936f384594dSTobias Grosser     return PPCGGen;
1937f384594dSTobias Grosser   }
1938f384594dSTobias Grosser 
1939f384594dSTobias Grosser   /// Free gpu_gen structure.
1940f384594dSTobias Grosser   ///
1941f384594dSTobias Grosser   /// @param PPCGGen The ppcg_gen object to free.
1942f384594dSTobias Grosser   void freePPCGGen(gpu_gen *PPCGGen) {
1943f384594dSTobias Grosser     isl_ast_node_free(PPCGGen->tree);
1944f384594dSTobias Grosser     isl_union_map_free(PPCGGen->sizes);
1945f384594dSTobias Grosser     isl_union_map_free(PPCGGen->used_sizes);
1946f384594dSTobias Grosser     free(PPCGGen);
1947f384594dSTobias Grosser   }
1948f384594dSTobias Grosser 
1949b307ed4dSTobias Grosser   /// Free the options in the ppcg scop structure.
1950b307ed4dSTobias Grosser   ///
1951b307ed4dSTobias Grosser   /// ppcg is not freeing these options for us. To avoid leaks we do this
1952b307ed4dSTobias Grosser   /// ourselves.
1953b307ed4dSTobias Grosser   ///
1954b307ed4dSTobias Grosser   /// @param PPCGScop The scop referencing the options to free.
1955b307ed4dSTobias Grosser   void freeOptions(ppcg_scop *PPCGScop) {
1956b307ed4dSTobias Grosser     free(PPCGScop->options->debug);
1957b307ed4dSTobias Grosser     PPCGScop->options->debug = nullptr;
1958b307ed4dSTobias Grosser     free(PPCGScop->options);
1959b307ed4dSTobias Grosser     PPCGScop->options = nullptr;
1960b307ed4dSTobias Grosser   }
1961b307ed4dSTobias Grosser 
196238fc0aedSTobias Grosser   /// Generate code for a given GPU AST described by @p Root.
196338fc0aedSTobias Grosser   ///
196432837fe3STobias Grosser   /// @param Root An isl_ast_node pointing to the root of the GPU AST.
196532837fe3STobias Grosser   /// @param Prog The GPU Program to generate code for.
196632837fe3STobias Grosser   void generateCode(__isl_take isl_ast_node *Root, gpu_prog *Prog) {
196738fc0aedSTobias Grosser     ScopAnnotator Annotator;
196838fc0aedSTobias Grosser     Annotator.buildAliasScopes(*S);
196938fc0aedSTobias Grosser 
197038fc0aedSTobias Grosser     Region *R = &S->getRegion();
197138fc0aedSTobias Grosser 
197238fc0aedSTobias Grosser     simplifyRegion(R, DT, LI, RI);
197338fc0aedSTobias Grosser 
197438fc0aedSTobias Grosser     BasicBlock *EnteringBB = R->getEnteringBlock();
197538fc0aedSTobias Grosser 
197638fc0aedSTobias Grosser     PollyIRBuilder Builder = createPollyIRBuilder(EnteringBB, Annotator);
197738fc0aedSTobias Grosser 
197832837fe3STobias Grosser     GPUNodeBuilder NodeBuilder(Builder, Annotator, this, *DL, *LI, *SE, *DT, *S,
197932837fe3STobias Grosser                                Prog);
198038fc0aedSTobias Grosser 
198138fc0aedSTobias Grosser     // Only build the run-time condition and parameters _after_ having
198238fc0aedSTobias Grosser     // introduced the conditional branch. This is important as the conditional
198338fc0aedSTobias Grosser     // branch will guard the original scop from new induction variables that
198438fc0aedSTobias Grosser     // the SCEVExpander may introduce while code generating the parameters and
198538fc0aedSTobias Grosser     // which may introduce scalar dependences that prevent us from correctly
198638fc0aedSTobias Grosser     // code generating this scop.
198738fc0aedSTobias Grosser     BasicBlock *StartBlock =
198838fc0aedSTobias Grosser         executeScopConditionally(*S, this, Builder.getTrue());
198938fc0aedSTobias Grosser 
199038fc0aedSTobias Grosser     // TODO: Handle LICM
199138fc0aedSTobias Grosser     // TODO: Verify run-time checks
199238fc0aedSTobias Grosser     auto SplitBlock = StartBlock->getSinglePredecessor();
199338fc0aedSTobias Grosser     Builder.SetInsertPoint(SplitBlock->getTerminator());
199438fc0aedSTobias Grosser     NodeBuilder.addParameters(S->getContext());
199538fc0aedSTobias Grosser     Builder.SetInsertPoint(&*StartBlock->begin());
1996fa7b0802STobias Grosser 
1997fa7b0802STobias Grosser     NodeBuilder.initializeAfterRTH();
199838fc0aedSTobias Grosser     NodeBuilder.create(Root);
19998ed5e599STobias Grosser     NodeBuilder.finalize();
200038fc0aedSTobias Grosser   }
200138fc0aedSTobias Grosser 
2002e938517eSTobias Grosser   bool runOnScop(Scop &CurrentScop) override {
2003e938517eSTobias Grosser     S = &CurrentScop;
200438fc0aedSTobias Grosser     LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
200538fc0aedSTobias Grosser     DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
200638fc0aedSTobias Grosser     SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
200738fc0aedSTobias Grosser     DL = &S->getRegion().getEntry()->getParent()->getParent()->getDataLayout();
200838fc0aedSTobias Grosser     RI = &getAnalysis<RegionInfoPass>().getRegionInfo();
2009e938517eSTobias Grosser 
20102d58a64eSTobias Grosser     // We currently do not support scops with invariant loads.
20112d58a64eSTobias Grosser     if (S->hasInvariantAccesses())
20122d58a64eSTobias Grosser       return false;
20132d58a64eSTobias Grosser 
2014e938517eSTobias Grosser     auto PPCGScop = createPPCGScop();
2015e938517eSTobias Grosser     auto PPCGProg = createPPCGProg(PPCGScop);
2016f384594dSTobias Grosser     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
201738fc0aedSTobias Grosser 
201838fc0aedSTobias Grosser     if (PPCGGen->tree)
201932837fe3STobias Grosser       generateCode(isl_ast_node_copy(PPCGGen->tree), PPCGProg);
202038fc0aedSTobias Grosser 
2021b307ed4dSTobias Grosser     freeOptions(PPCGScop);
2022f384594dSTobias Grosser     freePPCGGen(PPCGGen);
2023e938517eSTobias Grosser     gpu_prog_free(PPCGProg);
2024e938517eSTobias Grosser     ppcg_scop_free(PPCGScop);
2025e938517eSTobias Grosser 
2026e938517eSTobias Grosser     return true;
2027e938517eSTobias Grosser   }
20289dfe4e7cSTobias Grosser 
20299dfe4e7cSTobias Grosser   void printScop(raw_ostream &, Scop &) const override {}
20309dfe4e7cSTobias Grosser 
20319dfe4e7cSTobias Grosser   void getAnalysisUsage(AnalysisUsage &AU) const override {
20329dfe4e7cSTobias Grosser     AU.addRequired<DominatorTreeWrapperPass>();
20339dfe4e7cSTobias Grosser     AU.addRequired<RegionInfoPass>();
20349dfe4e7cSTobias Grosser     AU.addRequired<ScalarEvolutionWrapperPass>();
20359dfe4e7cSTobias Grosser     AU.addRequired<ScopDetection>();
20369dfe4e7cSTobias Grosser     AU.addRequired<ScopInfoRegionPass>();
20379dfe4e7cSTobias Grosser     AU.addRequired<LoopInfoWrapperPass>();
20389dfe4e7cSTobias Grosser 
20399dfe4e7cSTobias Grosser     AU.addPreserved<AAResultsWrapperPass>();
20409dfe4e7cSTobias Grosser     AU.addPreserved<BasicAAWrapperPass>();
20419dfe4e7cSTobias Grosser     AU.addPreserved<LoopInfoWrapperPass>();
20429dfe4e7cSTobias Grosser     AU.addPreserved<DominatorTreeWrapperPass>();
20439dfe4e7cSTobias Grosser     AU.addPreserved<GlobalsAAWrapperPass>();
20449dfe4e7cSTobias Grosser     AU.addPreserved<PostDominatorTreeWrapperPass>();
20459dfe4e7cSTobias Grosser     AU.addPreserved<ScopDetection>();
20469dfe4e7cSTobias Grosser     AU.addPreserved<ScalarEvolutionWrapperPass>();
20479dfe4e7cSTobias Grosser     AU.addPreserved<SCEVAAWrapperPass>();
20489dfe4e7cSTobias Grosser 
20499dfe4e7cSTobias Grosser     // FIXME: We do not yet add regions for the newly generated code to the
20509dfe4e7cSTobias Grosser     //        region tree.
20519dfe4e7cSTobias Grosser     AU.addPreserved<RegionInfoPass>();
20529dfe4e7cSTobias Grosser     AU.addPreserved<ScopInfoRegionPass>();
20539dfe4e7cSTobias Grosser   }
20549dfe4e7cSTobias Grosser };
20559dfe4e7cSTobias Grosser }
20569dfe4e7cSTobias Grosser 
20579dfe4e7cSTobias Grosser char PPCGCodeGeneration::ID = 1;
20589dfe4e7cSTobias Grosser 
20599dfe4e7cSTobias Grosser Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
20609dfe4e7cSTobias Grosser 
20619dfe4e7cSTobias Grosser INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
20629dfe4e7cSTobias Grosser                       "Polly - Apply PPCG translation to SCOP", false, false)
20639dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
20649dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
20659dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
20669dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
20679dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
20689dfe4e7cSTobias Grosser INITIALIZE_PASS_DEPENDENCY(ScopDetection);
20699dfe4e7cSTobias Grosser INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
20709dfe4e7cSTobias Grosser                     "Polly - Apply PPCG translation to SCOP", false, false)
2071