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