blob: 7daf9ccce181fbbe1234d00f9c02222189902003 [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 Grosserf81a691e2012-03-02 11:27:02 +0000182 Value *makeVectorOperand(Value *Operand);
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 Grosserf81a691e2012-03-02 11:27:02 +0000187 Type *getVectorPtrTy(const Value *V, int Width);
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 ///
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000197 Value *generateStrideOneLoad(const LoadInst *Load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000198
199 /// @brief Load a vector initialized from a single scalar in memory
200 ///
201 /// In case all elements of a vector are initialized to the same
202 /// scalar value, this value is loaded and shuffeled into all elements
203 /// of the vector.
204 ///
205 /// %splat_one = load <1 x double>* %p
206 /// %splat = shufflevector <1 x double> %splat_one, <1 x
207 /// double> %splat_one, <4 x i32> zeroinitializer
208 ///
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000209 Value *generateStrideZeroLoad(const LoadInst *Load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000210
211 /// @Load a vector from scalars distributed in memory
212 ///
213 /// In case some scalars a distributed randomly in memory. Create a vector
214 /// by loading each scalar and by inserting one after the other into the
215 /// vector.
216 ///
217 /// %scalar_1= load double* %p_1
218 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
219 /// %scalar 2 = load double* %p_2
220 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
221 ///
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000222 Value *generateUnknownStrideLoad(const LoadInst *Load,
223 VectorValueMapT &ScalarMaps);
Tobias Grosser75805372011-04-29 06:27:02 +0000224
Raghesh Aloora71989c2011-12-28 02:48:26 +0000225 static Value* islAffToValue(__isl_take isl_aff *Aff,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000226 IslPwAffUserInfo *UserInfo);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000227
228 static int mergeIslAffValues(__isl_take isl_set *Set,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000229 __isl_take isl_aff *Aff, void *User);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000230
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000231 Value* islPwAffToValue(__isl_take isl_pw_aff *PwAff);
Raghesh Aloora71989c2011-12-28 02:48:26 +0000232
Raghesh Aloor129e8672011-08-15 02:33:39 +0000233 /// @brief Get the memory access offset to be added to the base address
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000234 std::vector <Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000235 Value *BaseAddress);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000236
Raghesh Aloor62b13122011-08-03 17:02:50 +0000237 /// @brief Get the new operand address according to the changed access in
238 /// JSCOP file.
Raghesh Aloor46eceba2011-12-09 14:27:17 +0000239 Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
240 Value *BaseAddress, const Value *OldOperand,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000241 ValueMapT &BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000242
243 /// @brief Generate the operand address
244 Value *generateLocationAccessed(const Instruction *Inst,
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000245 const Value *Pointer, ValueMapT &BBMap );
Raghesh Aloor129e8672011-08-15 02:33:39 +0000246
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000247 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000248
249 /// @brief Load a value (or several values as a vector) from memory.
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000250 void generateLoad(const LoadInst *Load, ValueMapT &VectorMap,
251 VectorValueMapT &ScalarMaps);
Tobias Grosser75805372011-04-29 06:27:02 +0000252
Tobias Grosserc9215152011-09-04 11:45:52 +0000253 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000254 ValueMapT &VectorMap, int VectorDimension);
Tobias Grosserc9215152011-09-04 11:45:52 +0000255
Tobias Grosser09c57102011-09-04 11:45:29 +0000256 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000257 ValueMapT &VectorMap, int VectorDimension);
Tobias Grosser09c57102011-09-04 11:45:29 +0000258
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000259 void copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
260 ValueMapT &VectorMap, VectorValueMapT &ScalarMaps,
261 int VectorDimension);
Tobias Grosser75805372011-04-29 06:27:02 +0000262
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000263 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000264
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000265 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000266
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000267 int getVectorWidth();
Tobias Grosser75805372011-04-29 06:27:02 +0000268
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000269 bool isVectorBlock();
Tobias Grosser75805372011-04-29 06:27:02 +0000270
Tobias Grosser7551c302011-09-04 11:45:41 +0000271 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
Tobias Grosser262df3b2012-03-02 11:26:46 +0000272 ValueMapT &VectorMap, VectorValueMapT &ScalarMaps,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000273 int VectorDimension);
Tobias Grosser7551c302011-09-04 11:45:41 +0000274
Tobias Grosser75805372011-04-29 06:27:02 +0000275 // Insert a copy of a basic block in the newly generated code.
276 //
277 // @param Builder The builder used to insert the code. It also specifies
278 // where to insert the code.
Tobias Grosser75805372011-04-29 06:27:02 +0000279 // @param VMap A map returning for any old value its new equivalent. This
280 // is used to update the operands of the statements.
281 // For new statements a relation old->new is inserted in this
282 // map.
Tobias Grosser8412cda2012-03-02 11:26:55 +0000283 void copyBB();
Tobias Grosser75805372011-04-29 06:27:02 +0000284};
285
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000286BlockGenerator::BlockGenerator(IRBuilder<> &B, ValueMapT &vmap,
287 VectorValueMapT &vmaps, ScopStmt &Stmt,
Tobias Grosser8412cda2012-03-02 11:26:55 +0000288 __isl_keep isl_set *domain, Pass *P)
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000289 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
Tobias Grosser8412cda2012-03-02 11:26:55 +0000290 Statement(Stmt), ScatteringDomain(domain), P(P) {}
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000291
292const Region &BlockGenerator::getRegion() {
293 return S.getRegion();
294}
295
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000296Value *BlockGenerator::makeVectorOperand(Value *Operand) {
297 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000298 if (Operand->getType()->isVectorTy())
299 return Operand;
300
301 VectorType *VectorType = VectorType::get(Operand->getType(), VectorWidth);
302 Value *Vector = UndefValue::get(VectorType);
303 Vector = Builder.CreateInsertElement(Vector, Operand, Builder.getInt32(0));
304
305 std::vector<Constant*> Splat;
306
307 for (int i = 0; i < VectorWidth; i++)
308 Splat.push_back (Builder.getInt32(0));
309
310 Constant *SplatVector = ConstantVector::get(Splat);
311
312 return Builder.CreateShuffleVector(Vector, Vector, SplatVector);
313}
314
315Value *BlockGenerator::getOperand(const Value *OldOperand, ValueMapT &BBMap,
316 ValueMapT *VectorMap) {
317 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
318
319 if (!OpInst)
320 return const_cast<Value*>(OldOperand);
321
322 if (VectorMap && VectorMap->count(OldOperand))
323 return (*VectorMap)[OldOperand];
324
325 // IVS and Parameters.
326 if (VMap.count(OldOperand)) {
327 Value *NewOperand = VMap[OldOperand];
328
329 // Insert a cast if types are different
330 if (OldOperand->getType()->getScalarSizeInBits()
331 < NewOperand->getType()->getScalarSizeInBits())
332 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
333 OldOperand->getType());
334
335 return NewOperand;
336 }
337
338 // Instructions calculated in the current BB.
339 if (BBMap.count(OldOperand)) {
340 return BBMap[OldOperand];
341 }
342
343 // Ignore instructions that are referencing ops in the old BB. These
344 // instructions are unused. They where replace by new ones during
345 // createIndependentBlocks().
346 if (getRegion().contains(OpInst->getParent()))
347 return NULL;
348
349 return const_cast<Value*>(OldOperand);
350}
351
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000352Type *BlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000353 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
354 assert(PointerTy && "PointerType expected");
355
356 Type *ScalarType = PointerTy->getElementType();
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000357 VectorType *VectorType = VectorType::get(ScalarType, Width);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000358
359 return PointerType::getUnqual(VectorType);
360}
361
362Value *BlockGenerator::generateStrideOneLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000363 ValueMapT &BBMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000364 const Value *Pointer = Load->getPointerOperand();
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000365 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000366 Value *NewPointer = getOperand(Pointer, BBMap);
367 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
368 "vector_ptr");
369 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
370 Load->getName() + "_p_vec_full");
371 if (!Aligned)
372 VecLoad->setAlignment(8);
373
374 return VecLoad;
375}
376
377Value *BlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000378 ValueMapT &BBMap) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000379 const Value *Pointer = Load->getPointerOperand();
380 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
381 Value *NewPointer = getOperand(Pointer, BBMap);
382 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
383 Load->getName() + "_p_vec_p");
384 LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
385 Load->getName() + "_p_splat_one");
386
387 if (!Aligned)
388 ScalarLoad->setAlignment(8);
389
Tobias Grossere5b423252012-01-24 16:42:25 +0000390 Constant *SplatVector =
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000391 Constant::getNullValue(VectorType::get(Builder.getInt32Ty(),
392 getVectorWidth()));
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000393
394 Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
395 SplatVector,
396 Load->getName()
397 + "_p_splat");
398 return VectorLoad;
399}
400
401Value *BlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000402 VectorValueMapT &ScalarMaps) {
403 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000404 const Value *Pointer = Load->getPointerOperand();
405 VectorType *VectorType = VectorType::get(
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000406 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000407
408 Value *Vector = UndefValue::get(VectorType);
409
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000410 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000411 Value *NewPointer = getOperand(Pointer, ScalarMaps[i]);
412 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
413 Load->getName() + "_p_scalar_");
414 Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
415 Builder.getInt32(i),
416 Load->getName() + "_p_vec_");
417 }
418
419 return Vector;
420}
421
422Value *BlockGenerator::islAffToValue(__isl_take isl_aff *Aff,
423 IslPwAffUserInfo *UserInfo) {
424 assert(isl_aff_is_cst(Aff) && "Only constant access functions supported");
425
426 IRBuilder<> *Builder = UserInfo->Builder;
427
428 isl_int OffsetIsl;
429 mpz_t OffsetMPZ;
430
431 isl_int_init(OffsetIsl);
432 mpz_init(OffsetMPZ);
433 isl_aff_get_constant(Aff, &OffsetIsl);
434 isl_int_get_gmp(OffsetIsl, OffsetMPZ);
435
436 Value *OffsetValue = NULL;
437 APInt Offset = APInt_from_MPZ(OffsetMPZ);
438 OffsetValue = ConstantInt::get(Builder->getContext(), Offset);
439
440 mpz_clear(OffsetMPZ);
441 isl_int_clear(OffsetIsl);
442 isl_aff_free(Aff);
443
444 return OffsetValue;
445}
446
447int BlockGenerator::mergeIslAffValues(__isl_take isl_set *Set,
448 __isl_take isl_aff *Aff, void *User) {
449 IslPwAffUserInfo *UserInfo = (IslPwAffUserInfo *)User;
450
451 assert((UserInfo->Result == NULL) && "Result is already set."
452 "Currently only single isl_aff is supported");
453 assert(isl_set_plain_is_universe(Set)
454 && "Code generation failed because the set is not universe");
455
456 UserInfo->Result = islAffToValue(Aff, UserInfo);
457
458 isl_set_free(Set);
459 return 0;
460}
461
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000462Value *BlockGenerator::islPwAffToValue(__isl_take isl_pw_aff *PwAff) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000463 IslPwAffUserInfo UserInfo;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000464 UserInfo.Result = NULL;
465 UserInfo.Builder = &Builder;
466 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &UserInfo);
467 assert(UserInfo.Result && "Code generation for isl_pw_aff failed");
468
469 isl_pw_aff_free(PwAff);
470 return UserInfo.Result;
471}
472
473std::vector <Value*> BlockGenerator::getMemoryAccessIndex(
474 __isl_keep isl_map *AccessRelation, Value *BaseAddress) {
475 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
476 && "Only single dimensional access functions supported");
477
478 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
Tobias Grosser5c853ba2012-02-13 12:29:34 +0000479 Value *OffsetValue = islPwAffToValue(PwAff);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000480
481 PointerType *BaseAddressType = dyn_cast<PointerType>(
482 BaseAddress->getType());
483 Type *ArrayTy = BaseAddressType->getElementType();
484 Type *ArrayElementType = dyn_cast<ArrayType>(ArrayTy)->getElementType();
485 OffsetValue = Builder.CreateSExtOrBitCast(OffsetValue, ArrayElementType);
486
487 std::vector<Value*> IndexArray;
488 Value *NullValue = Constant::getNullValue(ArrayElementType);
489 IndexArray.push_back(NullValue);
490 IndexArray.push_back(OffsetValue);
491 return IndexArray;
492}
493
494Value *BlockGenerator::getNewAccessOperand(
495 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, const Value
496 *OldOperand, ValueMapT &BBMap) {
497 std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
498 BaseAddress);
499 Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
500 "p_newarrayidx_");
501 return NewOperand;
502}
503
504Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
505 const Value *Pointer,
506 ValueMapT &BBMap ) {
507 MemoryAccess &Access = Statement.getAccessFor(Inst);
508 isl_map *CurrentAccessRelation = Access.getAccessRelation();
509 isl_map *NewAccessRelation = Access.getNewAccessRelation();
510
511 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
512 && "Current and new access function use different spaces");
513
514 Value *NewPointer;
515
516 if (!NewAccessRelation) {
517 NewPointer = getOperand(Pointer, BBMap);
518 } else {
519 Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
520 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, Pointer,
521 BBMap);
522 }
523
524 isl_map_free(CurrentAccessRelation);
525 isl_map_free(NewAccessRelation);
526 return NewPointer;
527}
528
529Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
530 ValueMapT &BBMap) {
531 const Value *Pointer = Load->getPointerOperand();
532 const Instruction *Inst = dyn_cast<Instruction>(Load);
533 Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap);
534 Value *ScalarLoad = Builder.CreateLoad(NewPointer,
535 Load->getName() + "_p_scalar_");
536 return ScalarLoad;
537}
538
539void BlockGenerator::generateLoad(const LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000540 VectorValueMapT &ScalarMaps) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000541 if (ScalarMaps.size() == 1) {
542 ScalarMaps[0][Load] = generateScalarLoad(Load, ScalarMaps[0]);
543 return;
544 }
545
546 Value *NewLoad;
547
548 MemoryAccess &Access = Statement.getAccessFor(Load);
549
550 assert(ScatteringDomain && "No scattering domain available");
551
552 if (Access.isStrideZero(isl_set_copy(ScatteringDomain)))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000553 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000554 else if (Access.isStrideOne(isl_set_copy(ScatteringDomain)))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000555 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0]);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000556 else
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000557 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000558
559 VectorMap[Load] = NewLoad;
560}
561
562void BlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
563 ValueMapT &BBMap, ValueMapT &VectorMap,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000564 int VectorDimension) {
565 int VectorWidth = getVectorWidth();
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000566 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000567 NewOperand = makeVectorOperand(NewOperand);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000568
569 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
570
571 const CastInst *Cast = dyn_cast<CastInst>(Inst);
572 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
573 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
574}
575
576void BlockGenerator::copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000577 ValueMapT &VectorMap, int VectorDimension) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000578 Value *OpZero = Inst->getOperand(0);
579 Value *OpOne = Inst->getOperand(1);
580
581 Value *NewOpZero, *NewOpOne;
582 NewOpZero = getOperand(OpZero, BBMap, &VectorMap);
583 NewOpOne = getOperand(OpOne, BBMap, &VectorMap);
584
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000585 NewOpZero = makeVectorOperand(NewOpZero);
586 NewOpOne = makeVectorOperand(NewOpOne);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000587
588 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
589 NewOpOne,
590 Inst->getName() + "p_vec");
591 VectorMap[Inst] = NewInst;
592}
593
594void BlockGenerator::copyVectorStore(const StoreInst *Store, ValueMapT &BBMap,
595 ValueMapT &VectorMap,
596 VectorValueMapT &ScalarMaps,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000597 int VectorDimension) {
598 int VectorWidth = getVectorWidth();
599
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000600 // 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
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000666int BlockGenerator::getVectorWidth() {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000667 return ValueMaps.size();
668}
669
670bool BlockGenerator::isVectorBlock() {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000671 return getVectorWidth() > 1;
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000672}
673
674void BlockGenerator::copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
675 ValueMapT &VectorMap,
676 VectorValueMapT &ScalarMaps,
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000677 int VectorDimension) {
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000678 // 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)) {
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000692 generateLoad(Load, VectorMap, ScalarMaps);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000693 return;
694 }
695
696 if (isVectorBlock() && hasVectorOperands(Inst, VectorMap)) {
697 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000698 copyUnaryInst(UnaryInst, BBMap, VectorMap, VectorDimension);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000699 else if
700 (const BinaryOperator *BinaryInst = dyn_cast<BinaryOperator>(Inst))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000701 copyBinInst(BinaryInst, BBMap, VectorMap, VectorDimension);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000702 else if (const StoreInst *Store = dyn_cast<StoreInst>(Inst))
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000703 copyVectorStore(Store, BBMap, VectorMap, ScalarMaps, VectorDimension);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000704 else
705 llvm_unreachable("Cannot issue vector code for this instruction");
706
707 return;
708 }
709
710 copyInstScalar(Inst, BBMap);
711}
712
Tobias Grosser8412cda2012-03-02 11:26:55 +0000713void BlockGenerator::copyBB() {
Tobias Grosser14bcbd52012-03-02 11:26:52 +0000714 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosser0ac92142012-02-14 14:02:27 +0000715 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
716 Builder.GetInsertPoint(), P);
Tobias Grosserb61e6312012-02-15 09:58:46 +0000717 CopyBB->setName("polly.stmt." + BB->getName());
Tobias Grosser0ac92142012-02-14 14:02:27 +0000718 Builder.SetInsertPoint(CopyBB->begin());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000719
720 // Create two maps that store the mapping from the original instructions of
721 // the old basic block to their copies in the new basic block. Those maps
722 // are basic block local.
723 //
724 // As vector code generation is supported there is one map for scalar values
725 // and one for vector values.
726 //
727 // In case we just do scalar code generation, the vectorMap is not used and
728 // the scalarMap has just one dimension, which contains the mapping.
729 //
730 // In case vector code generation is done, an instruction may either appear
731 // in the vector map once (as it is calculating >vectorwidth< values at a
732 // time. Or (if the values are calculated using scalar operations), it
733 // appears once in every dimension of the scalarMap.
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000734 VectorValueMapT ScalarBlockMap(getVectorWidth());
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000735 ValueMapT VectorBlockMap;
736
737 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
738 II != IE; ++II)
Tobias Grosserf81a691e2012-03-02 11:27:02 +0000739 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
740 copyInstruction(II, ScalarBlockMap[VectorLane], VectorBlockMap,
741 ScalarBlockMap, VectorLane);
Tobias Grosser70e8cdb2012-01-24 16:42:21 +0000742}
743
Tobias Grosser75805372011-04-29 06:27:02 +0000744/// Class to generate LLVM-IR that calculates the value of a clast_expr.
745class ClastExpCodeGen {
746 IRBuilder<> &Builder;
747 const CharMapT *IVS;
748
Tobias Grosserbb137e32012-01-24 16:42:28 +0000749 Value *codegen(const clast_name *e, Type *Ty);
750 Value *codegen(const clast_term *e, Type *Ty);
751 Value *codegen(const clast_binary *e, Type *Ty);
752 Value *codegen(const clast_reduction *r, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000753public:
754
755 // A generator for clast expressions.
756 //
757 // @param B The IRBuilder that defines where the code to calculate the
758 // clast expressions should be inserted.
759 // @param IVMAP A Map that translates strings describing the induction
760 // variables to the Values* that represent these variables
761 // on the LLVM side.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000762 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000763
764 // Generates code to calculate a given clast expression.
765 //
766 // @param e The expression to calculate.
767 // @return The Value that holds the result.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000768 Value *codegen(const clast_expr *e, Type *Ty);
Tobias Grosser75805372011-04-29 06:27:02 +0000769
770 // @brief Reset the CharMap.
771 //
772 // This function is called to reset the CharMap to new one, while generating
773 // OpenMP code.
Tobias Grosserbb137e32012-01-24 16:42:28 +0000774 void setIVS(CharMapT *IVSNew);
775};
776
777Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
778 CharMapT::const_iterator I = IVS->find(e->name);
779
780 assert(I != IVS->end() && "Clast name not found");
781
782 return Builder.CreateSExtOrBitCast(I->second, Ty);
783}
784
785Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
786 APInt a = APInt_from_MPZ(e->val);
787
788 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
789 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
790
791 if (!e->var)
792 return ConstOne;
793
794 Value *var = codegen(e->var, Ty);
795 return Builder.CreateMul(ConstOne, var);
796}
797
798Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
799 Value *LHS = codegen(e->LHS, Ty);
800
801 APInt RHS_AP = APInt_from_MPZ(e->RHS);
802
803 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
804 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
805
806 switch (e->type) {
807 case clast_bin_mod:
808 return Builder.CreateSRem(LHS, RHS);
809 case clast_bin_fdiv:
810 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000811 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
Tobias Grosser906eafe2012-02-16 09:56:10 +0000812 Value *One = ConstantInt::get(Ty, 1);
813 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000814 Value *Sum1 = Builder.CreateSub(LHS, RHS);
815 Value *Sum2 = Builder.CreateAdd(Sum1, One);
816 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
817 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
818 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000819 }
820 case clast_bin_cdiv:
821 {
Tobias Grosser9a44b972012-02-16 14:13:19 +0000822 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
823 Value *One = ConstantInt::get(Ty, 1);
Tobias Grosser906eafe2012-02-16 09:56:10 +0000824 Value *Zero = ConstantInt::get(Ty, 0);
Tobias Grosser9a44b972012-02-16 14:13:19 +0000825 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
826 Value *Sum2 = Builder.CreateSub(Sum1, One);
827 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
828 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
829 return Builder.CreateSDiv(Dividend, RHS);
Tobias Grosserbb137e32012-01-24 16:42:28 +0000830 }
831 case clast_bin_div:
832 return Builder.CreateSDiv(LHS, RHS);
833 };
834
835 llvm_unreachable("Unknown clast binary expression type");
836}
837
838Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
839 assert(( r->type == clast_red_min
840 || r->type == clast_red_max
841 || r->type == clast_red_sum)
842 && "Clast reduction type not supported");
843 Value *old = codegen(r->elts[0], Ty);
844
845 for (int i=1; i < r->n; ++i) {
846 Value *exprValue = codegen(r->elts[i], Ty);
847
848 switch (r->type) {
849 case clast_red_min:
850 {
851 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
852 old = Builder.CreateSelect(cmp, old, exprValue);
853 break;
854 }
855 case clast_red_max:
856 {
857 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
858 old = Builder.CreateSelect(cmp, old, exprValue);
859 break;
860 }
861 case clast_red_sum:
862 old = Builder.CreateAdd(old, exprValue);
863 break;
Tobias Grosserbb137e32012-01-24 16:42:28 +0000864 }
Tobias Grosser75805372011-04-29 06:27:02 +0000865 }
866
Tobias Grosserbb137e32012-01-24 16:42:28 +0000867 return old;
868}
869
870ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap)
871 : Builder(B), IVS(IVMap) {}
872
873Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
874 switch(e->type) {
875 case clast_expr_name:
876 return codegen((const clast_name *)e, Ty);
877 case clast_expr_term:
878 return codegen((const clast_term *)e, Ty);
879 case clast_expr_bin:
880 return codegen((const clast_binary *)e, Ty);
881 case clast_expr_red:
882 return codegen((const clast_reduction *)e, Ty);
883 }
884
885 llvm_unreachable("Unknown clast expression!");
886}
887
888void ClastExpCodeGen::setIVS(CharMapT *IVSNew) {
889 IVS = IVSNew;
890}
Tobias Grosser75805372011-04-29 06:27:02 +0000891
892class ClastStmtCodeGen {
893 // The Scop we code generate.
894 Scop *S;
895 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000896 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000897 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000898 Dependences *DP;
899 TargetData *TD;
Tobias Grosser0ac92142012-02-14 14:02:27 +0000900 Pass *P;
Tobias Grosser75805372011-04-29 06:27:02 +0000901
902 // The Builder specifies the current location to code generate at.
903 IRBuilder<> &Builder;
904
905 // Map the Values from the old code to their counterparts in the new code.
906 ValueMapT ValueMap;
907
908 // clastVars maps from the textual representation of a clast variable to its
909 // current *Value. clast variables are scheduling variables, original
910 // induction variables or parameters. They are used either in loop bounds or
911 // to define the statement instance that is executed.
912 //
913 // for (s = 0; s < n + 3; ++i)
914 // for (t = s; t < m; ++j)
915 // Stmt(i = s + 3 * m, j = t);
916 //
917 // {s,t,i,j,n,m} is the set of clast variables in this clast.
918 CharMapT *clastVars;
919
920 // Codegenerator for clast expressions.
921 ClastExpCodeGen ExpGen;
922
923 // Do we currently generate parallel code?
924 bool parallelCodeGeneration;
925
926 std::vector<std::string> parallelLoops;
927
928public:
929
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000930 const std::vector<std::string> &getParallelLoops();
Tobias Grosser75805372011-04-29 06:27:02 +0000931
932 protected:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000933 void codegen(const clast_assignment *a);
Tobias Grosser75805372011-04-29 06:27:02 +0000934
935 void codegen(const clast_assignment *a, ScopStmt *Statement,
936 unsigned Dimension, int vectorDim,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000937 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000938
939 void codegenSubstitutions(const clast_stmt *Assignment,
940 ScopStmt *Statement, int vectorDim = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000941 std::vector<ValueMapT> *VectorVMap = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000942
943 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000944 const char *iterator = NULL, isl_set *scatteringDomain = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000945
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000946 void codegen(const clast_block *b);
Tobias Grosser75805372011-04-29 06:27:02 +0000947
948 /// @brief Create a classical sequential loop.
Tobias Grosser545bc312011-12-06 10:48:27 +0000949 void codegenForSequential(const clast_for *f, Value *LowerBound = 0,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000950 Value *UpperBound = 0);
Tobias Grosser75805372011-04-29 06:27:02 +0000951
Tobias Grosser75805372011-04-29 06:27:02 +0000952 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000953 Function *addOpenMPSubfunction(Module *M);
Tobias Grosser75805372011-04-29 06:27:02 +0000954
955 /// @brief Add values to the OpenMP structure.
956 ///
957 /// Create the subfunction structure and add the values from the list.
958 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000959 Function *SubFunction);
Tobias Grosser75805372011-04-29 06:27:02 +0000960
961 /// @brief Create OpenMP structure values.
962 ///
963 /// Create a list of values that has to be stored into the subfuncition
964 /// structure.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000965 SetVector<Value*> createOpenMPStructValues();
Tobias Grosser75805372011-04-29 06:27:02 +0000966
967 /// @brief Extract the values from the subfunction parameter.
968 ///
969 /// Extract the values from the subfunction parameter and update the clast
970 /// variables to point to the new values.
971 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
972 SetVector<Value*> OMPDataVals,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000973 Value *userContext);
Tobias Grosser75805372011-04-29 06:27:02 +0000974
975 /// @brief Add body to the subfunction.
976 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
977 Value *structData,
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000978 SetVector<Value*> OMPDataVals);
Tobias Grosser75805372011-04-29 06:27:02 +0000979
980 /// @brief Create an OpenMP parallel for loop.
981 ///
982 /// This loop reflects a loop as if it would have been created by an OpenMP
983 /// statement.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000984 void codegenForOpenMP(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000985
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000986 bool isInnermostLoop(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000987
988 /// @brief Get the number of loop iterations for this loop.
989 /// @param f The clast for loop to check.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000990 int getNumberOfIterations(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000991
992 /// @brief Create vector instructions for this loop.
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000993 void codegenForVector(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000994
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000995 void codegen(const clast_for *f);
Tobias Grosser75805372011-04-29 06:27:02 +0000996
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000997 Value *codegen(const clast_equation *eq);
Tobias Grosser75805372011-04-29 06:27:02 +0000998
Tobias Grosser9bc5eb082012-01-24 16:42:32 +0000999 void codegen(const clast_guard *g);
Tobias Grosser75805372011-04-29 06:27:02 +00001000
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001001 void codegen(const clast_stmt *stmt);
Tobias Grosser75805372011-04-29 06:27:02 +00001002
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001003 void addParameters(const CloogNames *names);
Tobias Grosser75805372011-04-29 06:27:02 +00001004
1005 public:
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001006 void codegen(const clast_root *r);
Tobias Grosser75805372011-04-29 06:27:02 +00001007
1008 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001009 ScopDetection *sd, Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001010 IRBuilder<> &B, Pass *P);
Tobias Grosser75805372011-04-29 06:27:02 +00001011};
1012}
1013
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001014const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1015 return parallelLoops;
1016}
1017
1018void ClastStmtCodeGen::codegen(const clast_assignment *a) {
1019 Value *V= ExpGen.codegen(a->RHS, TD->getIntPtrType(Builder.getContext()));
1020 (*clastVars)[a->LHS] = V;
1021}
1022
1023void ClastStmtCodeGen::codegen(const clast_assignment *a, ScopStmt *Statement,
1024 unsigned Dimension, int vectorDim,
1025 std::vector<ValueMapT> *VectorVMap) {
1026 Value *RHS = ExpGen.codegen(a->RHS,
1027 TD->getIntPtrType(Builder.getContext()));
1028
1029 assert(!a->LHS && "Statement assignments do not have left hand side");
1030 const PHINode *PN;
1031 PN = Statement->getInductionVariableForDimension(Dimension);
1032 const Value *V = PN;
1033
1034 if (VectorVMap)
1035 (*VectorVMap)[vectorDim][V] = RHS;
1036
1037 ValueMap[V] = RHS;
1038}
1039
1040void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1041 ScopStmt *Statement, int vectorDim,
1042 std::vector<ValueMapT> *VectorVMap) {
1043 int Dimension = 0;
1044
1045 while (Assignment) {
1046 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1047 && "Substitions are expected to be assignments");
1048 codegen((const clast_assignment *)Assignment, Statement, Dimension,
1049 vectorDim, VectorVMap);
1050 Assignment = Assignment->next;
1051 Dimension++;
1052 }
1053}
1054
1055void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1056 std::vector<Value*> *IVS , const char *iterator,
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001057 isl_set *Domain) {
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001058 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001059
1060 if (u->substitutions)
1061 codegenSubstitutions(u->substitutions, Statement);
1062
1063 int vectorDimensions = IVS ? IVS->size() : 1;
1064
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001065 VectorValueMapT VectorMap(vectorDimensions);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001066
1067 if (IVS) {
1068 assert (u->substitutions && "Substitutions expected!");
1069 int i = 0;
1070 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1071 II != IE; ++II) {
1072 (*clastVars)[iterator] = *II;
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001073 codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001074 i++;
1075 }
1076 }
1077
Tobias Grosser14bcbd52012-03-02 11:26:52 +00001078 BlockGenerator::generate(Builder, ValueMap, VectorMap, *Statement, Domain, P);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001079}
1080
1081void ClastStmtCodeGen::codegen(const clast_block *b) {
1082 if (b->body)
1083 codegen(b->body);
1084}
1085
1086void ClastStmtCodeGen::codegenForSequential(const clast_for *f,
1087 Value *LowerBound,
1088 Value *UpperBound) {
1089 APInt Stride;
Tobias Grosser0ac92142012-02-14 14:02:27 +00001090 BasicBlock *AfterBB;
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001091 Type *IntPtrTy;
1092
1093 Stride = APInt_from_MPZ(f->stride);
1094 IntPtrTy = TD->getIntPtrType(Builder.getContext());
1095
1096 // The value of lowerbound and upperbound will be supplied, if this
1097 // function is called while generating OpenMP code. Otherwise get
1098 // the values.
1099 assert(!!LowerBound == !!UpperBound && "Either give both bounds or none");
1100
1101 if (LowerBound == 0) {
1102 LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1103 UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1104 }
1105
Tobias Grosser0ac92142012-02-14 14:02:27 +00001106 Value *IV = createLoop(&Builder, LowerBound, UpperBound, Stride, DT, P,
1107 &AfterBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001108
1109 // Add loop iv to symbols.
1110 (*clastVars)[f->iterator] = IV;
1111
1112 if (f->body)
1113 codegen(f->body);
1114
1115 // Loop is finished, so remove its iv from the live symbols.
1116 clastVars->erase(f->iterator);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001117 Builder.SetInsertPoint(AfterBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001118}
1119
1120Function *ClastStmtCodeGen::addOpenMPSubfunction(Module *M) {
1121 Function *F = Builder.GetInsertBlock()->getParent();
1122 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
1123 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
1124 Function *FN = Function::Create(FT, Function::InternalLinkage,
1125 F->getName() + ".omp_subfn", M);
1126 // Do not run any polly pass on the new function.
1127 SD->markFunctionAsInvalid(FN);
1128
1129 Function::arg_iterator AI = FN->arg_begin();
1130 AI->setName("omp.userContext");
1131
1132 return FN;
1133}
1134
1135Value *ClastStmtCodeGen::addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
1136 Function *SubFunction) {
1137 std::vector<Type*> structMembers;
1138
1139 // Create the structure.
1140 for (unsigned i = 0; i < OMPDataVals.size(); i++)
1141 structMembers.push_back(OMPDataVals[i]->getType());
1142
1143 StructType *structTy = StructType::get(Builder.getContext(),
1144 structMembers);
1145 // Store the values into the structure.
1146 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
1147 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
1148 Value *storeAddr = Builder.CreateStructGEP(structData, i);
1149 Builder.CreateStore(OMPDataVals[i], storeAddr);
1150 }
1151
1152 return structData;
1153}
1154
1155SetVector<Value*> ClastStmtCodeGen::createOpenMPStructValues() {
1156 SetVector<Value*> OMPDataVals;
1157
1158 // Push the clast variables available in the clastVars.
1159 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1160 I != E; I++)
1161 OMPDataVals.insert(I->second);
1162
1163 // Push the base addresses of memory references.
1164 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1165 ScopStmt *Stmt = *SI;
1166 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1167 E = Stmt->memacc_end(); I != E; ++I) {
1168 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1169 OMPDataVals.insert((BaseAddr));
1170 }
1171 }
1172
1173 return OMPDataVals;
1174}
1175
1176void ClastStmtCodeGen::extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
1177 SetVector<Value*> OMPDataVals, Value *userContext) {
1178 // Extract the clast variables.
1179 unsigned i = 0;
1180 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
1181 I != E; I++) {
1182 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
1183 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
1184 i++;
1185 }
1186
1187 // Extract the base addresses of memory references.
1188 for (unsigned j = i; j < OMPDataVals.size(); j++) {
1189 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
1190 Value *baseAddr = OMPDataVals[j];
1191 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1192 }
1193}
1194
1195void ClastStmtCodeGen::addOpenMPSubfunctionBody(Function *FN,
1196 const clast_for *f,
1197 Value *structData,
1198 SetVector<Value*> OMPDataVals) {
1199 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1200 LLVMContext &Context = FN->getContext();
1201 IntegerType *intPtrTy = TD->getIntPtrType(Context);
1202
1203 // Store the previous basic block.
Tobias Grosser0ac92142012-02-14 14:02:27 +00001204 BasicBlock::iterator PrevInsertPoint = Builder.GetInsertPoint();
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001205 BasicBlock *PrevBB = Builder.GetInsertBlock();
1206
1207 // Create basic blocks.
1208 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1209 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1210 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1211 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1212 FN);
1213
1214 DT->addNewBlock(HeaderBB, PrevBB);
1215 DT->addNewBlock(ExitBB, HeaderBB);
1216 DT->addNewBlock(checkNextBB, HeaderBB);
1217 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1218
1219 // Fill up basic block HeaderBB.
1220 Builder.SetInsertPoint(HeaderBB);
1221 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1222 "omp.lowerBoundPtr");
1223 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1224 "omp.upperBoundPtr");
1225 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1226 structData->getType(),
1227 "omp.userContext");
1228
1229 CharMapT clastVarsOMP;
1230 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1231
1232 Builder.CreateBr(checkNextBB);
1233
1234 // Add code to check if another set of iterations will be executed.
1235 Builder.SetInsertPoint(checkNextBB);
1236 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1237 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1238 lowerBoundPtr, upperBoundPtr);
1239 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1240 "omp.hasNextScheduleBlock");
1241 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1242
1243 // Add code to to load the iv bounds for this set of iterations.
1244 Builder.SetInsertPoint(loadIVBoundsBB);
1245 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1246 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1247
1248 // Subtract one as the upper bound provided by openmp is a < comparison
1249 // whereas the codegenForSequential function creates a <= comparison.
1250 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1251 "omp.upperBoundAdjusted");
1252
1253 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1254 CharMapT *oldClastVars = clastVars;
1255 clastVars = &clastVarsOMP;
1256 ExpGen.setIVS(&clastVarsOMP);
1257
Tobias Grosser0ac92142012-02-14 14:02:27 +00001258 Builder.CreateBr(checkNextBB);
1259 Builder.SetInsertPoint(--Builder.GetInsertPoint());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001260 codegenForSequential(f, lowerBound, upperBound);
1261
1262 // Restore the old clastVars.
1263 clastVars = oldClastVars;
1264 ExpGen.setIVS(oldClastVars);
1265
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001266 // Add code to terminate this openmp subfunction.
1267 Builder.SetInsertPoint(ExitBB);
1268 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1269 Builder.CreateCall(endnowaitFunction);
1270 Builder.CreateRetVoid();
1271
Tobias Grosser0ac92142012-02-14 14:02:27 +00001272 // Restore the previous insert point.
1273 Builder.SetInsertPoint(PrevInsertPoint);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001274}
1275
1276void ClastStmtCodeGen::codegenForOpenMP(const clast_for *f) {
1277 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1278 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
1279
1280 Function *SubFunction = addOpenMPSubfunction(M);
1281 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1282 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1283
1284 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1285
1286 // Create call for GOMP_parallel_loop_runtime_start.
1287 Value *subfunctionParam = Builder.CreateBitCast(structData,
1288 Builder.getInt8PtrTy(),
1289 "omp_data");
1290
1291 Value *numberOfThreads = Builder.getInt32(0);
1292 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1293 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1294
1295 // Add one as the upper bound provided by openmp is a < comparison
1296 // whereas the codegenForSequential function creates a <= comparison.
1297 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1298 APInt APStride = APInt_from_MPZ(f->stride);
1299 Value *stride = ConstantInt::get(intPtrTy,
1300 APStride.zext(intPtrTy->getBitWidth()));
1301
1302 SmallVector<Value *, 6> Arguments;
1303 Arguments.push_back(SubFunction);
1304 Arguments.push_back(subfunctionParam);
1305 Arguments.push_back(numberOfThreads);
1306 Arguments.push_back(lowerBound);
1307 Arguments.push_back(upperBound);
1308 Arguments.push_back(stride);
1309
1310 Function *parallelStartFunction =
1311 M->getFunction("GOMP_parallel_loop_runtime_start");
1312 Builder.CreateCall(parallelStartFunction, Arguments);
1313
1314 // Create call to the subfunction.
1315 Builder.CreateCall(SubFunction, subfunctionParam);
1316
1317 // Create call for GOMP_parallel_end.
1318 Function *FN = M->getFunction("GOMP_parallel_end");
1319 Builder.CreateCall(FN);
1320}
1321
1322bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1323 const clast_stmt *stmt = f->body;
1324
1325 while (stmt) {
1326 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1327 return false;
1328
1329 stmt = stmt->next;
1330 }
1331
1332 return true;
1333}
1334
1335int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1336 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1337 isl_set *tmp = isl_set_copy(loopDomain);
1338
1339 // Calculate a map similar to the identity map, but with the last input
1340 // and output dimension not related.
1341 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1342 isl_space *Space = isl_set_get_space(loopDomain);
1343 Space = isl_space_drop_outputs(Space,
1344 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1345 Space = isl_space_map_from_set(Space);
1346 isl_map *identity = isl_map_identity(Space);
1347 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1348 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1349
1350 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1351 map = isl_map_intersect(map, identity);
1352
1353 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1354 isl_map *lexmin = isl_map_lexmin(map);
1355 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1356
1357 isl_set *elements = isl_map_range(sub);
1358
1359 if (!isl_set_is_singleton(elements)) {
1360 isl_set_free(elements);
1361 return -1;
1362 }
1363
1364 isl_point *p = isl_set_sample_point(elements);
1365
1366 isl_int v;
1367 isl_int_init(v);
1368 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1369 int numberIterations = isl_int_get_si(v);
1370 isl_int_clear(v);
1371 isl_point_free(p);
1372
1373 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1374}
1375
1376void ClastStmtCodeGen::codegenForVector(const clast_for *f) {
1377 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1378 int vectorWidth = getNumberOfIterations(f);
1379
1380 Value *LB = ExpGen.codegen(f->LB,
1381 TD->getIntPtrType(Builder.getContext()));
1382
1383 APInt Stride = APInt_from_MPZ(f->stride);
1384 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1385 Stride = Stride.zext(LoopIVType->getBitWidth());
1386 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1387
1388 std::vector<Value*> IVS(vectorWidth);
1389 IVS[0] = LB;
1390
1391 for (int i = 1; i < vectorWidth; i++)
1392 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1393
1394 isl_set *scatteringDomain =
1395 isl_set_copy(isl_set_from_cloog_domain(f->domain));
1396
1397 // Add loop iv to symbols.
1398 (*clastVars)[f->iterator] = LB;
1399
1400 const clast_stmt *stmt = f->body;
1401
1402 while (stmt) {
1403 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1404 scatteringDomain);
1405 stmt = stmt->next;
1406 }
1407
1408 // Loop is finished, so remove its iv from the live symbols.
1409 isl_set_free(scatteringDomain);
1410 clastVars->erase(f->iterator);
1411}
1412
1413void ClastStmtCodeGen::codegen(const clast_for *f) {
Tobias Grosserce3f5372012-03-02 11:26:42 +00001414 if ((Vector || OpenMP) && DP->isParallelFor(f)) {
1415 if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
1416 && (getNumberOfIterations(f) <= 16)) {
1417 codegenForVector(f);
1418 return;
1419 }
1420
1421 if (OpenMP && !parallelCodeGeneration) {
1422 parallelCodeGeneration = true;
1423 parallelLoops.push_back(f->iterator);
1424 codegenForOpenMP(f);
1425 parallelCodeGeneration = false;
1426 return;
1427 }
1428 }
1429
1430 codegenForSequential(f);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001431}
1432
1433Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
1434 Value *LHS = ExpGen.codegen(eq->LHS,
1435 TD->getIntPtrType(Builder.getContext()));
1436 Value *RHS = ExpGen.codegen(eq->RHS,
1437 TD->getIntPtrType(Builder.getContext()));
1438 CmpInst::Predicate P;
1439
1440 if (eq->sign == 0)
1441 P = ICmpInst::ICMP_EQ;
1442 else if (eq->sign > 0)
1443 P = ICmpInst::ICMP_SGE;
1444 else
1445 P = ICmpInst::ICMP_SLE;
1446
1447 return Builder.CreateICmp(P, LHS, RHS);
1448}
1449
1450void ClastStmtCodeGen::codegen(const clast_guard *g) {
1451 Function *F = Builder.GetInsertBlock()->getParent();
1452 LLVMContext &Context = F->getContext();
Tobias Grosser0ac92142012-02-14 14:02:27 +00001453
1454 BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1455 Builder.GetInsertPoint(), P);
1456 CondBB->setName("polly.cond");
1457 BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1458 MergeBB->setName("polly.merge");
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001459 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001460
1461 DT->addNewBlock(ThenBB, CondBB);
1462 DT->changeImmediateDominator(MergeBB, CondBB);
1463
1464 CondBB->getTerminator()->eraseFromParent();
1465
1466 Builder.SetInsertPoint(CondBB);
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001467
1468 Value *Predicate = codegen(&(g->eq[0]));
1469
1470 for (int i = 1; i < g->n; ++i) {
1471 Value *TmpPredicate = codegen(&(g->eq[i]));
1472 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1473 }
1474
1475 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1476 Builder.SetInsertPoint(ThenBB);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001477 Builder.CreateBr(MergeBB);
1478 Builder.SetInsertPoint(ThenBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001479
1480 codegen(g->then);
Tobias Grosser62a3c962012-02-16 09:56:21 +00001481
1482 Builder.SetInsertPoint(MergeBB->begin());
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001483}
1484
1485void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1486 if (CLAST_STMT_IS_A(stmt, stmt_root))
1487 assert(false && "No second root statement expected");
1488 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1489 codegen((const clast_assignment *)stmt);
1490 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1491 codegen((const clast_user_stmt *)stmt);
1492 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1493 codegen((const clast_block *)stmt);
1494 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1495 codegen((const clast_for *)stmt);
1496 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1497 codegen((const clast_guard *)stmt);
1498
1499 if (stmt->next)
1500 codegen(stmt->next);
1501}
1502
1503void ClastStmtCodeGen::addParameters(const CloogNames *names) {
1504 SCEVExpander Rewriter(SE, "polly");
1505
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001506 int i = 0;
1507 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1508 PI != PE; ++PI) {
1509 assert(i < names->nb_parameters && "Not enough parameter names");
1510
1511 const SCEV *Param = *PI;
1512 Type *Ty = Param->getType();
1513
1514 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1515 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1516 (*clastVars)[names->parameters[i]] = V;
1517
1518 ++i;
1519 }
1520}
1521
1522void ClastStmtCodeGen::codegen(const clast_root *r) {
1523 clastVars = new CharMapT();
1524 addParameters(r->names);
1525 ExpGen.setIVS(clastVars);
1526
1527 parallelCodeGeneration = false;
1528
1529 const clast_stmt *stmt = (const clast_stmt*) r;
1530 if (stmt->next)
1531 codegen(stmt->next);
1532
1533 delete clastVars;
1534}
1535
1536ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, ScalarEvolution &se,
1537 DominatorTree *dt, ScopDetection *sd,
1538 Dependences *dp, TargetData *td,
Tobias Grosser0ac92142012-02-14 14:02:27 +00001539 IRBuilder<> &B, Pass *P) :
1540 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), P(P), Builder(B),
Tobias Grosser9bc5eb082012-01-24 16:42:32 +00001541 ExpGen(Builder, NULL) {}
1542
Tobias Grosser75805372011-04-29 06:27:02 +00001543namespace {
1544class CodeGeneration : public ScopPass {
1545 Region *region;
1546 Scop *S;
1547 DominatorTree *DT;
1548 ScalarEvolution *SE;
1549 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001550 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001551 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001552
1553 std::vector<std::string> parallelLoops;
1554
1555 public:
1556 static char ID;
1557
1558 CodeGeneration() : ScopPass(ID) {}
1559
Tobias Grosserb1c95992012-02-12 12:09:27 +00001560 // Add the declarations needed by the OpenMP function calls that we insert in
1561 // OpenMP mode.
1562 void addOpenMPDeclarations(Module *M)
Tobias Grosser75805372011-04-29 06:27:02 +00001563 {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001564 IRBuilder<> Builder(M->getContext());
1565 IntegerType *LongTy = TD->getIntPtrType(M->getContext());
1566
1567 llvm::GlobalValue::LinkageTypes Linkage = Function::ExternalLinkage;
Tobias Grosser75805372011-04-29 06:27:02 +00001568
1569 if (!M->getFunction("GOMP_parallel_end")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001570 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1571 Function::Create(Ty, Linkage, "GOMP_parallel_end", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001572 }
1573
1574 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001575 Type *Params[] = {
1576 PointerType::getUnqual(FunctionType::get(Builder.getVoidTy(),
1577 Builder.getInt8PtrTy(),
1578 false)),
1579 Builder.getInt8PtrTy(),
1580 Builder.getInt32Ty(),
1581 LongTy,
1582 LongTy,
1583 LongTy,
1584 };
Tobias Grosser75805372011-04-29 06:27:02 +00001585
Tobias Grosserd855cc52012-02-12 12:09:32 +00001586 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), Params, false);
1587 Function::Create(Ty, Linkage, "GOMP_parallel_loop_runtime_start", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001588 }
1589
1590 if (!M->getFunction("GOMP_loop_runtime_next")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001591 PointerType *LongPtrTy = PointerType::getUnqual(LongTy);
1592 Type *Params[] = {
1593 LongPtrTy,
1594 LongPtrTy,
1595 };
Tobias Grosser75805372011-04-29 06:27:02 +00001596
Tobias Grosserd855cc52012-02-12 12:09:32 +00001597 FunctionType *Ty = FunctionType::get(Builder.getInt8Ty(), Params, false);
1598 Function::Create(Ty, Linkage, "GOMP_loop_runtime_next", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001599 }
1600
1601 if (!M->getFunction("GOMP_loop_end_nowait")) {
Tobias Grosserd855cc52012-02-12 12:09:32 +00001602 FunctionType *Ty = FunctionType::get(Builder.getVoidTy(), false);
1603 Function::Create(Ty, Linkage, "GOMP_loop_end_nowait", M);
Tobias Grosser75805372011-04-29 06:27:02 +00001604 }
1605 }
1606
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001607 // Split the entry edge of the region and generate a new basic block on this
1608 // edge. This function also updates ScopInfo and RegionInfo.
1609 //
1610 // @param region The region where the entry edge will be splitted.
1611 BasicBlock *splitEdgeAdvanced(Region *region) {
1612 BasicBlock *newBlock;
1613 BasicBlock *splitBlock;
1614
1615 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1616
1617 if (DT->dominates(region->getEntry(), newBlock)) {
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001618 BasicBlock *OldBlock = region->getEntry();
1619 std::string OldName = OldBlock->getName();
1620
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001621 // Update ScopInfo.
1622 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
Tobias Grosserf12cea42012-02-15 09:58:53 +00001623 if ((*SI)->getBasicBlock() == OldBlock) {
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001624 (*SI)->setBasicBlock(newBlock);
1625 break;
1626 }
1627
1628 // Update RegionInfo.
Tobias Grossercb47dfe2012-02-15 09:58:50 +00001629 splitBlock = OldBlock;
1630 OldBlock->setName("polly.split");
1631 newBlock->setName(OldName);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001632 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001633 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001634 } else {
1635 RI->setRegionFor(newBlock, region->getParent());
1636 splitBlock = newBlock;
1637 }
1638
1639 return splitBlock;
1640 }
1641
1642 // Create a split block that branches either to the old code or to a new basic
1643 // block where the new code can be inserted.
1644 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001645 // @param Builder A builder that will be set to point to a basic block, where
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001646 // the new code can be generated.
1647 // @return The split basic block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001648 BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1649 BasicBlock *StartBlock, *SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001650
Tobias Grosserbd608a82012-02-12 12:09:41 +00001651 SplitBlock = splitEdgeAdvanced(region);
1652 SplitBlock->setName("polly.split_new_and_old");
1653 Function *F = SplitBlock->getParent();
1654 StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1655 SplitBlock->getTerminator()->eraseFromParent();
1656 Builder->SetInsertPoint(SplitBlock);
1657 Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1658 DT->addNewBlock(StartBlock, SplitBlock);
1659 Builder->SetInsertPoint(StartBlock);
1660 return SplitBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001661 }
1662
1663 // Merge the control flow of the newly generated code with the existing code.
1664 //
Tobias Grosserbd608a82012-02-12 12:09:41 +00001665 // @param SplitBlock The basic block where the control flow was split between
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001666 // old and new version of the Scop.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001667 // @param Builder An IRBuilder that points to the last instruction of the
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001668 // newly generated code.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001669 void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1670 BasicBlock *MergeBlock;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001671 Region *R = region;
1672
1673 if (R->getExit()->getSinglePredecessor())
1674 // No splitEdge required. A block with a single predecessor cannot have
1675 // PHI nodes that would complicate life.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001676 MergeBlock = R->getExit();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001677 else {
Tobias Grosserbd608a82012-02-12 12:09:41 +00001678 MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001679 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1680 // one predecessor. Hence, mergeBlock is always a newly generated block.
Tobias Grosserbd608a82012-02-12 12:09:41 +00001681 R->replaceExit(MergeBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001682 }
1683
Tobias Grosserbd608a82012-02-12 12:09:41 +00001684 Builder->CreateBr(MergeBlock);
Tobias Grosser8518bbe2012-02-12 12:09:46 +00001685 MergeBlock->setName("polly.merge_new_and_old");
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001686
Tobias Grosserbd608a82012-02-12 12:09:41 +00001687 if (DT->dominates(SplitBlock, MergeBlock))
1688 DT->changeImmediateDominator(MergeBlock, SplitBlock);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001689 }
1690
Tobias Grosser75805372011-04-29 06:27:02 +00001691 bool runOnScop(Scop &scop) {
1692 S = &scop;
1693 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001694 DT = &getAnalysis<DominatorTree>();
1695 Dependences *DP = &getAnalysis<Dependences>();
1696 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001697 SD = &getAnalysis<ScopDetection>();
1698 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001699 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001700
1701 parallelLoops.clear();
1702
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001703 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001704
Tobias Grosserb1c95992012-02-12 12:09:27 +00001705 Module *M = region->getEntry()->getParent()->getParent();
1706
Tobias Grosserd855cc52012-02-12 12:09:32 +00001707 if (OpenMP) addOpenMPDeclarations(M);
Tobias Grosserb1c95992012-02-12 12:09:27 +00001708
Tobias Grosser5772e652012-02-01 14:23:33 +00001709 // In the CFG the optimized code of the SCoP is generated next to the
1710 // original code. Both the new and the original version of the code remain
1711 // in the CFG. A branch statement decides which version is executed.
1712 // For now, we always execute the new version (the old one is dead code
1713 // eliminated by the cleanup passes). In the future we may decide to execute
1714 // the new version only if certain run time checks succeed. This will be
1715 // useful to support constructs for which we cannot prove all assumptions at
1716 // compile time.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001717 //
1718 // Before transformation:
1719 //
1720 // bb0
1721 // |
1722 // orig_scop
1723 // |
1724 // bb1
1725 //
1726 // After transformation:
1727 // bb0
1728 // |
1729 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001730 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001731 // | startBlock
1732 // | |
1733 // orig_scop new_scop
1734 // \ /
1735 // \ /
1736 // bb1 (joinBlock)
1737 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001738
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001739 // The builder will be set to startBlock.
1740 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser0ac92142012-02-14 14:02:27 +00001741 BasicBlock *StartBlock = builder.GetInsertBlock();
Tobias Grosser75805372011-04-29 06:27:02 +00001742
Tobias Grosser0ac92142012-02-14 14:02:27 +00001743 mergeControlFlow(splitBlock, &builder);
1744 builder.SetInsertPoint(StartBlock->begin());
1745
1746 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder, this);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001747 CloogInfo &C = getAnalysis<CloogInfo>();
1748 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001749
Tobias Grosser75805372011-04-29 06:27:02 +00001750 parallelLoops.insert(parallelLoops.begin(),
1751 CodeGen.getParallelLoops().begin(),
1752 CodeGen.getParallelLoops().end());
1753
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001754 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001755 }
1756
1757 virtual void printScop(raw_ostream &OS) const {
1758 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1759 PE = parallelLoops.end(); PI != PE; ++PI)
1760 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1761 }
1762
1763 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1764 AU.addRequired<CloogInfo>();
1765 AU.addRequired<Dependences>();
1766 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001767 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001768 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001769 AU.addRequired<ScopDetection>();
1770 AU.addRequired<ScopInfo>();
1771 AU.addRequired<TargetData>();
1772
1773 AU.addPreserved<CloogInfo>();
1774 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001775
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001776 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001777 AU.addPreserved<LoopInfo>();
1778 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001779 AU.addPreserved<ScopDetection>();
1780 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001781
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001782 // FIXME: We do not yet add regions for the newly generated code to the
1783 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001784 AU.addPreserved<RegionInfo>();
1785 AU.addPreserved<TempScopInfo>();
1786 AU.addPreserved<ScopInfo>();
1787 AU.addPreservedID(IndependentBlocksID);
1788 }
1789};
1790}
1791
1792char CodeGeneration::ID = 1;
1793
Tobias Grosser73600b82011-10-08 00:30:40 +00001794INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1795 "Polly - Create LLVM-IR form SCoPs", false, false)
1796INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1797INITIALIZE_PASS_DEPENDENCY(Dependences)
1798INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1799INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1800INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1801INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1802INITIALIZE_PASS_DEPENDENCY(TargetData)
1803INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1804 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001805
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001806Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001807 return new CodeGeneration();
1808}