1 //===------ CodeGeneration.cpp - Code generate the Scops. -----------------===//
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 // The CodeGeneration pass takes a Scop created by ScopInfo and translates it
11 // back to LLVM-IR using Cloog.
12 //
13 // The Scop describes the high level memory behaviour of a control flow region.
14 // Transformation passes can update the schedule (execution order) of statements
15 // in the Scop. Cloog is used to generate an abstract syntax tree (clast) that
16 // reflects the updated execution order. This clast is used to create new
17 // LLVM-IR that is computational equivalent to the original control flow region,
18 // but executes its code in the new execution order defined by the changed
19 // scattering.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "polly/CodeGen/Cloog.h"
24 #ifdef CLOOG_FOUND
25 
26 #include "polly/Dependences.h"
27 #include "polly/LinkAllPasses.h"
28 #include "polly/Options.h"
29 #include "polly/ScopInfo.h"
30 #include "polly/TempScopInfo.h"
31 #include "polly/CodeGen/CodeGeneration.h"
32 #include "polly/CodeGen/BlockGenerators.h"
33 #include "polly/CodeGen/LoopGenerators.h"
34 #include "polly/CodeGen/PTXGenerator.h"
35 #include "polly/CodeGen/Utils.h"
36 #include "polly/Support/GICHelper.h"
37 #include "polly/Support/ScopHelper.h"
38 
39 #include "llvm/IR/Module.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/PostOrderIterator.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/ScalarEvolutionExpander.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 
48 #define CLOOG_INT_GMP 1
49 #include "cloog/cloog.h"
50 #include "cloog/isl/cloog.h"
51 
52 #include "isl/aff.h"
53 
54 #include <vector>
55 #include <utility>
56 
57 using namespace polly;
58 using namespace llvm;
59 
60 #define DEBUG_TYPE "polly-codegen"
61 
62 struct isl_set;
63 
64 namespace polly {
65 static cl::opt<bool>
66     OpenMP("enable-polly-openmp", cl::desc("Generate OpenMP parallel code"),
67            cl::value_desc("OpenMP code generation enabled if true"),
68            cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
69 
70 #ifdef GPU_CODEGEN
71 static cl::opt<bool>
72     GPGPU("enable-polly-gpgpu", cl::desc("Generate GPU parallel code"),
73           cl::Hidden, cl::value_desc("GPGPU code generation enabled if true"),
74           cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
75 
76 static cl::opt<std::string>
77     GPUTriple("polly-gpgpu-triple",
78               cl::desc("Target triple for GPU code generation"), cl::Hidden,
79               cl::init(""), cl::cat(PollyCategory));
80 #endif /* GPU_CODEGEN */
81 
82 typedef DenseMap<const char *, Value *> CharMapT;
83 
84 /// Class to generate LLVM-IR that calculates the value of a clast_expr.
85 class ClastExpCodeGen {
86   PollyIRBuilder &Builder;
87   const CharMapT &IVS;
88 
89   Value *codegen(const clast_name *e, Type *Ty);
90   Value *codegen(const clast_term *e, Type *Ty);
91   Value *codegen(const clast_binary *e, Type *Ty);
92   Value *codegen(const clast_reduction *r, Type *Ty);
93 
94 public:
95   // A generator for clast expressions.
96   //
97   // @param B The IRBuilder that defines where the code to calculate the
98   //          clast expressions should be inserted.
99   // @param IVMAP A Map that translates strings describing the induction
100   //              variables to the Values* that represent these variables
101   //              on the LLVM side.
102   ClastExpCodeGen(PollyIRBuilder &B, CharMapT &IVMap);
103 
104   // Generates code to calculate a given clast expression.
105   //
106   // @param e The expression to calculate.
107   // @return The Value that holds the result.
108   Value *codegen(const clast_expr *e, Type *Ty);
109 };
110 
111 Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
112   CharMapT::const_iterator I = IVS.find(e->name);
113 
114   assert(I != IVS.end() && "Clast name not found");
115 
116   return Builder.CreateSExtOrBitCast(I->second, Ty);
117 }
118 
119 static APInt APInt_from_MPZ(const mpz_t mpz) {
120   uint64_t *p = nullptr;
121   size_t sz;
122 
123   p = (uint64_t *)mpz_export(p, &sz, -1, sizeof(uint64_t), 0, 0, mpz);
124 
125   if (p) {
126     APInt A((unsigned)mpz_sizeinbase(mpz, 2), (unsigned)sz, p);
127     A = A.zext(A.getBitWidth() + 1);
128     free(p);
129 
130     if (mpz_sgn(mpz) == -1)
131       return -A;
132     else
133       return A;
134   } else {
135     uint64_t val = 0;
136     return APInt(1, 1, &val);
137   }
138 }
139 
140 Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
141   APInt a = APInt_from_MPZ(e->val);
142 
143   Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
144   ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
145 
146   if (!e->var)
147     return ConstOne;
148 
149   Value *var = codegen(e->var, Ty);
150   return Builder.CreateMul(ConstOne, var);
151 }
152 
153 Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
154   Value *LHS = codegen(e->LHS, Ty);
155 
156   APInt RHS_AP = APInt_from_MPZ(e->RHS);
157 
158   Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
159   RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
160 
161   switch (e->type) {
162   case clast_bin_mod:
163     return Builder.CreateSRem(LHS, RHS);
164   case clast_bin_fdiv: {
165     // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
166     Value *One = ConstantInt::get(Ty, 1);
167     Value *Zero = ConstantInt::get(Ty, 0);
168     Value *Sum1 = Builder.CreateSub(LHS, RHS);
169     Value *Sum2 = Builder.CreateAdd(Sum1, One);
170     Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
171     Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
172     return Builder.CreateSDiv(Dividend, RHS);
173   }
174   case clast_bin_cdiv: {
175     // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
176     Value *One = ConstantInt::get(Ty, 1);
177     Value *Zero = ConstantInt::get(Ty, 0);
178     Value *Sum1 = Builder.CreateAdd(LHS, RHS);
179     Value *Sum2 = Builder.CreateSub(Sum1, One);
180     Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
181     Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
182     return Builder.CreateSDiv(Dividend, RHS);
183   }
184   case clast_bin_div:
185     return Builder.CreateSDiv(LHS, RHS);
186   }
187 
188   llvm_unreachable("Unknown clast binary expression type");
189 }
190 
191 Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
192   assert((r->type == clast_red_min || r->type == clast_red_max ||
193           r->type == clast_red_sum) &&
194          "Clast reduction type not supported");
195   Value *old = codegen(r->elts[0], Ty);
196 
197   for (int i = 1; i < r->n; ++i) {
198     Value *exprValue = codegen(r->elts[i], Ty);
199 
200     switch (r->type) {
201     case clast_red_min: {
202       Value *cmp = Builder.CreateICmpSLT(old, exprValue);
203       old = Builder.CreateSelect(cmp, old, exprValue);
204       break;
205     }
206     case clast_red_max: {
207       Value *cmp = Builder.CreateICmpSGT(old, exprValue);
208       old = Builder.CreateSelect(cmp, old, exprValue);
209       break;
210     }
211     case clast_red_sum:
212       old = Builder.CreateAdd(old, exprValue);
213       break;
214     }
215   }
216 
217   return old;
218 }
219 
220 ClastExpCodeGen::ClastExpCodeGen(PollyIRBuilder &B, CharMapT &IVMap)
221     : Builder(B), IVS(IVMap) {}
222 
223 Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
224   switch (e->type) {
225   case clast_expr_name:
226     return codegen((const clast_name *)e, Ty);
227   case clast_expr_term:
228     return codegen((const clast_term *)e, Ty);
229   case clast_expr_bin:
230     return codegen((const clast_binary *)e, Ty);
231   case clast_expr_red:
232     return codegen((const clast_reduction *)e, Ty);
233   }
234 
235   llvm_unreachable("Unknown clast expression!");
236 }
237 
238 class ClastStmtCodeGen {
239 public:
240   const std::vector<std::string> &getParallelLoops();
241 
242 private:
243   // The Scop we code generate.
244   Scop *S;
245   Pass *P;
246 
247   // The Builder specifies the current location to code generate at.
248   PollyIRBuilder &Builder;
249 
250   // Map the Values from the old code to their counterparts in the new code.
251   ValueMapT ValueMap;
252 
253   // Map the loops from the old code to expressions function of the induction
254   // variables in the new code.  For example, when the code generator produces
255   // this AST:
256   //
257   //   for (int c1 = 0; c1 <= 1023; c1 += 1)
258   //     for (int c2 = 0; c2 <= 1023; c2 += 1)
259   //       Stmt(c2 + 3, c1);
260   //
261   // LoopToScev is a map associating:
262   //   "outer loop in the old loop nest" -> SCEV("c2 + 3"),
263   //   "inner loop in the old loop nest" -> SCEV("c1").
264   LoopToScevMapT LoopToScev;
265 
266   // clastVars maps from the textual representation of a clast variable to its
267   // current *Value. clast variables are scheduling variables, original
268   // induction variables or parameters. They are used either in loop bounds or
269   // to define the statement instance that is executed.
270   //
271   //   for (s = 0; s < n + 3; ++i)
272   //     for (t = s; t < m; ++j)
273   //       Stmt(i = s + 3 * m, j = t);
274   //
275   // {s,t,i,j,n,m} is the set of clast variables in this clast.
276   CharMapT ClastVars;
277 
278   // Codegenerator for clast expressions.
279   ClastExpCodeGen ExpGen;
280 
281   // Do we currently generate parallel code?
282   bool parallelCodeGeneration;
283 
284   std::vector<std::string> parallelLoops;
285 
286   void codegen(const clast_assignment *a);
287 
288   void codegen(const clast_assignment *a, ScopStmt *Statement,
289                unsigned Dimension, int vectorDim,
290                std::vector<ValueMapT> *VectorVMap = 0,
291                std::vector<LoopToScevMapT> *VLTS = 0);
292 
293   void codegenSubstitutions(const clast_stmt *Assignment, ScopStmt *Statement,
294                             int vectorDim = 0,
295                             std::vector<ValueMapT> *VectorVMap = 0,
296                             std::vector<LoopToScevMapT> *VLTS = 0);
297 
298   void codegen(const clast_user_stmt *u, std::vector<Value *> *IVS = nullptr,
299                const char *iterator = nullptr,
300                __isl_take isl_set *scatteringDomain = 0);
301 
302   void codegen(const clast_block *b);
303 
304   /// @brief Create a classical sequential loop.
305   void codegenForSequential(const clast_for *f);
306 
307   /// @brief Create OpenMP structure values.
308   ///
309   /// Create a list of values that has to be stored into the OpenMP subfuncition
310   /// structure.
311   SetVector<Value *> getOMPValues(const clast_stmt *Body);
312 
313   /// @brief Update ClastVars and ValueMap according to a value map.
314   ///
315   /// @param VMap A map from old to new values.
316   void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
317 
318   /// @brief Create an OpenMP parallel for loop.
319   ///
320   /// This loop reflects a loop as if it would have been created by an OpenMP
321   /// statement.
322   void codegenForOpenMP(const clast_for *f);
323 
324 #ifdef GPU_CODEGEN
325   /// @brief Create GPGPU device memory access values.
326   ///
327   /// Create a list of values that will be set to be parameters of the GPGPU
328   /// subfunction. These parameters represent device memory base addresses
329   /// and the size in bytes.
330   SetVector<Value *> getGPUValues(unsigned &OutputBytes);
331 
332   /// @brief Create a GPU parallel for loop.
333   ///
334   /// This loop reflects a loop as if it would have been created by a GPU
335   /// statement.
336   void codegenForGPGPU(const clast_for *F);
337 
338   /// @brief Get innermost for loop.
339   const clast_stmt *getScheduleInfo(const clast_for *F,
340                                     std::vector<int> &NumIters,
341                                     unsigned &LoopDepth,
342                                     unsigned &NonPLoopDepth);
343 #endif /* GPU_CODEGEN */
344 
345   /// @brief Check if a loop is parallel
346   ///
347   /// Detect if a clast_for loop can be executed in parallel.
348   ///
349   /// @param For The clast for loop to check.
350   ///
351   /// @return bool Returns true if the incoming clast_for statement can
352   ///              execute in parallel.
353   bool isParallelFor(const clast_for *For);
354 
355   bool isInnermostLoop(const clast_for *f);
356 
357   /// @brief Get the number of loop iterations for this loop.
358   /// @param f The clast for loop to check.
359   int getNumberOfIterations(const clast_for *f);
360 
361   /// @brief Create vector instructions for this loop.
362   void codegenForVector(const clast_for *f);
363 
364   void codegen(const clast_for *f);
365 
366   Value *codegen(const clast_equation *eq);
367 
368   void codegen(const clast_guard *g);
369 
370   void codegen(const clast_stmt *stmt);
371 
372   void addParameters(const CloogNames *names);
373 
374   IntegerType *getIntPtrTy();
375 
376 public:
377   void codegen(const clast_root *r);
378 
379   ClastStmtCodeGen(Scop *scop, PollyIRBuilder &B, Pass *P);
380 };
381 }
382 
383 IntegerType *ClastStmtCodeGen::getIntPtrTy() {
384   return P->getAnalysis<DataLayoutPass>().getDataLayout().getIntPtrType(
385       Builder.getContext());
386 }
387 
388 const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
389   return parallelLoops;
390 }
391 
392 void ClastStmtCodeGen::codegen(const clast_assignment *a) {
393   Value *V = ExpGen.codegen(a->RHS, getIntPtrTy());
394   ClastVars[a->LHS] = V;
395 }
396 
397 void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
398                                unsigned Dim, int VectorDim,
399                                std::vector<ValueMapT> *VectorVMap,
400                                std::vector<LoopToScevMapT> *VLTS) {
401   Value *RHS;
402 
403   assert(!A->LHS && "Statement assignments do not have left hand side");
404 
405   RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
406 
407   const llvm::SCEV *URHS = S->getSE()->getUnknown(RHS);
408   if (VLTS)
409     (*VLTS)[VectorDim][Stmt->getLoopForDimension(Dim)] = URHS;
410   LoopToScev[Stmt->getLoopForDimension(Dim)] = URHS;
411 
412   const PHINode *PN = Stmt->getInductionVariableForDimension(Dim);
413   if (PN) {
414     RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
415 
416     if (VectorVMap)
417       (*VectorVMap)[VectorDim][PN] = RHS;
418 
419     ValueMap[PN] = RHS;
420   }
421 }
422 
423 void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
424                                             ScopStmt *Statement, int vectorDim,
425                                             std::vector<ValueMapT> *VectorVMap,
426                                             std::vector<LoopToScevMapT> *VLTS) {
427   int Dimension = 0;
428 
429   while (Assignment) {
430     assert(CLAST_STMT_IS_A(Assignment, stmt_ass) &&
431            "Substitions are expected to be assignments");
432     codegen((const clast_assignment *)Assignment, Statement, Dimension,
433             vectorDim, VectorVMap, VLTS);
434     Assignment = Assignment->next;
435     Dimension++;
436   }
437 }
438 
439 // Takes the cloog specific domain and translates it into a map Statement ->
440 // PartialSchedule, where the PartialSchedule contains all the dimensions that
441 // have been code generated up to this point.
442 static __isl_give isl_map *extractPartialSchedule(ScopStmt *Statement,
443                                                   __isl_take isl_set *Domain) {
444   isl_map *Schedule = Statement->getScattering();
445   int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
446   int UnscheduledDimensions =
447       isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
448 
449   isl_set_free(Domain);
450 
451   return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
452                              UnscheduledDimensions);
453 }
454 
455 void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
456                                std::vector<Value *> *IVS, const char *iterator,
457                                __isl_take isl_set *Domain) {
458   ScopStmt *Statement = (ScopStmt *)u->statement->usr;
459 
460   if (u->substitutions)
461     codegenSubstitutions(u->substitutions, Statement);
462 
463   int VectorDimensions = IVS ? IVS->size() : 1;
464 
465   if (VectorDimensions == 1) {
466     BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P);
467     isl_set_free(Domain);
468     return;
469   }
470 
471   VectorValueMapT VectorMap(VectorDimensions);
472   std::vector<LoopToScevMapT> VLTS(VectorDimensions);
473 
474   if (IVS) {
475     assert(u->substitutions && "Substitutions expected!");
476     int i = 0;
477     for (std::vector<Value *>::iterator II = IVS->begin(), IE = IVS->end();
478          II != IE; ++II) {
479       ClastVars[iterator] = *II;
480       codegenSubstitutions(u->substitutions, Statement, i, &VectorMap, &VLTS);
481       i++;
482     }
483   }
484 
485   // Copy the current value map into all vector maps if the key wasn't
486   // available yet. This is needed in case vector codegen is performed in
487   // OpenMP subfunctions.
488   for (auto KV : ValueMap)
489     for (int i = 0; i < VectorDimensions; ++i)
490       VectorMap[i].insert(KV);
491 
492   isl_map *Schedule = extractPartialSchedule(Statement, Domain);
493   VectorBlockGenerator::generate(Builder, *Statement, VectorMap, VLTS, Schedule,
494                                  P);
495   isl_map_free(Schedule);
496 }
497 
498 void ClastStmtCodeGen::codegen(const clast_block *b) {
499   if (b->body)
500     codegen(b->body);
501 }
502 
503 void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
504   Value *LowerBound, *UpperBound, *IV, *Stride;
505   BasicBlock *ExitBlock;
506   Type *IntPtrTy = getIntPtrTy();
507 
508   LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
509   UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
510   Stride = Builder.getInt(APInt_from_MPZ(f->stride));
511 
512   IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, ExitBlock,
513                   CmpInst::ICMP_SLE);
514 
515   // Add loop iv to symbols.
516   ClastVars[f->iterator] = IV;
517 
518   if (f->body)
519     codegen(f->body);
520 
521   // Loop is finished, so remove its iv from the live symbols.
522   ClastVars.erase(f->iterator);
523   Builder.SetInsertPoint(ExitBlock->begin());
524 }
525 
526 // Helper class to determine all scalar parameters used in the basic blocks of a
527 // clast. Scalar parameters are scalar variables defined outside of the SCoP.
528 class ParameterVisitor : public ClastVisitor {
529   std::set<Value *> Values;
530 
531 public:
532   ParameterVisitor() : ClastVisitor(), Values() {}
533 
534   void visitUser(const clast_user_stmt *Stmt) {
535     const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
536     const BasicBlock *BB = S->getBasicBlock();
537 
538     // Check all the operands of instructions in the basic block.
539     for (const Instruction &Inst : *BB) {
540       for (Value *SrcVal : Inst.operands()) {
541         if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
542           if (S->getParent()->getRegion().contains(OpInst))
543             continue;
544 
545         if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
546           Values.insert(SrcVal);
547       }
548     }
549   }
550 
551   // Iterator to iterate over the values found.
552   typedef std::set<Value *>::const_iterator const_iterator;
553   inline const_iterator begin() const { return Values.begin(); }
554   inline const_iterator end() const { return Values.end(); }
555 };
556 
557 SetVector<Value *> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
558   SetVector<Value *> Values;
559 
560   // The clast variables
561   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
562        I++)
563     Values.insert(I->second);
564 
565   // Find the temporaries that are referenced in the clast statements'
566   // basic blocks but are not defined by these blocks (e.g., references
567   // to function arguments or temporaries defined before the start of
568   // the SCoP).
569   ParameterVisitor Params;
570   Params.visit(Body);
571 
572   for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
573        PI != PE; ++PI) {
574     Value *V = *PI;
575     Values.insert(V);
576     DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
577   }
578 
579   return Values;
580 }
581 
582 void
583 ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap) {
584   std::set<Value *> Inserted;
585 
586   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
587        I++) {
588     ClastVars[I->first] = VMap[I->second];
589     Inserted.insert(I->second);
590   }
591 
592   for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
593                                                  E = VMap.end();
594        I != E; ++I) {
595     if (Inserted.count(I->first))
596       continue;
597 
598     ValueMap[I->first] = I->second;
599   }
600 }
601 
602 static void clearDomtree(Function *F, DominatorTree &DT) {
603   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
604   std::vector<BasicBlock *> Nodes;
605   for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
606     Nodes.push_back(I->getBlock());
607 
608   for (std::vector<BasicBlock *>::iterator I = Nodes.begin(), E = Nodes.end();
609        I != E; ++I)
610     DT.eraseNode(*I);
611 }
612 
613 void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
614   Value *Stride, *LB, *UB, *IV;
615   BasicBlock::iterator LoopBody;
616   IntegerType *IntPtrTy = getIntPtrTy();
617   SetVector<Value *> Values;
618   OMPGenerator::ValueToValueMapTy VMap;
619   OMPGenerator OMPGen(Builder, P);
620 
621   Stride = Builder.getInt(APInt_from_MPZ(For->stride));
622   Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
623   LB = ExpGen.codegen(For->LB, IntPtrTy);
624   UB = ExpGen.codegen(For->UB, IntPtrTy);
625 
626   Values = getOMPValues(For->body);
627 
628   IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
629   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
630   Builder.SetInsertPoint(LoopBody);
631 
632   // Save the current values.
633   const ValueMapT ValueMapCopy = ValueMap;
634   const CharMapT ClastVarsCopy = ClastVars;
635 
636   updateWithValueMap(VMap);
637   ClastVars[For->iterator] = IV;
638 
639   if (For->body)
640     codegen(For->body);
641 
642   // Restore the original values.
643   ValueMap = ValueMapCopy;
644   ClastVars = ClastVarsCopy;
645 
646   clearDomtree((*LoopBody).getParent()->getParent(),
647                P->getAnalysis<DominatorTreeWrapperPass>().getDomTree());
648 
649   Builder.SetInsertPoint(AfterLoop);
650 }
651 
652 #ifdef GPU_CODEGEN
653 static unsigned getArraySizeInBytes(const ArrayType *AT) {
654   unsigned Bytes = AT->getNumElements();
655   if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
656     Bytes *= getArraySizeInBytes(T);
657   else
658     Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
659 
660   return Bytes;
661 }
662 
663 SetVector<Value *> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
664   SetVector<Value *> Values;
665   OutputBytes = 0;
666 
667   // Record the memory reference base addresses.
668   for (ScopStmt *Stmt : *S) {
669     for (MemoryAccess *MA : *Stmt) {
670       Value *BaseAddr = const_cast<Value *>(MA->getBaseAddr());
671       Values.insert((BaseAddr));
672 
673       // FIXME: we assume that there is one and only one array to be written
674       // in a SCoP.
675       int NumWrites = 0;
676       if (MA->isWrite()) {
677         ++NumWrites;
678         assert(NumWrites <= 1 &&
679                "We support at most one array to be written in a SCoP.");
680         if (const PointerType *PT =
681                 dyn_cast<PointerType>(BaseAddr->getType())) {
682           Type *T = PT->getArrayElementType();
683           const ArrayType *ATy = dyn_cast<ArrayType>(T);
684           OutputBytes = getArraySizeInBytes(ATy);
685         }
686       }
687     }
688   }
689 
690   return Values;
691 }
692 
693 const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
694                                                     std::vector<int> &NumIters,
695                                                     unsigned &LoopDepth,
696                                                     unsigned &NonPLoopDepth) {
697   clast_stmt *Stmt = (clast_stmt *)F;
698   const clast_for *Result;
699   bool NonParaFlag = false;
700   LoopDepth = 0;
701   NonPLoopDepth = 0;
702 
703   while (Stmt) {
704     if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
705       const clast_for *T = (clast_for *)Stmt;
706       if (isParallelFor(T)) {
707         if (!NonParaFlag) {
708           NumIters.push_back(getNumberOfIterations(T));
709           Result = T;
710         }
711       } else
712         NonParaFlag = true;
713 
714       Stmt = T->body;
715       LoopDepth++;
716       continue;
717     }
718     Stmt = Stmt->next;
719   }
720 
721   assert(NumIters.size() == 4 &&
722          "The loops should be tiled into 4-depth parallel loops and an "
723          "innermost non-parallel one (if exist).");
724   NonPLoopDepth = LoopDepth - NumIters.size();
725   assert(NonPLoopDepth <= 1 &&
726          "We support only one innermost non-parallel loop currently.");
727   return (const clast_stmt *)Result->body;
728 }
729 
730 void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
731   BasicBlock::iterator LoopBody;
732   SetVector<Value *> Values;
733   SetVector<Value *> IVS;
734   std::vector<int> NumIterations;
735   PTXGenerator::ValueToValueMapTy VMap;
736 
737   assert(!GPUTriple.empty() &&
738          "Target triple should be set properly for GPGPU code generation.");
739   PTXGenerator PTXGen(Builder, P, GPUTriple);
740 
741   // Get original IVS and ScopStmt
742   unsigned TiledLoopDepth, NonPLoopDepth;
743   const clast_stmt *InnerStmt =
744       getScheduleInfo(F, NumIterations, TiledLoopDepth, NonPLoopDepth);
745   const clast_stmt *TmpStmt;
746   const clast_user_stmt *U;
747   const clast_for *InnerFor;
748   if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
749     InnerFor = (const clast_for *)InnerStmt;
750     TmpStmt = InnerFor->body;
751   } else
752     TmpStmt = InnerStmt;
753   U = (const clast_user_stmt *)TmpStmt;
754   ScopStmt *Statement = (ScopStmt *)U->statement->usr;
755   for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
756     const Value *IV = Statement->getInductionVariableForDimension(i);
757     IVS.insert(const_cast<Value *>(IV));
758   }
759 
760   unsigned OutBytes;
761   Values = getGPUValues(OutBytes);
762   PTXGen.setOutputBytes(OutBytes);
763   PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
764 
765   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
766   Builder.SetInsertPoint(LoopBody);
767 
768   BasicBlock *AfterBB = 0;
769   if (NonPLoopDepth) {
770     Value *LowerBound, *UpperBound, *IV, *Stride;
771     Type *IntPtrTy = getIntPtrTy();
772     LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
773     UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
774     Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
775     IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
776                     CmpInst::ICMP_SLE);
777     const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
778     Value *OldIV = const_cast<Value *>(OldIV_);
779     VMap.insert(std::make_pair(OldIV, IV));
780   }
781 
782   updateWithValueMap(VMap);
783 
784   BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P);
785 
786   if (AfterBB)
787     Builder.SetInsertPoint(AfterBB->begin());
788 
789   // FIXME: The replacement of the host base address with the parameter of ptx
790   // subfunction should have been done by updateWithValueMap. We use the
791   // following codes to avoid affecting other parts of Polly. This should be
792   // fixed later.
793   Function *FN = Builder.GetInsertBlock()->getParent();
794   for (unsigned j = 0; j < Values.size(); j++) {
795     Value *baseAddr = Values[j];
796     for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
797       for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
798         I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
799     }
800   }
801   Builder.SetInsertPoint(AfterLoop);
802   PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
803                                 NumIterations[2], NumIterations[3]);
804   PTXGen.finishGeneration(FN);
805 }
806 #endif
807 
808 bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
809   const clast_stmt *stmt = f->body;
810 
811   while (stmt) {
812     if (!CLAST_STMT_IS_A(stmt, stmt_user))
813       return false;
814 
815     stmt = stmt->next;
816   }
817 
818   return true;
819 }
820 
821 int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
822   isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
823   int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
824   if (NumberOfIterations == -1)
825     return -1;
826   return NumberOfIterations / mpz_get_si(For->stride) + 1;
827 }
828 
829 void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
830   DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
831   int VectorWidth = getNumberOfIterations(F);
832 
833   Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
834 
835   APInt Stride = APInt_from_MPZ(F->stride);
836   IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
837   Stride = Stride.zext(LoopIVType->getBitWidth());
838   Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
839 
840   std::vector<Value *> IVS(VectorWidth);
841   IVS[0] = LB;
842 
843   for (int i = 1; i < VectorWidth; i++)
844     IVS[i] = Builder.CreateAdd(IVS[i - 1], StrideValue, "p_vector_iv");
845 
846   isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(F->domain));
847 
848   // Add loop iv to symbols.
849   ClastVars[F->iterator] = LB;
850 
851   const clast_stmt *Stmt = F->body;
852 
853   while (Stmt) {
854     codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
855             isl_set_copy(Domain));
856     Stmt = Stmt->next;
857   }
858 
859   // Loop is finished, so remove its iv from the live symbols.
860   isl_set_free(Domain);
861   ClastVars.erase(F->iterator);
862 }
863 
864 bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
865   isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
866   assert(Domain && "Cannot access domain of loop");
867 
868   Dependences &D = P->getAnalysis<Dependences>();
869 
870   return D.isParallelDimension(Domain, isl_set_n_dim(Domain));
871 }
872 
873 void ClastStmtCodeGen::codegen(const clast_for *f) {
874   bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
875   if ((Vector || OpenMP) && isParallelFor(f)) {
876     if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f)) &&
877         (getNumberOfIterations(f) <= 16)) {
878       codegenForVector(f);
879       return;
880     }
881 
882     if (OpenMP && !parallelCodeGeneration) {
883       parallelCodeGeneration = true;
884       parallelLoops.push_back(f->iterator);
885       codegenForOpenMP(f);
886       parallelCodeGeneration = false;
887       return;
888     }
889   }
890 
891 #ifdef GPU_CODEGEN
892   if (GPGPU && isParallelFor(f)) {
893     if (!parallelCodeGeneration) {
894       parallelCodeGeneration = true;
895       parallelLoops.push_back(f->iterator);
896       codegenForGPGPU(f);
897       parallelCodeGeneration = false;
898       return;
899     }
900   }
901 #endif
902 
903   codegenForSequential(f);
904 }
905 
906 Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
907   Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
908   Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
909   CmpInst::Predicate P;
910 
911   if (eq->sign == 0)
912     P = ICmpInst::ICMP_EQ;
913   else if (eq->sign > 0)
914     P = ICmpInst::ICMP_SGE;
915   else
916     P = ICmpInst::ICMP_SLE;
917 
918   return Builder.CreateICmp(P, LHS, RHS);
919 }
920 
921 void ClastStmtCodeGen::codegen(const clast_guard *g) {
922   Function *F = Builder.GetInsertBlock()->getParent();
923   LLVMContext &Context = F->getContext();
924 
925   BasicBlock *CondBB =
926       SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
927   CondBB->setName("polly.cond");
928   BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
929   MergeBB->setName("polly.merge");
930   BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
931 
932   DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
933   DT.addNewBlock(ThenBB, CondBB);
934   DT.changeImmediateDominator(MergeBB, CondBB);
935 
936   CondBB->getTerminator()->eraseFromParent();
937 
938   Builder.SetInsertPoint(CondBB);
939 
940   Value *Predicate = codegen(&(g->eq[0]));
941 
942   for (int i = 1; i < g->n; ++i) {
943     Value *TmpPredicate = codegen(&(g->eq[i]));
944     Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
945   }
946 
947   Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
948   Builder.SetInsertPoint(ThenBB);
949   Builder.CreateBr(MergeBB);
950   Builder.SetInsertPoint(ThenBB->begin());
951 
952   LoopInfo &LI = P->getAnalysis<LoopInfo>();
953   Loop *L = LI.getLoopFor(CondBB);
954   if (L)
955     L->addBasicBlockToLoop(ThenBB, LI.getBase());
956 
957   codegen(g->then);
958 
959   Builder.SetInsertPoint(MergeBB->begin());
960 }
961 
962 void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
963   if (CLAST_STMT_IS_A(stmt, stmt_root))
964     assert(false && "No second root statement expected");
965   else if (CLAST_STMT_IS_A(stmt, stmt_ass))
966     codegen((const clast_assignment *)stmt);
967   else if (CLAST_STMT_IS_A(stmt, stmt_user))
968     codegen((const clast_user_stmt *)stmt);
969   else if (CLAST_STMT_IS_A(stmt, stmt_block))
970     codegen((const clast_block *)stmt);
971   else if (CLAST_STMT_IS_A(stmt, stmt_for))
972     codegen((const clast_for *)stmt);
973   else if (CLAST_STMT_IS_A(stmt, stmt_guard))
974     codegen((const clast_guard *)stmt);
975 
976   if (stmt->next)
977     codegen(stmt->next);
978 }
979 
980 void ClastStmtCodeGen::addParameters(const CloogNames *names) {
981   SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
982 
983   int i = 0;
984   for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
985        PI != PE; ++PI) {
986     assert(i < names->nb_parameters && "Not enough parameter names");
987 
988     const SCEV *Param = *PI;
989     Type *Ty = Param->getType();
990 
991     Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
992     Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
993     ClastVars[names->parameters[i]] = V;
994 
995     ++i;
996   }
997 }
998 
999 void ClastStmtCodeGen::codegen(const clast_root *r) {
1000   addParameters(r->names);
1001 
1002   parallelCodeGeneration = false;
1003 
1004   const clast_stmt *stmt = (const clast_stmt *)r;
1005   if (stmt->next)
1006     codegen(stmt->next);
1007 }
1008 
1009 ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, PollyIRBuilder &B, Pass *P)
1010     : S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
1011 
1012 namespace {
1013 class CodeGeneration : public ScopPass {
1014   std::vector<std::string> ParallelLoops;
1015 
1016 public:
1017   static char ID;
1018 
1019   CodeGeneration() : ScopPass(ID) {}
1020 
1021   bool runOnScop(Scop &S) {
1022     ParallelLoops.clear();
1023 
1024     assert(!S.getRegion().isTopLevelRegion() &&
1025            "Top level regions are not supported");
1026 
1027     simplifyRegion(&S, this);
1028 
1029     BasicBlock *StartBlock = executeScopConditionally(S, this);
1030 
1031     PollyIRBuilder Builder(StartBlock->begin());
1032 
1033     ClastStmtCodeGen CodeGen(&S, Builder, this);
1034     CloogInfo &C = getAnalysis<CloogInfo>();
1035     CodeGen.codegen(C.getClast());
1036 
1037     ParallelLoops.insert(ParallelLoops.begin(),
1038                          CodeGen.getParallelLoops().begin(),
1039                          CodeGen.getParallelLoops().end());
1040     return true;
1041   }
1042 
1043   virtual void printScop(raw_ostream &OS) const {
1044     for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
1045                                                   PE = ParallelLoops.end();
1046          PI != PE; ++PI)
1047       OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1048   }
1049 
1050   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1051     AU.addRequired<CloogInfo>();
1052     AU.addRequired<Dependences>();
1053     AU.addRequired<DominatorTreeWrapperPass>();
1054     AU.addRequired<RegionInfo>();
1055     AU.addRequired<ScalarEvolution>();
1056     AU.addRequired<ScopDetection>();
1057     AU.addRequired<ScopInfo>();
1058     AU.addRequired<DataLayoutPass>();
1059     AU.addRequired<LoopInfo>();
1060 
1061     AU.addPreserved<CloogInfo>();
1062     AU.addPreserved<Dependences>();
1063     AU.addPreserved<LoopInfo>();
1064     AU.addPreserved<DominatorTreeWrapperPass>();
1065     AU.addPreserved<ScopDetection>();
1066     AU.addPreserved<ScalarEvolution>();
1067 
1068     // FIXME: We do not yet add regions for the newly generated code to the
1069     //        region tree.
1070     AU.addPreserved<RegionInfo>();
1071     AU.addPreserved<TempScopInfo>();
1072     AU.addPreserved<ScopInfo>();
1073     AU.addPreservedID(IndependentBlocksID);
1074   }
1075 };
1076 }
1077 
1078 char CodeGeneration::ID = 1;
1079 
1080 Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
1081 
1082 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1083                       "Polly - Create LLVM-IR from SCoPs", false, false);
1084 INITIALIZE_PASS_DEPENDENCY(CloogInfo);
1085 INITIALIZE_PASS_DEPENDENCY(Dependences);
1086 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
1087 INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1088 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1089 INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1090 INITIALIZE_PASS_DEPENDENCY(DataLayoutPass);
1091 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1092                     "Polly - Create LLVM-IR from SCoPs", false, false)
1093 
1094 #endif // CLOOG_FOUND
1095