blob: 6be929edc5acd6657f5a29b315503137e58710a4 [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
365 assert(isl_map_has_equal_dim(currentAccessRelation, newAccessRelation)
366 && "Current and new access function dimensions differ");
367
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) {
391
392 if (scalarMaps.size() == 1) {
393 scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]);
394 return;
395 }
396
397 Value *newLoad;
398
399 MemoryAccess &Access = statement.getAccessFor(load);
400
401 assert(scatteringDomain && "No scattering domain available");
402
403 if (Access.isStrideZero(scatteringDomain))
404 newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth);
405 else if (Access.isStrideOne(scatteringDomain))
406 newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth);
407 else
408 newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth);
409
410 vectorMap[load] = newLoad;
411 }
412
413 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
414 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
415 int vectorDimension, int vectorWidth) {
416 // If this instruction is already in the vectorMap, a vector instruction
417 // was already issued, that calculates the values of all dimensions. No
418 // need to create any more instructions.
419 if (vectorMap.count(Inst))
420 return;
421
422 // Terminator instructions control the control flow. They are explicitally
423 // expressed in the clast and do not need to be copied.
424 if (Inst->isTerminator())
425 return;
426
427 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
428 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
429 return;
430 }
431
432 if (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst)) {
433 Value *opZero = Inst->getOperand(0);
434 Value *opOne = Inst->getOperand(1);
435
436 // This is an old instruction that can be ignored.
437 if (!opZero && !opOne)
438 return;
439
440 bool isVectorOp = vectorMap.count(opZero) || vectorMap.count(opOne);
441
442 if (isVectorOp && vectorDimension > 0)
443 return;
444
445 Value *newOpZero, *newOpOne;
446 newOpZero = getOperand(opZero, BBMap, &vectorMap);
447 newOpOne = getOperand(opOne, BBMap, &vectorMap);
448
449
450 std::string name;
451 if (isVectorOp) {
452 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
453 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
454 name = Inst->getNameStr() + "p_vec";
455 } else
456 name = Inst->getNameStr() + "p_sca";
457
458 Value *newInst = Builder.CreateBinOp(binaryInst->getOpcode(), newOpZero,
459 newOpOne, name);
460 if (isVectorOp)
461 vectorMap[Inst] = newInst;
462 else
463 BBMap[Inst] = newInst;
464
465 return;
466 }
467
468 if (const StoreInst *store = dyn_cast<StoreInst>(Inst)) {
469 if (vectorMap.count(store->getValueOperand()) > 0) {
470
471 // We only need to generate one store if we are in vector mode.
472 if (vectorDimension > 0)
473 return;
474
475 MemoryAccess &Access = statement.getAccessFor(store);
476
477 assert(scatteringDomain && "No scattering domain available");
478
479 const Value *pointer = store->getPointerOperand();
480 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
481
482 if (Access.isStrideOne(scatteringDomain)) {
Tobias Grosser55927aa2011-07-18 09:53:32 +0000483 Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
Tobias Grosser75805372011-04-29 06:27:02 +0000484 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
485
486 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
487 "vector_ptr");
488 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
489
490 if (!Aligned)
491 Store->setAlignment(8);
492 } else {
493 for (unsigned i = 0; i < scalarMaps.size(); i++) {
494 Value *scalar = Builder.CreateExtractElement(vector,
495 Builder.getInt32(i));
496 Value *newPointer = getOperand(pointer, scalarMaps[i]);
497 Builder.CreateStore(scalar, newPointer);
498 }
499 }
500
501 return;
502 }
503 }
504
505 Instruction *NewInst = Inst->clone();
506
507 // Copy the operands in temporary vector, as an in place update
508 // fails if an instruction is referencing the same operand twice.
509 std::vector<Value*> Operands(NewInst->op_begin(), NewInst->op_end());
510
511 // Replace old operands with the new ones.
512 for (std::vector<Value*>::iterator UI = Operands.begin(),
513 UE = Operands.end(); UI != UE; ++UI) {
514 Value *newOperand = getOperand(*UI, BBMap);
515
516 if (!newOperand) {
517 assert(!isa<StoreInst>(NewInst)
518 && "Store instructions are always needed!");
519 delete NewInst;
520 return;
521 }
522
523 NewInst->replaceUsesOfWith(*UI, newOperand);
524 }
525
526 Builder.Insert(NewInst);
527 BBMap[Inst] = NewInst;
528
529 if (!NewInst->getType()->isVoidTy())
530 NewInst->setName("p_" + Inst->getName());
531 }
532
533 int getVectorSize() {
534 return ValueMaps.size();
535 }
536
537 bool isVectorBlock() {
538 return getVectorSize() > 1;
539 }
540
541 // Insert a copy of a basic block in the newly generated code.
542 //
543 // @param Builder The builder used to insert the code. It also specifies
544 // where to insert the code.
545 // @param BB The basic block to copy
546 // @param VMap A map returning for any old value its new equivalent. This
547 // is used to update the operands of the statements.
548 // For new statements a relation old->new is inserted in this
549 // map.
550 void copyBB(BasicBlock *BB, DominatorTree *DT) {
551 Function *F = Builder.GetInsertBlock()->getParent();
552 LLVMContext &Context = F->getContext();
553 BasicBlock *CopyBB = BasicBlock::Create(Context,
Tobias Grosser8ae9aca2011-09-04 11:45:22 +0000554 "polly." + BB->getNameStr()
555 + ".stmt",
Tobias Grosser75805372011-04-29 06:27:02 +0000556 F);
557 Builder.CreateBr(CopyBB);
558 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
559 Builder.SetInsertPoint(CopyBB);
560
561 // Create two maps that store the mapping from the original instructions of
562 // the old basic block to their copies in the new basic block. Those maps
563 // are basic block local.
564 //
565 // As vector code generation is supported there is one map for scalar values
566 // and one for vector values.
567 //
568 // In case we just do scalar code generation, the vectorMap is not used and
569 // the scalarMap has just one dimension, which contains the mapping.
570 //
571 // In case vector code generation is done, an instruction may either appear
572 // in the vector map once (as it is calculating >vectorwidth< values at a
573 // time. Or (if the values are calculated using scalar operations), it
574 // appears once in every dimension of the scalarMap.
575 VectorValueMapT scalarBlockMap(getVectorSize());
576 ValueMapT vectorBlockMap;
577
578 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
579 II != IE; ++II)
580 for (int i = 0; i < getVectorSize(); i++) {
581 if (isVectorBlock())
582 VMap = ValueMaps[i];
583
584 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
585 scalarBlockMap, i, getVectorSize());
586 }
587 }
588};
589
590/// Class to generate LLVM-IR that calculates the value of a clast_expr.
591class ClastExpCodeGen {
592 IRBuilder<> &Builder;
593 const CharMapT *IVS;
594
Tobias Grosser55927aa2011-07-18 09:53:32 +0000595 Value *codegen(const clast_name *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000596 CharMapT::const_iterator I = IVS->find(e->name);
597
598 if (I != IVS->end())
599 return Builder.CreateSExtOrBitCast(I->second, Ty);
600 else
601 llvm_unreachable("Clast name not found");
602 }
603
Tobias Grosser55927aa2011-07-18 09:53:32 +0000604 Value *codegen(const clast_term *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000605 APInt a = APInt_from_MPZ(e->val);
606
607 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
608 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
609
610 if (e->var) {
611 Value *var = codegen(e->var, Ty);
612 return Builder.CreateMul(ConstOne, var);
613 }
614
615 return ConstOne;
616 }
617
Tobias Grosser55927aa2011-07-18 09:53:32 +0000618 Value *codegen(const clast_binary *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000619 Value *LHS = codegen(e->LHS, Ty);
620
621 APInt RHS_AP = APInt_from_MPZ(e->RHS);
622
623 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
624 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
625
626 switch (e->type) {
627 case clast_bin_mod:
628 return Builder.CreateSRem(LHS, RHS);
629 case clast_bin_fdiv:
630 {
631 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
632 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
633 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
634 One = Builder.CreateZExtOrBitCast(One, Ty);
635 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
636 Value *Sum1 = Builder.CreateSub(LHS, RHS);
637 Value *Sum2 = Builder.CreateAdd(Sum1, One);
638 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
639 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
640 return Builder.CreateSDiv(Dividend, RHS);
641 }
642 case clast_bin_cdiv:
643 {
644 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
645 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
646 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
647 One = Builder.CreateZExtOrBitCast(One, Ty);
648 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
649 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
650 Value *Sum2 = Builder.CreateSub(Sum1, One);
651 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
652 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
653 return Builder.CreateSDiv(Dividend, RHS);
654 }
655 case clast_bin_div:
656 return Builder.CreateSDiv(LHS, RHS);
657 default:
658 llvm_unreachable("Unknown clast binary expression type");
659 };
660 }
661
Tobias Grosser55927aa2011-07-18 09:53:32 +0000662 Value *codegen(const clast_reduction *r, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000663 assert(( r->type == clast_red_min
664 || r->type == clast_red_max
665 || r->type == clast_red_sum)
666 && "Clast reduction type not supported");
667 Value *old = codegen(r->elts[0], Ty);
668
669 for (int i=1; i < r->n; ++i) {
670 Value *exprValue = codegen(r->elts[i], Ty);
671
672 switch (r->type) {
673 case clast_red_min:
674 {
675 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
676 old = Builder.CreateSelect(cmp, old, exprValue);
677 break;
678 }
679 case clast_red_max:
680 {
681 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
682 old = Builder.CreateSelect(cmp, old, exprValue);
683 break;
684 }
685 case clast_red_sum:
686 old = Builder.CreateAdd(old, exprValue);
687 break;
688 default:
689 llvm_unreachable("Clast unknown reduction type");
690 }
691 }
692
693 return old;
694 }
695
696public:
697
698 // A generator for clast expressions.
699 //
700 // @param B The IRBuilder that defines where the code to calculate the
701 // clast expressions should be inserted.
702 // @param IVMAP A Map that translates strings describing the induction
703 // variables to the Values* that represent these variables
704 // on the LLVM side.
705 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
706
707 // Generates code to calculate a given clast expression.
708 //
709 // @param e The expression to calculate.
710 // @return The Value that holds the result.
Tobias Grosser55927aa2011-07-18 09:53:32 +0000711 Value *codegen(const clast_expr *e, Type *Ty) {
Tobias Grosser75805372011-04-29 06:27:02 +0000712 switch(e->type) {
713 case clast_expr_name:
714 return codegen((const clast_name *)e, Ty);
715 case clast_expr_term:
716 return codegen((const clast_term *)e, Ty);
717 case clast_expr_bin:
718 return codegen((const clast_binary *)e, Ty);
719 case clast_expr_red:
720 return codegen((const clast_reduction *)e, Ty);
721 default:
722 llvm_unreachable("Unknown clast expression!");
723 }
724 }
725
726 // @brief Reset the CharMap.
727 //
728 // This function is called to reset the CharMap to new one, while generating
729 // OpenMP code.
730 void setIVS(CharMapT *IVSNew) {
731 IVS = IVSNew;
732 }
733
734};
735
736class ClastStmtCodeGen {
737 // The Scop we code generate.
738 Scop *S;
739 ScalarEvolution &SE;
Tobias Grosser75805372011-04-29 06:27:02 +0000740 DominatorTree *DT;
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000741 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +0000742 Dependences *DP;
743 TargetData *TD;
744
745 // The Builder specifies the current location to code generate at.
746 IRBuilder<> &Builder;
747
748 // Map the Values from the old code to their counterparts in the new code.
749 ValueMapT ValueMap;
750
751 // clastVars maps from the textual representation of a clast variable to its
752 // current *Value. clast variables are scheduling variables, original
753 // induction variables or parameters. They are used either in loop bounds or
754 // to define the statement instance that is executed.
755 //
756 // for (s = 0; s < n + 3; ++i)
757 // for (t = s; t < m; ++j)
758 // Stmt(i = s + 3 * m, j = t);
759 //
760 // {s,t,i,j,n,m} is the set of clast variables in this clast.
761 CharMapT *clastVars;
762
763 // Codegenerator for clast expressions.
764 ClastExpCodeGen ExpGen;
765
766 // Do we currently generate parallel code?
767 bool parallelCodeGeneration;
768
769 std::vector<std::string> parallelLoops;
770
771public:
772
773 const std::vector<std::string> &getParallelLoops() {
774 return parallelLoops;
775 }
776
777 protected:
778 void codegen(const clast_assignment *a) {
779 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
780 TD->getIntPtrType(Builder.getContext()));
781 }
782
783 void codegen(const clast_assignment *a, ScopStmt *Statement,
784 unsigned Dimension, int vectorDim,
785 std::vector<ValueMapT> *VectorVMap = 0) {
786 Value *RHS = ExpGen.codegen(a->RHS,
787 TD->getIntPtrType(Builder.getContext()));
788
789 assert(!a->LHS && "Statement assignments do not have left hand side");
790 const PHINode *PN;
791 PN = Statement->getInductionVariableForDimension(Dimension);
792 const Value *V = PN;
793
Tobias Grosser75805372011-04-29 06:27:02 +0000794 if (VectorVMap)
795 (*VectorVMap)[vectorDim][V] = RHS;
796
797 ValueMap[V] = RHS;
798 }
799
800 void codegenSubstitutions(const clast_stmt *Assignment,
801 ScopStmt *Statement, int vectorDim = 0,
802 std::vector<ValueMapT> *VectorVMap = 0) {
803 int Dimension = 0;
804
805 while (Assignment) {
806 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
807 && "Substitions are expected to be assignments");
808 codegen((const clast_assignment *)Assignment, Statement, Dimension,
809 vectorDim, VectorVMap);
810 Assignment = Assignment->next;
811 Dimension++;
812 }
813 }
814
815 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
816 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
817 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
818 BasicBlock *BB = Statement->getBasicBlock();
819
820 if (u->substitutions)
821 codegenSubstitutions(u->substitutions, Statement);
822
823 int vectorDimensions = IVS ? IVS->size() : 1;
824
825 VectorValueMapT VectorValueMap(vectorDimensions);
826
827 if (IVS) {
828 assert (u->substitutions && "Substitutions expected!");
829 int i = 0;
830 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
831 II != IE; ++II) {
832 (*clastVars)[iterator] = *II;
833 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
834 i++;
835 }
836 }
837
838 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
839 scatteringDomain);
840 Generator.copyBB(BB, DT);
841 }
842
843 void codegen(const clast_block *b) {
844 if (b->body)
845 codegen(b->body);
846 }
847
848 /// @brief Create a classical sequential loop.
849 void codegenForSequential(const clast_for *f, Value *lowerBound = 0,
850 Value *upperBound = 0) {
851 APInt Stride = APInt_from_MPZ(f->stride);
852 PHINode *IV;
853 Value *IncrementedIV;
854 BasicBlock *AfterBB;
855 // The value of lowerbound and upperbound will be supplied, if this
856 // function is called while generating OpenMP code. Otherwise get
857 // the values.
858 assert(((lowerBound && upperBound) || (!lowerBound && !upperBound))
859 && "Either give both bounds or none");
860 if (lowerBound == 0 || upperBound == 0) {
861 lowerBound = ExpGen.codegen(f->LB,
862 TD->getIntPtrType(Builder.getContext()));
863 upperBound = ExpGen.codegen(f->UB,
864 TD->getIntPtrType(Builder.getContext()));
865 }
866 createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB,
867 IncrementedIV, DT);
868
869 // Add loop iv to symbols.
870 (*clastVars)[f->iterator] = IV;
871
872 if (f->body)
873 codegen(f->body);
874
875 // Loop is finished, so remove its iv from the live symbols.
876 clastVars->erase(f->iterator);
877
878 BasicBlock *HeaderBB = *pred_begin(AfterBB);
879 BasicBlock *LastBodyBB = Builder.GetInsertBlock();
880 Builder.CreateBr(HeaderBB);
881 IV->addIncoming(IncrementedIV, LastBodyBB);
882 Builder.SetInsertPoint(AfterBB);
883 }
884
Tobias Grosser75805372011-04-29 06:27:02 +0000885 /// @brief Add a new definition of an openmp subfunction.
886 Function* addOpenMPSubfunction(Module *M) {
887 Function *F = Builder.GetInsertBlock()->getParent();
888 const std::string &Name = F->getNameStr() + ".omp_subfn";
889
Tobias Grosser851b96e2011-07-12 12:42:54 +0000890 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +0000891 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
892 Function *FN = Function::Create(FT, Function::InternalLinkage, Name, M);
Hongbin Zheng94c5df12011-05-06 02:38:20 +0000893 // Do not run any polly pass on the new function.
894 SD->markFunctionAsInvalid(FN);
Tobias Grosser75805372011-04-29 06:27:02 +0000895
896 Function::arg_iterator AI = FN->arg_begin();
897 AI->setName("omp.userContext");
898
899 return FN;
900 }
901
902 /// @brief Add values to the OpenMP structure.
903 ///
904 /// Create the subfunction structure and add the values from the list.
905 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
906 Function *SubFunction) {
Tobias Grosser851b96e2011-07-12 12:42:54 +0000907 std::vector<Type*> structMembers;
Tobias Grosser75805372011-04-29 06:27:02 +0000908
909 // Create the structure.
910 for (unsigned i = 0; i < OMPDataVals.size(); i++)
911 structMembers.push_back(OMPDataVals[i]->getType());
912
Tobias Grosser75805372011-04-29 06:27:02 +0000913 StructType *structTy = StructType::get(Builder.getContext(),
914 structMembers);
Tobias Grosser75805372011-04-29 06:27:02 +0000915 // Store the values into the structure.
916 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
917 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
918 Value *storeAddr = Builder.CreateStructGEP(structData, i);
919 Builder.CreateStore(OMPDataVals[i], storeAddr);
920 }
921
922 return structData;
923 }
924
925 /// @brief Create OpenMP structure values.
926 ///
927 /// Create a list of values that has to be stored into the subfuncition
928 /// structure.
929 SetVector<Value*> createOpenMPStructValues() {
930 SetVector<Value*> OMPDataVals;
931
932 // Push the clast variables available in the clastVars.
933 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
934 I != E; I++)
935 OMPDataVals.insert(I->second);
936
937 // Push the base addresses of memory references.
938 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
939 ScopStmt *Stmt = *SI;
940 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
941 E = Stmt->memacc_end(); I != E; ++I) {
942 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
943 OMPDataVals.insert((BaseAddr));
944 }
945 }
946
947 return OMPDataVals;
948 }
949
950 /// @brief Extract the values from the subfunction parameter.
951 ///
952 /// Extract the values from the subfunction parameter and update the clast
953 /// variables to point to the new values.
954 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
955 SetVector<Value*> OMPDataVals,
956 Value *userContext) {
957 // Extract the clast variables.
958 unsigned i = 0;
959 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
960 I != E; I++) {
961 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
962 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
963 i++;
964 }
965
966 // Extract the base addresses of memory references.
967 for (unsigned j = i; j < OMPDataVals.size(); j++) {
968 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
969 Value *baseAddr = OMPDataVals[j];
970 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
971 }
972
973 }
974
975 /// @brief Add body to the subfunction.
976 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
977 Value *structData,
978 SetVector<Value*> OMPDataVals) {
979 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
980 LLVMContext &Context = FN->getContext();
Tobias Grosser55927aa2011-07-18 09:53:32 +0000981 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +0000982
983 // Store the previous basic block.
984 BasicBlock *PrevBB = Builder.GetInsertBlock();
985
986 // Create basic blocks.
987 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
988 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
989 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
990 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
991 FN);
992
993 DT->addNewBlock(HeaderBB, PrevBB);
994 DT->addNewBlock(ExitBB, HeaderBB);
995 DT->addNewBlock(checkNextBB, HeaderBB);
996 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
997
998 // Fill up basic block HeaderBB.
999 Builder.SetInsertPoint(HeaderBB);
1000 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1001 "omp.lowerBoundPtr");
1002 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
1003 "omp.upperBoundPtr");
1004 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
1005 structData->getType(),
1006 "omp.userContext");
1007
1008 CharMapT clastVarsOMP;
1009 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
1010
1011 Builder.CreateBr(checkNextBB);
1012
1013 // Add code to check if another set of iterations will be executed.
1014 Builder.SetInsertPoint(checkNextBB);
1015 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
1016 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
1017 lowerBoundPtr, upperBoundPtr);
1018 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
1019 "omp.hasNextScheduleBlock");
1020 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
1021
1022 // Add code to to load the iv bounds for this set of iterations.
1023 Builder.SetInsertPoint(loadIVBoundsBB);
1024 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
1025 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
1026
1027 // Subtract one as the upper bound provided by openmp is a < comparison
1028 // whereas the codegenForSequential function creates a <= comparison.
1029 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
1030 "omp.upperBoundAdjusted");
1031
1032 // Use clastVarsOMP during code generation of the OpenMP subfunction.
1033 CharMapT *oldClastVars = clastVars;
1034 clastVars = &clastVarsOMP;
1035 ExpGen.setIVS(&clastVarsOMP);
1036
1037 codegenForSequential(f, lowerBound, upperBound);
1038
1039 // Restore the old clastVars.
1040 clastVars = oldClastVars;
1041 ExpGen.setIVS(oldClastVars);
1042
1043 Builder.CreateBr(checkNextBB);
1044
1045 // Add code to terminate this openmp subfunction.
1046 Builder.SetInsertPoint(ExitBB);
1047 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1048 Builder.CreateCall(endnowaitFunction);
1049 Builder.CreateRetVoid();
1050
1051 // Restore the builder back to previous basic block.
1052 Builder.SetInsertPoint(PrevBB);
1053 }
1054
1055 /// @brief Create an OpenMP parallel for loop.
1056 ///
1057 /// This loop reflects a loop as if it would have been created by an OpenMP
1058 /// statement.
1059 void codegenForOpenMP(const clast_for *f) {
1060 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Tobias Grosser55927aa2011-07-18 09:53:32 +00001061 IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
Tobias Grosser75805372011-04-29 06:27:02 +00001062
1063 Function *SubFunction = addOpenMPSubfunction(M);
1064 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1065 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1066
1067 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1068
1069 // Create call for GOMP_parallel_loop_runtime_start.
1070 Value *subfunctionParam = Builder.CreateBitCast(structData,
1071 Builder.getInt8PtrTy(),
1072 "omp_data");
1073
1074 Value *numberOfThreads = Builder.getInt32(0);
1075 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1076 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1077
1078 // Add one as the upper bound provided by openmp is a < comparison
1079 // whereas the codegenForSequential function creates a <= comparison.
1080 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1081 APInt APStride = APInt_from_MPZ(f->stride);
1082 Value *stride = ConstantInt::get(intPtrTy,
1083 APStride.zext(intPtrTy->getBitWidth()));
1084
1085 SmallVector<Value *, 6> Arguments;
1086 Arguments.push_back(SubFunction);
1087 Arguments.push_back(subfunctionParam);
1088 Arguments.push_back(numberOfThreads);
1089 Arguments.push_back(lowerBound);
1090 Arguments.push_back(upperBound);
1091 Arguments.push_back(stride);
1092
1093 Function *parallelStartFunction =
1094 M->getFunction("GOMP_parallel_loop_runtime_start");
Tobias Grosser0679e172011-07-15 22:54:41 +00001095 Builder.CreateCall(parallelStartFunction, Arguments);
Tobias Grosser75805372011-04-29 06:27:02 +00001096
1097 // Create call to the subfunction.
1098 Builder.CreateCall(SubFunction, subfunctionParam);
1099
1100 // Create call for GOMP_parallel_end.
1101 Function *FN = M->getFunction("GOMP_parallel_end");
1102 Builder.CreateCall(FN);
1103 }
1104
1105 bool isInnermostLoop(const clast_for *f) {
1106 const clast_stmt *stmt = f->body;
1107
1108 while (stmt) {
1109 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1110 return false;
1111
1112 stmt = stmt->next;
1113 }
1114
1115 return true;
1116 }
1117
1118 /// @brief Get the number of loop iterations for this loop.
1119 /// @param f The clast for loop to check.
1120 int getNumberOfIterations(const clast_for *f) {
1121 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1122 isl_set *tmp = isl_set_copy(loopDomain);
1123
1124 // Calculate a map similar to the identity map, but with the last input
1125 // and output dimension not related.
1126 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1127 isl_dim *dim = isl_set_get_dim(loopDomain);
1128 dim = isl_dim_drop_outputs(dim, isl_set_n_dim(loopDomain) - 2, 1);
1129 dim = isl_dim_map_from_set(dim);
1130 isl_map *identity = isl_map_identity(dim);
1131 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1132 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1133
1134 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1135 map = isl_map_intersect(map, identity);
1136
1137 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
Tobias Grosserb76f38532011-08-20 11:11:25 +00001138 isl_map *lexmin = isl_map_lexmin(map);
Tobias Grosser75805372011-04-29 06:27:02 +00001139 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1140
1141 isl_set *elements = isl_map_range(sub);
1142
Tobias Grosserc532f122011-08-25 08:40:59 +00001143 if (!isl_set_is_singleton(elements)) {
1144 isl_set_free(elements);
Tobias Grosser75805372011-04-29 06:27:02 +00001145 return -1;
Tobias Grosserc532f122011-08-25 08:40:59 +00001146 }
Tobias Grosser75805372011-04-29 06:27:02 +00001147
1148 isl_point *p = isl_set_sample_point(elements);
1149
1150 isl_int v;
1151 isl_int_init(v);
1152 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1153 int numberIterations = isl_int_get_si(v);
1154 isl_int_clear(v);
Tobias Grosserb76f38532011-08-20 11:11:25 +00001155 isl_point_free(p);
Tobias Grosser75805372011-04-29 06:27:02 +00001156
1157 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1158 }
1159
1160 /// @brief Create vector instructions for this loop.
1161 void codegenForVector(const clast_for *f) {
1162 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1163 int vectorWidth = getNumberOfIterations(f);
1164
1165 Value *LB = ExpGen.codegen(f->LB,
1166 TD->getIntPtrType(Builder.getContext()));
1167
1168 APInt Stride = APInt_from_MPZ(f->stride);
Tobias Grosser55927aa2011-07-18 09:53:32 +00001169 IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
Tobias Grosser75805372011-04-29 06:27:02 +00001170 Stride = Stride.zext(LoopIVType->getBitWidth());
1171 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1172
1173 std::vector<Value*> IVS(vectorWidth);
1174 IVS[0] = LB;
1175
1176 for (int i = 1; i < vectorWidth; i++)
1177 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1178
1179 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1180
1181 // Add loop iv to symbols.
1182 (*clastVars)[f->iterator] = LB;
1183
1184 const clast_stmt *stmt = f->body;
1185
1186 while (stmt) {
1187 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1188 scatteringDomain);
1189 stmt = stmt->next;
1190 }
1191
1192 // Loop is finished, so remove its iv from the live symbols.
1193 clastVars->erase(f->iterator);
1194 }
1195
1196 void codegen(const clast_for *f) {
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001197 if (Vector && isInnermostLoop(f) && DP->isParallelFor(f)
Tobias Grosser75805372011-04-29 06:27:02 +00001198 && (-1 != getNumberOfIterations(f))
1199 && (getNumberOfIterations(f) <= 16)) {
1200 codegenForVector(f);
Hongbin Zhengdbdebe22011-05-03 13:46:58 +00001201 } else if (OpenMP && !parallelCodeGeneration && DP->isParallelFor(f)) {
Tobias Grosser75805372011-04-29 06:27:02 +00001202 parallelCodeGeneration = true;
1203 parallelLoops.push_back(f->iterator);
1204 codegenForOpenMP(f);
1205 parallelCodeGeneration = false;
1206 } else
1207 codegenForSequential(f);
1208 }
1209
1210 Value *codegen(const clast_equation *eq) {
1211 Value *LHS = ExpGen.codegen(eq->LHS,
1212 TD->getIntPtrType(Builder.getContext()));
1213 Value *RHS = ExpGen.codegen(eq->RHS,
1214 TD->getIntPtrType(Builder.getContext()));
1215 CmpInst::Predicate P;
1216
1217 if (eq->sign == 0)
1218 P = ICmpInst::ICMP_EQ;
1219 else if (eq->sign > 0)
1220 P = ICmpInst::ICMP_SGE;
1221 else
1222 P = ICmpInst::ICMP_SLE;
1223
1224 return Builder.CreateICmp(P, LHS, RHS);
1225 }
1226
1227 void codegen(const clast_guard *g) {
1228 Function *F = Builder.GetInsertBlock()->getParent();
1229 LLVMContext &Context = F->getContext();
1230 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1231 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1232 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1233 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1234
1235 Value *Predicate = codegen(&(g->eq[0]));
1236
1237 for (int i = 1; i < g->n; ++i) {
1238 Value *TmpPredicate = codegen(&(g->eq[i]));
1239 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1240 }
1241
1242 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1243 Builder.SetInsertPoint(ThenBB);
1244
1245 codegen(g->then);
1246
1247 Builder.CreateBr(MergeBB);
1248 Builder.SetInsertPoint(MergeBB);
1249 }
1250
1251 void codegen(const clast_stmt *stmt) {
1252 if (CLAST_STMT_IS_A(stmt, stmt_root))
1253 assert(false && "No second root statement expected");
1254 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1255 codegen((const clast_assignment *)stmt);
1256 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1257 codegen((const clast_user_stmt *)stmt);
1258 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1259 codegen((const clast_block *)stmt);
1260 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1261 codegen((const clast_for *)stmt);
1262 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1263 codegen((const clast_guard *)stmt);
1264
1265 if (stmt->next)
1266 codegen(stmt->next);
1267 }
1268
1269 void addParameters(const CloogNames *names) {
Tobias Grosser97fb5ac2011-06-30 19:39:10 +00001270 SCEVExpander Rewriter(SE, "polly");
Tobias Grosser75805372011-04-29 06:27:02 +00001271
1272 // Create an instruction that specifies the location where the parameters
1273 // are expanded.
1274 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1275 Builder.getInt16Ty(), false, "insertInst",
1276 Builder.GetInsertBlock());
1277
1278 int i = 0;
1279 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1280 PI != PE; ++PI) {
1281 assert(i < names->nb_parameters && "Not enough parameter names");
1282
1283 const SCEV *Param = *PI;
Tobias Grosser55927aa2011-07-18 09:53:32 +00001284 Type *Ty = Param->getType();
Tobias Grosser75805372011-04-29 06:27:02 +00001285
1286 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1287 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1288 (*clastVars)[names->parameters[i]] = V;
1289
1290 ++i;
1291 }
1292 }
1293
1294 public:
1295 void codegen(const clast_root *r) {
1296 clastVars = new CharMapT();
1297 addParameters(r->names);
1298 ExpGen.setIVS(clastVars);
1299
1300 parallelCodeGeneration = false;
1301
1302 const clast_stmt *stmt = (const clast_stmt*) r;
1303 if (stmt->next)
1304 codegen(stmt->next);
1305
1306 delete clastVars;
1307 }
1308
1309 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
Hongbin Zheng94c5df12011-05-06 02:38:20 +00001310 ScopDetection *sd, Dependences *dp, TargetData *td,
1311 IRBuilder<> &B) :
1312 S(scop), SE(se), DT(dt), SD(sd), DP(dp), TD(td), Builder(B),
1313 ExpGen(Builder, NULL) {}
Tobias Grosser75805372011-04-29 06:27:02 +00001314
1315};
1316}
1317
1318namespace {
1319class CodeGeneration : public ScopPass {
1320 Region *region;
1321 Scop *S;
1322 DominatorTree *DT;
1323 ScalarEvolution *SE;
1324 ScopDetection *SD;
Tobias Grosser75805372011-04-29 06:27:02 +00001325 TargetData *TD;
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001326 RegionInfo *RI;
Tobias Grosser75805372011-04-29 06:27:02 +00001327
1328 std::vector<std::string> parallelLoops;
1329
1330 public:
1331 static char ID;
1332
1333 CodeGeneration() : ScopPass(ID) {}
1334
Tobias Grosser75805372011-04-29 06:27:02 +00001335 // Adding prototypes required if OpenMP is enabled.
1336 void addOpenMPDefinitions(IRBuilder<> &Builder)
1337 {
1338 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1339 LLVMContext &Context = Builder.getContext();
Tobias Grosser851b96e2011-07-12 12:42:54 +00001340 IntegerType *intPtrTy = TD->getIntPtrType(Context);
Tobias Grosser75805372011-04-29 06:27:02 +00001341
1342 if (!M->getFunction("GOMP_parallel_end")) {
1343 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1344 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1345 }
1346
1347 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1348 // Type of first argument.
Tobias Grosser851b96e2011-07-12 12:42:54 +00001349 std::vector<Type*> Arguments(1, Builder.getInt8PtrTy());
Tobias Grosser75805372011-04-29 06:27:02 +00001350 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1351 false);
1352 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1353
Tobias Grosser851b96e2011-07-12 12:42:54 +00001354 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001355 args.push_back(FnPtrTy);
1356 args.push_back(Builder.getInt8PtrTy());
1357 args.push_back(Builder.getInt32Ty());
1358 args.push_back(intPtrTy);
1359 args.push_back(intPtrTy);
1360 args.push_back(intPtrTy);
1361
1362 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1363 Function::Create(type, Function::ExternalLinkage,
1364 "GOMP_parallel_loop_runtime_start", M);
1365 }
1366
1367 if (!M->getFunction("GOMP_loop_runtime_next")) {
1368 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1369
Tobias Grosser851b96e2011-07-12 12:42:54 +00001370 std::vector<Type*> args;
Tobias Grosser75805372011-04-29 06:27:02 +00001371 args.push_back(intLongPtrTy);
1372 args.push_back(intLongPtrTy);
1373
1374 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1375 Function::Create(type, Function::ExternalLinkage,
1376 "GOMP_loop_runtime_next", M);
1377 }
1378
1379 if (!M->getFunction("GOMP_loop_end_nowait")) {
1380 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
Tobias Grosser851b96e2011-07-12 12:42:54 +00001381 std::vector<Type*>(), false);
Tobias Grosser75805372011-04-29 06:27:02 +00001382 Function::Create(FT, Function::ExternalLinkage,
1383 "GOMP_loop_end_nowait", M);
1384 }
1385 }
1386
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001387 // Split the entry edge of the region and generate a new basic block on this
1388 // edge. This function also updates ScopInfo and RegionInfo.
1389 //
1390 // @param region The region where the entry edge will be splitted.
1391 BasicBlock *splitEdgeAdvanced(Region *region) {
1392 BasicBlock *newBlock;
1393 BasicBlock *splitBlock;
1394
1395 newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1396
1397 if (DT->dominates(region->getEntry(), newBlock)) {
1398 // Update ScopInfo.
1399 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1400 if ((*SI)->getBasicBlock() == newBlock) {
1401 (*SI)->setBasicBlock(newBlock);
1402 break;
1403 }
1404
1405 // Update RegionInfo.
1406 splitBlock = region->getEntry();
1407 region->replaceEntry(newBlock);
Tobias Grosser7a16c892011-05-14 19:01:55 +00001408 RI->setRegionFor(newBlock, region);
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001409 } else {
1410 RI->setRegionFor(newBlock, region->getParent());
1411 splitBlock = newBlock;
1412 }
1413
1414 return splitBlock;
1415 }
1416
1417 // Create a split block that branches either to the old code or to a new basic
1418 // block where the new code can be inserted.
1419 //
1420 // @param builder A builder that will be set to point to a basic block, where
1421 // the new code can be generated.
1422 // @return The split basic block.
1423 BasicBlock *addSplitAndStartBlock(IRBuilder<> *builder) {
1424 BasicBlock *splitBlock = splitEdgeAdvanced(region);
1425
1426 splitBlock->setName("polly.enterScop");
1427
1428 Function *function = splitBlock->getParent();
1429 BasicBlock *startBlock = BasicBlock::Create(function->getContext(),
1430 "polly.start", function);
1431 splitBlock->getTerminator()->eraseFromParent();
1432 builder->SetInsertPoint(splitBlock);
1433 builder->CreateCondBr(builder->getTrue(), startBlock, region->getEntry());
1434 DT->addNewBlock(startBlock, splitBlock);
1435
1436 // Start code generation here.
1437 builder->SetInsertPoint(startBlock);
1438 return splitBlock;
1439 }
1440
1441 // Merge the control flow of the newly generated code with the existing code.
1442 //
1443 // @param splitBlock The basic block where the control flow was split between
1444 // old and new version of the Scop.
1445 // @param builder An IRBuilder that points to the last instruction of the
1446 // newly generated code.
1447 void mergeControlFlow(BasicBlock *splitBlock, IRBuilder<> *builder) {
1448 BasicBlock *mergeBlock;
1449 Region *R = region;
1450
1451 if (R->getExit()->getSinglePredecessor())
1452 // No splitEdge required. A block with a single predecessor cannot have
1453 // PHI nodes that would complicate life.
1454 mergeBlock = R->getExit();
1455 else {
1456 mergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1457 // SplitEdge will never split R->getExit(), as R->getExit() has more than
1458 // one predecessor. Hence, mergeBlock is always a newly generated block.
1459 mergeBlock->setName("polly.finalMerge");
1460 R->replaceExit(mergeBlock);
1461 }
1462
1463 builder->CreateBr(mergeBlock);
1464
1465 if (DT->dominates(splitBlock, mergeBlock))
1466 DT->changeImmediateDominator(mergeBlock, splitBlock);
1467 }
1468
Tobias Grosser75805372011-04-29 06:27:02 +00001469 bool runOnScop(Scop &scop) {
1470 S = &scop;
1471 region = &S->getRegion();
Tobias Grosser75805372011-04-29 06:27:02 +00001472 DT = &getAnalysis<DominatorTree>();
1473 Dependences *DP = &getAnalysis<Dependences>();
1474 SE = &getAnalysis<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001475 SD = &getAnalysis<ScopDetection>();
1476 TD = &getAnalysis<TargetData>();
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001477 RI = &getAnalysis<RegionInfo>();
Tobias Grosser75805372011-04-29 06:27:02 +00001478
1479 parallelLoops.clear();
1480
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001481 assert(region->isSimple() && "Only simple regions are supported");
Tobias Grosser76d7c522011-05-14 19:01:37 +00001482
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001483 // In the CFG and we generate next to original code of the Scop the
1484 // optimized version. Both the new and the original version of the code
1485 // remain in the CFG. A branch statement decides which version is executed.
1486 // At the moment, we always execute the newly generated version (the old one
1487 // is dead code eliminated by the cleanup passes). Later we may decide to
1488 // execute the new version only under certain conditions. This will be the
1489 // case if we support constructs for which we cannot prove all assumptions
1490 // at compile time.
1491 //
1492 // Before transformation:
1493 //
1494 // bb0
1495 // |
1496 // orig_scop
1497 // |
1498 // bb1
1499 //
1500 // After transformation:
1501 // bb0
1502 // |
1503 // polly.splitBlock
Tobias Grosser2bd3af12011-08-01 22:39:00 +00001504 // / \.
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001505 // | startBlock
1506 // | |
1507 // orig_scop new_scop
1508 // \ /
1509 // \ /
1510 // bb1 (joinBlock)
1511 IRBuilder<> builder(region->getEntry());
Tobias Grosser75805372011-04-29 06:27:02 +00001512
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001513 // The builder will be set to startBlock.
1514 BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001515
1516 if (OpenMP)
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001517 addOpenMPDefinitions(builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001518
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001519 ClastStmtCodeGen CodeGen(S, *SE, DT, SD, DP, TD, builder);
Tobias Grosser3fdecae2011-05-14 19:02:39 +00001520 CloogInfo &C = getAnalysis<CloogInfo>();
1521 CodeGen.codegen(C.getClast());
Tobias Grosser75805372011-04-29 06:27:02 +00001522
Tobias Grosser75805372011-04-29 06:27:02 +00001523 parallelLoops.insert(parallelLoops.begin(),
1524 CodeGen.getParallelLoops().begin(),
1525 CodeGen.getParallelLoops().end());
1526
Tobias Grosser8c4cfc322011-05-14 19:01:49 +00001527 mergeControlFlow(splitBlock, &builder);
Tobias Grosser75805372011-04-29 06:27:02 +00001528
Tobias Grosserabb6dcd2011-05-14 19:02:34 +00001529 return true;
Tobias Grosser75805372011-04-29 06:27:02 +00001530 }
1531
1532 virtual void printScop(raw_ostream &OS) const {
1533 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1534 PE = parallelLoops.end(); PI != PE; ++PI)
1535 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1536 }
1537
1538 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1539 AU.addRequired<CloogInfo>();
1540 AU.addRequired<Dependences>();
1541 AU.addRequired<DominatorTree>();
1542 AU.addRequired<ScalarEvolution>();
Tobias Grosser75805372011-04-29 06:27:02 +00001543 AU.addRequired<RegionInfo>();
1544 AU.addRequired<ScopDetection>();
1545 AU.addRequired<ScopInfo>();
1546 AU.addRequired<TargetData>();
1547
1548 AU.addPreserved<CloogInfo>();
1549 AU.addPreserved<Dependences>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001550
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001551 // FIXME: We do not create LoopInfo for the newly generated loops.
Tobias Grosser75805372011-04-29 06:27:02 +00001552 AU.addPreserved<LoopInfo>();
1553 AU.addPreserved<DominatorTree>();
Tobias Grosser75805372011-04-29 06:27:02 +00001554 AU.addPreserved<ScopDetection>();
1555 AU.addPreserved<ScalarEvolution>();
Tobias Grosser5d6eb862011-05-14 19:02:45 +00001556
Tobias Grosser4e3f9a42011-05-23 15:23:36 +00001557 // FIXME: We do not yet add regions for the newly generated code to the
1558 // region tree.
Tobias Grosser75805372011-04-29 06:27:02 +00001559 AU.addPreserved<RegionInfo>();
1560 AU.addPreserved<TempScopInfo>();
1561 AU.addPreserved<ScopInfo>();
1562 AU.addPreservedID(IndependentBlocksID);
1563 }
1564};
1565}
1566
1567char CodeGeneration::ID = 1;
1568
1569static RegisterPass<CodeGeneration>
1570Z("polly-codegen", "Polly - Create LLVM-IR from the polyhedral information");
1571
1572Pass* polly::createCodeGenerationPass() {
1573 return new CodeGeneration();
1574}