1 //===------ 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/Cloog.h"
26 #include "polly/CodeGeneration.h"
27 #include "polly/Dependences.h"
28 #include "polly/LinkAllPasses.h"
29 #include "polly/ScopInfo.h"
30 #include "polly/TempScopInfo.h"
31 #include "polly/Support/GICHelper.h"
32 #include "polly/LoopGenerators.h"
33 
34 #include "llvm/Module.h"
35 #include "llvm/ADT/SetVector.h"
36 #include "llvm/ADT/PostOrderIterator.h"
37 #include "llvm/Analysis/LoopInfo.h"
38 #include "llvm/Analysis/ScalarEvolutionExpander.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/IRBuilder.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 
45 #define CLOOG_INT_GMP 1
46 #include "cloog/cloog.h"
47 #include "cloog/isl/cloog.h"
48 
49 #include "isl/aff.h"
50 
51 #include <vector>
52 #include <utility>
53 
54 using namespace polly;
55 using namespace llvm;
56 
57 struct isl_set;
58 
59 namespace polly {
60 
61 bool EnablePollyVector;
62 
63 static cl::opt<bool, true>
64 Vector("enable-polly-vector",
65        cl::desc("Enable polly vector code generation"), cl::Hidden,
66        cl::location(EnablePollyVector), cl::init(false), cl::ZeroOrMore);
67 
68 static cl::opt<bool>
69 OpenMP("enable-polly-openmp",
70        cl::desc("Generate OpenMP parallel code"), cl::Hidden,
71        cl::value_desc("OpenMP code generation enabled if true"),
72        cl::init(false), cl::ZeroOrMore);
73 
74 static cl::opt<bool>
75 AtLeastOnce("enable-polly-atLeastOnce",
76        cl::desc("Give polly the hint, that every loop is executed at least"
77                 "once"), cl::Hidden,
78        cl::value_desc("OpenMP code generation enabled if true"),
79        cl::init(false), cl::ZeroOrMore);
80 
81 static cl::opt<bool>
82 Aligned("enable-polly-aligned",
83        cl::desc("Assumed aligned memory accesses."), cl::Hidden,
84        cl::value_desc("OpenMP code generation enabled if true"),
85        cl::init(false), cl::ZeroOrMore);
86 
87 static cl::opt<bool>
88 GroupedUnrolling("enable-polly-grouped-unroll",
89                  cl::desc("Perform grouped unrolling, but don't generate SIMD "
90                           "instuctions"), cl::Hidden, cl::init(false),
91                  cl::ZeroOrMore);
92 
93 typedef DenseMap<const Value*, Value*> ValueMapT;
94 typedef DenseMap<const char*, Value*> CharMapT;
95 typedef std::vector<ValueMapT> VectorValueMapT;
96 
97 class IslGenerator {
98 public:
99   IslGenerator(IRBuilder<> &Builder, std::vector<Value *> &IVS) :
100     Builder(Builder), IVS(IVS) {}
101   Value *generateIslInt(__isl_take isl_int Int);
102   Value *generateIslAff(__isl_take isl_aff *Aff);
103   Value *generateIslPwAff(__isl_take isl_pw_aff *PwAff);
104 
105 private:
106   typedef struct {
107     Value *Result;
108     class IslGenerator *Generator;
109   } IslGenInfo;
110 
111   IRBuilder<> &Builder;
112   std::vector<Value *> &IVS;
113   static int mergeIslAffValues(__isl_take isl_set *Set,
114                                __isl_take isl_aff *Aff, void *User);
115 };
116 
117 Value *IslGenerator::generateIslInt(isl_int Int) {
118   mpz_t IntMPZ;
119   mpz_init(IntMPZ);
120   isl_int_get_gmp(Int, IntMPZ);
121   Value *IntValue = Builder.getInt(APInt_from_MPZ(IntMPZ));
122   mpz_clear(IntMPZ);
123   return IntValue;
124 }
125 
126 Value *IslGenerator::generateIslAff(__isl_take isl_aff *Aff) {
127   Value *Result;
128   Value *ConstValue;
129   isl_int ConstIsl;
130 
131   isl_int_init(ConstIsl);
132   isl_aff_get_constant(Aff, &ConstIsl);
133   ConstValue = generateIslInt(ConstIsl);
134   Type *Ty = Builder.getInt64Ty();
135 
136   // FIXME: We should give the constant and coefficients the right type. Here
137   // we force it into i64.
138   Result = Builder.CreateSExtOrBitCast(ConstValue, Ty);
139 
140   unsigned int NbInputDims = isl_aff_dim(Aff, isl_dim_in);
141 
142   assert((IVS.size() == NbInputDims) && "The Dimension of Induction Variables"
143          "must match the dimension of the affine space.");
144 
145   isl_int CoefficientIsl;
146   isl_int_init(CoefficientIsl);
147 
148   for (unsigned int i = 0; i < NbInputDims; ++i) {
149     Value *CoefficientValue;
150     isl_aff_get_coefficient(Aff, isl_dim_in, i, &CoefficientIsl);
151 
152     if (isl_int_is_zero(CoefficientIsl))
153       continue;
154 
155     CoefficientValue = generateIslInt(CoefficientIsl);
156     CoefficientValue = Builder.CreateIntCast(CoefficientValue, Ty, true);
157     Value *IV = Builder.CreateIntCast(IVS[i], Ty, true);
158     Value *PAdd = Builder.CreateMul(CoefficientValue, IV, "p_mul_coeff");
159     Result = Builder.CreateAdd(Result, PAdd, "p_sum_coeff");
160   }
161 
162   isl_int_clear(CoefficientIsl);
163   isl_int_clear(ConstIsl);
164   isl_aff_free(Aff);
165 
166   return Result;
167 }
168 
169 int IslGenerator::mergeIslAffValues(__isl_take isl_set *Set,
170                                     __isl_take isl_aff *Aff, void *User) {
171   IslGenInfo *GenInfo = (IslGenInfo *)User;
172 
173   assert((GenInfo->Result == NULL) && "Result is already set."
174          "Currently only single isl_aff is supported");
175   assert(isl_set_plain_is_universe(Set)
176          && "Code generation failed because the set is not universe");
177 
178   GenInfo->Result = GenInfo->Generator->generateIslAff(Aff);
179 
180   isl_set_free(Set);
181   return 0;
182 }
183 
184 Value *IslGenerator::generateIslPwAff(__isl_take isl_pw_aff *PwAff) {
185   IslGenInfo User;
186   User.Result = NULL;
187   User.Generator = this;
188   isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &User);
189   assert(User.Result && "Code generation for isl_pw_aff failed");
190 
191   isl_pw_aff_free(PwAff);
192   return User.Result;
193 }
194 
195 /// @brief Generate a new basic block for a polyhedral statement.
196 ///
197 /// The only public function exposed is generate().
198 class BlockGenerator {
199 public:
200   /// @brief Generate a new BasicBlock for a ScopStmt.
201   ///
202   /// @param Builder   The LLVM-IR Builder used to generate the statement. The
203   ///                  code is generated at the location, the Builder points to.
204   /// @param Stmt      The statement to code generate.
205   /// @param GlobalMap A map that defines for certain Values referenced from the
206   ///                  original code new Values they should be replaced with.
207   /// @param P         A reference to the pass this function is called from.
208   ///                  The pass is needed to update other analysis.
209   static void generate(IRBuilder<> &Builder, ScopStmt &Stmt,
210                        ValueMapT &GlobalMap, Pass *P) {
211     BlockGenerator Generator(Builder, Stmt, P);
212     Generator.copyBB(GlobalMap);
213   }
214 
215 protected:
216   IRBuilder<> &Builder;
217   ScopStmt &Statement;
218   Pass *P;
219 
220   BlockGenerator(IRBuilder<> &B, ScopStmt &Stmt, Pass *P);
221 
222   /// @brief Get the new version of a Value.
223   ///
224   /// @param Old       The old Value.
225   /// @param BBMap     A mapping from old values to their new values
226   ///                  (for values recalculated within this basic block).
227   /// @param GlobalMap A mapping from old values to their new values
228   ///                  (for values recalculated in the new ScoP, but not
229   ///                   within this basic block).
230   ///
231   /// @returns  o The old value, if it is still valid.
232   ///           o The new value, if available.
233   ///           o NULL, if no value is found.
234   Value *getNewValue(const Value *Old, ValueMapT &BBMap, ValueMapT &GlobalMap);
235 
236   void copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
237                       ValueMapT &GlobalMap);
238 
239   /// @brief Get the memory access offset to be added to the base address
240   std::vector<Value*> getMemoryAccessIndex(__isl_keep isl_map *AccessRelation,
241                                            Value *BaseAddress, ValueMapT &BBMap,
242                                            ValueMapT &GlobalMap);
243 
244   /// @brief Get the new operand address according to the changed access in
245   ///        JSCOP file.
246   Value *getNewAccessOperand(__isl_keep isl_map *NewAccessRelation,
247                              Value *BaseAddress, ValueMapT &BBMap,
248                              ValueMapT &GlobalMap);
249 
250   /// @brief Generate the operand address
251   Value *generateLocationAccessed(const Instruction *Inst,
252                                   const Value *Pointer, ValueMapT &BBMap,
253                                   ValueMapT &GlobalMap);
254 
255   Value *generateScalarLoad(const LoadInst *load, ValueMapT &BBMap,
256                             ValueMapT &GlobalMap);
257 
258   Value *generateScalarStore(const StoreInst *store, ValueMapT &BBMap,
259                              ValueMapT &GlobalMap);
260 
261   /// @brief Copy a single Instruction.
262   ///
263   /// This copies a single Instruction and updates references to old values
264   /// with references to new values, as defined by GlobalMap and BBMap.
265   ///
266   /// @param BBMap     A mapping from old values to their new values
267   ///                  (for values recalculated within this basic block).
268   /// @param GlobalMap A mapping from old values to their new values
269   ///                  (for values recalculated in the new ScoP, but not
270   ///                  within this basic block).
271   void copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
272                        ValueMapT &GlobalMap);
273 
274   /// @brief Copy the basic block.
275   ///
276   /// This copies the entire basic block and updates references to old values
277   /// with references to new values, as defined by GlobalMap.
278   ///
279   /// @param GlobalMap A mapping from old values to their new values
280   ///                  (for values recalculated in the new ScoP, but not
281   ///                  within this basic block).
282   void copyBB(ValueMapT &GlobalMap);
283 };
284 
285 BlockGenerator::BlockGenerator(IRBuilder<> &B, ScopStmt &Stmt, Pass *P):
286   Builder(B), Statement(Stmt), P(P) {}
287 
288 Value *BlockGenerator::getNewValue(const Value *Old, ValueMapT &BBMap,
289                                    ValueMapT &GlobalMap) {
290   // We assume constants never change.
291   // This avoids map lookups for many calls to this function.
292   if (isa<Constant>(Old))
293     return const_cast<Value*>(Old);
294 
295   if (GlobalMap.count(Old)) {
296     Value *New = GlobalMap[Old];
297 
298     if (Old->getType()->getScalarSizeInBits()
299         < New->getType()->getScalarSizeInBits())
300       New = Builder.CreateTruncOrBitCast(New, Old->getType());
301 
302     return New;
303   }
304 
305   if (BBMap.count(Old)) {
306     return BBMap[Old];
307   }
308 
309   // 'Old' is within the original SCoP, but was not rewritten.
310   //
311   // Such values appear, if they only calculate information already available in
312   // the polyhedral description (e.g.  an induction variable increment). They
313   // can be safely ignored.
314   if (const Instruction *Inst = dyn_cast<Instruction>(Old))
315     if (Statement.getParent()->getRegion().contains(Inst->getParent()))
316       return NULL;
317 
318   // Everything else is probably a scop-constant value defined as global,
319   // function parameter or an instruction not within the scop.
320   return const_cast<Value*>(Old);
321 }
322 
323 void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
324                                     ValueMapT &GlobalMap) {
325   Instruction *NewInst = Inst->clone();
326 
327   // Replace old operands with the new ones.
328   for (Instruction::const_op_iterator OI = Inst->op_begin(),
329        OE = Inst->op_end(); OI != OE; ++OI) {
330     Value *OldOperand = *OI;
331     Value *NewOperand = getNewValue(OldOperand, BBMap, GlobalMap);
332 
333     if (!NewOperand) {
334       assert(!isa<StoreInst>(NewInst)
335              && "Store instructions are always needed!");
336       delete NewInst;
337       return;
338     }
339 
340     NewInst->replaceUsesOfWith(OldOperand, NewOperand);
341   }
342 
343   Builder.Insert(NewInst);
344   BBMap[Inst] = NewInst;
345 
346   if (!NewInst->getType()->isVoidTy())
347     NewInst->setName("p_" + Inst->getName());
348 }
349 
350 std::vector<Value*> BlockGenerator::getMemoryAccessIndex(
351   __isl_keep isl_map *AccessRelation, Value *BaseAddress,
352   ValueMapT &BBMap, ValueMapT &GlobalMap) {
353 
354   assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
355          && "Only single dimensional access functions supported");
356 
357   std::vector<Value *> IVS;
358   for (unsigned i = 0; i < Statement.getNumIterators(); ++i) {
359     const Value *OriginalIV = Statement.getInductionVariableForDimension(i);
360     Value *NewIV = getNewValue(OriginalIV, BBMap, GlobalMap);
361     IVS.push_back(NewIV);
362   }
363 
364   isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
365   IslGenerator IslGen(Builder, IVS);
366   Value *OffsetValue = IslGen.generateIslPwAff(PwAff);
367 
368   Type *Ty = Builder.getInt64Ty();
369   OffsetValue = Builder.CreateIntCast(OffsetValue, Ty, true);
370 
371   std::vector<Value*> IndexArray;
372   Value *NullValue = Constant::getNullValue(Ty);
373   IndexArray.push_back(NullValue);
374   IndexArray.push_back(OffsetValue);
375   return IndexArray;
376 }
377 
378 Value *BlockGenerator::getNewAccessOperand(
379   __isl_keep isl_map *NewAccessRelation, Value *BaseAddress,
380   ValueMapT &BBMap, ValueMapT &GlobalMap) {
381   std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
382                                                         BaseAddress,
383                                                         BBMap, GlobalMap);
384   Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
385                                         "p_newarrayidx_");
386   return NewOperand;
387 }
388 
389 Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
390                                                 const Value *Pointer,
391                                                 ValueMapT &BBMap,
392                                                 ValueMapT &GlobalMap) {
393   MemoryAccess &Access = Statement.getAccessFor(Inst);
394   isl_map *CurrentAccessRelation = Access.getAccessRelation();
395   isl_map *NewAccessRelation = Access.getNewAccessRelation();
396 
397   assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
398          && "Current and new access function use different spaces");
399 
400   Value *NewPointer;
401 
402   if (!NewAccessRelation) {
403     NewPointer = getNewValue(Pointer, BBMap, GlobalMap);
404   } else {
405     Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
406     NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress,
407                                      BBMap, GlobalMap);
408   }
409 
410   isl_map_free(CurrentAccessRelation);
411   isl_map_free(NewAccessRelation);
412   return NewPointer;
413 }
414 
415 Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
416                                           ValueMapT &BBMap,
417                                           ValueMapT &GlobalMap) {
418   const Value *Pointer = Load->getPointerOperand();
419   const Instruction *Inst = dyn_cast<Instruction>(Load);
420   Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap, GlobalMap);
421   Value *ScalarLoad = Builder.CreateLoad(NewPointer,
422                                          Load->getName() + "_p_scalar_");
423   return ScalarLoad;
424 }
425 
426 Value *BlockGenerator::generateScalarStore(const StoreInst *Store,
427                                            ValueMapT &BBMap,
428                                            ValueMapT &GlobalMap) {
429   const Value *Pointer = Store->getPointerOperand();
430   Value *NewPointer = generateLocationAccessed(Store, Pointer, BBMap,
431                                                GlobalMap);
432   Value *ValueOperand = getNewValue(Store->getValueOperand(), BBMap, GlobalMap);
433 
434   return Builder.CreateStore(ValueOperand, NewPointer);
435 }
436 
437 void BlockGenerator::copyInstruction(const Instruction *Inst,
438                                      ValueMapT &BBMap, ValueMapT &GlobalMap) {
439   // Terminator instructions control the control flow. They are explicitly
440   // expressed in the clast and do not need to be copied.
441   if (Inst->isTerminator())
442     return;
443 
444   if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
445     BBMap[Load] = generateScalarLoad(Load, BBMap, GlobalMap);
446     return;
447   }
448 
449   if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
450     BBMap[Store] = generateScalarStore(Store, BBMap, GlobalMap);
451     return;
452   }
453 
454   copyInstScalar(Inst, BBMap, GlobalMap);
455 }
456 
457 
458 void BlockGenerator::copyBB(ValueMapT &GlobalMap) {
459   BasicBlock *BB = Statement.getBasicBlock();
460   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
461                                   Builder.GetInsertPoint(), P);
462   CopyBB->setName("polly.stmt." + BB->getName());
463   Builder.SetInsertPoint(CopyBB->begin());
464 
465   ValueMapT BBMap;
466 
467   for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
468        ++II)
469       copyInstruction(II, BBMap, GlobalMap);
470 }
471 
472 /// @brief Generate a new vector basic block for a polyhedral statement.
473 ///
474 /// The only public function exposed is generate().
475 class VectorBlockGenerator : BlockGenerator {
476 public:
477   /// @brief Generate a new vector basic block for a ScoPStmt.
478   ///
479   /// This code generation is similar to the normal, scalar code generation,
480   /// except that each instruction is code generated for several vector lanes
481   /// at a time. If possible instructions are issued as actual vector
482   /// instructions, but e.g. for address calculation instructions we currently
483   /// generate scalar instructions for each vector lane.
484   ///
485   /// @param Builder    The LLVM-IR Builder used to generate the statement. The
486   ///                   code is generated at the location, the builder points
487   ///                   to.
488   /// @param Stmt       The statement to code generate.
489   /// @param GlobalMaps A vector of maps that define for certain Values
490   ///                   referenced from the original code new Values they should
491   ///                   be replaced with. Each map in the vector of maps is
492   ///                   used for one vector lane. The number of elements in the
493   ///                   vector defines the width of the generated vector
494   ///                   instructions.
495   /// @param P          A reference to the pass this function is called from.
496   ///                   The pass is needed to update other analysis.
497   static void generate(IRBuilder<> &B, ScopStmt &Stmt,
498                        VectorValueMapT &GlobalMaps, __isl_keep isl_set *Domain,
499                        Pass *P) {
500     VectorBlockGenerator Generator(B, GlobalMaps, Stmt, Domain, P);
501     Generator.copyBB();
502   }
503 
504 private:
505   // This is a vector of global value maps.  The first map is used for the first
506   // vector lane, ...
507   // Each map, contains information about Instructions in the old ScoP, which
508   // are recalculated in the new SCoP. When copying the basic block, we replace
509   // all referenes to the old instructions with their recalculated values.
510   VectorValueMapT &GlobalMaps;
511 
512   isl_set *Domain;
513 
514   VectorBlockGenerator(IRBuilder<> &B, VectorValueMapT &GlobalMaps,
515                        ScopStmt &Stmt, __isl_keep isl_set *Domain, Pass *P);
516 
517   int getVectorWidth();
518 
519   Value *getVectorValue(const Value *Old, ValueMapT &VectorMap,
520                         VectorValueMapT &ScalarMaps);
521 
522   Type *getVectorPtrTy(const Value *V, int Width);
523 
524   /// @brief Load a vector from a set of adjacent scalars
525   ///
526   /// In case a set of scalars is known to be next to each other in memory,
527   /// create a vector load that loads those scalars
528   ///
529   /// %vector_ptr= bitcast double* %p to <4 x double>*
530   /// %vec_full = load <4 x double>* %vector_ptr
531   ///
532   Value *generateStrideOneLoad(const LoadInst *Load, ValueMapT &BBMap);
533 
534   /// @brief Load a vector initialized from a single scalar in memory
535   ///
536   /// In case all elements of a vector are initialized to the same
537   /// scalar value, this value is loaded and shuffeled into all elements
538   /// of the vector.
539   ///
540   /// %splat_one = load <1 x double>* %p
541   /// %splat = shufflevector <1 x double> %splat_one, <1 x
542   ///       double> %splat_one, <4 x i32> zeroinitializer
543   ///
544   Value *generateStrideZeroLoad(const LoadInst *Load, ValueMapT &BBMap);
545 
546   /// @Load a vector from scalars distributed in memory
547   ///
548   /// In case some scalars a distributed randomly in memory. Create a vector
549   /// by loading each scalar and by inserting one after the other into the
550   /// vector.
551   ///
552   /// %scalar_1= load double* %p_1
553   /// %vec_1 = insertelement <2 x double> undef, double %scalar_1, i32 0
554   /// %scalar 2 = load double* %p_2
555   /// %vec_2 = insertelement <2 x double> %vec_1, double %scalar_1, i32 1
556   ///
557   Value *generateUnknownStrideLoad(const LoadInst *Load,
558                                    VectorValueMapT &ScalarMaps);
559 
560   void generateLoad(const LoadInst *Load, ValueMapT &VectorMap,
561                     VectorValueMapT &ScalarMaps);
562 
563   void copyUnaryInst(const UnaryInstruction *Inst, ValueMapT &VectorMap,
564                      VectorValueMapT &ScalarMaps);
565 
566   void copyBinaryInst(const BinaryOperator *Inst, ValueMapT &VectorMap,
567                       VectorValueMapT &ScalarMaps);
568 
569   void copyStore(const StoreInst *Store, ValueMapT &VectorMap,
570                  VectorValueMapT &ScalarMaps);
571 
572   bool hasVectorOperands(const Instruction *Inst, ValueMapT &VectorMap);
573 
574   void copyInstruction(const Instruction *Inst, ValueMapT &VectorMap,
575                        VectorValueMapT &ScalarMaps);
576 
577   void copyBB();
578 };
579 
580 VectorBlockGenerator::VectorBlockGenerator(IRBuilder<> &B,
581   VectorValueMapT &GlobalMaps, ScopStmt &Stmt, __isl_keep isl_set *Domain,
582   Pass *P) : BlockGenerator(B, Stmt, P), GlobalMaps(GlobalMaps),
583   Domain(Domain) {
584     assert(GlobalMaps.size() > 1 && "Only one vector lane found");
585     assert(Domain && "No statement domain provided");
586   }
587 
588 Value *VectorBlockGenerator::getVectorValue(const Value *Old,
589                                             ValueMapT &VectorMap,
590                                             VectorValueMapT &ScalarMaps) {
591   if (VectorMap.count(Old))
592     return VectorMap[Old];
593 
594   int Width = getVectorWidth();
595 
596   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
597 
598   for (int Lane = 0; Lane < Width; Lane++)
599     Vector = Builder.CreateInsertElement(Vector,
600                                          getNewValue(Old,
601                                                      ScalarMaps[Lane],
602                                                      GlobalMaps[Lane]),
603                                          Builder.getInt32(Lane));
604 
605   VectorMap[Old] = Vector;
606 
607   return Vector;
608 }
609 
610 Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
611   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
612   assert(PointerTy && "PointerType expected");
613 
614   Type *ScalarType = PointerTy->getElementType();
615   VectorType *VectorType = VectorType::get(ScalarType, Width);
616 
617   return PointerType::getUnqual(VectorType);
618 }
619 
620 Value *VectorBlockGenerator::generateStrideOneLoad(const LoadInst *Load,
621                                                    ValueMapT &BBMap) {
622   const Value *Pointer = Load->getPointerOperand();
623   Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
624   Value *NewPointer = getNewValue(Pointer, BBMap, GlobalMaps[0]);
625   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
626                                            "vector_ptr");
627   LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
628                                          Load->getName() + "_p_vec_full");
629   if (!Aligned)
630     VecLoad->setAlignment(8);
631 
632   return VecLoad;
633 }
634 
635 Value *VectorBlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
636                                                     ValueMapT &BBMap) {
637   const Value *Pointer = Load->getPointerOperand();
638   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
639   Value *NewPointer = getNewValue(Pointer, BBMap, GlobalMaps[0]);
640   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
641                                            Load->getName() + "_p_vec_p");
642   LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
643                                            Load->getName() + "_p_splat_one");
644 
645   if (!Aligned)
646     ScalarLoad->setAlignment(8);
647 
648   Constant *SplatVector =
649     Constant::getNullValue(VectorType::get(Builder.getInt32Ty(),
650                                            getVectorWidth()));
651 
652   Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
653                                                   SplatVector,
654                                                   Load->getName()
655                                                   + "_p_splat");
656   return VectorLoad;
657 }
658 
659 Value *VectorBlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
660   VectorValueMapT &ScalarMaps) {
661   int VectorWidth = getVectorWidth();
662   const Value *Pointer = Load->getPointerOperand();
663   VectorType *VectorType = VectorType::get(
664     dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
665 
666   Value *Vector = UndefValue::get(VectorType);
667 
668   for (int i = 0; i < VectorWidth; i++) {
669     Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i]);
670     Value *ScalarLoad = Builder.CreateLoad(NewPointer,
671                                            Load->getName() + "_p_scalar_");
672     Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
673                                          Builder.getInt32(i),
674                                          Load->getName() + "_p_vec_");
675   }
676 
677   return Vector;
678 }
679 
680 void VectorBlockGenerator::generateLoad(const LoadInst *Load,
681                                         ValueMapT &VectorMap,
682                                         VectorValueMapT &ScalarMaps) {
683   Value *NewLoad;
684 
685   if (GroupedUnrolling) {
686     for (int i = 0; i < getVectorWidth(); i++)
687       ScalarMaps[i][Load] = generateScalarLoad(Load, ScalarMaps[i],
688                                                GlobalMaps[i]);
689 
690     return;
691   }
692 
693   MemoryAccess &Access = Statement.getAccessFor(Load);
694 
695   if (Access.isStrideZero(isl_set_copy(Domain)))
696     NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
697   else if (Access.isStrideOne(isl_set_copy(Domain)))
698     NewLoad = generateStrideOneLoad(Load, ScalarMaps[0]);
699   else
700     NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
701 
702   VectorMap[Load] = NewLoad;
703 }
704 
705 void VectorBlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
706                                          ValueMapT &VectorMap,
707                                          VectorValueMapT &ScalarMaps) {
708   int VectorWidth = getVectorWidth();
709   Value *NewOperand = getVectorValue(Inst->getOperand(0), VectorMap,
710                                      ScalarMaps);
711 
712   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
713 
714   const CastInst *Cast = dyn_cast<CastInst>(Inst);
715   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
716   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
717 }
718 
719 void VectorBlockGenerator::copyBinaryInst(const BinaryOperator *Inst,
720                                           ValueMapT &VectorMap,
721                                           VectorValueMapT &ScalarMaps) {
722   Value *OpZero = Inst->getOperand(0);
723   Value *OpOne = Inst->getOperand(1);
724 
725   Value *NewOpZero, *NewOpOne;
726   NewOpZero = getVectorValue(OpZero, VectorMap, ScalarMaps);
727   NewOpOne = getVectorValue(OpOne, VectorMap, ScalarMaps);
728 
729   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
730                                        NewOpOne,
731                                        Inst->getName() + "p_vec");
732   VectorMap[Inst] = NewInst;
733 }
734 
735 void VectorBlockGenerator::copyStore(const StoreInst *Store,
736                                      ValueMapT &VectorMap,
737                                      VectorValueMapT &ScalarMaps) {
738   int VectorWidth = getVectorWidth();
739 
740   MemoryAccess &Access = Statement.getAccessFor(Store);
741 
742   const Value *Pointer = Store->getPointerOperand();
743   Value *Vector = getVectorValue(Store->getValueOperand(), VectorMap,
744                                    ScalarMaps);
745 
746   if (Access.isStrideOne(isl_set_copy(Domain))) {
747     Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
748     Value *NewPointer = getNewValue(Pointer, ScalarMaps[0], GlobalMaps[0]);
749 
750     Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
751                                              "vector_ptr");
752     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
753 
754     if (!Aligned)
755       Store->setAlignment(8);
756   } else {
757     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
758       Value *Scalar = Builder.CreateExtractElement(Vector,
759                                                    Builder.getInt32(i));
760       Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i]);
761       Builder.CreateStore(Scalar, NewPointer);
762     }
763   }
764 }
765 
766 bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
767                                              ValueMapT &VectorMap) {
768   for (Instruction::const_op_iterator OI = Inst->op_begin(),
769        OE = Inst->op_end(); OI != OE; ++OI)
770     if (VectorMap.count(*OI))
771       return true;
772   return false;
773 }
774 
775 int VectorBlockGenerator::getVectorWidth() {
776   return GlobalMaps.size();
777 }
778 
779 void VectorBlockGenerator::copyInstruction(const Instruction *Inst,
780                                            ValueMapT &VectorMap,
781                                            VectorValueMapT &ScalarMaps) {
782   // Terminator instructions control the control flow. They are explicitly
783   // expressed in the clast and do not need to be copied.
784   if (Inst->isTerminator())
785     return;
786 
787   if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
788     generateLoad(Load, VectorMap, ScalarMaps);
789     return;
790   }
791 
792   if (hasVectorOperands(Inst, VectorMap)) {
793     if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
794       copyStore(Store, VectorMap, ScalarMaps);
795       return;
796     }
797 
798     if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
799       copyUnaryInst(Unary, VectorMap, ScalarMaps);
800       return;
801     }
802 
803     if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
804       copyBinaryInst(Binary, VectorMap, ScalarMaps);
805       return;
806     }
807 
808     llvm_unreachable("Cannot issue vector code for this instruction");
809   }
810 
811   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
812     copyInstScalar(Inst, ScalarMaps[VectorLane], GlobalMaps[VectorLane]);
813 }
814 
815 void VectorBlockGenerator::copyBB() {
816   BasicBlock *BB = Statement.getBasicBlock();
817   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
818                                   Builder.GetInsertPoint(), P);
819   CopyBB->setName("polly.stmt." + BB->getName());
820   Builder.SetInsertPoint(CopyBB->begin());
821 
822   // Create two maps that store the mapping from the original instructions of
823   // the old basic block to their copies in the new basic block. Those maps
824   // are basic block local.
825   //
826   // As vector code generation is supported there is one map for scalar values
827   // and one for vector values.
828   //
829   // In case we just do scalar code generation, the vectorMap is not used and
830   // the scalarMap has just one dimension, which contains the mapping.
831   //
832   // In case vector code generation is done, an instruction may either appear
833   // in the vector map once (as it is calculating >vectorwidth< values at a
834   // time. Or (if the values are calculated using scalar operations), it
835   // appears once in every dimension of the scalarMap.
836   VectorValueMapT ScalarBlockMap(getVectorWidth());
837   ValueMapT VectorBlockMap;
838 
839   for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
840        II != IE; ++II)
841       copyInstruction(II, VectorBlockMap, ScalarBlockMap);
842 }
843 
844 /// Class to generate LLVM-IR that calculates the value of a clast_expr.
845 class ClastExpCodeGen {
846   IRBuilder<> &Builder;
847   const CharMapT &IVS;
848 
849   Value *codegen(const clast_name *e, Type *Ty);
850   Value *codegen(const clast_term *e, Type *Ty);
851   Value *codegen(const clast_binary *e, Type *Ty);
852   Value *codegen(const clast_reduction *r, Type *Ty);
853 public:
854 
855   // A generator for clast expressions.
856   //
857   // @param B The IRBuilder that defines where the code to calculate the
858   //          clast expressions should be inserted.
859   // @param IVMAP A Map that translates strings describing the induction
860   //              variables to the Values* that represent these variables
861   //              on the LLVM side.
862   ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap);
863 
864   // Generates code to calculate a given clast expression.
865   //
866   // @param e The expression to calculate.
867   // @return The Value that holds the result.
868   Value *codegen(const clast_expr *e, Type *Ty);
869 };
870 
871 Value *ClastExpCodeGen::codegen(const clast_name *e, Type *Ty) {
872   CharMapT::const_iterator I = IVS.find(e->name);
873 
874   assert(I != IVS.end() && "Clast name not found");
875 
876   return Builder.CreateSExtOrBitCast(I->second, Ty);
877 }
878 
879 Value *ClastExpCodeGen::codegen(const clast_term *e, Type *Ty) {
880   APInt a = APInt_from_MPZ(e->val);
881 
882   Value *ConstOne = ConstantInt::get(Builder.getContext(), a);
883   ConstOne = Builder.CreateSExtOrBitCast(ConstOne, Ty);
884 
885   if (!e->var)
886     return ConstOne;
887 
888   Value *var = codegen(e->var, Ty);
889   return Builder.CreateMul(ConstOne, var);
890 }
891 
892 Value *ClastExpCodeGen::codegen(const clast_binary *e, Type *Ty) {
893   Value *LHS = codegen(e->LHS, Ty);
894 
895   APInt RHS_AP = APInt_from_MPZ(e->RHS);
896 
897   Value *RHS = ConstantInt::get(Builder.getContext(), RHS_AP);
898   RHS = Builder.CreateSExtOrBitCast(RHS, Ty);
899 
900   switch (e->type) {
901   case clast_bin_mod:
902     return Builder.CreateSRem(LHS, RHS);
903   case clast_bin_fdiv:
904     {
905       // floord(n,d) ((n < 0) ? (n - d + 1) : n) / d
906       Value *One = ConstantInt::get(Ty, 1);
907       Value *Zero = ConstantInt::get(Ty, 0);
908       Value *Sum1 = Builder.CreateSub(LHS, RHS);
909       Value *Sum2 = Builder.CreateAdd(Sum1, One);
910       Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
911       Value *Dividend = Builder.CreateSelect(isNegative, Sum2, LHS);
912       return Builder.CreateSDiv(Dividend, RHS);
913     }
914   case clast_bin_cdiv:
915     {
916       // ceild(n,d) ((n < 0) ? n : (n + d - 1)) / d
917       Value *One = ConstantInt::get(Ty, 1);
918       Value *Zero = ConstantInt::get(Ty, 0);
919       Value *Sum1 = Builder.CreateAdd(LHS, RHS);
920       Value *Sum2 = Builder.CreateSub(Sum1, One);
921       Value *isNegative = Builder.CreateICmpSLT(LHS, Zero);
922       Value *Dividend = Builder.CreateSelect(isNegative, LHS, Sum2);
923       return Builder.CreateSDiv(Dividend, RHS);
924     }
925   case clast_bin_div:
926     return Builder.CreateSDiv(LHS, RHS);
927   };
928 
929   llvm_unreachable("Unknown clast binary expression type");
930 }
931 
932 Value *ClastExpCodeGen::codegen(const clast_reduction *r, Type *Ty) {
933   assert((   r->type == clast_red_min
934              || r->type == clast_red_max
935              || r->type == clast_red_sum)
936          && "Clast reduction type not supported");
937   Value *old = codegen(r->elts[0], Ty);
938 
939   for (int i=1; i < r->n; ++i) {
940     Value *exprValue = codegen(r->elts[i], Ty);
941 
942     switch (r->type) {
943     case clast_red_min:
944       {
945         Value *cmp = Builder.CreateICmpSLT(old, exprValue);
946         old = Builder.CreateSelect(cmp, old, exprValue);
947         break;
948       }
949     case clast_red_max:
950       {
951         Value *cmp = Builder.CreateICmpSGT(old, exprValue);
952         old = Builder.CreateSelect(cmp, old, exprValue);
953         break;
954       }
955     case clast_red_sum:
956       old = Builder.CreateAdd(old, exprValue);
957       break;
958     }
959   }
960 
961   return old;
962 }
963 
964 ClastExpCodeGen::ClastExpCodeGen(IRBuilder<> &B, CharMapT &IVMap)
965   : Builder(B), IVS(IVMap) {}
966 
967 Value *ClastExpCodeGen::codegen(const clast_expr *e, Type *Ty) {
968   switch(e->type) {
969   case clast_expr_name:
970     return codegen((const clast_name *)e, Ty);
971   case clast_expr_term:
972     return codegen((const clast_term *)e, Ty);
973   case clast_expr_bin:
974     return codegen((const clast_binary *)e, Ty);
975   case clast_expr_red:
976     return codegen((const clast_reduction *)e, Ty);
977   }
978 
979   llvm_unreachable("Unknown clast expression!");
980 }
981 
982 class ClastStmtCodeGen {
983 public:
984   const std::vector<std::string> &getParallelLoops();
985 
986 private:
987   // The Scop we code generate.
988   Scop *S;
989   Pass *P;
990 
991   // The Builder specifies the current location to code generate at.
992   IRBuilder<> &Builder;
993 
994   // Map the Values from the old code to their counterparts in the new code.
995   ValueMapT ValueMap;
996 
997   // clastVars maps from the textual representation of a clast variable to its
998   // current *Value. clast variables are scheduling variables, original
999   // induction variables or parameters. They are used either in loop bounds or
1000   // to define the statement instance that is executed.
1001   //
1002   //   for (s = 0; s < n + 3; ++i)
1003   //     for (t = s; t < m; ++j)
1004   //       Stmt(i = s + 3 * m, j = t);
1005   //
1006   // {s,t,i,j,n,m} is the set of clast variables in this clast.
1007   CharMapT ClastVars;
1008 
1009   // Codegenerator for clast expressions.
1010   ClastExpCodeGen ExpGen;
1011 
1012   // Do we currently generate parallel code?
1013   bool parallelCodeGeneration;
1014 
1015   std::vector<std::string> parallelLoops;
1016 
1017   void codegen(const clast_assignment *a);
1018 
1019   void codegen(const clast_assignment *a, ScopStmt *Statement,
1020                unsigned Dimension, int vectorDim,
1021                std::vector<ValueMapT> *VectorVMap = 0);
1022 
1023   void codegenSubstitutions(const clast_stmt *Assignment,
1024                             ScopStmt *Statement, int vectorDim = 0,
1025                             std::vector<ValueMapT> *VectorVMap = 0);
1026 
1027   void codegen(const clast_user_stmt *u, std::vector<Value*> *IVS = NULL,
1028                const char *iterator = NULL, isl_set *scatteringDomain = 0);
1029 
1030   void codegen(const clast_block *b);
1031 
1032   /// @brief Create a classical sequential loop.
1033   void codegenForSequential(const clast_for *f);
1034 
1035   /// @brief Create OpenMP structure values.
1036   ///
1037   /// Create a list of values that has to be stored into the OpenMP subfuncition
1038   /// structure.
1039   SetVector<Value*> getOMPValues();
1040 
1041   /// @brief Update the internal structures according to a Value Map.
1042   ///
1043   /// @param VMap     A map from old to new values.
1044   /// @param Reverse  If true, we assume the update should be reversed.
1045   void updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
1046                           bool Reverse);
1047 
1048   /// @brief Create an OpenMP parallel for loop.
1049   ///
1050   /// This loop reflects a loop as if it would have been created by an OpenMP
1051   /// statement.
1052   void codegenForOpenMP(const clast_for *f);
1053 
1054   bool isInnermostLoop(const clast_for *f);
1055 
1056   /// @brief Get the number of loop iterations for this loop.
1057   /// @param f The clast for loop to check.
1058   int getNumberOfIterations(const clast_for *f);
1059 
1060   /// @brief Create vector instructions for this loop.
1061   void codegenForVector(const clast_for *f);
1062 
1063   void codegen(const clast_for *f);
1064 
1065   Value *codegen(const clast_equation *eq);
1066 
1067   void codegen(const clast_guard *g);
1068 
1069   void codegen(const clast_stmt *stmt);
1070 
1071   void addParameters(const CloogNames *names);
1072 
1073   IntegerType *getIntPtrTy();
1074 
1075   public:
1076   void codegen(const clast_root *r);
1077 
1078   ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P);
1079 };
1080 }
1081 
1082 IntegerType *ClastStmtCodeGen::getIntPtrTy() {
1083   return P->getAnalysis<TargetData>().getIntPtrType(Builder.getContext());
1084 }
1085 
1086 const std::vector<std::string> &ClastStmtCodeGen::getParallelLoops() {
1087   return parallelLoops;
1088 }
1089 
1090 void ClastStmtCodeGen::codegen(const clast_assignment *a) {
1091   Value *V= ExpGen.codegen(a->RHS, getIntPtrTy());
1092   ClastVars[a->LHS] = V;
1093 }
1094 
1095 void ClastStmtCodeGen::codegen(const clast_assignment *A, ScopStmt *Stmt,
1096                                unsigned Dim, int VectorDim,
1097                                std::vector<ValueMapT> *VectorVMap) {
1098   const PHINode *PN;
1099   Value *RHS;
1100 
1101   assert(!A->LHS && "Statement assignments do not have left hand side");
1102 
1103   PN = Stmt->getInductionVariableForDimension(Dim);
1104   RHS = ExpGen.codegen(A->RHS, Builder.getInt64Ty());
1105   RHS = Builder.CreateTruncOrBitCast(RHS, PN->getType());
1106 
1107   if (VectorVMap)
1108     (*VectorVMap)[VectorDim][PN] = RHS;
1109 
1110   ValueMap[PN] = RHS;
1111 }
1112 
1113 void ClastStmtCodeGen::codegenSubstitutions(const clast_stmt *Assignment,
1114                                              ScopStmt *Statement, int vectorDim,
1115   std::vector<ValueMapT> *VectorVMap) {
1116   int Dimension = 0;
1117 
1118   while (Assignment) {
1119     assert(CLAST_STMT_IS_A(Assignment, stmt_ass)
1120            && "Substitions are expected to be assignments");
1121     codegen((const clast_assignment *)Assignment, Statement, Dimension,
1122             vectorDim, VectorVMap);
1123     Assignment = Assignment->next;
1124     Dimension++;
1125   }
1126 }
1127 
1128 void ClastStmtCodeGen::codegen(const clast_user_stmt *u,
1129                                std::vector<Value*> *IVS , const char *iterator,
1130                                isl_set *Domain) {
1131   ScopStmt *Statement = (ScopStmt *)u->statement->usr;
1132 
1133   if (u->substitutions)
1134     codegenSubstitutions(u->substitutions, Statement);
1135 
1136   int VectorDimensions = IVS ? IVS->size() : 1;
1137 
1138   if (VectorDimensions == 1) {
1139     BlockGenerator::generate(Builder, *Statement, ValueMap, P);
1140     return;
1141   }
1142 
1143   VectorValueMapT VectorMap(VectorDimensions);
1144 
1145   if (IVS) {
1146     assert (u->substitutions && "Substitutions expected!");
1147     int i = 0;
1148     for (std::vector<Value*>::iterator II = IVS->begin(), IE = IVS->end();
1149          II != IE; ++II) {
1150       ClastVars[iterator] = *II;
1151       codegenSubstitutions(u->substitutions, Statement, i, &VectorMap);
1152       i++;
1153     }
1154   }
1155 
1156   VectorBlockGenerator::generate(Builder, *Statement, VectorMap, Domain, P);
1157 }
1158 
1159 void ClastStmtCodeGen::codegen(const clast_block *b) {
1160   if (b->body)
1161     codegen(b->body);
1162 }
1163 
1164 void ClastStmtCodeGen::codegenForSequential(const clast_for *f) {
1165   Value *LowerBound, *UpperBound, *IV, *Stride;
1166   BasicBlock *AfterBB;
1167   Type *IntPtrTy = getIntPtrTy();
1168 
1169   LowerBound = ExpGen.codegen(f->LB, IntPtrTy);
1170   UpperBound = ExpGen.codegen(f->UB, IntPtrTy);
1171   Stride = Builder.getInt(APInt_from_MPZ(f->stride));
1172 
1173   IV = createLoop(LowerBound, UpperBound, Stride, &Builder, P, &AfterBB);
1174 
1175   // Add loop iv to symbols.
1176   ClastVars[f->iterator] = IV;
1177 
1178   if (f->body)
1179     codegen(f->body);
1180 
1181   // Loop is finished, so remove its iv from the live symbols.
1182   ClastVars.erase(f->iterator);
1183   Builder.SetInsertPoint(AfterBB->begin());
1184 }
1185 
1186 SetVector<Value*> ClastStmtCodeGen::getOMPValues() {
1187   SetVector<Value*> Values;
1188 
1189   // The clast variables
1190   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
1191        I != E; I++)
1192     Values.insert(I->second);
1193 
1194   // The memory reference base addresses
1195   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
1196     ScopStmt *Stmt = *SI;
1197     for (SmallVector<MemoryAccess*, 8>::iterator I = Stmt->memacc_begin(),
1198          E = Stmt->memacc_end(); I != E; ++I) {
1199       Value *BaseAddr = const_cast<Value*>((*I)->getBaseAddr());
1200       Values.insert((BaseAddr));
1201     }
1202   }
1203 
1204   return Values;
1205 }
1206 
1207 void ClastStmtCodeGen::updateWithValueMap(OMPGenerator::ValueToValueMapTy &VMap,
1208                                           bool Reverse) {
1209   std::set<Value*> Inserted;
1210 
1211   if (Reverse) {
1212     OMPGenerator::ValueToValueMapTy ReverseMap;
1213 
1214     for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
1215          I != E; ++I)
1216        ReverseMap.insert(std::make_pair(I->second, I->first));
1217 
1218     for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
1219          I != E; I++) {
1220       ClastVars[I->first] = ReverseMap[I->second];
1221       Inserted.insert(I->second);
1222     }
1223 
1224     /// FIXME: At the moment we do not reverse the update of the ValueMap.
1225     ///        This is incomplet, but the failure should be obvious, such that
1226     ///        we can fix this later.
1227     return;
1228   }
1229 
1230   for (CharMapT::iterator I = ClastVars.begin(), E = ClastVars.end();
1231        I != E; I++) {
1232     ClastVars[I->first] = VMap[I->second];
1233     Inserted.insert(I->second);
1234   }
1235 
1236   for (std::map<Value*, Value*>::iterator I = VMap.begin(), E = VMap.end();
1237        I != E; ++I) {
1238     if (Inserted.count(I->first))
1239       continue;
1240 
1241     ValueMap[I->first] = I->second;
1242   }
1243 }
1244 
1245 static void clearDomtree(Function *F, DominatorTree &DT) {
1246   DomTreeNode *N = DT.getNode(&F->getEntryBlock());
1247   std::vector<BasicBlock*> Nodes;
1248   for (po_iterator<DomTreeNode*> I = po_begin(N), E = po_end(N); I != E; ++I)
1249     Nodes.push_back(I->getBlock());
1250 
1251   for (std::vector<BasicBlock*>::iterator I = Nodes.begin(), E = Nodes.end();
1252        I != E; ++I)
1253     DT.eraseNode(*I);
1254 }
1255 
1256 void ClastStmtCodeGen::codegenForOpenMP(const clast_for *For) {
1257   Value *Stride, *LB, *UB, *IV;
1258   BasicBlock::iterator LoopBody;
1259   IntegerType *IntPtrTy = getIntPtrTy();
1260   SetVector<Value*> Values;
1261   OMPGenerator::ValueToValueMapTy VMap;
1262   OMPGenerator OMPGen(Builder, P);
1263 
1264   Stride = Builder.getInt(APInt_from_MPZ(For->stride));
1265   Stride = Builder.CreateSExtOrBitCast(Stride, IntPtrTy);
1266   LB = ExpGen.codegen(For->LB, IntPtrTy);
1267   UB = ExpGen.codegen(For->UB, IntPtrTy);
1268 
1269   Values = getOMPValues();
1270 
1271   IV = OMPGen.createParallelLoop(LB, UB, Stride, Values, VMap, &LoopBody);
1272   BasicBlock::iterator AfterLoop = Builder.GetInsertPoint();
1273   Builder.SetInsertPoint(LoopBody);
1274 
1275   updateWithValueMap(VMap, /* reverse */ false);
1276   ClastVars[For->iterator] = IV;
1277 
1278   if (For->body)
1279     codegen(For->body);
1280 
1281   ClastVars.erase(For->iterator);
1282   updateWithValueMap(VMap, /* reverse */ true);
1283 
1284   clearDomtree((*LoopBody).getParent()->getParent(),
1285                P->getAnalysis<DominatorTree>());
1286 
1287   Builder.SetInsertPoint(AfterLoop);
1288 }
1289 
1290 bool ClastStmtCodeGen::isInnermostLoop(const clast_for *f) {
1291   const clast_stmt *stmt = f->body;
1292 
1293   while (stmt) {
1294     if (!CLAST_STMT_IS_A(stmt, stmt_user))
1295       return false;
1296 
1297     stmt = stmt->next;
1298   }
1299 
1300   return true;
1301 }
1302 
1303 int ClastStmtCodeGen::getNumberOfIterations(const clast_for *f) {
1304   isl_set *loopDomain = isl_set_copy(isl_set_from_cloog_domain(f->domain));
1305   isl_set *tmp = isl_set_copy(loopDomain);
1306 
1307   // Calculate a map similar to the identity map, but with the last input
1308   // and output dimension not related.
1309   //  [i0, i1, i2, i3] -> [i0, i1, i2, o0]
1310   isl_space *Space = isl_set_get_space(loopDomain);
1311   Space = isl_space_drop_outputs(Space,
1312                                  isl_set_dim(loopDomain, isl_dim_set) - 2, 1);
1313   Space = isl_space_map_from_set(Space);
1314   isl_map *identity = isl_map_identity(Space);
1315   identity = isl_map_add_dims(identity, isl_dim_in, 1);
1316   identity = isl_map_add_dims(identity, isl_dim_out, 1);
1317 
1318   isl_map *map = isl_map_from_domain_and_range(tmp, loopDomain);
1319   map = isl_map_intersect(map, identity);
1320 
1321   isl_map *lexmax = isl_map_lexmax(isl_map_copy(map));
1322   isl_map *lexmin = isl_map_lexmin(map);
1323   isl_map *sub = isl_map_sum(lexmax, isl_map_neg(lexmin));
1324 
1325   isl_set *elements = isl_map_range(sub);
1326 
1327   if (!isl_set_is_singleton(elements)) {
1328     isl_set_free(elements);
1329     return -1;
1330   }
1331 
1332   isl_point *p = isl_set_sample_point(elements);
1333 
1334   isl_int v;
1335   isl_int_init(v);
1336   isl_point_get_coordinate(p, isl_dim_set, isl_set_n_dim(loopDomain) - 1, &v);
1337   int numberIterations = isl_int_get_si(v);
1338   isl_int_clear(v);
1339   isl_point_free(p);
1340 
1341   return (numberIterations) / isl_int_get_si(f->stride) + 1;
1342 }
1343 
1344 void ClastStmtCodeGen::codegenForVector(const clast_for *F) {
1345   DEBUG(dbgs() << "Vectorizing loop '" << F->iterator << "'\n";);
1346   int VectorWidth = getNumberOfIterations(F);
1347 
1348   Value *LB = ExpGen.codegen(F->LB, getIntPtrTy());
1349 
1350   APInt Stride = APInt_from_MPZ(F->stride);
1351   IntegerType *LoopIVType = dyn_cast<IntegerType>(LB->getType());
1352   Stride =  Stride.zext(LoopIVType->getBitWidth());
1353   Value *StrideValue = ConstantInt::get(LoopIVType, Stride);
1354 
1355   std::vector<Value*> IVS(VectorWidth);
1356   IVS[0] = LB;
1357 
1358   for (int i = 1; i < VectorWidth; i++)
1359     IVS[i] = Builder.CreateAdd(IVS[i-1], StrideValue, "p_vector_iv");
1360 
1361   isl_set *Domain = isl_set_from_cloog_domain(F->domain);
1362 
1363   // Add loop iv to symbols.
1364   ClastVars[F->iterator] = LB;
1365 
1366   const clast_stmt *Stmt = F->body;
1367 
1368   while (Stmt) {
1369     codegen((const clast_user_stmt *)Stmt, &IVS, F->iterator,
1370             isl_set_copy(Domain));
1371     Stmt = Stmt->next;
1372   }
1373 
1374   // Loop is finished, so remove its iv from the live symbols.
1375   isl_set_free(Domain);
1376   ClastVars.erase(F->iterator);
1377 }
1378 
1379 void ClastStmtCodeGen::codegen(const clast_for *f) {
1380   if ((Vector || OpenMP) && P->getAnalysis<Dependences>().isParallelFor(f)) {
1381     if (Vector && isInnermostLoop(f) && (-1 != getNumberOfIterations(f))
1382         && (getNumberOfIterations(f) <= 16)) {
1383       codegenForVector(f);
1384       return;
1385     }
1386 
1387     if (OpenMP && !parallelCodeGeneration) {
1388       parallelCodeGeneration = true;
1389       parallelLoops.push_back(f->iterator);
1390       codegenForOpenMP(f);
1391       parallelCodeGeneration = false;
1392       return;
1393     }
1394   }
1395 
1396   codegenForSequential(f);
1397 }
1398 
1399 Value *ClastStmtCodeGen::codegen(const clast_equation *eq) {
1400   Value *LHS = ExpGen.codegen(eq->LHS, getIntPtrTy());
1401   Value *RHS = ExpGen.codegen(eq->RHS, getIntPtrTy());
1402   CmpInst::Predicate P;
1403 
1404   if (eq->sign == 0)
1405     P = ICmpInst::ICMP_EQ;
1406   else if (eq->sign > 0)
1407     P = ICmpInst::ICMP_SGE;
1408   else
1409     P = ICmpInst::ICMP_SLE;
1410 
1411   return Builder.CreateICmp(P, LHS, RHS);
1412 }
1413 
1414 void ClastStmtCodeGen::codegen(const clast_guard *g) {
1415   Function *F = Builder.GetInsertBlock()->getParent();
1416   LLVMContext &Context = F->getContext();
1417 
1418   BasicBlock *CondBB = SplitBlock(Builder.GetInsertBlock(),
1419                                       Builder.GetInsertPoint(), P);
1420   CondBB->setName("polly.cond");
1421   BasicBlock *MergeBB = SplitBlock(CondBB, CondBB->begin(), P);
1422   MergeBB->setName("polly.merge");
1423   BasicBlock *ThenBB = BasicBlock::Create(Context, "polly.then", F);
1424 
1425   DominatorTree &DT = P->getAnalysis<DominatorTree>();
1426   DT.addNewBlock(ThenBB, CondBB);
1427   DT.changeImmediateDominator(MergeBB, CondBB);
1428 
1429   CondBB->getTerminator()->eraseFromParent();
1430 
1431   Builder.SetInsertPoint(CondBB);
1432 
1433   Value *Predicate = codegen(&(g->eq[0]));
1434 
1435   for (int i = 1; i < g->n; ++i) {
1436     Value *TmpPredicate = codegen(&(g->eq[i]));
1437     Predicate = Builder.CreateAnd(Predicate, TmpPredicate);
1438   }
1439 
1440   Builder.CreateCondBr(Predicate, ThenBB, MergeBB);
1441   Builder.SetInsertPoint(ThenBB);
1442   Builder.CreateBr(MergeBB);
1443   Builder.SetInsertPoint(ThenBB->begin());
1444 
1445   codegen(g->then);
1446 
1447   Builder.SetInsertPoint(MergeBB->begin());
1448 }
1449 
1450 void ClastStmtCodeGen::codegen(const clast_stmt *stmt) {
1451   if	    (CLAST_STMT_IS_A(stmt, stmt_root))
1452     assert(false && "No second root statement expected");
1453   else if (CLAST_STMT_IS_A(stmt, stmt_ass))
1454     codegen((const clast_assignment *)stmt);
1455   else if (CLAST_STMT_IS_A(stmt, stmt_user))
1456     codegen((const clast_user_stmt *)stmt);
1457   else if (CLAST_STMT_IS_A(stmt, stmt_block))
1458     codegen((const clast_block *)stmt);
1459   else if (CLAST_STMT_IS_A(stmt, stmt_for))
1460     codegen((const clast_for *)stmt);
1461   else if (CLAST_STMT_IS_A(stmt, stmt_guard))
1462     codegen((const clast_guard *)stmt);
1463 
1464   if (stmt->next)
1465     codegen(stmt->next);
1466 }
1467 
1468 void ClastStmtCodeGen::addParameters(const CloogNames *names) {
1469   SCEVExpander Rewriter(P->getAnalysis<ScalarEvolution>(), "polly");
1470 
1471   int i = 0;
1472   for (Scop::param_iterator PI = S->param_begin(), PE = S->param_end();
1473        PI != PE; ++PI) {
1474     assert(i < names->nb_parameters && "Not enough parameter names");
1475 
1476     const SCEV *Param = *PI;
1477     Type *Ty = Param->getType();
1478 
1479     Instruction *insertLocation = --(Builder.GetInsertBlock()->end());
1480     Value *V = Rewriter.expandCodeFor(Param, Ty, insertLocation);
1481     ClastVars[names->parameters[i]] = V;
1482 
1483     ++i;
1484   }
1485 }
1486 
1487 void ClastStmtCodeGen::codegen(const clast_root *r) {
1488   addParameters(r->names);
1489 
1490   parallelCodeGeneration = false;
1491 
1492   const clast_stmt *stmt = (const clast_stmt*) r;
1493   if (stmt->next)
1494     codegen(stmt->next);
1495 }
1496 
1497 ClastStmtCodeGen::ClastStmtCodeGen(Scop *scop, IRBuilder<> &B, Pass *P) :
1498     S(scop), P(P), Builder(B), ExpGen(Builder, ClastVars) {}
1499 
1500 namespace {
1501 class CodeGeneration : public ScopPass {
1502   Region *region;
1503   Scop *S;
1504   DominatorTree *DT;
1505   RegionInfo *RI;
1506 
1507   std::vector<std::string> parallelLoops;
1508 
1509   public:
1510   static char ID;
1511 
1512   CodeGeneration() : ScopPass(ID) {}
1513 
1514   // Split the entry edge of the region and generate a new basic block on this
1515   // edge. This function also updates ScopInfo and RegionInfo.
1516   //
1517   // @param region The region where the entry edge will be splitted.
1518   BasicBlock *splitEdgeAdvanced(Region *region) {
1519     BasicBlock *newBlock;
1520     BasicBlock *splitBlock;
1521 
1522     newBlock = SplitEdge(region->getEnteringBlock(), region->getEntry(), this);
1523 
1524     if (DT->dominates(region->getEntry(), newBlock)) {
1525       BasicBlock *OldBlock = region->getEntry();
1526       std::string OldName = OldBlock->getName();
1527 
1528       // Update ScopInfo.
1529       for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI)
1530         if ((*SI)->getBasicBlock() == OldBlock) {
1531           (*SI)->setBasicBlock(newBlock);
1532           break;
1533         }
1534 
1535       // Update RegionInfo.
1536       splitBlock = OldBlock;
1537       OldBlock->setName("polly.split");
1538       newBlock->setName(OldName);
1539       region->replaceEntry(newBlock);
1540       RI->setRegionFor(newBlock, region);
1541     } else {
1542       RI->setRegionFor(newBlock, region->getParent());
1543       splitBlock = newBlock;
1544     }
1545 
1546     return splitBlock;
1547   }
1548 
1549   // Create a split block that branches either to the old code or to a new basic
1550   // block where the new code can be inserted.
1551   //
1552   // @param Builder A builder that will be set to point to a basic block, where
1553   //                the new code can be generated.
1554   // @return The split basic block.
1555   BasicBlock *addSplitAndStartBlock(IRBuilder<> *Builder) {
1556     BasicBlock *StartBlock, *SplitBlock;
1557 
1558     SplitBlock = splitEdgeAdvanced(region);
1559     SplitBlock->setName("polly.split_new_and_old");
1560     Function *F = SplitBlock->getParent();
1561     StartBlock = BasicBlock::Create(F->getContext(), "polly.start", F);
1562     SplitBlock->getTerminator()->eraseFromParent();
1563     Builder->SetInsertPoint(SplitBlock);
1564     Builder->CreateCondBr(Builder->getTrue(), StartBlock, region->getEntry());
1565     DT->addNewBlock(StartBlock, SplitBlock);
1566     Builder->SetInsertPoint(StartBlock);
1567     return SplitBlock;
1568   }
1569 
1570   // Merge the control flow of the newly generated code with the existing code.
1571   //
1572   // @param SplitBlock The basic block where the control flow was split between
1573   //                   old and new version of the Scop.
1574   // @param Builder    An IRBuilder that points to the last instruction of the
1575   //                   newly generated code.
1576   void mergeControlFlow(BasicBlock *SplitBlock, IRBuilder<> *Builder) {
1577     BasicBlock *MergeBlock;
1578     Region *R = region;
1579 
1580     if (R->getExit()->getSinglePredecessor())
1581       // No splitEdge required.  A block with a single predecessor cannot have
1582       // PHI nodes that would complicate life.
1583       MergeBlock = R->getExit();
1584     else {
1585       MergeBlock = SplitEdge(R->getExitingBlock(), R->getExit(), this);
1586       // SplitEdge will never split R->getExit(), as R->getExit() has more than
1587       // one predecessor. Hence, mergeBlock is always a newly generated block.
1588       R->replaceExit(MergeBlock);
1589     }
1590 
1591     Builder->CreateBr(MergeBlock);
1592     MergeBlock->setName("polly.merge_new_and_old");
1593 
1594     if (DT->dominates(SplitBlock, MergeBlock))
1595       DT->changeImmediateDominator(MergeBlock, SplitBlock);
1596   }
1597 
1598   bool runOnScop(Scop &scop) {
1599     S = &scop;
1600     region = &S->getRegion();
1601     DT = &getAnalysis<DominatorTree>();
1602     RI = &getAnalysis<RegionInfo>();
1603 
1604     parallelLoops.clear();
1605 
1606     assert(region->isSimple() && "Only simple regions are supported");
1607 
1608     // In the CFG the optimized code of the SCoP is generated next to the
1609     // original code. Both the new and the original version of the code remain
1610     // in the CFG. A branch statement decides which version is executed.
1611     // For now, we always execute the new version (the old one is dead code
1612     // eliminated by the cleanup passes). In the future we may decide to execute
1613     // the new version only if certain run time checks succeed. This will be
1614     // useful to support constructs for which we cannot prove all assumptions at
1615     // compile time.
1616     //
1617     // Before transformation:
1618     //
1619     //                        bb0
1620     //                         |
1621     //                     orig_scop
1622     //                         |
1623     //                        bb1
1624     //
1625     // After transformation:
1626     //                        bb0
1627     //                         |
1628     //                  polly.splitBlock
1629     //                     /       \.
1630     //                     |     startBlock
1631     //                     |        |
1632     //               orig_scop   new_scop
1633     //                     \      /
1634     //                      \    /
1635     //                        bb1 (joinBlock)
1636     IRBuilder<> builder(region->getEntry());
1637 
1638     // The builder will be set to startBlock.
1639     BasicBlock *splitBlock = addSplitAndStartBlock(&builder);
1640     BasicBlock *StartBlock = builder.GetInsertBlock();
1641 
1642     mergeControlFlow(splitBlock, &builder);
1643     builder.SetInsertPoint(StartBlock->begin());
1644 
1645     ClastStmtCodeGen CodeGen(S, builder, this);
1646     CloogInfo &C = getAnalysis<CloogInfo>();
1647     CodeGen.codegen(C.getClast());
1648 
1649     parallelLoops.insert(parallelLoops.begin(),
1650                          CodeGen.getParallelLoops().begin(),
1651                          CodeGen.getParallelLoops().end());
1652 
1653     return true;
1654   }
1655 
1656   virtual void printScop(raw_ostream &OS) const {
1657     for (std::vector<std::string>::const_iterator PI = parallelLoops.begin(),
1658          PE = parallelLoops.end(); PI != PE; ++PI)
1659       OS << "Parallel loop with iterator '" << *PI << "' generated\n";
1660   }
1661 
1662   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1663     AU.addRequired<CloogInfo>();
1664     AU.addRequired<Dependences>();
1665     AU.addRequired<DominatorTree>();
1666     AU.addRequired<RegionInfo>();
1667     AU.addRequired<ScalarEvolution>();
1668     AU.addRequired<ScopDetection>();
1669     AU.addRequired<ScopInfo>();
1670     AU.addRequired<TargetData>();
1671 
1672     AU.addPreserved<CloogInfo>();
1673     AU.addPreserved<Dependences>();
1674 
1675     // FIXME: We do not create LoopInfo for the newly generated loops.
1676     AU.addPreserved<LoopInfo>();
1677     AU.addPreserved<DominatorTree>();
1678     AU.addPreserved<ScopDetection>();
1679     AU.addPreserved<ScalarEvolution>();
1680 
1681     // FIXME: We do not yet add regions for the newly generated code to the
1682     //        region tree.
1683     AU.addPreserved<RegionInfo>();
1684     AU.addPreserved<TempScopInfo>();
1685     AU.addPreserved<ScopInfo>();
1686     AU.addPreservedID(IndependentBlocksID);
1687   }
1688 };
1689 }
1690 
1691 char CodeGeneration::ID = 1;
1692 
1693 INITIALIZE_PASS_BEGIN(CodeGeneration, "polly-codegen",
1694                       "Polly - Create LLVM-IR from SCoPs", false, false)
1695 INITIALIZE_PASS_DEPENDENCY(CloogInfo)
1696 INITIALIZE_PASS_DEPENDENCY(Dependences)
1697 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
1698 INITIALIZE_PASS_DEPENDENCY(RegionInfo)
1699 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1700 INITIALIZE_PASS_DEPENDENCY(ScopDetection)
1701 INITIALIZE_PASS_DEPENDENCY(TargetData)
1702 INITIALIZE_PASS_END(CodeGeneration, "polly-codegen",
1703                       "Polly - Create LLVM-IR from SCoPs", false, false)
1704 
1705 Pass *polly::createCodeGenerationPass() {
1706   return new CodeGeneration();
1707 }
1708