blob: 833d20b7793b1a7fded998fa606082139824ea77 [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 Grosser0ee50f62013-04-10 06:55:31 +000037#include "polly/Support/ScopHelper.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000038
Chandler Carruth535d52c2013-01-02 11:47:44 +000039#include "llvm/IR/Module.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000040#include "llvm/ADT/SetVector.h"
Tobias Grosser900893d2012-03-29 13:10:26 +000041#include "llvm/ADT/PostOrderIterator.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000042#include "llvm/Analysis/LoopInfo.h"
43#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000044#include "llvm/Support/CommandLine.h"
45#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"),
66 cl::Hidden, 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>
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),
73 cl::ZeroOrMore);
Tobias Grosser6217e182012-08-03 12:50:07 +000074
Tobias Grosserc14582f2013-02-05 18:01:29 +000075static cl::opt<std::string> GPUTriple(
76 "polly-gpgpu-triple", cl::desc("Target triple for GPU code generation"),
77 cl::Hidden, cl::init(""));
Tobias Grosser6217e182012-08-03 12:50:07 +000078#endif /* GPU_CODEGEN */
79
Tobias Grosserc14582f2013-02-05 18:01:29 +000080typedef DenseMap<const char *, Value *> CharMapT;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +000081
Tobias Grosser75805372011-04-29 06:27:02 +000082/// Class to generate LLVM-IR that calculates the value of a clast_expr.
83class ClastExpCodeGen {
84 IRBuilder<> &Builder;
Tobias Grosser5e8ffa82012-03-23 12:20:36 +000085 const CharMapT &IVS;
Tobias Grosser75805372011-04-29 06:27:02 +000086
Tobias Grosserbb137e32012-01-24 16:42:28 +000087 Value *codegen(const clast_name *e, Type *Ty);
88 Value *codegen(const clast_term *e, Type *Ty);
89 Value *codegen(const clast_binary *e, Type *Ty);
90 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosserd7e58642013-04-10 06:55:45 +000091
Tobias Grosser75805372011-04-29 06:27:02 +000092public:
93
94 // A generator for clast expressions.
95 //
96 // @param B The IRBuilder that defines where the code to calculate the
97 // clast expressions should be inserted.
98 // @param IVMAP A Map that translates strings describing the induction
99 // variables to the Values* that represent these variables
100 // on the LLVM side.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000101 ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000102
103 // Generates code to calculate a given clast expression.
104 //
105 // @param e The expression to calculate.
106 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000107 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000108};
109
110Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000111 CharMapT::const_iterator I = IVS.find(e->name);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000112
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000113 assert(I != IVS.end() && "Clast name not found");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000114
115 return Builder.CreateSExtOrBitCast(I->second, Ty);
116}
117
118Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
119 APInt a = APInt_from_MPZ(e->val);
120
121 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
122 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
123
124 if (!e->var)
125 return ConstOne;
126
127 Value *var = codegen(e->var, Ty);
128 return Builder.CreateMul(ConstOne, var);
129}
130
131Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
132 Value *LHS = codegen(e->LHS, Ty);
133
134 APInt RHS_AP = APInt_from_MPZ(e->RHS);
135
136 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
137 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
138
139 switch (e->type) {
140 case clast_bin_mod:
141 return Builder.CreateSRem(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000142 case clast_bin_fdiv: {
143 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
144 Value *One = ConstantInt::get(Ty, 1);
145 Value *Zero = ConstantInt::get(Ty, 0);
146 Value *Sum1 = Builder.CreateSub(LHS, RHS);
147 Value *Sum2 = Builder.CreateAdd(Sum1, One);
148 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
149 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
150 return Builder.CreateSDiv(Dividend, RHS);
151 }
152 case clast_bin_cdiv: {
153 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
154 Value *One = ConstantInt::get(Ty, 1);
155 Value *Zero = ConstantInt::get(Ty, 0);
156 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
157 Value *Sum2 = Builder.CreateSub(Sum1, One);
158 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
159 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
160 return Builder.CreateSDiv(Dividend, RHS);
161 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000162 case clast_bin_div:
163 return Builder.CreateSDiv(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000164 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000165
166 llvm_unreachable("Unknown clast binary expression type");
167}
168
169Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000170 assert((r->type == clast_red_min || r->type == clast_red_max ||
171 r->type == clast_red_sum) && "Clast reduction type not supported");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000172 Value *old = codegen(r->elts[0], Ty);
173
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000174 for (int i = 1; i < r->n; ++i) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000175 Value *exprValue = codegen(r->elts[i], Ty);
176
177 switch (r->type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000178 case clast_red_min: {
179 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
180 old = Builder.CreateSelect(cmp, old, exprValue);
181 break;
182 }
183 case clast_red_max: {
184 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
185 old = Builder.CreateSelect(cmp, old, exprValue);
186 break;
187 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000188 case clast_red_sum:
189 old = Builder.CreateAdd(old, exprValue);
190 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000191 }
Tobias Grosser75805372011-04-29 06:27:02 +0000192 }
193
Tobias Grosserbb137e32012-01-24 16:42:28 +0000194 return old;
195}
196
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000197ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000198 : Builder(B), IVS(IVMap) {}
Tobias Grosserbb137e32012-01-24 16:42:28 +0000199
200Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000201 switch (e->type) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000202 case clast_expr_name:
203 return codegen((const clast_name *)e, Ty);
204 case clast_expr_term:
205 return codegen((const clast_term *)e, Ty);
206 case clast_expr_bin:
207 return codegen((const clast_binary *)e, Ty);
208 case clast_expr_red:
209 return codegen((const clast_reduction *)e, Ty);
210 }
211
212 llvm_unreachable("Unknown clast expression!");
213}
214
Tobias Grosser75805372011-04-29 06:27:02 +0000215class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000216public:
217 const std::vector<std::string> &getParallelLoops();
218
219private:
Tobias Grosser75805372011-04-29 06:27:02 +0000220 // The Scop we code generate.
221 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000222 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000223
224 // The Builder specifies the current location to code generate at.
225 IRBuilder<> &Builder;
226
227 // Map the Values from the old code to their counterparts in the new code.
228 ValueMapT ValueMap;
229
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000230 // Map the loops from the old code to expressions function of the induction
231 // variables in the new code. For example, when the code generator produces
232 // this AST:
233 //
234 // for (int c1 = 0; c1 <= 1023; c1 += 1)
235 // for (int c2 = 0; c2 <= 1023; c2 += 1)
236 // Stmt(c2 + 3, c1);
237 //
238 // LoopToScev is a map associating:
239 // "outer loop in the old loop nest" -> SCEV("c2 + 3"),
240 // "inner loop in the old loop nest" -> SCEV("c1").
241 LoopToScevMapT LoopToScev;
242
Tobias Grosser75805372011-04-29 06:27:02 +0000243 // clastVars maps from the textual representation of a clast variable to its
244 // current *Value. clast variables are scheduling variables, original
245 // induction variables or parameters. They are used either in loop bounds or
246 // to define the statement instance that is executed.
247 //
248 // for (s = 0; s < n + 3; ++i)
249 // for (t = s; t < m; ++j)
250 // Stmt(i = s + 3 * m, j = t);
251 //
252 // {s,t,i,j,n,m} is the set of clast variables in this clast.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000253 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000254
255 // Codegenerator for clast expressions.
256 ClastExpCodeGen ExpGen;
257
258 // Do we currently generate parallel code?
259 bool parallelCodeGeneration;
260
261 std::vector<std::string> parallelLoops;
262
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000263 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000264
Tobias Grosserd7e58642013-04-10 06:55:45 +0000265 void
266 codegen(const clast_assignment *a, ScopStmt *Statement, unsigned Dimension,
267 int vectorDim, std::vector<ValueMapT> *VectorVMap = 0,
268 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000269
Tobias Grosserc14582f2013-02-05 18:01:29 +0000270 void codegenSubstitutions(const clast_stmt *Assignment, ScopStmt *Statement,
271 int vectorDim = 0,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000272 std::vector<ValueMapT> *VectorVMap = 0,
273 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000274
Tobias Grosserc14582f2013-02-05 18:01:29 +0000275 void codegen(const clast_user_stmt *u, std::vector<Value *> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000276 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000277
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000278 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000279
280 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000281 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000282
283 /// @brief Create OpenMP structure values.
284 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000285 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000286 /// structure.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000287 SetVector<Value *> getOMPValues(const clast_stmt *Body);
Tobias Grosser75805372011-04-29 06:27:02 +0000288
Tobias Grossera17f6662012-11-01 05:34:35 +0000289 /// @brief Update ClastVars and ValueMap according to a value map.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000290 ///
Tobias Grossera17f6662012-11-01 05:34:35 +0000291 /// @param VMap A map from old to new values.
292 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000293
294 /// @brief Create an OpenMP parallel for loop.
295 ///
296 /// This loop reflects a loop as if it would have been created by an OpenMP
297 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000298 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000299
Tobias Grosser6217e182012-08-03 12:50:07 +0000300#ifdef GPU_CODEGEN
301 /// @brief Create GPGPU device memory access values.
302 ///
303 /// Create a list of values that will be set to be parameters of the GPGPU
304 /// subfunction. These parameters represent device memory base addresses
305 /// and the size in bytes.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000306 SetVector<Value *> getGPUValues(unsigned &OutputBytes);
Tobias Grosser6217e182012-08-03 12:50:07 +0000307
308 /// @brief Create a GPU parallel for loop.
309 ///
310 /// This loop reflects a loop as if it would have been created by a GPU
311 /// statement.
312 void codegenForGPGPU(const clast_for *F);
313
314 /// @brief Get innermost for loop.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000315 const clast_stmt *
316 getScheduleInfo(const clast_for *F, std::vector<int> &NumIters,
317 unsigned &LoopDepth, unsigned &NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000318#endif /* GPU_CODEGEN */
319
Tobias Grossere192b232012-05-22 08:46:07 +0000320 /// @brief Check if a loop is parallel
321 ///
322 /// Detect if a clast_for loop can be executed in parallel.
323 ///
Tobias Grosserc1b6cec2012-11-19 12:26:25 +0000324 /// @param For The clast for loop to check.
Tobias Grossere192b232012-05-22 08:46:07 +0000325 ///
326 /// @return bool Returns true if the incoming clast_for statement can
327 /// execute in parallel.
328 bool isParallelFor(const clast_for *For);
329
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000330 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000331
332 /// @brief Get the number of loop iterations for this loop.
333 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000334 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000335
336 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000337 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000338
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000339 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000340
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000341 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000342
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000343 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000344
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000345 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000346
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000347 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000348
Tobias Grossere9ffea22012-03-15 09:34:48 +0000349 IntegerType *getIntPtrTy();
350
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000351public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000352 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000353
Tobias Grosserd596b372012-03-15 09:34:52 +0000354 ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000355};
356}
357
Tobias Grossere9ffea22012-03-15 09:34:48 +0000358IntegerType *ClastStmtCodeGen::getIntPtrTy() {
Tobias Grosser5d01691d2012-11-01 16:45:18 +0000359 return P->getAnalysis<DataLayout>().getIntPtrType(Builder.getContext());
Tobias Grossere9ffea22012-03-15 09:34:48 +0000360}
361
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000362const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
363 return parallelLoops;
364}
365
366void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000367 Value *V = ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000368 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000369}
370
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000371void ClastStmtCodeGen::codegen(
372 const clast_assignment *A, ScopStmt *Stmt, unsigned Dim, int VectorDim,
373 std::vector<ValueMapT> *VectorVMap, std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosserf00bd962012-04-02 12:26:13 +0000374 Value *RHS;
375
376 assert(!A->LHS && "Statement assignments do not have left hand side");
377
Tobias Grosser0905a232012-04-03 12:24:32 +0000378 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000379
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000380 const llvm::SCEV *URHS = S->getSE()->getUnknown(RHS);
381 if (VLTS)
382 (*VLTS)[VectorDim][Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000383 LoopToScev[Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pope039bb12013-03-18 19:09:49 +0000384
385 const PHINode *PN = Stmt->getInductionVariableForDimension(Dim);
386 if (PN) {
387 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
388
389 if (VectorVMap)
390 (*VectorVMap)[VectorDim][PN] = RHS;
391
392 ValueMap[PN] = RHS;
393 }
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000394}
395
Tobias Grosserc14582f2013-02-05 18:01:29 +0000396void ClastStmtCodeGen::codegenSubstitutions(
397 const clast_stmt *Assignment, ScopStmt *Statement, int vectorDim,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000398 std::vector<ValueMapT> *VectorVMap, std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000399 int Dimension = 0;
400
401 while (Assignment) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000402 assert(CLAST_STMT_IS_A(Assignment, stmt_ass) &&
403 "Substitions are expected to be assignments");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000404 codegen((const clast_assignment *)Assignment, Statement, Dimension,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000405 vectorDim, VectorVMap, VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000406 Assignment = Assignment->next;
407 Dimension++;
408 }
409}
410
Sebastian Popa00a0292012-12-18 07:46:06 +0000411// Takes the cloog specific domain and translates it into a map Statement ->
412// PartialSchedule, where the PartialSchedule contains all the dimensions that
413// have been code generated up to this point.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000414static __isl_give isl_map *
415extractPartialSchedule(ScopStmt *Statement, isl_set *Domain) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000416 isl_map *Schedule = Statement->getScattering();
417 int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000418 int UnscheduledDimensions =
419 isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
Sebastian Popa00a0292012-12-18 07:46:06 +0000420
421 return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
422 UnscheduledDimensions);
423}
424
Tobias Grosserd7e58642013-04-10 06:55:45 +0000425void
426ClastStmtCodeGen::codegen(const clast_user_stmt *u, std::vector<Value *> *IVS,
427 const char *iterator, isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000428 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000429
430 if (u->substitutions)
431 codegenSubstitutions(u->substitutions, Statement);
432
Tobias Grosser80998e72012-03-02 11:27:28 +0000433 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000434
Tobias Grosser80998e72012-03-02 11:27:28 +0000435 if (VectorDimensions == 1) {
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000436 BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000437 return;
438 }
439
440 VectorValueMapT VectorMap(VectorDimensions);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000441 std::vector<LoopToScevMapT> VLTS(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000442
443 if (IVS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000444 assert(u->substitutions && "Substitutions expected!");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000445 int i = 0;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000446 for (std::vector<Value *>::iterator II = IVS->begin(), IE = IVS->end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000447 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000448 ClastVars[iterator] = *II;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000449 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap, &VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000450 i++;
451 }
452 }
453
Sebastian Popa00a0292012-12-18 07:46:06 +0000454 isl_map *Schedule = extractPartialSchedule(Statement, Domain);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000455 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, VLTS, Schedule,
456 P);
Sebastian Popa00a0292012-12-18 07:46:06 +0000457 isl_map_free(Schedule);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000458}
459
460void ClastStmtCodeGen::codegen(const clast_block *b) {
461 if (b->body)
462 codegen(b->body);
463}
464
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000465void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
466 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000467 BasicBlock *AfterBB;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000468 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000469
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000470 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
471 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
472 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000473
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000474 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
475 CmpInst::ICMP_SLE);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000476
477 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000478 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000479
480 if (f->body)
481 codegen(f->body);
482
483 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000484 ClastVars.erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000485 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000486}
487
Tobias Grosser177982c2012-11-01 05:34:48 +0000488// Helper class to determine all scalar parameters used in the basic blocks of a
489// clast. Scalar parameters are scalar variables defined outside of the SCoP.
490class ParameterVisitor : public ClastVisitor {
491 std::set<Value *> Values;
Tobias Grosserd7e58642013-04-10 06:55:45 +0000492
Tobias Grosser177982c2012-11-01 05:34:48 +0000493public:
Tobias Grosserc14582f2013-02-05 18:01:29 +0000494 ParameterVisitor() : ClastVisitor(), Values() {}
Tobias Grosser177982c2012-11-01 05:34:48 +0000495
496 void visitUser(const clast_user_stmt *Stmt) {
497 const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
498 const BasicBlock *BB = S->getBasicBlock();
499
500 // Check all the operands of instructions in the basic block.
501 for (BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); BI != BE;
502 ++BI) {
503 const Instruction &Inst = *BI;
504 for (Instruction::const_op_iterator II = Inst.op_begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000505 IE = Inst.op_end();
506 II != IE; ++II) {
Tobias Grosser177982c2012-11-01 05:34:48 +0000507 Value *SrcVal = *II;
508
509 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
510 if (S->getParent()->getRegion().contains(OpInst))
511 continue;
512
513 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
514 Values.insert(SrcVal);
515 }
516 }
517 }
518
519 // Iterator to iterate over the values found.
520 typedef std::set<Value *>::const_iterator const_iterator;
521 inline const_iterator begin() const { return Values.begin(); }
Tobias Grosserc14582f2013-02-05 18:01:29 +0000522 inline const_iterator end() const { return Values.end(); }
Tobias Grosser177982c2012-11-01 05:34:48 +0000523};
524
Tobias Grosserc14582f2013-02-05 18:01:29 +0000525SetVector<Value *> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
526 SetVector<Value *> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000527
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000528 // The clast variables
Tobias Grosserc14582f2013-02-05 18:01:29 +0000529 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
530 I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000531 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000532
Tobias Grosser177982c2012-11-01 05:34:48 +0000533 // Find the temporaries that are referenced in the clast statements'
534 // basic blocks but are not defined by these blocks (e.g., references
535 // to function arguments or temporaries defined before the start of
536 // the SCoP).
537 ParameterVisitor Params;
538 Params.visit(Body);
539
540 for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
541 PI != PE; ++PI) {
542 Value *V = *PI;
543 Values.insert(V);
544 DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
545 }
546
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000547 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000548}
549
Tobias Grosserd7e58642013-04-10 06:55:45 +0000550void
551ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000552 std::set<Value *> Inserted;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000553
Tobias Grosserc14582f2013-02-05 18:01:29 +0000554 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
555 I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000556 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000557 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000558 }
559
Tobias Grossera17f6662012-11-01 05:34:35 +0000560 for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000561 E = VMap.end();
562 I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000563 if (Inserted.count(I->first))
564 continue;
565
566 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000567 }
568}
569
Tobias Grosser900893d2012-03-29 13:10:26 +0000570static void clearDomtree(Function *F, DominatorTree &DT) {
571 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
Tobias Grosserc14582f2013-02-05 18:01:29 +0000572 std::vector<BasicBlock *> Nodes;
573 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
Tobias Grosser900893d2012-03-29 13:10:26 +0000574 Nodes.push_back(I->getBlock());
575
Tobias Grosserc14582f2013-02-05 18:01:29 +0000576 for (std::vector<BasicBlock *>::iterator I = Nodes.begin(), E = Nodes.end();
Tobias Grosser900893d2012-03-29 13:10:26 +0000577 I != E; ++I)
578 DT.eraseNode(*I);
579}
580
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000581void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000582 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000583 BasicBlock::iterator LoopBody;
584 IntegerType *IntPtrTy = getIntPtrTy();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000585 SetVector<Value *> Values;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000586 OMPGenerator::ValueToValueMapTy VMap;
587 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000588
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000589 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
590 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000591 LB = ExpGen.codegen(For->LB, IntPtrTy);
592 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000593
Tobias Grosser177982c2012-11-01 05:34:48 +0000594 Values = getOMPValues(For->body);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000595
Tobias Grosserebf30082012-03-23 12:20:32 +0000596 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000597 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
598 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000599
Tobias Grossera17f6662012-11-01 05:34:35 +0000600 // Save the current values.
601 const ValueMapT ValueMapCopy = ValueMap;
602 const CharMapT ClastVarsCopy = ClastVars;
603
604 updateWithValueMap(VMap);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000605 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000606
607 if (For->body)
608 codegen(For->body);
609
Tobias Grossera17f6662012-11-01 05:34:35 +0000610 // Restore the original values.
611 ValueMap = ValueMapCopy;
612 ClastVars = ClastVarsCopy;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000613
Tobias Grosser900893d2012-03-29 13:10:26 +0000614 clearDomtree((*LoopBody).getParent()->getParent(),
615 P->getAnalysis<DominatorTree>());
616
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000617 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000618}
619
Tobias Grosser6217e182012-08-03 12:50:07 +0000620#ifdef GPU_CODEGEN
621static unsigned getArraySizeInBytes(const ArrayType *AT) {
622 unsigned Bytes = AT->getNumElements();
623 if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
624 Bytes *= getArraySizeInBytes(T);
625 else
626 Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
627
628 return Bytes;
629}
630
Tobias Grosserc14582f2013-02-05 18:01:29 +0000631SetVector<Value *> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
632 SetVector<Value *> Values;
Tobias Grosser6217e182012-08-03 12:50:07 +0000633 OutputBytes = 0;
634
635 // Record the memory reference base addresses.
636 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
637 ScopStmt *Stmt = *SI;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000638 for (SmallVector<MemoryAccess *, 8>::iterator I = Stmt->memacc_begin(),
639 E = Stmt->memacc_end();
640 I != E; ++I) {
641 Value *BaseAddr = const_cast<Value *>((*I)->getBaseAddr());
Tobias Grosser6217e182012-08-03 12:50:07 +0000642 Values.insert((BaseAddr));
643
644 // FIXME: we assume that there is one and only one array to be written
645 // in a SCoP.
646 int NumWrites = 0;
647 if ((*I)->isWrite()) {
648 ++NumWrites;
649 assert(NumWrites <= 1 &&
650 "We support at most one array to be written in a SCoP.");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000651 if (const PointerType *PT =
652 dyn_cast<PointerType>(BaseAddr->getType())) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000653 Type *T = PT->getArrayElementType();
654 const ArrayType *ATy = dyn_cast<ArrayType>(T);
655 OutputBytes = getArraySizeInBytes(ATy);
656 }
657 }
658 }
659 }
660
661 return Values;
662}
663
Tobias Grosserc14582f2013-02-05 18:01:29 +0000664const clast_stmt *ClastStmtCodeGen::getScheduleInfo(
665 const clast_for *F, std::vector<int> &NumIters, unsigned &LoopDepth,
666 unsigned &NonPLoopDepth) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000667 clast_stmt *Stmt = (clast_stmt *)F;
668 const clast_for *Result;
669 bool NonParaFlag = false;
670 LoopDepth = 0;
671 NonPLoopDepth = 0;
672
673 while (Stmt) {
674 if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000675 const clast_for *T = (clast_for *)Stmt;
Tobias Grosser6217e182012-08-03 12:50:07 +0000676 if (isParallelFor(T)) {
677 if (!NonParaFlag) {
678 NumIters.push_back(getNumberOfIterations(T));
679 Result = T;
680 }
681 } else
682 NonParaFlag = true;
683
684 Stmt = T->body;
685 LoopDepth++;
686 continue;
687 }
688 Stmt = Stmt->next;
689 }
690
691 assert(NumIters.size() == 4 &&
692 "The loops should be tiled into 4-depth parallel loops and an "
693 "innermost non-parallel one (if exist).");
694 NonPLoopDepth = LoopDepth - NumIters.size();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000695 assert(NonPLoopDepth <= 1 &&
696 "We support only one innermost non-parallel loop currently.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000697 return (const clast_stmt *)Result->body;
698}
699
700void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
701 BasicBlock::iterator LoopBody;
702 SetVector<Value *> Values;
703 SetVector<Value *> IVS;
704 std::vector<int> NumIterations;
705 PTXGenerator::ValueToValueMapTy VMap;
706
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000707 assert(!GPUTriple.empty() &&
708 "Target triple should be set properly for GPGPU code generation.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000709 PTXGenerator PTXGen(Builder, P, GPUTriple);
710
711 // Get original IVS and ScopStmt
712 unsigned TiledLoopDepth, NonPLoopDepth;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000713 const clast_stmt *InnerStmt =
714 getScheduleInfo(F, NumIterations, TiledLoopDepth, NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000715 const clast_stmt *TmpStmt;
716 const clast_user_stmt *U;
717 const clast_for *InnerFor;
718 if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
719 InnerFor = (const clast_for *)InnerStmt;
720 TmpStmt = InnerFor->body;
721 } else
722 TmpStmt = InnerStmt;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000723 U = (const clast_user_stmt *)TmpStmt;
724 ScopStmt *Statement = (ScopStmt *)U->statement->usr;
Tobias Grosser6217e182012-08-03 12:50:07 +0000725 for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000726 const Value *IV = Statement->getInductionVariableForDimension(i);
Tobias Grosser6217e182012-08-03 12:50:07 +0000727 IVS.insert(const_cast<Value *>(IV));
728 }
729
730 unsigned OutBytes;
731 Values = getGPUValues(OutBytes);
732 PTXGen.setOutputBytes(OutBytes);
733 PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
734
735 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
736 Builder.SetInsertPoint(LoopBody);
737
738 BasicBlock *AfterBB = 0;
739 if (NonPLoopDepth) {
740 Value *LowerBound, *UpperBound, *IV, *Stride;
741 Type *IntPtrTy = getIntPtrTy();
742 LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
743 UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
744 Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
Tobias Grosser6f3d0632012-11-30 00:39:49 +0000745 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
746 CmpInst::ICMP_SLE);
Tobias Grosser6217e182012-08-03 12:50:07 +0000747 const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
748 Value *OldIV = const_cast<Value *>(OldIV_);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000749 VMap.insert(std::make_pair<Value *, Value *>(OldIV, IV));
Tobias Grosser6217e182012-08-03 12:50:07 +0000750 }
751
Tobias Grosser46c6abb2012-11-30 01:05:05 +0000752 updateWithValueMap(VMap);
Tobias Grossera17f6662012-11-01 05:34:35 +0000753
Tobias Grosser6217e182012-08-03 12:50:07 +0000754 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grossera17f6662012-11-01 05:34:35 +0000755
Tobias Grosser6217e182012-08-03 12:50:07 +0000756 if (AfterBB)
757 Builder.SetInsertPoint(AfterBB->begin());
758
759 // FIXME: The replacement of the host base address with the parameter of ptx
760 // subfunction should have been done by updateWithValueMap. We use the
761 // following codes to avoid affecting other parts of Polly. This should be
762 // fixed later.
763 Function *FN = Builder.GetInsertBlock()->getParent();
764 for (unsigned j = 0; j < Values.size(); j++) {
765 Value *baseAddr = Values[j];
766 for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
767 for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
768 I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
769 }
770 }
771 Builder.SetInsertPoint(AfterLoop);
772 PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
773 NumIterations[2], NumIterations[3]);
774 PTXGen.finishGeneration(FN);
775}
776#endif
777
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000778bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
779 const clast_stmt *stmt = f->body;
780
781 while (stmt) {
782 if (!CLAST_STMT_IS_A(stmt, stmt_user))
783 return false;
784
785 stmt = stmt->next;
786 }
787
788 return true;
789}
790
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000791int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
792 isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000793 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
794 if (NumberOfIterations == -1)
795 return -1;
796 return NumberOfIterations / isl_int_get_si(For->stride) + 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000797}
798
Tobias Grosser2da263e2012-03-15 09:34:55 +0000799void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
800 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
801 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000802
Tobias Grosser2da263e2012-03-15 09:34:55 +0000803 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000804
Tobias Grosser2da263e2012-03-15 09:34:55 +0000805 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000806 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000807 Stride = Stride.zext(LoopIVType->getBitWidth());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000808 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
809
Tobias Grosserc14582f2013-02-05 18:01:29 +0000810 std::vector<Value *> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000811 IVS[0] = LB;
812
Tobias Grosser2da263e2012-03-15 09:34:55 +0000813 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000814 IVS[i] = Builder.CreateAdd(IVS[i - 1], StrideValue, "p_vector_iv");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000815
Tobias Grosser00d898d2012-03-15 09:34:58 +0000816 isl_set *Domain = isl_set_from_cloog_domain(F->domain);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000817
818 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000819 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000820
Tobias Grosser2da263e2012-03-15 09:34:55 +0000821 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000822
Tobias Grosser2da263e2012-03-15 09:34:55 +0000823 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000824 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
825 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000826 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000827 }
828
829 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000830 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000831 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000832}
833
Tobias Grossere192b232012-05-22 08:46:07 +0000834bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
835 isl_set *Domain = isl_set_from_cloog_domain(f->domain);
836 assert(Domain && "Cannot access domain of loop");
837
838 Dependences &D = P->getAnalysis<Dependences>();
839
840 return D.isParallelDimension(isl_set_copy(Domain), isl_set_n_dim(Domain));
841}
842
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000843void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000844 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000845 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000846 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f)) &&
847 (getNumberOfIterations(f) <= 16)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000848 codegenForVector(f);
849 return;
850 }
851
852 if (OpenMP && !parallelCodeGeneration) {
853 parallelCodeGeneration = true;
854 parallelLoops.push_back(f->iterator);
855 codegenForOpenMP(f);
856 parallelCodeGeneration = false;
857 return;
858 }
859 }
860
Tobias Grosser6217e182012-08-03 12:50:07 +0000861#ifdef GPU_CODEGEN
862 if (GPGPU && isParallelFor(f)) {
863 if (!parallelCodeGeneration) {
864 parallelCodeGeneration = true;
865 parallelLoops.push_back(f->iterator);
866 codegenForGPGPU(f);
867 parallelCodeGeneration = false;
868 return;
869 }
870 }
871#endif
872
Tobias Grosserce3f5372012-03-02 11:26:42 +0000873 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000874}
875
876Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000877 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
878 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000879 CmpInst::Predicate P;
880
881 if (eq->sign == 0)
882 P = ICmpInst::ICMP_EQ;
883 else if (eq->sign > 0)
884 P = ICmpInst::ICMP_SGE;
885 else
886 P = ICmpInst::ICMP_SLE;
887
888 return Builder.CreateICmp(P, LHS, RHS);
889}
890
891void ClastStmtCodeGen::codegen(const clast_guard *g) {
892 Function *F = Builder.GetInsertBlock()->getParent();
893 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000894
Tobias Grosserc14582f2013-02-05 18:01:29 +0000895 BasicBlock *CondBB =
896 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000897 CondBB->setName("polly.cond");
898 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
899 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000900 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000901
Tobias Grosserd596b372012-03-15 09:34:52 +0000902 DominatorTree &DT = P->getAnalysis<DominatorTree>();
903 DT.addNewBlock(ThenBB, CondBB);
904 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000905
906 CondBB->getTerminator()->eraseFromParent();
907
908 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000909
910 Value *Predicate = codegen(&(g->eq[0]));
911
912 for (int i = 1; i < g->n; ++i) {
913 Value *TmpPredicate = codegen(&(g->eq[i]));
914 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
915 }
916
917 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
918 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000919 Builder.CreateBr(MergeBB);
920 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000921
922 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000923
924 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000925}
926
927void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000928 if (CLAST_STMT_IS_A(stmt, stmt_root))
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000929 assert(false && "No second root statement expected");
930 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
931 codegen((const clast_assignment *)stmt);
932 else if (CLAST_STMT_IS_A(stmt, stmt_user))
933 codegen((const clast_user_stmt *)stmt);
934 else if (CLAST_STMT_IS_A(stmt, stmt_block))
935 codegen((const clast_block *)stmt);
936 else if (CLAST_STMT_IS_A(stmt, stmt_for))
937 codegen((const clast_for *)stmt);
938 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
939 codegen((const clast_guard *)stmt);
940
941 if (stmt->next)
942 codegen(stmt->next);
943}
944
945void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000946 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000947
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000948 int i = 0;
949 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
950 PI != PE; ++PI) {
951 assert(i < names->nb_parameters && "Not enough parameter names");
952
953 const SCEV *Param = *PI;
954 Type *Ty = Param->getType();
955
956 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
957 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000958 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000959
960 ++i;
961 }
962}
963
964void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000965 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000966
967 parallelCodeGeneration = false;
968
Tobias Grosserc14582f2013-02-05 18:01:29 +0000969 const clast_stmt *stmt = (const clast_stmt *)r;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000970 if (stmt->next)
971 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000972}
973
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000974ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000975 : S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000976
Tobias Grosser75805372011-04-29 06:27:02 +0000977namespace {
978class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +0000979 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +0000980
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000981public:
Tobias Grosser75805372011-04-29 06:27:02 +0000982 static char ID;
983
984 CodeGeneration() : ScopPass(ID) {}
985
Tobias Grosser3a275d22012-05-29 09:11:54 +0000986 bool runOnScop(Scop &S) {
987 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +0000988
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000989 Region &R = S.getRegion();
990
Tobias Grosserd7e58642013-04-10 06:55:45 +0000991 assert(!R.isTopLevelRegion() && "Top level regions are not supported");
992 assert(R.getEnteringBlock() && "Only support regions with a single entry");
Tobias Grosser0ee50f62013-04-10 06:55:31 +0000993
994 if (!R.getExitingBlock()) {
995 BasicBlock *newExit = createSingleExitEdge(&R, this);
996 for (Region::const_iterator RI = R.begin(), RE = R.end(); RI != RE; ++RI)
997 (*RI)->replaceExitRecursive(newExit);
998 }
Tobias Grossercb47dfe2012-02-15 09:58:50 +0000999
Tobias Grosser3a275d22012-05-29 09:11:54 +00001000 BasicBlock *StartBlock = executeScopConditionally(S, this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001001
Tobias Grosser3a275d22012-05-29 09:11:54 +00001002 IRBuilder<> Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001003
Tobias Grosser3a275d22012-05-29 09:11:54 +00001004 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001005 CloogInfo &C = getAnalysis<CloogInfo>();
1006 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001007
Tobias Grosser3a275d22012-05-29 09:11:54 +00001008 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +00001009 CodeGen.getParallelLoops().begin(),
1010 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001011 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001012 }
1013
1014 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001015 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +00001016 PE = ParallelLoops.end();
1017 PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +00001018 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1019 }
1020
1021 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1022 AU.addRequired<CloogInfo>();
1023 AU.addRequired<Dependences>();
1024 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001025 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001026 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001027 AU.addRequired<ScopDetection>();
1028 AU.addRequired<ScopInfo>();
Micah Villmow7a3d8202012-10-08 17:26:19 +00001029 AU.addRequired<DataLayout>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001030 AU.addRequired<LoopInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001031
1032 AU.addPreserved<CloogInfo>();
1033 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001034
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001035 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001036 AU.addPreserved<LoopInfo>();
1037 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001038 AU.addPreserved<ScopDetection>();
1039 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001040
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001041 // FIXME: We do not yet add regions for the newly generated code to the
1042 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001043 AU.addPreserved<RegionInfo>();
1044 AU.addPreserved<TempScopInfo>();
1045 AU.addPreserved<ScopInfo>();
1046 AU.addPreservedID(IndependentBlocksID);
1047 }
1048};
1049}
1050
1051char CodeGeneration::ID = 1;
1052
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001053Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
Sebastian Pope1f65542012-05-07 16:35:11 +00001054
Tobias Grosser7242ad92013-02-22 08:07:06 +00001055INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1056 "Polly - Create LLVM-IR from SCoPs", false, false);
1057INITIALIZE_PASS_DEPENDENCY(CloogInfo);
1058INITIALIZE_PASS_DEPENDENCY(Dependences);
1059INITIALIZE_PASS_DEPENDENCY(DominatorTree);
1060INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1061INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1062INITIALIZE_PASS_DEPENDENCY(ScopDetection);
1063INITIALIZE_PASS_DEPENDENCY(DataLayout);
1064INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001065 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser7242ad92013-02-22 08:07:06 +00001066
Sebastian Pope1f65542012-05-07 16:35:11 +00001067#endif // CLOOG_FOUND