blob: fe5ad740d95192f18290d5c8acb335f3e434e167 [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
23#define DEBUG_TYPE "polly-codegen"
24
Tobias Grosser75805372011-04-29 06:27:02 +000025#include "polly/Cloog.h"
Tobias Grosser67707b72011-10-23 20:59:40 +000026#include "polly/CodeGeneration.h"
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"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000031#include "polly/Support/GICHelper.h"
32
33#include "llvm/Module.h"
34#include "llvm/ADT/SetVector.h"
35#include "llvm/Analysis/LoopInfo.h"
36#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser75805372011-04-29 06:27:02 +000037#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/IRBuilder.h"
Tobias Grosser75805372011-04-29 06:27:02 +000040#include "llvm/Target/TargetData.h"
Tobias Grosserbda1f8f2012-02-01 14:23:29 +000041#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000042
43#define CLOOG_INT_GMP 1
44#include "cloog/cloog.h"
45#include "cloog/isl/cloog.h"
46
Raghesh Aloora71989c2011-12-28 02:48:26 +000047#include "isl/aff.h"
48
Tobias Grosser75805372011-04-29 06:27:02 +000049#include <vector>
50#include <utility>
51
52using namespace polly;
53using namespace llvm;
54
55struct isl_set;
56
57namespace polly {
58
Tobias Grosser67707b72011-10-23 20:59:40 +000059bool EnablePollyVector;
60
61static cl::opt<bool, true>
Tobias Grosser75805372011-04-29 06:27:02 +000062Vector("enable-polly-vector",
63 cl::desc("Enable polly vector code generation"), cl::Hidden,
Tobias Grosser67707b72011-10-23 20:59:40 +000064 cl::location(EnablePollyVector), cl::init(false));
Tobias Grosser75805372011-04-29 06:27:02 +000065
66static cl::opt<bool>
67OpenMP("enable-polly-openmp",
68 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
69 cl::value_desc("OpenMP code generation enabled if true"),
70 cl::init(false));
71
72static cl::opt<bool>
73AtLeastOnce("enable-polly-atLeastOnce",
74 cl::desc("Give polly the hint, that every loop is executed at least"
75 "once"), cl::Hidden,
76 cl::value_desc("OpenMP code generation enabled if true"),
77 cl::init(false));
78
79static cl::opt<bool>
80Aligned("enable-polly-aligned",
81 cl::desc("Assumed aligned memory accesses."), cl::Hidden,
82 cl::value_desc("OpenMP code generation enabled if true"),
83 cl::init(false));
84
Tobias Grosser75805372011-04-29 06:27:02 +000085typedef DenseMap<const Value*, Value*> ValueMapT;
86typedef DenseMap<const char*, Value*> CharMapT;
87typedef std::vector<ValueMapT> VectorValueMapT;
Raghesh Aloora71989c2011-12-28 02:48:26 +000088typedef struct {
89 Value *BaseAddress;
90 Value *Result;
91 IRBuilder<> *Builder;
92}IslPwAffUserInfo;
Tobias Grosser75805372011-04-29 06:27:02 +000093
94// Create a new loop.
95//
96// @param Builder The builder used to create the loop. It also defines the
97// place where to create the loop.
98// @param UB The upper bound of the loop iv.
99// @param Stride The number by which the loop iv is incremented after every
100// iteration.
101static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride,
102 PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV,
103 DominatorTree *DT) {
104 Function *F = Builder->GetInsertBlock()->getParent();
105 LLVMContext &Context = F->getContext();
106
107 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
108 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
109 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
110 AfterBB = BasicBlock::Create(Context, "polly.after_loop", F);
111
112 Builder->CreateBr(HeaderBB);
113 DT->addNewBlock(HeaderBB, PreheaderBB);
114
115 Builder->SetInsertPoint(BodyBB);
116
117 Builder->SetInsertPoint(HeaderBB);
118
119 // Use the type of upper and lower bound.
120 assert(LB->getType() == UB->getType()
121 && "Different types for upper and lower bound.");
122
Tobias Grosser55927aa2011-07-18 09:53:32 +0000123 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000124 assert(LoopIVType && "UB is not integer?");
125
126 // IV
127 IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
128 IV->addIncoming(LB, PreheaderBB);
129
130 // IV increment.
131 Value *StrideValue = ConstantInt::get(LoopIVType,
132 Stride.zext(LoopIVType->getBitWidth()));
133 IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv");
134
135 // Exit condition.
136 if (AtLeastOnce) { // At least on iteration.
137 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
138 Value *CMP = Builder->CreateICmpEQ(IV, UB);
139 Builder->CreateCondBr(CMP, AfterBB, BodyBB);
140 } else { // Maybe not executed at all.
141 Value *CMP = Builder->CreateICmpSLE(IV, UB);
142 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
143 }
144 DT->addNewBlock(BodyBB, HeaderBB);
145 DT->addNewBlock(AfterBB, HeaderBB);
146
147 Builder->SetInsertPoint(BodyBB);
148}
149
150class BlockGenerator {
151 IRBuilder<> &Builder;
152 ValueMapT &VMap;
153 VectorValueMapT &ValueMaps;
154 Scop &S;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000155 ScopStmt &Statement;
156 isl_set *ScatteringDomain;
Tobias Grosser75805372011-04-29 06:27:02 +0000157
158public:
159 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000160 ScopStmt &Stmt, __isl_keep isl_set *domain);
Tobias Grosser75805372011-04-29 06:27:02 +0000161
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000162 const Region &getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000163
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000164 Value *makeVectorOperand(Value *operand, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000165
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000166 Value *getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000167 ValueMapT *VectorMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000168
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000169 Type *getVectorPtrTy(const Value *V, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000170
171 /// @brief Load a vector from a set of adjacent scalars
172 ///
173 /// In case a set of scalars is known to be next to each other in memory,
174 /// create a vector load that loads those scalars
175 ///
176 /// %vector_ptr= bitcast double* %p to <4 x double>*
177 /// %vec_full = load <4 x double>* %vector_ptr
178 ///
179 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000180 int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000181
182 /// @brief Load a vector initialized from a single scalar in memory
183 ///
184 /// In case all elements of a vector are initialized to the same
185 /// scalar value, this value is loaded and shuffeled into all elements
186 /// of the vector.
187 ///
188 /// %splat_one = load <1 x double>* %p
189 /// %splat = shufflevector <1 x double> %splat_one, <1 x
190 /// double> %splat_one, <4 x i32> zeroinitializer
191 ///
192 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000193 int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000194
195 /// @Load a vector from scalars distributed in memory
196 ///
197 /// In case some scalars a distributed randomly in memory. Create a vector
198 /// by loading each scalar and by inserting one after the other into the
199 /// vector.
200 ///
201 /// %scalar_1= load double* %p_1
202 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
203 /// %scalar 2 = load double* %p_2
204 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
205 ///
206 Value *generateUnknownStrideLoad(const LoadInst *load,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000207 VectorValueMapT &scalarMaps, int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000208
Raghesh Aloora71989c2011-12-28 02:48:26 +0000209 static Value* islAffToValue(__isl_take isl_aff *Aff,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000210 IslPwAffUserInfo *UserInfo);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000211
212 static int mergeIslAffValues(__isl_take isl_set *Set,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000213 __isl_take isl_aff *Aff, void *User);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000214
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000215 Value* islPwAffToValue(__isl_take isl_pw_aff *PwAff, Value *BaseAddress);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000216
Raghesh Aloor129e8672011-08-15 02:33:39 +0000217 /// @brief Get the memory access offset to be added to the base address
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000218 std::vector <Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000219 Value *BaseAddress);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000220
Raghesh Aloor62b13122011-08-03 17:02:50 +0000221 /// @brief Get the new operand address according to the changed access in
222 /// JSCOP file.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000223 Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
224 Value *BaseAddress, const Value *OldOperand,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000225 ValueMapT &BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000226
227 /// @brief Generate the operand address
228 Value *generateLocationAccessed(const Instruction *Inst,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000229 const Value *Pointer, ValueMapT &BBMap );
Raghesh Aloor129e8672011-08-15 02:33:39 +0000230
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000231 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000232
233 /// @brief Load a value (or several values as a vector) from memory.
234 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000235 VectorValueMapT &scalarMaps, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000236
Tobias Grosserc9215152011-09-04 11:45:52 +0000237 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
238 ValueMapT &VectorMap, int VectorDimension,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000239 int VectorWidth);
Tobias Grosserc9215152011-09-04 11:45:52 +0000240
Tobias Grosser09c57102011-09-04 11:45:29 +0000241 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000242 ValueMapT &vectorMap, int vectorDimension, int vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000243
244 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000245 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000246 int vectorDimension, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000247
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000248 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000249
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000250 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000251
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000252 int getVectorSize();
Tobias Grosser75805372011-04-29 06:27:02 +0000253
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000254 bool isVectorBlock();
Tobias Grosser75805372011-04-29 06:27:02 +0000255
Tobias Grosser7551c302011-09-04 11:45:41 +0000256 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
257 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000258 int vectorDimension, int vectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000259
Tobias Grosser75805372011-04-29 06:27:02 +0000260 // Insert a copy of a basic block in the newly generated code.
261 //
262 // @param Builder The builder used to insert the code. It also specifies
263 // where to insert the code.
264 // @param BB The basic block to copy
265 // @param VMap A map returning for any old value its new equivalent. This
266 // is used to update the operands of the statements.
267 // For new statements a relation old->new is inserted in this
268 // map.
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000269 void copyBB(BasicBlock *BB, DominatorTree *DT);
Tobias Grosser75805372011-04-29 06:27:02 +0000270};
271
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000272BlockGenerator::BlockGenerator(IRBuilder<> &B, ValueMapT &vmap,
273 VectorValueMapT &vmaps, ScopStmt &Stmt,
274 __isl_keep isl_set *domain)
275 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
276 Statement(Stmt), ScatteringDomain(domain) {}
277
278const Region &BlockGenerator::getRegion() {
279 return S.getRegion();
280}
281
282Value *BlockGenerator::makeVectorOperand(Value *Operand, int VectorWidth) {
283 if (Operand->getType()->isVectorTy())
284 return Operand;
285
286 VectorType *VectorType = VectorType::get(Operand->getType(), VectorWidth);
287 Value *Vector = UndefValue::get(VectorType);
288 Vector = Builder.CreateInsertElement(Vector, Operand, Builder.getInt32(0));
289
290 std::vector<Constant*> Splat;
291
292 for (int i = 0; i < VectorWidth; i++)
293 Splat.push_back (Builder.getInt32(0));
294
295 Constant *SplatVector = ConstantVector::get(Splat);
296
297 return Builder.CreateShuffleVector(Vector, Vector, SplatVector);
298}
299
300Value *BlockGenerator::getOperand(const Value *OldOperand, ValueMapT &BBMap,
301 ValueMapT *VectorMap) {
302 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
303
304 if (!OpInst)
305 return const_cast<Value*>(OldOperand);
306
307 if (VectorMap && VectorMap->count(OldOperand))
308 return (*VectorMap)[OldOperand];
309
310 // IVS and Parameters.
311 if (VMap.count(OldOperand)) {
312 Value *NewOperand = VMap[OldOperand];
313
314 // Insert a cast if types are different
315 if (OldOperand->getType()->getScalarSizeInBits()
316 < NewOperand->getType()->getScalarSizeInBits())
317 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
318 OldOperand->getType());
319
320 return NewOperand;
321 }
322
323 // Instructions calculated in the current BB.
324 if (BBMap.count(OldOperand)) {
325 return BBMap[OldOperand];
326 }
327
328 // Ignore instructions that are referencing ops in the old BB. These
329 // instructions are unused. They where replace by new ones during
330 // createIndependentBlocks().
331 if (getRegion().contains(OpInst->getParent()))
332 return NULL;
333
334 return const_cast<Value*>(OldOperand);
335}
336
337Type *BlockGenerator::getVectorPtrTy(const Value *Val, int VectorWidth) {
338 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
339 assert(PointerTy && "PointerType expected");
340
341 Type *ScalarType = PointerTy->getElementType();
342 VectorType *VectorType = VectorType::get(ScalarType, VectorWidth);
343
344 return PointerType::getUnqual(VectorType);
345}
346
347Value *BlockGenerator::generateStrideOneLoad(const LoadInst *Load,
348 ValueMapT &BBMap, int Size) {
349 const Value *Pointer = Load->getPointerOperand();
350 Type *VectorPtrType = getVectorPtrTy(Pointer, Size);
351 Value *NewPointer = getOperand(Pointer, BBMap);
352 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
353 "vector_ptr");
354 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
355 Load->getName() + "_p_vec_full");
356 if (!Aligned)
357 VecLoad->setAlignment(8);
358
359 return VecLoad;
360}
361
362Value *BlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
363 ValueMapT &BBMap, int Size) {
364 const Value *Pointer = Load->getPointerOperand();
365 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
366 Value *NewPointer = getOperand(Pointer, BBMap);
367 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
368 Load->getName() + "_p_vec_p");
369 LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
370 Load->getName() + "_p_splat_one");
371
372 if (!Aligned)
373 ScalarLoad->setAlignment(8);
374
Tobias Grossere5b423252012-01-24 16:42:25 +0000375 Constant *SplatVector =
376 Constant::getNullValue(VectorType::get(Builder.getInt32Ty(), Size));
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000377
378 Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
379 SplatVector,
380 Load->getName()
381 + "_p_splat");
382 return VectorLoad;
383}
384
385Value *BlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
386 VectorValueMapT &ScalarMaps,
387 int Size) {
388 const Value *Pointer = Load->getPointerOperand();
389 VectorType *VectorType = VectorType::get(
390 dyn_cast<PointerType>(Pointer->getType())->getElementType(), Size);
391
392 Value *Vector = UndefValue::get(VectorType);
393
394 for (int i = 0; i < Size; i++) {
395 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
396 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
397 Load->getName() + "_p_scalar_");
398 Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
399 Builder.getInt32(i),
400 Load->getName() + "_p_vec_");
401 }
402
403 return Vector;
404}
405
406Value *BlockGenerator::islAffToValue(__isl_take isl_aff *Aff,
407 IslPwAffUserInfo *UserInfo) {
408 assert(isl_aff_is_cst(Aff) && "Only constant access functions supported");
409
410 IRBuilder<> *Builder = UserInfo->Builder;
411
412 isl_int OffsetIsl;
413 mpz_t OffsetMPZ;
414
415 isl_int_init(OffsetIsl);
416 mpz_init(OffsetMPZ);
417 isl_aff_get_constant(Aff, &OffsetIsl);
418 isl_int_get_gmp(OffsetIsl, OffsetMPZ);
419
420 Value *OffsetValue = NULL;
421 APInt Offset = APInt_from_MPZ(OffsetMPZ);
422 OffsetValue = ConstantInt::get(Builder->getContext(), Offset);
423
424 mpz_clear(OffsetMPZ);
425 isl_int_clear(OffsetIsl);
426 isl_aff_free(Aff);
427
428 return OffsetValue;
429}
430
431int BlockGenerator::mergeIslAffValues(__isl_take isl_set *Set,
432 __isl_take isl_aff *Aff, void *User) {
433 IslPwAffUserInfo *UserInfo = (IslPwAffUserInfo *)User;
434
435 assert((UserInfo->Result == NULL) && "Result is already set."
436 "Currently only single isl_aff is supported");
437 assert(isl_set_plain_is_universe(Set)
438 && "Code generation failed because the set is not universe");
439
440 UserInfo->Result = islAffToValue(Aff, UserInfo);
441
442 isl_set_free(Set);
443 return 0;
444}
445
446Value *BlockGenerator::islPwAffToValue(__isl_take isl_pw_aff *PwAff,
447 Value *BaseAddress) {
448 IslPwAffUserInfo UserInfo;
449 UserInfo.BaseAddress = BaseAddress;
450 UserInfo.Result = NULL;
451 UserInfo.Builder = &Builder;
452 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &UserInfo);
453 assert(UserInfo.Result && "Code generation for isl_pw_aff failed");
454
455 isl_pw_aff_free(PwAff);
456 return UserInfo.Result;
457}
458
459std::vector <Value*> BlockGenerator::getMemoryAccessIndex(
460 __isl_keep isl_map *AccessRelation, Value *BaseAddress) {
461 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
462 && "Only single dimensional access functions supported");
463
464 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
465 Value *OffsetValue = islPwAffToValue(PwAff, BaseAddress);
466
467 PointerType *BaseAddressType = dyn_cast<PointerType>(
468 BaseAddress->getType());
469 Type *ArrayTy = BaseAddressType->getElementType();
470 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
471 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
472
473 std::vector<Value*> IndexArray;
474 Value *NullValue = Constant::getNullValue(ArrayElementType);
475 IndexArray.push_back(NullValue);
476 IndexArray.push_back(OffsetValue);
477 return IndexArray;
478}
479
480Value *BlockGenerator::getNewAccessOperand(
481 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, const Value
482 *OldOperand, ValueMapT &BBMap) {
483 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
484 BaseAddress);
485 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
486 "p_newarrayidx_");
487 return NewOperand;
488}
489
490Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
491 const Value *Pointer,
492 ValueMapT &BBMap ) {
493 MemoryAccess &Access = Statement.getAccessFor(Inst);
494 isl_map *CurrentAccessRelation = Access.getAccessRelation();
495 isl_map *NewAccessRelation = Access.getNewAccessRelation();
496
497 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
498 && "Current and new access function use different spaces");
499
500 Value *NewPointer;
501
502 if (!NewAccessRelation) {
503 NewPointer = getOperand(Pointer, BBMap);
504 } else {
505 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
506 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
507 BBMap);
508 }
509
510 isl_map_free(CurrentAccessRelation);
511 isl_map_free(NewAccessRelation);
512 return NewPointer;
513}
514
515Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
516 ValueMapT &BBMap) {
517 const Value *Pointer = Load->getPointerOperand();
518 const Instruction *Inst = dyn_cast<Instruction>(Load);
519 Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap);
520 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
521 Load->getName() + "_p_scalar_");
522 return ScalarLoad;
523}
524
525void BlockGenerator::generateLoad(const LoadInst *Load, ValueMapT &VectorMap,
526 VectorValueMapT &ScalarMaps,
527 int VectorWidth) {
528 if (ScalarMaps.size() == 1) {
529 ScalarMaps[0][Load] = generateScalarLoad(Load, ScalarMaps[0]);
530 return;
531 }
532
533 Value *NewLoad;
534
535 MemoryAccess &Access = Statement.getAccessFor(Load);
536
537 assert(ScatteringDomain && "No scattering domain available");
538
539 if (Access.isStrideZero(isl_set_copy(ScatteringDomain)))
540 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0], VectorWidth);
541 else if (Access.isStrideOne(isl_set_copy(ScatteringDomain)))
542 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0], VectorWidth);
543 else
544 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps, VectorWidth);
545
546 VectorMap[Load] = NewLoad;
547}
548
549void BlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
550 ValueMapT &BBMap, ValueMapT &VectorMap,
551 int VectorDimension, int VectorWidth) {
552 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
553 NewOperand = makeVectorOperand(NewOperand, VectorWidth);
554
555 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
556
557 const CastInst *Cast = dyn_cast<CastInst>(Inst);
558 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
559 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
560}
561
562void BlockGenerator::copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
563 ValueMapT &VectorMap, int VectorDimension,
564 int VectorWidth) {
565 Value *OpZero = Inst->getOperand(0);
566 Value *OpOne = Inst->getOperand(1);
567
568 Value *NewOpZero, *NewOpOne;
569 NewOpZero = getOperand(OpZero, BBMap, &VectorMap);
570 NewOpOne = getOperand(OpOne, BBMap, &VectorMap);
571
572 NewOpZero = makeVectorOperand(NewOpZero, VectorWidth);
573 NewOpOne = makeVectorOperand(NewOpOne, VectorWidth);
574
575 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
576 NewOpOne,
577 Inst->getName() + "p_vec");
578 VectorMap[Inst] = NewInst;
579}
580
581void BlockGenerator::copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
582 ValueMapT &VectorMap,
583 VectorValueMapT &ScalarMaps,
584 int VectorDimension, int VectorWidth) {
585 // In vector mode we only generate a store for the first dimension.
586 if (VectorDimension > 0)
587 return;
588
589 MemoryAccess &Access = Statement.getAccessFor(Store);
590
591 assert(ScatteringDomain && "No scattering domain available");
592
593 const Value *Pointer = Store->getPointerOperand();
594 Value *Vector = getOperand(Store->getValueOperand(), BBMap, &VectorMap);
595
596 if (Access.isStrideOne(isl_set_copy(ScatteringDomain))) {
597 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
598 Value *NewPointer = getOperand(Pointer, BBMap, &VectorMap);
599
600 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
601 "vector_ptr");
602 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
603
604 if (!Aligned)
605 Store->setAlignment(8);
606 } else {
607 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
608 Value *Scalar = Builder.CreateExtractElement(Vector,
609 Builder.getInt32(i));
610 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
611 Builder.CreateStore(Scalar, NewPointer);
612 }
613 }
614}
615
616void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
617 Instruction *NewInst = Inst->clone();
618
619 // Replace old operands with the new ones.
620 for (Instruction::const_op_iterator OI = Inst->op_begin(),
621 OE = Inst->op_end(); OI != OE; ++OI) {
622 Value *OldOperand = *OI;
623 Value *NewOperand = getOperand(OldOperand, BBMap);
624
625 if (!NewOperand) {
626 assert(!isa<StoreInst>(NewInst)
627 && "Store instructions are always needed!");
628 delete NewInst;
629 return;
630 }
631
632 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
633 }
634
635 Builder.Insert(NewInst);
636 BBMap[Inst] = NewInst;
637
638 if (!NewInst->getType()->isVoidTy())
639 NewInst->setName("p_" + Inst->getName());
640}
641
642bool BlockGenerator::hasVectorOperands(const Instruction *Inst,
643 ValueMapT &VectorMap) {
644 for (Instruction::const_op_iterator OI = Inst->op_begin(),
645 OE = Inst->op_end(); OI != OE; ++OI)
646 if (VectorMap.count(*OI))
647 return true;
648 return false;
649}
650
651int BlockGenerator::getVectorSize() {
652 return ValueMaps.size();
653}
654
655bool BlockGenerator::isVectorBlock() {
656 return getVectorSize() > 1;
657}
658
659void BlockGenerator::copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
660 ValueMapT &VectorMap,
661 VectorValueMapT &ScalarMaps,
662 int VectorDimension, int VectorWidth) {
663 // Terminator instructions control the control flow. They are explicitally
664 // expressed in the clast and do not need to be copied.
665 if (Inst->isTerminator())
666 return;
667
668 if (isVectorBlock()) {
669 // If this instruction is already in the vectorMap, a vector instruction
670 // was already issued, that calculates the values of all dimensions. No
671 // need to create any more instructions.
672 if (VectorMap.count(Inst))
673 return;
674 }
675
676 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
677 generateLoad(Load, VectorMap, ScalarMaps, VectorWidth);
678 return;
679 }
680
681 if (isVectorBlock() && hasVectorOperands(Inst, VectorMap)) {
682 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
683 copyUnaryInst(UnaryInst, BBMap, VectorMap, VectorDimension, VectorWidth);
684 else if
685 (const BinaryOperator *BinaryInst = dyn_cast<BinaryOperator>(Inst))
686 copyBinInst(BinaryInst, BBMap, VectorMap, VectorDimension, VectorWidth);
687 else if (const StoreInst *Store = dyn_cast<StoreInst>(Inst))
688 copyVectorStore(Store, BBMap, VectorMap, ScalarMaps, VectorDimension,
689 VectorWidth);
690 else
691 llvm_unreachable("Cannot issue vector code for this instruction");
692
693 return;
694 }
695
696 copyInstScalar(Inst, BBMap);
697}
698
699void BlockGenerator::copyBB(BasicBlock *BB, DominatorTree *DT) {
700 Function *F = Builder.GetInsertBlock()->getParent();
701 LLVMContext &Context = F->getContext();
702 BasicBlock *CopyBB = BasicBlock::Create(Context,
703 "polly." + BB->getName() + ".stmt",
704 F);
705 Builder.CreateBr(CopyBB);
706 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
707 Builder.SetInsertPoint(CopyBB);
708
709 // Create two maps that store the mapping from the original instructions of
710 // the old basic block to their copies in the new basic block. Those maps
711 // are basic block local.
712 //
713 // As vector code generation is supported there is one map for scalar values
714 // and one for vector values.
715 //
716 // In case we just do scalar code generation, the vectorMap is not used and
717 // the scalarMap has just one dimension, which contains the mapping.
718 //
719 // In case vector code generation is done, an instruction may either appear
720 // in the vector map once (as it is calculating >vectorwidth< values at a
721 // time. Or (if the values are calculated using scalar operations), it
722 // appears once in every dimension of the scalarMap.
723 VectorValueMapT ScalarBlockMap(getVectorSize());
724 ValueMapT VectorBlockMap;
725
726 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
727 II != IE; ++II)
728 for (int i = 0; i < getVectorSize(); i++) {
729 if (isVectorBlock())
730 VMap = ValueMaps[i];
731
732 copyInstruction(II, ScalarBlockMap[i], VectorBlockMap,
733 ScalarBlockMap, i, getVectorSize());
734 }
735}
736
Tobias Grosser75805372011-04-29 06:27:02 +0000737/// Class to generate LLVM-IR that calculates the value of a clast_expr.
738class ClastExpCodeGen {
739 IRBuilder<> &Builder;
740 const CharMapT *IVS;
741
Tobias Grosserbb137e32012-01-24 16:42:28 +0000742 Value *codegen(const clast_name *e, Type *Ty);
743 Value *codegen(const clast_term *e, Type *Ty);
744 Value *codegen(const clast_binary *e, Type *Ty);
745 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000746public:
747
748 // A generator for clast expressions.
749 //
750 // @param B The IRBuilder that defines where the code to calculate the
751 // clast expressions should be inserted.
752 // @param IVMAP A Map that translates strings describing the induction
753 // variables to the Values* that represent these variables
754 // on the LLVM side.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000755 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000756
757 // Generates code to calculate a given clast expression.
758 //
759 // @param e The expression to calculate.
760 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000761 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000762
763 // @brief Reset the CharMap.
764 //
765 // This function is called to reset the CharMap to new one, while generating
766 // OpenMP code.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000767 void setIVS(CharMapT *IVSNew);
768};
769
770Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
771 CharMapT::const_iterator I = IVS->find(e->name);
772
773 assert(I != IVS->end() && "Clast name not found");
774
775 return Builder.CreateSExtOrBitCast(I->second, Ty);
776}
777
778Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
779 APInt a = APInt_from_MPZ(e->val);
780
781 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
782 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
783
784 if (!e->var)
785 return ConstOne;
786
787 Value *var = codegen(e->var, Ty);
788 return Builder.CreateMul(ConstOne, var);
789}
790
791Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
792 Value *LHS = codegen(e->LHS, Ty);
793
794 APInt RHS_AP = APInt_from_MPZ(e->RHS);
795
796 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
797 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
798
799 switch (e->type) {
800 case clast_bin_mod:
801 return Builder.CreateSRem(LHS, RHS);
802 case clast_bin_fdiv:
803 {
804 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
805 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
806 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
807 One = Builder.CreateZExtOrBitCast(One, Ty);
808 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
809 Value *Sum1 = Builder.CreateSub(LHS, RHS);
810 Value *Sum2 = Builder.CreateAdd(Sum1, One);
811 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
812 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
813 return Builder.CreateSDiv(Dividend, RHS);
814 }
815 case clast_bin_cdiv:
816 {
817 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
818 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
819 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
820 One = Builder.CreateZExtOrBitCast(One, Ty);
821 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
822 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
823 Value *Sum2 = Builder.CreateSub(Sum1, One);
824 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
825 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
826 return Builder.CreateSDiv(Dividend, RHS);
827 }
828 case clast_bin_div:
829 return Builder.CreateSDiv(LHS, RHS);
830 };
831
832 llvm_unreachable("Unknown clast binary expression type");
833}
834
835Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
836 assert(( r->type == clast_red_min
837 || r->type == clast_red_max
838 || r->type == clast_red_sum)
839 && "Clast reduction type not supported");
840 Value *old = codegen(r->elts[0], Ty);
841
842 for (int i=1; i < r->n; ++i) {
843 Value *exprValue = codegen(r->elts[i], Ty);
844
845 switch (r->type) {
846 case clast_red_min:
847 {
848 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
849 old = Builder.CreateSelect(cmp, old, exprValue);
850 break;
851 }
852 case clast_red_max:
853 {
854 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
855 old = Builder.CreateSelect(cmp, old, exprValue);
856 break;
857 }
858 case clast_red_sum:
859 old = Builder.CreateAdd(old, exprValue);
860 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000861 }
Tobias Grosser75805372011-04-29 06:27:02 +0000862 }
863
Tobias Grosserbb137e32012-01-24 16:42:28 +0000864 return old;
865}
866
867ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap)
868 : Builder(B), IVS(IVMap) {}
869
870Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
871 switch(e->type) {
872 case clast_expr_name:
873 return codegen((const clast_name *)e, Ty);
874 case clast_expr_term:
875 return codegen((const clast_term *)e, Ty);
876 case clast_expr_bin:
877 return codegen((const clast_binary *)e, Ty);
878 case clast_expr_red:
879 return codegen((const clast_reduction *)e, Ty);
880 }
881
882 llvm_unreachable("Unknown clast expression!");
883}
884
885void ClastExpCodeGen::setIVS(CharMapT *IVSNew) {
886 IVS = IVSNew;
887}
Tobias Grosser75805372011-04-29 06:27:02 +0000888
889class ClastStmtCodeGen {
890 // The Scop we code generate.
891 Scop *S;
892 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000893 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000894 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000895 Dependences *DP;
896 TargetData *TD;
897
898 // The Builder specifies the current location to code generate at.
899 IRBuilder<> &Builder;
900
901 // Map the Values from the old code to their counterparts in the new code.
902 ValueMapT ValueMap;
903
904 // clastVars maps from the textual representation of a clast variable to its
905 // current *Value. clast variables are scheduling variables, original
906 // induction variables or parameters. They are used either in loop bounds or
907 // to define the statement instance that is executed.
908 //
909 // for (s = 0; s < n + 3; ++i)
910 // for (t = s; t < m; ++j)
911 // Stmt(i = s + 3 * m, j = t);
912 //
913 // {s,t,i,j,n,m} is the set of clast variables in this clast.
914 CharMapT *clastVars;
915
916 // Codegenerator for clast expressions.
917 ClastExpCodeGen ExpGen;
918
919 // Do we currently generate parallel code?
920 bool parallelCodeGeneration;
921
922 std::vector<std::string> parallelLoops;
923
924public:
925
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000926 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +0000927
928 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000929 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000930
931 void codegen(const clast_assignment *a, ScopStmt *Statement,
932 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000933 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000934
935 void codegenSubstitutions(const clast_stmt *Assignment,
936 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000937 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000938
939 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000940 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000941
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000942 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000943
944 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000945 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000946 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000947
Tobias Grosser75805372011-04-29 06:27:02 +0000948 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000949 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +0000950
951 /// @brief Add values to the OpenMP structure.
952 ///
953 /// Create the subfunction structure and add the values from the list.
954 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000955 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000956
957 /// @brief Create OpenMP structure values.
958 ///
959 /// Create a list of values that has to be stored into the subfuncition
960 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000961 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000962
963 /// @brief Extract the values from the subfunction parameter.
964 ///
965 /// Extract the values from the subfunction parameter and update the clast
966 /// variables to point to the new values.
967 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
968 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000969 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +0000970
971 /// @brief Add body to the subfunction.
972 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
973 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000974 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +0000975
976 /// @brief Create an OpenMP parallel for loop.
977 ///
978 /// This loop reflects a loop as if it would have been created by an OpenMP
979 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000980 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000981
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000982 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000983
984 /// @brief Get the number of loop iterations for this loop.
985 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000986 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000987
988 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000989 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000990
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000991 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000992
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000993 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000994
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000995 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +0000996
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000997 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +0000998
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000999 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +00001000
1001 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001002 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001003
1004 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001005 ScopDetection *sd, Dependences *dp, TargetData *td,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001006 IRBuilder<> &B);
Tobias Grosser75805372011-04-29 06:27:02 +00001007};
1008}
1009
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001010const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1011 return parallelLoops;
1012}
1013
1014void ClastStmtCodeGen::codegen(const clast_assignment *a) {
1015 Value *V= ExpGen.codegen(a->RHS, TD->getIntPtrType(Builder.getContext()));
1016 (*clastVars)[a->LHS] = V;
1017}
1018
1019void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1020 unsigned Dimension, int vectorDim,
1021 std::vector<ValueMapT> *VectorVMap) {
1022 Value *RHS = ExpGen.codegen(a->RHS,
1023 TD->getIntPtrType(Builder.getContext()));
1024
1025 assert(!a->LHS && "Statement assignments do not have left hand side");
1026 const PHINode *PN;
1027 PN = Statement->getInductionVariableForDimension(Dimension);
1028 const Value *V = PN;
1029
1030 if (VectorVMap)
1031 (*VectorVMap)[vectorDim][V] = RHS;
1032
1033 ValueMap[V] = RHS;
1034}
1035
1036void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1037 ScopStmt *Statement, int vectorDim,
1038 std::vector<ValueMapT> *VectorVMap) {
1039 int Dimension = 0;
1040
1041 while (Assignment) {
1042 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1043 && "Substitions are expected to be assignments");
1044 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1045 vectorDim, VectorVMap);
1046 Assignment = Assignment->next;
1047 Dimension++;
1048 }
1049}
1050
1051void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1052 std::vector<Value*> *IVS , const char *iterator,
1053 isl_set *scatteringDomain) {
1054 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
1055 BasicBlock *BB = Statement->getBasicBlock();
1056
1057 if (u->substitutions)
1058 codegenSubstitutions(u->substitutions, Statement);
1059
1060 int vectorDimensions = IVS ? IVS->size() : 1;
1061
1062 VectorValueMapT VectorValueMap(vectorDimensions);
1063
1064 if (IVS) {
1065 assert (u->substitutions && "Substitutions expected!");
1066 int i = 0;
1067 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1068 II != IE; ++II) {
1069 (*clastVars)[iterator] = *II;
1070 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
1071 i++;
1072 }
1073 }
1074
1075 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
1076 scatteringDomain);
1077 Generator.copyBB(BB, DT);
1078}
1079
1080void ClastStmtCodeGen::codegen(const clast_block *b) {
1081 if (b->body)
1082 codegen(b->body);
1083}
1084
1085void ClastStmtCodeGen::codegenForSequential(const clast_for *f,
1086 Value *LowerBound,
1087 Value *UpperBound) {
1088 APInt Stride;
1089 PHINode *IV;
1090 Value *IncrementedIV;
1091 BasicBlock *AfterBB, *HeaderBB, *LastBodyBB;
1092 Type *IntPtrTy;
1093
1094 Stride = APInt_from_MPZ(f->stride);
1095 IntPtrTy = TD->getIntPtrType(Builder.getContext());
1096
1097 // The value of lowerbound and upperbound will be supplied, if this
1098 // function is called while generating OpenMP code. Otherwise get
1099 // the values.
1100 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1101
1102 if (LowerBound == 0) {
1103 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1104 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1105 }
1106
1107 createLoop(&Builder, LowerBound, UpperBound, Stride, IV, AfterBB,
1108 IncrementedIV, DT);
1109
1110 // Add loop iv to symbols.
1111 (*clastVars)[f->iterator] = IV;
1112
1113 if (f->body)
1114 codegen(f->body);
1115
1116 // Loop is finished, so remove its iv from the live symbols.
1117 clastVars->erase(f->iterator);
1118
1119 HeaderBB = *pred_begin(AfterBB);
1120 LastBodyBB = Builder.GetInsertBlock();
1121 Builder.CreateBr(HeaderBB);
1122 IV->addIncoming(IncrementedIV, LastBodyBB);
1123 Builder.SetInsertPoint(AfterBB);
1124}
1125
1126Function *ClastStmtCodeGen::addOpenMPSubfunction(Module *M) {
1127 Function *F = Builder.GetInsertBlock()->getParent();
1128 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
1129 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
1130 Function *FN = Function::Create(FT, Function::InternalLinkage,
1131 F->getName() + ".omp_subfn", M);
1132 // Do not run any polly pass on the new function.
1133 SD->markFunctionAsInvalid(FN);
1134
1135 Function::arg_iterator AI = FN->arg_begin();
1136 AI->setName("omp.userContext");
1137
1138 return FN;
1139}
1140
1141Value *ClastStmtCodeGen::addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1142 Function *SubFunction) {
1143 std::vector<Type*> structMembers;
1144
1145 // Create the structure.
1146 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1147 structMembers.push_back(OMPDataVals[i]->getType());
1148
1149 StructType *structTy = StructType::get(Builder.getContext(),
1150 structMembers);
1151 // Store the values into the structure.
1152 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1153 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1154 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1155 Builder.CreateStore(OMPDataVals[i], storeAddr);
1156 }
1157
1158 return structData;
1159}
1160
1161SetVector<Value*> ClastStmtCodeGen::createOpenMPStructValues() {
1162 SetVector<Value*> OMPDataVals;
1163
1164 // Push the clast variables available in the clastVars.
1165 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1166 I != E; I++)
1167 OMPDataVals.insert(I->second);
1168
1169 // Push the base addresses of memory references.
1170 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1171 ScopStmt *Stmt = *SI;
1172 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1173 E = Stmt->memacc_end(); I != E; ++I) {
1174 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1175 OMPDataVals.insert((BaseAddr));
1176 }
1177 }
1178
1179 return OMPDataVals;
1180}
1181
1182void ClastStmtCodeGen::extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1183 SetVector<Value*> OMPDataVals, Value *userContext) {
1184 // Extract the clast variables.
1185 unsigned i = 0;
1186 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1187 I != E; I++) {
1188 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1189 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1190 i++;
1191 }
1192
1193 // Extract the base addresses of memory references.
1194 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1195 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1196 Value *baseAddr = OMPDataVals[j];
1197 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1198 }
1199}
1200
1201void ClastStmtCodeGen::addOpenMPSubfunctionBody(Function *FN,
1202 const clast_for *f,
1203 Value *structData,
1204 SetVector<Value*> OMPDataVals) {
1205 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1206 LLVMContext &Context = FN->getContext();
1207 IntegerType *intPtrTy = TD->getIntPtrType(Context);
1208
1209 // Store the previous basic block.
1210 BasicBlock *PrevBB = Builder.GetInsertBlock();
1211
1212 // Create basic blocks.
1213 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1214 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1215 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1216 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1217 FN);
1218
1219 DT->addNewBlock(HeaderBB, PrevBB);
1220 DT->addNewBlock(ExitBB, HeaderBB);
1221 DT->addNewBlock(checkNextBB, HeaderBB);
1222 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1223
1224 // Fill up basic block HeaderBB.
1225 Builder.SetInsertPoint(HeaderBB);
1226 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1227 "omp.lowerBoundPtr");
1228 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1229 "omp.upperBoundPtr");
1230 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1231 structData->getType(),
1232 "omp.userContext");
1233
1234 CharMapT clastVarsOMP;
1235 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1236
1237 Builder.CreateBr(checkNextBB);
1238
1239 // Add code to check if another set of iterations will be executed.
1240 Builder.SetInsertPoint(checkNextBB);
1241 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1242 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1243 lowerBoundPtr, upperBoundPtr);
1244 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1245 "omp.hasNextScheduleBlock");
1246 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1247
1248 // Add code to to load the iv bounds for this set of iterations.
1249 Builder.SetInsertPoint(loadIVBoundsBB);
1250 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1251 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1252
1253 // Subtract one as the upper bound provided by openmp is a < comparison
1254 // whereas the codegenForSequential function creates a <= comparison.
1255 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1256 "omp.upperBoundAdjusted");
1257
1258 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1259 CharMapT *oldClastVars = clastVars;
1260 clastVars = &clastVarsOMP;
1261 ExpGen.setIVS(&clastVarsOMP);
1262
1263 codegenForSequential(f, lowerBound, upperBound);
1264
1265 // Restore the old clastVars.
1266 clastVars = oldClastVars;
1267 ExpGen.setIVS(oldClastVars);
1268
1269 Builder.CreateBr(checkNextBB);
1270
1271 // Add code to terminate this openmp subfunction.
1272 Builder.SetInsertPoint(ExitBB);
1273 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1274 Builder.CreateCall(endnowaitFunction);
1275 Builder.CreateRetVoid();
1276
1277 // Restore the builder back to previous basic block.
1278 Builder.SetInsertPoint(PrevBB);
1279}
1280
1281void ClastStmtCodeGen::codegenForOpenMP(const clast_for *f) {
1282 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1283 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
1284
1285 Function *SubFunction = addOpenMPSubfunction(M);
1286 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1287 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1288
1289 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1290
1291 // Create call for GOMP_parallel_loop_runtime_start.
1292 Value *subfunctionParam = Builder.CreateBitCast(structData,
1293 Builder.getInt8PtrTy(),
1294 "omp_data");
1295
1296 Value *numberOfThreads = Builder.getInt32(0);
1297 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1298 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1299
1300 // Add one as the upper bound provided by openmp is a < comparison
1301 // whereas the codegenForSequential function creates a <= comparison.
1302 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1303 APInt APStride = APInt_from_MPZ(f->stride);
1304 Value *stride = ConstantInt::get(intPtrTy,
1305 APStride.zext(intPtrTy->getBitWidth()));
1306
1307 SmallVector<Value *, 6> Arguments;
1308 Arguments.push_back(SubFunction);
1309 Arguments.push_back(subfunctionParam);
1310 Arguments.push_back(numberOfThreads);
1311 Arguments.push_back(lowerBound);
1312 Arguments.push_back(upperBound);
1313 Arguments.push_back(stride);
1314
1315 Function *parallelStartFunction =
1316 M->getFunction("GOMP_parallel_loop_runtime_start");
1317 Builder.CreateCall(parallelStartFunction, Arguments);
1318
1319 // Create call to the subfunction.
1320 Builder.CreateCall(SubFunction, subfunctionParam);
1321
1322 // Create call for GOMP_parallel_end.
1323 Function *FN = M->getFunction("GOMP_parallel_end");
1324 Builder.CreateCall(FN);
1325}
1326
1327bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1328 const clast_stmt *stmt = f->body;
1329
1330 while (stmt) {
1331 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1332 return false;
1333
1334 stmt = stmt->next;
1335 }
1336
1337 return true;
1338}
1339
1340int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1341 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1342 isl_set *tmp = isl_set_copy(loopDomain);
1343
1344 // Calculate a map similar to the identity map, but with the last input
1345 // and output dimension not related.
1346 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1347 isl_space *Space = isl_set_get_space(loopDomain);
1348 Space = isl_space_drop_outputs(Space,
1349 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1350 Space = isl_space_map_from_set(Space);
1351 isl_map *identity = isl_map_identity(Space);
1352 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1353 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1354
1355 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1356 map = isl_map_intersect(map, identity);
1357
1358 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1359 isl_map *lexmin = isl_map_lexmin(map);
1360 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1361
1362 isl_set *elements = isl_map_range(sub);
1363
1364 if (!isl_set_is_singleton(elements)) {
1365 isl_set_free(elements);
1366 return -1;
1367 }
1368
1369 isl_point *p = isl_set_sample_point(elements);
1370
1371 isl_int v;
1372 isl_int_init(v);
1373 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1374 int numberIterations = isl_int_get_si(v);
1375 isl_int_clear(v);
1376 isl_point_free(p);
1377
1378 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1379}
1380
1381void ClastStmtCodeGen::codegenForVector(const clast_for *f) {
1382 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1383 int vectorWidth = getNumberOfIterations(f);
1384
1385 Value *LB = ExpGen.codegen(f->LB,
1386 TD->getIntPtrType(Builder.getContext()));
1387
1388 APInt Stride = APInt_from_MPZ(f->stride);
1389 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1390 Stride = Stride.zext(LoopIVType->getBitWidth());
1391 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1392
1393 std::vector<Value*> IVS(vectorWidth);
1394 IVS[0] = LB;
1395
1396 for (int i = 1; i < vectorWidth; i++)
1397 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1398
1399 isl_set *scatteringDomain =
1400 isl_set_copy(isl_set_from_cloog_domain(f->domain));
1401
1402 // Add loop iv to symbols.
1403 (*clastVars)[f->iterator] = LB;
1404
1405 const clast_stmt *stmt = f->body;
1406
1407 while (stmt) {
1408 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1409 scatteringDomain);
1410 stmt = stmt->next;
1411 }
1412
1413 // Loop is finished, so remove its iv from the live symbols.
1414 isl_set_free(scatteringDomain);
1415 clastVars->erase(f->iterator);
1416}
1417
1418void ClastStmtCodeGen::codegen(const clast_for *f) {
1419 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
1420 && (-1 != getNumberOfIterations(f))
1421 && (getNumberOfIterations(f) <= 16)) {
1422 codegenForVector(f);
1423 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
1424 parallelCodeGeneration = true;
1425 parallelLoops.push_back(f->iterator);
1426 codegenForOpenMP(f);
1427 parallelCodeGeneration = false;
1428 } else
1429 codegenForSequential(f);
1430}
1431
1432Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
1433 Value *LHS = ExpGen.codegen(eq->LHS,
1434 TD->getIntPtrType(Builder.getContext()));
1435 Value *RHS = ExpGen.codegen(eq->RHS,
1436 TD->getIntPtrType(Builder.getContext()));
1437 CmpInst::Predicate P;
1438
1439 if (eq->sign == 0)
1440 P = ICmpInst::ICMP_EQ;
1441 else if (eq->sign > 0)
1442 P = ICmpInst::ICMP_SGE;
1443 else
1444 P = ICmpInst::ICMP_SLE;
1445
1446 return Builder.CreateICmp(P, LHS, RHS);
1447}
1448
1449void ClastStmtCodeGen::codegen(const clast_guard *g) {
1450 Function *F = Builder.GetInsertBlock()->getParent();
1451 LLVMContext &Context = F->getContext();
1452 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1453 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1454 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1455 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1456
1457 Value *Predicate = codegen(&(g->eq[0]));
1458
1459 for (int i = 1; i < g->n; ++i) {
1460 Value *TmpPredicate = codegen(&(g->eq[i]));
1461 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1462 }
1463
1464 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1465 Builder.SetInsertPoint(ThenBB);
1466
1467 codegen(g->then);
1468
1469 Builder.CreateBr(MergeBB);
1470 Builder.SetInsertPoint(MergeBB);
1471}
1472
1473void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1474 if (CLAST_STMT_IS_A(stmt, stmt_root))
1475 assert(false && "No second root statement expected");
1476 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1477 codegen((const clast_assignment *)stmt);
1478 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1479 codegen((const clast_user_stmt *)stmt);
1480 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1481 codegen((const clast_block *)stmt);
1482 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1483 codegen((const clast_for *)stmt);
1484 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1485 codegen((const clast_guard *)stmt);
1486
1487 if (stmt->next)
1488 codegen(stmt->next);
1489}
1490
1491void ClastStmtCodeGen::addParameters(const CloogNames *names) {
1492 SCEVExpander Rewriter(SE, "polly");
1493
1494 // Create an instruction that specifies the location where the parameters
1495 // are expanded.
1496 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1497 Builder.getInt16Ty(), false, "insertInst",
1498 Builder.GetInsertBlock());
1499
1500 int i = 0;
1501 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1502 PI != PE; ++PI) {
1503 assert(i < names->nb_parameters && "Not enough parameter names");
1504
1505 const SCEV *Param = *PI;
1506 Type *Ty = Param->getType();
1507
1508 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1509 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1510 (*clastVars)[names->parameters[i]] = V;
1511
1512 ++i;
1513 }
1514}
1515
1516void ClastStmtCodeGen::codegen(const clast_root *r) {
1517 clastVars = new CharMapT();
1518 addParameters(r->names);
1519 ExpGen.setIVS(clastVars);
1520
1521 parallelCodeGeneration = false;
1522
1523 const clast_stmt *stmt = (const clast_stmt*) r;
1524 if (stmt->next)
1525 codegen(stmt->next);
1526
1527 delete clastVars;
1528}
1529
1530ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, ScalarEvolution &se,
1531 DominatorTree *dt, ScopDetection *sd,
1532 Dependences *dp, TargetData *td,
1533 IRBuilder<> &B) :
1534 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1535 ExpGen(Builder, NULL) {}
1536
Tobias Grosser75805372011-04-29 06:27:02 +00001537namespace {
1538class CodeGeneration : public ScopPass {
1539 Region *region;
1540 Scop *S;
1541 DominatorTree *DT;
1542 ScalarEvolution *SE;
1543 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001544 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001545 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001546
1547 std::vector<std::string> parallelLoops;
1548
1549 public:
1550 static char ID;
1551
1552 CodeGeneration() : ScopPass(ID) {}
1553
Tobias Grosserb1c95992012-02-12 12:09:27 +00001554 // Add the declarations needed by the OpenMP function calls that we insert in
1555 // OpenMP mode.
1556 void addOpenMPDeclarations(Module *M)
Tobias Grosser75805372011-04-29 06:27:02 +00001557 {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001558 IRBuilder<> Builder(M->getContext());
1559 IntegerType *LongTy = TD->getIntPtrType(M->getContext());
1560
1561 llvm::GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosser75805372011-04-29 06:27:02 +00001562
1563 if (!M->getFunction("GOMP_parallel_end")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001564 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1565 Function::Create(Ty, Linkage, "GOMP_parallel_end", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001566 }
1567
1568 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001569 Type *Params[] = {
1570 PointerType::getUnqual(FunctionType::get(Builder.getVoidTy(),
1571 Builder.getInt8PtrTy(),
1572 false)),
1573 Builder.getInt8PtrTy(),
1574 Builder.getInt32Ty(),
1575 LongTy,
1576 LongTy,
1577 LongTy,
1578 };
Tobias Grosser75805372011-04-29 06:27:02 +00001579
Tobias Grosserd855cc52012-02-12 12:09:32 +00001580 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
1581 Function::Create(Ty, Linkage, "GOMP_parallel_loop_runtime_start", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001582 }
1583
1584 if (!M->getFunction("GOMP_loop_runtime_next")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001585 PointerType *LongPtrTy = PointerType::getUnqual(LongTy);
1586 Type *Params[] = {
1587 LongPtrTy,
1588 LongPtrTy,
1589 };
Tobias Grosser75805372011-04-29 06:27:02 +00001590
Tobias Grosserd855cc52012-02-12 12:09:32 +00001591 FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
1592 Function::Create(Ty, Linkage, "GOMP_loop_runtime_next", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001593 }
1594
1595 if (!M->getFunction("GOMP_loop_end_nowait")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001596 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1597 Function::Create(Ty, Linkage, "GOMP_loop_end_nowait", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001598 }
1599 }
1600
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001601 // Split the entry edge of the region and generate a new basic block on this
1602 // edge. This function also updates ScopInfo and RegionInfo.
1603 //
1604 // @param region The region where the entry edge will be splitted.
1605 BasicBlock *splitEdgeAdvanced(Region *region) {
1606 BasicBlock *newBlock;
1607 BasicBlock *splitBlock;
1608
1609 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1610
1611 if (DT->dominates(region->getEntry(), newBlock)) {
1612 // Update ScopInfo.
1613 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1614 if ((*SI)->getBasicBlock() == newBlock) {
1615 (*SI)->setBasicBlock(newBlock);
1616 break;
1617 }
1618
1619 // Update RegionInfo.
1620 splitBlock = region->getEntry();
1621 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001622 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001623 } else {
1624 RI->setRegionFor(newBlock, region->getParent());
1625 splitBlock = newBlock;
1626 }
1627
1628 return splitBlock;
1629 }
1630
1631 // Create a split block that branches either to the old code or to a new basic
1632 // block where the new code can be inserted.
1633 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001634 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001635 // the new code can be generated.
1636 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001637 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1638 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001639
Tobias Grosserbd608a82012-02-12 12:09:41 +00001640 SplitBlock = splitEdgeAdvanced(region);
1641 SplitBlock->setName("polly.split_new_and_old");
1642 Function *F = SplitBlock->getParent();
1643 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1644 SplitBlock->getTerminator()->eraseFromParent();
1645 Builder->SetInsertPoint(SplitBlock);
1646 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1647 DT->addNewBlock(StartBlock, SplitBlock);
1648 Builder->SetInsertPoint(StartBlock);
1649 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001650 }
1651
1652 // Merge the control flow of the newly generated code with the existing code.
1653 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001654 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001655 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001656 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001657 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001658 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1659 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001660 Region *R = region;
1661
1662 if (R->getExit()->getSinglePredecessor())
1663 // No splitEdge required. A block with a single predecessor cannot have
1664 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001665 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001666 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001667 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001668 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1669 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001670 MergeBlock->setName("polly.merge_new_and_old");
1671 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001672 }
1673
Tobias Grosserbd608a82012-02-12 12:09:41 +00001674 Builder->CreateBr(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001675
Tobias Grosserbd608a82012-02-12 12:09:41 +00001676 if (DT->dominates(SplitBlock, MergeBlock))
1677 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001678 }
1679
Tobias Grosser75805372011-04-29 06:27:02 +00001680 bool runOnScop(Scop &scop) {
1681 S = &scop;
1682 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001683 DT = &getAnalysis<DominatorTree>();
1684 Dependences *DP = &getAnalysis<Dependences>();
1685 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001686 SD = &getAnalysis<ScopDetection>();
1687 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001688 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001689
1690 parallelLoops.clear();
1691
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001692 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001693
Tobias Grosserb1c95992012-02-12 12:09:27 +00001694 Module *M = region->getEntry()->getParent()->getParent();
1695
Tobias Grosserd855cc52012-02-12 12:09:32 +00001696 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001697
Tobias Grosser5772e652012-02-01 14:23:33 +00001698 // In the CFG the optimized code of the SCoP is generated next to the
1699 // original code. Both the new and the original version of the code remain
1700 // in the CFG. A branch statement decides which version is executed.
1701 // For now, we always execute the new version (the old one is dead code
1702 // eliminated by the cleanup passes). In the future we may decide to execute
1703 // the new version only if certain run time checks succeed. This will be
1704 // useful to support constructs for which we cannot prove all assumptions at
1705 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001706 //
1707 // Before transformation:
1708 //
1709 // bb0
1710 // |
1711 // orig_scop
1712 // |
1713 // bb1
1714 //
1715 // After transformation:
1716 // bb0
1717 // |
1718 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001719 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001720 // | startBlock
1721 // | |
1722 // orig_scop new_scop
1723 // \ /
1724 // \ /
1725 // bb1 (joinBlock)
1726 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001727
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001728 // The builder will be set to startBlock.
1729 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001730
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001731 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001732 CloogInfo &C = getAnalysis<CloogInfo>();
1733 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001734
Tobias Grosser75805372011-04-29 06:27:02 +00001735 parallelLoops.insert(parallelLoops.begin(),
1736 CodeGen.getParallelLoops().begin(),
1737 CodeGen.getParallelLoops().end());
1738
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001739 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001740
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001741 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001742 }
1743
1744 virtual void printScop(raw_ostream &OS) const {
1745 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1746 PE = parallelLoops.end(); PI != PE; ++PI)
1747 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1748 }
1749
1750 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1751 AU.addRequired<CloogInfo>();
1752 AU.addRequired<Dependences>();
1753 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001754 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001755 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001756 AU.addRequired<ScopDetection>();
1757 AU.addRequired<ScopInfo>();
1758 AU.addRequired<TargetData>();
1759
1760 AU.addPreserved<CloogInfo>();
1761 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001762
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001763 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001764 AU.addPreserved<LoopInfo>();
1765 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001766 AU.addPreserved<ScopDetection>();
1767 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001768
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001769 // FIXME: We do not yet add regions for the newly generated code to the
1770 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001771 AU.addPreserved<RegionInfo>();
1772 AU.addPreserved<TempScopInfo>();
1773 AU.addPreserved<ScopInfo>();
1774 AU.addPreservedID(IndependentBlocksID);
1775 }
1776};
1777}
1778
1779char CodeGeneration::ID = 1;
1780
Tobias Grosser73600b82011-10-08 00:30:40 +00001781INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1782 "Polly - Create LLVM-IR form SCoPs", false, false)
1783INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1784INITIALIZE_PASS_DEPENDENCY(Dependences)
1785INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1786INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1787INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1788INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1789INITIALIZE_PASS_DEPENDENCY(TargetData)
1790INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1791 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001792
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001793Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001794 return new CodeGeneration();
1795}