blob: 80bde8376fb8e5930f216343e246f994ae1ac9eb [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
25#include "polly/LinkAllPasses.h"
26#include "polly/Support/GICHelper.h"
27#include "polly/Support/ScopHelper.h"
28#include "polly/Cloog.h"
Tobias Grosser67707b72011-10-23 20:59:40 +000029#include "polly/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000030#include "polly/Dependences.h"
31#include "polly/ScopInfo.h"
32#include "polly/TempScopInfo.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/IRBuilder.h"
36#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser8c4cfc322011-05-14 19:01:49 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Module.h"
41#include "llvm/ADT/SetVector.h"
42
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 Grosser55927aa2011-07-18 09:53:32 +0000742 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000743 CharMapT::const_iterator I = IVS->find(e->name);
744
745 if (I != IVS->end())
746 return Builder.CreateSExtOrBitCast(I->second, Ty);
747 else
748 llvm_unreachable("Clast name not found");
749 }
750
Tobias Grosser55927aa2011-07-18 09:53:32 +0000751 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000752 APInt a = APInt_from_MPZ(e->val);
753
754 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
755 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
756
757 if (e->var) {
758 Value *var = codegen(e->var, Ty);
759 return Builder.CreateMul(ConstOne, var);
760 }
761
762 return ConstOne;
763 }
764
Tobias Grosser55927aa2011-07-18 09:53:32 +0000765 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000766 Value *LHS = codegen(e->LHS, Ty);
767
768 APInt RHS_AP = APInt_from_MPZ(e->RHS);
769
770 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
771 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
772
773 switch (e->type) {
774 case clast_bin_mod:
775 return Builder.CreateSRem(LHS, RHS);
776 case clast_bin_fdiv:
777 {
778 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
779 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
780 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
781 One = Builder.CreateZExtOrBitCast(One, Ty);
782 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
783 Value *Sum1 = Builder.CreateSub(LHS, RHS);
784 Value *Sum2 = Builder.CreateAdd(Sum1, One);
785 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
786 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
787 return Builder.CreateSDiv(Dividend, RHS);
788 }
789 case clast_bin_cdiv:
790 {
791 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
792 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
793 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
794 One = Builder.CreateZExtOrBitCast(One, Ty);
795 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
796 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
797 Value *Sum2 = Builder.CreateSub(Sum1, One);
798 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
799 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
800 return Builder.CreateSDiv(Dividend, RHS);
801 }
802 case clast_bin_div:
803 return Builder.CreateSDiv(LHS, RHS);
804 default:
805 llvm_unreachable("Unknown clast binary expression type");
806 };
807 }
808
Tobias Grosser55927aa2011-07-18 09:53:32 +0000809 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000810 assert(( r->type == clast_red_min
811 || r->type == clast_red_max
812 || r->type == clast_red_sum)
813 && "Clast reduction type not supported");
814 Value *old = codegen(r->elts[0], Ty);
815
816 for (int i=1; i < r->n; ++i) {
817 Value *exprValue = codegen(r->elts[i], Ty);
818
819 switch (r->type) {
820 case clast_red_min:
821 {
822 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
823 old = Builder.CreateSelect(cmp, old, exprValue);
824 break;
825 }
826 case clast_red_max:
827 {
828 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
829 old = Builder.CreateSelect(cmp, old, exprValue);
830 break;
831 }
832 case clast_red_sum:
833 old = Builder.CreateAdd(old, exprValue);
834 break;
835 default:
836 llvm_unreachable("Clast unknown reduction type");
837 }
838 }
839
840 return old;
841 }
842
843public:
844
845 // A generator for clast expressions.
846 //
847 // @param B The IRBuilder that defines where the code to calculate the
848 // clast expressions should be inserted.
849 // @param IVMAP A Map that translates strings describing the induction
850 // variables to the Values* that represent these variables
851 // on the LLVM side.
852 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
853
854 // Generates code to calculate a given clast expression.
855 //
856 // @param e The expression to calculate.
857 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000858 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000859 switch(e->type) {
860 case clast_expr_name:
861 return codegen((const clast_name *)e, Ty);
862 case clast_expr_term:
863 return codegen((const clast_term *)e, Ty);
864 case clast_expr_bin:
865 return codegen((const clast_binary *)e, Ty);
866 case clast_expr_red:
867 return codegen((const clast_reduction *)e, Ty);
868 default:
869 llvm_unreachable("Unknown clast expression!");
870 }
871 }
872
873 // @brief Reset the CharMap.
874 //
875 // This function is called to reset the CharMap to new one, while generating
876 // OpenMP code.
877 void setIVS(CharMapT *IVSNew) {
878 IVS = IVSNew;
879 }
880
881};
882
883class ClastStmtCodeGen {
884 // The Scop we code generate.
885 Scop *S;
886 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000887 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000888 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000889 Dependences *DP;
890 TargetData *TD;
891
892 // The Builder specifies the current location to code generate at.
893 IRBuilder<> &Builder;
894
895 // Map the Values from the old code to their counterparts in the new code.
896 ValueMapT ValueMap;
897
898 // clastVars maps from the textual representation of a clast variable to its
899 // current *Value. clast variables are scheduling variables, original
900 // induction variables or parameters. They are used either in loop bounds or
901 // to define the statement instance that is executed.
902 //
903 // for (s = 0; s < n + 3; ++i)
904 // for (t = s; t < m; ++j)
905 // Stmt(i = s + 3 * m, j = t);
906 //
907 // {s,t,i,j,n,m} is the set of clast variables in this clast.
908 CharMapT *clastVars;
909
910 // Codegenerator for clast expressions.
911 ClastExpCodeGen ExpGen;
912
913 // Do we currently generate parallel code?
914 bool parallelCodeGeneration;
915
916 std::vector<std::string> parallelLoops;
917
918public:
919
920 const std::vector<std::string> &getParallelLoops() {
921 return parallelLoops;
922 }
923
924 protected:
925 void codegen(const clast_assignment *a) {
926 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
927 TD->getIntPtrType(Builder.getContext()));
928 }
929
930 void codegen(const clast_assignment *a, ScopStmt *Statement,
931 unsigned Dimension, int vectorDim,
932 std::vector<ValueMapT> *VectorVMap = 0) {
933 Value *RHS = ExpGen.codegen(a->RHS,
934 TD->getIntPtrType(Builder.getContext()));
935
936 assert(!a->LHS && "Statement assignments do not have left hand side");
937 const PHINode *PN;
938 PN = Statement->getInductionVariableForDimension(Dimension);
939 const Value *V = PN;
940
Tobias Grosser75805372011-04-29 06:27:02 +0000941 if (VectorVMap)
942 (*VectorVMap)[vectorDim][V] = RHS;
943
944 ValueMap[V] = RHS;
945 }
946
947 void codegenSubstitutions(const clast_stmt *Assignment,
948 ScopStmt *Statement, int vectorDim = 0,
949 std::vector<ValueMapT> *VectorVMap = 0) {
950 int Dimension = 0;
951
952 while (Assignment) {
953 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
954 && "Substitions are expected to be assignments");
955 codegen((const clast_assignment *)Assignment, Statement, Dimension,
956 vectorDim, VectorVMap);
957 Assignment = Assignment->next;
958 Dimension++;
959 }
960 }
961
962 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
963 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
964 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
965 BasicBlock *BB = Statement->getBasicBlock();
966
967 if (u->substitutions)
968 codegenSubstitutions(u->substitutions, Statement);
969
970 int vectorDimensions = IVS ? IVS->size() : 1;
971
972 VectorValueMapT VectorValueMap(vectorDimensions);
973
974 if (IVS) {
975 assert (u->substitutions && "Substitutions expected!");
976 int i = 0;
977 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
978 II != IE; ++II) {
979 (*clastVars)[iterator] = *II;
980 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
981 i++;
982 }
983 }
984
985 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
986 scatteringDomain);
987 Generator.copyBB(BB, DT);
988 }
989
990 void codegen(const clast_block *b) {
991 if (b->body)
992 codegen(b->body);
993 }
994
995 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000996 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
997 Value *UpperBound = 0) {
998 APInt Stride;
Tobias Grosser75805372011-04-29 06:27:02 +0000999 PHINode *IV;
1000 Value *IncrementedIV;
Tobias Grosser545bc312011-12-06 10:48:27 +00001001 BasicBlock *AfterBB, *HeaderBB, *LastBodyBB;
1002 Type *IntPtrTy;
1003
1004 Stride = APInt_from_MPZ(f->stride);
1005 IntPtrTy = TD->getIntPtrType(Builder.getContext());
1006
Tobias Grosser75805372011-04-29 06:27:02 +00001007 // The value of lowerbound and upperbound will be supplied, if this
1008 // function is called while generating OpenMP code. Otherwise get
1009 // the values.
Tobias Grosser545bc312011-12-06 10:48:27 +00001010 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1011
1012 if (LowerBound == 0) {
1013 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1014 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
Tobias Grosser75805372011-04-29 06:27:02 +00001015 }
Tobias Grosser545bc312011-12-06 10:48:27 +00001016
1017 createLoop(&Builder, LowerBound, UpperBound, Stride, IV, AfterBB,
Tobias Grosser75805372011-04-29 06:27:02 +00001018 IncrementedIV, DT);
1019
1020 // Add loop iv to symbols.
1021 (*clastVars)[f->iterator] = IV;
1022
1023 if (f->body)
1024 codegen(f->body);
1025
1026 // Loop is finished, so remove its iv from the live symbols.
1027 clastVars->erase(f->iterator);
1028
Tobias Grosser545bc312011-12-06 10:48:27 +00001029 HeaderBB = *pred_begin(AfterBB);
1030 LastBodyBB = Builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001031 Builder.CreateBr(HeaderBB);
1032 IV->addIncoming(IncrementedIV, LastBodyBB);
1033 Builder.SetInsertPoint(AfterBB);
1034 }
1035
Tobias Grosser75805372011-04-29 06:27:02 +00001036 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001037 Function *addOpenMPSubfunction(Module *M) {
Tobias Grosser75805372011-04-29 06:27:02 +00001038 Function *F = Builder.GetInsertBlock()->getParent();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001039 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001040 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
Tobias Grosser29ee0b12011-11-17 14:52:36 +00001041 Function *FN = Function::Create(FT, Function::InternalLinkage,
1042 F->getName() + ".omp_subfn", M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001043 // Do not run any polly pass on the new function.
1044 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +00001045
1046 Function::arg_iterator AI = FN->arg_begin();
1047 AI->setName("omp.userContext");
1048
1049 return FN;
1050 }
1051
1052 /// @brief Add values to the OpenMP structure.
1053 ///
1054 /// Create the subfunction structure and add the values from the list.
1055 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1056 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +00001057 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +00001058
1059 // Create the structure.
1060 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1061 structMembers.push_back(OMPDataVals[i]->getType());
1062
Tobias Grosser75805372011-04-29 06:27:02 +00001063 StructType *structTy = StructType::get(Builder.getContext(),
1064 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +00001065 // Store the values into the structure.
1066 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1067 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1068 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1069 Builder.CreateStore(OMPDataVals[i], storeAddr);
1070 }
1071
1072 return structData;
1073 }
1074
1075 /// @brief Create OpenMP structure values.
1076 ///
1077 /// Create a list of values that has to be stored into the subfuncition
1078 /// structure.
1079 SetVector<Value*> createOpenMPStructValues() {
1080 SetVector<Value*> OMPDataVals;
1081
1082 // Push the clast variables available in the clastVars.
1083 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1084 I != E; I++)
1085 OMPDataVals.insert(I->second);
1086
1087 // Push the base addresses of memory references.
1088 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1089 ScopStmt *Stmt = *SI;
1090 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1091 E = Stmt->memacc_end(); I != E; ++I) {
1092 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1093 OMPDataVals.insert((BaseAddr));
1094 }
1095 }
1096
1097 return OMPDataVals;
1098 }
1099
1100 /// @brief Extract the values from the subfunction parameter.
1101 ///
1102 /// Extract the values from the subfunction parameter and update the clast
1103 /// variables to point to the new values.
1104 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1105 SetVector<Value*> OMPDataVals,
1106 Value *userContext) {
1107 // Extract the clast variables.
1108 unsigned i = 0;
1109 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1110 I != E; I++) {
1111 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1112 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1113 i++;
1114 }
1115
1116 // Extract the base addresses of memory references.
1117 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1118 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1119 Value *baseAddr = OMPDataVals[j];
1120 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1121 }
1122
1123 }
1124
1125 /// @brief Add body to the subfunction.
1126 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
1127 Value *structData,
1128 SetVector<Value*> OMPDataVals) {
1129 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1130 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001131 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001132
1133 // Store the previous basic block.
1134 BasicBlock *PrevBB = Builder.GetInsertBlock();
1135
1136 // Create basic blocks.
1137 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1138 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1139 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1140 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1141 FN);
1142
1143 DT->addNewBlock(HeaderBB, PrevBB);
1144 DT->addNewBlock(ExitBB, HeaderBB);
1145 DT->addNewBlock(checkNextBB, HeaderBB);
1146 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1147
1148 // Fill up basic block HeaderBB.
1149 Builder.SetInsertPoint(HeaderBB);
1150 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1151 "omp.lowerBoundPtr");
1152 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1153 "omp.upperBoundPtr");
1154 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1155 structData->getType(),
1156 "omp.userContext");
1157
1158 CharMapT clastVarsOMP;
1159 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1160
1161 Builder.CreateBr(checkNextBB);
1162
1163 // Add code to check if another set of iterations will be executed.
1164 Builder.SetInsertPoint(checkNextBB);
1165 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1166 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1167 lowerBoundPtr, upperBoundPtr);
1168 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1169 "omp.hasNextScheduleBlock");
1170 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1171
1172 // Add code to to load the iv bounds for this set of iterations.
1173 Builder.SetInsertPoint(loadIVBoundsBB);
1174 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1175 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1176
1177 // Subtract one as the upper bound provided by openmp is a < comparison
1178 // whereas the codegenForSequential function creates a <= comparison.
1179 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1180 "omp.upperBoundAdjusted");
1181
1182 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1183 CharMapT *oldClastVars = clastVars;
1184 clastVars = &clastVarsOMP;
1185 ExpGen.setIVS(&clastVarsOMP);
1186
1187 codegenForSequential(f, lowerBound, upperBound);
1188
1189 // Restore the old clastVars.
1190 clastVars = oldClastVars;
1191 ExpGen.setIVS(oldClastVars);
1192
1193 Builder.CreateBr(checkNextBB);
1194
1195 // Add code to terminate this openmp subfunction.
1196 Builder.SetInsertPoint(ExitBB);
1197 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1198 Builder.CreateCall(endnowaitFunction);
1199 Builder.CreateRetVoid();
1200
1201 // Restore the builder back to previous basic block.
1202 Builder.SetInsertPoint(PrevBB);
1203 }
1204
1205 /// @brief Create an OpenMP parallel for loop.
1206 ///
1207 /// This loop reflects a loop as if it would have been created by an OpenMP
1208 /// statement.
1209 void codegenForOpenMP(const clast_for *f) {
1210 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001211 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001212
1213 Function *SubFunction = addOpenMPSubfunction(M);
1214 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1215 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1216
1217 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1218
1219 // Create call for GOMP_parallel_loop_runtime_start.
1220 Value *subfunctionParam = Builder.CreateBitCast(structData,
1221 Builder.getInt8PtrTy(),
1222 "omp_data");
1223
1224 Value *numberOfThreads = Builder.getInt32(0);
1225 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1226 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1227
1228 // Add one as the upper bound provided by openmp is a < comparison
1229 // whereas the codegenForSequential function creates a <= comparison.
1230 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1231 APInt APStride = APInt_from_MPZ(f->stride);
1232 Value *stride = ConstantInt::get(intPtrTy,
1233 APStride.zext(intPtrTy->getBitWidth()));
1234
1235 SmallVector<Value *, 6> Arguments;
1236 Arguments.push_back(SubFunction);
1237 Arguments.push_back(subfunctionParam);
1238 Arguments.push_back(numberOfThreads);
1239 Arguments.push_back(lowerBound);
1240 Arguments.push_back(upperBound);
1241 Arguments.push_back(stride);
1242
1243 Function *parallelStartFunction =
1244 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001245 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001246
1247 // Create call to the subfunction.
1248 Builder.CreateCall(SubFunction, subfunctionParam);
1249
1250 // Create call for GOMP_parallel_end.
1251 Function *FN = M->getFunction("GOMP_parallel_end");
1252 Builder.CreateCall(FN);
1253 }
1254
1255 bool isInnermostLoop(const clast_for *f) {
1256 const clast_stmt *stmt = f->body;
1257
1258 while (stmt) {
1259 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1260 return false;
1261
1262 stmt = stmt->next;
1263 }
1264
1265 return true;
1266 }
1267
1268 /// @brief Get the number of loop iterations for this loop.
1269 /// @param f The clast for loop to check.
1270 int getNumberOfIterations(const clast_for *f) {
1271 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1272 isl_set *tmp = isl_set_copy(loopDomain);
1273
1274 // Calculate a map similar to the identity map, but with the last input
1275 // and output dimension not related.
1276 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
Tobias Grosserf5338802011-10-06 00:03:35 +00001277 isl_space *Space = isl_set_get_space(loopDomain);
1278 Space = isl_space_drop_outputs(Space,
1279 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1280 Space = isl_space_map_from_set(Space);
1281 isl_map *identity = isl_map_identity(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001282 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1283 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1284
1285 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1286 map = isl_map_intersect(map, identity);
1287
1288 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001289 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001290 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1291
1292 isl_set *elements = isl_map_range(sub);
1293
Tobias Grosserc532f122011-08-25 08:40:59 +00001294 if (!isl_set_is_singleton(elements)) {
1295 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001296 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001297 }
Tobias Grosser75805372011-04-29 06:27:02 +00001298
1299 isl_point *p = isl_set_sample_point(elements);
1300
1301 isl_int v;
1302 isl_int_init(v);
1303 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1304 int numberIterations = isl_int_get_si(v);
1305 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001306 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001307
1308 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1309 }
1310
1311 /// @brief Create vector instructions for this loop.
1312 void codegenForVector(const clast_for *f) {
1313 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1314 int vectorWidth = getNumberOfIterations(f);
1315
1316 Value *LB = ExpGen.codegen(f->LB,
1317 TD->getIntPtrType(Builder.getContext()));
1318
1319 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001320 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001321 Stride = Stride.zext(LoopIVType->getBitWidth());
1322 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1323
1324 std::vector<Value*> IVS(vectorWidth);
1325 IVS[0] = LB;
1326
1327 for (int i = 1; i < vectorWidth; i++)
1328 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1329
Tobias Grosser28dd4862012-01-24 16:42:16 +00001330 isl_set *scatteringDomain =
1331 isl_set_copy(isl_set_from_cloog_domain(f->domain));
Tobias Grosser75805372011-04-29 06:27:02 +00001332
1333 // Add loop iv to symbols.
1334 (*clastVars)[f->iterator] = LB;
1335
1336 const clast_stmt *stmt = f->body;
1337
1338 while (stmt) {
1339 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1340 scatteringDomain);
1341 stmt = stmt->next;
1342 }
1343
1344 // Loop is finished, so remove its iv from the live symbols.
Tobias Grosser28dd4862012-01-24 16:42:16 +00001345 isl_set_free(scatteringDomain);
Tobias Grosser75805372011-04-29 06:27:02 +00001346 clastVars->erase(f->iterator);
1347 }
1348
1349 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001350 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001351 && (-1 != getNumberOfIterations(f))
1352 && (getNumberOfIterations(f) <= 16)) {
1353 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001354 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001355 parallelCodeGeneration = true;
1356 parallelLoops.push_back(f->iterator);
1357 codegenForOpenMP(f);
1358 parallelCodeGeneration = false;
1359 } else
1360 codegenForSequential(f);
1361 }
1362
1363 Value *codegen(const clast_equation *eq) {
1364 Value *LHS = ExpGen.codegen(eq->LHS,
1365 TD->getIntPtrType(Builder.getContext()));
1366 Value *RHS = ExpGen.codegen(eq->RHS,
1367 TD->getIntPtrType(Builder.getContext()));
1368 CmpInst::Predicate P;
1369
1370 if (eq->sign == 0)
1371 P = ICmpInst::ICMP_EQ;
1372 else if (eq->sign > 0)
1373 P = ICmpInst::ICMP_SGE;
1374 else
1375 P = ICmpInst::ICMP_SLE;
1376
1377 return Builder.CreateICmp(P, LHS, RHS);
1378 }
1379
1380 void codegen(const clast_guard *g) {
1381 Function *F = Builder.GetInsertBlock()->getParent();
1382 LLVMContext &Context = F->getContext();
1383 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1384 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1385 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1386 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1387
1388 Value *Predicate = codegen(&(g->eq[0]));
1389
1390 for (int i = 1; i < g->n; ++i) {
1391 Value *TmpPredicate = codegen(&(g->eq[i]));
1392 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1393 }
1394
1395 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1396 Builder.SetInsertPoint(ThenBB);
1397
1398 codegen(g->then);
1399
1400 Builder.CreateBr(MergeBB);
1401 Builder.SetInsertPoint(MergeBB);
1402 }
1403
1404 void codegen(const clast_stmt *stmt) {
1405 if (CLAST_STMT_IS_A(stmt, stmt_root))
1406 assert(false && "No second root statement expected");
1407 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1408 codegen((const clast_assignment *)stmt);
1409 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1410 codegen((const clast_user_stmt *)stmt);
1411 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1412 codegen((const clast_block *)stmt);
1413 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1414 codegen((const clast_for *)stmt);
1415 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1416 codegen((const clast_guard *)stmt);
1417
1418 if (stmt->next)
1419 codegen(stmt->next);
1420 }
1421
1422 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001423 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001424
1425 // Create an instruction that specifies the location where the parameters
1426 // are expanded.
1427 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1428 Builder.getInt16Ty(), false, "insertInst",
1429 Builder.GetInsertBlock());
1430
1431 int i = 0;
1432 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1433 PI != PE; ++PI) {
1434 assert(i < names->nb_parameters && "Not enough parameter names");
1435
1436 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001437 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001438
1439 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1440 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1441 (*clastVars)[names->parameters[i]] = V;
1442
1443 ++i;
1444 }
1445 }
1446
1447 public:
1448 void codegen(const clast_root *r) {
1449 clastVars = new CharMapT();
1450 addParameters(r->names);
1451 ExpGen.setIVS(clastVars);
1452
1453 parallelCodeGeneration = false;
1454
1455 const clast_stmt *stmt = (const clast_stmt*) r;
1456 if (stmt->next)
1457 codegen(stmt->next);
1458
1459 delete clastVars;
1460 }
1461
1462 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001463 ScopDetection *sd, Dependences *dp, TargetData *td,
1464 IRBuilder<> &B) :
1465 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1466 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001467
1468};
1469}
1470
1471namespace {
1472class CodeGeneration : public ScopPass {
1473 Region *region;
1474 Scop *S;
1475 DominatorTree *DT;
1476 ScalarEvolution *SE;
1477 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001478 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001479 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001480
1481 std::vector<std::string> parallelLoops;
1482
1483 public:
1484 static char ID;
1485
1486 CodeGeneration() : ScopPass(ID) {}
1487
Tobias Grosser75805372011-04-29 06:27:02 +00001488 // Adding prototypes required if OpenMP is enabled.
1489 void addOpenMPDefinitions(IRBuilder<> &Builder)
1490 {
1491 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1492 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001493 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001494
1495 if (!M->getFunction("GOMP_parallel_end")) {
1496 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1497 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1498 }
1499
1500 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1501 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001502 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001503 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1504 false);
1505 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1506
Tobias Grosser851b96e2011-07-12 12:42:54 +00001507 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001508 args.push_back(FnPtrTy);
1509 args.push_back(Builder.getInt8PtrTy());
1510 args.push_back(Builder.getInt32Ty());
1511 args.push_back(intPtrTy);
1512 args.push_back(intPtrTy);
1513 args.push_back(intPtrTy);
1514
1515 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1516 Function::Create(type, Function::ExternalLinkage,
1517 "GOMP_parallel_loop_runtime_start", M);
1518 }
1519
1520 if (!M->getFunction("GOMP_loop_runtime_next")) {
1521 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1522
Tobias Grosser851b96e2011-07-12 12:42:54 +00001523 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001524 args.push_back(intLongPtrTy);
1525 args.push_back(intLongPtrTy);
1526
1527 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1528 Function::Create(type, Function::ExternalLinkage,
1529 "GOMP_loop_runtime_next", M);
1530 }
1531
1532 if (!M->getFunction("GOMP_loop_end_nowait")) {
1533 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001534 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001535 Function::Create(FT, Function::ExternalLinkage,
1536 "GOMP_loop_end_nowait", M);
1537 }
1538 }
1539
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001540 // Split the entry edge of the region and generate a new basic block on this
1541 // edge. This function also updates ScopInfo and RegionInfo.
1542 //
1543 // @param region The region where the entry edge will be splitted.
1544 BasicBlock *splitEdgeAdvanced(Region *region) {
1545 BasicBlock *newBlock;
1546 BasicBlock *splitBlock;
1547
1548 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1549
1550 if (DT->dominates(region->getEntry(), newBlock)) {
1551 // Update ScopInfo.
1552 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1553 if ((*SI)->getBasicBlock() == newBlock) {
1554 (*SI)->setBasicBlock(newBlock);
1555 break;
1556 }
1557
1558 // Update RegionInfo.
1559 splitBlock = region->getEntry();
1560 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001561 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001562 } else {
1563 RI->setRegionFor(newBlock, region->getParent());
1564 splitBlock = newBlock;
1565 }
1566
1567 return splitBlock;
1568 }
1569
1570 // Create a split block that branches either to the old code or to a new basic
1571 // block where the new code can be inserted.
1572 //
1573 // @param builder A builder that will be set to point to a basic block, where
1574 // the new code can be generated.
1575 // @return The split basic block.
1576 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1577 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1578
1579 splitBlock->setName("polly.enterScop");
1580
1581 Function *function = splitBlock->getParent();
1582 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1583 "polly.start", function);
1584 splitBlock->getTerminator()->eraseFromParent();
1585 builder->SetInsertPoint(splitBlock);
1586 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1587 DT->addNewBlock(startBlock, splitBlock);
1588
1589 // Start code generation here.
1590 builder->SetInsertPoint(startBlock);
1591 return splitBlock;
1592 }
1593
1594 // Merge the control flow of the newly generated code with the existing code.
1595 //
1596 // @param splitBlock The basic block where the control flow was split between
1597 // old and new version of the Scop.
1598 // @param builder An IRBuilder that points to the last instruction of the
1599 // newly generated code.
1600 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1601 BasicBlock *mergeBlock;
1602 Region *R = region;
1603
1604 if (R->getExit()->getSinglePredecessor())
1605 // No splitEdge required. A block with a single predecessor cannot have
1606 // PHI nodes that would complicate life.
1607 mergeBlock = R->getExit();
1608 else {
1609 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1610 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1611 // one predecessor. Hence, mergeBlock is always a newly generated block.
1612 mergeBlock->setName("polly.finalMerge");
1613 R->replaceExit(mergeBlock);
1614 }
1615
1616 builder->CreateBr(mergeBlock);
1617
1618 if (DT->dominates(splitBlock, mergeBlock))
1619 DT->changeImmediateDominator(mergeBlock, splitBlock);
1620 }
1621
Tobias Grosser75805372011-04-29 06:27:02 +00001622 bool runOnScop(Scop &scop) {
1623 S = &scop;
1624 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001625 DT = &getAnalysis<DominatorTree>();
1626 Dependences *DP = &getAnalysis<Dependences>();
1627 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001628 SD = &getAnalysis<ScopDetection>();
1629 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001630 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001631
1632 parallelLoops.clear();
1633
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001634 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001635
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001636 // In the CFG and we generate next to original code of the Scop the
1637 // optimized version. Both the new and the original version of the code
1638 // remain in the CFG. A branch statement decides which version is executed.
1639 // At the moment, we always execute the newly generated version (the old one
1640 // is dead code eliminated by the cleanup passes). Later we may decide to
1641 // execute the new version only under certain conditions. This will be the
1642 // case if we support constructs for which we cannot prove all assumptions
1643 // at compile time.
1644 //
1645 // Before transformation:
1646 //
1647 // bb0
1648 // |
1649 // orig_scop
1650 // |
1651 // bb1
1652 //
1653 // After transformation:
1654 // bb0
1655 // |
1656 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001657 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001658 // | startBlock
1659 // | |
1660 // orig_scop new_scop
1661 // \ /
1662 // \ /
1663 // bb1 (joinBlock)
1664 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001665
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001666 // The builder will be set to startBlock.
1667 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001668
1669 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001670 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001671
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001672 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001673 CloogInfo &C = getAnalysis<CloogInfo>();
1674 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001675
Tobias Grosser75805372011-04-29 06:27:02 +00001676 parallelLoops.insert(parallelLoops.begin(),
1677 CodeGen.getParallelLoops().begin(),
1678 CodeGen.getParallelLoops().end());
1679
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001680 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001681
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001682 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001683 }
1684
1685 virtual void printScop(raw_ostream &OS) const {
1686 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1687 PE = parallelLoops.end(); PI != PE; ++PI)
1688 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1689 }
1690
1691 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1692 AU.addRequired<CloogInfo>();
1693 AU.addRequired<Dependences>();
1694 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001695 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001696 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001697 AU.addRequired<ScopDetection>();
1698 AU.addRequired<ScopInfo>();
1699 AU.addRequired<TargetData>();
1700
1701 AU.addPreserved<CloogInfo>();
1702 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001703
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001704 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001705 AU.addPreserved<LoopInfo>();
1706 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001707 AU.addPreserved<ScopDetection>();
1708 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001709
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001710 // FIXME: We do not yet add regions for the newly generated code to the
1711 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001712 AU.addPreserved<RegionInfo>();
1713 AU.addPreserved<TempScopInfo>();
1714 AU.addPreserved<ScopInfo>();
1715 AU.addPreservedID(IndependentBlocksID);
1716 }
1717};
1718}
1719
1720char CodeGeneration::ID = 1;
1721
Tobias Grosser73600b82011-10-08 00:30:40 +00001722INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1723 "Polly - Create LLVM-IR form SCoPs", false, false)
1724INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1725INITIALIZE_PASS_DEPENDENCY(Dependences)
1726INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1727INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1728INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1729INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1730INITIALIZE_PASS_DEPENDENCY(TargetData)
1731INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1732 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001733
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001734Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001735 return new CodeGeneration();
1736}