1 //===------ PPCGCodeGeneration.cpp - Polly Accelerator Code Generation. ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Take a scop created by ScopInfo and map it to GPU code using the ppcg
11 // GPU mapping strategy.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/CodeGen/IslNodeBuilder.h"
16 #include "polly/DependenceInfo.h"
17 #include "polly/LinkAllPasses.h"
18 #include "polly/Options.h"
19 #include "polly/ScopInfo.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BasicAliasAnalysis.h"
22 #include "llvm/Analysis/GlobalsModRef.h"
23 #include "llvm/Analysis/PostDominators.h"
24 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
25 
26 #include "isl/union_map.h"
27 
28 extern "C" {
29 #include "cuda.h"
30 #include "gpu.h"
31 #include "gpu_print.h"
32 #include "ppcg.h"
33 #include "schedule.h"
34 }
35 
36 #include "llvm/Support/Debug.h"
37 
38 using namespace polly;
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "polly-codegen-ppcg"
42 
43 static cl::opt<bool> DumpSchedule("polly-acc-dump-schedule",
44                                   cl::desc("Dump the computed GPU Schedule"),
45                                   cl::Hidden, cl::init(false), cl::ZeroOrMore,
46                                   cl::cat(PollyCategory));
47 
48 static cl::opt<bool>
49     DumpCode("polly-acc-dump-code",
50              cl::desc("Dump C code describing the GPU mapping"), cl::Hidden,
51              cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
52 
53 /// Create the ast expressions for a ScopStmt.
54 ///
55 /// This function is a callback for to generate the ast expressions for each
56 /// of the scheduled ScopStmts.
57 static __isl_give isl_id_to_ast_expr *pollyBuildAstExprForStmt(
58     void *Stmt, isl_ast_build *Build,
59     isl_multi_pw_aff *(*FunctionIndex)(__isl_take isl_multi_pw_aff *MPA,
60                                        isl_id *Id, void *User),
61     void *UserIndex,
62     isl_ast_expr *(*FunctionExpr)(isl_ast_expr *Expr, isl_id *Id, void *User),
63     void *User_expr) {
64 
65   // TODO: Implement the AST expression generation. For now we just return a
66   // nullptr to ensure that we do not free uninitialized pointers.
67 
68   return nullptr;
69 }
70 
71 namespace {
72 class PPCGCodeGeneration : public ScopPass {
73 public:
74   static char ID;
75 
76   /// The scop that is currently processed.
77   Scop *S;
78 
79   PPCGCodeGeneration() : ScopPass(ID) {}
80 
81   /// Construct compilation options for PPCG.
82   ///
83   /// @returns The compilation options.
84   ppcg_options *createPPCGOptions() {
85     auto DebugOptions =
86         (ppcg_debug_options *)malloc(sizeof(ppcg_debug_options));
87     auto Options = (ppcg_options *)malloc(sizeof(ppcg_options));
88 
89     DebugOptions->dump_schedule_constraints = false;
90     DebugOptions->dump_schedule = false;
91     DebugOptions->dump_final_schedule = false;
92     DebugOptions->dump_sizes = false;
93 
94     Options->debug = DebugOptions;
95 
96     Options->reschedule = true;
97     Options->scale_tile_loops = false;
98     Options->wrap = false;
99 
100     Options->non_negative_parameters = false;
101     Options->ctx = nullptr;
102     Options->sizes = nullptr;
103 
104     Options->tile_size = 32;
105 
106     Options->use_private_memory = false;
107     Options->use_shared_memory = false;
108     Options->max_shared_memory = 0;
109 
110     Options->target = PPCG_TARGET_CUDA;
111     Options->openmp = false;
112     Options->linearize_device_arrays = true;
113     Options->live_range_reordering = false;
114 
115     Options->opencl_compiler_options = nullptr;
116     Options->opencl_use_gpu = false;
117     Options->opencl_n_include_file = 0;
118     Options->opencl_include_files = nullptr;
119     Options->opencl_print_kernel_types = false;
120     Options->opencl_embed_kernel_code = false;
121 
122     Options->save_schedule_file = nullptr;
123     Options->load_schedule_file = nullptr;
124 
125     return Options;
126   }
127 
128   /// Get a tagged access relation containing all accesses of type @p AccessTy.
129   ///
130   /// Instead of a normal access of the form:
131   ///
132   ///   Stmt[i,j,k] -> Array[f_0(i,j,k), f_1(i,j,k)]
133   ///
134   /// a tagged access has the form
135   ///
136   ///   [Stmt[i,j,k] -> id[]] -> Array[f_0(i,j,k), f_1(i,j,k)]
137   ///
138   /// where 'id' is an additional space that references the memory access that
139   /// triggered the access.
140   ///
141   /// @param AccessTy The type of the memory accesses to collect.
142   ///
143   /// @return The relation describing all tagged memory accesses.
144   isl_union_map *getTaggedAccesses(enum MemoryAccess::AccessType AccessTy) {
145     isl_union_map *Accesses = isl_union_map_empty(S->getParamSpace());
146 
147     for (auto &Stmt : *S)
148       for (auto &Acc : Stmt)
149         if (Acc->getType() == AccessTy) {
150           isl_map *Relation = Acc->getAccessRelation();
151           Relation = isl_map_intersect_domain(Relation, Stmt.getDomain());
152 
153           isl_space *Space = isl_map_get_space(Relation);
154           Space = isl_space_range(Space);
155           Space = isl_space_from_range(Space);
156           isl_map *Universe = isl_map_universe(Space);
157           Relation = isl_map_domain_product(Relation, Universe);
158           Accesses = isl_union_map_add_map(Accesses, Relation);
159         }
160 
161     return Accesses;
162   }
163 
164   /// Get the set of all read accesses, tagged with the access id.
165   ///
166   /// @see getTaggedAccesses
167   isl_union_map *getTaggedReads() {
168     return getTaggedAccesses(MemoryAccess::READ);
169   }
170 
171   /// Get the set of all may (and must) accesses, tagged with the access id.
172   ///
173   /// @see getTaggedAccesses
174   isl_union_map *getTaggedMayWrites() {
175     return isl_union_map_union(getTaggedAccesses(MemoryAccess::MAY_WRITE),
176                                getTaggedAccesses(MemoryAccess::MUST_WRITE));
177   }
178 
179   /// Get the set of all must accesses, tagged with the access id.
180   ///
181   /// @see getTaggedAccesses
182   isl_union_map *getTaggedMustWrites() {
183     return getTaggedAccesses(MemoryAccess::MUST_WRITE);
184   }
185 
186   /// Collect parameter and array names as isl_ids.
187   ///
188   /// To reason about the different parameters and arrays used, ppcg requires
189   /// a list of all isl_ids in use. As PPCG traditionally performs
190   /// source-to-source compilation each of these isl_ids is mapped to the
191   /// expression that represents it. As we do not have a corresponding
192   /// expression in Polly, we just map each id to a 'zero' expression to match
193   /// the data format that ppcg expects.
194   ///
195   /// @returns Retun a map from collected ids to 'zero' ast expressions.
196   __isl_give isl_id_to_ast_expr *getNames() {
197     auto *Names = isl_id_to_ast_expr_alloc(
198         S->getIslCtx(),
199         S->getNumParams() + std::distance(S->array_begin(), S->array_end()));
200     auto *Zero = isl_ast_expr_from_val(isl_val_zero(S->getIslCtx()));
201     auto *Space = S->getParamSpace();
202 
203     for (int I = 0, E = S->getNumParams(); I < E; ++I) {
204       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, I);
205       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
206     }
207 
208     for (auto &Array : S->arrays()) {
209       auto Id = Array.second->getBasePtrId();
210       Names = isl_id_to_ast_expr_set(Names, Id, isl_ast_expr_copy(Zero));
211     }
212 
213     isl_space_free(Space);
214     isl_ast_expr_free(Zero);
215 
216     return Names;
217   }
218 
219   /// Create a new PPCG scop from the current scop.
220   ///
221   /// The PPCG scop is initialized with data from the current polly::Scop. From
222   /// this initial data, the data-dependences in the PPCG scop are initialized.
223   /// We do not use Polly's dependence analysis for now, to ensure we match
224   /// the PPCG default behaviour more closely.
225   ///
226   /// @returns A new ppcg scop.
227   ppcg_scop *createPPCGScop() {
228     auto PPCGScop = (ppcg_scop *)malloc(sizeof(ppcg_scop));
229 
230     PPCGScop->options = createPPCGOptions();
231 
232     PPCGScop->start = 0;
233     PPCGScop->end = 0;
234 
235     PPCGScop->context = S->getContext();
236     PPCGScop->domain = S->getDomains();
237     PPCGScop->call = nullptr;
238     PPCGScop->tagged_reads = getTaggedReads();
239     PPCGScop->reads = S->getReads();
240     PPCGScop->live_in = nullptr;
241     PPCGScop->tagged_may_writes = getTaggedMayWrites();
242     PPCGScop->may_writes = S->getWrites();
243     PPCGScop->tagged_must_writes = getTaggedMustWrites();
244     PPCGScop->must_writes = S->getMustWrites();
245     PPCGScop->live_out = nullptr;
246     PPCGScop->tagged_must_kills = isl_union_map_empty(S->getParamSpace());
247     PPCGScop->tagger = nullptr;
248 
249     PPCGScop->independence = nullptr;
250     PPCGScop->dep_flow = nullptr;
251     PPCGScop->tagged_dep_flow = nullptr;
252     PPCGScop->dep_false = nullptr;
253     PPCGScop->dep_forced = nullptr;
254     PPCGScop->dep_order = nullptr;
255     PPCGScop->tagged_dep_order = nullptr;
256 
257     PPCGScop->schedule = S->getScheduleTree();
258     PPCGScop->names = getNames();
259 
260     PPCGScop->pet = nullptr;
261 
262     compute_tagger(PPCGScop);
263     compute_dependences(PPCGScop);
264 
265     return PPCGScop;
266   }
267 
268   /// Collect the list of GPU statements.
269   ///
270   /// Each statement has an id, a pointer to the underlying data structure,
271   /// as well as a list with all memory accesses.
272   ///
273   /// TODO: Initialize the list of memory accesses.
274   ///
275   /// @returns A linked-list of statements.
276   gpu_stmt *getStatements() {
277     gpu_stmt *Stmts = isl_calloc_array(S->getIslCtx(), struct gpu_stmt,
278                                        std::distance(S->begin(), S->end()));
279 
280     int i = 0;
281     for (auto &Stmt : *S) {
282       gpu_stmt *GPUStmt = &Stmts[i];
283 
284       GPUStmt->id = Stmt.getDomainId();
285 
286       // We use the pet stmt pointer to keep track of the Polly statements.
287       GPUStmt->stmt = (pet_stmt *)&Stmt;
288       GPUStmt->accesses = nullptr;
289       i++;
290     }
291 
292     return Stmts;
293   }
294 
295   /// Create a default-initialized PPCG GPU program.
296   ///
297   /// @returns A new gpu grogram description.
298   gpu_prog *createPPCGProg(ppcg_scop *PPCGScop) {
299 
300     if (!PPCGScop)
301       return nullptr;
302 
303     auto PPCGProg = isl_calloc_type(S->getIslCtx(), struct gpu_prog);
304 
305     PPCGProg->ctx = S->getIslCtx();
306     PPCGProg->scop = PPCGScop;
307     PPCGProg->context = isl_set_copy(PPCGScop->context);
308     PPCGProg->read = nullptr;
309     PPCGProg->may_write = nullptr;
310     PPCGProg->must_write = nullptr;
311     PPCGProg->tagged_must_kill = nullptr;
312     PPCGProg->may_persist = nullptr;
313     PPCGProg->to_outer = nullptr;
314     PPCGProg->to_inner = nullptr;
315     PPCGProg->any_to_outer = nullptr;
316     PPCGProg->array_order = nullptr;
317     PPCGProg->n_stmts = std::distance(S->begin(), S->end());
318     PPCGProg->stmts = getStatements();
319     PPCGProg->n_array = 0;
320     PPCGProg->array = nullptr;
321 
322     return PPCGProg;
323   }
324 
325   struct PrintGPUUserData {
326     struct cuda_info *CudaInfo;
327     struct gpu_prog *PPCGProg;
328     std::vector<ppcg_kernel *> Kernels;
329   };
330 
331   /// Print a user statement node in the host code.
332   ///
333   /// We use ppcg's printing facilities to print the actual statement and
334   /// additionally build up a list of all kernels that are encountered in the
335   /// host ast.
336   ///
337   /// @param P The printer to print to
338   /// @param Options The printing options to use
339   /// @param Node The node to print
340   /// @param User A user pointer to carry additional data. This pointer is
341   ///             expected to be of type PrintGPUUserData.
342   ///
343   /// @returns A printer to which the output has been printed.
344   static __isl_give isl_printer *
345   printHostUser(__isl_take isl_printer *P,
346                 __isl_take isl_ast_print_options *Options,
347                 __isl_take isl_ast_node *Node, void *User) {
348     auto Data = (struct PrintGPUUserData *)User;
349     auto Id = isl_ast_node_get_annotation(Node);
350 
351     if (Id) {
352       auto Kernel = (struct ppcg_kernel *)isl_id_get_user(Id);
353       isl_id_free(Id);
354       Data->Kernels.push_back(Kernel);
355     }
356 
357     return print_host_user(P, Options, Node, User);
358   }
359 
360   /// Print C code corresponding to the control flow in @p Kernel.
361   ///
362   /// @param Kernel The kernel to print
363   void printKernel(ppcg_kernel *Kernel) {
364     auto *P = isl_printer_to_str(S->getIslCtx());
365     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
366     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
367     P = isl_ast_node_print(Kernel->tree, P, Options);
368     char *String = isl_printer_get_str(P);
369     printf("%s\n", String);
370     free(String);
371     isl_printer_free(P);
372   }
373 
374   /// Print C code corresponding to the GPU code described by @p Tree.
375   ///
376   /// @param Tree An AST describing GPU code
377   /// @param PPCGProg The PPCG program from which @Tree has been constructed.
378   void printGPUTree(isl_ast_node *Tree, gpu_prog *PPCGProg) {
379     auto *P = isl_printer_to_str(S->getIslCtx());
380     P = isl_printer_set_output_format(P, ISL_FORMAT_C);
381 
382     PrintGPUUserData Data;
383     Data.PPCGProg = PPCGProg;
384 
385     auto *Options = isl_ast_print_options_alloc(S->getIslCtx());
386     Options =
387         isl_ast_print_options_set_print_user(Options, printHostUser, &Data);
388     P = isl_ast_node_print(Tree, P, Options);
389     char *String = isl_printer_get_str(P);
390     printf("# host\n");
391     printf("%s\n", String);
392     free(String);
393     isl_printer_free(P);
394 
395     for (auto Kernel : Data.Kernels) {
396       printf("# kernel%d\n", Kernel->id);
397       printKernel(Kernel);
398     }
399   }
400 
401   // Generate a GPU program using PPCG.
402   //
403   // GPU mapping consists of multiple steps:
404   //
405   //  1) Compute new schedule for the program.
406   //  2) Map schedule to GPU (TODO)
407   //  3) Generate code for new schedule (TODO)
408   //
409   // We do not use here the Polly ScheduleOptimizer, as the schedule optimizer
410   // is mostly CPU specific. Instead, we use PPCG's GPU code generation
411   // strategy directly from this pass.
412   gpu_gen *generateGPU(ppcg_scop *PPCGScop, gpu_prog *PPCGProg) {
413 
414     auto PPCGGen = isl_calloc_type(S->getIslCtx(), struct gpu_gen);
415 
416     PPCGGen->ctx = S->getIslCtx();
417     PPCGGen->options = PPCGScop->options;
418     PPCGGen->print = nullptr;
419     PPCGGen->print_user = nullptr;
420     PPCGGen->build_ast_expr = &pollyBuildAstExprForStmt;
421     PPCGGen->prog = PPCGProg;
422     PPCGGen->tree = nullptr;
423     PPCGGen->types.n = 0;
424     PPCGGen->types.name = nullptr;
425     PPCGGen->sizes = nullptr;
426     PPCGGen->used_sizes = nullptr;
427     PPCGGen->kernel_id = 0;
428 
429     // Set scheduling strategy to same strategy PPCG is using.
430     isl_options_set_schedule_outer_coincidence(PPCGGen->ctx, true);
431     isl_options_set_schedule_maximize_band_depth(PPCGGen->ctx, true);
432 
433     isl_schedule *Schedule = get_schedule(PPCGGen);
434 
435     int has_permutable = has_any_permutable_node(Schedule);
436 
437     if (!has_permutable || has_permutable < 0) {
438       Schedule = isl_schedule_free(Schedule);
439     } else {
440       Schedule = map_to_device(PPCGGen, Schedule);
441       PPCGGen->tree = generate_code(PPCGGen, isl_schedule_copy(Schedule));
442     }
443 
444     if (DumpSchedule) {
445       isl_printer *P = isl_printer_to_str(S->getIslCtx());
446       P = isl_printer_set_yaml_style(P, ISL_YAML_STYLE_BLOCK);
447       P = isl_printer_print_str(P, "Schedule\n");
448       P = isl_printer_print_str(P, "========\n");
449       if (Schedule)
450         P = isl_printer_print_schedule(P, Schedule);
451       else
452         P = isl_printer_print_str(P, "No schedule found\n");
453 
454       printf("%s\n", isl_printer_get_str(P));
455       isl_printer_free(P);
456     }
457 
458     if (DumpCode) {
459       printf("Code\n");
460       printf("====\n");
461       if (PPCGGen->tree)
462         printGPUTree(PPCGGen->tree, PPCGProg);
463       else
464         printf("No code generated\n");
465     }
466 
467     isl_schedule_free(Schedule);
468 
469     return PPCGGen;
470   }
471 
472   /// Free gpu_gen structure.
473   ///
474   /// @param PPCGGen The ppcg_gen object to free.
475   void freePPCGGen(gpu_gen *PPCGGen) {
476     isl_ast_node_free(PPCGGen->tree);
477     isl_union_map_free(PPCGGen->sizes);
478     isl_union_map_free(PPCGGen->used_sizes);
479     free(PPCGGen);
480   }
481 
482   bool runOnScop(Scop &CurrentScop) override {
483     S = &CurrentScop;
484 
485     auto PPCGScop = createPPCGScop();
486     auto PPCGProg = createPPCGProg(PPCGScop);
487     auto PPCGGen = generateGPU(PPCGScop, PPCGProg);
488     freePPCGGen(PPCGGen);
489     gpu_prog_free(PPCGProg);
490     ppcg_scop_free(PPCGScop);
491 
492     return true;
493   }
494 
495   void printScop(raw_ostream &, Scop &) const override {}
496 
497   void getAnalysisUsage(AnalysisUsage &AU) const override {
498     AU.addRequired<DominatorTreeWrapperPass>();
499     AU.addRequired<RegionInfoPass>();
500     AU.addRequired<ScalarEvolutionWrapperPass>();
501     AU.addRequired<ScopDetection>();
502     AU.addRequired<ScopInfoRegionPass>();
503     AU.addRequired<LoopInfoWrapperPass>();
504 
505     AU.addPreserved<AAResultsWrapperPass>();
506     AU.addPreserved<BasicAAWrapperPass>();
507     AU.addPreserved<LoopInfoWrapperPass>();
508     AU.addPreserved<DominatorTreeWrapperPass>();
509     AU.addPreserved<GlobalsAAWrapperPass>();
510     AU.addPreserved<PostDominatorTreeWrapperPass>();
511     AU.addPreserved<ScopDetection>();
512     AU.addPreserved<ScalarEvolutionWrapperPass>();
513     AU.addPreserved<SCEVAAWrapperPass>();
514 
515     // FIXME: We do not yet add regions for the newly generated code to the
516     //        region tree.
517     AU.addPreserved<RegionInfoPass>();
518     AU.addPreserved<ScopInfoRegionPass>();
519   }
520 };
521 }
522 
523 char PPCGCodeGeneration::ID = 1;
524 
525 Pass *polly::createPPCGCodeGenerationPass() { return new PPCGCodeGeneration(); }
526 
527 INITIALIZE_PASS_BEGIN(PPCGCodeGeneration, "polly-codegen-ppcg",
528                       "Polly - Apply PPCG translation to SCOP", false, false)
529 INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
530 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
531 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass);
532 INITIALIZE_PASS_DEPENDENCY(RegionInfoPass);
533 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass);
534 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
535 INITIALIZE_PASS_END(PPCGCodeGeneration, "polly-codegen-ppcg",
536                     "Polly - Apply PPCG translation to SCOP", false, false)
537