blob: c4e524fb4b9adbcd1730e350075b35496f2f3d5f [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"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Module.h"
39#include "llvm/ADT/SetVector.h"
40
41#define CLOOG_INT_GMP 1
42#include "cloog/cloog.h"
43#include "cloog/isl/cloog.h"
44
45#include <vector>
46#include <utility>
47
48using namespace polly;
49using namespace llvm;
50
51struct isl_set;
52
53namespace polly {
54
55static cl::opt<bool>
56Vector("enable-polly-vector",
57 cl::desc("Enable polly vector code generation"), cl::Hidden,
58 cl::value_desc("Vector code generation enabled if true"),
59 cl::init(false));
60
61static cl::opt<bool>
62OpenMP("enable-polly-openmp",
63 cl::desc("Generate OpenMP parallel code"), cl::Hidden,
64 cl::value_desc("OpenMP code generation enabled if true"),
65 cl::init(false));
66
67static cl::opt<bool>
68AtLeastOnce("enable-polly-atLeastOnce",
69 cl::desc("Give polly the hint, that every loop is executed at least"
70 "once"), cl::Hidden,
71 cl::value_desc("OpenMP code generation enabled if true"),
72 cl::init(false));
73
74static cl::opt<bool>
75Aligned("enable-polly-aligned",
76 cl::desc("Assumed aligned memory accesses."), cl::Hidden,
77 cl::value_desc("OpenMP code generation enabled if true"),
78 cl::init(false));
79
80static cl::opt<std::string>
81CodegenOnly("polly-codegen-only",
82 cl::desc("Codegen only this function"), cl::Hidden,
83 cl::value_desc("The function name to codegen"),
84 cl::ValueRequired, cl::init(""));
85
86typedef DenseMap<const Value*, Value*> ValueMapT;
87typedef DenseMap<const char*, Value*> CharMapT;
88typedef std::vector<ValueMapT> VectorValueMapT;
89
90// Create a new loop.
91//
92// @param Builder The builder used to create the loop. It also defines the
93// place where to create the loop.
94// @param UB The upper bound of the loop iv.
95// @param Stride The number by which the loop iv is incremented after every
96// iteration.
97static void createLoop(IRBuilder<> *Builder, Value *LB, Value *UB, APInt Stride,
98 PHINode*& IV, BasicBlock*& AfterBB, Value*& IncrementedIV,
99 DominatorTree *DT) {
100 Function *F = Builder->GetInsertBlock()->getParent();
101 LLVMContext &Context = F->getContext();
102
103 BasicBlock *PreheaderBB = Builder->GetInsertBlock();
104 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
105 BasicBlock *BodyBB = BasicBlock::Create(Context, "polly.loop_body", F);
106 AfterBB = BasicBlock::Create(Context, "polly.after_loop", F);
107
108 Builder->CreateBr(HeaderBB);
109 DT->addNewBlock(HeaderBB, PreheaderBB);
110
111 Builder->SetInsertPoint(BodyBB);
112
113 Builder->SetInsertPoint(HeaderBB);
114
115 // Use the type of upper and lower bound.
116 assert(LB->getType() == UB->getType()
117 && "Different types for upper and lower bound.");
118
119 const IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
120 assert(LoopIVType && "UB is not integer?");
121
122 // IV
123 IV = Builder->CreatePHI(LoopIVType, 2, "polly.loopiv");
124 IV->addIncoming(LB, PreheaderBB);
125
126 // IV increment.
127 Value *StrideValue = ConstantInt::get(LoopIVType,
128 Stride.zext(LoopIVType->getBitWidth()));
129 IncrementedIV = Builder->CreateAdd(IV, StrideValue, "polly.next_loopiv");
130
131 // Exit condition.
132 if (AtLeastOnce) { // At least on iteration.
133 UB = Builder->CreateAdd(UB, Builder->getInt64(1));
134 Value *CMP = Builder->CreateICmpEQ(IV, UB);
135 Builder->CreateCondBr(CMP, AfterBB, BodyBB);
136 } else { // Maybe not executed at all.
137 Value *CMP = Builder->CreateICmpSLE(IV, UB);
138 Builder->CreateCondBr(CMP, BodyBB, AfterBB);
139 }
140 DT->addNewBlock(BodyBB, HeaderBB);
141 DT->addNewBlock(AfterBB, HeaderBB);
142
143 Builder->SetInsertPoint(BodyBB);
144}
145
146class BlockGenerator {
147 IRBuilder<> &Builder;
148 ValueMapT &VMap;
149 VectorValueMapT &ValueMaps;
150 Scop &S;
151 ScopStmt &statement;
152 isl_set *scatteringDomain;
153
154public:
155 BlockGenerator(IRBuilder<> &B, ValueMapT &vmap, VectorValueMapT &vmaps,
156 ScopStmt &Stmt, isl_set *domain)
157 : Builder(B), VMap(vmap), ValueMaps(vmaps), S(*Stmt.getParent()),
158 statement(Stmt), scatteringDomain(domain) {}
159
160 const Region &getRegion() {
161 return S.getRegion();
162 }
163
164 Value* makeVectorOperand(Value *operand, int vectorWidth) {
165 if (operand->getType()->isVectorTy())
166 return operand;
167
168 VectorType *vectorType = VectorType::get(operand->getType(), vectorWidth);
169 Value *vector = UndefValue::get(vectorType);
170 vector = Builder.CreateInsertElement(vector, operand, Builder.getInt32(0));
171
172 std::vector<Constant*> splat;
173
174 for (int i = 0; i < vectorWidth; i++)
175 splat.push_back (Builder.getInt32(0));
176
177 Constant *splatVector = ConstantVector::get(splat);
178
179 return Builder.CreateShuffleVector(vector, vector, splatVector);
180 }
181
182 Value* getOperand(const Value *OldOperand, ValueMapT &BBMap,
183 ValueMapT *VectorMap = 0) {
184 const Instruction *OpInst = dyn_cast<Instruction>(OldOperand);
185
186 if (!OpInst)
187 return const_cast<Value*>(OldOperand);
188
189 if (VectorMap && VectorMap->count(OldOperand))
190 return (*VectorMap)[OldOperand];
191
192 // IVS and Parameters.
193 if (VMap.count(OldOperand)) {
194 Value *NewOperand = VMap[OldOperand];
195
196 // Insert a cast if types are different
197 if (OldOperand->getType()->getScalarSizeInBits()
198 < NewOperand->getType()->getScalarSizeInBits())
199 NewOperand = Builder.CreateTruncOrBitCast(NewOperand,
200 OldOperand->getType());
201
202 return NewOperand;
203 }
204
205 // Instructions calculated in the current BB.
206 if (BBMap.count(OldOperand)) {
207 return BBMap[OldOperand];
208 }
209
210 // Ignore instructions that are referencing ops in the old BB. These
211 // instructions are unused. They where replace by new ones during
212 // createIndependentBlocks().
213 if (getRegion().contains(OpInst->getParent()))
214 return NULL;
215
216 return const_cast<Value*>(OldOperand);
217 }
218
219 const Type *getVectorPtrTy(const Value *V, int vectorWidth) {
220 const PointerType *pointerType = dyn_cast<PointerType>(V->getType());
221 assert(pointerType && "PointerType expected");
222
223 const Type *scalarType = pointerType->getElementType();
224 VectorType *vectorType = VectorType::get(scalarType, vectorWidth);
225
226 return PointerType::getUnqual(vectorType);
227 }
228
229 /// @brief Load a vector from a set of adjacent scalars
230 ///
231 /// In case a set of scalars is known to be next to each other in memory,
232 /// create a vector load that loads those scalars
233 ///
234 /// %vector_ptr= bitcast double* %p to <4 x double>*
235 /// %vec_full = load <4 x double>* %vector_ptr
236 ///
237 Value *generateStrideOneLoad(const LoadInst *load, ValueMapT &BBMap,
238 int size) {
239 const Value *pointer = load->getPointerOperand();
240 const Type *vectorPtrType = getVectorPtrTy(pointer, size);
241 Value *newPointer = getOperand(pointer, BBMap);
242 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
243 "vector_ptr");
244 LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
245 load->getNameStr()
246 + "_p_vec_full");
247 if (!Aligned)
248 VecLoad->setAlignment(8);
249
250 return VecLoad;
251 }
252
253 /// @brief Load a vector initialized from a single scalar in memory
254 ///
255 /// In case all elements of a vector are initialized to the same
256 /// scalar value, this value is loaded and shuffeled into all elements
257 /// of the vector.
258 ///
259 /// %splat_one = load <1 x double>* %p
260 /// %splat = shufflevector <1 x double> %splat_one, <1 x
261 /// double> %splat_one, <4 x i32> zeroinitializer
262 ///
263 Value *generateStrideZeroLoad(const LoadInst *load, ValueMapT &BBMap,
264 int size) {
265 const Value *pointer = load->getPointerOperand();
266 const Type *vectorPtrType = getVectorPtrTy(pointer, 1);
267 Value *newPointer = getOperand(pointer, BBMap);
268 Value *vectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
269 load->getNameStr() + "_p_vec_p");
270 LoadInst *scalarLoad= Builder.CreateLoad(vectorPtr,
271 load->getNameStr() + "_p_splat_one");
272
273 if (!Aligned)
274 scalarLoad->setAlignment(8);
275
276 std::vector<Constant*> splat;
277
278 for (int i = 0; i < size; i++)
279 splat.push_back (Builder.getInt32(0));
280
281 Constant *splatVector = ConstantVector::get(splat);
282
283 Value *vectorLoad = Builder.CreateShuffleVector(scalarLoad, scalarLoad,
284 splatVector,
285 load->getNameStr()
286 + "_p_splat");
287 return vectorLoad;
288 }
289
290 /// @Load a vector from scalars distributed in memory
291 ///
292 /// In case some scalars a distributed randomly in memory. Create a vector
293 /// by loading each scalar and by inserting one after the other into the
294 /// vector.
295 ///
296 /// %scalar_1= load double* %p_1
297 /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
298 /// %scalar 2 = load double* %p_2
299 /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
300 ///
301 Value *generateUnknownStrideLoad(const LoadInst *load,
302 VectorValueMapT &scalarMaps,
303 int size) {
304 const Value *pointer = load->getPointerOperand();
305 VectorType *vectorType = VectorType::get(
306 dyn_cast<PointerType>(pointer->getType())->getElementType(), size);
307
308 Value *vector = UndefValue::get(vectorType);
309
310 for (int i = 0; i < size; i++) {
311 Value *newPointer = getOperand(pointer, scalarMaps[i]);
312 Value *scalarLoad = Builder.CreateLoad(newPointer,
313 load->getNameStr() + "_p_scalar_");
314 vector = Builder.CreateInsertElement(vector, scalarLoad,
315 Builder.getInt32(i),
316 load->getNameStr() + "_p_vec_");
317 }
318
319 return vector;
320 }
321
322 Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap) {
323 const Value *pointer = load->getPointerOperand();
324 Value *newPointer = getOperand(pointer, BBMap);
325 Value *scalarLoad = Builder.CreateLoad(newPointer,
326 load->getNameStr() + "_p_scalar_");
327 return scalarLoad;
328 }
329
330 /// @brief Load a value (or several values as a vector) from memory.
331 void generateLoad(const LoadInst *load, ValueMapT &vectorMap,
332 VectorValueMapT &scalarMaps, int vectorWidth) {
333
334 if (scalarMaps.size() == 1) {
335 scalarMaps[0][load] = generateScalarLoad(load, scalarMaps[0]);
336 return;
337 }
338
339 Value *newLoad;
340
341 MemoryAccess &Access = statement.getAccessFor(load);
342
343 assert(scatteringDomain && "No scattering domain available");
344
345 if (Access.isStrideZero(scatteringDomain))
346 newLoad = generateStrideZeroLoad(load, scalarMaps[0], vectorWidth);
347 else if (Access.isStrideOne(scatteringDomain))
348 newLoad = generateStrideOneLoad(load, scalarMaps[0], vectorWidth);
349 else
350 newLoad = generateUnknownStrideLoad(load, scalarMaps, vectorWidth);
351
352 vectorMap[load] = newLoad;
353 }
354
355 void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
356 ValueMapT &vectorMap, VectorValueMapT &scalarMaps,
357 int vectorDimension, int vectorWidth) {
358 // If this instruction is already in the vectorMap, a vector instruction
359 // was already issued, that calculates the values of all dimensions. No
360 // need to create any more instructions.
361 if (vectorMap.count(Inst))
362 return;
363
364 // Terminator instructions control the control flow. They are explicitally
365 // expressed in the clast and do not need to be copied.
366 if (Inst->isTerminator())
367 return;
368
369 if (const LoadInst *load = dyn_cast<LoadInst>(Inst)) {
370 generateLoad(load, vectorMap, scalarMaps, vectorWidth);
371 return;
372 }
373
374 if (const BinaryOperator *binaryInst = dyn_cast<BinaryOperator>(Inst)) {
375 Value *opZero = Inst->getOperand(0);
376 Value *opOne = Inst->getOperand(1);
377
378 // This is an old instruction that can be ignored.
379 if (!opZero && !opOne)
380 return;
381
382 bool isVectorOp = vectorMap.count(opZero) || vectorMap.count(opOne);
383
384 if (isVectorOp && vectorDimension > 0)
385 return;
386
387 Value *newOpZero, *newOpOne;
388 newOpZero = getOperand(opZero, BBMap, &vectorMap);
389 newOpOne = getOperand(opOne, BBMap, &vectorMap);
390
391
392 std::string name;
393 if (isVectorOp) {
394 newOpZero = makeVectorOperand(newOpZero, vectorWidth);
395 newOpOne = makeVectorOperand(newOpOne, vectorWidth);
396 name = Inst->getNameStr() + "p_vec";
397 } else
398 name = Inst->getNameStr() + "p_sca";
399
400 Value *newInst = Builder.CreateBinOp(binaryInst->getOpcode(), newOpZero,
401 newOpOne, name);
402 if (isVectorOp)
403 vectorMap[Inst] = newInst;
404 else
405 BBMap[Inst] = newInst;
406
407 return;
408 }
409
410 if (const StoreInst *store = dyn_cast<StoreInst>(Inst)) {
411 if (vectorMap.count(store->getValueOperand()) > 0) {
412
413 // We only need to generate one store if we are in vector mode.
414 if (vectorDimension > 0)
415 return;
416
417 MemoryAccess &Access = statement.getAccessFor(store);
418
419 assert(scatteringDomain && "No scattering domain available");
420
421 const Value *pointer = store->getPointerOperand();
422 Value *vector = getOperand(store->getValueOperand(), BBMap, &vectorMap);
423
424 if (Access.isStrideOne(scatteringDomain)) {
425 const Type *vectorPtrType = getVectorPtrTy(pointer, vectorWidth);
426 Value *newPointer = getOperand(pointer, BBMap, &vectorMap);
427
428 Value *VectorPtr = Builder.CreateBitCast(newPointer, vectorPtrType,
429 "vector_ptr");
430 StoreInst *Store = Builder.CreateStore(vector, VectorPtr);
431
432 if (!Aligned)
433 Store->setAlignment(8);
434 } else {
435 for (unsigned i = 0; i < scalarMaps.size(); i++) {
436 Value *scalar = Builder.CreateExtractElement(vector,
437 Builder.getInt32(i));
438 Value *newPointer = getOperand(pointer, scalarMaps[i]);
439 Builder.CreateStore(scalar, newPointer);
440 }
441 }
442
443 return;
444 }
445 }
446
447 Instruction *NewInst = Inst->clone();
448
449 // Copy the operands in temporary vector, as an in place update
450 // fails if an instruction is referencing the same operand twice.
451 std::vector<Value*> Operands(NewInst->op_begin(), NewInst->op_end());
452
453 // Replace old operands with the new ones.
454 for (std::vector<Value*>::iterator UI = Operands.begin(),
455 UE = Operands.end(); UI != UE; ++UI) {
456 Value *newOperand = getOperand(*UI, BBMap);
457
458 if (!newOperand) {
459 assert(!isa<StoreInst>(NewInst)
460 && "Store instructions are always needed!");
461 delete NewInst;
462 return;
463 }
464
465 NewInst->replaceUsesOfWith(*UI, newOperand);
466 }
467
468 Builder.Insert(NewInst);
469 BBMap[Inst] = NewInst;
470
471 if (!NewInst->getType()->isVoidTy())
472 NewInst->setName("p_" + Inst->getName());
473 }
474
475 int getVectorSize() {
476 return ValueMaps.size();
477 }
478
479 bool isVectorBlock() {
480 return getVectorSize() > 1;
481 }
482
483 // Insert a copy of a basic block in the newly generated code.
484 //
485 // @param Builder The builder used to insert the code. It also specifies
486 // where to insert the code.
487 // @param BB The basic block to copy
488 // @param VMap A map returning for any old value its new equivalent. This
489 // is used to update the operands of the statements.
490 // For new statements a relation old->new is inserted in this
491 // map.
492 void copyBB(BasicBlock *BB, DominatorTree *DT) {
493 Function *F = Builder.GetInsertBlock()->getParent();
494 LLVMContext &Context = F->getContext();
495 BasicBlock *CopyBB = BasicBlock::Create(Context,
496 "polly.stmt_" + BB->getNameStr(),
497 F);
498 Builder.CreateBr(CopyBB);
499 DT->addNewBlock(CopyBB, Builder.GetInsertBlock());
500 Builder.SetInsertPoint(CopyBB);
501
502 // Create two maps that store the mapping from the original instructions of
503 // the old basic block to their copies in the new basic block. Those maps
504 // are basic block local.
505 //
506 // As vector code generation is supported there is one map for scalar values
507 // and one for vector values.
508 //
509 // In case we just do scalar code generation, the vectorMap is not used and
510 // the scalarMap has just one dimension, which contains the mapping.
511 //
512 // In case vector code generation is done, an instruction may either appear
513 // in the vector map once (as it is calculating >vectorwidth< values at a
514 // time. Or (if the values are calculated using scalar operations), it
515 // appears once in every dimension of the scalarMap.
516 VectorValueMapT scalarBlockMap(getVectorSize());
517 ValueMapT vectorBlockMap;
518
519 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
520 II != IE; ++II)
521 for (int i = 0; i < getVectorSize(); i++) {
522 if (isVectorBlock())
523 VMap = ValueMaps[i];
524
525 copyInstruction(II, scalarBlockMap[i], vectorBlockMap,
526 scalarBlockMap, i, getVectorSize());
527 }
528 }
529};
530
531/// Class to generate LLVM-IR that calculates the value of a clast_expr.
532class ClastExpCodeGen {
533 IRBuilder<> &Builder;
534 const CharMapT *IVS;
535
536 Value *codegen(const clast_name *e, const Type *Ty) {
537 CharMapT::const_iterator I = IVS->find(e->name);
538
539 if (I != IVS->end())
540 return Builder.CreateSExtOrBitCast(I->second, Ty);
541 else
542 llvm_unreachable("Clast name not found");
543 }
544
545 Value *codegen(const clast_term *e, const Type *Ty) {
546 APInt a = APInt_from_MPZ(e->val);
547
548 Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
549 ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
550
551 if (e->var) {
552 Value *var = codegen(e->var, Ty);
553 return Builder.CreateMul(ConstOne, var);
554 }
555
556 return ConstOne;
557 }
558
559 Value *codegen(const clast_binary *e, const Type *Ty) {
560 Value *LHS = codegen(e->LHS, Ty);
561
562 APInt RHS_AP = APInt_from_MPZ(e->RHS);
563
564 Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
565 RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
566
567 switch (e->type) {
568 case clast_bin_mod:
569 return Builder.CreateSRem(LHS, RHS);
570 case clast_bin_fdiv:
571 {
572 // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
573 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
574 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
575 One = Builder.CreateZExtOrBitCast(One, Ty);
576 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
577 Value *Sum1 = Builder.CreateSub(LHS, RHS);
578 Value *Sum2 = Builder.CreateAdd(Sum1, One);
579 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
580 Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
581 return Builder.CreateSDiv(Dividend, RHS);
582 }
583 case clast_bin_cdiv:
584 {
585 // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
586 Value *One = ConstantInt::get(Builder.getInt1Ty(), 1);
587 Value *Zero = ConstantInt::get(Builder.getInt1Ty(), 0);
588 One = Builder.CreateZExtOrBitCast(One, Ty);
589 Zero = Builder.CreateZExtOrBitCast(Zero, Ty);
590 Value *Sum1 = Builder.CreateAdd(LHS, RHS);
591 Value *Sum2 = Builder.CreateSub(Sum1, One);
592 Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
593 Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
594 return Builder.CreateSDiv(Dividend, RHS);
595 }
596 case clast_bin_div:
597 return Builder.CreateSDiv(LHS, RHS);
598 default:
599 llvm_unreachable("Unknown clast binary expression type");
600 };
601 }
602
603 Value *codegen(const clast_reduction *r, const Type *Ty) {
604 assert(( r->type == clast_red_min
605 || r->type == clast_red_max
606 || r->type == clast_red_sum)
607 && "Clast reduction type not supported");
608 Value *old = codegen(r->elts[0], Ty);
609
610 for (int i=1; i < r->n; ++i) {
611 Value *exprValue = codegen(r->elts[i], Ty);
612
613 switch (r->type) {
614 case clast_red_min:
615 {
616 Value *cmp = Builder.CreateICmpSLT(old, exprValue);
617 old = Builder.CreateSelect(cmp, old, exprValue);
618 break;
619 }
620 case clast_red_max:
621 {
622 Value *cmp = Builder.CreateICmpSGT(old, exprValue);
623 old = Builder.CreateSelect(cmp, old, exprValue);
624 break;
625 }
626 case clast_red_sum:
627 old = Builder.CreateAdd(old, exprValue);
628 break;
629 default:
630 llvm_unreachable("Clast unknown reduction type");
631 }
632 }
633
634 return old;
635 }
636
637public:
638
639 // A generator for clast expressions.
640 //
641 // @param B The IRBuilder that defines where the code to calculate the
642 // clast expressions should be inserted.
643 // @param IVMAP A Map that translates strings describing the induction
644 // variables to the Values* that represent these variables
645 // on the LLVM side.
646 ClastExpCodeGen(IRBuilder<> &B, CharMapT *IVMap) : Builder(B), IVS(IVMap) {}
647
648 // Generates code to calculate a given clast expression.
649 //
650 // @param e The expression to calculate.
651 // @return The Value that holds the result.
652 Value *codegen(const clast_expr *e, const Type *Ty) {
653 switch(e->type) {
654 case clast_expr_name:
655 return codegen((const clast_name *)e, Ty);
656 case clast_expr_term:
657 return codegen((const clast_term *)e, Ty);
658 case clast_expr_bin:
659 return codegen((const clast_binary *)e, Ty);
660 case clast_expr_red:
661 return codegen((const clast_reduction *)e, Ty);
662 default:
663 llvm_unreachable("Unknown clast expression!");
664 }
665 }
666
667 // @brief Reset the CharMap.
668 //
669 // This function is called to reset the CharMap to new one, while generating
670 // OpenMP code.
671 void setIVS(CharMapT *IVSNew) {
672 IVS = IVSNew;
673 }
674
675};
676
677class ClastStmtCodeGen {
678 // The Scop we code generate.
679 Scop *S;
680 ScalarEvolution &SE;
681
682 DominatorTree *DT;
683 Dependences *DP;
684 TargetData *TD;
685
686 // The Builder specifies the current location to code generate at.
687 IRBuilder<> &Builder;
688
689 // Map the Values from the old code to their counterparts in the new code.
690 ValueMapT ValueMap;
691
692 // clastVars maps from the textual representation of a clast variable to its
693 // current *Value. clast variables are scheduling variables, original
694 // induction variables or parameters. They are used either in loop bounds or
695 // to define the statement instance that is executed.
696 //
697 // for (s = 0; s < n + 3; ++i)
698 // for (t = s; t < m; ++j)
699 // Stmt(i = s + 3 * m, j = t);
700 //
701 // {s,t,i,j,n,m} is the set of clast variables in this clast.
702 CharMapT *clastVars;
703
704 // Codegenerator for clast expressions.
705 ClastExpCodeGen ExpGen;
706
707 // Do we currently generate parallel code?
708 bool parallelCodeGeneration;
709
710 std::vector<std::string> parallelLoops;
711
712public:
713
714 const std::vector<std::string> &getParallelLoops() {
715 return parallelLoops;
716 }
717
718 protected:
719 void codegen(const clast_assignment *a) {
720 (*clastVars)[a->LHS] = ExpGen.codegen(a->RHS,
721 TD->getIntPtrType(Builder.getContext()));
722 }
723
724 void codegen(const clast_assignment *a, ScopStmt *Statement,
725 unsigned Dimension, int vectorDim,
726 std::vector<ValueMapT> *VectorVMap = 0) {
727 Value *RHS = ExpGen.codegen(a->RHS,
728 TD->getIntPtrType(Builder.getContext()));
729
730 assert(!a->LHS && "Statement assignments do not have left hand side");
731 const PHINode *PN;
732 PN = Statement->getInductionVariableForDimension(Dimension);
733 const Value *V = PN;
734
735 if (PN->getNumOperands() == 2)
736 V = *(PN->use_begin());
737
738 if (VectorVMap)
739 (*VectorVMap)[vectorDim][V] = RHS;
740
741 ValueMap[V] = RHS;
742 }
743
744 void codegenSubstitutions(const clast_stmt *Assignment,
745 ScopStmt *Statement, int vectorDim = 0,
746 std::vector<ValueMapT> *VectorVMap = 0) {
747 int Dimension = 0;
748
749 while (Assignment) {
750 assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
751 && "Substitions are expected to be assignments");
752 codegen((const clast_assignment *)Assignment, Statement, Dimension,
753 vectorDim, VectorVMap);
754 Assignment = Assignment->next;
755 Dimension++;
756 }
757 }
758
759 void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
760 const char *iterator = NULL, isl_set *scatteringDomain = 0) {
761 ScopStmt *Statement = (ScopStmt *)u->statement->usr;
762 BasicBlock *BB = Statement->getBasicBlock();
763
764 if (u->substitutions)
765 codegenSubstitutions(u->substitutions, Statement);
766
767 int vectorDimensions = IVS ? IVS->size() : 1;
768
769 VectorValueMapT VectorValueMap(vectorDimensions);
770
771 if (IVS) {
772 assert (u->substitutions && "Substitutions expected!");
773 int i = 0;
774 for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
775 II != IE; ++II) {
776 (*clastVars)[iterator] = *II;
777 codegenSubstitutions(u->substitutions, Statement, i, &VectorValueMap);
778 i++;
779 }
780 }
781
782 BlockGenerator Generator(Builder, ValueMap, VectorValueMap, *Statement,
783 scatteringDomain);
784 Generator.copyBB(BB, DT);
785 }
786
787 void codegen(const clast_block *b) {
788 if (b->body)
789 codegen(b->body);
790 }
791
792 /// @brief Create a classical sequential loop.
793 void codegenForSequential(const clast_for *f, Value *lowerBound = 0,
794 Value *upperBound = 0) {
795 APInt Stride = APInt_from_MPZ(f->stride);
796 PHINode *IV;
797 Value *IncrementedIV;
798 BasicBlock *AfterBB;
799 // The value of lowerbound and upperbound will be supplied, if this
800 // function is called while generating OpenMP code. Otherwise get
801 // the values.
802 assert(((lowerBound && upperBound) || (!lowerBound && !upperBound))
803 && "Either give both bounds or none");
804 if (lowerBound == 0 || upperBound == 0) {
805 lowerBound = ExpGen.codegen(f->LB,
806 TD->getIntPtrType(Builder.getContext()));
807 upperBound = ExpGen.codegen(f->UB,
808 TD->getIntPtrType(Builder.getContext()));
809 }
810 createLoop(&Builder, lowerBound, upperBound, Stride, IV, AfterBB,
811 IncrementedIV, DT);
812
813 // Add loop iv to symbols.
814 (*clastVars)[f->iterator] = IV;
815
816 if (f->body)
817 codegen(f->body);
818
819 // Loop is finished, so remove its iv from the live symbols.
820 clastVars->erase(f->iterator);
821
822 BasicBlock *HeaderBB = *pred_begin(AfterBB);
823 BasicBlock *LastBodyBB = Builder.GetInsertBlock();
824 Builder.CreateBr(HeaderBB);
825 IV->addIncoming(IncrementedIV, LastBodyBB);
826 Builder.SetInsertPoint(AfterBB);
827 }
828
829 /// @brief Check if a loop is parallel
830 ///
831 /// Detect if a clast_for loop can be executed in parallel.
832 ///
833 /// @param f The clast for loop to check.
834 bool isParallelFor(const clast_for *f) {
835 isl_set *loopDomain = isl_set_from_cloog_domain(f->domain);
836 assert(loopDomain && "Cannot access domain of loop");
837
838 bool isParallel = DP->isParallelDimension(loopDomain,
839 isl_set_n_dim(loopDomain));
840
841 if (isParallel)
842 DEBUG(dbgs() << "Parallel loop with induction variable '" << f->iterator
843 << "' found\n";);
844
845 return isParallel;
846 }
847
848 /// @brief Add a new definition of an openmp subfunction.
849 Function* addOpenMPSubfunction(Module *M) {
850 Function *F = Builder.GetInsertBlock()->getParent();
851 const std::string &Name = F->getNameStr() + ".omp_subfn";
852
853 std::vector<const Type*> Arguments(1, Builder.getInt8PtrTy());
854 FunctionType *FT = FunctionType::get(Builder.getVoidTy(), Arguments, false);
855 Function *FN = Function::Create(FT, Function::InternalLinkage, Name, M);
856
857 Function::arg_iterator AI = FN->arg_begin();
858 AI->setName("omp.userContext");
859
860 return FN;
861 }
862
863 /// @brief Add values to the OpenMP structure.
864 ///
865 /// Create the subfunction structure and add the values from the list.
866 Value *addValuesToOpenMPStruct(SetVector<Value*> OMPDataVals,
867 Function *SubFunction) {
868 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
869 std::vector<const Type*> structMembers;
870
871 // Create the structure.
872 for (unsigned i = 0; i < OMPDataVals.size(); i++)
873 structMembers.push_back(OMPDataVals[i]->getType());
874
875 const std::string &Name = SubFunction->getNameStr() + ".omp.userContext";
876 StructType *structTy = StructType::get(Builder.getContext(),
877 structMembers);
878 M->addTypeName(Name, structTy);
879
880 // Store the values into the structure.
881 Value *structData = Builder.CreateAlloca(structTy, 0, "omp.userContext");
882 for (unsigned i = 0; i < OMPDataVals.size(); i++) {
883 Value *storeAddr = Builder.CreateStructGEP(structData, i);
884 Builder.CreateStore(OMPDataVals[i], storeAddr);
885 }
886
887 return structData;
888 }
889
890 /// @brief Create OpenMP structure values.
891 ///
892 /// Create a list of values that has to be stored into the subfuncition
893 /// structure.
894 SetVector<Value*> createOpenMPStructValues() {
895 SetVector<Value*> OMPDataVals;
896
897 // Push the clast variables available in the clastVars.
898 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
899 I != E; I++)
900 OMPDataVals.insert(I->second);
901
902 // Push the base addresses of memory references.
903 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
904 ScopStmt *Stmt = *SI;
905 for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
906 E = Stmt->memacc_end(); I != E; ++I) {
907 Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
908 OMPDataVals.insert((BaseAddr));
909 }
910 }
911
912 return OMPDataVals;
913 }
914
915 /// @brief Extract the values from the subfunction parameter.
916 ///
917 /// Extract the values from the subfunction parameter and update the clast
918 /// variables to point to the new values.
919 void extractValuesFromOpenMPStruct(CharMapT *clastVarsOMP,
920 SetVector<Value*> OMPDataVals,
921 Value *userContext) {
922 // Extract the clast variables.
923 unsigned i = 0;
924 for (CharMapT::iterator I = clastVars->begin(), E = clastVars->end();
925 I != E; I++) {
926 Value *loadAddr = Builder.CreateStructGEP(userContext, i);
927 (*clastVarsOMP)[I->first] = Builder.CreateLoad(loadAddr);
928 i++;
929 }
930
931 // Extract the base addresses of memory references.
932 for (unsigned j = i; j < OMPDataVals.size(); j++) {
933 Value *loadAddr = Builder.CreateStructGEP(userContext, j);
934 Value *baseAddr = OMPDataVals[j];
935 ValueMap[baseAddr] = Builder.CreateLoad(loadAddr);
936 }
937
938 }
939
940 /// @brief Add body to the subfunction.
941 void addOpenMPSubfunctionBody(Function *FN, const clast_for *f,
942 Value *structData,
943 SetVector<Value*> OMPDataVals) {
944 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
945 LLVMContext &Context = FN->getContext();
946 const IntegerType *intPtrTy = TD->getIntPtrType(Context);
947
948 // Store the previous basic block.
949 BasicBlock *PrevBB = Builder.GetInsertBlock();
950
951 // Create basic blocks.
952 BasicBlock *HeaderBB = BasicBlock::Create(Context, "omp.setup", FN);
953 BasicBlock *ExitBB = BasicBlock::Create(Context, "omp.exit", FN);
954 BasicBlock *checkNextBB = BasicBlock::Create(Context, "omp.checkNext", FN);
955 BasicBlock *loadIVBoundsBB = BasicBlock::Create(Context, "omp.loadIVBounds",
956 FN);
957
958 DT->addNewBlock(HeaderBB, PrevBB);
959 DT->addNewBlock(ExitBB, HeaderBB);
960 DT->addNewBlock(checkNextBB, HeaderBB);
961 DT->addNewBlock(loadIVBoundsBB, HeaderBB);
962
963 // Fill up basic block HeaderBB.
964 Builder.SetInsertPoint(HeaderBB);
965 Value *lowerBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
966 "omp.lowerBoundPtr");
967 Value *upperBoundPtr = Builder.CreateAlloca(intPtrTy, 0,
968 "omp.upperBoundPtr");
969 Value *userContext = Builder.CreateBitCast(FN->arg_begin(),
970 structData->getType(),
971 "omp.userContext");
972
973 CharMapT clastVarsOMP;
974 extractValuesFromOpenMPStruct(&clastVarsOMP, OMPDataVals, userContext);
975
976 Builder.CreateBr(checkNextBB);
977
978 // Add code to check if another set of iterations will be executed.
979 Builder.SetInsertPoint(checkNextBB);
980 Function *runtimeNextFunction = M->getFunction("GOMP_loop_runtime_next");
981 Value *ret1 = Builder.CreateCall2(runtimeNextFunction,
982 lowerBoundPtr, upperBoundPtr);
983 Value *hasNextSchedule = Builder.CreateTrunc(ret1, Builder.getInt1Ty(),
984 "omp.hasNextScheduleBlock");
985 Builder.CreateCondBr(hasNextSchedule, loadIVBoundsBB, ExitBB);
986
987 // Add code to to load the iv bounds for this set of iterations.
988 Builder.SetInsertPoint(loadIVBoundsBB);
989 Value *lowerBound = Builder.CreateLoad(lowerBoundPtr, "omp.lowerBound");
990 Value *upperBound = Builder.CreateLoad(upperBoundPtr, "omp.upperBound");
991
992 // Subtract one as the upper bound provided by openmp is a < comparison
993 // whereas the codegenForSequential function creates a <= comparison.
994 upperBound = Builder.CreateSub(upperBound, ConstantInt::get(intPtrTy, 1),
995 "omp.upperBoundAdjusted");
996
997 // Use clastVarsOMP during code generation of the OpenMP subfunction.
998 CharMapT *oldClastVars = clastVars;
999 clastVars = &clastVarsOMP;
1000 ExpGen.setIVS(&clastVarsOMP);
1001
1002 codegenForSequential(f, lowerBound, upperBound);
1003
1004 // Restore the old clastVars.
1005 clastVars = oldClastVars;
1006 ExpGen.setIVS(oldClastVars);
1007
1008 Builder.CreateBr(checkNextBB);
1009
1010 // Add code to terminate this openmp subfunction.
1011 Builder.SetInsertPoint(ExitBB);
1012 Function *endnowaitFunction = M->getFunction("GOMP_loop_end_nowait");
1013 Builder.CreateCall(endnowaitFunction);
1014 Builder.CreateRetVoid();
1015
1016 // Restore the builder back to previous basic block.
1017 Builder.SetInsertPoint(PrevBB);
1018 }
1019
1020 /// @brief Create an OpenMP parallel for loop.
1021 ///
1022 /// This loop reflects a loop as if it would have been created by an OpenMP
1023 /// statement.
1024 void codegenForOpenMP(const clast_for *f) {
1025 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1026 const IntegerType *intPtrTy = TD->getIntPtrType(Builder.getContext());
1027
1028 Function *SubFunction = addOpenMPSubfunction(M);
1029 SetVector<Value*> OMPDataVals = createOpenMPStructValues();
1030 Value *structData = addValuesToOpenMPStruct(OMPDataVals, SubFunction);
1031
1032 addOpenMPSubfunctionBody(SubFunction, f, structData, OMPDataVals);
1033
1034 // Create call for GOMP_parallel_loop_runtime_start.
1035 Value *subfunctionParam = Builder.CreateBitCast(structData,
1036 Builder.getInt8PtrTy(),
1037 "omp_data");
1038
1039 Value *numberOfThreads = Builder.getInt32(0);
1040 Value *lowerBound = ExpGen.codegen(f->LB, intPtrTy);
1041 Value *upperBound = ExpGen.codegen(f->UB, intPtrTy);
1042
1043 // Add one as the upper bound provided by openmp is a < comparison
1044 // whereas the codegenForSequential function creates a <= comparison.
1045 upperBound = Builder.CreateAdd(upperBound, ConstantInt::get(intPtrTy, 1));
1046 APInt APStride = APInt_from_MPZ(f->stride);
1047 Value *stride = ConstantInt::get(intPtrTy,
1048 APStride.zext(intPtrTy->getBitWidth()));
1049
1050 SmallVector<Value *, 6> Arguments;
1051 Arguments.push_back(SubFunction);
1052 Arguments.push_back(subfunctionParam);
1053 Arguments.push_back(numberOfThreads);
1054 Arguments.push_back(lowerBound);
1055 Arguments.push_back(upperBound);
1056 Arguments.push_back(stride);
1057
1058 Function *parallelStartFunction =
1059 M->getFunction("GOMP_parallel_loop_runtime_start");
1060 Builder.CreateCall(parallelStartFunction, Arguments.begin(),
1061 Arguments.end());
1062
1063 // Create call to the subfunction.
1064 Builder.CreateCall(SubFunction, subfunctionParam);
1065
1066 // Create call for GOMP_parallel_end.
1067 Function *FN = M->getFunction("GOMP_parallel_end");
1068 Builder.CreateCall(FN);
1069 }
1070
1071 bool isInnermostLoop(const clast_for *f) {
1072 const clast_stmt *stmt = f->body;
1073
1074 while (stmt) {
1075 if (!CLAST_STMT_IS_A(stmt, stmt_user))
1076 return false;
1077
1078 stmt = stmt->next;
1079 }
1080
1081 return true;
1082 }
1083
1084 /// @brief Get the number of loop iterations for this loop.
1085 /// @param f The clast for loop to check.
1086 int getNumberOfIterations(const clast_for *f) {
1087 isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1088 isl_set *tmp = isl_set_copy(loopDomain);
1089
1090 // Calculate a map similar to the identity map, but with the last input
1091 // and output dimension not related.
1092 // [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1093 isl_dim *dim = isl_set_get_dim(loopDomain);
1094 dim = isl_dim_drop_outputs(dim, isl_set_n_dim(loopDomain) - 2, 1);
1095 dim = isl_dim_map_from_set(dim);
1096 isl_map *identity = isl_map_identity(dim);
1097 identity = isl_map_add_dims(identity, isl_dim_in, 1);
1098 identity = isl_map_add_dims(identity, isl_dim_out, 1);
1099
1100 isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1101 map = isl_map_intersect(map, identity);
1102
1103 isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1104 isl_map *lexmin = isl_map_lexmin(isl_map_copy(map));
1105 isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1106
1107 isl_set *elements = isl_map_range(sub);
1108
1109 if (!isl_set_is_singleton(elements))
1110 return -1;
1111
1112 isl_point *p = isl_set_sample_point(elements);
1113
1114 isl_int v;
1115 isl_int_init(v);
1116 isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1117 int numberIterations = isl_int_get_si(v);
1118 isl_int_clear(v);
1119
1120 return (numberIterations) / isl_int_get_si(f->stride) + 1;
1121 }
1122
1123 /// @brief Create vector instructions for this loop.
1124 void codegenForVector(const clast_for *f) {
1125 DEBUG(dbgs() << "Vectorizing loop '" << f->iterator << "'\n";);
1126 int vectorWidth = getNumberOfIterations(f);
1127
1128 Value *LB = ExpGen.codegen(f->LB,
1129 TD->getIntPtrType(Builder.getContext()));
1130
1131 APInt Stride = APInt_from_MPZ(f->stride);
1132 const IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1133 Stride = Stride.zext(LoopIVType->getBitWidth());
1134 Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1135
1136 std::vector<Value*> IVS(vectorWidth);
1137 IVS[0] = LB;
1138
1139 for (int i = 1; i < vectorWidth; i++)
1140 IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1141
1142 isl_set *scatteringDomain = isl_set_from_cloog_domain(f->domain);
1143
1144 // Add loop iv to symbols.
1145 (*clastVars)[f->iterator] = LB;
1146
1147 const clast_stmt *stmt = f->body;
1148
1149 while (stmt) {
1150 codegen((const clast_user_stmt *)stmt, &IVS, f->iterator,
1151 scatteringDomain);
1152 stmt = stmt->next;
1153 }
1154
1155 // Loop is finished, so remove its iv from the live symbols.
1156 clastVars->erase(f->iterator);
1157 }
1158
1159 void codegen(const clast_for *f) {
1160 if (Vector && isInnermostLoop(f) && isParallelFor(f)
1161 && (-1 != getNumberOfIterations(f))
1162 && (getNumberOfIterations(f) <= 16)) {
1163 codegenForVector(f);
1164 } else if (OpenMP && !parallelCodeGeneration && isParallelFor(f)) {
1165 parallelCodeGeneration = true;
1166 parallelLoops.push_back(f->iterator);
1167 codegenForOpenMP(f);
1168 parallelCodeGeneration = false;
1169 } else
1170 codegenForSequential(f);
1171 }
1172
1173 Value *codegen(const clast_equation *eq) {
1174 Value *LHS = ExpGen.codegen(eq->LHS,
1175 TD->getIntPtrType(Builder.getContext()));
1176 Value *RHS = ExpGen.codegen(eq->RHS,
1177 TD->getIntPtrType(Builder.getContext()));
1178 CmpInst::Predicate P;
1179
1180 if (eq->sign == 0)
1181 P = ICmpInst::ICMP_EQ;
1182 else if (eq->sign > 0)
1183 P = ICmpInst::ICMP_SGE;
1184 else
1185 P = ICmpInst::ICMP_SLE;
1186
1187 return Builder.CreateICmp(P, LHS, RHS);
1188 }
1189
1190 void codegen(const clast_guard *g) {
1191 Function *F = Builder.GetInsertBlock()->getParent();
1192 LLVMContext &Context = F->getContext();
1193 BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1194 BasicBlock *MergeBB = BasicBlock::Create(Context, "polly.merge", F);
1195 DT->addNewBlock(ThenBB, Builder.GetInsertBlock());
1196 DT->addNewBlock(MergeBB, Builder.GetInsertBlock());
1197
1198 Value *Predicate = codegen(&(g->eq[0]));
1199
1200 for (int i = 1; i < g->n; ++i) {
1201 Value *TmpPredicate = codegen(&(g->eq[i]));
1202 Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1203 }
1204
1205 Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1206 Builder.SetInsertPoint(ThenBB);
1207
1208 codegen(g->then);
1209
1210 Builder.CreateBr(MergeBB);
1211 Builder.SetInsertPoint(MergeBB);
1212 }
1213
1214 void codegen(const clast_stmt *stmt) {
1215 if (CLAST_STMT_IS_A(stmt, stmt_root))
1216 assert(false && "No second root statement expected");
1217 else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1218 codegen((const clast_assignment *)stmt);
1219 else if (CLAST_STMT_IS_A(stmt, stmt_user))
1220 codegen((const clast_user_stmt *)stmt);
1221 else if (CLAST_STMT_IS_A(stmt, stmt_block))
1222 codegen((const clast_block *)stmt);
1223 else if (CLAST_STMT_IS_A(stmt, stmt_for))
1224 codegen((const clast_for *)stmt);
1225 else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1226 codegen((const clast_guard *)stmt);
1227
1228 if (stmt->next)
1229 codegen(stmt->next);
1230 }
1231
1232 void addParameters(const CloogNames *names) {
1233 SCEVExpander Rewriter(SE);
1234
1235 // Create an instruction that specifies the location where the parameters
1236 // are expanded.
1237 CastInst::CreateIntegerCast(ConstantInt::getTrue(Builder.getContext()),
1238 Builder.getInt16Ty(), false, "insertInst",
1239 Builder.GetInsertBlock());
1240
1241 int i = 0;
1242 for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1243 PI != PE; ++PI) {
1244 assert(i < names->nb_parameters && "Not enough parameter names");
1245
1246 const SCEV *Param = *PI;
1247 const Type *Ty = Param->getType();
1248
1249 Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1250 Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1251 (*clastVars)[names->parameters[i]] = V;
1252
1253 ++i;
1254 }
1255 }
1256
1257 public:
1258 void codegen(const clast_root *r) {
1259 clastVars = new CharMapT();
1260 addParameters(r->names);
1261 ExpGen.setIVS(clastVars);
1262
1263 parallelCodeGeneration = false;
1264
1265 const clast_stmt *stmt = (const clast_stmt*) r;
1266 if (stmt->next)
1267 codegen(stmt->next);
1268
1269 delete clastVars;
1270 }
1271
1272 ClastStmtCodeGen(Scop *scop, ScalarEvolution &se, DominatorTree *dt,
1273 Dependences *dp, TargetData *td, IRBuilder<> &B) :
1274 S(scop), SE(se), DT(dt), DP(dp), TD(td), Builder(B), ExpGen(Builder, NULL) {}
1275
1276};
1277}
1278
1279namespace {
1280class CodeGeneration : public ScopPass {
1281 Region *region;
1282 Scop *S;
1283 DominatorTree *DT;
1284 ScalarEvolution *SE;
1285 ScopDetection *SD;
1286 CloogInfo *C;
1287 LoopInfo *LI;
1288 TargetData *TD;
1289
1290 std::vector<std::string> parallelLoops;
1291
1292 public:
1293 static char ID;
1294
1295 CodeGeneration() : ScopPass(ID) {}
1296
1297 void createSeSeEdges(Region *R) {
1298 BasicBlock *newEntry = createSingleEntryEdge(R, this);
1299
1300 for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1301 if ((*SI)->getBasicBlock() == R->getEntry())
1302 (*SI)->setBasicBlock(newEntry);
1303
1304 createSingleExitEdge(R, this);
1305 }
1306
1307
1308 // Adding prototypes required if OpenMP is enabled.
1309 void addOpenMPDefinitions(IRBuilder<> &Builder)
1310 {
1311 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
1312 LLVMContext &Context = Builder.getContext();
1313 const IntegerType *intPtrTy = TD->getIntPtrType(Context);
1314
1315 if (!M->getFunction("GOMP_parallel_end")) {
1316 FunctionType *FT = FunctionType::get(Type::getVoidTy(Context), false);
1317 Function::Create(FT, Function::ExternalLinkage, "GOMP_parallel_end", M);
1318 }
1319
1320 if (!M->getFunction("GOMP_parallel_loop_runtime_start")) {
1321 // Type of first argument.
1322 std::vector<const Type*> Arguments(1, Builder.getInt8PtrTy());
1323 FunctionType *FnArgTy = FunctionType::get(Builder.getVoidTy(), Arguments,
1324 false);
1325 PointerType *FnPtrTy = PointerType::getUnqual(FnArgTy);
1326
1327 std::vector<const Type*> args;
1328 args.push_back(FnPtrTy);
1329 args.push_back(Builder.getInt8PtrTy());
1330 args.push_back(Builder.getInt32Ty());
1331 args.push_back(intPtrTy);
1332 args.push_back(intPtrTy);
1333 args.push_back(intPtrTy);
1334
1335 FunctionType *type = FunctionType::get(Builder.getVoidTy(), args, false);
1336 Function::Create(type, Function::ExternalLinkage,
1337 "GOMP_parallel_loop_runtime_start", M);
1338 }
1339
1340 if (!M->getFunction("GOMP_loop_runtime_next")) {
1341 PointerType *intLongPtrTy = PointerType::getUnqual(intPtrTy);
1342
1343 std::vector<const Type*> args;
1344 args.push_back(intLongPtrTy);
1345 args.push_back(intLongPtrTy);
1346
1347 FunctionType *type = FunctionType::get(Builder.getInt8Ty(), args, false);
1348 Function::Create(type, Function::ExternalLinkage,
1349 "GOMP_loop_runtime_next", M);
1350 }
1351
1352 if (!M->getFunction("GOMP_loop_end_nowait")) {
1353 FunctionType *FT = FunctionType::get(Builder.getVoidTy(),
1354 std::vector<const Type*>(), false);
1355 Function::Create(FT, Function::ExternalLinkage,
1356 "GOMP_loop_end_nowait", M);
1357 }
1358 }
1359
1360 bool runOnScop(Scop &scop) {
1361 S = &scop;
1362 region = &S->getRegion();
1363 Region *R = region;
1364 DT = &getAnalysis<DominatorTree>();
1365 Dependences *DP = &getAnalysis<Dependences>();
1366 SE = &getAnalysis<ScalarEvolution>();
1367 LI = &getAnalysis<LoopInfo>();
1368 C = &getAnalysis<CloogInfo>();
1369 SD = &getAnalysis<ScopDetection>();
1370 TD = &getAnalysis<TargetData>();
1371
1372 Function *F = R->getEntry()->getParent();
1373
1374 parallelLoops.clear();
1375
1376 if (CodegenOnly != "" && CodegenOnly != F->getNameStr()) {
1377 errs() << "Codegenerating only function '" << CodegenOnly
1378 << "' skipping '" << F->getNameStr() << "' \n";
1379 return false;
1380 }
1381
1382 createSeSeEdges(R);
1383
1384 // Create a basic block in which to start code generation.
1385 BasicBlock *PollyBB = BasicBlock::Create(F->getContext(), "pollyBB", F);
1386 IRBuilder<> Builder(PollyBB);
1387 DT->addNewBlock(PollyBB, R->getEntry());
1388
1389 const clast_root *clast = (const clast_root *) C->getClast();
1390
1391 ClastStmtCodeGen CodeGen(S, *SE, DT, DP, TD, Builder);
1392
1393 if (OpenMP)
1394 addOpenMPDefinitions(Builder);
1395
1396 CodeGen.codegen(clast);
1397
1398 // Save the parallel loops generated.
1399 parallelLoops.insert(parallelLoops.begin(),
1400 CodeGen.getParallelLoops().begin(),
1401 CodeGen.getParallelLoops().end());
1402
1403 BasicBlock *AfterScop = *pred_begin(R->getExit());
1404 Builder.CreateBr(AfterScop);
1405
1406 BasicBlock *successorBlock = *succ_begin(R->getEntry());
1407
1408 // Update old PHI nodes to pass LLVM verification.
1409 std::vector<PHINode*> PHINodes;
1410 for (BasicBlock::iterator SI = successorBlock->begin(),
1411 SE = successorBlock->getFirstNonPHI(); SI != SE; ++SI) {
1412 PHINode *PN = static_cast<PHINode*>(&*SI);
1413 PHINodes.push_back(PN);
1414 }
1415
1416 for (std::vector<PHINode*>::iterator PI = PHINodes.begin(),
1417 PE = PHINodes.end(); PI != PE; ++PI)
1418 (*PI)->removeIncomingValue(R->getEntry());
1419
1420 DT->changeImmediateDominator(AfterScop, Builder.GetInsertBlock());
1421
1422 BasicBlock *OldRegionEntry = *succ_begin(R->getEntry());
1423
1424 // Enable the new polly code.
1425 R->getEntry()->getTerminator()->setSuccessor(0, PollyBB);
1426
1427 // Remove old Scop nodes from dominator tree.
1428 std::vector<DomTreeNode*> ToVisit;
1429 std::vector<DomTreeNode*> Visited;
1430 ToVisit.push_back(DT->getNode(OldRegionEntry));
1431
1432 while (!ToVisit.empty()) {
1433 DomTreeNode *Node = ToVisit.back();
1434
1435 ToVisit.pop_back();
1436
1437 if (AfterScop == Node->getBlock())
1438 continue;
1439
1440 Visited.push_back(Node);
1441
1442 std::vector<DomTreeNode*> Children = Node->getChildren();
1443 ToVisit.insert(ToVisit.end(), Children.begin(), Children.end());
1444 }
1445
1446 for (std::vector<DomTreeNode*>::reverse_iterator I = Visited.rbegin(),
1447 E = Visited.rend(); I != E; ++I)
1448 DT->eraseNode((*I)->getBlock());
1449
1450 R->getParent()->removeSubRegion(R);
1451
1452 // And forget the Scop if we remove the region.
1453 SD->forgetScop(*R);
1454
1455 return false;
1456 }
1457
1458 virtual void printScop(raw_ostream &OS) const {
1459 for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1460 PE = parallelLoops.end(); PI != PE; ++PI)
1461 OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1462 }
1463
1464 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1465 AU.addRequired<CloogInfo>();
1466 AU.addRequired<Dependences>();
1467 AU.addRequired<DominatorTree>();
1468 AU.addRequired<ScalarEvolution>();
1469 AU.addRequired<LoopInfo>();
1470 AU.addRequired<RegionInfo>();
1471 AU.addRequired<ScopDetection>();
1472 AU.addRequired<ScopInfo>();
1473 AU.addRequired<TargetData>();
1474
1475 AU.addPreserved<CloogInfo>();
1476 AU.addPreserved<Dependences>();
1477 AU.addPreserved<LoopInfo>();
1478 AU.addPreserved<DominatorTree>();
1479 AU.addPreserved<PostDominatorTree>();
1480 AU.addPreserved<ScopDetection>();
1481 AU.addPreserved<ScalarEvolution>();
1482 AU.addPreserved<RegionInfo>();
1483 AU.addPreserved<TempScopInfo>();
1484 AU.addPreserved<ScopInfo>();
1485 AU.addPreservedID(IndependentBlocksID);
1486 }
1487};
1488}
1489
1490char CodeGeneration::ID = 1;
1491
1492static RegisterPass<CodeGeneration>
1493Z("polly-codegen", "Polly - Create LLVM-IR from the polyhedral information");
1494
1495Pass* polly::createCodeGenerationPass() {
1496 return new CodeGeneration();
1497}