blob: be5b150f90de7e3316d4f77e13c6592e5e6e25d3 [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 {
Raghesh Aloora71989c2011-12-28 02:48:26 +000089 Value *Result;
90 IRBuilder<> *Builder;
91}IslPwAffUserInfo;
Tobias Grosser75805372011-04-29 06:27:02 +000092
93// Create a new loop.
94//
95// @param Builder The builder used to create the loop. It also defines the
96// place where to create the loop.
97// @param UB The upper bound of the loop iv.
98// @param Stride The number by which the loop iv is incremented after every
99// iteration.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000100static Value *createLoop(IRBuilder<> *Builder, Value *LB, Value *UB,
101 APInt Stride, DominatorTree *DT, Pass *P,
102 BasicBlock **AfterBlock) {
Tobias Grosser75805372011-04-29 06:27:02 +0000103 Function *F = Builder->GetInsertBlock()->getParent();
104 LLVMContext &Context = F->getContext();
105
106 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
107 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
108 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000109 BasicBlock *AfterBB = SplitBlock(PreheaderBB, Builder->GetInsertPoint()++, P);
110 AfterBB->setName("polly.loop_after");
Tobias Grosser75805372011-04-29 06:27:02 +0000111
Tobias Grosser0ac92142012-02-14 14:02:27 +0000112 PreheaderBB->getTerminator()->setSuccessor(0, HeaderBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000113 DT->addNewBlock(HeaderBB, PreheaderBB);
114
Tobias Grosser75805372011-04-29 06:27:02 +0000115 Builder->SetInsertPoint(HeaderBB);
116
117 // Use the type of upper and lower bound.
118 assert(LB->getType() == UB->getType()
119 && "Different types for upper and lower bound.");
120
Tobias Grosser55927aa2011-07-18 09:53:32 +0000121 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000122 assert(LoopIVType && "UB is not integer?");
123
124 // IV
Tobias Grosser0ac92142012-02-14 14:02:27 +0000125 PHINode *IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
Tobias Grosser75805372011-04-29 06:27:02 +0000126 IV->addIncoming(LB, PreheaderBB);
127
128 // IV increment.
129 Value *StrideValue = ConstantInt::get(LoopIVType,
130 Stride.zext(LoopIVType->getBitWidth()));
Tobias Grosser0ac92142012-02-14 14:02:27 +0000131 Value *IncrementedIV = Builder->CreateAdd(IV, StrideValue,
132 "polly.next_loopiv");
Tobias Grosser75805372011-04-29 06:27:02 +0000133
134 // Exit condition.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000135 Value *CMP;
Tobias Grosser75805372011-04-29 06:27:02 +0000136 if (AtLeastOnce) { // At least on iteration.
137 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
Tobias Grosser0ac92142012-02-14 14:02:27 +0000138 CMP = Builder->CreateICmpNE(IV, UB);
Tobias Grosser75805372011-04-29 06:27:02 +0000139 } else { // Maybe not executed at all.
Tobias Grosser0ac92142012-02-14 14:02:27 +0000140 CMP = Builder->CreateICmpSLE(IV, UB);
Tobias Grosser75805372011-04-29 06:27:02 +0000141 }
Tobias Grosser0ac92142012-02-14 14:02:27 +0000142
143 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000144 DT->addNewBlock(BodyBB, HeaderBB);
Tobias Grosser75805372011-04-29 06:27:02 +0000145
146 Builder->SetInsertPoint(BodyBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +0000147 Builder->CreateBr(HeaderBB);
148 IV->addIncoming(IncrementedIV, BodyBB);
149 DT->changeImmediateDominator(AfterBB, HeaderBB);
150
151 Builder->SetInsertPoint(BodyBB->begin());
152 *AfterBlock = AfterBB;
153
154 return IV;
Tobias Grosser75805372011-04-29 06:27:02 +0000155}
156
157class BlockGenerator {
Tobias Grosserc941ede2012-03-02 11:26:49 +0000158public:
159 /// @brief Generate code for single basic block.
160 static void generate(IRBuilder<> &B, ValueMapT &ValueMap,
161 VectorValueMapT &VectorMaps, ScopStmt &Stmt,
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000162 __isl_keep isl_set *Domain, Pass *P) {
Tobias Grosser8412cda2012-03-02 11:26:55 +0000163 BlockGenerator Generator(B, ValueMap, VectorMaps, Stmt, Domain, P);
164 Generator.copyBB();
Tobias Grosserc941ede2012-03-02 11:26:49 +0000165 }
166
167private:
168 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
Tobias Grosser8412cda2012-03-02 11:26:55 +0000169 ScopStmt &Stmt, __isl_keep isl_set *domain, Pass *p);
Tobias Grosserc941ede2012-03-02 11:26:49 +0000170
Tobias Grosser75805372011-04-29 06:27:02 +0000171 IRBuilder<> &Builder;
172 ValueMapT &VMap;
173 VectorValueMapT &ValueMaps;
174 Scop &S;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000175 ScopStmt &Statement;
176 isl_set *ScatteringDomain;
Tobias Grosser8412cda2012-03-02 11:26:55 +0000177 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000178
Tobias Grosser75805372011-04-29 06:27:02 +0000179
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000180 const Region &getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +0000181
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000182 Value *makeVectorOperand(Value *operand, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000183
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000184 Value *getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000185 ValueMapT *VectorMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000186
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000187 Type *getVectorPtrTy(const Value *V, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000188
189 /// @brief Load a vector from a set of adjacent scalars
190 ///
191 /// In case a set of scalars is known to be next to each other in memory,
192 /// create a vector load that loads those scalars
193 ///
194 /// %vector_ptr= bitcast double* %p to <4 x double>*
195 /// %vec_full = load <4 x double>* %vector_ptr
196 ///
197 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000198 int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000199
200 /// @brief Load a vector initialized from a single scalar in memory
201 ///
202 /// In case all elements of a vector are initialized to the same
203 /// scalar value, this value is loaded and shuffeled into all elements
204 /// of the vector.
205 ///
206 /// %splat_one = load <1 x double>* %p
207 /// %splat = shufflevector <1 x double> %splat_one, <1 x
208 /// double> %splat_one, <4 x i32> zeroinitializer
209 ///
210 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000211 int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000212
213 /// @Load a vector from scalars distributed in memory
214 ///
215 /// In case some scalars a distributed randomly in memory. Create a vector
216 /// by loading each scalar and by inserting one after the other into the
217 /// vector.
218 ///
219 /// %scalar_1= load double* %p_1
220 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
221 /// %scalar 2 = load double* %p_2
222 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
223 ///
224 Value *generateUnknownStrideLoad(const LoadInst *load,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000225 VectorValueMapT &scalarMaps, int size);
Tobias Grosser75805372011-04-29 06:27:02 +0000226
Raghesh Aloora71989c2011-12-28 02:48:26 +0000227 static Value* islAffToValue(__isl_take isl_aff *Aff,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000228 IslPwAffUserInfo *UserInfo);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000229
230 static int mergeIslAffValues(__isl_take isl_set *Set,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000231 __isl_take isl_aff *Aff, void *User);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000232
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000233 Value* islPwAffToValue(__isl_take isl_pw_aff *PwAff);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000234
Raghesh Aloor129e8672011-08-15 02:33:39 +0000235 /// @brief Get the memory access offset to be added to the base address
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000236 std::vector <Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000237 Value *BaseAddress);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000238
Raghesh Aloor62b13122011-08-03 17:02:50 +0000239 /// @brief Get the new operand address according to the changed access in
240 /// JSCOP file.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000241 Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
242 Value *BaseAddress, const Value *OldOperand,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000243 ValueMapT &BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000244
245 /// @brief Generate the operand address
246 Value *generateLocationAccessed(const Instruction *Inst,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000247 const Value *Pointer, ValueMapT &BBMap );
Raghesh Aloor129e8672011-08-15 02:33:39 +0000248
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000249 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000250
251 /// @brief Load a value (or several values as a vector) from memory.
252 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000253 VectorValueMapT &scalarMaps, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000254
Tobias Grosserc9215152011-09-04 11:45:52 +0000255 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
256 ValueMapT &VectorMap, int VectorDimension,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000257 int VectorWidth);
Tobias Grosserc9215152011-09-04 11:45:52 +0000258
Tobias Grosser09c57102011-09-04 11:45:29 +0000259 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000260 ValueMapT &vectorMap, int vectorDimension, int vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000261
262 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000263 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000264 int vectorDimension, int vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000265
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000266 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000267
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000268 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000269
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000270 int getVectorSize();
Tobias Grosser75805372011-04-29 06:27:02 +0000271
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000272 bool isVectorBlock();
Tobias Grosser75805372011-04-29 06:27:02 +0000273
Tobias Grosser7551c302011-09-04 11:45:41 +0000274 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
Tobias Grosser262df3b2012-03-02 11:26:46 +0000275 ValueMapT &VectorMap, VectorValueMapT &ScalarMaps,
276 int VectorDimension, int VectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000277
Tobias Grosser75805372011-04-29 06:27:02 +0000278 // Insert a copy of a basic block in the newly generated code.
279 //
280 // @param Builder The builder used to insert the code. It also specifies
281 // where to insert the code.
Tobias Grosser75805372011-04-29 06:27:02 +0000282 // @param VMap A map returning for any old value its new equivalent. This
283 // is used to update the operands of the statements.
284 // For new statements a relation old->new is inserted in this
285 // map.
Tobias Grosser8412cda2012-03-02 11:26:55 +0000286 void copyBB();
Tobias Grosser75805372011-04-29 06:27:02 +0000287};
288
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000289BlockGenerator::BlockGenerator(IRBuilder<> &B, ValueMapT &vmap,
290 VectorValueMapT &vmaps, ScopStmt &Stmt,
Tobias Grosser8412cda2012-03-02 11:26:55 +0000291 __isl_keep isl_set *domain, Pass *P)
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000292 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
Tobias Grosser8412cda2012-03-02 11:26:55 +0000293 Statement(Stmt), ScatteringDomain(domain), P(P) {}
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000294
295const Region &BlockGenerator::getRegion() {
296 return S.getRegion();
297}
298
299Value *BlockGenerator::makeVectorOperand(Value *Operand, int VectorWidth) {
300 if (Operand->getType()->isVectorTy())
301 return Operand;
302
303 VectorType *VectorType = VectorType::get(Operand->getType(), VectorWidth);
304 Value *Vector = UndefValue::get(VectorType);
305 Vector = Builder.CreateInsertElement(Vector, Operand, Builder.getInt32(0));
306
307 std::vector<Constant*> Splat;
308
309 for (int i = 0; i < VectorWidth; i++)
310 Splat.push_back (Builder.getInt32(0));
311
312 Constant *SplatVector = ConstantVector::get(Splat);
313
314 return Builder.CreateShuffleVector(Vector, Vector, SplatVector);
315}
316
317Value *BlockGenerator::getOperand(const Value *OldOperand, ValueMapT &BBMap,
318 ValueMapT *VectorMap) {
319 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
320
321 if (!OpInst)
322 return const_cast<Value*>(OldOperand);
323
324 if (VectorMap && VectorMap->count(OldOperand))
325 return (*VectorMap)[OldOperand];
326
327 // IVS and Parameters.
328 if (VMap.count(OldOperand)) {
329 Value *NewOperand = VMap[OldOperand];
330
331 // Insert a cast if types are different
332 if (OldOperand->getType()->getScalarSizeInBits()
333 < NewOperand->getType()->getScalarSizeInBits())
334 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
335 OldOperand->getType());
336
337 return NewOperand;
338 }
339
340 // Instructions calculated in the current BB.
341 if (BBMap.count(OldOperand)) {
342 return BBMap[OldOperand];
343 }
344
345 // Ignore instructions that are referencing ops in the old BB. These
346 // instructions are unused. They where replace by new ones during
347 // createIndependentBlocks().
348 if (getRegion().contains(OpInst->getParent()))
349 return NULL;
350
351 return const_cast<Value*>(OldOperand);
352}
353
354Type *BlockGenerator::getVectorPtrTy(const Value *Val, int VectorWidth) {
355 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
356 assert(PointerTy && "PointerType expected");
357
358 Type *ScalarType = PointerTy->getElementType();
359 VectorType *VectorType = VectorType::get(ScalarType, VectorWidth);
360
361 return PointerType::getUnqual(VectorType);
362}
363
364Value *BlockGenerator::generateStrideOneLoad(const LoadInst *Load,
365 ValueMapT &BBMap, int Size) {
366 const Value *Pointer = Load->getPointerOperand();
367 Type *VectorPtrType = getVectorPtrTy(Pointer, Size);
368 Value *NewPointer = getOperand(Pointer, BBMap);
369 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
370 "vector_ptr");
371 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
372 Load->getName() + "_p_vec_full");
373 if (!Aligned)
374 VecLoad->setAlignment(8);
375
376 return VecLoad;
377}
378
379Value *BlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
380 ValueMapT &BBMap, int Size) {
381 const Value *Pointer = Load->getPointerOperand();
382 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
383 Value *NewPointer = getOperand(Pointer, BBMap);
384 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
385 Load->getName() + "_p_vec_p");
386 LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
387 Load->getName() + "_p_splat_one");
388
389 if (!Aligned)
390 ScalarLoad->setAlignment(8);
391
Tobias Grossere5b423252012-01-24 16:42:25 +0000392 Constant *SplatVector =
393 Constant::getNullValue(VectorType::get(Builder.getInt32Ty(), Size));
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000394
395 Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
396 SplatVector,
397 Load->getName()
398 + "_p_splat");
399 return VectorLoad;
400}
401
402Value *BlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
403 VectorValueMapT &ScalarMaps,
404 int Size) {
405 const Value *Pointer = Load->getPointerOperand();
406 VectorType *VectorType = VectorType::get(
407 dyn_cast<PointerType>(Pointer->getType())->getElementType(), Size);
408
409 Value *Vector = UndefValue::get(VectorType);
410
411 for (int i = 0; i < Size; i++) {
412 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
413 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
414 Load->getName() + "_p_scalar_");
415 Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
416 Builder.getInt32(i),
417 Load->getName() + "_p_vec_");
418 }
419
420 return Vector;
421}
422
423Value *BlockGenerator::islAffToValue(__isl_take isl_aff *Aff,
424 IslPwAffUserInfo *UserInfo) {
425 assert(isl_aff_is_cst(Aff) && "Only constant access functions supported");
426
427 IRBuilder<> *Builder = UserInfo->Builder;
428
429 isl_int OffsetIsl;
430 mpz_t OffsetMPZ;
431
432 isl_int_init(OffsetIsl);
433 mpz_init(OffsetMPZ);
434 isl_aff_get_constant(Aff, &OffsetIsl);
435 isl_int_get_gmp(OffsetIsl, OffsetMPZ);
436
437 Value *OffsetValue = NULL;
438 APInt Offset = APInt_from_MPZ(OffsetMPZ);
439 OffsetValue = ConstantInt::get(Builder->getContext(), Offset);
440
441 mpz_clear(OffsetMPZ);
442 isl_int_clear(OffsetIsl);
443 isl_aff_free(Aff);
444
445 return OffsetValue;
446}
447
448int BlockGenerator::mergeIslAffValues(__isl_take isl_set *Set,
449 __isl_take isl_aff *Aff, void *User) {
450 IslPwAffUserInfo *UserInfo = (IslPwAffUserInfo *)User;
451
452 assert((UserInfo->Result == NULL) && "Result is already set."
453 "Currently only single isl_aff is supported");
454 assert(isl_set_plain_is_universe(Set)
455 && "Code generation failed because the set is not universe");
456
457 UserInfo->Result = islAffToValue(Aff, UserInfo);
458
459 isl_set_free(Set);
460 return 0;
461}
462
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000463Value *BlockGenerator::islPwAffToValue(__isl_take isl_pw_aff *PwAff) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000464 IslPwAffUserInfo UserInfo;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000465 UserInfo.Result = NULL;
466 UserInfo.Builder = &Builder;
467 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &UserInfo);
468 assert(UserInfo.Result && "Code generation for isl_pw_aff failed");
469
470 isl_pw_aff_free(PwAff);
471 return UserInfo.Result;
472}
473
474std::vector <Value*> BlockGenerator::getMemoryAccessIndex(
475 __isl_keep isl_map *AccessRelation, Value *BaseAddress) {
476 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
477 && "Only single dimensional access functions supported");
478
479 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000480 Value *OffsetValue = islPwAffToValue(PwAff);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000481
482 PointerType *BaseAddressType = dyn_cast<PointerType>(
483 BaseAddress->getType());
484 Type *ArrayTy = BaseAddressType->getElementType();
485 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
486 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
487
488 std::vector<Value*> IndexArray;
489 Value *NullValue = Constant::getNullValue(ArrayElementType);
490 IndexArray.push_back(NullValue);
491 IndexArray.push_back(OffsetValue);
492 return IndexArray;
493}
494
495Value *BlockGenerator::getNewAccessOperand(
496 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, const Value
497 *OldOperand, ValueMapT &BBMap) {
498 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
499 BaseAddress);
500 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
501 "p_newarrayidx_");
502 return NewOperand;
503}
504
505Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
506 const Value *Pointer,
507 ValueMapT &BBMap ) {
508 MemoryAccess &Access = Statement.getAccessFor(Inst);
509 isl_map *CurrentAccessRelation = Access.getAccessRelation();
510 isl_map *NewAccessRelation = Access.getNewAccessRelation();
511
512 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
513 && "Current and new access function use different spaces");
514
515 Value *NewPointer;
516
517 if (!NewAccessRelation) {
518 NewPointer = getOperand(Pointer, BBMap);
519 } else {
520 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
521 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
522 BBMap);
523 }
524
525 isl_map_free(CurrentAccessRelation);
526 isl_map_free(NewAccessRelation);
527 return NewPointer;
528}
529
530Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
531 ValueMapT &BBMap) {
532 const Value *Pointer = Load->getPointerOperand();
533 const Instruction *Inst = dyn_cast<Instruction>(Load);
534 Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap);
535 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
536 Load->getName() + "_p_scalar_");
537 return ScalarLoad;
538}
539
540void BlockGenerator::generateLoad(const LoadInst *Load, ValueMapT &VectorMap,
541 VectorValueMapT &ScalarMaps,
542 int VectorWidth) {
543 if (ScalarMaps.size() == 1) {
544 ScalarMaps[0][Load] = generateScalarLoad(Load, ScalarMaps[0]);
545 return;
546 }
547
548 Value *NewLoad;
549
550 MemoryAccess &Access = Statement.getAccessFor(Load);
551
552 assert(ScatteringDomain && "No scattering domain available");
553
554 if (Access.isStrideZero(isl_set_copy(ScatteringDomain)))
555 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0], VectorWidth);
556 else if (Access.isStrideOne(isl_set_copy(ScatteringDomain)))
557 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0], VectorWidth);
558 else
559 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps, VectorWidth);
560
561 VectorMap[Load] = NewLoad;
562}
563
564void BlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
565 ValueMapT &BBMap, ValueMapT &VectorMap,
566 int VectorDimension, int VectorWidth) {
567 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
568 NewOperand = makeVectorOperand(NewOperand, VectorWidth);
569
570 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
571
572 const CastInst *Cast = dyn_cast<CastInst>(Inst);
573 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
574 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
575}
576
577void BlockGenerator::copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
578 ValueMapT &VectorMap, int VectorDimension,
579 int VectorWidth) {
580 Value *OpZero = Inst->getOperand(0);
581 Value *OpOne = Inst->getOperand(1);
582
583 Value *NewOpZero, *NewOpOne;
584 NewOpZero = getOperand(OpZero, BBMap, &VectorMap);
585 NewOpOne = getOperand(OpOne, BBMap, &VectorMap);
586
587 NewOpZero = makeVectorOperand(NewOpZero, VectorWidth);
588 NewOpOne = makeVectorOperand(NewOpOne, VectorWidth);
589
590 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
591 NewOpOne,
592 Inst->getName() + "p_vec");
593 VectorMap[Inst] = NewInst;
594}
595
596void BlockGenerator::copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
597 ValueMapT &VectorMap,
598 VectorValueMapT &ScalarMaps,
599 int VectorDimension, int VectorWidth) {
600 // In vector mode we only generate a store for the first dimension.
601 if (VectorDimension > 0)
602 return;
603
604 MemoryAccess &Access = Statement.getAccessFor(Store);
605
606 assert(ScatteringDomain && "No scattering domain available");
607
608 const Value *Pointer = Store->getPointerOperand();
609 Value *Vector = getOperand(Store->getValueOperand(), BBMap, &VectorMap);
610
611 if (Access.isStrideOne(isl_set_copy(ScatteringDomain))) {
612 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
613 Value *NewPointer = getOperand(Pointer, BBMap, &VectorMap);
614
615 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
616 "vector_ptr");
617 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
618
619 if (!Aligned)
620 Store->setAlignment(8);
621 } else {
622 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
623 Value *Scalar = Builder.CreateExtractElement(Vector,
624 Builder.getInt32(i));
625 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
626 Builder.CreateStore(Scalar, NewPointer);
627 }
628 }
629}
630
631void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
632 Instruction *NewInst = Inst->clone();
633
634 // Replace old operands with the new ones.
635 for (Instruction::const_op_iterator OI = Inst->op_begin(),
636 OE = Inst->op_end(); OI != OE; ++OI) {
637 Value *OldOperand = *OI;
638 Value *NewOperand = getOperand(OldOperand, BBMap);
639
640 if (!NewOperand) {
641 assert(!isa<StoreInst>(NewInst)
642 && "Store instructions are always needed!");
643 delete NewInst;
644 return;
645 }
646
647 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
648 }
649
650 Builder.Insert(NewInst);
651 BBMap[Inst] = NewInst;
652
653 if (!NewInst->getType()->isVoidTy())
654 NewInst->setName("p_" + Inst->getName());
655}
656
657bool BlockGenerator::hasVectorOperands(const Instruction *Inst,
658 ValueMapT &VectorMap) {
659 for (Instruction::const_op_iterator OI = Inst->op_begin(),
660 OE = Inst->op_end(); OI != OE; ++OI)
661 if (VectorMap.count(*OI))
662 return true;
663 return false;
664}
665
666int BlockGenerator::getVectorSize() {
667 return ValueMaps.size();
668}
669
670bool BlockGenerator::isVectorBlock() {
671 return getVectorSize() > 1;
672}
673
674void BlockGenerator::copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
675 ValueMapT &VectorMap,
676 VectorValueMapT &ScalarMaps,
677 int VectorDimension, int VectorWidth) {
678 // Terminator instructions control the control flow. They are explicitally
679 // expressed in the clast and do not need to be copied.
680 if (Inst->isTerminator())
681 return;
682
683 if (isVectorBlock()) {
684 // If this instruction is already in the vectorMap, a vector instruction
685 // was already issued, that calculates the values of all dimensions. No
686 // need to create any more instructions.
687 if (VectorMap.count(Inst))
688 return;
689 }
690
691 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
692 generateLoad(Load, VectorMap, ScalarMaps, VectorWidth);
693 return;
694 }
695
696 if (isVectorBlock() && hasVectorOperands(Inst, VectorMap)) {
697 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
698 copyUnaryInst(UnaryInst, BBMap, VectorMap, VectorDimension, VectorWidth);
699 else if
700 (const BinaryOperator *BinaryInst = dyn_cast<BinaryOperator>(Inst))
701 copyBinInst(BinaryInst, BBMap, VectorMap, VectorDimension, VectorWidth);
702 else if (const StoreInst *Store = dyn_cast<StoreInst>(Inst))
703 copyVectorStore(Store, BBMap, VectorMap, ScalarMaps, VectorDimension,
704 VectorWidth);
705 else
706 llvm_unreachable("Cannot issue vector code for this instruction");
707
708 return;
709 }
710
711 copyInstScalar(Inst, BBMap);
712}
713
Tobias Grosser8412cda2012-03-02 11:26:55 +0000714void BlockGenerator::copyBB() {
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000715 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000716 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
717 Builder.GetInsertPoint(), P);
Tobias Grosserb61e6312012-02-15 09:58:46 +0000718 CopyBB->setName("polly.stmt." + BB->getName());
Tobias Grosser0ac92142012-02-14 14:02:27 +0000719 Builder.SetInsertPoint(CopyBB->begin());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000720
721 // Create two maps that store the mapping from the original instructions of
722 // the old basic block to their copies in the new basic block. Those maps
723 // are basic block local.
724 //
725 // As vector code generation is supported there is one map for scalar values
726 // and one for vector values.
727 //
728 // In case we just do scalar code generation, the vectorMap is not used and
729 // the scalarMap has just one dimension, which contains the mapping.
730 //
731 // In case vector code generation is done, an instruction may either appear
732 // in the vector map once (as it is calculating >vectorwidth< values at a
733 // time. Or (if the values are calculated using scalar operations), it
734 // appears once in every dimension of the scalarMap.
735 VectorValueMapT ScalarBlockMap(getVectorSize());
736 ValueMapT VectorBlockMap;
737
738 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
739 II != IE; ++II)
740 for (int i = 0; i < getVectorSize(); i++) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000741 copyInstruction(II, ScalarBlockMap[i], VectorBlockMap,
742 ScalarBlockMap, i, getVectorSize());
743 }
744}
745
Tobias Grosser75805372011-04-29 06:27:02 +0000746/// Class to generate LLVM-IR that calculates the value of a clast_expr.
747class ClastExpCodeGen {
748 IRBuilder<> &Builder;
749 const CharMapT *IVS;
750
Tobias Grosserbb137e32012-01-24 16:42:28 +0000751 Value *codegen(const clast_name *e, Type *Ty);
752 Value *codegen(const clast_term *e, Type *Ty);
753 Value *codegen(const clast_binary *e, Type *Ty);
754 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000755public:
756
757 // A generator for clast expressions.
758 //
759 // @param B The IRBuilder that defines where the code to calculate the
760 // clast expressions should be inserted.
761 // @param IVMAP A Map that translates strings describing the induction
762 // variables to the Values* that represent these variables
763 // on the LLVM side.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000764 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000765
766 // Generates code to calculate a given clast expression.
767 //
768 // @param e The expression to calculate.
769 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000770 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000771
772 // @brief Reset the CharMap.
773 //
774 // This function is called to reset the CharMap to new one, while generating
775 // OpenMP code.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000776 void setIVS(CharMapT *IVSNew);
777};
778
779Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
780 CharMapT::const_iterator I = IVS->find(e->name);
781
782 assert(I != IVS->end() && "Clast name not found");
783
784 return Builder.CreateSExtOrBitCast(I->second, Ty);
785}
786
787Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
788 APInt a = APInt_from_MPZ(e->val);
789
790 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
791 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
792
793 if (!e->var)
794 return ConstOne;
795
796 Value *var = codegen(e->var, Ty);
797 return Builder.CreateMul(ConstOne, var);
798}
799
800Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
801 Value *LHS = codegen(e->LHS, Ty);
802
803 APInt RHS_AP = APInt_from_MPZ(e->RHS);
804
805 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
806 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
807
808 switch (e->type) {
809 case clast_bin_mod:
810 return Builder.CreateSRem(LHS, RHS);
811 case clast_bin_fdiv:
812 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000813 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000814 Value *One = ConstantInt::get(Ty, 1);
815 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000816 Value *Sum1 = Builder.CreateSub(LHS, RHS);
817 Value *Sum2 = Builder.CreateAdd(Sum1, One);
818 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
819 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
820 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000821 }
822 case clast_bin_cdiv:
823 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000824 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
825 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000826 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000827 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
828 Value *Sum2 = Builder.CreateSub(Sum1, One);
829 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
830 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
831 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000832 }
833 case clast_bin_div:
834 return Builder.CreateSDiv(LHS, RHS);
835 };
836
837 llvm_unreachable("Unknown clast binary expression type");
838}
839
840Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
841 assert(( r->type == clast_red_min
842 || r->type == clast_red_max
843 || r->type == clast_red_sum)
844 && "Clast reduction type not supported");
845 Value *old = codegen(r->elts[0], Ty);
846
847 for (int i=1; i < r->n; ++i) {
848 Value *exprValue = codegen(r->elts[i], Ty);
849
850 switch (r->type) {
851 case clast_red_min:
852 {
853 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
854 old = Builder.CreateSelect(cmp, old, exprValue);
855 break;
856 }
857 case clast_red_max:
858 {
859 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
860 old = Builder.CreateSelect(cmp, old, exprValue);
861 break;
862 }
863 case clast_red_sum:
864 old = Builder.CreateAdd(old, exprValue);
865 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000866 }
Tobias Grosser75805372011-04-29 06:27:02 +0000867 }
868
Tobias Grosserbb137e32012-01-24 16:42:28 +0000869 return old;
870}
871
872ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap)
873 : Builder(B), IVS(IVMap) {}
874
875Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
876 switch(e->type) {
877 case clast_expr_name:
878 return codegen((const clast_name *)e, Ty);
879 case clast_expr_term:
880 return codegen((const clast_term *)e, Ty);
881 case clast_expr_bin:
882 return codegen((const clast_binary *)e, Ty);
883 case clast_expr_red:
884 return codegen((const clast_reduction *)e, Ty);
885 }
886
887 llvm_unreachable("Unknown clast expression!");
888}
889
890void ClastExpCodeGen::setIVS(CharMapT *IVSNew) {
891 IVS = IVSNew;
892}
Tobias Grosser75805372011-04-29 06:27:02 +0000893
894class ClastStmtCodeGen {
895 // The Scop we code generate.
896 Scop *S;
897 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000898 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000899 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000900 Dependences *DP;
901 TargetData *TD;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000902 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000903
904 // The Builder specifies the current location to code generate at.
905 IRBuilder<> &Builder;
906
907 // Map the Values from the old code to their counterparts in the new code.
908 ValueMapT ValueMap;
909
910 // clastVars maps from the textual representation of a clast variable to its
911 // current *Value. clast variables are scheduling variables, original
912 // induction variables or parameters. They are used either in loop bounds or
913 // to define the statement instance that is executed.
914 //
915 // for (s = 0; s < n + 3; ++i)
916 // for (t = s; t < m; ++j)
917 // Stmt(i = s + 3 * m, j = t);
918 //
919 // {s,t,i,j,n,m} is the set of clast variables in this clast.
920 CharMapT *clastVars;
921
922 // Codegenerator for clast expressions.
923 ClastExpCodeGen ExpGen;
924
925 // Do we currently generate parallel code?
926 bool parallelCodeGeneration;
927
928 std::vector<std::string> parallelLoops;
929
930public:
931
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000932 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +0000933
934 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000935 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000936
937 void codegen(const clast_assignment *a, ScopStmt *Statement,
938 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000939 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000940
941 void codegenSubstitutions(const clast_stmt *Assignment,
942 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000943 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000944
945 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000946 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000947
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000948 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000949
950 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000951 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000952 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000953
Tobias Grosser75805372011-04-29 06:27:02 +0000954 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000955 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +0000956
957 /// @brief Add values to the OpenMP structure.
958 ///
959 /// Create the subfunction structure and add the values from the list.
960 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000961 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000962
963 /// @brief Create OpenMP structure values.
964 ///
965 /// Create a list of values that has to be stored into the subfuncition
966 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000967 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000968
969 /// @brief Extract the values from the subfunction parameter.
970 ///
971 /// Extract the values from the subfunction parameter and update the clast
972 /// variables to point to the new values.
973 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
974 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000975 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +0000976
977 /// @brief Add body to the subfunction.
978 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
979 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000980 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +0000981
982 /// @brief Create an OpenMP parallel for loop.
983 ///
984 /// This loop reflects a loop as if it would have been created by an OpenMP
985 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000986 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000987
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000988 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000989
990 /// @brief Get the number of loop iterations for this loop.
991 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000992 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000993
994 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000995 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000996
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000997 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000998
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000999 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +00001000
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001001 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +00001002
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001003 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +00001004
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001005 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +00001006
1007 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001008 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001009
1010 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001011 ScopDetection *sd, Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001012 IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +00001013};
1014}
1015
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001016const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1017 return parallelLoops;
1018}
1019
1020void ClastStmtCodeGen::codegen(const clast_assignment *a) {
1021 Value *V= ExpGen.codegen(a->RHS, TD->getIntPtrType(Builder.getContext()));
1022 (*clastVars)[a->LHS] = V;
1023}
1024
1025void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1026 unsigned Dimension, int vectorDim,
1027 std::vector<ValueMapT> *VectorVMap) {
1028 Value *RHS = ExpGen.codegen(a->RHS,
1029 TD->getIntPtrType(Builder.getContext()));
1030
1031 assert(!a->LHS && "Statement assignments do not have left hand side");
1032 const PHINode *PN;
1033 PN = Statement->getInductionVariableForDimension(Dimension);
1034 const Value *V = PN;
1035
1036 if (VectorVMap)
1037 (*VectorVMap)[vectorDim][V] = RHS;
1038
1039 ValueMap[V] = RHS;
1040}
1041
1042void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1043 ScopStmt *Statement, int vectorDim,
1044 std::vector<ValueMapT> *VectorVMap) {
1045 int Dimension = 0;
1046
1047 while (Assignment) {
1048 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1049 && "Substitions are expected to be assignments");
1050 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1051 vectorDim, VectorVMap);
1052 Assignment = Assignment->next;
1053 Dimension++;
1054 }
1055}
1056
1057void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1058 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001059 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001060 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001061
1062 if (u->substitutions)
1063 codegenSubstitutions(u->substitutions, Statement);
1064
1065 int vectorDimensions = IVS ? IVS->size() : 1;
1066
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001067 VectorValueMapT VectorMap(vectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001068
1069 if (IVS) {
1070 assert (u->substitutions && "Substitutions expected!");
1071 int i = 0;
1072 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1073 II != IE; ++II) {
1074 (*clastVars)[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001075 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001076 i++;
1077 }
1078 }
1079
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001080 BlockGenerator::generate(Builder, ValueMap, VectorMap, *Statement, Domain, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001081}
1082
1083void ClastStmtCodeGen::codegen(const clast_block *b) {
1084 if (b->body)
1085 codegen(b->body);
1086}
1087
1088void ClastStmtCodeGen::codegenForSequential(const clast_for *f,
1089 Value *LowerBound,
1090 Value *UpperBound) {
1091 APInt Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +00001092 BasicBlock *AfterBB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001093 Type *IntPtrTy;
1094
1095 Stride = APInt_from_MPZ(f->stride);
1096 IntPtrTy = TD->getIntPtrType(Builder.getContext());
1097
1098 // The value of lowerbound and upperbound will be supplied, if this
1099 // function is called while generating OpenMP code. Otherwise get
1100 // the values.
1101 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1102
1103 if (LowerBound == 0) {
1104 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1105 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1106 }
1107
Tobias Grosser0ac92142012-02-14 14:02:27 +00001108 Value *IV = createLoop(&Builder, LowerBound, UpperBound, Stride, DT, P,
1109 &AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001110
1111 // Add loop iv to symbols.
1112 (*clastVars)[f->iterator] = IV;
1113
1114 if (f->body)
1115 codegen(f->body);
1116
1117 // Loop is finished, so remove its iv from the live symbols.
1118 clastVars->erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001119 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001120}
1121
1122Function *ClastStmtCodeGen::addOpenMPSubfunction(Module *M) {
1123 Function *F = Builder.GetInsertBlock()->getParent();
1124 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
1125 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
1126 Function *FN = Function::Create(FT, Function::InternalLinkage,
1127 F->getName() + ".omp_subfn", M);
1128 // Do not run any polly pass on the new function.
1129 SD->markFunctionAsInvalid(FN);
1130
1131 Function::arg_iterator AI = FN->arg_begin();
1132 AI->setName("omp.userContext");
1133
1134 return FN;
1135}
1136
1137Value *ClastStmtCodeGen::addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1138 Function *SubFunction) {
1139 std::vector<Type*> structMembers;
1140
1141 // Create the structure.
1142 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1143 structMembers.push_back(OMPDataVals[i]->getType());
1144
1145 StructType *structTy = StructType::get(Builder.getContext(),
1146 structMembers);
1147 // Store the values into the structure.
1148 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1149 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1150 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1151 Builder.CreateStore(OMPDataVals[i], storeAddr);
1152 }
1153
1154 return structData;
1155}
1156
1157SetVector<Value*> ClastStmtCodeGen::createOpenMPStructValues() {
1158 SetVector<Value*> OMPDataVals;
1159
1160 // Push the clast variables available in the clastVars.
1161 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1162 I != E; I++)
1163 OMPDataVals.insert(I->second);
1164
1165 // Push the base addresses of memory references.
1166 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1167 ScopStmt *Stmt = *SI;
1168 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1169 E = Stmt->memacc_end(); I != E; ++I) {
1170 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1171 OMPDataVals.insert((BaseAddr));
1172 }
1173 }
1174
1175 return OMPDataVals;
1176}
1177
1178void ClastStmtCodeGen::extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1179 SetVector<Value*> OMPDataVals, Value *userContext) {
1180 // Extract the clast variables.
1181 unsigned i = 0;
1182 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1183 I != E; I++) {
1184 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1185 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1186 i++;
1187 }
1188
1189 // Extract the base addresses of memory references.
1190 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1191 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1192 Value *baseAddr = OMPDataVals[j];
1193 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1194 }
1195}
1196
1197void ClastStmtCodeGen::addOpenMPSubfunctionBody(Function *FN,
1198 const clast_for *f,
1199 Value *structData,
1200 SetVector<Value*> OMPDataVals) {
1201 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1202 LLVMContext &Context = FN->getContext();
1203 IntegerType *intPtrTy = TD->getIntPtrType(Context);
1204
1205 // Store the previous basic block.
Tobias Grosser0ac92142012-02-14 14:02:27 +00001206 BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001207 BasicBlock *PrevBB = Builder.GetInsertBlock();
1208
1209 // Create basic blocks.
1210 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1211 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1212 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1213 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1214 FN);
1215
1216 DT->addNewBlock(HeaderBB, PrevBB);
1217 DT->addNewBlock(ExitBB, HeaderBB);
1218 DT->addNewBlock(checkNextBB, HeaderBB);
1219 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1220
1221 // Fill up basic block HeaderBB.
1222 Builder.SetInsertPoint(HeaderBB);
1223 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1224 "omp.lowerBoundPtr");
1225 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1226 "omp.upperBoundPtr");
1227 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1228 structData->getType(),
1229 "omp.userContext");
1230
1231 CharMapT clastVarsOMP;
1232 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1233
1234 Builder.CreateBr(checkNextBB);
1235
1236 // Add code to check if another set of iterations will be executed.
1237 Builder.SetInsertPoint(checkNextBB);
1238 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1239 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1240 lowerBoundPtr, upperBoundPtr);
1241 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1242 "omp.hasNextScheduleBlock");
1243 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1244
1245 // Add code to to load the iv bounds for this set of iterations.
1246 Builder.SetInsertPoint(loadIVBoundsBB);
1247 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1248 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1249
1250 // Subtract one as the upper bound provided by openmp is a < comparison
1251 // whereas the codegenForSequential function creates a <= comparison.
1252 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1253 "omp.upperBoundAdjusted");
1254
1255 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1256 CharMapT *oldClastVars = clastVars;
1257 clastVars = &clastVarsOMP;
1258 ExpGen.setIVS(&clastVarsOMP);
1259
Tobias Grosser0ac92142012-02-14 14:02:27 +00001260 Builder.CreateBr(checkNextBB);
1261 Builder.SetInsertPoint(--Builder.GetInsertPoint());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001262 codegenForSequential(f, lowerBound, upperBound);
1263
1264 // Restore the old clastVars.
1265 clastVars = oldClastVars;
1266 ExpGen.setIVS(oldClastVars);
1267
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001268 // Add code to terminate this openmp subfunction.
1269 Builder.SetInsertPoint(ExitBB);
1270 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1271 Builder.CreateCall(endnowaitFunction);
1272 Builder.CreateRetVoid();
1273
Tobias Grosser0ac92142012-02-14 14:02:27 +00001274 // Restore the previous insert point.
1275 Builder.SetInsertPoint(PrevInsertPoint);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001276}
1277
1278void ClastStmtCodeGen::codegenForOpenMP(const clast_for *f) {
1279 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1280 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
1281
1282 Function *SubFunction = addOpenMPSubfunction(M);
1283 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1284 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1285
1286 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1287
1288 // Create call for GOMP_parallel_loop_runtime_start.
1289 Value *subfunctionParam = Builder.CreateBitCast(structData,
1290 Builder.getInt8PtrTy(),
1291 "omp_data");
1292
1293 Value *numberOfThreads = Builder.getInt32(0);
1294 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1295 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1296
1297 // Add one as the upper bound provided by openmp is a < comparison
1298 // whereas the codegenForSequential function creates a <= comparison.
1299 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1300 APInt APStride = APInt_from_MPZ(f->stride);
1301 Value *stride = ConstantInt::get(intPtrTy,
1302 APStride.zext(intPtrTy->getBitWidth()));
1303
1304 SmallVector<Value *, 6> Arguments;
1305 Arguments.push_back(SubFunction);
1306 Arguments.push_back(subfunctionParam);
1307 Arguments.push_back(numberOfThreads);
1308 Arguments.push_back(lowerBound);
1309 Arguments.push_back(upperBound);
1310 Arguments.push_back(stride);
1311
1312 Function *parallelStartFunction =
1313 M->getFunction("GOMP_parallel_loop_runtime_start");
1314 Builder.CreateCall(parallelStartFunction, Arguments);
1315
1316 // Create call to the subfunction.
1317 Builder.CreateCall(SubFunction, subfunctionParam);
1318
1319 // Create call for GOMP_parallel_end.
1320 Function *FN = M->getFunction("GOMP_parallel_end");
1321 Builder.CreateCall(FN);
1322}
1323
1324bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1325 const clast_stmt *stmt = f->body;
1326
1327 while (stmt) {
1328 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1329 return false;
1330
1331 stmt = stmt->next;
1332 }
1333
1334 return true;
1335}
1336
1337int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1338 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1339 isl_set *tmp = isl_set_copy(loopDomain);
1340
1341 // Calculate a map similar to the identity map, but with the last input
1342 // and output dimension not related.
1343 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1344 isl_space *Space = isl_set_get_space(loopDomain);
1345 Space = isl_space_drop_outputs(Space,
1346 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1347 Space = isl_space_map_from_set(Space);
1348 isl_map *identity = isl_map_identity(Space);
1349 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1350 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1351
1352 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1353 map = isl_map_intersect(map, identity);
1354
1355 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1356 isl_map *lexmin = isl_map_lexmin(map);
1357 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1358
1359 isl_set *elements = isl_map_range(sub);
1360
1361 if (!isl_set_is_singleton(elements)) {
1362 isl_set_free(elements);
1363 return -1;
1364 }
1365
1366 isl_point *p = isl_set_sample_point(elements);
1367
1368 isl_int v;
1369 isl_int_init(v);
1370 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1371 int numberIterations = isl_int_get_si(v);
1372 isl_int_clear(v);
1373 isl_point_free(p);
1374
1375 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1376}
1377
1378void ClastStmtCodeGen::codegenForVector(const clast_for *f) {
1379 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1380 int vectorWidth = getNumberOfIterations(f);
1381
1382 Value *LB = ExpGen.codegen(f->LB,
1383 TD->getIntPtrType(Builder.getContext()));
1384
1385 APInt Stride = APInt_from_MPZ(f->stride);
1386 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1387 Stride = Stride.zext(LoopIVType->getBitWidth());
1388 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1389
1390 std::vector<Value*> IVS(vectorWidth);
1391 IVS[0] = LB;
1392
1393 for (int i = 1; i < vectorWidth; i++)
1394 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1395
1396 isl_set *scatteringDomain =
1397 isl_set_copy(isl_set_from_cloog_domain(f->domain));
1398
1399 // Add loop iv to symbols.
1400 (*clastVars)[f->iterator] = LB;
1401
1402 const clast_stmt *stmt = f->body;
1403
1404 while (stmt) {
1405 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1406 scatteringDomain);
1407 stmt = stmt->next;
1408 }
1409
1410 // Loop is finished, so remove its iv from the live symbols.
1411 isl_set_free(scatteringDomain);
1412 clastVars->erase(f->iterator);
1413}
1414
1415void ClastStmtCodeGen::codegen(const clast_for *f) {
Tobias Grosserce3f5372012-03-02 11:26:42 +00001416 if ((Vector || OpenMP) && DP->isParallelFor(f)) {
1417 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
1418 && (getNumberOfIterations(f) <= 16)) {
1419 codegenForVector(f);
1420 return;
1421 }
1422
1423 if (OpenMP && !parallelCodeGeneration) {
1424 parallelCodeGeneration = true;
1425 parallelLoops.push_back(f->iterator);
1426 codegenForOpenMP(f);
1427 parallelCodeGeneration = false;
1428 return;
1429 }
1430 }
1431
1432 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001433}
1434
1435Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
1436 Value *LHS = ExpGen.codegen(eq->LHS,
1437 TD->getIntPtrType(Builder.getContext()));
1438 Value *RHS = ExpGen.codegen(eq->RHS,
1439 TD->getIntPtrType(Builder.getContext()));
1440 CmpInst::Predicate P;
1441
1442 if (eq->sign == 0)
1443 P = ICmpInst::ICMP_EQ;
1444 else if (eq->sign > 0)
1445 P = ICmpInst::ICMP_SGE;
1446 else
1447 P = ICmpInst::ICMP_SLE;
1448
1449 return Builder.CreateICmp(P, LHS, RHS);
1450}
1451
1452void ClastStmtCodeGen::codegen(const clast_guard *g) {
1453 Function *F = Builder.GetInsertBlock()->getParent();
1454 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +00001455
1456 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1457 Builder.GetInsertPoint(), P);
1458 CondBB->setName("polly.cond");
1459 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1460 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001461 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001462
1463 DT->addNewBlock(ThenBB, CondBB);
1464 DT->changeImmediateDominator(MergeBB, CondBB);
1465
1466 CondBB->getTerminator()->eraseFromParent();
1467
1468 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001469
1470 Value *Predicate = codegen(&(g->eq[0]));
1471
1472 for (int i = 1; i < g->n; ++i) {
1473 Value *TmpPredicate = codegen(&(g->eq[i]));
1474 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1475 }
1476
1477 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1478 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001479 Builder.CreateBr(MergeBB);
1480 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001481
1482 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +00001483
1484 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001485}
1486
1487void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1488 if (CLAST_STMT_IS_A(stmt, stmt_root))
1489 assert(false && "No second root statement expected");
1490 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1491 codegen((const clast_assignment *)stmt);
1492 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1493 codegen((const clast_user_stmt *)stmt);
1494 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1495 codegen((const clast_block *)stmt);
1496 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1497 codegen((const clast_for *)stmt);
1498 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1499 codegen((const clast_guard *)stmt);
1500
1501 if (stmt->next)
1502 codegen(stmt->next);
1503}
1504
1505void ClastStmtCodeGen::addParameters(const CloogNames *names) {
1506 SCEVExpander Rewriter(SE, "polly");
1507
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001508 int i = 0;
1509 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1510 PI != PE; ++PI) {
1511 assert(i < names->nb_parameters && "Not enough parameter names");
1512
1513 const SCEV *Param = *PI;
1514 Type *Ty = Param->getType();
1515
1516 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1517 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1518 (*clastVars)[names->parameters[i]] = V;
1519
1520 ++i;
1521 }
1522}
1523
1524void ClastStmtCodeGen::codegen(const clast_root *r) {
1525 clastVars = new CharMapT();
1526 addParameters(r->names);
1527 ExpGen.setIVS(clastVars);
1528
1529 parallelCodeGeneration = false;
1530
1531 const clast_stmt *stmt = (const clast_stmt*) r;
1532 if (stmt->next)
1533 codegen(stmt->next);
1534
1535 delete clastVars;
1536}
1537
1538ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, ScalarEvolution &se,
1539 DominatorTree *dt, ScopDetection *sd,
1540 Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001541 IRBuilder<> &B, Pass *P) :
1542 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), P(P), Builder(B),
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001543 ExpGen(Builder, NULL) {}
1544
Tobias Grosser75805372011-04-29 06:27:02 +00001545namespace {
1546class CodeGeneration : public ScopPass {
1547 Region *region;
1548 Scop *S;
1549 DominatorTree *DT;
1550 ScalarEvolution *SE;
1551 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001552 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001553 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001554
1555 std::vector<std::string> parallelLoops;
1556
1557 public:
1558 static char ID;
1559
1560 CodeGeneration() : ScopPass(ID) {}
1561
Tobias Grosserb1c95992012-02-12 12:09:27 +00001562 // Add the declarations needed by the OpenMP function calls that we insert in
1563 // OpenMP mode.
1564 void addOpenMPDeclarations(Module *M)
Tobias Grosser75805372011-04-29 06:27:02 +00001565 {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001566 IRBuilder<> Builder(M->getContext());
1567 IntegerType *LongTy = TD->getIntPtrType(M->getContext());
1568
1569 llvm::GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosser75805372011-04-29 06:27:02 +00001570
1571 if (!M->getFunction("GOMP_parallel_end")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001572 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1573 Function::Create(Ty, Linkage, "GOMP_parallel_end", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001574 }
1575
1576 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001577 Type *Params[] = {
1578 PointerType::getUnqual(FunctionType::get(Builder.getVoidTy(),
1579 Builder.getInt8PtrTy(),
1580 false)),
1581 Builder.getInt8PtrTy(),
1582 Builder.getInt32Ty(),
1583 LongTy,
1584 LongTy,
1585 LongTy,
1586 };
Tobias Grosser75805372011-04-29 06:27:02 +00001587
Tobias Grosserd855cc52012-02-12 12:09:32 +00001588 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
1589 Function::Create(Ty, Linkage, "GOMP_parallel_loop_runtime_start", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001590 }
1591
1592 if (!M->getFunction("GOMP_loop_runtime_next")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001593 PointerType *LongPtrTy = PointerType::getUnqual(LongTy);
1594 Type *Params[] = {
1595 LongPtrTy,
1596 LongPtrTy,
1597 };
Tobias Grosser75805372011-04-29 06:27:02 +00001598
Tobias Grosserd855cc52012-02-12 12:09:32 +00001599 FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
1600 Function::Create(Ty, Linkage, "GOMP_loop_runtime_next", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001601 }
1602
1603 if (!M->getFunction("GOMP_loop_end_nowait")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001604 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1605 Function::Create(Ty, Linkage, "GOMP_loop_end_nowait", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001606 }
1607 }
1608
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001609 // Split the entry edge of the region and generate a new basic block on this
1610 // edge. This function also updates ScopInfo and RegionInfo.
1611 //
1612 // @param region The region where the entry edge will be splitted.
1613 BasicBlock *splitEdgeAdvanced(Region *region) {
1614 BasicBlock *newBlock;
1615 BasicBlock *splitBlock;
1616
1617 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1618
1619 if (DT->dominates(region->getEntry(), newBlock)) {
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001620 BasicBlock *OldBlock = region->getEntry();
1621 std::string OldName = OldBlock->getName();
1622
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001623 // Update ScopInfo.
1624 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
Tobias Grosserf12cea42012-02-15 09:58:53 +00001625 if ((*SI)->getBasicBlock() == OldBlock) {
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001626 (*SI)->setBasicBlock(newBlock);
1627 break;
1628 }
1629
1630 // Update RegionInfo.
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001631 splitBlock = OldBlock;
1632 OldBlock->setName("polly.split");
1633 newBlock->setName(OldName);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001634 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001635 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001636 } else {
1637 RI->setRegionFor(newBlock, region->getParent());
1638 splitBlock = newBlock;
1639 }
1640
1641 return splitBlock;
1642 }
1643
1644 // Create a split block that branches either to the old code or to a new basic
1645 // block where the new code can be inserted.
1646 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001647 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001648 // the new code can be generated.
1649 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001650 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1651 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001652
Tobias Grosserbd608a82012-02-12 12:09:41 +00001653 SplitBlock = splitEdgeAdvanced(region);
1654 SplitBlock->setName("polly.split_new_and_old");
1655 Function *F = SplitBlock->getParent();
1656 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1657 SplitBlock->getTerminator()->eraseFromParent();
1658 Builder->SetInsertPoint(SplitBlock);
1659 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1660 DT->addNewBlock(StartBlock, SplitBlock);
1661 Builder->SetInsertPoint(StartBlock);
1662 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001663 }
1664
1665 // Merge the control flow of the newly generated code with the existing code.
1666 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001667 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001668 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001669 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001670 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001671 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1672 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001673 Region *R = region;
1674
1675 if (R->getExit()->getSinglePredecessor())
1676 // No splitEdge required. A block with a single predecessor cannot have
1677 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001678 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001679 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001680 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001681 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1682 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001683 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001684 }
1685
Tobias Grosserbd608a82012-02-12 12:09:41 +00001686 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +00001687 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001688
Tobias Grosserbd608a82012-02-12 12:09:41 +00001689 if (DT->dominates(SplitBlock, MergeBlock))
1690 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001691 }
1692
Tobias Grosser75805372011-04-29 06:27:02 +00001693 bool runOnScop(Scop &scop) {
1694 S = &scop;
1695 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001696 DT = &getAnalysis<DominatorTree>();
1697 Dependences *DP = &getAnalysis<Dependences>();
1698 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001699 SD = &getAnalysis<ScopDetection>();
1700 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001701 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001702
1703 parallelLoops.clear();
1704
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001705 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001706
Tobias Grosserb1c95992012-02-12 12:09:27 +00001707 Module *M = region->getEntry()->getParent()->getParent();
1708
Tobias Grosserd855cc52012-02-12 12:09:32 +00001709 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001710
Tobias Grosser5772e652012-02-01 14:23:33 +00001711 // In the CFG the optimized code of the SCoP is generated next to the
1712 // original code. Both the new and the original version of the code remain
1713 // in the CFG. A branch statement decides which version is executed.
1714 // For now, we always execute the new version (the old one is dead code
1715 // eliminated by the cleanup passes). In the future we may decide to execute
1716 // the new version only if certain run time checks succeed. This will be
1717 // useful to support constructs for which we cannot prove all assumptions at
1718 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001719 //
1720 // Before transformation:
1721 //
1722 // bb0
1723 // |
1724 // orig_scop
1725 // |
1726 // bb1
1727 //
1728 // After transformation:
1729 // bb0
1730 // |
1731 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001732 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001733 // | startBlock
1734 // | |
1735 // orig_scop new_scop
1736 // \ /
1737 // \ /
1738 // bb1 (joinBlock)
1739 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001740
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001741 // The builder will be set to startBlock.
1742 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001743 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001744
Tobias Grosser0ac92142012-02-14 14:02:27 +00001745 mergeControlFlow(splitBlock, &builder);
1746 builder.SetInsertPoint(StartBlock->begin());
1747
1748 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001749 CloogInfo &C = getAnalysis<CloogInfo>();
1750 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001751
Tobias Grosser75805372011-04-29 06:27:02 +00001752 parallelLoops.insert(parallelLoops.begin(),
1753 CodeGen.getParallelLoops().begin(),
1754 CodeGen.getParallelLoops().end());
1755
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001756 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001757 }
1758
1759 virtual void printScop(raw_ostream &OS) const {
1760 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1761 PE = parallelLoops.end(); PI != PE; ++PI)
1762 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1763 }
1764
1765 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1766 AU.addRequired<CloogInfo>();
1767 AU.addRequired<Dependences>();
1768 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001769 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001770 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001771 AU.addRequired<ScopDetection>();
1772 AU.addRequired<ScopInfo>();
1773 AU.addRequired<TargetData>();
1774
1775 AU.addPreserved<CloogInfo>();
1776 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001777
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001778 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001779 AU.addPreserved<LoopInfo>();
1780 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001781 AU.addPreserved<ScopDetection>();
1782 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001783
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001784 // FIXME: We do not yet add regions for the newly generated code to the
1785 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001786 AU.addPreserved<RegionInfo>();
1787 AU.addPreserved<TempScopInfo>();
1788 AU.addPreserved<ScopInfo>();
1789 AU.addPreservedID(IndependentBlocksID);
1790 }
1791};
1792}
1793
1794char CodeGeneration::ID = 1;
1795
Tobias Grosser73600b82011-10-08 00:30:40 +00001796INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1797 "Polly - Create LLVM-IR form SCoPs", false, false)
1798INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1799INITIALIZE_PASS_DEPENDENCY(Dependences)
1800INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1801INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1802INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1803INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1804INITIALIZE_PASS_DEPENDENCY(TargetData)
1805INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1806 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001807
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001808Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001809 return new CodeGeneration();
1810}