blob: c677cc6c00be8065b78a7c9a7c51f8cec0ae73c8 [file] [log] [blame]
Tobias Grosser75805372011-04-29 06:27:02 +00001//===------ CodeGeneration.cpp - Code generate the Scops. -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The CodeGeneration pass takes a Scop created by ScopInfo and translates it
11// back to LLVM-IR using Cloog.
12//
13// The Scop describes the high level memory behaviour of a control flow region.
14// Transformation passes can update the schedule (execution order) of statements
15// in the Scop. Cloog is used to generate an abstract syntax tree (clast) that
16// reflects the updated execution order. This clast is used to create new
17// LLVM-IR that is computational equivalent to the original control flow region,
18// but executes its code in the new execution order defined by the changed
19// scattering.
20//
21//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "polly-codegen"
24
25#include "polly/LinkAllPasses.h"
26#include "polly/Support/GICHelper.h"
27#include "polly/Support/ScopHelper.h"
28#include "polly/Cloog.h"
Tobias Grosser67707b72011-10-23 20:59:40 +000029#include "polly/CodeGeneration.h"
Tobias Grosser75805372011-04-29 06:27:02 +000030#include "polly/Dependences.h"
31#include "polly/ScopInfo.h"
32#include "polly/TempScopInfo.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/IRBuilder.h"
36#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser8c4cfc322011-05-14 19:01:49 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Tobias Grosser75805372011-04-29 06:27:02 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Module.h"
41#include "llvm/ADT/SetVector.h"
42
43#define CLOOG_INT_GMP 1
44#include "cloog/cloog.h"
45#include "cloog/isl/cloog.h"
46
47#include <vector>
48#include <utility>
49
50using namespace polly;
51using namespace llvm;
52
53struct isl_set;
54
55namespace polly {
56
Tobias Grosser67707b72011-10-23 20:59:40 +000057bool EnablePollyVector;
58
59static cl::opt<bool, true>
Tobias Grosser75805372011-04-29 06:27:02 +000060Vector("enable-polly-vector",
61 cl::desc("Enable polly vector code generation"), cl::Hidden,
Tobias Grosser67707b72011-10-23 20:59:40 +000062 cl::location(EnablePollyVector), cl::init(false));
Tobias Grosser75805372011-04-29 06:27:02 +000063
64static cl::opt<bool>
65OpenMP("enable-polly-openmp",
66 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
67 cl::value_desc("OpenMP code generation enabled if true"),
68 cl::init(false));
69
70static cl::opt<bool>
71AtLeastOnce("enable-polly-atLeastOnce",
72 cl::desc("Give polly the hint, that every loop is executed at least"
73 "once"), cl::Hidden,
74 cl::value_desc("OpenMP code generation enabled if true"),
75 cl::init(false));
76
77static cl::opt<bool>
78Aligned("enable-polly-aligned",
79 cl::desc("Assumed aligned memory accesses."), cl::Hidden,
80 cl::value_desc("OpenMP code generation enabled if true"),
81 cl::init(false));
82
Tobias Grosser75805372011-04-29 06:27:02 +000083typedef DenseMap<const Value*, Value*> ValueMapT;
84typedef DenseMap<const char*, Value*> CharMapT;
85typedef std::vector<ValueMapT> VectorValueMapT;
86
87// Create a new loop.
88//
89// @param Builder The builder used to create the loop. It also defines the
90// place where to create the loop.
91// @param UB The upper bound of the loop iv.
92// @param Stride The number by which the loop iv is incremented after every
93// iteration.
94static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride,
95 PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV,
96 DominatorTree *DT) {
97 Function *F = Builder->GetInsertBlock()->getParent();
98 LLVMContext &Context = F->getContext();
99
100 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
101 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
102 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
103 AfterBB = BasicBlock::Create(Context, "polly.after_loop", F);
104
105 Builder->CreateBr(HeaderBB);
106 DT->addNewBlock(HeaderBB, PreheaderBB);
107
108 Builder->SetInsertPoint(BodyBB);
109
110 Builder->SetInsertPoint(HeaderBB);
111
112 // Use the type of upper and lower bound.
113 assert(LB->getType() == UB->getType()
114 && "Different types for upper and lower bound.");
115
Tobias Grosser55927aa2011-07-18 09:53:32 +0000116 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000117 assert(LoopIVType && "UB is not integer?");
118
119 // IV
120 IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
121 IV->addIncoming(LB, PreheaderBB);
122
123 // IV increment.
124 Value *StrideValue = ConstantInt::get(LoopIVType,
125 Stride.zext(LoopIVType->getBitWidth()));
126 IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv");
127
128 // Exit condition.
129 if (AtLeastOnce) { // At least on iteration.
130 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
131 Value *CMP = Builder->CreateICmpEQ(IV, UB);
132 Builder->CreateCondBr(CMP, AfterBB, BodyBB);
133 } else { // Maybe not executed at all.
134 Value *CMP = Builder->CreateICmpSLE(IV, UB);
135 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
136 }
137 DT->addNewBlock(BodyBB, HeaderBB);
138 DT->addNewBlock(AfterBB, HeaderBB);
139
140 Builder->SetInsertPoint(BodyBB);
141}
142
143class BlockGenerator {
144 IRBuilder<> &Builder;
145 ValueMapT &VMap;
146 VectorValueMapT &ValueMaps;
147 Scop &S;
148 ScopStmt &statement;
149 isl_set *scatteringDomain;
150
151public:
152 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
153 ScopStmt &Stmt, isl_set *domain)
154 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
155 statement(Stmt), scatteringDomain(domain) {}
156
157 const Region &getRegion() {
158 return S.getRegion();
159 }
160
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000161 Value *makeVectorOperand(Value *operand, int vectorWidth) {
Tobias Grosser75805372011-04-29 06:27:02 +0000162 if (operand->getType()->isVectorTy())
163 return operand;
164
165 VectorType *vectorType = VectorType::get(operand->getType(), vectorWidth);
166 Value *vector = UndefValue::get(vectorType);
167 vector = Builder.CreateInsertElement(vector, operand, Builder.getInt32(0));
168
169 std::vector<Constant*> splat;
170
171 for (int i = 0; i < vectorWidth; i++)
172 splat.push_back (Builder.getInt32(0));
173
174 Constant *splatVector = ConstantVector::get(splat);
175
176 return Builder.CreateShuffleVector(vector, vector, splatVector);
177 }
178
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000179 Value *getOperand(const Value *oldOperand, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000180 ValueMapT *VectorMap = 0) {
Raghesh Aloor490c5982011-08-08 08:34:16 +0000181 const Instruction *OpInst = dyn_cast<Instruction>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000182
183 if (!OpInst)
Raghesh Aloor490c5982011-08-08 08:34:16 +0000184 return const_cast<Value*>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000185
Raghesh Aloor490c5982011-08-08 08:34:16 +0000186 if (VectorMap && VectorMap->count(oldOperand))
187 return (*VectorMap)[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000188
189 // IVS and Parameters.
Raghesh Aloor490c5982011-08-08 08:34:16 +0000190 if (VMap.count(oldOperand)) {
191 Value *NewOperand = VMap[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000192
193 // Insert a cast if types are different
Raghesh Aloor490c5982011-08-08 08:34:16 +0000194 if (oldOperand->getType()->getScalarSizeInBits()
Tobias Grosser75805372011-04-29 06:27:02 +0000195 < NewOperand->getType()->getScalarSizeInBits())
196 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
Raghesh Aloor490c5982011-08-08 08:34:16 +0000197 oldOperand->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000198
199 return NewOperand;
200 }
201
202 // Instructions calculated in the current BB.
Raghesh Aloor490c5982011-08-08 08:34:16 +0000203 if (BBMap.count(oldOperand)) {
204 return BBMap[oldOperand];
Tobias Grosser75805372011-04-29 06:27:02 +0000205 }
206
207 // Ignore instructions that are referencing ops in the old BB. These
208 // instructions are unused. They where replace by new ones during
209 // createIndependentBlocks().
210 if (getRegion().contains(OpInst->getParent()))
211 return NULL;
212
Raghesh Aloor490c5982011-08-08 08:34:16 +0000213 return const_cast<Value*>(oldOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000214 }
215
Tobias Grosser55927aa2011-07-18 09:53:32 +0000216 Type *getVectorPtrTy(const Value *V, int vectorWidth) {
217 PointerType *pointerType = dyn_cast<PointerType>(V->getType());
Tobias Grosser75805372011-04-29 06:27:02 +0000218 assert(pointerType && "PointerType expected");
219
Tobias Grosser55927aa2011-07-18 09:53:32 +0000220 Type *scalarType = pointerType->getElementType();
Tobias Grosser75805372011-04-29 06:27:02 +0000221 VectorType *vectorType = VectorType::get(scalarType, vectorWidth);
222
223 return PointerType::getUnqual(vectorType);
224 }
225
226 /// @brief Load a vector from a set of adjacent scalars
227 ///
228 /// In case a set of scalars is known to be next to each other in memory,
229 /// create a vector load that loads those scalars
230 ///
231 /// %vector_ptr= bitcast double* %p to <4 x double>*
232 /// %vec_full = load <4 x double>* %vector_ptr
233 ///
234 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
235 int size) {
236 const Value *pointer = load->getPointerOperand();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000237 Type *vectorPtrType = getVectorPtrTy(pointer, size);
Tobias Grosser75805372011-04-29 06:27:02 +0000238 Value *newPointer = getOperand(pointer, BBMap);
239 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
240 "vector_ptr");
241 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
242 load->getNameStr()
243 + "_p_vec_full");
244 if (!Aligned)
245 VecLoad->setAlignment(8);
246
247 return VecLoad;
248 }
249
250 /// @brief Load a vector initialized from a single scalar in memory
251 ///
252 /// In case all elements of a vector are initialized to the same
253 /// scalar value, this value is loaded and shuffeled into all elements
254 /// of the vector.
255 ///
256 /// %splat_one = load <1 x double>* %p
257 /// %splat = shufflevector <1 x double> %splat_one, <1 x
258 /// double> %splat_one, <4 x i32> zeroinitializer
259 ///
260 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
261 int size) {
262 const Value *pointer = load->getPointerOperand();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000263 Type *vectorPtrType = getVectorPtrTy(pointer, 1);
Tobias Grosser75805372011-04-29 06:27:02 +0000264 Value *newPointer = getOperand(pointer, BBMap);
265 Value *vectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
266 load->getNameStr() + "_p_vec_p");
267 LoadInst *scalarLoad= Builder.CreateLoad(vectorPtr,
268 load->getNameStr() + "_p_splat_one");
269
270 if (!Aligned)
271 scalarLoad->setAlignment(8);
272
273 std::vector<Constant*> splat;
274
275 for (int i = 0; i < size; i++)
276 splat.push_back (Builder.getInt32(0));
277
278 Constant *splatVector = ConstantVector::get(splat);
279
280 Value *vectorLoad = Builder.CreateShuffleVector(scalarLoad, scalarLoad,
281 splatVector,
282 load->getNameStr()
283 + "_p_splat");
284 return vectorLoad;
285 }
286
287 /// @Load a vector from scalars distributed in memory
288 ///
289 /// In case some scalars a distributed randomly in memory. Create a vector
290 /// by loading each scalar and by inserting one after the other into the
291 /// vector.
292 ///
293 /// %scalar_1= load double* %p_1
294 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
295 /// %scalar 2 = load double* %p_2
296 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
297 ///
298 Value *generateUnknownStrideLoad(const LoadInst *load,
299 VectorValueMapT &scalarMaps,
300 int size) {
301 const Value *pointer = load->getPointerOperand();
302 VectorType *vectorType = VectorType::get(
303 dyn_cast<PointerType>(pointer->getType())->getElementType(), size);
304
305 Value *vector = UndefValue::get(vectorType);
306
307 for (int i = 0; i < size; i++) {
308 Value *newPointer = getOperand(pointer, scalarMaps[i]);
309 Value *scalarLoad = Builder.CreateLoad(newPointer,
310 load->getNameStr() + "_p_scalar_");
311 vector = Builder.CreateInsertElement(vector, scalarLoad,
312 Builder.getInt32(i),
313 load->getNameStr() + "_p_vec_");
314 }
315
316 return vector;
317 }
318
Raghesh Aloor129e8672011-08-15 02:33:39 +0000319 /// @brief Get the memory access offset to be added to the base address
320 std::vector <Value*> getMemoryAccessIndex(isl_map *accessRelation,
321 Value *baseAddr) {
322 isl_int offsetMPZ;
323 isl_int_init(offsetMPZ);
324
325 assert((isl_map_dim(accessRelation, isl_dim_out) == 1)
326 && "Only single dimensional access functions supported");
327
328 if (isl_map_plain_is_fixed(accessRelation, isl_dim_out,
329 0, &offsetMPZ) == -1)
330 errs() << "Only fixed value access functions supported\n";
331
332 // Convert the offset from MPZ to Value*.
333 APInt offset = APInt_from_MPZ(offsetMPZ);
334 Value *offsetValue = ConstantInt::get(Builder.getContext(), offset);
335 PointerType *baseAddrType = dyn_cast<PointerType>(baseAddr->getType());
336 Type *arrayType = baseAddrType->getElementType();
337 Type *arrayElementType = dyn_cast<ArrayType>(arrayType)->getElementType();
338 offsetValue = Builder.CreateSExtOrBitCast(offsetValue, arrayElementType);
339
340 std::vector<Value*> indexArray;
341 Value *nullValue = Constant::getNullValue(arrayElementType);
342 indexArray.push_back(nullValue);
343 indexArray.push_back(offsetValue);
344
345 isl_int_clear(offsetMPZ);
346 return indexArray;
347 }
348
Raghesh Aloor62b13122011-08-03 17:02:50 +0000349 /// @brief Get the new operand address according to the changed access in
350 /// JSCOP file.
351 Value *getNewAccessOperand(isl_map *newAccessRelation, Value *baseAddr,
Raghesh Aloor490c5982011-08-08 08:34:16 +0000352 const Value *oldOperand, ValueMapT &BBMap) {
Raghesh Aloor129e8672011-08-15 02:33:39 +0000353 std::vector<Value*> indexArray = getMemoryAccessIndex(newAccessRelation,
354 baseAddr);
355 Value *newOperand = Builder.CreateGEP(baseAddr, indexArray,
356 "p_newarrayidx_");
Raghesh Aloor62b13122011-08-03 17:02:50 +0000357 return newOperand;
358 }
359
360 /// @brief Generate the operand address
361 Value *generateLocationAccessed(const Instruction *Inst,
362 const Value *pointer, ValueMapT &BBMap ) {
Tobias Grosser5d453812011-10-06 00:04:11 +0000363 MemoryAccess &Access = statement.getAccessFor(Inst);
364 isl_map *CurrentAccessRelation = Access.getAccessRelation();
365 isl_map *NewAccessRelation = Access.getNewAccessRelation();
Raghesh Aloor129e8672011-08-15 02:33:39 +0000366
Tobias Grosser5d453812011-10-06 00:04:11 +0000367 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
Tobias Grosserf5338802011-10-06 00:03:35 +0000368 && "Current and new access function use different spaces");
Raghesh Aloor129e8672011-08-15 02:33:39 +0000369
Tobias Grosser5d453812011-10-06 00:04:11 +0000370 Value *NewPointer;
371
372 if (!NewAccessRelation) {
373 NewPointer = getOperand(pointer, BBMap);
374 } else {
375 Value *BaseAddr = const_cast<Value*>(Access.getBaseAddr());
376 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddr, pointer,
377 BBMap);
Raghesh Aloor62b13122011-08-03 17:02:50 +0000378 }
Raghesh Aloore75e9862011-08-11 08:44:56 +0000379
Tobias Grosser5d453812011-10-06 00:04:11 +0000380 isl_map_free(CurrentAccessRelation);
381 isl_map_free(NewAccessRelation);
382 return NewPointer;
Raghesh Aloor62b13122011-08-03 17:02:50 +0000383 }
384
Tobias Grosser75805372011-04-29 06:27:02 +0000385 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap) {
386 const Value *pointer = load->getPointerOperand();
Raghesh Aloor62b13122011-08-03 17:02:50 +0000387 const Instruction *Inst = dyn_cast<Instruction>(load);
388 Value *newPointer = generateLocationAccessed(Inst, pointer, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000389 Value *scalarLoad = Builder.CreateLoad(newPointer,
390 load->getNameStr() + "_p_scalar_");
391 return scalarLoad;
392 }
393
394 /// @brief Load a value (or several values as a vector) from memory.
395 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
396 VectorValueMapT &scalarMaps, int vectorWidth) {
Tobias Grosser75805372011-04-29 06:27:02 +0000397 if (scalarMaps.size() == 1) {
398 scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]);
399 return;
400 }
401
402 Value *newLoad;
403
404 MemoryAccess &Access = statement.getAccessFor(load);
405
406 assert(scatteringDomain && "No scattering domain available");
407
408 if (Access.isStrideZero(scatteringDomain))
409 newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth);
410 else if (Access.isStrideOne(scatteringDomain))
411 newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth);
412 else
413 newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth);
414
415 vectorMap[load] = newLoad;
416 }
417
Tobias Grosserc9215152011-09-04 11:45:52 +0000418 void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &BBMap,
419 ValueMapT &VectorMap, int VectorDimension,
420 int VectorWidth) {
421 Value *NewOperand = getOperand(Inst->getOperand(0), BBMap, &VectorMap);
422 NewOperand = makeVectorOperand(NewOperand, VectorWidth);
423
424 if (const CastInst *Cast = dyn_cast<CastInst>(Inst)) {
425 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
426 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand,
427 DestType);
428 } else
429 llvm_unreachable("Can not generate vector code for instruction");
430 return;
431 }
432
Tobias Grosser09c57102011-09-04 11:45:29 +0000433 void copyBinInst(const BinaryOperator *Inst, ValueMapT &BBMap,
Tobias Grosser8b00a512011-09-04 11:45:45 +0000434 ValueMapT &vectorMap, int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000435 Value *opZero = Inst->getOperand(0);
436 Value *opOne = Inst->getOperand(1);
437
Tobias Grosser09c57102011-09-04 11:45:29 +0000438 Value *newOpZero, *newOpOne;
439 newOpZero = getOperand(opZero, BBMap, &vectorMap);
440 newOpOne = getOperand(opOne, BBMap, &vectorMap);
441
Tobias Grosser7551c302011-09-04 11:45:41 +0000442 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
443 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
Tobias Grosser09c57102011-09-04 11:45:29 +0000444
445 Value *newInst = Builder.CreateBinOp(Inst->getOpcode(), newOpZero,
Tobias Grosser7551c302011-09-04 11:45:41 +0000446 newOpOne,
447 Inst->getNameStr() + "p_vec");
448 vectorMap[Inst] = newInst;
Tobias Grosser09c57102011-09-04 11:45:29 +0000449
450 return;
451 }
452
453 void copyVectorStore(const StoreInst *store, ValueMapT &BBMap,
Tobias Grosser75805372011-04-29 06:27:02 +0000454 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
455 int vectorDimension, int vectorWidth) {
Tobias Grosser09c57102011-09-04 11:45:29 +0000456 // In vector mode we only generate a store for the first dimension.
457 if (vectorDimension > 0)
Tobias Grosser75805372011-04-29 06:27:02 +0000458 return;
459
Tobias Grosser09c57102011-09-04 11:45:29 +0000460 MemoryAccess &Access = statement.getAccessFor(store);
Tobias Grosser75805372011-04-29 06:27:02 +0000461
Tobias Grosser09c57102011-09-04 11:45:29 +0000462 assert(scatteringDomain && "No scattering domain available");
Tobias Grosser75805372011-04-29 06:27:02 +0000463
Tobias Grosser09c57102011-09-04 11:45:29 +0000464 const Value *pointer = store->getPointerOperand();
465 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000466
Tobias Grosser09c57102011-09-04 11:45:29 +0000467 if (Access.isStrideOne(scatteringDomain)) {
468 Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
469 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000470
Tobias Grosser09c57102011-09-04 11:45:29 +0000471 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
472 "vector_ptr");
473 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
Tobias Grosser75805372011-04-29 06:27:02 +0000474
Tobias Grosser09c57102011-09-04 11:45:29 +0000475 if (!Aligned)
476 Store->setAlignment(8);
477 } else {
478 for (unsigned i = 0; i < scalarMaps.size(); i++) {
479 Value *scalar = Builder.CreateExtractElement(vector,
480 Builder.getInt32(i));
481 Value *newPointer = getOperand(pointer, scalarMaps[i]);
482 Builder.CreateStore(scalar, newPointer);
Tobias Grosser75805372011-04-29 06:27:02 +0000483 }
484 }
485
Tobias Grosser09c57102011-09-04 11:45:29 +0000486 return;
487 }
488
Tobias Grosser7551c302011-09-04 11:45:41 +0000489 void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap) {
Tobias Grosser75805372011-04-29 06:27:02 +0000490 Instruction *NewInst = Inst->clone();
491
Tobias Grosser75805372011-04-29 06:27:02 +0000492 // Replace old operands with the new ones.
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000493 for (Instruction::const_op_iterator OI = Inst->op_begin(),
494 OE = Inst->op_end(); OI != OE; ++OI) {
495 Value *OldOperand = *OI;
496 Value *NewOperand = getOperand(OldOperand, BBMap);
Tobias Grosser75805372011-04-29 06:27:02 +0000497
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000498 if (!NewOperand) {
Tobias Grosser75805372011-04-29 06:27:02 +0000499 assert(!isa<StoreInst>(NewInst)
500 && "Store instructions are always needed!");
501 delete NewInst;
502 return;
503 }
504
Tobias Grosserb06e71b2011-09-04 11:45:34 +0000505 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
Tobias Grosser75805372011-04-29 06:27:02 +0000506 }
507
508 Builder.Insert(NewInst);
509 BBMap[Inst] = NewInst;
510
511 if (!NewInst->getType()->isVoidTy())
512 NewInst->setName("p_" + Inst->getName());
513 }
514
Tobias Grosser7551c302011-09-04 11:45:41 +0000515 bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap) {
516 for (Instruction::const_op_iterator OI = Inst->op_begin(),
517 OE = Inst->op_end(); OI != OE; ++OI)
518 if (VectorMap.count(*OI))
519 return true;
520 return false;
Tobias Grosser09c57102011-09-04 11:45:29 +0000521 }
522
Tobias Grosser75805372011-04-29 06:27:02 +0000523 int getVectorSize() {
524 return ValueMaps.size();
525 }
526
527 bool isVectorBlock() {
528 return getVectorSize() > 1;
529 }
530
Tobias Grosser7551c302011-09-04 11:45:41 +0000531 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
532 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
533 int vectorDimension, int vectorWidth) {
534 // Terminator instructions control the control flow. They are explicitally
535 // expressed in the clast and do not need to be copied.
536 if (Inst->isTerminator())
537 return;
538
539 if (isVectorBlock()) {
540 // If this instruction is already in the vectorMap, a vector instruction
541 // was already issued, that calculates the values of all dimensions. No
542 // need to create any more instructions.
543 if (vectorMap.count(Inst))
544 return;
545 }
546
547 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
548 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
549 return;
550 }
551
552 if (isVectorBlock() && hasVectorOperands(Inst, vectorMap)) {
Tobias Grosserc9215152011-09-04 11:45:52 +0000553 if (const UnaryInstruction *UnaryInst = dyn_cast<UnaryInstruction>(Inst))
554 copyUnaryInst(UnaryInst, BBMap, vectorMap, vectorDimension,
555 vectorWidth);
556 else if
557 (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst))
Tobias Grosser8b00a512011-09-04 11:45:45 +0000558 copyBinInst(binaryInst, BBMap, vectorMap, vectorDimension, vectorWidth);
Tobias Grosser7551c302011-09-04 11:45:41 +0000559 else if (const StoreInst *store = dyn_cast<StoreInst>(Inst))
560 copyVectorStore(store, BBMap, vectorMap, scalarMaps, vectorDimension,
561 vectorWidth);
562 else
563 llvm_unreachable("Cannot issue vector code for this instruction");
564
565 return;
566 }
567
568 copyInstScalar(Inst, BBMap);
569 }
Tobias Grosser75805372011-04-29 06:27:02 +0000570 // Insert a copy of a basic block in the newly generated code.
571 //
572 // @param Builder The builder used to insert the code. It also specifies
573 // where to insert the code.
574 // @param BB The basic block to copy
575 // @param VMap A map returning for any old value its new equivalent. This
576 // is used to update the operands of the statements.
577 // For new statements a relation old->new is inserted in this
578 // map.
579 void copyBB(BasicBlock *BB, DominatorTree *DT) {
580 Function *F = Builder.GetInsertBlock()->getParent();
581 LLVMContext &Context = F->getContext();
582 BasicBlock *CopyBB = BasicBlock::Create(Context,
Tobias Grosser8ae9aca2011-09-04 11:45:22 +0000583 "polly." + BB->getNameStr()
584 + ".stmt",
Tobias Grosser75805372011-04-29 06:27:02 +0000585 F);
586 Builder.CreateBr(CopyBB);
587 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
588 Builder.SetInsertPoint(CopyBB);
589
590 // Create two maps that store the mapping from the original instructions of
591 // the old basic block to their copies in the new basic block. Those maps
592 // are basic block local.
593 //
594 // As vector code generation is supported there is one map for scalar values
595 // and one for vector values.
596 //
597 // In case we just do scalar code generation, the vectorMap is not used and
598 // the scalarMap has just one dimension, which contains the mapping.
599 //
600 // In case vector code generation is done, an instruction may either appear
601 // in the vector map once (as it is calculating >vectorwidth< values at a
602 // time. Or (if the values are calculated using scalar operations), it
603 // appears once in every dimension of the scalarMap.
604 VectorValueMapT scalarBlockMap(getVectorSize());
605 ValueMapT vectorBlockMap;
606
607 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
608 II != IE; ++II)
609 for (int i = 0; i < getVectorSize(); i++) {
610 if (isVectorBlock())
611 VMap = ValueMaps[i];
612
613 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
614 scalarBlockMap, i, getVectorSize());
615 }
616 }
617};
618
619/// Class to generate LLVM-IR that calculates the value of a clast_expr.
620class ClastExpCodeGen {
621 IRBuilder<> &Builder;
622 const CharMapT *IVS;
623
Tobias Grosser55927aa2011-07-18 09:53:32 +0000624 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000625 CharMapT::const_iterator I = IVS->find(e->name);
626
627 if (I != IVS->end())
628 return Builder.CreateSExtOrBitCast(I->second, Ty);
629 else
630 llvm_unreachable("Clast name not found");
631 }
632
Tobias Grosser55927aa2011-07-18 09:53:32 +0000633 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000634 APInt a = APInt_from_MPZ(e->val);
635
636 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
637 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
638
639 if (e->var) {
640 Value *var = codegen(e->var, Ty);
641 return Builder.CreateMul(ConstOne, var);
642 }
643
644 return ConstOne;
645 }
646
Tobias Grosser55927aa2011-07-18 09:53:32 +0000647 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000648 Value *LHS = codegen(e->LHS, Ty);
649
650 APInt RHS_AP = APInt_from_MPZ(e->RHS);
651
652 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
653 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
654
655 switch (e->type) {
656 case clast_bin_mod:
657 return Builder.CreateSRem(LHS, RHS);
658 case clast_bin_fdiv:
659 {
660 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
661 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
662 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
663 One = Builder.CreateZExtOrBitCast(One, Ty);
664 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
665 Value *Sum1 = Builder.CreateSub(LHS, RHS);
666 Value *Sum2 = Builder.CreateAdd(Sum1, One);
667 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
668 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
669 return Builder.CreateSDiv(Dividend, RHS);
670 }
671 case clast_bin_cdiv:
672 {
673 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
674 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
675 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
676 One = Builder.CreateZExtOrBitCast(One, Ty);
677 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
678 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
679 Value *Sum2 = Builder.CreateSub(Sum1, One);
680 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
681 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
682 return Builder.CreateSDiv(Dividend, RHS);
683 }
684 case clast_bin_div:
685 return Builder.CreateSDiv(LHS, RHS);
686 default:
687 llvm_unreachable("Unknown clast binary expression type");
688 };
689 }
690
Tobias Grosser55927aa2011-07-18 09:53:32 +0000691 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000692 assert(( r->type == clast_red_min
693 || r->type == clast_red_max
694 || r->type == clast_red_sum)
695 && "Clast reduction type not supported");
696 Value *old = codegen(r->elts[0], Ty);
697
698 for (int i=1; i < r->n; ++i) {
699 Value *exprValue = codegen(r->elts[i], Ty);
700
701 switch (r->type) {
702 case clast_red_min:
703 {
704 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
705 old = Builder.CreateSelect(cmp, old, exprValue);
706 break;
707 }
708 case clast_red_max:
709 {
710 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
711 old = Builder.CreateSelect(cmp, old, exprValue);
712 break;
713 }
714 case clast_red_sum:
715 old = Builder.CreateAdd(old, exprValue);
716 break;
717 default:
718 llvm_unreachable("Clast unknown reduction type");
719 }
720 }
721
722 return old;
723 }
724
725public:
726
727 // A generator for clast expressions.
728 //
729 // @param B The IRBuilder that defines where the code to calculate the
730 // clast expressions should be inserted.
731 // @param IVMAP A Map that translates strings describing the induction
732 // variables to the Values* that represent these variables
733 // on the LLVM side.
734 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
735
736 // Generates code to calculate a given clast expression.
737 //
738 // @param e The expression to calculate.
739 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000740 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000741 switch(e->type) {
742 case clast_expr_name:
743 return codegen((const clast_name *)e, Ty);
744 case clast_expr_term:
745 return codegen((const clast_term *)e, Ty);
746 case clast_expr_bin:
747 return codegen((const clast_binary *)e, Ty);
748 case clast_expr_red:
749 return codegen((const clast_reduction *)e, Ty);
750 default:
751 llvm_unreachable("Unknown clast expression!");
752 }
753 }
754
755 // @brief Reset the CharMap.
756 //
757 // This function is called to reset the CharMap to new one, while generating
758 // OpenMP code.
759 void setIVS(CharMapT *IVSNew) {
760 IVS = IVSNew;
761 }
762
763};
764
765class ClastStmtCodeGen {
766 // The Scop we code generate.
767 Scop *S;
768 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000769 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000770 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000771 Dependences *DP;
772 TargetData *TD;
773
774 // The Builder specifies the current location to code generate at.
775 IRBuilder<> &Builder;
776
777 // Map the Values from the old code to their counterparts in the new code.
778 ValueMapT ValueMap;
779
780 // clastVars maps from the textual representation of a clast variable to its
781 // current *Value. clast variables are scheduling variables, original
782 // induction variables or parameters. They are used either in loop bounds or
783 // to define the statement instance that is executed.
784 //
785 // for (s = 0; s < n + 3; ++i)
786 // for (t = s; t < m; ++j)
787 // Stmt(i = s + 3 * m, j = t);
788 //
789 // {s,t,i,j,n,m} is the set of clast variables in this clast.
790 CharMapT *clastVars;
791
792 // Codegenerator for clast expressions.
793 ClastExpCodeGen ExpGen;
794
795 // Do we currently generate parallel code?
796 bool parallelCodeGeneration;
797
798 std::vector<std::string> parallelLoops;
799
800public:
801
802 const std::vector<std::string> &getParallelLoops() {
803 return parallelLoops;
804 }
805
806 protected:
807 void codegen(const clast_assignment *a) {
808 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
809 TD->getIntPtrType(Builder.getContext()));
810 }
811
812 void codegen(const clast_assignment *a, ScopStmt *Statement,
813 unsigned Dimension, int vectorDim,
814 std::vector<ValueMapT> *VectorVMap = 0) {
815 Value *RHS = ExpGen.codegen(a->RHS,
816 TD->getIntPtrType(Builder.getContext()));
817
818 assert(!a->LHS && "Statement assignments do not have left hand side");
819 const PHINode *PN;
820 PN = Statement->getInductionVariableForDimension(Dimension);
821 const Value *V = PN;
822
Tobias Grosser75805372011-04-29 06:27:02 +0000823 if (VectorVMap)
824 (*VectorVMap)[vectorDim][V] = RHS;
825
826 ValueMap[V] = RHS;
827 }
828
829 void codegenSubstitutions(const clast_stmt *Assignment,
830 ScopStmt *Statement, int vectorDim = 0,
831 std::vector<ValueMapT> *VectorVMap = 0) {
832 int Dimension = 0;
833
834 while (Assignment) {
835 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
836 && "Substitions are expected to be assignments");
837 codegen((const clast_assignment *)Assignment, Statement, Dimension,
838 vectorDim, VectorVMap);
839 Assignment = Assignment->next;
840 Dimension++;
841 }
842 }
843
844 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
845 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
846 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
847 BasicBlock *BB = Statement->getBasicBlock();
848
849 if (u->substitutions)
850 codegenSubstitutions(u->substitutions, Statement);
851
852 int vectorDimensions = IVS ? IVS->size() : 1;
853
854 VectorValueMapT VectorValueMap(vectorDimensions);
855
856 if (IVS) {
857 assert (u->substitutions && "Substitutions expected!");
858 int i = 0;
859 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
860 II != IE; ++II) {
861 (*clastVars)[iterator] = *II;
862 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
863 i++;
864 }
865 }
866
867 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
868 scatteringDomain);
869 Generator.copyBB(BB, DT);
870 }
871
872 void codegen(const clast_block *b) {
873 if (b->body)
874 codegen(b->body);
875 }
876
877 /// @brief Create a classical sequential loop.
878 void codegenForSequential(const clast_for *f, Value *lowerBound = 0,
879 Value *upperBound = 0) {
880 APInt Stride = APInt_from_MPZ(f->stride);
881 PHINode *IV;
882 Value *IncrementedIV;
883 BasicBlock *AfterBB;
884 // The value of lowerbound and upperbound will be supplied, if this
885 // function is called while generating OpenMP code. Otherwise get
886 // the values.
887 assert(((lowerBound && upperBound) || (!lowerBound && !upperBound))
888 && "Either give both bounds or none");
889 if (lowerBound == 0 || upperBound == 0) {
890 lowerBound = ExpGen.codegen(f->LB,
891 TD->getIntPtrType(Builder.getContext()));
892 upperBound = ExpGen.codegen(f->UB,
893 TD->getIntPtrType(Builder.getContext()));
894 }
895 createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB,
896 IncrementedIV, DT);
897
898 // Add loop iv to symbols.
899 (*clastVars)[f->iterator] = IV;
900
901 if (f->body)
902 codegen(f->body);
903
904 // Loop is finished, so remove its iv from the live symbols.
905 clastVars->erase(f->iterator);
906
907 BasicBlock *HeaderBB = *pred_begin(AfterBB);
908 BasicBlock *LastBodyBB = Builder.GetInsertBlock();
909 Builder.CreateBr(HeaderBB);
910 IV->addIncoming(IncrementedIV, LastBodyBB);
911 Builder.SetInsertPoint(AfterBB);
912 }
913
Tobias Grosser75805372011-04-29 06:27:02 +0000914 /// @brief Add a new definition of an openmp subfunction.
Tobias Grosser7ffe4e82011-11-17 12:56:10 +0000915 Function *addOpenMPSubfunction(Module *M) {
Tobias Grosser75805372011-04-29 06:27:02 +0000916 Function *F = Builder.GetInsertBlock()->getParent();
917 const std::string &Name = F->getNameStr() + ".omp_subfn";
918
Tobias Grosser851b96e2011-07-12 12:42:54 +0000919 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +0000920 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
921 Function *FN = Function::Create(FT, Function::InternalLinkage, Name, M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000922 // Do not run any polly pass on the new function.
923 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +0000924
925 Function::arg_iterator AI = FN->arg_begin();
926 AI->setName("omp.userContext");
927
928 return FN;
929 }
930
931 /// @brief Add values to the OpenMP structure.
932 ///
933 /// Create the subfunction structure and add the values from the list.
934 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
935 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +0000936 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +0000937
938 // Create the structure.
939 for (unsigned i = 0; i < OMPDataVals.size(); i++)
940 structMembers.push_back(OMPDataVals[i]->getType());
941
Tobias Grosser75805372011-04-29 06:27:02 +0000942 StructType *structTy = StructType::get(Builder.getContext(),
943 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +0000944 // Store the values into the structure.
945 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
946 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
947 Value *storeAddr = Builder.CreateStructGEP(structData, i);
948 Builder.CreateStore(OMPDataVals[i], storeAddr);
949 }
950
951 return structData;
952 }
953
954 /// @brief Create OpenMP structure values.
955 ///
956 /// Create a list of values that has to be stored into the subfuncition
957 /// structure.
958 SetVector<Value*> createOpenMPStructValues() {
959 SetVector<Value*> OMPDataVals;
960
961 // Push the clast variables available in the clastVars.
962 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
963 I != E; I++)
964 OMPDataVals.insert(I->second);
965
966 // Push the base addresses of memory references.
967 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
968 ScopStmt *Stmt = *SI;
969 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
970 E = Stmt->memacc_end(); I != E; ++I) {
971 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
972 OMPDataVals.insert((BaseAddr));
973 }
974 }
975
976 return OMPDataVals;
977 }
978
979 /// @brief Extract the values from the subfunction parameter.
980 ///
981 /// Extract the values from the subfunction parameter and update the clast
982 /// variables to point to the new values.
983 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
984 SetVector<Value*> OMPDataVals,
985 Value *userContext) {
986 // Extract the clast variables.
987 unsigned i = 0;
988 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
989 I != E; I++) {
990 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
991 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
992 i++;
993 }
994
995 // Extract the base addresses of memory references.
996 for (unsigned j = i; j < OMPDataVals.size(); j++) {
997 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
998 Value *baseAddr = OMPDataVals[j];
999 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
1000 }
1001
1002 }
1003
1004 /// @brief Add body to the subfunction.
1005 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
1006 Value *structData,
1007 SetVector<Value*> OMPDataVals) {
1008 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1009 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001010 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001011
1012 // Store the previous basic block.
1013 BasicBlock *PrevBB = Builder.GetInsertBlock();
1014
1015 // Create basic blocks.
1016 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
1017 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
1018 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
1019 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
1020 FN);
1021
1022 DT->addNewBlock(HeaderBB, PrevBB);
1023 DT->addNewBlock(ExitBB, HeaderBB);
1024 DT->addNewBlock(checkNextBB, HeaderBB);
1025 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
1026
1027 // Fill up basic block HeaderBB.
1028 Builder.SetInsertPoint(HeaderBB);
1029 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1030 "omp.lowerBoundPtr");
1031 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1032 "omp.upperBoundPtr");
1033 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1034 structData->getType(),
1035 "omp.userContext");
1036
1037 CharMapT clastVarsOMP;
1038 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1039
1040 Builder.CreateBr(checkNextBB);
1041
1042 // Add code to check if another set of iterations will be executed.
1043 Builder.SetInsertPoint(checkNextBB);
1044 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1045 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1046 lowerBoundPtr, upperBoundPtr);
1047 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1048 "omp.hasNextScheduleBlock");
1049 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1050
1051 // Add code to to load the iv bounds for this set of iterations.
1052 Builder.SetInsertPoint(loadIVBoundsBB);
1053 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1054 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1055
1056 // Subtract one as the upper bound provided by openmp is a < comparison
1057 // whereas the codegenForSequential function creates a <= comparison.
1058 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1059 "omp.upperBoundAdjusted");
1060
1061 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1062 CharMapT *oldClastVars = clastVars;
1063 clastVars = &clastVarsOMP;
1064 ExpGen.setIVS(&clastVarsOMP);
1065
1066 codegenForSequential(f, lowerBound, upperBound);
1067
1068 // Restore the old clastVars.
1069 clastVars = oldClastVars;
1070 ExpGen.setIVS(oldClastVars);
1071
1072 Builder.CreateBr(checkNextBB);
1073
1074 // Add code to terminate this openmp subfunction.
1075 Builder.SetInsertPoint(ExitBB);
1076 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1077 Builder.CreateCall(endnowaitFunction);
1078 Builder.CreateRetVoid();
1079
1080 // Restore the builder back to previous basic block.
1081 Builder.SetInsertPoint(PrevBB);
1082 }
1083
1084 /// @brief Create an OpenMP parallel for loop.
1085 ///
1086 /// This loop reflects a loop as if it would have been created by an OpenMP
1087 /// statement.
1088 void codegenForOpenMP(const clast_for *f) {
1089 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001090 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001091
1092 Function *SubFunction = addOpenMPSubfunction(M);
1093 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1094 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1095
1096 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1097
1098 // Create call for GOMP_parallel_loop_runtime_start.
1099 Value *subfunctionParam = Builder.CreateBitCast(structData,
1100 Builder.getInt8PtrTy(),
1101 "omp_data");
1102
1103 Value *numberOfThreads = Builder.getInt32(0);
1104 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1105 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1106
1107 // Add one as the upper bound provided by openmp is a < comparison
1108 // whereas the codegenForSequential function creates a <= comparison.
1109 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1110 APInt APStride = APInt_from_MPZ(f->stride);
1111 Value *stride = ConstantInt::get(intPtrTy,
1112 APStride.zext(intPtrTy->getBitWidth()));
1113
1114 SmallVector<Value *, 6> Arguments;
1115 Arguments.push_back(SubFunction);
1116 Arguments.push_back(subfunctionParam);
1117 Arguments.push_back(numberOfThreads);
1118 Arguments.push_back(lowerBound);
1119 Arguments.push_back(upperBound);
1120 Arguments.push_back(stride);
1121
1122 Function *parallelStartFunction =
1123 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001124 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001125
1126 // Create call to the subfunction.
1127 Builder.CreateCall(SubFunction, subfunctionParam);
1128
1129 // Create call for GOMP_parallel_end.
1130 Function *FN = M->getFunction("GOMP_parallel_end");
1131 Builder.CreateCall(FN);
1132 }
1133
1134 bool isInnermostLoop(const clast_for *f) {
1135 const clast_stmt *stmt = f->body;
1136
1137 while (stmt) {
1138 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1139 return false;
1140
1141 stmt = stmt->next;
1142 }
1143
1144 return true;
1145 }
1146
1147 /// @brief Get the number of loop iterations for this loop.
1148 /// @param f The clast for loop to check.
1149 int getNumberOfIterations(const clast_for *f) {
1150 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1151 isl_set *tmp = isl_set_copy(loopDomain);
1152
1153 // Calculate a map similar to the identity map, but with the last input
1154 // and output dimension not related.
1155 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
Tobias Grosserf5338802011-10-06 00:03:35 +00001156 isl_space *Space = isl_set_get_space(loopDomain);
1157 Space = isl_space_drop_outputs(Space,
1158 isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1159 Space = isl_space_map_from_set(Space);
1160 isl_map *identity = isl_map_identity(Space);
Tobias Grosser75805372011-04-29 06:27:02 +00001161 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1162 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1163
1164 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1165 map = isl_map_intersect(map, identity);
1166
1167 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001168 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001169 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1170
1171 isl_set *elements = isl_map_range(sub);
1172
Tobias Grosserc532f122011-08-25 08:40:59 +00001173 if (!isl_set_is_singleton(elements)) {
1174 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001175 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001176 }
Tobias Grosser75805372011-04-29 06:27:02 +00001177
1178 isl_point *p = isl_set_sample_point(elements);
1179
1180 isl_int v;
1181 isl_int_init(v);
1182 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1183 int numberIterations = isl_int_get_si(v);
1184 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001185 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001186
1187 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1188 }
1189
1190 /// @brief Create vector instructions for this loop.
1191 void codegenForVector(const clast_for *f) {
1192 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1193 int vectorWidth = getNumberOfIterations(f);
1194
1195 Value *LB = ExpGen.codegen(f->LB,
1196 TD->getIntPtrType(Builder.getContext()));
1197
1198 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001199 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001200 Stride = Stride.zext(LoopIVType->getBitWidth());
1201 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1202
1203 std::vector<Value*> IVS(vectorWidth);
1204 IVS[0] = LB;
1205
1206 for (int i = 1; i < vectorWidth; i++)
1207 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1208
1209 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1210
1211 // Add loop iv to symbols.
1212 (*clastVars)[f->iterator] = LB;
1213
1214 const clast_stmt *stmt = f->body;
1215
1216 while (stmt) {
1217 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1218 scatteringDomain);
1219 stmt = stmt->next;
1220 }
1221
1222 // Loop is finished, so remove its iv from the live symbols.
1223 clastVars->erase(f->iterator);
1224 }
1225
1226 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001227 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001228 && (-1 != getNumberOfIterations(f))
1229 && (getNumberOfIterations(f) <= 16)) {
1230 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001231 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001232 parallelCodeGeneration = true;
1233 parallelLoops.push_back(f->iterator);
1234 codegenForOpenMP(f);
1235 parallelCodeGeneration = false;
1236 } else
1237 codegenForSequential(f);
1238 }
1239
1240 Value *codegen(const clast_equation *eq) {
1241 Value *LHS = ExpGen.codegen(eq->LHS,
1242 TD->getIntPtrType(Builder.getContext()));
1243 Value *RHS = ExpGen.codegen(eq->RHS,
1244 TD->getIntPtrType(Builder.getContext()));
1245 CmpInst::Predicate P;
1246
1247 if (eq->sign == 0)
1248 P = ICmpInst::ICMP_EQ;
1249 else if (eq->sign > 0)
1250 P = ICmpInst::ICMP_SGE;
1251 else
1252 P = ICmpInst::ICMP_SLE;
1253
1254 return Builder.CreateICmp(P, LHS, RHS);
1255 }
1256
1257 void codegen(const clast_guard *g) {
1258 Function *F = Builder.GetInsertBlock()->getParent();
1259 LLVMContext &Context = F->getContext();
1260 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1261 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1262 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1263 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1264
1265 Value *Predicate = codegen(&(g->eq[0]));
1266
1267 for (int i = 1; i < g->n; ++i) {
1268 Value *TmpPredicate = codegen(&(g->eq[i]));
1269 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1270 }
1271
1272 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1273 Builder.SetInsertPoint(ThenBB);
1274
1275 codegen(g->then);
1276
1277 Builder.CreateBr(MergeBB);
1278 Builder.SetInsertPoint(MergeBB);
1279 }
1280
1281 void codegen(const clast_stmt *stmt) {
1282 if (CLAST_STMT_IS_A(stmt, stmt_root))
1283 assert(false && "No second root statement expected");
1284 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1285 codegen((const clast_assignment *)stmt);
1286 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1287 codegen((const clast_user_stmt *)stmt);
1288 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1289 codegen((const clast_block *)stmt);
1290 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1291 codegen((const clast_for *)stmt);
1292 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1293 codegen((const clast_guard *)stmt);
1294
1295 if (stmt->next)
1296 codegen(stmt->next);
1297 }
1298
1299 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001300 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001301
1302 // Create an instruction that specifies the location where the parameters
1303 // are expanded.
1304 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1305 Builder.getInt16Ty(), false, "insertInst",
1306 Builder.GetInsertBlock());
1307
1308 int i = 0;
1309 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1310 PI != PE; ++PI) {
1311 assert(i < names->nb_parameters && "Not enough parameter names");
1312
1313 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001314 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001315
1316 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1317 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1318 (*clastVars)[names->parameters[i]] = V;
1319
1320 ++i;
1321 }
1322 }
1323
1324 public:
1325 void codegen(const clast_root *r) {
1326 clastVars = new CharMapT();
1327 addParameters(r->names);
1328 ExpGen.setIVS(clastVars);
1329
1330 parallelCodeGeneration = false;
1331
1332 const clast_stmt *stmt = (const clast_stmt*) r;
1333 if (stmt->next)
1334 codegen(stmt->next);
1335
1336 delete clastVars;
1337 }
1338
1339 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001340 ScopDetection *sd, Dependences *dp, TargetData *td,
1341 IRBuilder<> &B) :
1342 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1343 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001344
1345};
1346}
1347
1348namespace {
1349class CodeGeneration : public ScopPass {
1350 Region *region;
1351 Scop *S;
1352 DominatorTree *DT;
1353 ScalarEvolution *SE;
1354 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001355 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001356 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001357
1358 std::vector<std::string> parallelLoops;
1359
1360 public:
1361 static char ID;
1362
1363 CodeGeneration() : ScopPass(ID) {}
1364
Tobias Grosser75805372011-04-29 06:27:02 +00001365 // Adding prototypes required if OpenMP is enabled.
1366 void addOpenMPDefinitions(IRBuilder<> &Builder)
1367 {
1368 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1369 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001370 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001371
1372 if (!M->getFunction("GOMP_parallel_end")) {
1373 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1374 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1375 }
1376
1377 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1378 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001379 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001380 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1381 false);
1382 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1383
Tobias Grosser851b96e2011-07-12 12:42:54 +00001384 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001385 args.push_back(FnPtrTy);
1386 args.push_back(Builder.getInt8PtrTy());
1387 args.push_back(Builder.getInt32Ty());
1388 args.push_back(intPtrTy);
1389 args.push_back(intPtrTy);
1390 args.push_back(intPtrTy);
1391
1392 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1393 Function::Create(type, Function::ExternalLinkage,
1394 "GOMP_parallel_loop_runtime_start", M);
1395 }
1396
1397 if (!M->getFunction("GOMP_loop_runtime_next")) {
1398 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1399
Tobias Grosser851b96e2011-07-12 12:42:54 +00001400 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001401 args.push_back(intLongPtrTy);
1402 args.push_back(intLongPtrTy);
1403
1404 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1405 Function::Create(type, Function::ExternalLinkage,
1406 "GOMP_loop_runtime_next", M);
1407 }
1408
1409 if (!M->getFunction("GOMP_loop_end_nowait")) {
1410 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001411 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001412 Function::Create(FT, Function::ExternalLinkage,
1413 "GOMP_loop_end_nowait", M);
1414 }
1415 }
1416
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001417 // Split the entry edge of the region and generate a new basic block on this
1418 // edge. This function also updates ScopInfo and RegionInfo.
1419 //
1420 // @param region The region where the entry edge will be splitted.
1421 BasicBlock *splitEdgeAdvanced(Region *region) {
1422 BasicBlock *newBlock;
1423 BasicBlock *splitBlock;
1424
1425 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1426
1427 if (DT->dominates(region->getEntry(), newBlock)) {
1428 // Update ScopInfo.
1429 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1430 if ((*SI)->getBasicBlock() == newBlock) {
1431 (*SI)->setBasicBlock(newBlock);
1432 break;
1433 }
1434
1435 // Update RegionInfo.
1436 splitBlock = region->getEntry();
1437 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001438 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001439 } else {
1440 RI->setRegionFor(newBlock, region->getParent());
1441 splitBlock = newBlock;
1442 }
1443
1444 return splitBlock;
1445 }
1446
1447 // Create a split block that branches either to the old code or to a new basic
1448 // block where the new code can be inserted.
1449 //
1450 // @param builder A builder that will be set to point to a basic block, where
1451 // the new code can be generated.
1452 // @return The split basic block.
1453 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1454 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1455
1456 splitBlock->setName("polly.enterScop");
1457
1458 Function *function = splitBlock->getParent();
1459 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1460 "polly.start", function);
1461 splitBlock->getTerminator()->eraseFromParent();
1462 builder->SetInsertPoint(splitBlock);
1463 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1464 DT->addNewBlock(startBlock, splitBlock);
1465
1466 // Start code generation here.
1467 builder->SetInsertPoint(startBlock);
1468 return splitBlock;
1469 }
1470
1471 // Merge the control flow of the newly generated code with the existing code.
1472 //
1473 // @param splitBlock The basic block where the control flow was split between
1474 // old and new version of the Scop.
1475 // @param builder An IRBuilder that points to the last instruction of the
1476 // newly generated code.
1477 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1478 BasicBlock *mergeBlock;
1479 Region *R = region;
1480
1481 if (R->getExit()->getSinglePredecessor())
1482 // No splitEdge required. A block with a single predecessor cannot have
1483 // PHI nodes that would complicate life.
1484 mergeBlock = R->getExit();
1485 else {
1486 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1487 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1488 // one predecessor. Hence, mergeBlock is always a newly generated block.
1489 mergeBlock->setName("polly.finalMerge");
1490 R->replaceExit(mergeBlock);
1491 }
1492
1493 builder->CreateBr(mergeBlock);
1494
1495 if (DT->dominates(splitBlock, mergeBlock))
1496 DT->changeImmediateDominator(mergeBlock, splitBlock);
1497 }
1498
Tobias Grosser75805372011-04-29 06:27:02 +00001499 bool runOnScop(Scop &scop) {
1500 S = &scop;
1501 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001502 DT = &getAnalysis<DominatorTree>();
1503 Dependences *DP = &getAnalysis<Dependences>();
1504 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001505 SD = &getAnalysis<ScopDetection>();
1506 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001507 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001508
1509 parallelLoops.clear();
1510
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001511 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001512
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001513 // In the CFG and we generate next to original code of the Scop the
1514 // optimized version. Both the new and the original version of the code
1515 // remain in the CFG. A branch statement decides which version is executed.
1516 // At the moment, we always execute the newly generated version (the old one
1517 // is dead code eliminated by the cleanup passes). Later we may decide to
1518 // execute the new version only under certain conditions. This will be the
1519 // case if we support constructs for which we cannot prove all assumptions
1520 // at compile time.
1521 //
1522 // Before transformation:
1523 //
1524 // bb0
1525 // |
1526 // orig_scop
1527 // |
1528 // bb1
1529 //
1530 // After transformation:
1531 // bb0
1532 // |
1533 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001534 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001535 // | startBlock
1536 // | |
1537 // orig_scop new_scop
1538 // \ /
1539 // \ /
1540 // bb1 (joinBlock)
1541 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001542
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001543 // The builder will be set to startBlock.
1544 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001545
1546 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001547 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001548
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001549 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001550 CloogInfo &C = getAnalysis<CloogInfo>();
1551 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001552
Tobias Grosser75805372011-04-29 06:27:02 +00001553 parallelLoops.insert(parallelLoops.begin(),
1554 CodeGen.getParallelLoops().begin(),
1555 CodeGen.getParallelLoops().end());
1556
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001557 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001558
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001559 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001560 }
1561
1562 virtual void printScop(raw_ostream &OS) const {
1563 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1564 PE = parallelLoops.end(); PI != PE; ++PI)
1565 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1566 }
1567
1568 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1569 AU.addRequired<CloogInfo>();
1570 AU.addRequired<Dependences>();
1571 AU.addRequired<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001572 AU.addRequired<RegionInfo>();
Tobias Grosser73600b82011-10-08 00:30:40 +00001573 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001574 AU.addRequired<ScopDetection>();
1575 AU.addRequired<ScopInfo>();
1576 AU.addRequired<TargetData>();
1577
1578 AU.addPreserved<CloogInfo>();
1579 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001580
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001581 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001582 AU.addPreserved<LoopInfo>();
1583 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001584 AU.addPreserved<ScopDetection>();
1585 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001586
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001587 // FIXME: We do not yet add regions for the newly generated code to the
1588 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001589 AU.addPreserved<RegionInfo>();
1590 AU.addPreserved<TempScopInfo>();
1591 AU.addPreserved<ScopInfo>();
1592 AU.addPreservedID(IndependentBlocksID);
1593 }
1594};
1595}
1596
1597char CodeGeneration::ID = 1;
1598
Tobias Grosser73600b82011-10-08 00:30:40 +00001599INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1600 "Polly - Create LLVM-IR form SCoPs", false, false)
1601INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1602INITIALIZE_PASS_DEPENDENCY(Dependences)
1603INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1604INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1605INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1606INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1607INITIALIZE_PASS_DEPENDENCY(TargetData)
1608INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1609 "Polly - Create LLVM-IR form SCoPs", false, false)
Tobias Grosser75805372011-04-29 06:27:02 +00001610
Tobias Grosser7ffe4e82011-11-17 12:56:10 +00001611Pass *polly::createCodeGenerationPass() {
Tobias Grosser75805372011-04-29 06:27:02 +00001612 return new CodeGeneration();
1613}