blob: 051d0287278f2f14fa2b9c82340d2be1f7d8c5b1 [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 Grosser637bd632013-05-07 07:31:10 +000029#include "polly/Options.h"
Tobias Grosser75805372011-04-29 06:27:02 +000030#include "polly/ScopInfo.h"
31#include "polly/TempScopInfo.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000032#include "polly/CodeGen/CodeGeneration.h"
33#include "polly/CodeGen/BlockGenerators.h"
34#include "polly/CodeGen/LoopGenerators.h"
Tobias Grosser6217e182012-08-03 12:50:07 +000035#include "polly/CodeGen/PTXGenerator.h"
Tobias Grosser3a275d22012-05-29 09:11:54 +000036#include "polly/CodeGen/Utils.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000037#include "polly/Support/GICHelper.h"
Tobias Grosser0ee50f62013-04-10 06:55:31 +000038#include "polly/Support/ScopHelper.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000039
Chandler Carruth535d52c2013-01-02 11:47:44 +000040#include "llvm/IR/Module.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000041#include "llvm/ADT/SetVector.h"
Tobias Grosser900893d2012-03-29 13:10:26 +000042#include "llvm/ADT/PostOrderIterator.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000043#include "llvm/Analysis/LoopInfo.h"
44#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000045#include "llvm/Support/Debug.h"
Chandler Carruth535d52c2013-01-02 11:47:44 +000046#include "llvm/IR/DataLayout.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000048
49#define CLOOG_INT_GMP 1
50#include "cloog/cloog.h"
51#include "cloog/isl/cloog.h"
52
Raghesh Aloora71989c2011-12-28 02:48:26 +000053#include "isl/aff.h"
54
Tobias Grosser75805372011-04-29 06:27:02 +000055#include <vector>
56#include <utility>
57
58using namespace polly;
59using namespace llvm;
60
61struct isl_set;
62
63namespace polly {
Tobias Grosser75805372011-04-29 06:27:02 +000064static cl::opt<bool>
Tobias Grosserc14582f2013-02-05 18:01:29 +000065OpenMP("enable-polly-openmp", cl::desc("Generate OpenMP parallel code"),
Tobias Grosser637bd632013-05-07 07:31:10 +000066 cl::value_desc("OpenMP code generation enabled if true"),
67 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser75805372011-04-29 06:27:02 +000068
Tobias Grosser6217e182012-08-03 12:50:07 +000069#ifdef GPU_CODEGEN
70static cl::opt<bool>
Tobias Grosserc14582f2013-02-05 18:01:29 +000071GPGPU("enable-polly-gpgpu", cl::desc("Generate GPU parallel code"), cl::Hidden,
72 cl::value_desc("GPGPU code generation enabled if true"), cl::init(false),
Tobias Grosser637bd632013-05-07 07:31:10 +000073 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosser6217e182012-08-03 12:50:07 +000074
Tobias Grossere602a072013-05-07 07:30:56 +000075static cl::opt<std::string>
76GPUTriple("polly-gpgpu-triple",
77 cl::desc("Target triple for GPU code generation"), cl::Hidden,
Tobias Grosser637bd632013-05-07 07:31:10 +000078 cl::init(""), cl::cat(PollyCategory));
Tobias Grosser6217e182012-08-03 12:50:07 +000079#endif /* GPU_CODEGEN */
80
Tobias Grosserc14582f2013-02-05 18:01:29 +000081typedef DenseMap<const char *, Value *> CharMapT;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +000082
Tobias Grosser75805372011-04-29 06:27:02 +000083/// Class to generate LLVM-IR that calculates the value of a clast_expr.
84class ClastExpCodeGen {
85 IRBuilder<> &Builder;
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000086 const CharMapT &IVS;
Tobias Grosser75805372011-04-29 06:27:02 +000087
Tobias Grosserbb137e32012-01-24 16:42:28 +000088 Value *codegen(const clast_name *e, Type *Ty);
89 Value *codegen(const clast_term *e, Type *Ty);
90 Value *codegen(const clast_binary *e, Type *Ty);
91 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosserd7e58642013-04-10 06:55:45 +000092
Tobias Grosser75805372011-04-29 06:27:02 +000093public:
94
95 // A generator for clast expressions.
96 //
97 // @param B The IRBuilder that defines where the code to calculate the
98 // clast expressions should be inserted.
99 // @param IVMAP A Map that translates strings describing the induction
100 // variables to the Values* that represent these variables
101 // on the LLVM side.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000102 ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000103
104 // Generates code to calculate a given clast expression.
105 //
106 // @param e The expression to calculate.
107 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000108 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000109};
110
111Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000112 CharMapT::const_iterator I = IVS.find(e->name);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000113
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000114 assert(I != IVS.end() && "Clast name not found");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000115
116 return Builder.CreateSExtOrBitCast(I->second, Ty);
117}
118
119Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
120 APInt a = APInt_from_MPZ(e->val);
121
122 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
123 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
124
125 if (!e->var)
126 return ConstOne;
127
128 Value *var = codegen(e->var, Ty);
129 return Builder.CreateMul(ConstOne, var);
130}
131
132Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
133 Value *LHS = codegen(e->LHS, Ty);
134
135 APInt RHS_AP = APInt_from_MPZ(e->RHS);
136
137 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
138 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
139
140 switch (e->type) {
141 case clast_bin_mod:
142 return Builder.CreateSRem(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000143 case clast_bin_fdiv: {
144 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
145 Value *One = ConstantInt::get(Ty, 1);
146 Value *Zero = ConstantInt::get(Ty, 0);
147 Value *Sum1 = Builder.CreateSub(LHS, RHS);
148 Value *Sum2 = Builder.CreateAdd(Sum1, One);
149 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
150 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
151 return Builder.CreateSDiv(Dividend, RHS);
152 }
153 case clast_bin_cdiv: {
154 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
155 Value *One = ConstantInt::get(Ty, 1);
156 Value *Zero = ConstantInt::get(Ty, 0);
157 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
158 Value *Sum2 = Builder.CreateSub(Sum1, One);
159 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
160 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
161 return Builder.CreateSDiv(Dividend, RHS);
162 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000163 case clast_bin_div:
164 return Builder.CreateSDiv(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000165 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000166
167 llvm_unreachable("Unknown clast binary expression type");
168}
169
170Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000171 assert((r->type == clast_red_min || r->type == clast_red_max ||
172 r->type == clast_red_sum) && "Clast reduction type not supported");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000173 Value *old = codegen(r->elts[0], Ty);
174
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000175 for (int i = 1; i < r->n; ++i) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000176 Value *exprValue = codegen(r->elts[i], Ty);
177
178 switch (r->type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000179 case clast_red_min: {
180 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
181 old = Builder.CreateSelect(cmp, old, exprValue);
182 break;
183 }
184 case clast_red_max: {
185 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
186 old = Builder.CreateSelect(cmp, old, exprValue);
187 break;
188 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000189 case clast_red_sum:
190 old = Builder.CreateAdd(old, exprValue);
191 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000192 }
Tobias Grosser75805372011-04-29 06:27:02 +0000193 }
194
Tobias Grosserbb137e32012-01-24 16:42:28 +0000195 return old;
196}
197
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000198ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000199 : Builder(B), IVS(IVMap) {}
Tobias Grosserbb137e32012-01-24 16:42:28 +0000200
201Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000202 switch (e->type) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000203 case clast_expr_name:
204 return codegen((const clast_name *)e, Ty);
205 case clast_expr_term:
206 return codegen((const clast_term *)e, Ty);
207 case clast_expr_bin:
208 return codegen((const clast_binary *)e, Ty);
209 case clast_expr_red:
210 return codegen((const clast_reduction *)e, Ty);
211 }
212
213 llvm_unreachable("Unknown clast expression!");
214}
215
Tobias Grosser75805372011-04-29 06:27:02 +0000216class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000217public:
218 const std::vector<std::string> &getParallelLoops();
219
220private:
Tobias Grosser75805372011-04-29 06:27:02 +0000221 // The Scop we code generate.
222 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000223 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000224
225 // The Builder specifies the current location to code generate at.
226 IRBuilder<> &Builder;
227
228 // Map the Values from the old code to their counterparts in the new code.
229 ValueMapT ValueMap;
230
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000231 // Map the loops from the old code to expressions function of the induction
232 // variables in the new code. For example, when the code generator produces
233 // this AST:
234 //
235 // for (int c1 = 0; c1 <= 1023; c1 += 1)
236 // for (int c2 = 0; c2 <= 1023; c2 += 1)
237 // Stmt(c2 + 3, c1);
238 //
239 // LoopToScev is a map associating:
240 // "outer loop in the old loop nest" -> SCEV("c2 + 3"),
241 // "inner loop in the old loop nest" -> SCEV("c1").
242 LoopToScevMapT LoopToScev;
243
Tobias Grosser75805372011-04-29 06:27:02 +0000244 // 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
Tobias Grossere602a072013-05-07 07:30:56 +0000266 void codegen(const clast_assignment *a, ScopStmt *Statement,
267 unsigned Dimension, int vectorDim,
268 std::vector<ValueMapT> *VectorVMap = 0,
269 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000270
Tobias Grosserc14582f2013-02-05 18:01:29 +0000271 void codegenSubstitutions(const clast_stmt *Assignment, ScopStmt *Statement,
272 int vectorDim = 0,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000273 std::vector<ValueMapT> *VectorVMap = 0,
274 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000275
Tobias Grosserc14582f2013-02-05 18:01:29 +0000276 void codegen(const clast_user_stmt *u, std::vector<Value *> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000277 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000278
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000279 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000280
281 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000282 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000283
284 /// @brief Create OpenMP structure values.
285 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000286 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000287 /// structure.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000288 SetVector<Value *> getOMPValues(const clast_stmt *Body);
Tobias Grosser75805372011-04-29 06:27:02 +0000289
Tobias Grossera17f6662012-11-01 05:34:35 +0000290 /// @brief Update ClastVars and ValueMap according to a value map.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000291 ///
Tobias Grossera17f6662012-11-01 05:34:35 +0000292 /// @param VMap A map from old to new values.
293 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
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.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000307 SetVector<Value *> getGPUValues(unsigned &OutputBytes);
Tobias Grosser6217e182012-08-03 12:50:07 +0000308
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.
Tobias Grossere602a072013-05-07 07:30:56 +0000316 const clast_stmt *getScheduleInfo(const clast_for *F,
317 std::vector<int> &NumIters,
318 unsigned &LoopDepth,
319 unsigned &NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000320#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 ///
Tobias Grosserc1b6cec2012-11-19 12:26:25 +0000326 /// @param For The clast for loop to check.
Tobias Grossere192b232012-05-22 08:46:07 +0000327 ///
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 Grosser1bb59b02012-12-29 23:47:38 +0000353public:
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() {
Tobias Grosser5d01691d2012-11-01 16:45:18 +0000361 return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext());
Tobias Grossere9ffea22012-03-15 09:34:48 +0000362}
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 Grosser1bb59b02012-12-29 23:47:38 +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 Grossere602a072013-05-07 07:30:56 +0000373void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
374 unsigned Dim, int VectorDim,
375 std::vector<ValueMapT> *VectorVMap,
376 std::vector<LoopToScevMapT> *VLTS) {
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 Grosser0905a232012-04-03 12:24:32 +0000381 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000382
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000383 const llvm::SCEV *URHS = S->getSE()->getUnknown(RHS);
384 if (VLTS)
385 (*VLTS)[VectorDim][Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000386 LoopToScev[Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pope039bb12013-03-18 19:09:49 +0000387
388 const PHINode *PN = Stmt->getInductionVariableForDimension(Dim);
389 if (PN) {
390 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
391
392 if (VectorVMap)
393 (*VectorVMap)[VectorDim][PN] = RHS;
394
395 ValueMap[PN] = RHS;
396 }
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000397}
398
Tobias Grossere602a072013-05-07 07:30:56 +0000399void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
400 ScopStmt *Statement, int vectorDim,
401 std::vector<ValueMapT> *VectorVMap,
402 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000403 int Dimension = 0;
404
405 while (Assignment) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000406 assert(CLAST_STMT_IS_A(Assignment, stmt_ass) &&
407 "Substitions are expected to be assignments");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000408 codegen((const clast_assignment *)Assignment, Statement, Dimension,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000409 vectorDim, VectorVMap, VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000410 Assignment = Assignment->next;
411 Dimension++;
412 }
413}
414
Sebastian Popa00a0292012-12-18 07:46:06 +0000415// Takes the cloog specific domain and translates it into a map Statement ->
416// PartialSchedule, where the PartialSchedule contains all the dimensions that
417// have been code generated up to this point.
Tobias Grossere602a072013-05-07 07:30:56 +0000418static __isl_give isl_map *extractPartialSchedule(ScopStmt *Statement,
419 isl_set *Domain) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000420 isl_map *Schedule = Statement->getScattering();
421 int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000422 int UnscheduledDimensions =
423 isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
Sebastian Popa00a0292012-12-18 07:46:06 +0000424
425 return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
426 UnscheduledDimensions);
427}
428
Tobias Grossere602a072013-05-07 07:30:56 +0000429void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
430 std::vector<Value *> *IVS, const char *iterator,
431 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000432 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000433
434 if (u->substitutions)
435 codegenSubstitutions(u->substitutions, Statement);
436
Tobias Grosser80998e72012-03-02 11:27:28 +0000437 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000438
Tobias Grosser80998e72012-03-02 11:27:28 +0000439 if (VectorDimensions == 1) {
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000440 BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000441 return;
442 }
443
444 VectorValueMapT VectorMap(VectorDimensions);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000445 std::vector<LoopToScevMapT> VLTS(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000446
447 if (IVS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000448 assert(u->substitutions && "Substitutions expected!");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000449 int i = 0;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000450 for (std::vector<Value *>::iterator II = IVS->begin(), IE = IVS->end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000451 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000452 ClastVars[iterator] = *II;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000453 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap, &VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000454 i++;
455 }
456 }
457
Sebastian Popa00a0292012-12-18 07:46:06 +0000458 isl_map *Schedule = extractPartialSchedule(Statement, Domain);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000459 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, VLTS, Schedule,
460 P);
Sebastian Popa00a0292012-12-18 07:46:06 +0000461 isl_map_free(Schedule);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000462}
463
464void ClastStmtCodeGen::codegen(const clast_block *b) {
465 if (b->body)
466 codegen(b->body);
467}
468
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000469void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
470 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000471 BasicBlock *AfterBB;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000472 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000473
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000474 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
475 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
476 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000477
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000478 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
479 CmpInst::ICMP_SLE);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000480
481 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000482 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000483
484 if (f->body)
485 codegen(f->body);
486
487 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000488 ClastVars.erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000489 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000490}
491
Tobias Grosser177982c2012-11-01 05:34:48 +0000492// Helper class to determine all scalar parameters used in the basic blocks of a
493// clast. Scalar parameters are scalar variables defined outside of the SCoP.
494class ParameterVisitor : public ClastVisitor {
495 std::set<Value *> Values;
Tobias Grosserd7e58642013-04-10 06:55:45 +0000496
Tobias Grosser177982c2012-11-01 05:34:48 +0000497public:
Tobias Grosserc14582f2013-02-05 18:01:29 +0000498 ParameterVisitor() : ClastVisitor(), Values() {}
Tobias Grosser177982c2012-11-01 05:34:48 +0000499
500 void visitUser(const clast_user_stmt *Stmt) {
501 const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
502 const BasicBlock *BB = S->getBasicBlock();
503
504 // Check all the operands of instructions in the basic block.
505 for (BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); BI != BE;
506 ++BI) {
507 const Instruction &Inst = *BI;
508 for (Instruction::const_op_iterator II = Inst.op_begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000509 IE = Inst.op_end();
510 II != IE; ++II) {
Tobias Grosser177982c2012-11-01 05:34:48 +0000511 Value *SrcVal = *II;
512
513 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
514 if (S->getParent()->getRegion().contains(OpInst))
515 continue;
516
517 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
518 Values.insert(SrcVal);
519 }
520 }
521 }
522
523 // Iterator to iterate over the values found.
524 typedef std::set<Value *>::const_iterator const_iterator;
525 inline const_iterator begin() const { return Values.begin(); }
Tobias Grosserc14582f2013-02-05 18:01:29 +0000526 inline const_iterator end() const { return Values.end(); }
Tobias Grosser177982c2012-11-01 05:34:48 +0000527};
528
Tobias Grosserc14582f2013-02-05 18:01:29 +0000529SetVector<Value *> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
530 SetVector<Value *> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000531
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000532 // The clast variables
Tobias Grosserc14582f2013-02-05 18:01:29 +0000533 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
534 I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000535 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000536
Tobias Grosser177982c2012-11-01 05:34:48 +0000537 // Find the temporaries that are referenced in the clast statements'
538 // basic blocks but are not defined by these blocks (e.g., references
539 // to function arguments or temporaries defined before the start of
540 // the SCoP).
541 ParameterVisitor Params;
542 Params.visit(Body);
543
544 for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
545 PI != PE; ++PI) {
546 Value *V = *PI;
547 Values.insert(V);
548 DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
549 }
550
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000551 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000552}
553
Tobias Grosserd7e58642013-04-10 06:55:45 +0000554void
555ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000556 std::set<Value *> Inserted;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000557
Tobias Grosserc14582f2013-02-05 18:01:29 +0000558 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
559 I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000560 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000561 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000562 }
563
Tobias Grossera17f6662012-11-01 05:34:35 +0000564 for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000565 E = VMap.end();
566 I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000567 if (Inserted.count(I->first))
568 continue;
569
570 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000571 }
572}
573
Tobias Grosser900893d2012-03-29 13:10:26 +0000574static void clearDomtree(Function *F, DominatorTree &DT) {
575 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
Tobias Grosserc14582f2013-02-05 18:01:29 +0000576 std::vector<BasicBlock *> Nodes;
577 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
Tobias Grosser900893d2012-03-29 13:10:26 +0000578 Nodes.push_back(I->getBlock());
579
Tobias Grosserc14582f2013-02-05 18:01:29 +0000580 for (std::vector<BasicBlock *>::iterator I = Nodes.begin(), E = Nodes.end();
Tobias Grosser900893d2012-03-29 13:10:26 +0000581 I != E; ++I)
582 DT.eraseNode(*I);
583}
584
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000585void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000586 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000587 BasicBlock::iterator LoopBody;
588 IntegerType *IntPtrTy = getIntPtrTy();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000589 SetVector<Value *> Values;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000590 OMPGenerator::ValueToValueMapTy VMap;
591 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000592
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000593 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
594 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000595 LB = ExpGen.codegen(For->LB, IntPtrTy);
596 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000597
Tobias Grosser177982c2012-11-01 05:34:48 +0000598 Values = getOMPValues(For->body);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000599
Tobias Grosserebf30082012-03-23 12:20:32 +0000600 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000601 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
602 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000603
Tobias Grossera17f6662012-11-01 05:34:35 +0000604 // Save the current values.
605 const ValueMapT ValueMapCopy = ValueMap;
606 const CharMapT ClastVarsCopy = ClastVars;
607
608 updateWithValueMap(VMap);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000609 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000610
611 if (For->body)
612 codegen(For->body);
613
Tobias Grossera17f6662012-11-01 05:34:35 +0000614 // Restore the original values.
615 ValueMap = ValueMapCopy;
616 ClastVars = ClastVarsCopy;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000617
Tobias Grosser900893d2012-03-29 13:10:26 +0000618 clearDomtree((*LoopBody).getParent()->getParent(),
619 P->getAnalysis<DominatorTree>());
620
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000621 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000622}
623
Tobias Grosser6217e182012-08-03 12:50:07 +0000624#ifdef GPU_CODEGEN
625static unsigned getArraySizeInBytes(const ArrayType *AT) {
626 unsigned Bytes = AT->getNumElements();
627 if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
628 Bytes *= getArraySizeInBytes(T);
629 else
630 Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
631
632 return Bytes;
633}
634
Tobias Grosserc14582f2013-02-05 18:01:29 +0000635SetVector<Value *> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
636 SetVector<Value *> Values;
Tobias Grosser6217e182012-08-03 12:50:07 +0000637 OutputBytes = 0;
638
639 // Record the memory reference base addresses.
640 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
641 ScopStmt *Stmt = *SI;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000642 for (SmallVector<MemoryAccess *, 8>::iterator I = Stmt->memacc_begin(),
643 E = Stmt->memacc_end();
644 I != E; ++I) {
645 Value *BaseAddr = const_cast<Value *>((*I)->getBaseAddr());
Tobias Grosser6217e182012-08-03 12:50:07 +0000646 Values.insert((BaseAddr));
647
648 // FIXME: we assume that there is one and only one array to be written
649 // in a SCoP.
650 int NumWrites = 0;
651 if ((*I)->isWrite()) {
652 ++NumWrites;
653 assert(NumWrites <= 1 &&
654 "We support at most one array to be written in a SCoP.");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000655 if (const PointerType *PT =
656 dyn_cast<PointerType>(BaseAddr->getType())) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000657 Type *T = PT->getArrayElementType();
658 const ArrayType *ATy = dyn_cast<ArrayType>(T);
659 OutputBytes = getArraySizeInBytes(ATy);
660 }
661 }
662 }
663 }
664
665 return Values;
666}
667
Tobias Grossere602a072013-05-07 07:30:56 +0000668const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
669 std::vector<int> &NumIters,
670 unsigned &LoopDepth,
671 unsigned &NonPLoopDepth) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000672 clast_stmt *Stmt = (clast_stmt *)F;
673 const clast_for *Result;
674 bool NonParaFlag = false;
675 LoopDepth = 0;
676 NonPLoopDepth = 0;
677
678 while (Stmt) {
679 if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000680 const clast_for *T = (clast_for *)Stmt;
Tobias Grosser6217e182012-08-03 12:50:07 +0000681 if (isParallelFor(T)) {
682 if (!NonParaFlag) {
683 NumIters.push_back(getNumberOfIterations(T));
684 Result = T;
685 }
686 } else
687 NonParaFlag = true;
688
689 Stmt = T->body;
690 LoopDepth++;
691 continue;
692 }
693 Stmt = Stmt->next;
694 }
695
696 assert(NumIters.size() == 4 &&
697 "The loops should be tiled into 4-depth parallel loops and an "
698 "innermost non-parallel one (if exist).");
699 NonPLoopDepth = LoopDepth - NumIters.size();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000700 assert(NonPLoopDepth <= 1 &&
701 "We support only one innermost non-parallel loop currently.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000702 return (const clast_stmt *)Result->body;
703}
704
705void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
706 BasicBlock::iterator LoopBody;
707 SetVector<Value *> Values;
708 SetVector<Value *> IVS;
709 std::vector<int> NumIterations;
710 PTXGenerator::ValueToValueMapTy VMap;
711
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000712 assert(!GPUTriple.empty() &&
713 "Target triple should be set properly for GPGPU code generation.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000714 PTXGenerator PTXGen(Builder, P, GPUTriple);
715
716 // Get original IVS and ScopStmt
717 unsigned TiledLoopDepth, NonPLoopDepth;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000718 const clast_stmt *InnerStmt =
719 getScheduleInfo(F, NumIterations, TiledLoopDepth, NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000720 const clast_stmt *TmpStmt;
721 const clast_user_stmt *U;
722 const clast_for *InnerFor;
723 if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
724 InnerFor = (const clast_for *)InnerStmt;
725 TmpStmt = InnerFor->body;
726 } else
727 TmpStmt = InnerStmt;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000728 U = (const clast_user_stmt *)TmpStmt;
729 ScopStmt *Statement = (ScopStmt *)U->statement->usr;
Tobias Grosser6217e182012-08-03 12:50:07 +0000730 for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000731 const Value *IV = Statement->getInductionVariableForDimension(i);
Tobias Grosser6217e182012-08-03 12:50:07 +0000732 IVS.insert(const_cast<Value *>(IV));
733 }
734
735 unsigned OutBytes;
736 Values = getGPUValues(OutBytes);
737 PTXGen.setOutputBytes(OutBytes);
738 PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
739
740 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
741 Builder.SetInsertPoint(LoopBody);
742
743 BasicBlock *AfterBB = 0;
744 if (NonPLoopDepth) {
745 Value *LowerBound, *UpperBound, *IV, *Stride;
746 Type *IntPtrTy = getIntPtrTy();
747 LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
748 UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
749 Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
Tobias Grosser6f3d0632012-11-30 00:39:49 +0000750 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
751 CmpInst::ICMP_SLE);
Tobias Grosser6217e182012-08-03 12:50:07 +0000752 const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
753 Value *OldIV = const_cast<Value *>(OldIV_);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000754 VMap.insert(std::make_pair<Value *, Value *>(OldIV, IV));
Tobias Grosser6217e182012-08-03 12:50:07 +0000755 }
756
Tobias Grosser46c6abb2012-11-30 01:05:05 +0000757 updateWithValueMap(VMap);
Tobias Grossera17f6662012-11-01 05:34:35 +0000758
Tobias Grosser6217e182012-08-03 12:50:07 +0000759 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grossera17f6662012-11-01 05:34:35 +0000760
Tobias Grosser6217e182012-08-03 12:50:07 +0000761 if (AfterBB)
762 Builder.SetInsertPoint(AfterBB->begin());
763
764 // FIXME: The replacement of the host base address with the parameter of ptx
765 // subfunction should have been done by updateWithValueMap. We use the
766 // following codes to avoid affecting other parts of Polly. This should be
767 // fixed later.
768 Function *FN = Builder.GetInsertBlock()->getParent();
769 for (unsigned j = 0; j < Values.size(); j++) {
770 Value *baseAddr = Values[j];
771 for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
772 for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
773 I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
774 }
775 }
776 Builder.SetInsertPoint(AfterLoop);
777 PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
778 NumIterations[2], NumIterations[3]);
779 PTXGen.finishGeneration(FN);
780}
781#endif
782
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000783bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
784 const clast_stmt *stmt = f->body;
785
786 while (stmt) {
787 if (!CLAST_STMT_IS_A(stmt, stmt_user))
788 return false;
789
790 stmt = stmt->next;
791 }
792
793 return true;
794}
795
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000796int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
797 isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000798 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
799 if (NumberOfIterations == -1)
800 return -1;
801 return NumberOfIterations / isl_int_get_si(For->stride) + 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000802}
803
Tobias Grosser2da263e2012-03-15 09:34:55 +0000804void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
805 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
806 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000807
Tobias Grosser2da263e2012-03-15 09:34:55 +0000808 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000809
Tobias Grosser2da263e2012-03-15 09:34:55 +0000810 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000811 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000812 Stride = Stride.zext(LoopIVType->getBitWidth());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000813 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
814
Tobias Grosserc14582f2013-02-05 18:01:29 +0000815 std::vector<Value *> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000816 IVS[0] = LB;
817
Tobias Grosser2da263e2012-03-15 09:34:55 +0000818 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000819 IVS[i] = Builder.CreateAdd(IVS[i - 1], StrideValue, "p_vector_iv");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000820
Tobias Grosser00d898d2012-03-15 09:34:58 +0000821 isl_set *Domain = isl_set_from_cloog_domain(F->domain);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000822
823 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000824 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000825
Tobias Grosser2da263e2012-03-15 09:34:55 +0000826 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000827
Tobias Grosser2da263e2012-03-15 09:34:55 +0000828 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000829 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
830 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000831 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000832 }
833
834 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000835 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000836 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000837}
838
Tobias Grossere192b232012-05-22 08:46:07 +0000839bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
840 isl_set *Domain = isl_set_from_cloog_domain(f->domain);
841 assert(Domain && "Cannot access domain of loop");
842
843 Dependences &D = P->getAnalysis<Dependences>();
844
845 return D.isParallelDimension(isl_set_copy(Domain), isl_set_n_dim(Domain));
846}
847
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000848void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000849 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000850 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000851 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f)) &&
852 (getNumberOfIterations(f) <= 16)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000853 codegenForVector(f);
854 return;
855 }
856
857 if (OpenMP && !parallelCodeGeneration) {
858 parallelCodeGeneration = true;
859 parallelLoops.push_back(f->iterator);
860 codegenForOpenMP(f);
861 parallelCodeGeneration = false;
862 return;
863 }
864 }
865
Tobias Grosser6217e182012-08-03 12:50:07 +0000866#ifdef GPU_CODEGEN
867 if (GPGPU && isParallelFor(f)) {
868 if (!parallelCodeGeneration) {
869 parallelCodeGeneration = true;
870 parallelLoops.push_back(f->iterator);
871 codegenForGPGPU(f);
872 parallelCodeGeneration = false;
873 return;
874 }
875 }
876#endif
877
Tobias Grosserce3f5372012-03-02 11:26:42 +0000878 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000879}
880
881Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000882 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
883 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000884 CmpInst::Predicate P;
885
886 if (eq->sign == 0)
887 P = ICmpInst::ICMP_EQ;
888 else if (eq->sign > 0)
889 P = ICmpInst::ICMP_SGE;
890 else
891 P = ICmpInst::ICMP_SLE;
892
893 return Builder.CreateICmp(P, LHS, RHS);
894}
895
896void ClastStmtCodeGen::codegen(const clast_guard *g) {
897 Function *F = Builder.GetInsertBlock()->getParent();
898 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000899
Tobias Grosserc14582f2013-02-05 18:01:29 +0000900 BasicBlock *CondBB =
901 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000902 CondBB->setName("polly.cond");
903 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
904 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000905 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000906
Tobias Grosserd596b372012-03-15 09:34:52 +0000907 DominatorTree &DT = P->getAnalysis<DominatorTree>();
908 DT.addNewBlock(ThenBB, CondBB);
909 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000910
911 CondBB->getTerminator()->eraseFromParent();
912
913 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000914
915 Value *Predicate = codegen(&(g->eq[0]));
916
917 for (int i = 1; i < g->n; ++i) {
918 Value *TmpPredicate = codegen(&(g->eq[i]));
919 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
920 }
921
922 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
923 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000924 Builder.CreateBr(MergeBB);
925 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000926
927 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000928
929 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000930}
931
932void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000933 if (CLAST_STMT_IS_A(stmt, stmt_root))
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000934 assert(false && "No second root statement expected");
935 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
936 codegen((const clast_assignment *)stmt);
937 else if (CLAST_STMT_IS_A(stmt, stmt_user))
938 codegen((const clast_user_stmt *)stmt);
939 else if (CLAST_STMT_IS_A(stmt, stmt_block))
940 codegen((const clast_block *)stmt);
941 else if (CLAST_STMT_IS_A(stmt, stmt_for))
942 codegen((const clast_for *)stmt);
943 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
944 codegen((const clast_guard *)stmt);
945
946 if (stmt->next)
947 codegen(stmt->next);
948}
949
950void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000951 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000952
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000953 int i = 0;
954 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
955 PI != PE; ++PI) {
956 assert(i < names->nb_parameters && "Not enough parameter names");
957
958 const SCEV *Param = *PI;
959 Type *Ty = Param->getType();
960
961 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
962 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000963 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000964
965 ++i;
966 }
967}
968
969void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000970 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000971
972 parallelCodeGeneration = false;
973
Tobias Grosserc14582f2013-02-05 18:01:29 +0000974 const clast_stmt *stmt = (const clast_stmt *)r;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000975 if (stmt->next)
976 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000977}
978
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000979ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000980 : S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000981
Tobias Grosser75805372011-04-29 06:27:02 +0000982namespace {
983class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +0000984 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +0000985
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000986public:
Tobias Grosser75805372011-04-29 06:27:02 +0000987 static char ID;
988
989 CodeGeneration() : ScopPass(ID) {}
990
Tobias Grosser3a275d22012-05-29 09:11:54 +0000991 bool runOnScop(Scop &S) {
992 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000993
Tobias Grossere602a072013-05-07 07:30:56 +0000994 assert(!S.getRegion().isTopLevelRegion() &&
995 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000996
Tobias Grosser8edce4e2013-04-16 08:04:42 +0000997 simplifyRegion(&S, this);
Tobias Grossercb47dfe2012-02-15 09:58:50 +0000998
Tobias Grosser3a275d22012-05-29 09:11:54 +0000999 BasicBlock *StartBlock = executeScopConditionally(S, this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001000
Tobias Grosser3a275d22012-05-29 09:11:54 +00001001 IRBuilder<> Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001002
Tobias Grosser3a275d22012-05-29 09:11:54 +00001003 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001004 CloogInfo &C = getAnalysis<CloogInfo>();
1005 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001006
Tobias Grosser3a275d22012-05-29 09:11:54 +00001007 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +00001008 CodeGen.getParallelLoops().begin(),
1009 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001010 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001011 }
1012
1013 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001014 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +00001015 PE = ParallelLoops.end();
1016 PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +00001017 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1018 }
1019
1020 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1021 AU.addRequired<CloogInfo>();
1022 AU.addRequired<Dependences>();
1023 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001024 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001025 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001026 AU.addRequired<ScopDetection>();
1027 AU.addRequired<ScopInfo>();
Micah Villmow7a3d8202012-10-08 17:26:19 +00001028 AU.addRequired<DataLayout>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001029 AU.addRequired<LoopInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001030
1031 AU.addPreserved<CloogInfo>();
1032 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001033
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001034 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001035 AU.addPreserved<LoopInfo>();
1036 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001037 AU.addPreserved<ScopDetection>();
1038 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001039
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001040 // FIXME: We do not yet add regions for the newly generated code to the
1041 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001042 AU.addPreserved<RegionInfo>();
1043 AU.addPreserved<TempScopInfo>();
1044 AU.addPreserved<ScopInfo>();
1045 AU.addPreservedID(IndependentBlocksID);
1046 }
1047};
1048}
1049
1050char CodeGeneration::ID = 1;
1051
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001052Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
Sebastian Pope1f65542012-05-07 16:35:11 +00001053
Tobias Grosser7242ad92013-02-22 08:07:06 +00001054INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1055 "Polly - Create LLVM-IR from SCoPs", false, false);
1056INITIALIZE_PASS_DEPENDENCY(CloogInfo);
1057INITIALIZE_PASS_DEPENDENCY(Dependences);
1058INITIALIZE_PASS_DEPENDENCY(DominatorTree);
1059INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1060INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1061INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1062INITIALIZE_PASS_DEPENDENCY(DataLayout);
1063INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001064 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser7242ad92013-02-22 08:07:06 +00001065
Sebastian Pope1f65542012-05-07 16:35:11 +00001066#endif // CLOOG_FOUND