blob: 6305a09cd6829258b1c49c3fcdfb0833e730d064 [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"
Tobias Grosser6217e182012-08-03 12:50:07 +000034#include "polly/CodeGen/PTXGenerator.h"
Tobias Grosser3a275d22012-05-29 09:11:54 +000035#include "polly/CodeGen/Utils.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000036#include "polly/Support/GICHelper.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000037
38#include "llvm/Module.h"
39#include "llvm/ADT/SetVector.h"
Tobias Grosser900893d2012-03-29 13:10:26 +000040#include "llvm/ADT/PostOrderIterator.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000041#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
Tobias Grosser75805372011-04-29 06:27:02 +000045#include "llvm/Target/TargetData.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000047
48#define CLOOG_INT_GMP 1
49#include "cloog/cloog.h"
50#include "cloog/isl/cloog.h"
51
Raghesh Aloora71989c2011-12-28 02:48:26 +000052#include "isl/aff.h"
53
Tobias Grosser75805372011-04-29 06:27:02 +000054#include <vector>
55#include <utility>
56
57using namespace polly;
58using namespace llvm;
59
60struct isl_set;
61
62namespace polly {
Tobias Grosser75805372011-04-29 06:27:02 +000063static cl::opt<bool>
64OpenMP("enable-polly-openmp",
65 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
66 cl::value_desc("OpenMP code generation enabled if true"),
Tobias Grosser0acfcdb2012-03-16 17:17:16 +000067 cl::init(false), cl::ZeroOrMore);
Tobias Grosser75805372011-04-29 06:27:02 +000068
Tobias Grosser6217e182012-08-03 12:50:07 +000069#ifdef GPU_CODEGEN
70static cl::opt<bool>
71GPGPU("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
76static cl::opt<std::string>
77GPUTriple("polly-gpgpu-triple",
78 cl::desc("Target triple for GPU code generation"),
79 cl::Hidden, cl::init(""));
80#endif /* GPU_CODEGEN */
81
Tobias Grosser75805372011-04-29 06:27:02 +000082static cl::opt<bool>
83AtLeastOnce("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"),
Tobias Grosser0acfcdb2012-03-16 17:17:16 +000087 cl::init(false), cl::ZeroOrMore);
Tobias Grosser75805372011-04-29 06:27:02 +000088
Tobias Grosser75805372011-04-29 06:27:02 +000089typedef DenseMap<const char*, Value*> CharMapT;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +000090
Tobias Grosser75805372011-04-29 06:27:02 +000091/// Class to generate LLVM-IR that calculates the value of a clast_expr.
92class ClastExpCodeGen {
93 IRBuilder<> &Builder;
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000094 const CharMapT &IVS;
Tobias Grosser75805372011-04-29 06:27:02 +000095
Tobias Grosserbb137e32012-01-24 16:42:28 +000096 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);
Tobias Grosser75805372011-04-29 06:27:02 +0000100public:
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.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000109 ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000110
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.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000115 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000116};
117
118Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000119 CharMapT::const_iterator I = IVS.find(e->name);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000120
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000121 assert(I != IVS.end() && "Clast name not found");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000122
123 return Builder.CreateSExtOrBitCast(I->second, Ty);
124}
125
126Value *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
139Value *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 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000152 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000153 Value *One = ConstantInt::get(Ty, 1);
154 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000155 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);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000160 }
161 case clast_bin_cdiv:
162 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000163 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
164 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000165 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000166 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);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000171 }
172 case clast_bin_div:
173 return Builder.CreateSDiv(LHS, RHS);
174 };
175
176 llvm_unreachable("Unknown clast binary expression type");
177}
178
179Value *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;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000205 }
Tobias Grosser75805372011-04-29 06:27:02 +0000206 }
207
Tobias Grosserbb137e32012-01-24 16:42:28 +0000208 return old;
209}
210
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000211ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
Tobias Grosserbb137e32012-01-24 16:42:28 +0000212 : Builder(B), IVS(IVMap) {}
213
214Value *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
Tobias Grosser75805372011-04-29 06:27:02 +0000229class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000230public:
231 const std::vector<std::string> &getParallelLoops();
232
233private:
Tobias Grosser75805372011-04-29 06:27:02 +0000234 // The Scop we code generate.
235 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000236 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000237
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.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000254 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000255
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
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000264 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000265
266 void codegen(const clast_assignment *a, ScopStmt *Statement,
267 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000268 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000269
270 void codegenSubstitutions(const clast_stmt *Assignment,
271 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000272 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000273
274 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000275 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000276
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000277 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000278
279 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000280 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000281
282 /// @brief Create OpenMP structure values.
283 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000284 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000285 /// structure.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000286 SetVector<Value*> getOMPValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000287
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000288 /// @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.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000292 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000293 bool Reverse);
Tobias Grosser75805372011-04-29 06:27:02 +0000294
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.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000299 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000300
Tobias Grosser6217e182012-08-03 12:50:07 +0000301#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
Tobias Grossere192b232012-05-22 08:46:07 +0000322 /// @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
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000332 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000333
334 /// @brief Get the number of loop iterations for this loop.
335 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000336 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000337
338 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000339 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000340
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000341 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000342
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000343 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000344
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000345 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000346
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000347 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000348
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000349 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000350
Tobias Grossere9ffea22012-03-15 09:34:48 +0000351 IntegerType *getIntPtrTy();
352
Tobias Grosser75805372011-04-29 06:27:02 +0000353 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000354 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000355
Tobias Grosserd596b372012-03-15 09:34:52 +0000356 ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000357};
358}
359
Tobias Grossere9ffea22012-03-15 09:34:48 +0000360IntegerType *ClastStmtCodeGen::getIntPtrTy() {
361 return P->getAnalysis<TargetData>().getIntPtrType(Builder.getContext());
362}
363
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000364const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
365 return parallelLoops;
366}
367
368void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000369 Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000370 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000371}
372
Tobias Grosserf00bd962012-04-02 12:26:13 +0000373void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
374 unsigned Dim, int VectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000375 std::vector<ValueMapT> *VectorVMap) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000376 const PHINode *PN;
Tobias Grosserf00bd962012-04-02 12:26:13 +0000377 Value *RHS;
378
379 assert(!A->LHS && "Statement assignments do not have left hand side");
380
Tobias Grosserf00bd962012-04-02 12:26:13 +0000381 PN = Stmt->getInductionVariableForDimension(Dim);
Tobias Grosser0905a232012-04-03 12:24:32 +0000382 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
383 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000384
385 if (VectorVMap)
Tobias Grosserf00bd962012-04-02 12:26:13 +0000386 (*VectorVMap)[VectorDim][PN] = RHS;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000387
Tobias Grosserf00bd962012-04-02 12:26:13 +0000388 ValueMap[PN] = RHS;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000389}
390
391void 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
406void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
407 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000408 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000409 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000410
411 if (u->substitutions)
412 codegenSubstitutions(u->substitutions, Statement);
413
Tobias Grosser80998e72012-03-02 11:27:28 +0000414 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000415
Tobias Grosser80998e72012-03-02 11:27:28 +0000416 if (VectorDimensions == 1) {
Tobias Grosser55d52082012-03-02 15:20:39 +0000417 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000418 return;
419 }
420
421 VectorValueMapT VectorMap(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000422
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) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000428 ClastVars[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000429 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000430 i++;
431 }
432 }
433
Tobias Grosser55d52082012-03-02 15:20:39 +0000434 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Domain, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000435}
436
437void ClastStmtCodeGen::codegen(const clast_block *b) {
438 if (b->body)
439 codegen(b->body);
440}
441
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000442void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
443 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000444 BasicBlock *AfterBB;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000445 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000446
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000447 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
448 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
449 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000450
Hongbin Zheng4ac4e152012-04-23 13:03:56 +0000451 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000452
453 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000454 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000455
456 if (f->body)
457 codegen(f->body);
458
459 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000460 ClastVars.erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000461 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000462}
463
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000464SetVector<Value*> ClastStmtCodeGen::getOMPValues() {
465 SetVector<Value*> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000466
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000467 // The clast variables
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000468 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000469 I != E; I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000470 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000471
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000472 // The memory reference base addresses
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000473 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());
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000478 Values.insert((BaseAddr));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000479 }
480 }
481
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000482 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000483}
484
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000485void ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000486 bool Reverse) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000487 std::set<Value*> Inserted;
488
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000489 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();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000509 I != E; I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000510 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000511 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000512 }
513
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000514 for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000515 I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000516 if (Inserted.count(I->first))
517 continue;
518
519 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000520 }
521}
522
Tobias Grosser900893d2012-03-29 13:10:26 +0000523static 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
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000534void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000535 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000536 BasicBlock::iterator LoopBody;
537 IntegerType *IntPtrTy = getIntPtrTy();
538 SetVector<Value*> Values;
539 OMPGenerator::ValueToValueMapTy VMap;
540 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000541
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000542 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
543 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000544 LB = ExpGen.codegen(For->LB, IntPtrTy);
545 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000546
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000547 Values = getOMPValues();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000548
Tobias Grosserebf30082012-03-23 12:20:32 +0000549 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000550 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
551 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000552
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000553 updateWithValueMap(VMap, /* reverse */ false);
554 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000555
556 if (For->body)
557 codegen(For->body);
558
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000559 ClastVars.erase(For->iterator);
560 updateWithValueMap(VMap, /* reverse */ true);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000561
Tobias Grosser900893d2012-03-29 13:10:26 +0000562 clearDomtree((*LoopBody).getParent()->getParent(),
563 P->getAnalysis<DominatorTree>());
564
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000565 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000566}
567
Tobias Grosser6217e182012-08-03 12:50:07 +0000568#ifdef GPU_CODEGEN
569static 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
579SetVector<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
611const 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
648void 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
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000725bool 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
738int 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
Tobias Grosser2da263e2012-03-15 09:34:55 +0000779void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
780 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
781 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000782
Tobias Grosser2da263e2012-03-15 09:34:55 +0000783 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000784
Tobias Grosser2da263e2012-03-15 09:34:55 +0000785 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000786 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
787 Stride = Stride.zext(LoopIVType->getBitWidth());
788 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
789
Tobias Grosser2da263e2012-03-15 09:34:55 +0000790 std::vector<Value*> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000791 IVS[0] = LB;
792
Tobias Grosser2da263e2012-03-15 09:34:55 +0000793 for (int i = 1; i < VectorWidth; i++)
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000794 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
795
Tobias Grosser00d898d2012-03-15 09:34:58 +0000796 isl_set *Domain = isl_set_from_cloog_domain(F->domain);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000797
798 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000799 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000800
Tobias Grosser2da263e2012-03-15 09:34:55 +0000801 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000802
Tobias Grosser2da263e2012-03-15 09:34:55 +0000803 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000804 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
805 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000806 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000807 }
808
809 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000810 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000811 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000812}
813
Tobias Grossere192b232012-05-22 08:46:07 +0000814
815bool 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
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000824void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000825 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000826 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000827 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
Tobias Grosser6217e182012-08-03 12:50:07 +0000842#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
Tobias Grosserce3f5372012-03-02 11:26:42 +0000854 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000855}
856
857Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000858 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
859 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000860 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
872void ClastStmtCodeGen::codegen(const clast_guard *g) {
873 Function *F = Builder.GetInsertBlock()->getParent();
874 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000875
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");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000881 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000882
Tobias Grosserd596b372012-03-15 09:34:52 +0000883 DominatorTree &DT = P->getAnalysis<DominatorTree>();
884 DT.addNewBlock(ThenBB, CondBB);
885 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000886
887 CondBB->getTerminator()->eraseFromParent();
888
889 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000890
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);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000900 Builder.CreateBr(MergeBB);
901 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000902
903 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000904
905 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000906}
907
908void 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
926void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000927 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000928
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000929 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);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000939 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000940
941 ++i;
942 }
943}
944
945void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000946 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000947
948 parallelCodeGeneration = false;
949
950 const clast_stmt *stmt = (const clast_stmt*) r;
951 if (stmt->next)
952 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000953}
954
Tobias Grosserd596b372012-03-15 09:34:52 +0000955ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P) :
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000956 S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000957
Tobias Grosser75805372011-04-29 06:27:02 +0000958namespace {
959class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +0000960 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +0000961
962 public:
963 static char ID;
964
965 CodeGeneration() : ScopPass(ID) {}
966
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000967
Tobias Grosser3a275d22012-05-29 09:11:54 +0000968 bool runOnScop(Scop &S) {
969 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000970
Tobias Grosser3a275d22012-05-29 09:11:54 +0000971 assert(S.getRegion().isSimple() && "Only simple regions are supported");
Tobias Grossercb47dfe2012-02-15 09:58:50 +0000972
Tobias Grosser3a275d22012-05-29 09:11:54 +0000973 BasicBlock *StartBlock = executeScopConditionally(S, this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000974
Tobias Grosser3a275d22012-05-29 09:11:54 +0000975 IRBuilder<> Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000976
Tobias Grosser3a275d22012-05-29 09:11:54 +0000977 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +0000978 CloogInfo &C = getAnalysis<CloogInfo>();
979 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +0000980
Tobias Grosser3a275d22012-05-29 09:11:54 +0000981 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +0000982 CodeGen.getParallelLoops().begin(),
983 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +0000984 return true;
Tobias Grosser75805372011-04-29 06:27:02 +0000985 }
986
987 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +0000988 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
989 PE = ParallelLoops.end(); PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +0000990 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>();
Tobias Grosser75805372011-04-29 06:27:02 +0000997 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +0000998 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +0000999 AU.addRequired<ScopDetection>();
1000 AU.addRequired<ScopInfo>();
1001 AU.addRequired<TargetData>();
1002
1003 AU.addPreserved<CloogInfo>();
1004 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001005
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001006 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001007 AU.addPreserved<LoopInfo>();
1008 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001009 AU.addPreserved<ScopDetection>();
1010 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001011
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001012 // FIXME: We do not yet add regions for the newly generated code to the
1013 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001014 AU.addPreserved<RegionInfo>();
1015 AU.addPreserved<TempScopInfo>();
1016 AU.addPreserved<ScopInfo>();
1017 AU.addPreservedID(IndependentBlocksID);
1018 }
1019};
1020}
1021
1022char CodeGeneration::ID = 1;
1023
Tobias Grosser73600b82011-10-08 00:30:40 +00001024INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001025 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser73600b82011-10-08 00:30:40 +00001026INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1027INITIALIZE_PASS_DEPENDENCY(Dependences)
1028INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1029INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1030INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1031INITIALIZE_PASS_DEPENDENCY(ScopDetection)
Tobias Grosser660b58d2012-10-08 08:56:52 +00001032INITIALIZE_PASS_DEPENDENCY(DataLayout)
Tobias Grosser73600b82011-10-08 00:30:40 +00001033INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser3c2efba2012-03-06 07:38:57 +00001034 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001035
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001036Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001037 return new CodeGeneration();
1038}
Sebastian Pope1f65542012-05-07 16:35:11 +00001039
1040#endif // CLOOG_FOUND