blob: 13aa4d76950fbfdd1b0edd5c8678d144e02ba96a [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===------ 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
Tobias Grosser0a91f322012-05-29 09:11:46 +000023#include "polly/CodeGen/Cloog.h"
Sebastian Pope1f65542012-05-07 16:35:11 +000024#ifdef CLOOG_FOUND
25
26#define DEBUG_TYPE "polly-codegen"
Tobias Grosser75805372011-04-29 06:27:02 +000027#include "polly/Dependences.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000028#include "polly/LinkAllPasses.h"
Tobias Grosser75805372011-04-29 06:27:02 +000029#include "polly/ScopInfo.h"
30#include "polly/TempScopInfo.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000031#include "polly/CodeGen/CodeGeneration.h"
32#include "polly/CodeGen/BlockGenerators.h"
33#include "polly/CodeGen/LoopGenerators.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000034#include "polly/Support/GICHelper.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000035
36#include "llvm/Module.h"
37#include "llvm/ADT/SetVector.h"
Tobias Grosser900893d2012-03-29 13:10:26 +000038#include "llvm/ADT/PostOrderIterator.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000039#include "llvm/Analysis/LoopInfo.h"
40#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/Debug.h"
Tobias Grosser75805372011-04-29 06:27:02 +000043#include "llvm/Target/TargetData.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000045
46#define CLOOG_INT_GMP 1
47#include "cloog/cloog.h"
48#include "cloog/isl/cloog.h"
49
Raghesh Aloora71989c2011-12-28 02:48:26 +000050#include "isl/aff.h"
51
Tobias Grosser75805372011-04-29 06:27:02 +000052#include <vector>
53#include <utility>
54
55using namespace polly;
56using namespace llvm;
57
58struct isl_set;
59
60namespace polly {
Tobias Grosser75805372011-04-29 06:27:02 +000061static cl::opt<bool>
62OpenMP("enable-polly-openmp",
63 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
64 cl::value_desc("OpenMP code generation enabled if true"),
Tobias Grosser0acfcdb2012-03-16 17:17:16 +000065 cl::init(false), cl::ZeroOrMore);
Tobias Grosser75805372011-04-29 06:27:02 +000066
67static cl::opt<bool>
68AtLeastOnce("enable-polly-atLeastOnce",
69 cl::desc("Give polly the hint, that every loop is executed at least"
70 "once"), cl::Hidden,
71 cl::value_desc("OpenMP code generation enabled if true"),
Tobias Grosser0acfcdb2012-03-16 17:17:16 +000072 cl::init(false), cl::ZeroOrMore);
Tobias Grosser75805372011-04-29 06:27:02 +000073
Tobias Grosser75805372011-04-29 06:27:02 +000074typedef DenseMap<const char*, Value*> CharMapT;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +000075
Tobias Grosser75805372011-04-29 06:27:02 +000076/// Class to generate LLVM-IR that calculates the value of a clast_expr.
77class ClastExpCodeGen {
78 IRBuilder<> &Builder;
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000079 const CharMapT &IVS;
Tobias Grosser75805372011-04-29 06:27:02 +000080
Tobias Grosserbb137e32012-01-24 16:42:28 +000081 Value *codegen(const clast_name *e, Type *Ty);
82 Value *codegen(const clast_term *e, Type *Ty);
83 Value *codegen(const clast_binary *e, Type *Ty);
84 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +000085public:
86
87 // A generator for clast expressions.
88 //
89 // @param B The IRBuilder that defines where the code to calculate the
90 // clast expressions should be inserted.
91 // @param IVMAP A Map that translates strings describing the induction
92 // variables to the Values* that represent these variables
93 // on the LLVM side.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000094 ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +000095
96 // Generates code to calculate a given clast expression.
97 //
98 // @param e The expression to calculate.
99 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000100 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000101};
102
103Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000104 CharMapT::const_iterator I = IVS.find(e->name);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000105
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000106 assert(I != IVS.end() && "Clast name not found");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000107
108 return Builder.CreateSExtOrBitCast(I->second, Ty);
109}
110
111Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
112 APInt a = APInt_from_MPZ(e->val);
113
114 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
115 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
116
117 if (!e->var)
118 return ConstOne;
119
120 Value *var = codegen(e->var, Ty);
121 return Builder.CreateMul(ConstOne, var);
122}
123
124Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
125 Value *LHS = codegen(e->LHS, Ty);
126
127 APInt RHS_AP = APInt_from_MPZ(e->RHS);
128
129 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
130 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
131
132 switch (e->type) {
133 case clast_bin_mod:
134 return Builder.CreateSRem(LHS, RHS);
135 case clast_bin_fdiv:
136 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000137 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000138 Value *One = ConstantInt::get(Ty, 1);
139 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000140 Value *Sum1 = Builder.CreateSub(LHS, RHS);
141 Value *Sum2 = Builder.CreateAdd(Sum1, One);
142 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
143 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
144 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000145 }
146 case clast_bin_cdiv:
147 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000148 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
149 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000150 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000151 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
152 Value *Sum2 = Builder.CreateSub(Sum1, One);
153 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
154 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
155 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000156 }
157 case clast_bin_div:
158 return Builder.CreateSDiv(LHS, RHS);
159 };
160
161 llvm_unreachable("Unknown clast binary expression type");
162}
163
164Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
165 assert(( r->type == clast_red_min
166 || r->type == clast_red_max
167 || r->type == clast_red_sum)
168 && "Clast reduction type not supported");
169 Value *old = codegen(r->elts[0], Ty);
170
171 for (int i=1; i < r->n; ++i) {
172 Value *exprValue = codegen(r->elts[i], Ty);
173
174 switch (r->type) {
175 case clast_red_min:
176 {
177 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
178 old = Builder.CreateSelect(cmp, old, exprValue);
179 break;
180 }
181 case clast_red_max:
182 {
183 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
184 old = Builder.CreateSelect(cmp, old, exprValue);
185 break;
186 }
187 case clast_red_sum:
188 old = Builder.CreateAdd(old, exprValue);
189 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000190 }
Tobias Grosser75805372011-04-29 06:27:02 +0000191 }
192
Tobias Grosserbb137e32012-01-24 16:42:28 +0000193 return old;
194}
195
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000196ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
Tobias Grosserbb137e32012-01-24 16:42:28 +0000197 : Builder(B), IVS(IVMap) {}
198
199Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
200 switch(e->type) {
201 case clast_expr_name:
202 return codegen((const clast_name *)e, Ty);
203 case clast_expr_term:
204 return codegen((const clast_term *)e, Ty);
205 case clast_expr_bin:
206 return codegen((const clast_binary *)e, Ty);
207 case clast_expr_red:
208 return codegen((const clast_reduction *)e, Ty);
209 }
210
211 llvm_unreachable("Unknown clast expression!");
212}
213
Tobias Grosser75805372011-04-29 06:27:02 +0000214class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000215public:
216 const std::vector<std::string> &getParallelLoops();
217
218private:
Tobias Grosser75805372011-04-29 06:27:02 +0000219 // The Scop we code generate.
220 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000221 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000222
223 // The Builder specifies the current location to code generate at.
224 IRBuilder<> &Builder;
225
226 // Map the Values from the old code to their counterparts in the new code.
227 ValueMapT ValueMap;
228
229 // clastVars maps from the textual representation of a clast variable to its
230 // current *Value. clast variables are scheduling variables, original
231 // induction variables or parameters. They are used either in loop bounds or
232 // to define the statement instance that is executed.
233 //
234 // for (s = 0; s < n + 3; ++i)
235 // for (t = s; t < m; ++j)
236 // Stmt(i = s + 3 * m, j = t);
237 //
238 // {s,t,i,j,n,m} is the set of clast variables in this clast.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000239 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000240
241 // Codegenerator for clast expressions.
242 ClastExpCodeGen ExpGen;
243
244 // Do we currently generate parallel code?
245 bool parallelCodeGeneration;
246
247 std::vector<std::string> parallelLoops;
248
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000249 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000250
251 void codegen(const clast_assignment *a, ScopStmt *Statement,
252 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000253 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000254
255 void codegenSubstitutions(const clast_stmt *Assignment,
256 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000257 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000258
259 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000260 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000261
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000262 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000263
264 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000265 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000266
267 /// @brief Create OpenMP structure values.
268 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000269 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000270 /// structure.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000271 SetVector<Value*> getOMPValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000272
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000273 /// @brief Update the internal structures according to a Value Map.
274 ///
275 /// @param VMap A map from old to new values.
276 /// @param Reverse If true, we assume the update should be reversed.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000277 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000278 bool Reverse);
Tobias Grosser75805372011-04-29 06:27:02 +0000279
280 /// @brief Create an OpenMP parallel for loop.
281 ///
282 /// This loop reflects a loop as if it would have been created by an OpenMP
283 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000284 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000285
Tobias Grossere192b232012-05-22 08:46:07 +0000286 /// @brief Check if a loop is parallel
287 ///
288 /// Detect if a clast_for loop can be executed in parallel.
289 ///
290 /// @param f The clast for loop to check.
291 ///
292 /// @return bool Returns true if the incoming clast_for statement can
293 /// execute in parallel.
294 bool isParallelFor(const clast_for *For);
295
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000296 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000297
298 /// @brief Get the number of loop iterations for this loop.
299 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000300 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000301
302 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000303 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000304
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000305 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000306
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000307 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000308
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000309 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000310
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000311 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000312
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000313 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000314
Tobias Grossere9ffea22012-03-15 09:34:48 +0000315 IntegerType *getIntPtrTy();
316
Tobias Grosser75805372011-04-29 06:27:02 +0000317 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000318 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000319
Tobias Grosserd596b372012-03-15 09:34:52 +0000320 ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000321};
322}
323
Tobias Grossere9ffea22012-03-15 09:34:48 +0000324IntegerType *ClastStmtCodeGen::getIntPtrTy() {
325 return P->getAnalysis<TargetData>().getIntPtrType(Builder.getContext());
326}
327
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000328const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
329 return parallelLoops;
330}
331
332void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000333 Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000334 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000335}
336
Tobias Grosserf00bd962012-04-02 12:26:13 +0000337void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
338 unsigned Dim, int VectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000339 std::vector<ValueMapT> *VectorVMap) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000340 const PHINode *PN;
Tobias Grosserf00bd962012-04-02 12:26:13 +0000341 Value *RHS;
342
343 assert(!A->LHS && "Statement assignments do not have left hand side");
344
Tobias Grosserf00bd962012-04-02 12:26:13 +0000345 PN = Stmt->getInductionVariableForDimension(Dim);
Tobias Grosser0905a232012-04-03 12:24:32 +0000346 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
347 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000348
349 if (VectorVMap)
Tobias Grosserf00bd962012-04-02 12:26:13 +0000350 (*VectorVMap)[VectorDim][PN] = RHS;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000351
Tobias Grosserf00bd962012-04-02 12:26:13 +0000352 ValueMap[PN] = RHS;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000353}
354
355void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
356 ScopStmt *Statement, int vectorDim,
357 std::vector<ValueMapT> *VectorVMap) {
358 int Dimension = 0;
359
360 while (Assignment) {
361 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
362 && "Substitions are expected to be assignments");
363 codegen((const clast_assignment *)Assignment, Statement, Dimension,
364 vectorDim, VectorVMap);
365 Assignment = Assignment->next;
366 Dimension++;
367 }
368}
369
370void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
371 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000372 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000373 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000374
375 if (u->substitutions)
376 codegenSubstitutions(u->substitutions, Statement);
377
Tobias Grosser80998e72012-03-02 11:27:28 +0000378 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000379
Tobias Grosser80998e72012-03-02 11:27:28 +0000380 if (VectorDimensions == 1) {
Tobias Grosser55d52082012-03-02 15:20:39 +0000381 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000382 return;
383 }
384
385 VectorValueMapT VectorMap(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000386
387 if (IVS) {
388 assert (u->substitutions && "Substitutions expected!");
389 int i = 0;
390 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
391 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000392 ClastVars[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000393 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000394 i++;
395 }
396 }
397
Tobias Grosser55d52082012-03-02 15:20:39 +0000398 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Domain, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000399}
400
401void ClastStmtCodeGen::codegen(const clast_block *b) {
402 if (b->body)
403 codegen(b->body);
404}
405
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000406void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
407 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000408 BasicBlock *AfterBB;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000409 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000410
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000411 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
412 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
413 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000414
Hongbin Zheng4ac4e152012-04-23 13:03:56 +0000415 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000416
417 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000418 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000419
420 if (f->body)
421 codegen(f->body);
422
423 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000424 ClastVars.erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000425 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000426}
427
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000428SetVector<Value*> ClastStmtCodeGen::getOMPValues() {
429 SetVector<Value*> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000430
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000431 // The clast variables
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000432 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000433 I != E; I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000434 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000435
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000436 // The memory reference base addresses
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000437 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
438 ScopStmt *Stmt = *SI;
439 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
440 E = Stmt->memacc_end(); I != E; ++I) {
441 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000442 Values.insert((BaseAddr));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000443 }
444 }
445
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000446 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000447}
448
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000449void ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000450 bool Reverse) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000451 std::set<Value*> Inserted;
452
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000453 if (Reverse) {
454 OMPGenerator::ValueToValueMapTy ReverseMap;
455
456 for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
457 I != E; ++I)
458 ReverseMap.insert(std::make_pair(I->second, I->first));
459
460 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
461 I != E; I++) {
462 ClastVars[I->first] = ReverseMap[I->second];
463 Inserted.insert(I->second);
464 }
465
466 /// FIXME: At the moment we do not reverse the update of the ValueMap.
467 /// This is incomplet, but the failure should be obvious, such that
468 /// we can fix this later.
469 return;
470 }
471
472 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000473 I != E; I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000474 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000475 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000476 }
477
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000478 for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000479 I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000480 if (Inserted.count(I->first))
481 continue;
482
483 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000484 }
485}
486
Tobias Grosser900893d2012-03-29 13:10:26 +0000487static void clearDomtree(Function *F, DominatorTree &DT) {
488 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
489 std::vector<BasicBlock*> Nodes;
490 for (po_iterator<DomTreeNode*> I = po_begin(N), E = po_end(N); I != E; ++I)
491 Nodes.push_back(I->getBlock());
492
493 for (std::vector<BasicBlock*>::iterator I = Nodes.begin(), E = Nodes.end();
494 I != E; ++I)
495 DT.eraseNode(*I);
496}
497
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000498void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000499 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000500 BasicBlock::iterator LoopBody;
501 IntegerType *IntPtrTy = getIntPtrTy();
502 SetVector<Value*> Values;
503 OMPGenerator::ValueToValueMapTy VMap;
504 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000505
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000506 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
507 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000508 LB = ExpGen.codegen(For->LB, IntPtrTy);
509 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000510
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000511 Values = getOMPValues();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000512
Tobias Grosserebf30082012-03-23 12:20:32 +0000513 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000514 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
515 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000516
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000517 updateWithValueMap(VMap, /* reverse */ false);
518 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000519
520 if (For->body)
521 codegen(For->body);
522
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000523 ClastVars.erase(For->iterator);
524 updateWithValueMap(VMap, /* reverse */ true);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000525
Tobias Grosser900893d2012-03-29 13:10:26 +0000526 clearDomtree((*LoopBody).getParent()->getParent(),
527 P->getAnalysis<DominatorTree>());
528
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000529 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000530}
531
532bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
533 const clast_stmt *stmt = f->body;
534
535 while (stmt) {
536 if (!CLAST_STMT_IS_A(stmt, stmt_user))
537 return false;
538
539 stmt = stmt->next;
540 }
541
542 return true;
543}
544
545int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
546 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
547 isl_set *tmp = isl_set_copy(loopDomain);
548
549 // Calculate a map similar to the identity map, but with the last input
550 // and output dimension not related.
551 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
552 isl_space *Space = isl_set_get_space(loopDomain);
553 Space = isl_space_drop_outputs(Space,
554 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
555 Space = isl_space_map_from_set(Space);
556 isl_map *identity = isl_map_identity(Space);
557 identity = isl_map_add_dims(identity, isl_dim_in, 1);
558 identity = isl_map_add_dims(identity, isl_dim_out, 1);
559
560 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
561 map = isl_map_intersect(map, identity);
562
563 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
564 isl_map *lexmin = isl_map_lexmin(map);
565 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
566
567 isl_set *elements = isl_map_range(sub);
568
569 if (!isl_set_is_singleton(elements)) {
570 isl_set_free(elements);
571 return -1;
572 }
573
574 isl_point *p = isl_set_sample_point(elements);
575
576 isl_int v;
577 isl_int_init(v);
578 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
579 int numberIterations = isl_int_get_si(v);
580 isl_int_clear(v);
581 isl_point_free(p);
582
583 return (numberIterations) / isl_int_get_si(f->stride) + 1;
584}
585
Tobias Grosser2da263e2012-03-15 09:34:55 +0000586void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
587 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
588 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000589
Tobias Grosser2da263e2012-03-15 09:34:55 +0000590 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000591
Tobias Grosser2da263e2012-03-15 09:34:55 +0000592 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000593 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
594 Stride = Stride.zext(LoopIVType->getBitWidth());
595 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
596
Tobias Grosser2da263e2012-03-15 09:34:55 +0000597 std::vector<Value*> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000598 IVS[0] = LB;
599
Tobias Grosser2da263e2012-03-15 09:34:55 +0000600 for (int i = 1; i < VectorWidth; i++)
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000601 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
602
Tobias Grosser00d898d2012-03-15 09:34:58 +0000603 isl_set *Domain = isl_set_from_cloog_domain(F->domain);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000604
605 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000606 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000607
Tobias Grosser2da263e2012-03-15 09:34:55 +0000608 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000609
Tobias Grosser2da263e2012-03-15 09:34:55 +0000610 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000611 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
612 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000613 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000614 }
615
616 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000617 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000618 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000619}
620
Tobias Grossere192b232012-05-22 08:46:07 +0000621
622bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
623 isl_set *Domain = isl_set_from_cloog_domain(f->domain);
624 assert(Domain && "Cannot access domain of loop");
625
626 Dependences &D = P->getAnalysis<Dependences>();
627
628 return D.isParallelDimension(isl_set_copy(Domain), isl_set_n_dim(Domain));
629}
630
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000631void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000632 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000633 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000634 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
635 && (getNumberOfIterations(f) <= 16)) {
636 codegenForVector(f);
637 return;
638 }
639
640 if (OpenMP && !parallelCodeGeneration) {
641 parallelCodeGeneration = true;
642 parallelLoops.push_back(f->iterator);
643 codegenForOpenMP(f);
644 parallelCodeGeneration = false;
645 return;
646 }
647 }
648
649 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000650}
651
652Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000653 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
654 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000655 CmpInst::Predicate P;
656
657 if (eq->sign == 0)
658 P = ICmpInst::ICMP_EQ;
659 else if (eq->sign > 0)
660 P = ICmpInst::ICMP_SGE;
661 else
662 P = ICmpInst::ICMP_SLE;
663
664 return Builder.CreateICmp(P, LHS, RHS);
665}
666
667void ClastStmtCodeGen::codegen(const clast_guard *g) {
668 Function *F = Builder.GetInsertBlock()->getParent();
669 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000670
671 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
672 Builder.GetInsertPoint(), P);
673 CondBB->setName("polly.cond");
674 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
675 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000676 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000677
Tobias Grosserd596b372012-03-15 09:34:52 +0000678 DominatorTree &DT = P->getAnalysis<DominatorTree>();
679 DT.addNewBlock(ThenBB, CondBB);
680 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000681
682 CondBB->getTerminator()->eraseFromParent();
683
684 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000685
686 Value *Predicate = codegen(&(g->eq[0]));
687
688 for (int i = 1; i < g->n; ++i) {
689 Value *TmpPredicate = codegen(&(g->eq[i]));
690 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
691 }
692
693 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
694 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000695 Builder.CreateBr(MergeBB);
696 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000697
698 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000699
700 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000701}
702
703void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
704 if (CLAST_STMT_IS_A(stmt, stmt_root))
705 assert(false && "No second root statement expected");
706 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
707 codegen((const clast_assignment *)stmt);
708 else if (CLAST_STMT_IS_A(stmt, stmt_user))
709 codegen((const clast_user_stmt *)stmt);
710 else if (CLAST_STMT_IS_A(stmt, stmt_block))
711 codegen((const clast_block *)stmt);
712 else if (CLAST_STMT_IS_A(stmt, stmt_for))
713 codegen((const clast_for *)stmt);
714 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
715 codegen((const clast_guard *)stmt);
716
717 if (stmt->next)
718 codegen(stmt->next);
719}
720
721void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000722 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000723
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000724 int i = 0;
725 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
726 PI != PE; ++PI) {
727 assert(i < names->nb_parameters && "Not enough parameter names");
728
729 const SCEV *Param = *PI;
730 Type *Ty = Param->getType();
731
732 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
733 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000734 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000735
736 ++i;
737 }
738}
739
740void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000741 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000742
743 parallelCodeGeneration = false;
744
745 const clast_stmt *stmt = (const clast_stmt*) r;
746 if (stmt->next)
747 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000748}
749
Tobias Grosserd596b372012-03-15 09:34:52 +0000750ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P) :
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000751 S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000752
Tobias Grosser75805372011-04-29 06:27:02 +0000753namespace {
754class CodeGeneration : public ScopPass {
755 Region *region;
756 Scop *S;
757 DominatorTree *DT;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000758 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +0000759
760 std::vector<std::string> parallelLoops;
761
762 public:
763 static char ID;
764
765 CodeGeneration() : ScopPass(ID) {}
766
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000767 // Split the entry edge of the region and generate a new basic block on this
768 // edge. This function also updates ScopInfo and RegionInfo.
769 //
770 // @param region The region where the entry edge will be splitted.
771 BasicBlock *splitEdgeAdvanced(Region *region) {
772 BasicBlock *newBlock;
773 BasicBlock *splitBlock;
774
775 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
776
777 if (DT->dominates(region->getEntry(), newBlock)) {
Tobias Grossercb47dfe2012-02-15 09:58:50 +0000778 BasicBlock *OldBlock = region->getEntry();
779 std::string OldName = OldBlock->getName();
780
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000781 // Update ScopInfo.
782 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
Tobias Grosserf12cea42012-02-15 09:58:53 +0000783 if ((*SI)->getBasicBlock() == OldBlock) {
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000784 (*SI)->setBasicBlock(newBlock);
785 break;
786 }
787
788 // Update RegionInfo.
Tobias Grossercb47dfe2012-02-15 09:58:50 +0000789 splitBlock = OldBlock;
790 OldBlock->setName("polly.split");
791 newBlock->setName(OldName);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000792 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +0000793 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000794 } else {
795 RI->setRegionFor(newBlock, region->getParent());
796 splitBlock = newBlock;
797 }
798
799 return splitBlock;
800 }
801
802 // Create a split block that branches either to the old code or to a new basic
803 // block where the new code can be inserted.
804 //
Tobias Grosserbd608a82012-02-12 12:09:41 +0000805 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000806 // the new code can be generated.
807 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +0000808 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
809 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000810
Tobias Grosserbd608a82012-02-12 12:09:41 +0000811 SplitBlock = splitEdgeAdvanced(region);
812 SplitBlock->setName("polly.split_new_and_old");
813 Function *F = SplitBlock->getParent();
814 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
815 SplitBlock->getTerminator()->eraseFromParent();
816 Builder->SetInsertPoint(SplitBlock);
817 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
818 DT->addNewBlock(StartBlock, SplitBlock);
819 Builder->SetInsertPoint(StartBlock);
820 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000821 }
822
823 // Merge the control flow of the newly generated code with the existing code.
824 //
Tobias Grosserbd608a82012-02-12 12:09:41 +0000825 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000826 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +0000827 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000828 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +0000829 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
830 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000831 Region *R = region;
832
833 if (R->getExit()->getSinglePredecessor())
834 // No splitEdge required. A block with a single predecessor cannot have
835 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +0000836 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000837 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +0000838 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000839 // SplitEdge will never split R->getExit(), as R->getExit() has more than
840 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +0000841 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000842 }
843
Tobias Grosserbd608a82012-02-12 12:09:41 +0000844 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +0000845 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000846
Tobias Grosserbd608a82012-02-12 12:09:41 +0000847 if (DT->dominates(SplitBlock, MergeBlock))
848 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000849 }
850
Tobias Grosser75805372011-04-29 06:27:02 +0000851 bool runOnScop(Scop &scop) {
852 S = &scop;
853 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000854 DT = &getAnalysis<DominatorTree>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000855 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +0000856
857 parallelLoops.clear();
858
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000859 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +0000860
Tobias Grosser5772e652012-02-01 14:23:33 +0000861 // In the CFG the optimized code of the SCoP is generated next to the
862 // original code. Both the new and the original version of the code remain
863 // in the CFG. A branch statement decides which version is executed.
864 // For now, we always execute the new version (the old one is dead code
865 // eliminated by the cleanup passes). In the future we may decide to execute
866 // the new version only if certain run time checks succeed. This will be
867 // useful to support constructs for which we cannot prove all assumptions at
868 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000869 //
870 // Before transformation:
871 //
872 // bb0
873 // |
874 // orig_scop
875 // |
876 // bb1
877 //
878 // After transformation:
879 // bb0
880 // |
881 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +0000882 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000883 // | startBlock
884 // | |
885 // orig_scop new_scop
886 // \ /
887 // \ /
888 // bb1 (joinBlock)
889 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +0000890
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000891 // The builder will be set to startBlock.
892 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000893 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +0000894
Tobias Grosser0ac92142012-02-14 14:02:27 +0000895 mergeControlFlow(splitBlock, &builder);
896 builder.SetInsertPoint(StartBlock->begin());
897
Tobias Grosserd596b372012-03-15 09:34:52 +0000898 ClastStmtCodeGen CodeGen(S, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +0000899 CloogInfo &C = getAnalysis<CloogInfo>();
900 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +0000901
Tobias Grosser75805372011-04-29 06:27:02 +0000902 parallelLoops.insert(parallelLoops.begin(),
903 CodeGen.getParallelLoops().begin(),
904 CodeGen.getParallelLoops().end());
905
Tobias Grosserabb6dcd2011-05-14 19:02:34 +0000906 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000907 }
908
909 virtual void printScop(raw_ostream &OS) const {
910 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
911 PE = parallelLoops.end(); PI != PE; ++PI)
912 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
913 }
914
915 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
916 AU.addRequired<CloogInfo>();
917 AU.addRequired<Dependences>();
918 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +0000919 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +0000920 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000921 AU.addRequired<ScopDetection>();
922 AU.addRequired<ScopInfo>();
923 AU.addRequired<TargetData>();
924
925 AU.addPreserved<CloogInfo>();
926 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +0000927
Tobias Grosser4e3f9a42011-05-23 15:23:36 +0000928 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +0000929 AU.addPreserved<LoopInfo>();
930 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +0000931 AU.addPreserved<ScopDetection>();
932 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +0000933
Tobias Grosser4e3f9a42011-05-23 15:23:36 +0000934 // FIXME: We do not yet add regions for the newly generated code to the
935 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +0000936 AU.addPreserved<RegionInfo>();
937 AU.addPreserved<TempScopInfo>();
938 AU.addPreserved<ScopInfo>();
939 AU.addPreservedID(IndependentBlocksID);
940 }
941};
942}
943
944char CodeGeneration::ID = 1;
945
Tobias Grosser73600b82011-10-08 00:30:40 +0000946INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +0000947 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser73600b82011-10-08 00:30:40 +0000948INITIALIZE_PASS_DEPENDENCY(CloogInfo)
949INITIALIZE_PASS_DEPENDENCY(Dependences)
950INITIALIZE_PASS_DEPENDENCY(DominatorTree)
951INITIALIZE_PASS_DEPENDENCY(RegionInfo)
952INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
953INITIALIZE_PASS_DEPENDENCY(ScopDetection)
954INITIALIZE_PASS_DEPENDENCY(TargetData)
955INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +0000956 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +0000957
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000958Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +0000959 return new CodeGeneration();
960}
Sebastian Pope1f65542012-05-07 16:35:11 +0000961
962#endif // CLOOG_FOUND