blob: 5e155aa46fa81ab1228e341e9c6893369e1e589a [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===------ CodeGeneration.cpp - Code generate the Scops. -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The CodeGeneration pass takes a Scop created by ScopInfo and translates it
11// back to LLVM-IR using Cloog.
12//
13// The Scop describes the high level memory behaviour of a control flow region.
14// Transformation passes can update the schedule (execution order) of statements
15// in the Scop. Cloog is used to generate an abstract syntax tree (clast) that
16// reflects the updated execution order. This clast is used to create new
17// LLVM-IR that is computational equivalent to the original control flow region,
18// but executes its code in the new execution order defined by the changed
19// scattering.
20//
21//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "polly-codegen"
24
25#include "polly/LinkAllPasses.h"
26#include "polly/Support/GICHelper.h"
27#include "polly/Support/ScopHelper.h"
28#include "polly/Cloog.h"
29#include "polly/Dependences.h"
30#include "polly/ScopInfo.h"
31#include "polly/TempScopInfo.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/IRBuilder.h"
35#include "llvm/Analysis/LoopInfo.h"
36#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser8c4cfc322011-05-14 19:01:49 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Module.h"
40#include "llvm/ADT/SetVector.h"
41
42#define CLOOG_INT_GMP 1
43#include "cloog/cloog.h"
44#include "cloog/isl/cloog.h"
45
46#include <vector>
47#include <utility>
48
49using namespace polly;
50using namespace llvm;
51
52struct isl_set;
53
54namespace polly {
55
56static cl::opt<bool>
57Vector("enable-polly-vector",
58 cl::desc("Enable polly vector code generation"), cl::Hidden,
59 cl::value_desc("Vector code generation enabled if true"),
60 cl::init(false));
61
62static cl::opt<bool>
63OpenMP("enable-polly-openmp",
64 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
65 cl::value_desc("OpenMP code generation enabled if true"),
66 cl::init(false));
67
68static cl::opt<bool>
69AtLeastOnce("enable-polly-atLeastOnce",
70 cl::desc("Give polly the hint, that every loop is executed at least"
71 "once"), cl::Hidden,
72 cl::value_desc("OpenMP code generation enabled if true"),
73 cl::init(false));
74
75static cl::opt<bool>
76Aligned("enable-polly-aligned",
77 cl::desc("Assumed aligned memory accesses."), cl::Hidden,
78 cl::value_desc("OpenMP code generation enabled if true"),
79 cl::init(false));
80
Tobias Grosser75805372011-04-29 06:27:02 +000081typedef DenseMap<const Value*, Value*> ValueMapT;
82typedef DenseMap<const char*, Value*> CharMapT;
83typedef std::vector<ValueMapT> VectorValueMapT;
84
85// Create a new loop.
86//
87// @param Builder The builder used to create the loop. It also defines the
88// place where to create the loop.
89// @param UB The upper bound of the loop iv.
90// @param Stride The number by which the loop iv is incremented after every
91// iteration.
92static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride,
93 PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV,
94 DominatorTree *DT) {
95 Function *F = Builder->GetInsertBlock()->getParent();
96 LLVMContext &Context = F->getContext();
97
98 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
99 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
100 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
101 AfterBB = BasicBlock::Create(Context, "polly.after_loop", F);
102
103 Builder->CreateBr(HeaderBB);
104 DT->addNewBlock(HeaderBB, PreheaderBB);
105
106 Builder->SetInsertPoint(BodyBB);
107
108 Builder->SetInsertPoint(HeaderBB);
109
110 // Use the type of upper and lower bound.
111 assert(LB->getType() == UB->getType()
112 && "Different types for upper and lower bound.");
113
Tobias Grosser55927aa2011-07-18 09:53:32 +0000114 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000115 assert(LoopIVType && "UB is not integer?");
116
117 // IV
118 IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
119 IV->addIncoming(LB, PreheaderBB);
120
121 // IV increment.
122 Value *StrideValue = ConstantInt::get(LoopIVType,
123 Stride.zext(LoopIVType->getBitWidth()));
124 IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv");
125
126 // Exit condition.
127 if (AtLeastOnce) { // At least on iteration.
128 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
129 Value *CMP = Builder->CreateICmpEQ(IV, UB);
130 Builder->CreateCondBr(CMP, AfterBB, BodyBB);
131 } else { // Maybe not executed at all.
132 Value *CMP = Builder->CreateICmpSLE(IV, UB);
133 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
134 }
135 DT->addNewBlock(BodyBB, HeaderBB);
136 DT->addNewBlock(AfterBB, HeaderBB);
137
138 Builder->SetInsertPoint(BodyBB);
139}
140
141class BlockGenerator {
142 IRBuilder<> &Builder;
143 ValueMapT &VMap;
144 VectorValueMapT &ValueMaps;
145 Scop &S;
146 ScopStmt &statement;
147 isl_set *scatteringDomain;
148
149public:
150 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
151 ScopStmt &Stmt, isl_set *domain)
152 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
153 statement(Stmt), scatteringDomain(domain) {}
154
155 const Region &getRegion() {
156 return S.getRegion();
157 }
158
159 Value* makeVectorOperand(Value *operand, int vectorWidth) {
160 if (operand->getType()->isVectorTy())
161 return operand;
162
163 VectorType *vectorType = VectorType::get(operand->getType(), vectorWidth);
164 Value *vector = UndefValue::get(vectorType);
165 vector = Builder.CreateInsertElement(vector, operand, Builder.getInt32(0));
166
167 std::vector<Constant*> splat;
168
169 for (int i = 0; i < vectorWidth; i++)
170 splat.push_back (Builder.getInt32(0));
171
172 Constant *splatVector = ConstantVector::get(splat);
173
174 return Builder.CreateShuffleVector(vector, vector, splatVector);
175 }
176
Raghesh Aloor490c5982011-08-08 08:34:16 +0000177 Value* getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000178 ValueMapT *VectorMap = 0) {
Raghesh Aloor490c5982011-08-08 08:34:16 +0000179 const Instruction *OpInst = dyn_cast<Instruction>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000180
181 if (!OpInst)
Raghesh Aloor490c5982011-08-08 08:34:16 +0000182 return const_cast<Value*>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000183
Raghesh Aloor490c5982011-08-08 08:34:16 +0000184 if (VectorMap && VectorMap->count(oldOperand))
185 return (*VectorMap)[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000186
187 // IVS and Parameters.
Raghesh Aloor490c5982011-08-08 08:34:16 +0000188 if (VMap.count(oldOperand)) {
189 Value *NewOperand = VMap[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000190
191 // Insert a cast if types are different
Raghesh Aloor490c5982011-08-08 08:34:16 +0000192 if (oldOperand->getType()->getScalarSizeInBits()
Tobias Grosser75805372011-04-29 06:27:02 +0000193 < NewOperand->getType()->getScalarSizeInBits())
194 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
Raghesh Aloor490c5982011-08-08 08:34:16 +0000195 oldOperand->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000196
197 return NewOperand;
198 }
199
200 // Instructions calculated in the current BB.
Raghesh Aloor490c5982011-08-08 08:34:16 +0000201 if (BBMap.count(oldOperand)) {
202 return BBMap[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000203 }
204
205 // Ignore instructions that are referencing ops in the old BB. These
206 // instructions are unused. They where replace by new ones during
207 // createIndependentBlocks().
208 if (getRegion().contains(OpInst->getParent()))
209 return NULL;
210
Raghesh Aloor490c5982011-08-08 08:34:16 +0000211 return const_cast<Value*>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000212 }
213
Tobias Grosser55927aa2011-07-18 09:53:32 +0000214 Type *getVectorPtrTy(const Value *V, int vectorWidth) {
215 PointerType *pointerType = dyn_cast<PointerType>(V->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000216 assert(pointerType && "PointerType expected");
217
Tobias Grosser55927aa2011-07-18 09:53:32 +0000218 Type *scalarType = pointerType->getElementType();
Tobias Grosser75805372011-04-29 06:27:02 +0000219 VectorType *vectorType = VectorType::get(scalarType, vectorWidth);
220
221 return PointerType::getUnqual(vectorType);
222 }
223
224 /// @brief Load a vector from a set of adjacent scalars
225 ///
226 /// In case a set of scalars is known to be next to each other in memory,
227 /// create a vector load that loads those scalars
228 ///
229 /// %vector_ptr= bitcast double* %p to <4 x double>*
230 /// %vec_full = load <4 x double>* %vector_ptr
231 ///
232 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
233 int size) {
234 const Value *pointer = load->getPointerOperand();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000235 Type *vectorPtrType = getVectorPtrTy(pointer, size);
Tobias Grosser75805372011-04-29 06:27:02 +0000236 Value *newPointer = getOperand(pointer, BBMap);
237 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
238 "vector_ptr");
239 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
240 load->getNameStr()
241 + "_p_vec_full");
242 if (!Aligned)
243 VecLoad->setAlignment(8);
244
245 return VecLoad;
246 }
247
248 /// @brief Load a vector initialized from a single scalar in memory
249 ///
250 /// In case all elements of a vector are initialized to the same
251 /// scalar value, this value is loaded and shuffeled into all elements
252 /// of the vector.
253 ///
254 /// %splat_one = load <1 x double>* %p
255 /// %splat = shufflevector <1 x double> %splat_one, <1 x
256 /// double> %splat_one, <4 x i32> zeroinitializer
257 ///
258 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
259 int size) {
260 const Value *pointer = load->getPointerOperand();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000261 Type *vectorPtrType = getVectorPtrTy(pointer, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000262 Value *newPointer = getOperand(pointer, BBMap);
263 Value *vectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
264 load->getNameStr() + "_p_vec_p");
265 LoadInst *scalarLoad= Builder.CreateLoad(vectorPtr,
266 load->getNameStr() + "_p_splat_one");
267
268 if (!Aligned)
269 scalarLoad->setAlignment(8);
270
271 std::vector<Constant*> splat;
272
273 for (int i = 0; i < size; i++)
274 splat.push_back (Builder.getInt32(0));
275
276 Constant *splatVector = ConstantVector::get(splat);
277
278 Value *vectorLoad = Builder.CreateShuffleVector(scalarLoad, scalarLoad,
279 splatVector,
280 load->getNameStr()
281 + "_p_splat");
282 return vectorLoad;
283 }
284
285 /// @Load a vector from scalars distributed in memory
286 ///
287 /// In case some scalars a distributed randomly in memory. Create a vector
288 /// by loading each scalar and by inserting one after the other into the
289 /// vector.
290 ///
291 /// %scalar_1= load double* %p_1
292 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
293 /// %scalar 2 = load double* %p_2
294 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
295 ///
296 Value *generateUnknownStrideLoad(const LoadInst *load,
297 VectorValueMapT &scalarMaps,
298 int size) {
299 const Value *pointer = load->getPointerOperand();
300 VectorType *vectorType = VectorType::get(
301 dyn_cast<PointerType>(pointer->getType())->getElementType(), size);
302
303 Value *vector = UndefValue::get(vectorType);
304
305 for (int i = 0; i < size; i++) {
306 Value *newPointer = getOperand(pointer, scalarMaps[i]);
307 Value *scalarLoad = Builder.CreateLoad(newPointer,
308 load->getNameStr() + "_p_scalar_");
309 vector = Builder.CreateInsertElement(vector, scalarLoad,
310 Builder.getInt32(i),
311 load->getNameStr() + "_p_vec_");
312 }
313
314 return vector;
315 }
316
Raghesh Aloor129e8672011-08-15 02:33:39 +0000317 /// @brief Get the memory access offset to be added to the base address
318 std::vector <Value*> getMemoryAccessIndex(isl_map *accessRelation,
319 Value *baseAddr) {
320 isl_int offsetMPZ;
321 isl_int_init(offsetMPZ);
322
323 assert((isl_map_dim(accessRelation, isl_dim_out) == 1)
324 && "Only single dimensional access functions supported");
325
326 if (isl_map_plain_is_fixed(accessRelation, isl_dim_out,
327 0, &offsetMPZ) == -1)
328 errs() << "Only fixed value access functions supported\n";
329
330 // Convert the offset from MPZ to Value*.
331 APInt offset = APInt_from_MPZ(offsetMPZ);
332 Value *offsetValue = ConstantInt::get(Builder.getContext(), offset);
333 PointerType *baseAddrType = dyn_cast<PointerType>(baseAddr->getType());
334 Type *arrayType = baseAddrType->getElementType();
335 Type *arrayElementType = dyn_cast<ArrayType>(arrayType)->getElementType();
336 offsetValue = Builder.CreateSExtOrBitCast(offsetValue, arrayElementType);
337
338 std::vector<Value*> indexArray;
339 Value *nullValue = Constant::getNullValue(arrayElementType);
340 indexArray.push_back(nullValue);
341 indexArray.push_back(offsetValue);
342
343 isl_int_clear(offsetMPZ);
344 return indexArray;
345 }
346
Raghesh Aloor62b13122011-08-03 17:02:50 +0000347 /// @brief Get the new operand address according to the changed access in
348 /// JSCOP file.
349 Value *getNewAccessOperand(isl_map *newAccessRelation, Value *baseAddr,
Raghesh Aloor490c5982011-08-08 08:34:16 +0000350 const Value *oldOperand, ValueMapT &BBMap) {
Raghesh Aloor129e8672011-08-15 02:33:39 +0000351 std::vector<Value*> indexArray = getMemoryAccessIndex(newAccessRelation,
352 baseAddr);
353 Value *newOperand = Builder.CreateGEP(baseAddr, indexArray,
354 "p_newarrayidx_");
Raghesh Aloor62b13122011-08-03 17:02:50 +0000355 return newOperand;
356 }
357
358 /// @brief Generate the operand address
359 Value *generateLocationAccessed(const Instruction *Inst,
360 const Value *pointer, ValueMapT &BBMap ) {
Raghesh Aloor490c5982011-08-08 08:34:16 +0000361 MemoryAccess &access = statement.getAccessFor(Inst);
Raghesh Aloor129e8672011-08-15 02:33:39 +0000362 isl_map *currentAccessRelation = access.getAccessFunction();
Raghesh Aloor490c5982011-08-08 08:34:16 +0000363 isl_map *newAccessRelation = access.getNewAccessFunction();
Raghesh Aloor129e8672011-08-15 02:33:39 +0000364
Tobias Grosserf5338802011-10-06 00:03:35 +0000365 assert(isl_map_has_equal_space(currentAccessRelation, newAccessRelation)
366 && "Current and new access function use different spaces");
Raghesh Aloor129e8672011-08-15 02:33:39 +0000367
Raghesh Aloor62b13122011-08-03 17:02:50 +0000368 if (!newAccessRelation) {
369 Value *newPointer = getOperand(pointer, BBMap);
370 return newPointer;
371 }
Raghesh Aloore75e9862011-08-11 08:44:56 +0000372
Raghesh Aloor490c5982011-08-08 08:34:16 +0000373 Value *baseAddr = const_cast<Value*>(access.getBaseAddr());
Raghesh Aloor62b13122011-08-03 17:02:50 +0000374 Value *newPointer = getNewAccessOperand(newAccessRelation, baseAddr,
375 pointer, BBMap);
376 return newPointer;
377 }
378
Tobias Grosser75805372011-04-29 06:27:02 +0000379 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap) {
380 const Value *pointer = load->getPointerOperand();
Raghesh Aloor62b13122011-08-03 17:02:50 +0000381 const Instruction *Inst = dyn_cast<Instruction>(load);
382 Value *newPointer = generateLocationAccessed(Inst, pointer, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000383 Value *scalarLoad = Builder.CreateLoad(newPointer,
384 load->getNameStr() + "_p_scalar_");
385 return scalarLoad;
386 }
387
388 /// @brief Load a value (or several values as a vector) from memory.
389 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
390 VectorValueMapT &scalarMaps, int vectorWidth) {
Tobias Grosser75805372011-04-29 06:27:02 +0000391 if (scalarMaps.size() == 1) {
392 scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]);
393 return;
394 }
395
396 Value *newLoad;
397
398 MemoryAccess &Access = statement.getAccessFor(load);
399
400 assert(scatteringDomain && "No scattering domain available");
401
402 if (Access.isStrideZero(scatteringDomain))
403 newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth);
404 else if (Access.isStrideOne(scatteringDomain))
405 newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth);
406 else
407 newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth);
408
409 vectorMap[load] = newLoad;
410 }
411
Tobias Grosserc9215152011-09-04 11:45:52 +0000412 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
413 ValueMapT &VectorMap, int VectorDimension,
414 int VectorWidth) {
415 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
416 NewOperand = makeVectorOperand(NewOperand, VectorWidth);
417
418 if (const CastInst *Cast = dyn_cast<CastInst>(Inst)) {
419 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
420 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand,
421 DestType);
422 } else
423 llvm_unreachable("Can not generate vector code for instruction");
424 return;
425 }
426
Tobias Grosser09c57102011-09-04 11:45:29 +0000427 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosser8b00a512011-09-04 11:45:45 +0000428 ValueMapT &vectorMap, int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000429 Value *opZero = Inst->getOperand(0);
430 Value *opOne = Inst->getOperand(1);
431
Tobias Grosser09c57102011-09-04 11:45:29 +0000432 Value *newOpZero, *newOpOne;
433 newOpZero = getOperand(opZero, BBMap, &vectorMap);
434 newOpOne = getOperand(opOne, BBMap, &vectorMap);
435
Tobias Grosser7551c302011-09-04 11:45:41 +0000436 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
437 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000438
439 Value *newInst = Builder.CreateBinOp(Inst->getOpcode(), newOpZero,
Tobias Grosser7551c302011-09-04 11:45:41 +0000440 newOpOne,
441 Inst->getNameStr() + "p_vec");
442 vectorMap[Inst] = newInst;
Tobias Grosser09c57102011-09-04 11:45:29 +0000443
444 return;
445 }
446
447 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000448 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
449 int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000450 // In vector mode we only generate a store for the first dimension.
451 if (vectorDimension > 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000452 return;
453
Tobias Grosser09c57102011-09-04 11:45:29 +0000454 MemoryAccess &Access = statement.getAccessFor(store);
Tobias Grosser75805372011-04-29 06:27:02 +0000455
Tobias Grosser09c57102011-09-04 11:45:29 +0000456 assert(scatteringDomain && "No scattering domain available");
Tobias Grosser75805372011-04-29 06:27:02 +0000457
Tobias Grosser09c57102011-09-04 11:45:29 +0000458 const Value *pointer = store->getPointerOperand();
459 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000460
Tobias Grosser09c57102011-09-04 11:45:29 +0000461 if (Access.isStrideOne(scatteringDomain)) {
462 Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
463 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000464
Tobias Grosser09c57102011-09-04 11:45:29 +0000465 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
466 "vector_ptr");
467 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
Tobias Grosser75805372011-04-29 06:27:02 +0000468
Tobias Grosser09c57102011-09-04 11:45:29 +0000469 if (!Aligned)
470 Store->setAlignment(8);
471 } else {
472 for (unsigned i = 0; i < scalarMaps.size(); i++) {
473 Value *scalar = Builder.CreateExtractElement(vector,
474 Builder.getInt32(i));
475 Value *newPointer = getOperand(pointer, scalarMaps[i]);
476 Builder.CreateStore(scalar, newPointer);
Tobias Grosser75805372011-04-29 06:27:02 +0000477 }
478 }
479
Tobias Grosser09c57102011-09-04 11:45:29 +0000480 return;
481 }
482
Tobias Grosser7551c302011-09-04 11:45:41 +0000483 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
Tobias Grosser75805372011-04-29 06:27:02 +0000484 Instruction *NewInst = Inst->clone();
485
Tobias Grosser75805372011-04-29 06:27:02 +0000486 // Replace old operands with the new ones.
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000487 for (Instruction::const_op_iterator OI = Inst->op_begin(),
488 OE = Inst->op_end(); OI != OE; ++OI) {
489 Value *OldOperand = *OI;
490 Value *NewOperand = getOperand(OldOperand, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000491
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000492 if (!NewOperand) {
Tobias Grosser75805372011-04-29 06:27:02 +0000493 assert(!isa<StoreInst>(NewInst)
494 && "Store instructions are always needed!");
495 delete NewInst;
496 return;
497 }
498
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000499 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000500 }
501
502 Builder.Insert(NewInst);
503 BBMap[Inst] = NewInst;
504
505 if (!NewInst->getType()->isVoidTy())
506 NewInst->setName("p_" + Inst->getName());
507 }
508
Tobias Grosser7551c302011-09-04 11:45:41 +0000509 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap) {
510 for (Instruction::const_op_iterator OI = Inst->op_begin(),
511 OE = Inst->op_end(); OI != OE; ++OI)
512 if (VectorMap.count(*OI))
513 return true;
514 return false;
Tobias Grosser09c57102011-09-04 11:45:29 +0000515 }
516
Tobias Grosser75805372011-04-29 06:27:02 +0000517 int getVectorSize() {
518 return ValueMaps.size();
519 }
520
521 bool isVectorBlock() {
522 return getVectorSize() > 1;
523 }
524
Tobias Grosser7551c302011-09-04 11:45:41 +0000525 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
526 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
527 int vectorDimension, int vectorWidth) {
528 // Terminator instructions control the control flow. They are explicitally
529 // expressed in the clast and do not need to be copied.
530 if (Inst->isTerminator())
531 return;
532
533 if (isVectorBlock()) {
534 // If this instruction is already in the vectorMap, a vector instruction
535 // was already issued, that calculates the values of all dimensions. No
536 // need to create any more instructions.
537 if (vectorMap.count(Inst))
538 return;
539 }
540
541 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
542 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
543 return;
544 }
545
546 if (isVectorBlock() && hasVectorOperands(Inst, vectorMap)) {
Tobias Grosserc9215152011-09-04 11:45:52 +0000547 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
548 copyUnaryInst(UnaryInst, BBMap, vectorMap, vectorDimension,
549 vectorWidth);
550 else if
551 (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst))
Tobias Grosser8b00a512011-09-04 11:45:45 +0000552 copyBinInst(binaryInst, BBMap, vectorMap, vectorDimension, vectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000553 else if (const StoreInst *store = dyn_cast<StoreInst>(Inst))
554 copyVectorStore(store, BBMap, vectorMap, scalarMaps, vectorDimension,
555 vectorWidth);
556 else
557 llvm_unreachable("Cannot issue vector code for this instruction");
558
559 return;
560 }
561
562 copyInstScalar(Inst, BBMap);
563 }
Tobias Grosser75805372011-04-29 06:27:02 +0000564 // Insert a copy of a basic block in the newly generated code.
565 //
566 // @param Builder The builder used to insert the code. It also specifies
567 // where to insert the code.
568 // @param BB The basic block to copy
569 // @param VMap A map returning for any old value its new equivalent. This
570 // is used to update the operands of the statements.
571 // For new statements a relation old->new is inserted in this
572 // map.
573 void copyBB(BasicBlock *BB, DominatorTree *DT) {
574 Function *F = Builder.GetInsertBlock()->getParent();
575 LLVMContext &Context = F->getContext();
576 BasicBlock *CopyBB = BasicBlock::Create(Context,
Tobias Grosser8ae9aca2011-09-04 11:45:22 +0000577 "polly." + BB->getNameStr()
578 + ".stmt",
Tobias Grosser75805372011-04-29 06:27:02 +0000579 F);
580 Builder.CreateBr(CopyBB);
581 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
582 Builder.SetInsertPoint(CopyBB);
583
584 // Create two maps that store the mapping from the original instructions of
585 // the old basic block to their copies in the new basic block. Those maps
586 // are basic block local.
587 //
588 // As vector code generation is supported there is one map for scalar values
589 // and one for vector values.
590 //
591 // In case we just do scalar code generation, the vectorMap is not used and
592 // the scalarMap has just one dimension, which contains the mapping.
593 //
594 // In case vector code generation is done, an instruction may either appear
595 // in the vector map once (as it is calculating >vectorwidth< values at a
596 // time. Or (if the values are calculated using scalar operations), it
597 // appears once in every dimension of the scalarMap.
598 VectorValueMapT scalarBlockMap(getVectorSize());
599 ValueMapT vectorBlockMap;
600
601 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
602 II != IE; ++II)
603 for (int i = 0; i < getVectorSize(); i++) {
604 if (isVectorBlock())
605 VMap = ValueMaps[i];
606
607 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
608 scalarBlockMap, i, getVectorSize());
609 }
610 }
611};
612
613/// Class to generate LLVM-IR that calculates the value of a clast_expr.
614class ClastExpCodeGen {
615 IRBuilder<> &Builder;
616 const CharMapT *IVS;
617
Tobias Grosser55927aa2011-07-18 09:53:32 +0000618 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000619 CharMapT::const_iterator I = IVS->find(e->name);
620
621 if (I != IVS->end())
622 return Builder.CreateSExtOrBitCast(I->second, Ty);
623 else
624 llvm_unreachable("Clast name not found");
625 }
626
Tobias Grosser55927aa2011-07-18 09:53:32 +0000627 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000628 APInt a = APInt_from_MPZ(e->val);
629
630 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
631 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
632
633 if (e->var) {
634 Value *var = codegen(e->var, Ty);
635 return Builder.CreateMul(ConstOne, var);
636 }
637
638 return ConstOne;
639 }
640
Tobias Grosser55927aa2011-07-18 09:53:32 +0000641 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000642 Value *LHS = codegen(e->LHS, Ty);
643
644 APInt RHS_AP = APInt_from_MPZ(e->RHS);
645
646 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
647 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
648
649 switch (e->type) {
650 case clast_bin_mod:
651 return Builder.CreateSRem(LHS, RHS);
652 case clast_bin_fdiv:
653 {
654 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
655 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
656 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
657 One = Builder.CreateZExtOrBitCast(One, Ty);
658 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
659 Value *Sum1 = Builder.CreateSub(LHS, RHS);
660 Value *Sum2 = Builder.CreateAdd(Sum1, One);
661 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
662 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
663 return Builder.CreateSDiv(Dividend, RHS);
664 }
665 case clast_bin_cdiv:
666 {
667 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
668 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
669 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
670 One = Builder.CreateZExtOrBitCast(One, Ty);
671 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
672 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
673 Value *Sum2 = Builder.CreateSub(Sum1, One);
674 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
675 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
676 return Builder.CreateSDiv(Dividend, RHS);
677 }
678 case clast_bin_div:
679 return Builder.CreateSDiv(LHS, RHS);
680 default:
681 llvm_unreachable("Unknown clast binary expression type");
682 };
683 }
684
Tobias Grosser55927aa2011-07-18 09:53:32 +0000685 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000686 assert(( r->type == clast_red_min
687 || r->type == clast_red_max
688 || r->type == clast_red_sum)
689 && "Clast reduction type not supported");
690 Value *old = codegen(r->elts[0], Ty);
691
692 for (int i=1; i < r->n; ++i) {
693 Value *exprValue = codegen(r->elts[i], Ty);
694
695 switch (r->type) {
696 case clast_red_min:
697 {
698 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
699 old = Builder.CreateSelect(cmp, old, exprValue);
700 break;
701 }
702 case clast_red_max:
703 {
704 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
705 old = Builder.CreateSelect(cmp, old, exprValue);
706 break;
707 }
708 case clast_red_sum:
709 old = Builder.CreateAdd(old, exprValue);
710 break;
711 default:
712 llvm_unreachable("Clast unknown reduction type");
713 }
714 }
715
716 return old;
717 }
718
719public:
720
721 // A generator for clast expressions.
722 //
723 // @param B The IRBuilder that defines where the code to calculate the
724 // clast expressions should be inserted.
725 // @param IVMAP A Map that translates strings describing the induction
726 // variables to the Values* that represent these variables
727 // on the LLVM side.
728 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
729
730 // Generates code to calculate a given clast expression.
731 //
732 // @param e The expression to calculate.
733 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000734 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000735 switch(e->type) {
736 case clast_expr_name:
737 return codegen((const clast_name *)e, Ty);
738 case clast_expr_term:
739 return codegen((const clast_term *)e, Ty);
740 case clast_expr_bin:
741 return codegen((const clast_binary *)e, Ty);
742 case clast_expr_red:
743 return codegen((const clast_reduction *)e, Ty);
744 default:
745 llvm_unreachable("Unknown clast expression!");
746 }
747 }
748
749 // @brief Reset the CharMap.
750 //
751 // This function is called to reset the CharMap to new one, while generating
752 // OpenMP code.
753 void setIVS(CharMapT *IVSNew) {
754 IVS = IVSNew;
755 }
756
757};
758
759class ClastStmtCodeGen {
760 // The Scop we code generate.
761 Scop *S;
762 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000763 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000764 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000765 Dependences *DP;
766 TargetData *TD;
767
768 // The Builder specifies the current location to code generate at.
769 IRBuilder<> &Builder;
770
771 // Map the Values from the old code to their counterparts in the new code.
772 ValueMapT ValueMap;
773
774 // clastVars maps from the textual representation of a clast variable to its
775 // current *Value. clast variables are scheduling variables, original
776 // induction variables or parameters. They are used either in loop bounds or
777 // to define the statement instance that is executed.
778 //
779 // for (s = 0; s < n + 3; ++i)
780 // for (t = s; t < m; ++j)
781 // Stmt(i = s + 3 * m, j = t);
782 //
783 // {s,t,i,j,n,m} is the set of clast variables in this clast.
784 CharMapT *clastVars;
785
786 // Codegenerator for clast expressions.
787 ClastExpCodeGen ExpGen;
788
789 // Do we currently generate parallel code?
790 bool parallelCodeGeneration;
791
792 std::vector<std::string> parallelLoops;
793
794public:
795
796 const std::vector<std::string> &getParallelLoops() {
797 return parallelLoops;
798 }
799
800 protected:
801 void codegen(const clast_assignment *a) {
802 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
803 TD->getIntPtrType(Builder.getContext()));
804 }
805
806 void codegen(const clast_assignment *a, ScopStmt *Statement,
807 unsigned Dimension, int vectorDim,
808 std::vector<ValueMapT> *VectorVMap = 0) {
809 Value *RHS = ExpGen.codegen(a->RHS,
810 TD->getIntPtrType(Builder.getContext()));
811
812 assert(!a->LHS && "Statement assignments do not have left hand side");
813 const PHINode *PN;
814 PN = Statement->getInductionVariableForDimension(Dimension);
815 const Value *V = PN;
816
Tobias Grosser75805372011-04-29 06:27:02 +0000817 if (VectorVMap)
818 (*VectorVMap)[vectorDim][V] = RHS;
819
820 ValueMap[V] = RHS;
821 }
822
823 void codegenSubstitutions(const clast_stmt *Assignment,
824 ScopStmt *Statement, int vectorDim = 0,
825 std::vector<ValueMapT> *VectorVMap = 0) {
826 int Dimension = 0;
827
828 while (Assignment) {
829 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
830 && "Substitions are expected to be assignments");
831 codegen((const clast_assignment *)Assignment, Statement, Dimension,
832 vectorDim, VectorVMap);
833 Assignment = Assignment->next;
834 Dimension++;
835 }
836 }
837
838 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
839 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
840 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
841 BasicBlock *BB = Statement->getBasicBlock();
842
843 if (u->substitutions)
844 codegenSubstitutions(u->substitutions, Statement);
845
846 int vectorDimensions = IVS ? IVS->size() : 1;
847
848 VectorValueMapT VectorValueMap(vectorDimensions);
849
850 if (IVS) {
851 assert (u->substitutions && "Substitutions expected!");
852 int i = 0;
853 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
854 II != IE; ++II) {
855 (*clastVars)[iterator] = *II;
856 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
857 i++;
858 }
859 }
860
861 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
862 scatteringDomain);
863 Generator.copyBB(BB, DT);
864 }
865
866 void codegen(const clast_block *b) {
867 if (b->body)
868 codegen(b->body);
869 }
870
871 /// @brief Create a classical sequential loop.
872 void codegenForSequential(const clast_for *f, Value *lowerBound = 0,
873 Value *upperBound = 0) {
874 APInt Stride = APInt_from_MPZ(f->stride);
875 PHINode *IV;
876 Value *IncrementedIV;
877 BasicBlock *AfterBB;
878 // The value of lowerbound and upperbound will be supplied, if this
879 // function is called while generating OpenMP code. Otherwise get
880 // the values.
881 assert(((lowerBound && upperBound) || (!lowerBound && !upperBound))
882 && "Either give both bounds or none");
883 if (lowerBound == 0 || upperBound == 0) {
884 lowerBound = ExpGen.codegen(f->LB,
885 TD->getIntPtrType(Builder.getContext()));
886 upperBound = ExpGen.codegen(f->UB,
887 TD->getIntPtrType(Builder.getContext()));
888 }
889 createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB,
890 IncrementedIV, DT);
891
892 // Add loop iv to symbols.
893 (*clastVars)[f->iterator] = IV;
894
895 if (f->body)
896 codegen(f->body);
897
898 // Loop is finished, so remove its iv from the live symbols.
899 clastVars->erase(f->iterator);
900
901 BasicBlock *HeaderBB = *pred_begin(AfterBB);
902 BasicBlock *LastBodyBB = Builder.GetInsertBlock();
903 Builder.CreateBr(HeaderBB);
904 IV->addIncoming(IncrementedIV, LastBodyBB);
905 Builder.SetInsertPoint(AfterBB);
906 }
907
Tobias Grosser75805372011-04-29 06:27:02 +0000908 /// @brief Add a new definition of an openmp subfunction.
909 Function* addOpenMPSubfunction(Module *M) {
910 Function *F = Builder.GetInsertBlock()->getParent();
911 const std::string &Name = F->getNameStr() + ".omp_subfn";
912
Tobias Grosser851b96e2011-07-12 12:42:54 +0000913 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +0000914 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
915 Function *FN = Function::Create(FT, Function::InternalLinkage, Name, M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000916 // Do not run any polly pass on the new function.
917 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +0000918
919 Function::arg_iterator AI = FN->arg_begin();
920 AI->setName("omp.userContext");
921
922 return FN;
923 }
924
925 /// @brief Add values to the OpenMP structure.
926 ///
927 /// Create the subfunction structure and add the values from the list.
928 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
929 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +0000930 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +0000931
932 // Create the structure.
933 for (unsigned i = 0; i < OMPDataVals.size(); i++)
934 structMembers.push_back(OMPDataVals[i]->getType());
935
Tobias Grosser75805372011-04-29 06:27:02 +0000936 StructType *structTy = StructType::get(Builder.getContext(),
937 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +0000938 // Store the values into the structure.
939 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
940 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
941 Value *storeAddr = Builder.CreateStructGEP(structData, i);
942 Builder.CreateStore(OMPDataVals[i], storeAddr);
943 }
944
945 return structData;
946 }
947
948 /// @brief Create OpenMP structure values.
949 ///
950 /// Create a list of values that has to be stored into the subfuncition
951 /// structure.
952 SetVector<Value*> createOpenMPStructValues() {
953 SetVector<Value*> OMPDataVals;
954
955 // Push the clast variables available in the clastVars.
956 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
957 I != E; I++)
958 OMPDataVals.insert(I->second);
959
960 // Push the base addresses of memory references.
961 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
962 ScopStmt *Stmt = *SI;
963 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
964 E = Stmt->memacc_end(); I != E; ++I) {
965 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
966 OMPDataVals.insert((BaseAddr));
967 }
968 }
969
970 return OMPDataVals;
971 }
972
973 /// @brief Extract the values from the subfunction parameter.
974 ///
975 /// Extract the values from the subfunction parameter and update the clast
976 /// variables to point to the new values.
977 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
978 SetVector<Value*> OMPDataVals,
979 Value *userContext) {
980 // Extract the clast variables.
981 unsigned i = 0;
982 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
983 I != E; I++) {
984 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
985 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
986 i++;
987 }
988
989 // Extract the base addresses of memory references.
990 for (unsigned j = i; j < OMPDataVals.size(); j++) {
991 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
992 Value *baseAddr = OMPDataVals[j];
993 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
994 }
995
996 }
997
998 /// @brief Add body to the subfunction.
999 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
1000 Value *structData,
1001 SetVector<Value*> OMPDataVals) {
1002 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1003 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001004 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001005
1006 // Store the previous basic block.
1007 BasicBlock *PrevBB = Builder.GetInsertBlock();
1008
1009 // Create basic blocks.
1010 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1011 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1012 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1013 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1014 FN);
1015
1016 DT->addNewBlock(HeaderBB, PrevBB);
1017 DT->addNewBlock(ExitBB, HeaderBB);
1018 DT->addNewBlock(checkNextBB, HeaderBB);
1019 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1020
1021 // Fill up basic block HeaderBB.
1022 Builder.SetInsertPoint(HeaderBB);
1023 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1024 "omp.lowerBoundPtr");
1025 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1026 "omp.upperBoundPtr");
1027 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1028 structData->getType(),
1029 "omp.userContext");
1030
1031 CharMapT clastVarsOMP;
1032 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1033
1034 Builder.CreateBr(checkNextBB);
1035
1036 // Add code to check if another set of iterations will be executed.
1037 Builder.SetInsertPoint(checkNextBB);
1038 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1039 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1040 lowerBoundPtr, upperBoundPtr);
1041 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1042 "omp.hasNextScheduleBlock");
1043 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1044
1045 // Add code to to load the iv bounds for this set of iterations.
1046 Builder.SetInsertPoint(loadIVBoundsBB);
1047 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1048 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1049
1050 // Subtract one as the upper bound provided by openmp is a < comparison
1051 // whereas the codegenForSequential function creates a <= comparison.
1052 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1053 "omp.upperBoundAdjusted");
1054
1055 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1056 CharMapT *oldClastVars = clastVars;
1057 clastVars = &clastVarsOMP;
1058 ExpGen.setIVS(&clastVarsOMP);
1059
1060 codegenForSequential(f, lowerBound, upperBound);
1061
1062 // Restore the old clastVars.
1063 clastVars = oldClastVars;
1064 ExpGen.setIVS(oldClastVars);
1065
1066 Builder.CreateBr(checkNextBB);
1067
1068 // Add code to terminate this openmp subfunction.
1069 Builder.SetInsertPoint(ExitBB);
1070 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1071 Builder.CreateCall(endnowaitFunction);
1072 Builder.CreateRetVoid();
1073
1074 // Restore the builder back to previous basic block.
1075 Builder.SetInsertPoint(PrevBB);
1076 }
1077
1078 /// @brief Create an OpenMP parallel for loop.
1079 ///
1080 /// This loop reflects a loop as if it would have been created by an OpenMP
1081 /// statement.
1082 void codegenForOpenMP(const clast_for *f) {
1083 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001084 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001085
1086 Function *SubFunction = addOpenMPSubfunction(M);
1087 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1088 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1089
1090 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1091
1092 // Create call for GOMP_parallel_loop_runtime_start.
1093 Value *subfunctionParam = Builder.CreateBitCast(structData,
1094 Builder.getInt8PtrTy(),
1095 "omp_data");
1096
1097 Value *numberOfThreads = Builder.getInt32(0);
1098 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1099 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1100
1101 // Add one as the upper bound provided by openmp is a < comparison
1102 // whereas the codegenForSequential function creates a <= comparison.
1103 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1104 APInt APStride = APInt_from_MPZ(f->stride);
1105 Value *stride = ConstantInt::get(intPtrTy,
1106 APStride.zext(intPtrTy->getBitWidth()));
1107
1108 SmallVector<Value *, 6> Arguments;
1109 Arguments.push_back(SubFunction);
1110 Arguments.push_back(subfunctionParam);
1111 Arguments.push_back(numberOfThreads);
1112 Arguments.push_back(lowerBound);
1113 Arguments.push_back(upperBound);
1114 Arguments.push_back(stride);
1115
1116 Function *parallelStartFunction =
1117 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001118 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001119
1120 // Create call to the subfunction.
1121 Builder.CreateCall(SubFunction, subfunctionParam);
1122
1123 // Create call for GOMP_parallel_end.
1124 Function *FN = M->getFunction("GOMP_parallel_end");
1125 Builder.CreateCall(FN);
1126 }
1127
1128 bool isInnermostLoop(const clast_for *f) {
1129 const clast_stmt *stmt = f->body;
1130
1131 while (stmt) {
1132 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1133 return false;
1134
1135 stmt = stmt->next;
1136 }
1137
1138 return true;
1139 }
1140
1141 /// @brief Get the number of loop iterations for this loop.
1142 /// @param f The clast for loop to check.
1143 int getNumberOfIterations(const clast_for *f) {
1144 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1145 isl_set *tmp = isl_set_copy(loopDomain);
1146
1147 // Calculate a map similar to the identity map, but with the last input
1148 // and output dimension not related.
1149 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
Tobias Grosserf5338802011-10-06 00:03:35 +00001150 isl_space *Space = isl_set_get_space(loopDomain);
1151 Space = isl_space_drop_outputs(Space,
1152 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1153 Space = isl_space_map_from_set(Space);
1154 isl_map *identity = isl_map_identity(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001155 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1156 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1157
1158 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1159 map = isl_map_intersect(map, identity);
1160
1161 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001162 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001163 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1164
1165 isl_set *elements = isl_map_range(sub);
1166
Tobias Grosserc532f122011-08-25 08:40:59 +00001167 if (!isl_set_is_singleton(elements)) {
1168 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001169 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001170 }
Tobias Grosser75805372011-04-29 06:27:02 +00001171
1172 isl_point *p = isl_set_sample_point(elements);
1173
1174 isl_int v;
1175 isl_int_init(v);
1176 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1177 int numberIterations = isl_int_get_si(v);
1178 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001179 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001180
1181 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1182 }
1183
1184 /// @brief Create vector instructions for this loop.
1185 void codegenForVector(const clast_for *f) {
1186 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1187 int vectorWidth = getNumberOfIterations(f);
1188
1189 Value *LB = ExpGen.codegen(f->LB,
1190 TD->getIntPtrType(Builder.getContext()));
1191
1192 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001193 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001194 Stride = Stride.zext(LoopIVType->getBitWidth());
1195 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1196
1197 std::vector<Value*> IVS(vectorWidth);
1198 IVS[0] = LB;
1199
1200 for (int i = 1; i < vectorWidth; i++)
1201 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1202
1203 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1204
1205 // Add loop iv to symbols.
1206 (*clastVars)[f->iterator] = LB;
1207
1208 const clast_stmt *stmt = f->body;
1209
1210 while (stmt) {
1211 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1212 scatteringDomain);
1213 stmt = stmt->next;
1214 }
1215
1216 // Loop is finished, so remove its iv from the live symbols.
1217 clastVars->erase(f->iterator);
1218 }
1219
1220 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001221 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001222 && (-1 != getNumberOfIterations(f))
1223 && (getNumberOfIterations(f) <= 16)) {
1224 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001225 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001226 parallelCodeGeneration = true;
1227 parallelLoops.push_back(f->iterator);
1228 codegenForOpenMP(f);
1229 parallelCodeGeneration = false;
1230 } else
1231 codegenForSequential(f);
1232 }
1233
1234 Value *codegen(const clast_equation *eq) {
1235 Value *LHS = ExpGen.codegen(eq->LHS,
1236 TD->getIntPtrType(Builder.getContext()));
1237 Value *RHS = ExpGen.codegen(eq->RHS,
1238 TD->getIntPtrType(Builder.getContext()));
1239 CmpInst::Predicate P;
1240
1241 if (eq->sign == 0)
1242 P = ICmpInst::ICMP_EQ;
1243 else if (eq->sign > 0)
1244 P = ICmpInst::ICMP_SGE;
1245 else
1246 P = ICmpInst::ICMP_SLE;
1247
1248 return Builder.CreateICmp(P, LHS, RHS);
1249 }
1250
1251 void codegen(const clast_guard *g) {
1252 Function *F = Builder.GetInsertBlock()->getParent();
1253 LLVMContext &Context = F->getContext();
1254 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1255 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1256 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1257 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1258
1259 Value *Predicate = codegen(&(g->eq[0]));
1260
1261 for (int i = 1; i < g->n; ++i) {
1262 Value *TmpPredicate = codegen(&(g->eq[i]));
1263 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1264 }
1265
1266 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1267 Builder.SetInsertPoint(ThenBB);
1268
1269 codegen(g->then);
1270
1271 Builder.CreateBr(MergeBB);
1272 Builder.SetInsertPoint(MergeBB);
1273 }
1274
1275 void codegen(const clast_stmt *stmt) {
1276 if (CLAST_STMT_IS_A(stmt, stmt_root))
1277 assert(false && "No second root statement expected");
1278 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1279 codegen((const clast_assignment *)stmt);
1280 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1281 codegen((const clast_user_stmt *)stmt);
1282 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1283 codegen((const clast_block *)stmt);
1284 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1285 codegen((const clast_for *)stmt);
1286 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1287 codegen((const clast_guard *)stmt);
1288
1289 if (stmt->next)
1290 codegen(stmt->next);
1291 }
1292
1293 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001294 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001295
1296 // Create an instruction that specifies the location where the parameters
1297 // are expanded.
1298 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1299 Builder.getInt16Ty(), false, "insertInst",
1300 Builder.GetInsertBlock());
1301
1302 int i = 0;
1303 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1304 PI != PE; ++PI) {
1305 assert(i < names->nb_parameters && "Not enough parameter names");
1306
1307 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001308 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001309
1310 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1311 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1312 (*clastVars)[names->parameters[i]] = V;
1313
1314 ++i;
1315 }
1316 }
1317
1318 public:
1319 void codegen(const clast_root *r) {
1320 clastVars = new CharMapT();
1321 addParameters(r->names);
1322 ExpGen.setIVS(clastVars);
1323
1324 parallelCodeGeneration = false;
1325
1326 const clast_stmt *stmt = (const clast_stmt*) r;
1327 if (stmt->next)
1328 codegen(stmt->next);
1329
1330 delete clastVars;
1331 }
1332
1333 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001334 ScopDetection *sd, Dependences *dp, TargetData *td,
1335 IRBuilder<> &B) :
1336 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1337 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001338
1339};
1340}
1341
1342namespace {
1343class CodeGeneration : public ScopPass {
1344 Region *region;
1345 Scop *S;
1346 DominatorTree *DT;
1347 ScalarEvolution *SE;
1348 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001349 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001350 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001351
1352 std::vector<std::string> parallelLoops;
1353
1354 public:
1355 static char ID;
1356
1357 CodeGeneration() : ScopPass(ID) {}
1358
Tobias Grosser75805372011-04-29 06:27:02 +00001359 // Adding prototypes required if OpenMP is enabled.
1360 void addOpenMPDefinitions(IRBuilder<> &Builder)
1361 {
1362 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1363 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001364 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001365
1366 if (!M->getFunction("GOMP_parallel_end")) {
1367 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1368 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1369 }
1370
1371 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1372 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001373 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001374 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1375 false);
1376 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1377
Tobias Grosser851b96e2011-07-12 12:42:54 +00001378 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001379 args.push_back(FnPtrTy);
1380 args.push_back(Builder.getInt8PtrTy());
1381 args.push_back(Builder.getInt32Ty());
1382 args.push_back(intPtrTy);
1383 args.push_back(intPtrTy);
1384 args.push_back(intPtrTy);
1385
1386 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1387 Function::Create(type, Function::ExternalLinkage,
1388 "GOMP_parallel_loop_runtime_start", M);
1389 }
1390
1391 if (!M->getFunction("GOMP_loop_runtime_next")) {
1392 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1393
Tobias Grosser851b96e2011-07-12 12:42:54 +00001394 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001395 args.push_back(intLongPtrTy);
1396 args.push_back(intLongPtrTy);
1397
1398 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1399 Function::Create(type, Function::ExternalLinkage,
1400 "GOMP_loop_runtime_next", M);
1401 }
1402
1403 if (!M->getFunction("GOMP_loop_end_nowait")) {
1404 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001405 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001406 Function::Create(FT, Function::ExternalLinkage,
1407 "GOMP_loop_end_nowait", M);
1408 }
1409 }
1410
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001411 // Split the entry edge of the region and generate a new basic block on this
1412 // edge. This function also updates ScopInfo and RegionInfo.
1413 //
1414 // @param region The region where the entry edge will be splitted.
1415 BasicBlock *splitEdgeAdvanced(Region *region) {
1416 BasicBlock *newBlock;
1417 BasicBlock *splitBlock;
1418
1419 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1420
1421 if (DT->dominates(region->getEntry(), newBlock)) {
1422 // Update ScopInfo.
1423 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1424 if ((*SI)->getBasicBlock() == newBlock) {
1425 (*SI)->setBasicBlock(newBlock);
1426 break;
1427 }
1428
1429 // Update RegionInfo.
1430 splitBlock = region->getEntry();
1431 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001432 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001433 } else {
1434 RI->setRegionFor(newBlock, region->getParent());
1435 splitBlock = newBlock;
1436 }
1437
1438 return splitBlock;
1439 }
1440
1441 // Create a split block that branches either to the old code or to a new basic
1442 // block where the new code can be inserted.
1443 //
1444 // @param builder A builder that will be set to point to a basic block, where
1445 // the new code can be generated.
1446 // @return The split basic block.
1447 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1448 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1449
1450 splitBlock->setName("polly.enterScop");
1451
1452 Function *function = splitBlock->getParent();
1453 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1454 "polly.start", function);
1455 splitBlock->getTerminator()->eraseFromParent();
1456 builder->SetInsertPoint(splitBlock);
1457 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1458 DT->addNewBlock(startBlock, splitBlock);
1459
1460 // Start code generation here.
1461 builder->SetInsertPoint(startBlock);
1462 return splitBlock;
1463 }
1464
1465 // Merge the control flow of the newly generated code with the existing code.
1466 //
1467 // @param splitBlock The basic block where the control flow was split between
1468 // old and new version of the Scop.
1469 // @param builder An IRBuilder that points to the last instruction of the
1470 // newly generated code.
1471 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1472 BasicBlock *mergeBlock;
1473 Region *R = region;
1474
1475 if (R->getExit()->getSinglePredecessor())
1476 // No splitEdge required. A block with a single predecessor cannot have
1477 // PHI nodes that would complicate life.
1478 mergeBlock = R->getExit();
1479 else {
1480 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1481 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1482 // one predecessor. Hence, mergeBlock is always a newly generated block.
1483 mergeBlock->setName("polly.finalMerge");
1484 R->replaceExit(mergeBlock);
1485 }
1486
1487 builder->CreateBr(mergeBlock);
1488
1489 if (DT->dominates(splitBlock, mergeBlock))
1490 DT->changeImmediateDominator(mergeBlock, splitBlock);
1491 }
1492
Tobias Grosser75805372011-04-29 06:27:02 +00001493 bool runOnScop(Scop &scop) {
1494 S = &scop;
1495 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001496 DT = &getAnalysis<DominatorTree>();
1497 Dependences *DP = &getAnalysis<Dependences>();
1498 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001499 SD = &getAnalysis<ScopDetection>();
1500 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001501 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001502
1503 parallelLoops.clear();
1504
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001505 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001506
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001507 // In the CFG and we generate next to original code of the Scop the
1508 // optimized version. Both the new and the original version of the code
1509 // remain in the CFG. A branch statement decides which version is executed.
1510 // At the moment, we always execute the newly generated version (the old one
1511 // is dead code eliminated by the cleanup passes). Later we may decide to
1512 // execute the new version only under certain conditions. This will be the
1513 // case if we support constructs for which we cannot prove all assumptions
1514 // at compile time.
1515 //
1516 // Before transformation:
1517 //
1518 // bb0
1519 // |
1520 // orig_scop
1521 // |
1522 // bb1
1523 //
1524 // After transformation:
1525 // bb0
1526 // |
1527 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001528 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001529 // | startBlock
1530 // | |
1531 // orig_scop new_scop
1532 // \ /
1533 // \ /
1534 // bb1 (joinBlock)
1535 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001536
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001537 // The builder will be set to startBlock.
1538 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001539
1540 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001541 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001542
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001543 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001544 CloogInfo &C = getAnalysis<CloogInfo>();
1545 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001546
Tobias Grosser75805372011-04-29 06:27:02 +00001547 parallelLoops.insert(parallelLoops.begin(),
1548 CodeGen.getParallelLoops().begin(),
1549 CodeGen.getParallelLoops().end());
1550
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001551 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001552
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001553 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001554 }
1555
1556 virtual void printScop(raw_ostream &OS) const {
1557 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1558 PE = parallelLoops.end(); PI != PE; ++PI)
1559 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1560 }
1561
1562 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1563 AU.addRequired<CloogInfo>();
1564 AU.addRequired<Dependences>();
1565 AU.addRequired<DominatorTree>();
1566 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001567 AU.addRequired<RegionInfo>();
1568 AU.addRequired<ScopDetection>();
1569 AU.addRequired<ScopInfo>();
1570 AU.addRequired<TargetData>();
1571
1572 AU.addPreserved<CloogInfo>();
1573 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001574
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001575 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001576 AU.addPreserved<LoopInfo>();
1577 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001578 AU.addPreserved<ScopDetection>();
1579 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001580
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001581 // FIXME: We do not yet add regions for the newly generated code to the
1582 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001583 AU.addPreserved<RegionInfo>();
1584 AU.addPreserved<TempScopInfo>();
1585 AU.addPreserved<ScopInfo>();
1586 AU.addPreservedID(IndependentBlocksID);
1587 }
1588};
1589}
1590
1591char CodeGeneration::ID = 1;
1592
1593static RegisterPass<CodeGeneration>
1594Z("polly-codegen", "Polly - Create LLVM-IR from the polyhedral information");
1595
1596Pass* polly::createCodeGenerationPass() {
1597 return new CodeGeneration();
1598}