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/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 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   // FIXME: This might need to get a proper address space. Hard code 0 for now.
362   return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext(), 0u);
363 }
364 
365 const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
366   return parallelLoops;
367 }
368 
369 void ClastStmtCodeGen::codegen(const clast_assignment *a) {
370   Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
371   ClastVars[a->LHS] = V;
372 }
373 
374 void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
375                                unsigned Dim, int VectorDim,
376                                std::vector<ValueMapT> *VectorVMap) {
377   const PHINode *PN;
378   Value *RHS;
379 
380   assert(!A->LHS && "Statement assignments do not have left hand side");
381 
382   PN = Stmt->getInductionVariableForDimension(Dim);
383   RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
384   RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
385 
386   if (VectorVMap)
387     (*VectorVMap)[VectorDim][PN] = RHS;
388 
389   ValueMap[PN] = RHS;
390 }
391 
392 void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
393                                              ScopStmt *Statement, int vectorDim,
394   std::vector<ValueMapT> *VectorVMap) {
395   int Dimension = 0;
396 
397   while (Assignment) {
398     assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
399            && "Substitions are expected to be assignments");
400     codegen((const clast_assignment *)Assignment, Statement, Dimension,
401             vectorDim, VectorVMap);
402     Assignment = Assignment->next;
403     Dimension++;
404   }
405 }
406 
407 void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
408                                std::vector<Value*> *IVS , const char *iterator,
409                                isl_set *Domain) {
410   ScopStmt *Statement = (ScopStmt *)u->statement->usr;
411 
412   if (u->substitutions)
413     codegenSubstitutions(u->substitutions, Statement);
414 
415   int VectorDimensions = IVS ? IVS->size() : 1;
416 
417   if (VectorDimensions == 1) {
418     BlockGenerator::generate(Builder, *Statement, ValueMap, P);
419     return;
420   }
421 
422   VectorValueMapT VectorMap(VectorDimensions);
423 
424   if (IVS) {
425     assert (u->substitutions && "Substitutions expected!");
426     int i = 0;
427     for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
428          II != IE; ++II) {
429       ClastVars[iterator] = *II;
430       codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
431       i++;
432     }
433   }
434 
435   VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Domain, P);
436 }
437 
438 void ClastStmtCodeGen::codegen(const clast_block *b) {
439   if (b->body)
440     codegen(b->body);
441 }
442 
443 void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
444   Value *LowerBound, *UpperBound, *IV, *Stride;
445   BasicBlock *AfterBB;
446   Type *IntPtrTy = getIntPtrTy();
447 
448   LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
449   UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
450   Stride = Builder.getInt(APInt_from_MPZ(f->stride));
451 
452   IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
453                   CmpInst::ICMP_SLE);
454 
455   // Add loop iv to symbols.
456   ClastVars[f->iterator] = IV;
457 
458   if (f->body)
459     codegen(f->body);
460 
461   // Loop is finished, so remove its iv from the live symbols.
462   ClastVars.erase(f->iterator);
463   Builder.SetInsertPoint(AfterBB->begin());
464 }
465 
466 SetVector<Value*> ClastStmtCodeGen::getOMPValues() {
467   SetVector<Value*> Values;
468 
469   // The clast variables
470   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
471        I != E; I++)
472     Values.insert(I->second);
473 
474   // The memory reference base addresses
475   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
476     ScopStmt *Stmt = *SI;
477     for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
478          E = Stmt->memacc_end(); I != E; ++I) {
479       Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
480       Values.insert((BaseAddr));
481     }
482   }
483 
484   return Values;
485 }
486 
487 void ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
488                                           bool Reverse) {
489   std::set<Value*> Inserted;
490 
491   if (Reverse) {
492     OMPGenerator::ValueToValueMapTy ReverseMap;
493 
494     for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
495          I != E; ++I)
496        ReverseMap.insert(std::make_pair(I->second, I->first));
497 
498     for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
499          I != E; I++) {
500       ClastVars[I->first] = ReverseMap[I->second];
501       Inserted.insert(I->second);
502     }
503 
504     /// FIXME: At the moment we do not reverse the update of the ValueMap.
505     ///        This is incomplet, but the failure should be obvious, such that
506     ///        we can fix this later.
507     return;
508   }
509 
510   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
511        I != E; I++) {
512     ClastVars[I->first] = VMap[I->second];
513     Inserted.insert(I->second);
514   }
515 
516   for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
517        I != E; ++I) {
518     if (Inserted.count(I->first))
519       continue;
520 
521     ValueMap[I->first] = I->second;
522   }
523 }
524 
525 static void clearDomtree(Function *F, DominatorTree &DT) {
526   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
527   std::vector<BasicBlock*> Nodes;
528   for (po_iterator<DomTreeNode*> I = po_begin(N), E = po_end(N); I != E; ++I)
529     Nodes.push_back(I->getBlock());
530 
531   for (std::vector<BasicBlock*>::iterator I = Nodes.begin(), E = Nodes.end();
532        I != E; ++I)
533     DT.eraseNode(*I);
534 }
535 
536 void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
537   Value *Stride, *LB, *UB, *IV;
538   BasicBlock::iterator LoopBody;
539   IntegerType *IntPtrTy = getIntPtrTy();
540   SetVector<Value*> Values;
541   OMPGenerator::ValueToValueMapTy VMap;
542   OMPGenerator OMPGen(Builder, P);
543 
544   Stride = Builder.getInt(APInt_from_MPZ(For->stride));
545   Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
546   LB = ExpGen.codegen(For->LB, IntPtrTy);
547   UB = ExpGen.codegen(For->UB, IntPtrTy);
548 
549   Values = getOMPValues();
550 
551   IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
552   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
553   Builder.SetInsertPoint(LoopBody);
554 
555   updateWithValueMap(VMap, /* reverse */ false);
556   ClastVars[For->iterator] = IV;
557 
558   if (For->body)
559     codegen(For->body);
560 
561   ClastVars.erase(For->iterator);
562   updateWithValueMap(VMap, /* reverse */ true);
563 
564   clearDomtree((*LoopBody).getParent()->getParent(),
565                P->getAnalysis<DominatorTree>());
566 
567   Builder.SetInsertPoint(AfterLoop);
568 }
569 
570 #ifdef GPU_CODEGEN
571 static unsigned getArraySizeInBytes(const ArrayType *AT) {
572   unsigned Bytes = AT->getNumElements();
573   if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
574     Bytes *= getArraySizeInBytes(T);
575   else
576     Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
577 
578   return Bytes;
579 }
580 
581 SetVector<Value*> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
582   SetVector<Value*> Values;
583   OutputBytes = 0;
584 
585   // Record the memory reference base addresses.
586   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
587     ScopStmt *Stmt = *SI;
588     for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
589          E = Stmt->memacc_end(); I != E; ++I) {
590       Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
591       Values.insert((BaseAddr));
592 
593       // FIXME: we assume that there is one and only one array to be written
594       // in a SCoP.
595       int NumWrites = 0;
596       if ((*I)->isWrite()) {
597         ++NumWrites;
598         assert(NumWrites <= 1 &&
599                "We support at most one array to be written in a SCoP.");
600         if (const PointerType * PT =
601             dyn_cast<PointerType>(BaseAddr->getType())) {
602           Type *T = PT->getArrayElementType();
603           const ArrayType *ATy = dyn_cast<ArrayType>(T);
604           OutputBytes = getArraySizeInBytes(ATy);
605         }
606       }
607     }
608   }
609 
610   return Values;
611 }
612 
613 const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
614                                                     std::vector<int> &NumIters,
615                                                     unsigned &LoopDepth,
616                                                     unsigned &NonPLoopDepth) {
617   clast_stmt *Stmt = (clast_stmt *)F;
618   const clast_for *Result;
619   bool NonParaFlag = false;
620   LoopDepth = 0;
621   NonPLoopDepth = 0;
622 
623   while (Stmt) {
624     if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
625       const clast_for *T = (clast_for *) Stmt;
626       if (isParallelFor(T)) {
627         if (!NonParaFlag) {
628           NumIters.push_back(getNumberOfIterations(T));
629           Result = T;
630         }
631       } else
632         NonParaFlag = true;
633 
634       Stmt = T->body;
635       LoopDepth++;
636       continue;
637     }
638     Stmt = Stmt->next;
639   }
640 
641   assert(NumIters.size() == 4 &&
642          "The loops should be tiled into 4-depth parallel loops and an "
643          "innermost non-parallel one (if exist).");
644   NonPLoopDepth = LoopDepth - NumIters.size();
645   assert(NonPLoopDepth <= 1
646          && "We support only one innermost non-parallel loop currently.");
647   return (const clast_stmt *)Result->body;
648 }
649 
650 void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
651   BasicBlock::iterator LoopBody;
652   SetVector<Value *> Values;
653   SetVector<Value *> IVS;
654   std::vector<int> NumIterations;
655   PTXGenerator::ValueToValueMapTy VMap;
656 
657   assert(!GPUTriple.empty()
658          && "Target triple should be set properly for GPGPU code generation.");
659   PTXGenerator PTXGen(Builder, P, GPUTriple);
660 
661   // Get original IVS and ScopStmt
662   unsigned TiledLoopDepth, NonPLoopDepth;
663   const clast_stmt *InnerStmt = getScheduleInfo(F, NumIterations,
664                                                 TiledLoopDepth, NonPLoopDepth);
665   const clast_stmt *TmpStmt;
666   const clast_user_stmt *U;
667   const clast_for *InnerFor;
668   if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
669     InnerFor = (const clast_for *)InnerStmt;
670     TmpStmt = InnerFor->body;
671   } else
672     TmpStmt = InnerStmt;
673   U = (const clast_user_stmt *) TmpStmt;
674   ScopStmt *Statement = (ScopStmt *) U->statement->usr;
675   for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
676     const Value* IV = Statement->getInductionVariableForDimension(i);
677     IVS.insert(const_cast<Value *>(IV));
678   }
679 
680   unsigned OutBytes;
681   Values = getGPUValues(OutBytes);
682   PTXGen.setOutputBytes(OutBytes);
683   PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
684 
685   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
686   Builder.SetInsertPoint(LoopBody);
687 
688   BasicBlock *AfterBB = 0;
689   if (NonPLoopDepth) {
690     Value *LowerBound, *UpperBound, *IV, *Stride;
691     Type *IntPtrTy = getIntPtrTy();
692     LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
693     UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
694     Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
695     IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB);
696     const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
697     Value *OldIV = const_cast<Value *>(OldIV_);
698     VMap.insert(std::make_pair<Value*, Value*>(OldIV, IV));
699   }
700 
701   updateWithValueMap(VMap, /* reverse */ false);
702   BlockGenerator::generate(Builder, *Statement, ValueMap, P);
703   updateWithValueMap(VMap, /* reverse */ true);
704 
705   if (AfterBB)
706     Builder.SetInsertPoint(AfterBB->begin());
707 
708   // FIXME: The replacement of the host base address with the parameter of ptx
709   // subfunction should have been done by updateWithValueMap. We use the
710   // following codes to avoid affecting other parts of Polly. This should be
711   // fixed later.
712   Function *FN = Builder.GetInsertBlock()->getParent();
713   for (unsigned j = 0; j < Values.size(); j++) {
714     Value *baseAddr = Values[j];
715     for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
716       for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
717         I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
718     }
719   }
720   Builder.SetInsertPoint(AfterLoop);
721   PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
722                                 NumIterations[2], NumIterations[3]);
723   PTXGen.finishGeneration(FN);
724 }
725 #endif
726 
727 bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
728   const clast_stmt *stmt = f->body;
729 
730   while (stmt) {
731     if (!CLAST_STMT_IS_A(stmt, stmt_user))
732       return false;
733 
734     stmt = stmt->next;
735   }
736 
737   return true;
738 }
739 
740 int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
741   isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
742   isl_set *tmp = isl_set_copy(loopDomain);
743 
744   // Calculate a map similar to the identity map, but with the last input
745   // and output dimension not related.
746   //  [i0, i1, i2, i3] -> [i0, i1, i2, o0]
747   isl_space *Space = isl_set_get_space(loopDomain);
748   Space = isl_space_drop_outputs(Space,
749                                  isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
750   Space = isl_space_map_from_set(Space);
751   isl_map *identity = isl_map_identity(Space);
752   identity = isl_map_add_dims(identity, isl_dim_in, 1);
753   identity = isl_map_add_dims(identity, isl_dim_out, 1);
754 
755   isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
756   map = isl_map_intersect(map, identity);
757 
758   isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
759   isl_map *lexmin = isl_map_lexmin(map);
760   isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
761 
762   isl_set *elements = isl_map_range(sub);
763 
764   if (!isl_set_is_singleton(elements)) {
765     isl_set_free(elements);
766     return -1;
767   }
768 
769   isl_point *p = isl_set_sample_point(elements);
770 
771   isl_int v;
772   isl_int_init(v);
773   isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
774   int numberIterations = isl_int_get_si(v);
775   isl_int_clear(v);
776   isl_point_free(p);
777 
778   return (numberIterations) / isl_int_get_si(f->stride) + 1;
779 }
780 
781 void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
782   DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
783   int VectorWidth = getNumberOfIterations(F);
784 
785   Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
786 
787   APInt Stride = APInt_from_MPZ(F->stride);
788   IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
789   Stride =  Stride.zext(LoopIVType->getBitWidth());
790   Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
791 
792   std::vector<Value*> IVS(VectorWidth);
793   IVS[0] = LB;
794 
795   for (int i = 1; i < VectorWidth; i++)
796     IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
797 
798   isl_set *Domain = isl_set_from_cloog_domain(F->domain);
799 
800   // Add loop iv to symbols.
801   ClastVars[F->iterator] = LB;
802 
803   const clast_stmt *Stmt = F->body;
804 
805   while (Stmt) {
806     codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
807             isl_set_copy(Domain));
808     Stmt = Stmt->next;
809   }
810 
811   // Loop is finished, so remove its iv from the live symbols.
812   isl_set_free(Domain);
813   ClastVars.erase(F->iterator);
814 }
815 
816 
817 bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
818   isl_set *Domain = isl_set_from_cloog_domain(f->domain);
819   assert(Domain && "Cannot access domain of loop");
820 
821   Dependences &D = P->getAnalysis<Dependences>();
822 
823   return D.isParallelDimension(isl_set_copy(Domain), isl_set_n_dim(Domain));
824 }
825 
826 void ClastStmtCodeGen::codegen(const clast_for *f) {
827   bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
828   if ((Vector || OpenMP) && isParallelFor(f)) {
829     if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
830         && (getNumberOfIterations(f) <= 16)) {
831       codegenForVector(f);
832       return;
833     }
834 
835     if (OpenMP && !parallelCodeGeneration) {
836       parallelCodeGeneration = true;
837       parallelLoops.push_back(f->iterator);
838       codegenForOpenMP(f);
839       parallelCodeGeneration = false;
840       return;
841     }
842   }
843 
844 #ifdef GPU_CODEGEN
845   if (GPGPU && isParallelFor(f)) {
846     if (!parallelCodeGeneration) {
847       parallelCodeGeneration = true;
848       parallelLoops.push_back(f->iterator);
849       codegenForGPGPU(f);
850       parallelCodeGeneration = false;
851       return;
852     }
853   }
854 #endif
855 
856   codegenForSequential(f);
857 }
858 
859 Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
860   Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
861   Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
862   CmpInst::Predicate P;
863 
864   if (eq->sign == 0)
865     P = ICmpInst::ICMP_EQ;
866   else if (eq->sign > 0)
867     P = ICmpInst::ICMP_SGE;
868   else
869     P = ICmpInst::ICMP_SLE;
870 
871   return Builder.CreateICmp(P, LHS, RHS);
872 }
873 
874 void ClastStmtCodeGen::codegen(const clast_guard *g) {
875   Function *F = Builder.GetInsertBlock()->getParent();
876   LLVMContext &Context = F->getContext();
877 
878   BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
879                                       Builder.GetInsertPoint(), P);
880   CondBB->setName("polly.cond");
881   BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
882   MergeBB->setName("polly.merge");
883   BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
884 
885   DominatorTree &DT = P->getAnalysis<DominatorTree>();
886   DT.addNewBlock(ThenBB, CondBB);
887   DT.changeImmediateDominator(MergeBB, CondBB);
888 
889   CondBB->getTerminator()->eraseFromParent();
890 
891   Builder.SetInsertPoint(CondBB);
892 
893   Value *Predicate = codegen(&(g->eq[0]));
894 
895   for (int i = 1; i < g->n; ++i) {
896     Value *TmpPredicate = codegen(&(g->eq[i]));
897     Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
898   }
899 
900   Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
901   Builder.SetInsertPoint(ThenBB);
902   Builder.CreateBr(MergeBB);
903   Builder.SetInsertPoint(ThenBB->begin());
904 
905   codegen(g->then);
906 
907   Builder.SetInsertPoint(MergeBB->begin());
908 }
909 
910 void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
911   if	    (CLAST_STMT_IS_A(stmt, stmt_root))
912     assert(false && "No second root statement expected");
913   else if (CLAST_STMT_IS_A(stmt, stmt_ass))
914     codegen((const clast_assignment *)stmt);
915   else if (CLAST_STMT_IS_A(stmt, stmt_user))
916     codegen((const clast_user_stmt *)stmt);
917   else if (CLAST_STMT_IS_A(stmt, stmt_block))
918     codegen((const clast_block *)stmt);
919   else if (CLAST_STMT_IS_A(stmt, stmt_for))
920     codegen((const clast_for *)stmt);
921   else if (CLAST_STMT_IS_A(stmt, stmt_guard))
922     codegen((const clast_guard *)stmt);
923 
924   if (stmt->next)
925     codegen(stmt->next);
926 }
927 
928 void ClastStmtCodeGen::addParameters(const CloogNames *names) {
929   SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
930 
931   int i = 0;
932   for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
933        PI != PE; ++PI) {
934     assert(i < names->nb_parameters && "Not enough parameter names");
935 
936     const SCEV *Param = *PI;
937     Type *Ty = Param->getType();
938 
939     Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
940     Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
941     ClastVars[names->parameters[i]] = V;
942 
943     ++i;
944   }
945 }
946 
947 void ClastStmtCodeGen::codegen(const clast_root *r) {
948   addParameters(r->names);
949 
950   parallelCodeGeneration = false;
951 
952   const clast_stmt *stmt = (const clast_stmt*) r;
953   if (stmt->next)
954     codegen(stmt->next);
955 }
956 
957 ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P) :
958     S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
959 
960 namespace {
961 class CodeGeneration : public ScopPass {
962   std::vector<std::string> ParallelLoops;
963 
964   public:
965   static char ID;
966 
967   CodeGeneration() : ScopPass(ID) {}
968 
969 
970   bool runOnScop(Scop &S) {
971     ParallelLoops.clear();
972 
973     assert(S.getRegion().isSimple() && "Only simple regions are supported");
974 
975     BasicBlock *StartBlock = executeScopConditionally(S, this);
976 
977     IRBuilder<> Builder(StartBlock->begin());
978 
979     ClastStmtCodeGen CodeGen(&S, Builder, this);
980     CloogInfo &C = getAnalysis<CloogInfo>();
981     CodeGen.codegen(C.getClast());
982 
983     ParallelLoops.insert(ParallelLoops.begin(),
984                          CodeGen.getParallelLoops().begin(),
985                          CodeGen.getParallelLoops().end());
986     return true;
987   }
988 
989   virtual void printScop(raw_ostream &OS) const {
990     for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
991          PE = ParallelLoops.end(); PI != PE; ++PI)
992       OS << "Parallel loop with iterator '" << *PI << "' generated\n";
993   }
994 
995   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
996     AU.addRequired<CloogInfo>();
997     AU.addRequired<Dependences>();
998     AU.addRequired<DominatorTree>();
999     AU.addRequired<RegionInfo>();
1000     AU.addRequired<ScalarEvolution>();
1001     AU.addRequired<ScopDetection>();
1002     AU.addRequired<ScopInfo>();
1003     AU.addRequired<DataLayout>();
1004 
1005     AU.addPreserved<CloogInfo>();
1006     AU.addPreserved<Dependences>();
1007 
1008     // FIXME: We do not create LoopInfo for the newly generated loops.
1009     AU.addPreserved<LoopInfo>();
1010     AU.addPreserved<DominatorTree>();
1011     AU.addPreserved<ScopDetection>();
1012     AU.addPreserved<ScalarEvolution>();
1013 
1014     // FIXME: We do not yet add regions for the newly generated code to the
1015     //        region tree.
1016     AU.addPreserved<RegionInfo>();
1017     AU.addPreserved<TempScopInfo>();
1018     AU.addPreserved<ScopInfo>();
1019     AU.addPreservedID(IndependentBlocksID);
1020   }
1021 };
1022 }
1023 
1024 char CodeGeneration::ID = 1;
1025 
1026 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1027                       "Polly - Create LLVM-IR from SCoPs", false, false)
1028 INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1029 INITIALIZE_PASS_DEPENDENCY(Dependences)
1030 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1031 INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1032 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1033 INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1034 INITIALIZE_PASS_DEPENDENCY(DataLayout)
1035 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1036                       "Polly - Create LLVM-IR from SCoPs", false, false)
1037 
1038 Pass *polly::createCodeGenerationPass() {
1039   return new CodeGeneration();
1040 }
1041 
1042 #endif // CLOOG_FOUND
1043