blob: 36c39cd070e7ed0da9ff162a35d6735cae5b4baa [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:
Tobias Grosser75805372011-04-29 06:27:02 +000094 // 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
Sebastian Popbfec3612014-02-22 02:15:39 +0000118static APInt APInt_from_MPZ(const mpz_t mpz) {
119 uint64_t *p = NULL;
120 size_t sz;
121
122 p = (uint64_t *)mpz_export(p, &sz, -1, sizeof(uint64_t), 0, 0, mpz);
123
124 if (p) {
125 APInt A((unsigned)mpz_sizeinbase(mpz, 2), (unsigned)sz, p);
126 A = A.zext(A.getBitWidth() + 1);
127 free(p);
128
129 if (mpz_sgn(mpz) == -1)
130 return -A;
131 else
132 return A;
133 } else {
134 uint64_t val = 0;
135 return APInt(1, 1, &val);
136 }
137}
138
Tobias Grosserbb137e32012-01-24 16:42:28 +0000139Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
140 APInt a = APInt_from_MPZ(e->val);
141
142 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
143 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
144
145 if (!e->var)
146 return ConstOne;
147
148 Value *var = codegen(e->var, Ty);
149 return Builder.CreateMul(ConstOne, var);
150}
151
152Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
153 Value *LHS = codegen(e->LHS, Ty);
154
155 APInt RHS_AP = APInt_from_MPZ(e->RHS);
156
157 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
158 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
159
160 switch (e->type) {
161 case clast_bin_mod:
162 return Builder.CreateSRem(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000163 case clast_bin_fdiv: {
164 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
165 Value *One = ConstantInt::get(Ty, 1);
166 Value *Zero = ConstantInt::get(Ty, 0);
167 Value *Sum1 = Builder.CreateSub(LHS, RHS);
168 Value *Sum2 = Builder.CreateAdd(Sum1, One);
169 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
170 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
171 return Builder.CreateSDiv(Dividend, RHS);
172 }
173 case clast_bin_cdiv: {
174 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
175 Value *One = ConstantInt::get(Ty, 1);
176 Value *Zero = ConstantInt::get(Ty, 0);
177 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
178 Value *Sum2 = Builder.CreateSub(Sum1, One);
179 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
180 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
181 return Builder.CreateSDiv(Dividend, RHS);
182 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000183 case clast_bin_div:
184 return Builder.CreateSDiv(LHS, RHS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000185 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000186
187 llvm_unreachable("Unknown clast binary expression type");
188}
189
190Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000191 assert((r->type == clast_red_min || r->type == clast_red_max ||
Tobias Grosser58032cb2013-06-23 01:29:29 +0000192 r->type == clast_red_sum) &&
193 "Clast reduction type not supported");
Tobias Grosserbb137e32012-01-24 16:42:28 +0000194 Value *old = codegen(r->elts[0], Ty);
195
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000196 for (int i = 1; i < r->n; ++i) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000197 Value *exprValue = codegen(r->elts[i], Ty);
198
199 switch (r->type) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000200 case clast_red_min: {
201 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
202 old = Builder.CreateSelect(cmp, old, exprValue);
203 break;
204 }
205 case clast_red_max: {
206 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
207 old = Builder.CreateSelect(cmp, old, exprValue);
208 break;
209 }
Tobias Grosserbb137e32012-01-24 16:42:28 +0000210 case clast_red_sum:
211 old = Builder.CreateAdd(old, exprValue);
212 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000213 }
Tobias Grosser75805372011-04-29 06:27:02 +0000214 }
215
Tobias Grosserbb137e32012-01-24 16:42:28 +0000216 return old;
217}
218
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000219ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000220 : Builder(B), IVS(IVMap) {}
Tobias Grosserbb137e32012-01-24 16:42:28 +0000221
222Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000223 switch (e->type) {
Tobias Grosserbb137e32012-01-24 16:42:28 +0000224 case clast_expr_name:
225 return codegen((const clast_name *)e, Ty);
226 case clast_expr_term:
227 return codegen((const clast_term *)e, Ty);
228 case clast_expr_bin:
229 return codegen((const clast_binary *)e, Ty);
230 case clast_expr_red:
231 return codegen((const clast_reduction *)e, Ty);
232 }
233
234 llvm_unreachable("Unknown clast expression!");
235}
236
Tobias Grosser75805372011-04-29 06:27:02 +0000237class ClastStmtCodeGen {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000238public:
239 const std::vector<std::string> &getParallelLoops();
240
241private:
Tobias Grosser75805372011-04-29 06:27:02 +0000242 // The Scop we code generate.
243 Scop *S;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000244 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000245
246 // The Builder specifies the current location to code generate at.
247 IRBuilder<> &Builder;
248
249 // Map the Values from the old code to their counterparts in the new code.
250 ValueMapT ValueMap;
251
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000252 // Map the loops from the old code to expressions function of the induction
253 // variables in the new code. For example, when the code generator produces
254 // this AST:
255 //
256 // for (int c1 = 0; c1 <= 1023; c1 += 1)
257 // for (int c2 = 0; c2 <= 1023; c2 += 1)
258 // Stmt(c2 + 3, c1);
259 //
260 // LoopToScev is a map associating:
261 // "outer loop in the old loop nest" -> SCEV("c2 + 3"),
262 // "inner loop in the old loop nest" -> SCEV("c1").
263 LoopToScevMapT LoopToScev;
264
Tobias Grosser75805372011-04-29 06:27:02 +0000265 // clastVars maps from the textual representation of a clast variable to its
266 // current *Value. clast variables are scheduling variables, original
267 // induction variables or parameters. They are used either in loop bounds or
268 // to define the statement instance that is executed.
269 //
270 // for (s = 0; s < n + 3; ++i)
271 // for (t = s; t < m; ++j)
272 // Stmt(i = s + 3 * m, j = t);
273 //
274 // {s,t,i,j,n,m} is the set of clast variables in this clast.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000275 CharMapT ClastVars;
Tobias Grosser75805372011-04-29 06:27:02 +0000276
277 // Codegenerator for clast expressions.
278 ClastExpCodeGen ExpGen;
279
280 // Do we currently generate parallel code?
281 bool parallelCodeGeneration;
282
283 std::vector<std::string> parallelLoops;
284
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000285 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000286
Tobias Grossere602a072013-05-07 07:30:56 +0000287 void codegen(const clast_assignment *a, ScopStmt *Statement,
288 unsigned Dimension, int vectorDim,
289 std::vector<ValueMapT> *VectorVMap = 0,
290 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000291
Tobias Grosserc14582f2013-02-05 18:01:29 +0000292 void codegenSubstitutions(const clast_stmt *Assignment, ScopStmt *Statement,
293 int vectorDim = 0,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000294 std::vector<ValueMapT> *VectorVMap = 0,
295 std::vector<LoopToScevMapT> *VLTS = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000296
Tobias Grosserc14582f2013-02-05 18:01:29 +0000297 void codegen(const clast_user_stmt *u, std::vector<Value *> *IVS = NULL,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000298 const char *iterator = NULL,
299 __isl_take isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000300
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000301 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000302
303 /// @brief Create a classical sequential loop.
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000304 void codegenForSequential(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000305
306 /// @brief Create OpenMP structure values.
307 ///
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000308 /// Create a list of values that has to be stored into the OpenMP subfuncition
Tobias Grosser75805372011-04-29 06:27:02 +0000309 /// structure.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000310 SetVector<Value *> getOMPValues(const clast_stmt *Body);
Tobias Grosser75805372011-04-29 06:27:02 +0000311
Tobias Grossera17f6662012-11-01 05:34:35 +0000312 /// @brief Update ClastVars and ValueMap according to a value map.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000313 ///
Tobias Grossera17f6662012-11-01 05:34:35 +0000314 /// @param VMap A map from old to new values.
315 void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000316
317 /// @brief Create an OpenMP parallel for loop.
318 ///
319 /// This loop reflects a loop as if it would have been created by an OpenMP
320 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000321 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000322
Tobias Grosser6217e182012-08-03 12:50:07 +0000323#ifdef GPU_CODEGEN
324 /// @brief Create GPGPU device memory access values.
325 ///
326 /// Create a list of values that will be set to be parameters of the GPGPU
327 /// subfunction. These parameters represent device memory base addresses
328 /// and the size in bytes.
Tobias Grosserc14582f2013-02-05 18:01:29 +0000329 SetVector<Value *> getGPUValues(unsigned &OutputBytes);
Tobias Grosser6217e182012-08-03 12:50:07 +0000330
331 /// @brief Create a GPU parallel for loop.
332 ///
333 /// This loop reflects a loop as if it would have been created by a GPU
334 /// statement.
335 void codegenForGPGPU(const clast_for *F);
336
337 /// @brief Get innermost for loop.
Tobias Grossere602a072013-05-07 07:30:56 +0000338 const clast_stmt *getScheduleInfo(const clast_for *F,
339 std::vector<int> &NumIters,
340 unsigned &LoopDepth,
341 unsigned &NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000342#endif /* GPU_CODEGEN */
343
Tobias Grossere192b232012-05-22 08:46:07 +0000344 /// @brief Check if a loop is parallel
345 ///
346 /// Detect if a clast_for loop can be executed in parallel.
347 ///
Tobias Grosserc1b6cec2012-11-19 12:26:25 +0000348 /// @param For The clast for loop to check.
Tobias Grossere192b232012-05-22 08:46:07 +0000349 ///
350 /// @return bool Returns true if the incoming clast_for statement can
351 /// execute in parallel.
352 bool isParallelFor(const clast_for *For);
353
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000354 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000355
356 /// @brief Get the number of loop iterations for this loop.
357 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000358 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000359
360 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000361 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000362
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000363 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000364
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000365 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000366
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000367 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000368
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000369 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000370
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000371 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +0000372
Tobias Grossere9ffea22012-03-15 09:34:48 +0000373 IntegerType *getIntPtrTy();
374
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000375public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000376 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +0000377
Tobias Grosserd596b372012-03-15 09:34:52 +0000378 ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +0000379};
380}
381
Tobias Grossere9ffea22012-03-15 09:34:48 +0000382IntegerType *ClastStmtCodeGen::getIntPtrTy() {
Rafael Espindolac5d16892014-02-25 19:17:57 +0000383 return P->getAnalysis<DataLayoutPass>().getDataLayout().getIntPtrType(
384 Builder.getContext());
Tobias Grossere9ffea22012-03-15 09:34:48 +0000385}
386
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000387const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
388 return parallelLoops;
389}
390
391void ClastStmtCodeGen::codegen(const clast_assignment *a) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000392 Value *V = ExpGen.codegen(a->RHS, getIntPtrTy());
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000393 ClastVars[a->LHS] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000394}
395
Tobias Grossere602a072013-05-07 07:30:56 +0000396void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
397 unsigned Dim, int VectorDim,
398 std::vector<ValueMapT> *VectorVMap,
399 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosserf00bd962012-04-02 12:26:13 +0000400 Value *RHS;
401
402 assert(!A->LHS && "Statement assignments do not have left hand side");
403
Tobias Grosser0905a232012-04-03 12:24:32 +0000404 RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000405
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000406 const llvm::SCEV *URHS = S->getSE()->getUnknown(RHS);
407 if (VLTS)
408 (*VLTS)[VectorDim][Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000409 LoopToScev[Stmt->getLoopForDimension(Dim)] = URHS;
Sebastian Pope039bb12013-03-18 19:09:49 +0000410
411 const PHINode *PN = Stmt->getInductionVariableForDimension(Dim);
412 if (PN) {
413 RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
414
415 if (VectorVMap)
416 (*VectorVMap)[VectorDim][PN] = RHS;
417
418 ValueMap[PN] = RHS;
419 }
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000420}
421
Tobias Grossere602a072013-05-07 07:30:56 +0000422void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
423 ScopStmt *Statement, int vectorDim,
424 std::vector<ValueMapT> *VectorVMap,
425 std::vector<LoopToScevMapT> *VLTS) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000426 int Dimension = 0;
427
428 while (Assignment) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000429 assert(CLAST_STMT_IS_A(Assignment, stmt_ass) &&
430 "Substitions are expected to be assignments");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000431 codegen((const clast_assignment *)Assignment, Statement, Dimension,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000432 vectorDim, VectorVMap, VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000433 Assignment = Assignment->next;
434 Dimension++;
435 }
436}
437
Sebastian Popa00a0292012-12-18 07:46:06 +0000438// Takes the cloog specific domain and translates it into a map Statement ->
439// PartialSchedule, where the PartialSchedule contains all the dimensions that
440// have been code generated up to this point.
Tobias Grossere602a072013-05-07 07:30:56 +0000441static __isl_give isl_map *extractPartialSchedule(ScopStmt *Statement,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000442 __isl_take isl_set *Domain) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000443 isl_map *Schedule = Statement->getScattering();
444 int ScheduledDimensions = isl_set_dim(Domain, isl_dim_set);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000445 int UnscheduledDimensions =
446 isl_map_dim(Schedule, isl_dim_out) - ScheduledDimensions;
Sebastian Popa00a0292012-12-18 07:46:06 +0000447
Tobias Grosser880c52f2013-07-29 01:58:07 +0000448 isl_set_free(Domain);
449
Sebastian Popa00a0292012-12-18 07:46:06 +0000450 return isl_map_project_out(Schedule, isl_dim_out, ScheduledDimensions,
451 UnscheduledDimensions);
452}
453
Tobias Grossere602a072013-05-07 07:30:56 +0000454void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
455 std::vector<Value *> *IVS, const char *iterator,
Tobias Grosser880c52f2013-07-29 01:58:07 +0000456 __isl_take isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000457 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000458
459 if (u->substitutions)
460 codegenSubstitutions(u->substitutions, Statement);
461
Tobias Grosser80998e72012-03-02 11:27:28 +0000462 int VectorDimensions = IVS ? IVS->size() : 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000463
Tobias Grosser80998e72012-03-02 11:27:28 +0000464 if (VectorDimensions == 1) {
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000465 BlockGenerator::generate(Builder, *Statement, ValueMap, LoopToScev, P);
Tobias Grosser80998e72012-03-02 11:27:28 +0000466 return;
467 }
468
469 VectorValueMapT VectorMap(VectorDimensions);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000470 std::vector<LoopToScevMapT> VLTS(VectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000471
472 if (IVS) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000473 assert(u->substitutions && "Substitutions expected!");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000474 int i = 0;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000475 for (std::vector<Value *>::iterator II = IVS->begin(), IE = IVS->end();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000476 II != IE; ++II) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000477 ClastVars[iterator] = *II;
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000478 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap, &VLTS);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000479 i++;
480 }
481 }
482
Sebastian Popa00a0292012-12-18 07:46:06 +0000483 isl_map *Schedule = extractPartialSchedule(Statement, Domain);
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000484 VectorBlockGenerator::generate(Builder, *Statement, VectorMap, VLTS, Schedule,
485 P);
Sebastian Popa00a0292012-12-18 07:46:06 +0000486 isl_map_free(Schedule);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000487}
488
489void ClastStmtCodeGen::codegen(const clast_block *b) {
490 if (b->body)
491 codegen(b->body);
492}
493
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000494void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
495 Value *LowerBound, *UpperBound, *IV, *Stride;
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000496 BasicBlock *ExitBlock;
Tobias Grossere9ffea22012-03-15 09:34:48 +0000497 Type *IntPtrTy = getIntPtrTy();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000498
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000499 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
500 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
501 Stride = Builder.getInt(APInt_from_MPZ(f->stride));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000502
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000503 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, ExitBlock,
Tobias Grosserc967d8e2012-10-16 07:29:13 +0000504 CmpInst::ICMP_SLE);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000505
506 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000507 ClastVars[f->iterator] = IV;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000508
509 if (f->body)
510 codegen(f->body);
511
512 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000513 ClastVars.erase(f->iterator);
Tobias Grosser5db6ffd2013-05-16 06:40:06 +0000514 Builder.SetInsertPoint(ExitBlock->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000515}
516
Tobias Grosser177982c2012-11-01 05:34:48 +0000517// Helper class to determine all scalar parameters used in the basic blocks of a
518// clast. Scalar parameters are scalar variables defined outside of the SCoP.
519class ParameterVisitor : public ClastVisitor {
520 std::set<Value *> Values;
Tobias Grosserd7e58642013-04-10 06:55:45 +0000521
Tobias Grosser177982c2012-11-01 05:34:48 +0000522public:
Tobias Grosserc14582f2013-02-05 18:01:29 +0000523 ParameterVisitor() : ClastVisitor(), Values() {}
Tobias Grosser177982c2012-11-01 05:34:48 +0000524
525 void visitUser(const clast_user_stmt *Stmt) {
526 const ScopStmt *S = static_cast<const ScopStmt *>(Stmt->statement->usr);
527 const BasicBlock *BB = S->getBasicBlock();
528
529 // Check all the operands of instructions in the basic block.
530 for (BasicBlock::const_iterator BI = BB->begin(), BE = BB->end(); BI != BE;
531 ++BI) {
532 const Instruction &Inst = *BI;
533 for (Instruction::const_op_iterator II = Inst.op_begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000534 IE = Inst.op_end();
535 II != IE; ++II) {
Tobias Grosser177982c2012-11-01 05:34:48 +0000536 Value *SrcVal = *II;
537
538 if (Instruction *OpInst = dyn_cast<Instruction>(SrcVal))
539 if (S->getParent()->getRegion().contains(OpInst))
540 continue;
541
542 if (isa<Instruction>(SrcVal) || isa<Argument>(SrcVal))
543 Values.insert(SrcVal);
544 }
545 }
546 }
547
548 // Iterator to iterate over the values found.
549 typedef std::set<Value *>::const_iterator const_iterator;
550 inline const_iterator begin() const { return Values.begin(); }
Tobias Grosserc14582f2013-02-05 18:01:29 +0000551 inline const_iterator end() const { return Values.end(); }
Tobias Grosser177982c2012-11-01 05:34:48 +0000552};
553
Tobias Grosserc14582f2013-02-05 18:01:29 +0000554SetVector<Value *> ClastStmtCodeGen::getOMPValues(const clast_stmt *Body) {
555 SetVector<Value *> Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000556
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000557 // The clast variables
Tobias Grosserc14582f2013-02-05 18:01:29 +0000558 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
559 I++)
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000560 Values.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000561
Tobias Grosser177982c2012-11-01 05:34:48 +0000562 // Find the temporaries that are referenced in the clast statements'
563 // basic blocks but are not defined by these blocks (e.g., references
564 // to function arguments or temporaries defined before the start of
565 // the SCoP).
566 ParameterVisitor Params;
567 Params.visit(Body);
568
569 for (ParameterVisitor::const_iterator PI = Params.begin(), PE = Params.end();
570 PI != PE; ++PI) {
571 Value *V = *PI;
572 Values.insert(V);
573 DEBUG(dbgs() << "Adding temporary for OMP copy-in: " << *V << "\n");
574 }
575
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000576 return Values;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000577}
578
Tobias Grosserd7e58642013-04-10 06:55:45 +0000579void
580ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000581 std::set<Value *> Inserted;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000582
Tobias Grosserc14582f2013-02-05 18:01:29 +0000583 for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end(); I != E;
584 I++) {
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000585 ClastVars[I->first] = VMap[I->second];
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000586 Inserted.insert(I->second);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000587 }
588
Tobias Grossera17f6662012-11-01 05:34:35 +0000589 for (OMPGenerator::ValueToValueMapTy::iterator I = VMap.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000590 E = VMap.end();
591 I != E; ++I) {
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000592 if (Inserted.count(I->first))
593 continue;
594
595 ValueMap[I->first] = I->second;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000596 }
597}
598
Tobias Grosser900893d2012-03-29 13:10:26 +0000599static void clearDomtree(Function *F, DominatorTree &DT) {
600 DomTreeNode *N = DT.getNode(&F->getEntryBlock());
Tobias Grosserc14582f2013-02-05 18:01:29 +0000601 std::vector<BasicBlock *> Nodes;
602 for (po_iterator<DomTreeNode *> I = po_begin(N), E = po_end(N); I != E; ++I)
Tobias Grosser900893d2012-03-29 13:10:26 +0000603 Nodes.push_back(I->getBlock());
604
Tobias Grosserc14582f2013-02-05 18:01:29 +0000605 for (std::vector<BasicBlock *>::iterator I = Nodes.begin(), E = Nodes.end();
Tobias Grosser900893d2012-03-29 13:10:26 +0000606 I != E; ++I)
607 DT.eraseNode(*I);
608}
609
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000610void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
Tobias Grosserebf30082012-03-23 12:20:32 +0000611 Value *Stride, *LB, *UB, *IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000612 BasicBlock::iterator LoopBody;
613 IntegerType *IntPtrTy = getIntPtrTy();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000614 SetVector<Value *> Values;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000615 OMPGenerator::ValueToValueMapTy VMap;
616 OMPGenerator OMPGen(Builder, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000617
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000618 Stride = Builder.getInt(APInt_from_MPZ(For->stride));
619 Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
Tobias Grosserebf30082012-03-23 12:20:32 +0000620 LB = ExpGen.codegen(For->LB, IntPtrTy);
621 UB = ExpGen.codegen(For->UB, IntPtrTy);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000622
Tobias Grosser177982c2012-11-01 05:34:48 +0000623 Values = getOMPValues(For->body);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000624
Tobias Grosserebf30082012-03-23 12:20:32 +0000625 IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000626 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
627 Builder.SetInsertPoint(LoopBody);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000628
Tobias Grossera17f6662012-11-01 05:34:35 +0000629 // Save the current values.
630 const ValueMapT ValueMapCopy = ValueMap;
631 const CharMapT ClastVarsCopy = ClastVars;
632
633 updateWithValueMap(VMap);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000634 ClastVars[For->iterator] = IV;
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000635
636 if (For->body)
637 codegen(For->body);
638
Tobias Grossera17f6662012-11-01 05:34:35 +0000639 // Restore the original values.
640 ValueMap = ValueMapCopy;
641 ClastVars = ClastVarsCopy;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000642
Tobias Grosser900893d2012-03-29 13:10:26 +0000643 clearDomtree((*LoopBody).getParent()->getParent(),
Tobias Grosser42aff302014-01-13 22:29:56 +0000644 P->getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Tobias Grosser900893d2012-03-29 13:10:26 +0000645
Tobias Grosserf74a4cd2012-03-23 10:35:18 +0000646 Builder.SetInsertPoint(AfterLoop);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000647}
648
Tobias Grosser6217e182012-08-03 12:50:07 +0000649#ifdef GPU_CODEGEN
650static unsigned getArraySizeInBytes(const ArrayType *AT) {
651 unsigned Bytes = AT->getNumElements();
652 if (const ArrayType *T = dyn_cast<ArrayType>(AT->getElementType()))
653 Bytes *= getArraySizeInBytes(T);
654 else
655 Bytes *= AT->getElementType()->getPrimitiveSizeInBits() / 8;
656
657 return Bytes;
658}
659
Tobias Grosserc14582f2013-02-05 18:01:29 +0000660SetVector<Value *> ClastStmtCodeGen::getGPUValues(unsigned &OutputBytes) {
661 SetVector<Value *> Values;
Tobias Grosser6217e182012-08-03 12:50:07 +0000662 OutputBytes = 0;
663
664 // Record the memory reference base addresses.
665 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
666 ScopStmt *Stmt = *SI;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000667 for (SmallVector<MemoryAccess *, 8>::iterator I = Stmt->memacc_begin(),
668 E = Stmt->memacc_end();
669 I != E; ++I) {
670 Value *BaseAddr = const_cast<Value *>((*I)->getBaseAddr());
Tobias Grosser6217e182012-08-03 12:50:07 +0000671 Values.insert((BaseAddr));
672
673 // FIXME: we assume that there is one and only one array to be written
674 // in a SCoP.
675 int NumWrites = 0;
676 if ((*I)->isWrite()) {
677 ++NumWrites;
678 assert(NumWrites <= 1 &&
679 "We support at most one array to be written in a SCoP.");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000680 if (const PointerType *PT =
681 dyn_cast<PointerType>(BaseAddr->getType())) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000682 Type *T = PT->getArrayElementType();
683 const ArrayType *ATy = dyn_cast<ArrayType>(T);
684 OutputBytes = getArraySizeInBytes(ATy);
685 }
686 }
687 }
688 }
689
690 return Values;
691}
692
Tobias Grossere602a072013-05-07 07:30:56 +0000693const clast_stmt *ClastStmtCodeGen::getScheduleInfo(const clast_for *F,
694 std::vector<int> &NumIters,
695 unsigned &LoopDepth,
696 unsigned &NonPLoopDepth) {
Tobias Grosser6217e182012-08-03 12:50:07 +0000697 clast_stmt *Stmt = (clast_stmt *)F;
698 const clast_for *Result;
699 bool NonParaFlag = false;
700 LoopDepth = 0;
701 NonPLoopDepth = 0;
702
703 while (Stmt) {
704 if (CLAST_STMT_IS_A(Stmt, stmt_for)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000705 const clast_for *T = (clast_for *)Stmt;
Tobias Grosser6217e182012-08-03 12:50:07 +0000706 if (isParallelFor(T)) {
707 if (!NonParaFlag) {
708 NumIters.push_back(getNumberOfIterations(T));
709 Result = T;
710 }
711 } else
712 NonParaFlag = true;
713
714 Stmt = T->body;
715 LoopDepth++;
716 continue;
717 }
718 Stmt = Stmt->next;
719 }
720
721 assert(NumIters.size() == 4 &&
722 "The loops should be tiled into 4-depth parallel loops and an "
723 "innermost non-parallel one (if exist).");
724 NonPLoopDepth = LoopDepth - NumIters.size();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000725 assert(NonPLoopDepth <= 1 &&
726 "We support only one innermost non-parallel loop currently.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000727 return (const clast_stmt *)Result->body;
728}
729
730void ClastStmtCodeGen::codegenForGPGPU(const clast_for *F) {
731 BasicBlock::iterator LoopBody;
732 SetVector<Value *> Values;
733 SetVector<Value *> IVS;
734 std::vector<int> NumIterations;
735 PTXGenerator::ValueToValueMapTy VMap;
736
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000737 assert(!GPUTriple.empty() &&
738 "Target triple should be set properly for GPGPU code generation.");
Tobias Grosser6217e182012-08-03 12:50:07 +0000739 PTXGenerator PTXGen(Builder, P, GPUTriple);
740
741 // Get original IVS and ScopStmt
742 unsigned TiledLoopDepth, NonPLoopDepth;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000743 const clast_stmt *InnerStmt =
744 getScheduleInfo(F, NumIterations, TiledLoopDepth, NonPLoopDepth);
Tobias Grosser6217e182012-08-03 12:50:07 +0000745 const clast_stmt *TmpStmt;
746 const clast_user_stmt *U;
747 const clast_for *InnerFor;
748 if (CLAST_STMT_IS_A(InnerStmt, stmt_for)) {
749 InnerFor = (const clast_for *)InnerStmt;
750 TmpStmt = InnerFor->body;
751 } else
752 TmpStmt = InnerStmt;
Tobias Grosserc14582f2013-02-05 18:01:29 +0000753 U = (const clast_user_stmt *)TmpStmt;
754 ScopStmt *Statement = (ScopStmt *)U->statement->usr;
Tobias Grosser6217e182012-08-03 12:50:07 +0000755 for (unsigned i = 0; i < Statement->getNumIterators() - NonPLoopDepth; i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000756 const Value *IV = Statement->getInductionVariableForDimension(i);
Tobias Grosser6217e182012-08-03 12:50:07 +0000757 IVS.insert(const_cast<Value *>(IV));
758 }
759
760 unsigned OutBytes;
761 Values = getGPUValues(OutBytes);
762 PTXGen.setOutputBytes(OutBytes);
763 PTXGen.startGeneration(Values, IVS, VMap, &LoopBody);
764
765 BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
766 Builder.SetInsertPoint(LoopBody);
767
768 BasicBlock *AfterBB = 0;
769 if (NonPLoopDepth) {
770 Value *LowerBound, *UpperBound, *IV, *Stride;
771 Type *IntPtrTy = getIntPtrTy();
772 LowerBound = ExpGen.codegen(InnerFor->LB, IntPtrTy);
773 UpperBound = ExpGen.codegen(InnerFor->UB, IntPtrTy);
774 Stride = Builder.getInt(APInt_from_MPZ(InnerFor->stride));
Tobias Grosser6f3d0632012-11-30 00:39:49 +0000775 IV = createLoop(LowerBound, UpperBound, Stride, Builder, P, AfterBB,
776 CmpInst::ICMP_SLE);
Tobias Grosser6217e182012-08-03 12:50:07 +0000777 const Value *OldIV_ = Statement->getInductionVariableForDimension(2);
778 Value *OldIV = const_cast<Value *>(OldIV_);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000779 VMap.insert(std::make_pair<Value *, Value *>(OldIV, IV));
Tobias Grosser6217e182012-08-03 12:50:07 +0000780 }
781
Tobias Grosser46c6abb2012-11-30 01:05:05 +0000782 updateWithValueMap(VMap);
Tobias Grossera17f6662012-11-01 05:34:35 +0000783
Tobias Grosser6217e182012-08-03 12:50:07 +0000784 BlockGenerator::generate(Builder, *Statement, ValueMap, P);
Tobias Grossera17f6662012-11-01 05:34:35 +0000785
Tobias Grosser6217e182012-08-03 12:50:07 +0000786 if (AfterBB)
787 Builder.SetInsertPoint(AfterBB->begin());
788
789 // FIXME: The replacement of the host base address with the parameter of ptx
790 // subfunction should have been done by updateWithValueMap. We use the
791 // following codes to avoid affecting other parts of Polly. This should be
792 // fixed later.
793 Function *FN = Builder.GetInsertBlock()->getParent();
794 for (unsigned j = 0; j < Values.size(); j++) {
795 Value *baseAddr = Values[j];
796 for (Function::iterator B = FN->begin(); B != FN->end(); ++B) {
797 for (BasicBlock::iterator I = B->begin(); I != B->end(); ++I)
798 I->replaceUsesOfWith(baseAddr, ValueMap[baseAddr]);
799 }
800 }
801 Builder.SetInsertPoint(AfterLoop);
802 PTXGen.setLaunchingParameters(NumIterations[0], NumIterations[1],
803 NumIterations[2], NumIterations[3]);
804 PTXGen.finishGeneration(FN);
805}
806#endif
807
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000808bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
809 const clast_stmt *stmt = f->body;
810
811 while (stmt) {
812 if (!CLAST_STMT_IS_A(stmt, stmt_user))
813 return false;
814
815 stmt = stmt->next;
816 }
817
818 return true;
819}
820
Sebastian Pop04c4ce32012-12-18 07:46:13 +0000821int ClastStmtCodeGen::getNumberOfIterations(const clast_for *For) {
822 isl_set *LoopDomain = isl_set_copy(isl_set_from_cloog_domain(For->domain));
Sebastian Pop2aa5c242012-12-18 08:56:51 +0000823 int NumberOfIterations = polly::getNumberOfIterations(LoopDomain);
824 if (NumberOfIterations == -1)
825 return -1;
Tobias Grosserb8cd4a82014-01-19 11:31:23 +0000826 return NumberOfIterations / mpz_get_si(For->stride) + 1;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000827}
828
Tobias Grosser2da263e2012-03-15 09:34:55 +0000829void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
830 DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
831 int VectorWidth = getNumberOfIterations(F);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000832
Tobias Grosser2da263e2012-03-15 09:34:55 +0000833 Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000834
Tobias Grosser2da263e2012-03-15 09:34:55 +0000835 APInt Stride = APInt_from_MPZ(F->stride);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000836 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000837 Stride = Stride.zext(LoopIVType->getBitWidth());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000838 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
839
Tobias Grosserc14582f2013-02-05 18:01:29 +0000840 std::vector<Value *> IVS(VectorWidth);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000841 IVS[0] = LB;
842
Tobias Grosser2da263e2012-03-15 09:34:55 +0000843 for (int i = 1; i < VectorWidth; i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000844 IVS[i] = Builder.CreateAdd(IVS[i - 1], StrideValue, "p_vector_iv");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000845
Tobias Grosser880c52f2013-07-29 01:58:07 +0000846 isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(F->domain));
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000847
848 // Add loop iv to symbols.
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000849 ClastVars[F->iterator] = LB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000850
Tobias Grosser2da263e2012-03-15 09:34:55 +0000851 const clast_stmt *Stmt = F->body;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000852
Tobias Grosser2da263e2012-03-15 09:34:55 +0000853 while (Stmt) {
Tobias Grosser00d898d2012-03-15 09:34:58 +0000854 codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
855 isl_set_copy(Domain));
Tobias Grosser2da263e2012-03-15 09:34:55 +0000856 Stmt = Stmt->next;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000857 }
858
859 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser00d898d2012-03-15 09:34:58 +0000860 isl_set_free(Domain);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000861 ClastVars.erase(F->iterator);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000862}
863
Tobias Grossere192b232012-05-22 08:46:07 +0000864bool ClastStmtCodeGen::isParallelFor(const clast_for *f) {
Tobias Grosser880c52f2013-07-29 01:58:07 +0000865 isl_set *Domain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
Tobias Grossere192b232012-05-22 08:46:07 +0000866 assert(Domain && "Cannot access domain of loop");
867
868 Dependences &D = P->getAnalysis<Dependences>();
869
Tobias Grosser880c52f2013-07-29 01:58:07 +0000870 return D.isParallelDimension(Domain, isl_set_n_dim(Domain));
Tobias Grossere192b232012-05-22 08:46:07 +0000871}
872
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000873void ClastStmtCodeGen::codegen(const clast_for *f) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000874 bool Vector = PollyVectorizerChoice != VECTORIZER_NONE;
Tobias Grossere192b232012-05-22 08:46:07 +0000875 if ((Vector || OpenMP) && isParallelFor(f)) {
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000876 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f)) &&
877 (getNumberOfIterations(f) <= 16)) {
Tobias Grosserce3f5372012-03-02 11:26:42 +0000878 codegenForVector(f);
879 return;
880 }
881
882 if (OpenMP && !parallelCodeGeneration) {
883 parallelCodeGeneration = true;
884 parallelLoops.push_back(f->iterator);
885 codegenForOpenMP(f);
886 parallelCodeGeneration = false;
887 return;
888 }
889 }
890
Tobias Grosser6217e182012-08-03 12:50:07 +0000891#ifdef GPU_CODEGEN
892 if (GPGPU && isParallelFor(f)) {
893 if (!parallelCodeGeneration) {
894 parallelCodeGeneration = true;
895 parallelLoops.push_back(f->iterator);
896 codegenForGPGPU(f);
897 parallelCodeGeneration = false;
898 return;
899 }
900 }
901#endif
902
Tobias Grosserce3f5372012-03-02 11:26:42 +0000903 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000904}
905
906Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
Tobias Grossere9ffea22012-03-15 09:34:48 +0000907 Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
908 Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000909 CmpInst::Predicate P;
910
911 if (eq->sign == 0)
912 P = ICmpInst::ICMP_EQ;
913 else if (eq->sign > 0)
914 P = ICmpInst::ICMP_SGE;
915 else
916 P = ICmpInst::ICMP_SLE;
917
918 return Builder.CreateICmp(P, LHS, RHS);
919}
920
921void ClastStmtCodeGen::codegen(const clast_guard *g) {
922 Function *F = Builder.GetInsertBlock()->getParent();
923 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000924
Tobias Grosserc14582f2013-02-05 18:01:29 +0000925 BasicBlock *CondBB =
926 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000927 CondBB->setName("polly.cond");
928 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
929 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000930 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000931
Tobias Grosser42aff302014-01-13 22:29:56 +0000932 DominatorTree &DT = P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Tobias Grosserd596b372012-03-15 09:34:52 +0000933 DT.addNewBlock(ThenBB, CondBB);
934 DT.changeImmediateDominator(MergeBB, CondBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000935
936 CondBB->getTerminator()->eraseFromParent();
937
938 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000939
940 Value *Predicate = codegen(&(g->eq[0]));
941
942 for (int i = 1; i < g->n; ++i) {
943 Value *TmpPredicate = codegen(&(g->eq[i]));
944 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
945 }
946
947 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
948 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000949 Builder.CreateBr(MergeBB);
950 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000951
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000952 LoopInfo &LI = P->getAnalysis<LoopInfo>();
953 Loop *L = LI.getLoopFor(CondBB);
Tobias Grosser815c6352013-09-02 16:13:00 +0000954 if (L)
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000955 L->addBasicBlockToLoop(ThenBB, LI.getBase());
Tobias Grosser3081b0f2013-05-16 06:40:24 +0000956
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000957 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +0000958
959 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000960}
961
962void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000963 if (CLAST_STMT_IS_A(stmt, stmt_root))
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000964 assert(false && "No second root statement expected");
965 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
966 codegen((const clast_assignment *)stmt);
967 else if (CLAST_STMT_IS_A(stmt, stmt_user))
968 codegen((const clast_user_stmt *)stmt);
969 else if (CLAST_STMT_IS_A(stmt, stmt_block))
970 codegen((const clast_block *)stmt);
971 else if (CLAST_STMT_IS_A(stmt, stmt_for))
972 codegen((const clast_for *)stmt);
973 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
974 codegen((const clast_guard *)stmt);
975
976 if (stmt->next)
977 codegen(stmt->next);
978}
979
980void ClastStmtCodeGen::addParameters(const CloogNames *names) {
Tobias Grosserd596b372012-03-15 09:34:52 +0000981 SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000982
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000983 int i = 0;
984 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
985 PI != PE; ++PI) {
986 assert(i < names->nb_parameters && "Not enough parameter names");
987
988 const SCEV *Param = *PI;
989 Type *Ty = Param->getType();
990
991 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
992 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
Tobias Grosser5e8ffa82012-03-23 12:20:36 +0000993 ClastVars[names->parameters[i]] = V;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000994
995 ++i;
996 }
997}
998
999void ClastStmtCodeGen::codegen(const clast_root *r) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001000 addParameters(r->names);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001001
1002 parallelCodeGeneration = false;
1003
Tobias Grosserc14582f2013-02-05 18:01:29 +00001004 const clast_stmt *stmt = (const clast_stmt *)r;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001005 if (stmt->next)
1006 codegen(stmt->next);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001007}
1008
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001009ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P)
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001010 : S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001011
Tobias Grosser75805372011-04-29 06:27:02 +00001012namespace {
1013class CodeGeneration : public ScopPass {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001014 std::vector<std::string> ParallelLoops;
Tobias Grosser75805372011-04-29 06:27:02 +00001015
Tobias Grosser1bb59b02012-12-29 23:47:38 +00001016public:
Tobias Grosser75805372011-04-29 06:27:02 +00001017 static char ID;
1018
1019 CodeGeneration() : ScopPass(ID) {}
1020
Tobias Grosser3a275d22012-05-29 09:11:54 +00001021 bool runOnScop(Scop &S) {
1022 ParallelLoops.clear();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001023
Tobias Grossere602a072013-05-07 07:30:56 +00001024 assert(!S.getRegion().isTopLevelRegion() &&
1025 "Top level regions are not supported");
Tobias Grosser0ee50f62013-04-10 06:55:31 +00001026
Tobias Grosser8edce4e2013-04-16 08:04:42 +00001027 simplifyRegion(&S, this);
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001028
Tobias Grosser3a275d22012-05-29 09:11:54 +00001029 BasicBlock *StartBlock = executeScopConditionally(S, this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001030
Tobias Grosser3a275d22012-05-29 09:11:54 +00001031 IRBuilder<> Builder(StartBlock->begin());
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001032
Tobias Grosser3a275d22012-05-29 09:11:54 +00001033 ClastStmtCodeGen CodeGen(&S, Builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001034 CloogInfo &C = getAnalysis<CloogInfo>();
1035 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001036
Tobias Grosser3a275d22012-05-29 09:11:54 +00001037 ParallelLoops.insert(ParallelLoops.begin(),
Tobias Grosser75805372011-04-29 06:27:02 +00001038 CodeGen.getParallelLoops().begin(),
1039 CodeGen.getParallelLoops().end());
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001040 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001041 }
1042
1043 virtual void printScop(raw_ostream &OS) const {
Tobias Grosser3a275d22012-05-29 09:11:54 +00001044 for (std::vector<std::string>::const_iterator PI = ParallelLoops.begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +00001045 PE = ParallelLoops.end();
1046 PI != PE; ++PI)
Tobias Grosser75805372011-04-29 06:27:02 +00001047 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1048 }
1049
1050 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1051 AU.addRequired<CloogInfo>();
1052 AU.addRequired<Dependences>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001053 AU.addRequired<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001054 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001055 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001056 AU.addRequired<ScopDetection>();
1057 AU.addRequired<ScopInfo>();
Rafael Espindolac5d16892014-02-25 19:17:57 +00001058 AU.addRequired<DataLayoutPass>();
Tobias Grosserecfe21b2013-03-20 18:03:18 +00001059 AU.addRequired<LoopInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001060
1061 AU.addPreserved<CloogInfo>();
1062 AU.addPreserved<Dependences>();
1063 AU.addPreserved<LoopInfo>();
Tobias Grosser42aff302014-01-13 22:29:56 +00001064 AU.addPreserved<DominatorTreeWrapperPass>();
Tobias Grosser75805372011-04-29 06:27:02 +00001065 AU.addPreserved<ScopDetection>();
1066 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001067
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001068 // FIXME: We do not yet add regions for the newly generated code to the
1069 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001070 AU.addPreserved<RegionInfo>();
1071 AU.addPreserved<TempScopInfo>();
1072 AU.addPreserved<ScopInfo>();
1073 AU.addPreservedID(IndependentBlocksID);
1074 }
1075};
1076}
1077
1078char CodeGeneration::ID = 1;
1079
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001080Pass *polly::createCodeGenerationPass() { return new CodeGeneration(); }
Sebastian Pope1f65542012-05-07 16:35:11 +00001081
Tobias Grosser7242ad92013-02-22 08:07:06 +00001082INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1083 "Polly - Create LLVM-IR from SCoPs", false, false);
1084INITIALIZE_PASS_DEPENDENCY(CloogInfo);
1085INITIALIZE_PASS_DEPENDENCY(Dependences);
Tobias Grosser42aff302014-01-13 22:29:56 +00001086INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001087INITIALIZE_PASS_DEPENDENCY(RegionInfo);
1088INITIALIZE_PASS_DEPENDENCY(ScalarEvolution);
1089INITIALIZE_PASS_DEPENDENCY(ScopDetection);
Rafael Espindolac5d16892014-02-25 19:17:57 +00001090INITIALIZE_PASS_DEPENDENCY(DataLayoutPass);
Tobias Grosser7242ad92013-02-22 08:07:06 +00001091INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
Tobias Grosser4d96c8d2013-03-23 01:05:07 +00001092 "Polly - Create LLVM-IR from SCoPs", false, false)
Tobias Grosser7242ad92013-02-22 08:07:06 +00001093
Sebastian Pope1f65542012-05-07 16:35:11 +00001094#endif // CLOOG_FOUND