13b11a16aSHongbin Zheng //===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
23b11a16aSHongbin Zheng //
33b11a16aSHongbin Zheng //                     The LLVM Compiler Infrastructure
43b11a16aSHongbin Zheng //
53b11a16aSHongbin Zheng // This file is distributed under the University of Illinois Open Source
63b11a16aSHongbin Zheng // License. See LICENSE.TXT for details.
73b11a16aSHongbin Zheng //
83b11a16aSHongbin Zheng //===----------------------------------------------------------------------===//
93b11a16aSHongbin Zheng //
103b11a16aSHongbin Zheng // This file implements the BlockGenerator and VectorBlockGenerator classes,
113b11a16aSHongbin Zheng // which generate sequential code and vectorized code for a polyhedral
123b11a16aSHongbin Zheng // statement, respectively.
133b11a16aSHongbin Zheng //
143b11a16aSHongbin Zheng //===----------------------------------------------------------------------===//
153b11a16aSHongbin Zheng 
163b11a16aSHongbin Zheng #include "polly/ScopInfo.h"
178a846610SHongbin Zheng #include "polly/CodeGen/BlockGenerators.h"
183b11a16aSHongbin Zheng #include "polly/Support/GICHelper.h"
193b11a16aSHongbin Zheng 
20*e71c6ab5STobias Grosser #include "llvm/Analysis/LoopInfo.h"
21*e71c6ab5STobias Grosser #include "llvm/Analysis/ScalarEvolution.h"
22*e71c6ab5STobias Grosser #include "llvm/Analysis/ScalarEvolutionExpander.h"
233b11a16aSHongbin Zheng #include "llvm/Transforms/Utils/BasicBlockUtils.h"
243b11a16aSHongbin Zheng #include "llvm/Support/CommandLine.h"
253b11a16aSHongbin Zheng 
263b11a16aSHongbin Zheng #include "isl/aff.h"
273b11a16aSHongbin Zheng #include "isl/set.h"
283b11a16aSHongbin Zheng 
293b11a16aSHongbin Zheng using namespace llvm;
303b11a16aSHongbin Zheng using namespace polly;
313b11a16aSHongbin Zheng 
323b11a16aSHongbin Zheng static cl::opt<bool>
333b11a16aSHongbin Zheng Aligned("enable-polly-aligned",
343b11a16aSHongbin Zheng        cl::desc("Assumed aligned memory accesses."), cl::Hidden,
353b11a16aSHongbin Zheng        cl::value_desc("OpenMP code generation enabled if true"),
363b11a16aSHongbin Zheng        cl::init(false), cl::ZeroOrMore);
373b11a16aSHongbin Zheng 
383b11a16aSHongbin Zheng static cl::opt<bool>
393b11a16aSHongbin Zheng GroupedUnrolling("enable-polly-grouped-unroll",
403b11a16aSHongbin Zheng                  cl::desc("Perform grouped unrolling, but don't generate SIMD "
413b11a16aSHongbin Zheng                           "instuctions"), cl::Hidden, cl::init(false),
423b11a16aSHongbin Zheng                  cl::ZeroOrMore);
43*e71c6ab5STobias Grosser 
44*e71c6ab5STobias Grosser static cl::opt<bool>
45*e71c6ab5STobias Grosser SCEVCodegen("polly-codegen-scev",
46*e71c6ab5STobias Grosser             cl::desc("Use SCEV based code generation."), cl::Hidden,
47*e71c6ab5STobias Grosser             cl::init(false), cl::ZeroOrMore);
48*e71c6ab5STobias Grosser 
49*e71c6ab5STobias Grosser /// The SCEVRewriter takes a scalar evolution expression and updates the
50*e71c6ab5STobias Grosser /// following components:
51*e71c6ab5STobias Grosser ///
52*e71c6ab5STobias Grosser /// - SCEVUnknown
53*e71c6ab5STobias Grosser ///
54*e71c6ab5STobias Grosser ///   Values referenced in SCEVUnknown subexpressions are looked up in
55*e71c6ab5STobias Grosser ///   two Value to Value maps (GlobalMap and BBMap). If they are found they are
56*e71c6ab5STobias Grosser ///   replaced by a reference to the value they map to.
57*e71c6ab5STobias Grosser ///
58*e71c6ab5STobias Grosser /// - SCEVAddRecExpr
59*e71c6ab5STobias Grosser ///
60*e71c6ab5STobias Grosser ///   Based on a Loop -> Value map {Loop_1: %Value}, an expression
61*e71c6ab5STobias Grosser ///   {%Base, +, %Step}<Loop_1> is rewritten to %Base + %Value * %Step.
62*e71c6ab5STobias Grosser ///   AddRecExpr's with more than two operands can not be translated.
63*e71c6ab5STobias Grosser ///
64*e71c6ab5STobias Grosser ///   FIXME: The comment above is not yet reality. At the moment we derive
65*e71c6ab5STobias Grosser ///   %Value by looking up the canonical IV of the loop and by defining
66*e71c6ab5STobias Grosser ///   %Value = GlobalMap[%IV]. This needs to be changed to remove the need for
67*e71c6ab5STobias Grosser ///   canonical induction variables.
68*e71c6ab5STobias Grosser ///
69*e71c6ab5STobias Grosser ///
70*e71c6ab5STobias Grosser /// How can this be used?
71*e71c6ab5STobias Grosser /// ====================
72*e71c6ab5STobias Grosser ///
73*e71c6ab5STobias Grosser /// SCEVRewrite based code generation works on virtually independent blocks.
74*e71c6ab5STobias Grosser /// This means we do not run the independent blocks pass to rewrite scalar
75*e71c6ab5STobias Grosser /// instructions, but just ignore instructions that we can analyze with scalar
76*e71c6ab5STobias Grosser /// evolution. Virtually independent blocks are blocks that only reference the
77*e71c6ab5STobias Grosser /// following values:
78*e71c6ab5STobias Grosser ///
79*e71c6ab5STobias Grosser /// o Values calculated within a basic block
80*e71c6ab5STobias Grosser /// o Values representable by SCEV
81*e71c6ab5STobias Grosser ///
82*e71c6ab5STobias Grosser /// During code generation we can ignore all instructions:
83*e71c6ab5STobias Grosser ///
84*e71c6ab5STobias Grosser /// - Ignore all instructions except:
85*e71c6ab5STobias Grosser ///   - Load instructions
86*e71c6ab5STobias Grosser ///   - Instructions that reference operands already calculated within the
87*e71c6ab5STobias Grosser ///     basic block.
88*e71c6ab5STobias Grosser ///   - Store instructions
89*e71c6ab5STobias Grosser struct SCEVRewriter : public SCEVVisitor<SCEVRewriter, const SCEV*> {
90*e71c6ab5STobias Grosser public:
91*e71c6ab5STobias Grosser   static const SCEV *rewrite(const SCEV *scev, Scop &S, ScalarEvolution &SE,
92*e71c6ab5STobias Grosser                              ValueMapT &GlobalMap,  ValueMapT &BBMap) {
93*e71c6ab5STobias Grosser     SCEVRewriter Rewriter(S, SE, GlobalMap, BBMap);
94*e71c6ab5STobias Grosser     return Rewriter.visit(scev);
95*e71c6ab5STobias Grosser   }
96*e71c6ab5STobias Grosser 
97*e71c6ab5STobias Grosser   SCEVRewriter(Scop &S, ScalarEvolution &SE, ValueMapT &GlobalMap,
98*e71c6ab5STobias Grosser                ValueMapT &BBMap) : S(S), SE(SE), GlobalMap(GlobalMap),
99*e71c6ab5STobias Grosser                BBMap(BBMap) {}
100*e71c6ab5STobias Grosser 
101*e71c6ab5STobias Grosser   const SCEV *visit(const SCEV *Expr) {
102*e71c6ab5STobias Grosser     // FIXME: The parameter handling is incorrect.
103*e71c6ab5STobias Grosser     //
104*e71c6ab5STobias Grosser     // Polly does only detect parameters in Access function and loop iteration
105*e71c6ab5STobias Grosser     // counters, but it does not get parameters that are just used by
106*e71c6ab5STobias Grosser     // instructions within the basic block.
107*e71c6ab5STobias Grosser     //
108*e71c6ab5STobias Grosser     // There are two options to solve this:
109*e71c6ab5STobias Grosser     //  o Iterate over all instructions of the SCoP and find the actual
110*e71c6ab5STobias Grosser     //    parameters.
111*e71c6ab5STobias Grosser     //  o Just check within the SCEVRewriter if Values lay outside of the SCoP
112*e71c6ab5STobias Grosser     //    and detect parameters on the fly.
113*e71c6ab5STobias Grosser     //
114*e71c6ab5STobias Grosser     // This is especially important for OpenMP and GPGPU code generation, as
115*e71c6ab5STobias Grosser     // they require us to detect and possibly rewrite the corresponding
116*e71c6ab5STobias Grosser     // parameters.
117*e71c6ab5STobias Grosser     if (isl_id *Id = S.getIdForParam(Expr)) {
118*e71c6ab5STobias Grosser       isl_id_free(Id);
119*e71c6ab5STobias Grosser       return Expr;
120*e71c6ab5STobias Grosser     }
121*e71c6ab5STobias Grosser 
122*e71c6ab5STobias Grosser 
123*e71c6ab5STobias Grosser     return SCEVVisitor<SCEVRewriter, const SCEV*>::visit(Expr);
124*e71c6ab5STobias Grosser   }
125*e71c6ab5STobias Grosser 
126*e71c6ab5STobias Grosser   const SCEV *visitConstant(const SCEVConstant *Constant) {
127*e71c6ab5STobias Grosser     return Constant;
128*e71c6ab5STobias Grosser   }
129*e71c6ab5STobias Grosser 
130*e71c6ab5STobias Grosser   const SCEV *visitTruncateExpr(const SCEVTruncateExpr *Expr) {
131*e71c6ab5STobias Grosser     const SCEV *Operand = visit(Expr->getOperand());
132*e71c6ab5STobias Grosser     return SE.getTruncateExpr(Operand, Expr->getType());
133*e71c6ab5STobias Grosser   }
134*e71c6ab5STobias Grosser 
135*e71c6ab5STobias Grosser   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
136*e71c6ab5STobias Grosser     const SCEV *Operand = visit(Expr->getOperand());
137*e71c6ab5STobias Grosser     return SE.getZeroExtendExpr(Operand, Expr->getType());
138*e71c6ab5STobias Grosser   }
139*e71c6ab5STobias Grosser 
140*e71c6ab5STobias Grosser   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
141*e71c6ab5STobias Grosser     const SCEV *Operand = visit(Expr->getOperand());
142*e71c6ab5STobias Grosser     return SE.getSignExtendExpr(Operand, Expr->getType());
143*e71c6ab5STobias Grosser   }
144*e71c6ab5STobias Grosser 
145*e71c6ab5STobias Grosser   const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
146*e71c6ab5STobias Grosser     SmallVector<const SCEV *, 2> Operands;
147*e71c6ab5STobias Grosser     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
148*e71c6ab5STobias Grosser       const SCEV *Operand = visit(Expr->getOperand(i));
149*e71c6ab5STobias Grosser       Operands.push_back(Operand);
150*e71c6ab5STobias Grosser     }
151*e71c6ab5STobias Grosser 
152*e71c6ab5STobias Grosser     return SE.getAddExpr(Operands);
153*e71c6ab5STobias Grosser   }
154*e71c6ab5STobias Grosser 
155*e71c6ab5STobias Grosser   const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
156*e71c6ab5STobias Grosser     SmallVector<const SCEV *, 2> Operands;
157*e71c6ab5STobias Grosser     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
158*e71c6ab5STobias Grosser       const SCEV *Operand = visit(Expr->getOperand(i));
159*e71c6ab5STobias Grosser       Operands.push_back(Operand);
160*e71c6ab5STobias Grosser     }
161*e71c6ab5STobias Grosser 
162*e71c6ab5STobias Grosser     return SE.getMulExpr(Operands);
163*e71c6ab5STobias Grosser   }
164*e71c6ab5STobias Grosser 
165*e71c6ab5STobias Grosser   const SCEV *visitUDivExpr(const SCEVUDivExpr *Expr) {
166*e71c6ab5STobias Grosser     return SE.getUDivExpr(visit(Expr->getLHS()), visit(Expr->getRHS()));
167*e71c6ab5STobias Grosser   }
168*e71c6ab5STobias Grosser 
169*e71c6ab5STobias Grosser   // Return a new induction variable if the loop is within the original SCoP
170*e71c6ab5STobias Grosser   // or NULL otherwise.
171*e71c6ab5STobias Grosser   Value *getNewIV(const Loop *L) {
172*e71c6ab5STobias Grosser     Value *IV = L->getCanonicalInductionVariable();
173*e71c6ab5STobias Grosser     if (!IV)
174*e71c6ab5STobias Grosser       return NULL;
175*e71c6ab5STobias Grosser 
176*e71c6ab5STobias Grosser     ValueMapT::iterator NewIV = GlobalMap.find(IV);
177*e71c6ab5STobias Grosser 
178*e71c6ab5STobias Grosser     if (NewIV == GlobalMap.end())
179*e71c6ab5STobias Grosser       return NULL;
180*e71c6ab5STobias Grosser 
181*e71c6ab5STobias Grosser     return NewIV->second;
182*e71c6ab5STobias Grosser   }
183*e71c6ab5STobias Grosser 
184*e71c6ab5STobias Grosser   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
185*e71c6ab5STobias Grosser     Value *IV;
186*e71c6ab5STobias Grosser 
187*e71c6ab5STobias Grosser     IV = getNewIV(Expr->getLoop());
188*e71c6ab5STobias Grosser 
189*e71c6ab5STobias Grosser     // The IV is not within the GlobalMaps. So do not rewrite it and also do
190*e71c6ab5STobias Grosser     // not rewrite any descendants.
191*e71c6ab5STobias Grosser     if (!IV)
192*e71c6ab5STobias Grosser       return Expr;
193*e71c6ab5STobias Grosser 
194*e71c6ab5STobias Grosser     assert(Expr->getNumOperands() == 2
195*e71c6ab5STobias Grosser           && "An AddRecExpr with more than two operands can not be rewritten.");
196*e71c6ab5STobias Grosser 
197*e71c6ab5STobias Grosser     const SCEV *Base, *Step, *IVExpr, *Product;
198*e71c6ab5STobias Grosser 
199*e71c6ab5STobias Grosser     Base = visit(Expr->getStart());
200*e71c6ab5STobias Grosser     Step = visit(Expr->getOperand(1));
201*e71c6ab5STobias Grosser     IVExpr = SE.getUnknown(IV);
202*e71c6ab5STobias Grosser     IVExpr = SE.getTruncateOrSignExtend(IVExpr, Step->getType());
203*e71c6ab5STobias Grosser     Product = SE.getMulExpr(Step, IVExpr);
204*e71c6ab5STobias Grosser 
205*e71c6ab5STobias Grosser     return SE.getAddExpr(Base, Product);
206*e71c6ab5STobias Grosser   }
207*e71c6ab5STobias Grosser 
208*e71c6ab5STobias Grosser   const SCEV *visitSMaxExpr(const SCEVSMaxExpr *Expr) {
209*e71c6ab5STobias Grosser     SmallVector<const SCEV *, 2> Operands;
210*e71c6ab5STobias Grosser     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
211*e71c6ab5STobias Grosser       const SCEV *Operand = visit(Expr->getOperand(i));
212*e71c6ab5STobias Grosser       Operands.push_back(Operand);
213*e71c6ab5STobias Grosser     }
214*e71c6ab5STobias Grosser 
215*e71c6ab5STobias Grosser     return SE.getSMaxExpr(Operands);
216*e71c6ab5STobias Grosser   }
217*e71c6ab5STobias Grosser 
218*e71c6ab5STobias Grosser   const SCEV *visitUMaxExpr(const SCEVUMaxExpr *Expr) {
219*e71c6ab5STobias Grosser     SmallVector<const SCEV *, 2> Operands;
220*e71c6ab5STobias Grosser     for (int i = 0, e = Expr->getNumOperands(); i < e; ++i) {
221*e71c6ab5STobias Grosser       const SCEV *Operand = visit(Expr->getOperand(i));
222*e71c6ab5STobias Grosser       Operands.push_back(Operand);
223*e71c6ab5STobias Grosser     }
224*e71c6ab5STobias Grosser 
225*e71c6ab5STobias Grosser     return SE.getUMaxExpr(Operands);
226*e71c6ab5STobias Grosser   }
227*e71c6ab5STobias Grosser 
228*e71c6ab5STobias Grosser   const SCEV *visitUnknown(const SCEVUnknown *Expr) {
229*e71c6ab5STobias Grosser     Value *V = Expr->getValue();
230*e71c6ab5STobias Grosser 
231*e71c6ab5STobias Grosser     if (GlobalMap.count(V))
232*e71c6ab5STobias Grosser       return SE.getUnknown(GlobalMap[V]);
233*e71c6ab5STobias Grosser 
234*e71c6ab5STobias Grosser     if (BBMap.count(V))
235*e71c6ab5STobias Grosser       return SE.getUnknown(BBMap[V]);
236*e71c6ab5STobias Grosser 
237*e71c6ab5STobias Grosser     return Expr;
238*e71c6ab5STobias Grosser   }
239*e71c6ab5STobias Grosser 
240*e71c6ab5STobias Grosser private:
241*e71c6ab5STobias Grosser   Scop &S;
242*e71c6ab5STobias Grosser   ScalarEvolution &SE;
243*e71c6ab5STobias Grosser   ValueMapT &GlobalMap;
244*e71c6ab5STobias Grosser   ValueMapT &BBMap;
245*e71c6ab5STobias Grosser };
246*e71c6ab5STobias Grosser 
247*e71c6ab5STobias Grosser 
2483b11a16aSHongbin Zheng // Helper class to generate memory location.
2493b11a16aSHongbin Zheng namespace {
2503b11a16aSHongbin Zheng class IslGenerator {
2513b11a16aSHongbin Zheng public:
2523b11a16aSHongbin Zheng   IslGenerator(IRBuilder<> &Builder, std::vector<Value *> &IVS) :
2533b11a16aSHongbin Zheng     Builder(Builder), IVS(IVS) {}
2543b11a16aSHongbin Zheng   Value *generateIslInt(__isl_take isl_int Int);
2553b11a16aSHongbin Zheng   Value *generateIslAff(__isl_take isl_aff *Aff);
2563b11a16aSHongbin Zheng   Value *generateIslPwAff(__isl_take isl_pw_aff *PwAff);
2573b11a16aSHongbin Zheng 
2583b11a16aSHongbin Zheng private:
2593b11a16aSHongbin Zheng   typedef struct {
2603b11a16aSHongbin Zheng     Value *Result;
2613b11a16aSHongbin Zheng     class IslGenerator *Generator;
2623b11a16aSHongbin Zheng   } IslGenInfo;
2633b11a16aSHongbin Zheng 
2643b11a16aSHongbin Zheng   IRBuilder<> &Builder;
2653b11a16aSHongbin Zheng   std::vector<Value *> &IVS;
2663b11a16aSHongbin Zheng   static int mergeIslAffValues(__isl_take isl_set *Set,
2673b11a16aSHongbin Zheng                                __isl_take isl_aff *Aff, void *User);
2683b11a16aSHongbin Zheng };
2693b11a16aSHongbin Zheng }
2703b11a16aSHongbin Zheng 
2713b11a16aSHongbin Zheng 
2723b11a16aSHongbin Zheng Value *IslGenerator::generateIslInt(isl_int Int) {
2733b11a16aSHongbin Zheng   mpz_t IntMPZ;
2743b11a16aSHongbin Zheng   mpz_init(IntMPZ);
2753b11a16aSHongbin Zheng   isl_int_get_gmp(Int, IntMPZ);
2763b11a16aSHongbin Zheng   Value *IntValue = Builder.getInt(APInt_from_MPZ(IntMPZ));
2773b11a16aSHongbin Zheng   mpz_clear(IntMPZ);
2783b11a16aSHongbin Zheng   return IntValue;
2793b11a16aSHongbin Zheng }
2803b11a16aSHongbin Zheng 
2813b11a16aSHongbin Zheng Value *IslGenerator::generateIslAff(__isl_take isl_aff *Aff) {
2823b11a16aSHongbin Zheng   Value *Result;
2833b11a16aSHongbin Zheng   Value *ConstValue;
2843b11a16aSHongbin Zheng   isl_int ConstIsl;
2853b11a16aSHongbin Zheng 
2863b11a16aSHongbin Zheng   isl_int_init(ConstIsl);
2873b11a16aSHongbin Zheng   isl_aff_get_constant(Aff, &ConstIsl);
2883b11a16aSHongbin Zheng   ConstValue = generateIslInt(ConstIsl);
2893b11a16aSHongbin Zheng   Type *Ty = Builder.getInt64Ty();
2903b11a16aSHongbin Zheng 
2913b11a16aSHongbin Zheng   // FIXME: We should give the constant and coefficients the right type. Here
2923b11a16aSHongbin Zheng   // we force it into i64.
2933b11a16aSHongbin Zheng   Result = Builder.CreateSExtOrBitCast(ConstValue, Ty);
2943b11a16aSHongbin Zheng 
2953b11a16aSHongbin Zheng   unsigned int NbInputDims = isl_aff_dim(Aff, isl_dim_in);
2963b11a16aSHongbin Zheng 
2973b11a16aSHongbin Zheng   assert((IVS.size() == NbInputDims) && "The Dimension of Induction Variables"
2983b11a16aSHongbin Zheng          "must match the dimension of the affine space.");
2993b11a16aSHongbin Zheng 
3003b11a16aSHongbin Zheng   isl_int CoefficientIsl;
3013b11a16aSHongbin Zheng   isl_int_init(CoefficientIsl);
3023b11a16aSHongbin Zheng 
3033b11a16aSHongbin Zheng   for (unsigned int i = 0; i < NbInputDims; ++i) {
3043b11a16aSHongbin Zheng     Value *CoefficientValue;
3053b11a16aSHongbin Zheng     isl_aff_get_coefficient(Aff, isl_dim_in, i, &CoefficientIsl);
3063b11a16aSHongbin Zheng 
3073b11a16aSHongbin Zheng     if (isl_int_is_zero(CoefficientIsl))
3083b11a16aSHongbin Zheng       continue;
3093b11a16aSHongbin Zheng 
3103b11a16aSHongbin Zheng     CoefficientValue = generateIslInt(CoefficientIsl);
3113b11a16aSHongbin Zheng     CoefficientValue = Builder.CreateIntCast(CoefficientValue, Ty, true);
3123b11a16aSHongbin Zheng     Value *IV = Builder.CreateIntCast(IVS[i], Ty, true);
3133b11a16aSHongbin Zheng     Value *PAdd = Builder.CreateMul(CoefficientValue, IV, "p_mul_coeff");
3143b11a16aSHongbin Zheng     Result = Builder.CreateAdd(Result, PAdd, "p_sum_coeff");
3153b11a16aSHongbin Zheng   }
3163b11a16aSHongbin Zheng 
3173b11a16aSHongbin Zheng   isl_int_clear(CoefficientIsl);
3183b11a16aSHongbin Zheng   isl_int_clear(ConstIsl);
3193b11a16aSHongbin Zheng   isl_aff_free(Aff);
3203b11a16aSHongbin Zheng 
3213b11a16aSHongbin Zheng   return Result;
3223b11a16aSHongbin Zheng }
3233b11a16aSHongbin Zheng 
3243b11a16aSHongbin Zheng int IslGenerator::mergeIslAffValues(__isl_take isl_set *Set,
3253b11a16aSHongbin Zheng                                     __isl_take isl_aff *Aff, void *User) {
3263b11a16aSHongbin Zheng   IslGenInfo *GenInfo = (IslGenInfo *)User;
3273b11a16aSHongbin Zheng 
3283b11a16aSHongbin Zheng   assert((GenInfo->Result == NULL) && "Result is already set."
3293b11a16aSHongbin Zheng          "Currently only single isl_aff is supported");
3303b11a16aSHongbin Zheng   assert(isl_set_plain_is_universe(Set)
3313b11a16aSHongbin Zheng          && "Code generation failed because the set is not universe");
3323b11a16aSHongbin Zheng 
3333b11a16aSHongbin Zheng   GenInfo->Result = GenInfo->Generator->generateIslAff(Aff);
3343b11a16aSHongbin Zheng 
3353b11a16aSHongbin Zheng   isl_set_free(Set);
3363b11a16aSHongbin Zheng   return 0;
3373b11a16aSHongbin Zheng }
3383b11a16aSHongbin Zheng 
3393b11a16aSHongbin Zheng Value *IslGenerator::generateIslPwAff(__isl_take isl_pw_aff *PwAff) {
3403b11a16aSHongbin Zheng   IslGenInfo User;
3413b11a16aSHongbin Zheng   User.Result = NULL;
3423b11a16aSHongbin Zheng   User.Generator = this;
3433b11a16aSHongbin Zheng   isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &User);
3443b11a16aSHongbin Zheng   assert(User.Result && "Code generation for isl_pw_aff failed");
3453b11a16aSHongbin Zheng 
3463b11a16aSHongbin Zheng   isl_pw_aff_free(PwAff);
3473b11a16aSHongbin Zheng   return User.Result;
3483b11a16aSHongbin Zheng }
3493b11a16aSHongbin Zheng 
3503b11a16aSHongbin Zheng 
3513b11a16aSHongbin Zheng BlockGenerator::BlockGenerator(IRBuilder<> &B, ScopStmt &Stmt, Pass *P):
352*e71c6ab5STobias Grosser   Builder(B), Statement(Stmt), P(P), SE(P->getAnalysis<ScalarEvolution>()) {}
353*e71c6ab5STobias Grosser 
354*e71c6ab5STobias Grosser bool BlockGenerator::isSCEVIgnore(const Instruction *Inst) {
355*e71c6ab5STobias Grosser   if (SCEVCodegen && SE.isSCEVable(Inst->getType()))
356*e71c6ab5STobias Grosser     if (const SCEV *Scev = SE.getSCEV(const_cast<Instruction*>(Inst)))
357*e71c6ab5STobias Grosser       if (!isa<SCEVCouldNotCompute>(Scev)) {
358*e71c6ab5STobias Grosser         if (const SCEVUnknown *Unknown = dyn_cast<SCEVUnknown>(Scev)) {
359*e71c6ab5STobias Grosser           if (Unknown->getValue() != Inst)
360*e71c6ab5STobias Grosser             return true;
361*e71c6ab5STobias Grosser         } else {
362*e71c6ab5STobias Grosser           return true;
363*e71c6ab5STobias Grosser         }
364*e71c6ab5STobias Grosser       }
365*e71c6ab5STobias Grosser 
366*e71c6ab5STobias Grosser   return false;
367*e71c6ab5STobias Grosser }
3683b11a16aSHongbin Zheng 
3693b11a16aSHongbin Zheng Value *BlockGenerator::getNewValue(const Value *Old, ValueMapT &BBMap,
3703b11a16aSHongbin Zheng                                    ValueMapT &GlobalMap) {
3713b11a16aSHongbin Zheng   // We assume constants never change.
3723b11a16aSHongbin Zheng   // This avoids map lookups for many calls to this function.
3733b11a16aSHongbin Zheng   if (isa<Constant>(Old))
3743b11a16aSHongbin Zheng     return const_cast<Value*>(Old);
3753b11a16aSHongbin Zheng 
3763b11a16aSHongbin Zheng   if (GlobalMap.count(Old)) {
3773b11a16aSHongbin Zheng     Value *New = GlobalMap[Old];
3783b11a16aSHongbin Zheng 
3793b11a16aSHongbin Zheng     if (Old->getType()->getScalarSizeInBits()
3803b11a16aSHongbin Zheng         < New->getType()->getScalarSizeInBits())
3813b11a16aSHongbin Zheng       New = Builder.CreateTruncOrBitCast(New, Old->getType());
3823b11a16aSHongbin Zheng 
3833b11a16aSHongbin Zheng     return New;
3843b11a16aSHongbin Zheng   }
3853b11a16aSHongbin Zheng 
3863b11a16aSHongbin Zheng   if (BBMap.count(Old)) {
3873b11a16aSHongbin Zheng     return BBMap[Old];
3883b11a16aSHongbin Zheng   }
3893b11a16aSHongbin Zheng 
390*e71c6ab5STobias Grosser   if (SCEVCodegen && SE.isSCEVable(Old->getType()))
391*e71c6ab5STobias Grosser     if (const SCEV *Scev = SE.getSCEV(const_cast<Value*>(Old)))
392*e71c6ab5STobias Grosser       if (!isa<SCEVCouldNotCompute>(Scev)) {
393*e71c6ab5STobias Grosser         const SCEV *NewScev = SCEVRewriter::rewrite(Scev,
394*e71c6ab5STobias Grosser                                                     *Statement.getParent(), SE,
395*e71c6ab5STobias Grosser                                                     GlobalMap, BBMap);
396*e71c6ab5STobias Grosser         SCEVExpander Expander(SE, "polly");
397*e71c6ab5STobias Grosser         Value *Expanded = Expander.expandCodeFor(NewScev, Old->getType(),
398*e71c6ab5STobias Grosser                                                  Builder.GetInsertPoint());
399*e71c6ab5STobias Grosser 
400*e71c6ab5STobias Grosser         BBMap[Old] = Expanded;
401*e71c6ab5STobias Grosser         return Expanded;
402*e71c6ab5STobias Grosser       }
403*e71c6ab5STobias Grosser 
4043b11a16aSHongbin Zheng   // 'Old' is within the original SCoP, but was not rewritten.
4053b11a16aSHongbin Zheng   //
4063b11a16aSHongbin Zheng   // Such values appear, if they only calculate information already available in
4073b11a16aSHongbin Zheng   // the polyhedral description (e.g.  an induction variable increment). They
4083b11a16aSHongbin Zheng   // can be safely ignored.
4093b11a16aSHongbin Zheng   if (const Instruction *Inst = dyn_cast<Instruction>(Old))
4103b11a16aSHongbin Zheng     if (Statement.getParent()->getRegion().contains(Inst->getParent()))
4113b11a16aSHongbin Zheng       return NULL;
4123b11a16aSHongbin Zheng 
4133b11a16aSHongbin Zheng   // Everything else is probably a scop-constant value defined as global,
4143b11a16aSHongbin Zheng   // function parameter or an instruction not within the scop.
4153b11a16aSHongbin Zheng   return const_cast<Value*>(Old);
4163b11a16aSHongbin Zheng }
4173b11a16aSHongbin Zheng 
4183b11a16aSHongbin Zheng void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
4193b11a16aSHongbin Zheng                                     ValueMapT &GlobalMap) {
4203b11a16aSHongbin Zheng   Instruction *NewInst = Inst->clone();
4213b11a16aSHongbin Zheng 
4223b11a16aSHongbin Zheng   // Replace old operands with the new ones.
4233b11a16aSHongbin Zheng   for (Instruction::const_op_iterator OI = Inst->op_begin(),
4243b11a16aSHongbin Zheng        OE = Inst->op_end(); OI != OE; ++OI) {
4253b11a16aSHongbin Zheng     Value *OldOperand = *OI;
4263b11a16aSHongbin Zheng     Value *NewOperand = getNewValue(OldOperand, BBMap, GlobalMap);
4273b11a16aSHongbin Zheng 
4283b11a16aSHongbin Zheng     if (!NewOperand) {
4293b11a16aSHongbin Zheng       assert(!isa<StoreInst>(NewInst)
4303b11a16aSHongbin Zheng              && "Store instructions are always needed!");
4313b11a16aSHongbin Zheng       delete NewInst;
4323b11a16aSHongbin Zheng       return;
4333b11a16aSHongbin Zheng     }
4343b11a16aSHongbin Zheng 
4353b11a16aSHongbin Zheng     NewInst->replaceUsesOfWith(OldOperand, NewOperand);
4363b11a16aSHongbin Zheng   }
4373b11a16aSHongbin Zheng 
4383b11a16aSHongbin Zheng   Builder.Insert(NewInst);
4393b11a16aSHongbin Zheng   BBMap[Inst] = NewInst;
4403b11a16aSHongbin Zheng 
4413b11a16aSHongbin Zheng   if (!NewInst->getType()->isVoidTy())
4423b11a16aSHongbin Zheng     NewInst->setName("p_" + Inst->getName());
4433b11a16aSHongbin Zheng }
4443b11a16aSHongbin Zheng 
4453b11a16aSHongbin Zheng std::vector<Value*> BlockGenerator::getMemoryAccessIndex(
4463b11a16aSHongbin Zheng   __isl_keep isl_map *AccessRelation, Value *BaseAddress,
4473b11a16aSHongbin Zheng   ValueMapT &BBMap, ValueMapT &GlobalMap) {
4483b11a16aSHongbin Zheng 
4493b11a16aSHongbin Zheng   assert((isl_map_dim(AccessRelation, isl_dim_out) == 1)
4503b11a16aSHongbin Zheng          && "Only single dimensional access functions supported");
4513b11a16aSHongbin Zheng 
4523b11a16aSHongbin Zheng   std::vector<Value *> IVS;
4533b11a16aSHongbin Zheng   for (unsigned i = 0; i < Statement.getNumIterators(); ++i) {
4543b11a16aSHongbin Zheng     const Value *OriginalIV = Statement.getInductionVariableForDimension(i);
4553b11a16aSHongbin Zheng     Value *NewIV = getNewValue(OriginalIV, BBMap, GlobalMap);
4563b11a16aSHongbin Zheng     IVS.push_back(NewIV);
4573b11a16aSHongbin Zheng   }
4583b11a16aSHongbin Zheng 
4593b11a16aSHongbin Zheng   isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
4603b11a16aSHongbin Zheng   IslGenerator IslGen(Builder, IVS);
4613b11a16aSHongbin Zheng   Value *OffsetValue = IslGen.generateIslPwAff(PwAff);
4623b11a16aSHongbin Zheng 
4633b11a16aSHongbin Zheng   Type *Ty = Builder.getInt64Ty();
4643b11a16aSHongbin Zheng   OffsetValue = Builder.CreateIntCast(OffsetValue, Ty, true);
4653b11a16aSHongbin Zheng 
4663b11a16aSHongbin Zheng   std::vector<Value*> IndexArray;
4673b11a16aSHongbin Zheng   Value *NullValue = Constant::getNullValue(Ty);
4683b11a16aSHongbin Zheng   IndexArray.push_back(NullValue);
4693b11a16aSHongbin Zheng   IndexArray.push_back(OffsetValue);
4703b11a16aSHongbin Zheng   return IndexArray;
4713b11a16aSHongbin Zheng }
4723b11a16aSHongbin Zheng 
4733b11a16aSHongbin Zheng Value *BlockGenerator::getNewAccessOperand(
4743b11a16aSHongbin Zheng   __isl_keep isl_map *NewAccessRelation, Value *BaseAddress,
4753b11a16aSHongbin Zheng   ValueMapT &BBMap, ValueMapT &GlobalMap) {
4763b11a16aSHongbin Zheng   std::vector<Value*> IndexArray = getMemoryAccessIndex(NewAccessRelation,
4773b11a16aSHongbin Zheng                                                         BaseAddress,
4783b11a16aSHongbin Zheng                                                         BBMap, GlobalMap);
4793b11a16aSHongbin Zheng   Value *NewOperand = Builder.CreateGEP(BaseAddress, IndexArray,
4803b11a16aSHongbin Zheng                                         "p_newarrayidx_");
4813b11a16aSHongbin Zheng   return NewOperand;
4823b11a16aSHongbin Zheng }
4833b11a16aSHongbin Zheng 
4843b11a16aSHongbin Zheng Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
4853b11a16aSHongbin Zheng                                                 const Value *Pointer,
4863b11a16aSHongbin Zheng                                                 ValueMapT &BBMap,
4873b11a16aSHongbin Zheng                                                 ValueMapT &GlobalMap) {
4883b11a16aSHongbin Zheng   MemoryAccess &Access = Statement.getAccessFor(Inst);
4893b11a16aSHongbin Zheng   isl_map *CurrentAccessRelation = Access.getAccessRelation();
4903b11a16aSHongbin Zheng   isl_map *NewAccessRelation = Access.getNewAccessRelation();
4913b11a16aSHongbin Zheng 
4923b11a16aSHongbin Zheng   assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation)
4933b11a16aSHongbin Zheng          && "Current and new access function use different spaces");
4943b11a16aSHongbin Zheng 
4953b11a16aSHongbin Zheng   Value *NewPointer;
4963b11a16aSHongbin Zheng 
4973b11a16aSHongbin Zheng   if (!NewAccessRelation) {
4983b11a16aSHongbin Zheng     NewPointer = getNewValue(Pointer, BBMap, GlobalMap);
4993b11a16aSHongbin Zheng   } else {
5003b11a16aSHongbin Zheng     Value *BaseAddress = const_cast<Value*>(Access.getBaseAddr());
5013b11a16aSHongbin Zheng     NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress,
5023b11a16aSHongbin Zheng                                      BBMap, GlobalMap);
5033b11a16aSHongbin Zheng   }
5043b11a16aSHongbin Zheng 
5053b11a16aSHongbin Zheng   isl_map_free(CurrentAccessRelation);
5063b11a16aSHongbin Zheng   isl_map_free(NewAccessRelation);
5073b11a16aSHongbin Zheng   return NewPointer;
5083b11a16aSHongbin Zheng }
5093b11a16aSHongbin Zheng 
5103b11a16aSHongbin Zheng Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
5113b11a16aSHongbin Zheng                                           ValueMapT &BBMap,
5123b11a16aSHongbin Zheng                                           ValueMapT &GlobalMap) {
5133b11a16aSHongbin Zheng   const Value *Pointer = Load->getPointerOperand();
5143b11a16aSHongbin Zheng   const Instruction *Inst = dyn_cast<Instruction>(Load);
5153b11a16aSHongbin Zheng   Value *NewPointer = generateLocationAccessed(Inst, Pointer, BBMap, GlobalMap);
5163b11a16aSHongbin Zheng   Value *ScalarLoad = Builder.CreateLoad(NewPointer,
5173b11a16aSHongbin Zheng                                          Load->getName() + "_p_scalar_");
5183b11a16aSHongbin Zheng   return ScalarLoad;
5193b11a16aSHongbin Zheng }
5203b11a16aSHongbin Zheng 
5213b11a16aSHongbin Zheng Value *BlockGenerator::generateScalarStore(const StoreInst *Store,
5223b11a16aSHongbin Zheng                                            ValueMapT &BBMap,
5233b11a16aSHongbin Zheng                                            ValueMapT &GlobalMap) {
5243b11a16aSHongbin Zheng   const Value *Pointer = Store->getPointerOperand();
5253b11a16aSHongbin Zheng   Value *NewPointer = generateLocationAccessed(Store, Pointer, BBMap,
5263b11a16aSHongbin Zheng                                                GlobalMap);
5273b11a16aSHongbin Zheng   Value *ValueOperand = getNewValue(Store->getValueOperand(), BBMap, GlobalMap);
5283b11a16aSHongbin Zheng 
5293b11a16aSHongbin Zheng   return Builder.CreateStore(ValueOperand, NewPointer);
5303b11a16aSHongbin Zheng }
5313b11a16aSHongbin Zheng 
5323b11a16aSHongbin Zheng void BlockGenerator::copyInstruction(const Instruction *Inst,
5333b11a16aSHongbin Zheng                                      ValueMapT &BBMap, ValueMapT &GlobalMap) {
5343b11a16aSHongbin Zheng   // Terminator instructions control the control flow. They are explicitly
5353b11a16aSHongbin Zheng   // expressed in the clast and do not need to be copied.
5363b11a16aSHongbin Zheng   if (Inst->isTerminator())
5373b11a16aSHongbin Zheng     return;
5383b11a16aSHongbin Zheng 
539*e71c6ab5STobias Grosser   if (isSCEVIgnore(Inst))
540*e71c6ab5STobias Grosser     return;
541*e71c6ab5STobias Grosser 
5423b11a16aSHongbin Zheng   if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
5433b11a16aSHongbin Zheng     BBMap[Load] = generateScalarLoad(Load, BBMap, GlobalMap);
5443b11a16aSHongbin Zheng     return;
5453b11a16aSHongbin Zheng   }
5463b11a16aSHongbin Zheng 
5473b11a16aSHongbin Zheng   if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
5483b11a16aSHongbin Zheng     BBMap[Store] = generateScalarStore(Store, BBMap, GlobalMap);
5493b11a16aSHongbin Zheng     return;
5503b11a16aSHongbin Zheng   }
5513b11a16aSHongbin Zheng 
5523b11a16aSHongbin Zheng   copyInstScalar(Inst, BBMap, GlobalMap);
5533b11a16aSHongbin Zheng }
5543b11a16aSHongbin Zheng 
5553b11a16aSHongbin Zheng 
5563b11a16aSHongbin Zheng void BlockGenerator::copyBB(ValueMapT &GlobalMap) {
5573b11a16aSHongbin Zheng   BasicBlock *BB = Statement.getBasicBlock();
5583b11a16aSHongbin Zheng   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
5593b11a16aSHongbin Zheng                                   Builder.GetInsertPoint(), P);
5603b11a16aSHongbin Zheng   CopyBB->setName("polly.stmt." + BB->getName());
5613b11a16aSHongbin Zheng   Builder.SetInsertPoint(CopyBB->begin());
5623b11a16aSHongbin Zheng 
5633b11a16aSHongbin Zheng   ValueMapT BBMap;
5643b11a16aSHongbin Zheng 
5653b11a16aSHongbin Zheng   for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
5663b11a16aSHongbin Zheng        ++II)
5673b11a16aSHongbin Zheng       copyInstruction(II, BBMap, GlobalMap);
5683b11a16aSHongbin Zheng }
5693b11a16aSHongbin Zheng 
5703b11a16aSHongbin Zheng VectorBlockGenerator::VectorBlockGenerator(IRBuilder<> &B,
5713b11a16aSHongbin Zheng   VectorValueMapT &GlobalMaps, ScopStmt &Stmt, __isl_keep isl_set *Domain,
5723b11a16aSHongbin Zheng   Pass *P) : BlockGenerator(B, Stmt, P), GlobalMaps(GlobalMaps),
5733b11a16aSHongbin Zheng   Domain(Domain) {
5743b11a16aSHongbin Zheng     assert(GlobalMaps.size() > 1 && "Only one vector lane found");
5753b11a16aSHongbin Zheng     assert(Domain && "No statement domain provided");
5763b11a16aSHongbin Zheng   }
5773b11a16aSHongbin Zheng 
5783b11a16aSHongbin Zheng Value *VectorBlockGenerator::getVectorValue(const Value *Old,
5793b11a16aSHongbin Zheng                                             ValueMapT &VectorMap,
5803b11a16aSHongbin Zheng                                             VectorValueMapT &ScalarMaps) {
5813b11a16aSHongbin Zheng   if (VectorMap.count(Old))
5823b11a16aSHongbin Zheng     return VectorMap[Old];
5833b11a16aSHongbin Zheng 
5843b11a16aSHongbin Zheng   int Width = getVectorWidth();
5853b11a16aSHongbin Zheng 
5863b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
5873b11a16aSHongbin Zheng 
5883b11a16aSHongbin Zheng   for (int Lane = 0; Lane < Width; Lane++)
5893b11a16aSHongbin Zheng     Vector = Builder.CreateInsertElement(Vector,
5903b11a16aSHongbin Zheng                                          getNewValue(Old,
5913b11a16aSHongbin Zheng                                                      ScalarMaps[Lane],
5923b11a16aSHongbin Zheng                                                      GlobalMaps[Lane]),
5933b11a16aSHongbin Zheng                                          Builder.getInt32(Lane));
5943b11a16aSHongbin Zheng 
5953b11a16aSHongbin Zheng   VectorMap[Old] = Vector;
5963b11a16aSHongbin Zheng 
5973b11a16aSHongbin Zheng   return Vector;
5983b11a16aSHongbin Zheng }
5993b11a16aSHongbin Zheng 
6003b11a16aSHongbin Zheng Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
6013b11a16aSHongbin Zheng   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
6023b11a16aSHongbin Zheng   assert(PointerTy && "PointerType expected");
6033b11a16aSHongbin Zheng 
6043b11a16aSHongbin Zheng   Type *ScalarType = PointerTy->getElementType();
6053b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(ScalarType, Width);
6063b11a16aSHongbin Zheng 
6073b11a16aSHongbin Zheng   return PointerType::getUnqual(VectorType);
6083b11a16aSHongbin Zheng }
6093b11a16aSHongbin Zheng 
6103b11a16aSHongbin Zheng Value *VectorBlockGenerator::generateStrideOneLoad(const LoadInst *Load,
6113b11a16aSHongbin Zheng                                                    ValueMapT &BBMap) {
6123b11a16aSHongbin Zheng   const Value *Pointer = Load->getPointerOperand();
6133b11a16aSHongbin Zheng   Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
6143b11a16aSHongbin Zheng   Value *NewPointer = getNewValue(Pointer, BBMap, GlobalMaps[0]);
6153b11a16aSHongbin Zheng   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
6163b11a16aSHongbin Zheng                                            "vector_ptr");
6173b11a16aSHongbin Zheng   LoadInst *VecLoad = Builder.CreateLoad(VectorPtr,
6183b11a16aSHongbin Zheng                                          Load->getName() + "_p_vec_full");
6193b11a16aSHongbin Zheng   if (!Aligned)
6203b11a16aSHongbin Zheng     VecLoad->setAlignment(8);
6213b11a16aSHongbin Zheng 
6223b11a16aSHongbin Zheng   return VecLoad;
6233b11a16aSHongbin Zheng }
6243b11a16aSHongbin Zheng 
6253b11a16aSHongbin Zheng Value *VectorBlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
6263b11a16aSHongbin Zheng                                                     ValueMapT &BBMap) {
6273b11a16aSHongbin Zheng   const Value *Pointer = Load->getPointerOperand();
6283b11a16aSHongbin Zheng   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
6293b11a16aSHongbin Zheng   Value *NewPointer = getNewValue(Pointer, BBMap, GlobalMaps[0]);
6303b11a16aSHongbin Zheng   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
6313b11a16aSHongbin Zheng                                            Load->getName() + "_p_vec_p");
6323b11a16aSHongbin Zheng   LoadInst *ScalarLoad= Builder.CreateLoad(VectorPtr,
6333b11a16aSHongbin Zheng                                            Load->getName() + "_p_splat_one");
6343b11a16aSHongbin Zheng 
6353b11a16aSHongbin Zheng   if (!Aligned)
6363b11a16aSHongbin Zheng     ScalarLoad->setAlignment(8);
6373b11a16aSHongbin Zheng 
6383b11a16aSHongbin Zheng   Constant *SplatVector =
6393b11a16aSHongbin Zheng     Constant::getNullValue(VectorType::get(Builder.getInt32Ty(),
6403b11a16aSHongbin Zheng                                            getVectorWidth()));
6413b11a16aSHongbin Zheng 
6423b11a16aSHongbin Zheng   Value *VectorLoad = Builder.CreateShuffleVector(ScalarLoad, ScalarLoad,
6433b11a16aSHongbin Zheng                                                   SplatVector,
6443b11a16aSHongbin Zheng                                                   Load->getName()
6453b11a16aSHongbin Zheng                                                   + "_p_splat");
6463b11a16aSHongbin Zheng   return VectorLoad;
6473b11a16aSHongbin Zheng }
6483b11a16aSHongbin Zheng 
6493b11a16aSHongbin Zheng Value *VectorBlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
6503b11a16aSHongbin Zheng   VectorValueMapT &ScalarMaps) {
6513b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
6523b11a16aSHongbin Zheng   const Value *Pointer = Load->getPointerOperand();
6533b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(
6543b11a16aSHongbin Zheng     dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
6553b11a16aSHongbin Zheng 
6563b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType);
6573b11a16aSHongbin Zheng 
6583b11a16aSHongbin Zheng   for (int i = 0; i < VectorWidth; i++) {
6593b11a16aSHongbin Zheng     Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i]);
6603b11a16aSHongbin Zheng     Value *ScalarLoad = Builder.CreateLoad(NewPointer,
6613b11a16aSHongbin Zheng                                            Load->getName() + "_p_scalar_");
6623b11a16aSHongbin Zheng     Vector = Builder.CreateInsertElement(Vector, ScalarLoad,
6633b11a16aSHongbin Zheng                                          Builder.getInt32(i),
6643b11a16aSHongbin Zheng                                          Load->getName() + "_p_vec_");
6653b11a16aSHongbin Zheng   }
6663b11a16aSHongbin Zheng 
6673b11a16aSHongbin Zheng   return Vector;
6683b11a16aSHongbin Zheng }
6693b11a16aSHongbin Zheng 
6703b11a16aSHongbin Zheng void VectorBlockGenerator::generateLoad(const LoadInst *Load,
6713b11a16aSHongbin Zheng                                         ValueMapT &VectorMap,
6723b11a16aSHongbin Zheng                                         VectorValueMapT &ScalarMaps) {
6733b11a16aSHongbin Zheng   if (GroupedUnrolling || !VectorType::isValidElementType(Load->getType())) {
6743b11a16aSHongbin Zheng     for (int i = 0; i < getVectorWidth(); i++)
6753b11a16aSHongbin Zheng       ScalarMaps[i][Load] = generateScalarLoad(Load, ScalarMaps[i],
6763b11a16aSHongbin Zheng                                                GlobalMaps[i]);
6773b11a16aSHongbin Zheng     return;
6783b11a16aSHongbin Zheng   }
6793b11a16aSHongbin Zheng 
6803b11a16aSHongbin Zheng   MemoryAccess &Access = Statement.getAccessFor(Load);
6813b11a16aSHongbin Zheng 
6823b11a16aSHongbin Zheng   Value *NewLoad;
6833b11a16aSHongbin Zheng   if (Access.isStrideZero(isl_set_copy(Domain)))
6843b11a16aSHongbin Zheng     NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
6853b11a16aSHongbin Zheng   else if (Access.isStrideOne(isl_set_copy(Domain)))
6863b11a16aSHongbin Zheng     NewLoad = generateStrideOneLoad(Load, ScalarMaps[0]);
6873b11a16aSHongbin Zheng   else
6883b11a16aSHongbin Zheng     NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
6893b11a16aSHongbin Zheng 
6903b11a16aSHongbin Zheng   VectorMap[Load] = NewLoad;
6913b11a16aSHongbin Zheng }
6923b11a16aSHongbin Zheng 
6933b11a16aSHongbin Zheng void VectorBlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
6943b11a16aSHongbin Zheng                                          ValueMapT &VectorMap,
6953b11a16aSHongbin Zheng                                          VectorValueMapT &ScalarMaps) {
6963b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
6973b11a16aSHongbin Zheng   Value *NewOperand = getVectorValue(Inst->getOperand(0), VectorMap,
6983b11a16aSHongbin Zheng                                      ScalarMaps);
6993b11a16aSHongbin Zheng 
7003b11a16aSHongbin Zheng   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
7013b11a16aSHongbin Zheng 
7023b11a16aSHongbin Zheng   const CastInst *Cast = dyn_cast<CastInst>(Inst);
7033b11a16aSHongbin Zheng   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
7043b11a16aSHongbin Zheng   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
7053b11a16aSHongbin Zheng }
7063b11a16aSHongbin Zheng 
7073b11a16aSHongbin Zheng void VectorBlockGenerator::copyBinaryInst(const BinaryOperator *Inst,
7083b11a16aSHongbin Zheng                                           ValueMapT &VectorMap,
7093b11a16aSHongbin Zheng                                           VectorValueMapT &ScalarMaps) {
7103b11a16aSHongbin Zheng   Value *OpZero = Inst->getOperand(0);
7113b11a16aSHongbin Zheng   Value *OpOne = Inst->getOperand(1);
7123b11a16aSHongbin Zheng 
7133b11a16aSHongbin Zheng   Value *NewOpZero, *NewOpOne;
7143b11a16aSHongbin Zheng   NewOpZero = getVectorValue(OpZero, VectorMap, ScalarMaps);
7153b11a16aSHongbin Zheng   NewOpOne = getVectorValue(OpOne, VectorMap, ScalarMaps);
7163b11a16aSHongbin Zheng 
7173b11a16aSHongbin Zheng   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero,
7183b11a16aSHongbin Zheng                                        NewOpOne,
7193b11a16aSHongbin Zheng                                        Inst->getName() + "p_vec");
7203b11a16aSHongbin Zheng   VectorMap[Inst] = NewInst;
7213b11a16aSHongbin Zheng }
7223b11a16aSHongbin Zheng 
7233b11a16aSHongbin Zheng void VectorBlockGenerator::copyStore(const StoreInst *Store,
7243b11a16aSHongbin Zheng                                      ValueMapT &VectorMap,
7253b11a16aSHongbin Zheng                                      VectorValueMapT &ScalarMaps) {
7263b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
7273b11a16aSHongbin Zheng 
7283b11a16aSHongbin Zheng   MemoryAccess &Access = Statement.getAccessFor(Store);
7293b11a16aSHongbin Zheng 
7303b11a16aSHongbin Zheng   const Value *Pointer = Store->getPointerOperand();
7313b11a16aSHongbin Zheng   Value *Vector = getVectorValue(Store->getValueOperand(), VectorMap,
7323b11a16aSHongbin Zheng                                    ScalarMaps);
7333b11a16aSHongbin Zheng 
7343b11a16aSHongbin Zheng   if (Access.isStrideOne(isl_set_copy(Domain))) {
7353b11a16aSHongbin Zheng     Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
7363b11a16aSHongbin Zheng     Value *NewPointer = getNewValue(Pointer, ScalarMaps[0], GlobalMaps[0]);
7373b11a16aSHongbin Zheng 
7383b11a16aSHongbin Zheng     Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
7393b11a16aSHongbin Zheng                                              "vector_ptr");
7403b11a16aSHongbin Zheng     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
7413b11a16aSHongbin Zheng 
7423b11a16aSHongbin Zheng     if (!Aligned)
7433b11a16aSHongbin Zheng       Store->setAlignment(8);
7443b11a16aSHongbin Zheng   } else {
7453b11a16aSHongbin Zheng     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
7463b11a16aSHongbin Zheng       Value *Scalar = Builder.CreateExtractElement(Vector,
7473b11a16aSHongbin Zheng                                                    Builder.getInt32(i));
7483b11a16aSHongbin Zheng       Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i]);
7493b11a16aSHongbin Zheng       Builder.CreateStore(Scalar, NewPointer);
7503b11a16aSHongbin Zheng     }
7513b11a16aSHongbin Zheng   }
7523b11a16aSHongbin Zheng }
7533b11a16aSHongbin Zheng 
7543b11a16aSHongbin Zheng bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
7553b11a16aSHongbin Zheng                                              ValueMapT &VectorMap) {
7563b11a16aSHongbin Zheng   for (Instruction::const_op_iterator OI = Inst->op_begin(),
7573b11a16aSHongbin Zheng        OE = Inst->op_end(); OI != OE; ++OI)
7583b11a16aSHongbin Zheng     if (VectorMap.count(*OI))
7593b11a16aSHongbin Zheng       return true;
7603b11a16aSHongbin Zheng   return false;
7613b11a16aSHongbin Zheng }
7623b11a16aSHongbin Zheng 
7633b11a16aSHongbin Zheng bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
7643b11a16aSHongbin Zheng                                                ValueMapT &VectorMap,
7653b11a16aSHongbin Zheng                                                VectorValueMapT &ScalarMaps) {
7663b11a16aSHongbin Zheng   bool HasVectorOperand = false;
7673b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
7683b11a16aSHongbin Zheng 
7693b11a16aSHongbin Zheng   for (Instruction::const_op_iterator OI = Inst->op_begin(),
7703b11a16aSHongbin Zheng        OE = Inst->op_end(); OI != OE; ++OI) {
7713b11a16aSHongbin Zheng     ValueMapT::iterator VecOp = VectorMap.find(*OI);
7723b11a16aSHongbin Zheng 
7733b11a16aSHongbin Zheng     if (VecOp == VectorMap.end())
7743b11a16aSHongbin Zheng       continue;
7753b11a16aSHongbin Zheng 
7763b11a16aSHongbin Zheng     HasVectorOperand = true;
7773b11a16aSHongbin Zheng     Value *NewVector = VecOp->second;
7783b11a16aSHongbin Zheng 
7793b11a16aSHongbin Zheng     for (int i = 0; i < VectorWidth; ++i) {
7803b11a16aSHongbin Zheng       ValueMapT &SM = ScalarMaps[i];
7813b11a16aSHongbin Zheng 
7823b11a16aSHongbin Zheng       // If there is one scalar extracted, all scalar elements should have
7833b11a16aSHongbin Zheng       // already been extracted by the code here. So no need to check for the
7843b11a16aSHongbin Zheng       // existance of all of them.
7853b11a16aSHongbin Zheng       if (SM.count(*OI))
7863b11a16aSHongbin Zheng         break;
7873b11a16aSHongbin Zheng 
7883b11a16aSHongbin Zheng       SM[*OI] = Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
7893b11a16aSHongbin Zheng     }
7903b11a16aSHongbin Zheng   }
7913b11a16aSHongbin Zheng 
7923b11a16aSHongbin Zheng   return HasVectorOperand;
7933b11a16aSHongbin Zheng }
7943b11a16aSHongbin Zheng 
7953b11a16aSHongbin Zheng void VectorBlockGenerator::copyInstScalarized(const Instruction *Inst,
7963b11a16aSHongbin Zheng                                               ValueMapT &VectorMap,
7973b11a16aSHongbin Zheng                                               VectorValueMapT &ScalarMaps) {
7983b11a16aSHongbin Zheng   bool HasVectorOperand;
7993b11a16aSHongbin Zheng   int VectorWidth = getVectorWidth();
8003b11a16aSHongbin Zheng 
8013b11a16aSHongbin Zheng   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
8023b11a16aSHongbin Zheng 
8033b11a16aSHongbin Zheng   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
8043b11a16aSHongbin Zheng     copyInstScalar(Inst, ScalarMaps[VectorLane], GlobalMaps[VectorLane]);
8053b11a16aSHongbin Zheng 
8063b11a16aSHongbin Zheng   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
8073b11a16aSHongbin Zheng     return;
8083b11a16aSHongbin Zheng 
8093b11a16aSHongbin Zheng   // Make the result available as vector value.
8103b11a16aSHongbin Zheng   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
8113b11a16aSHongbin Zheng   Value *Vector = UndefValue::get(VectorType);
8123b11a16aSHongbin Zheng 
8133b11a16aSHongbin Zheng   for (int i = 0; i < VectorWidth; i++)
8143b11a16aSHongbin Zheng     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
8153b11a16aSHongbin Zheng                                          Builder.getInt32(i));
8163b11a16aSHongbin Zheng 
8173b11a16aSHongbin Zheng   VectorMap[Inst] = Vector;
8183b11a16aSHongbin Zheng }
8193b11a16aSHongbin Zheng 
8203b11a16aSHongbin Zheng int VectorBlockGenerator::getVectorWidth() {
8213b11a16aSHongbin Zheng   return GlobalMaps.size();
8223b11a16aSHongbin Zheng }
8233b11a16aSHongbin Zheng 
8243b11a16aSHongbin Zheng void VectorBlockGenerator::copyInstruction(const Instruction *Inst,
8253b11a16aSHongbin Zheng                                            ValueMapT &VectorMap,
8263b11a16aSHongbin Zheng                                            VectorValueMapT &ScalarMaps) {
8273b11a16aSHongbin Zheng   // Terminator instructions control the control flow. They are explicitly
8283b11a16aSHongbin Zheng   // expressed in the clast and do not need to be copied.
8293b11a16aSHongbin Zheng   if (Inst->isTerminator())
8303b11a16aSHongbin Zheng     return;
8313b11a16aSHongbin Zheng 
832*e71c6ab5STobias Grosser   if (isSCEVIgnore(Inst))
833*e71c6ab5STobias Grosser     return;
834*e71c6ab5STobias Grosser 
8353b11a16aSHongbin Zheng   if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
8363b11a16aSHongbin Zheng     generateLoad(Load, VectorMap, ScalarMaps);
8373b11a16aSHongbin Zheng     return;
8383b11a16aSHongbin Zheng   }
8393b11a16aSHongbin Zheng 
8403b11a16aSHongbin Zheng   if (hasVectorOperands(Inst, VectorMap)) {
8413b11a16aSHongbin Zheng     if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
8423b11a16aSHongbin Zheng       copyStore(Store, VectorMap, ScalarMaps);
8433b11a16aSHongbin Zheng       return;
8443b11a16aSHongbin Zheng     }
8453b11a16aSHongbin Zheng 
8463b11a16aSHongbin Zheng     if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
8473b11a16aSHongbin Zheng       copyUnaryInst(Unary, VectorMap, ScalarMaps);
8483b11a16aSHongbin Zheng       return;
8493b11a16aSHongbin Zheng     }
8503b11a16aSHongbin Zheng 
8513b11a16aSHongbin Zheng     if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
8523b11a16aSHongbin Zheng       copyBinaryInst(Binary, VectorMap, ScalarMaps);
8533b11a16aSHongbin Zheng       return;
8543b11a16aSHongbin Zheng     }
8553b11a16aSHongbin Zheng 
8563b11a16aSHongbin Zheng     // Falltrough: We generate scalar instructions, if we don't know how to
8573b11a16aSHongbin Zheng     // generate vector code.
8583b11a16aSHongbin Zheng   }
8593b11a16aSHongbin Zheng 
8603b11a16aSHongbin Zheng   copyInstScalarized(Inst, VectorMap, ScalarMaps);
8613b11a16aSHongbin Zheng }
8623b11a16aSHongbin Zheng 
8633b11a16aSHongbin Zheng void VectorBlockGenerator::copyBB() {
8643b11a16aSHongbin Zheng   BasicBlock *BB = Statement.getBasicBlock();
8653b11a16aSHongbin Zheng   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
8663b11a16aSHongbin Zheng                                   Builder.GetInsertPoint(), P);
8673b11a16aSHongbin Zheng   CopyBB->setName("polly.stmt." + BB->getName());
8683b11a16aSHongbin Zheng   Builder.SetInsertPoint(CopyBB->begin());
8693b11a16aSHongbin Zheng 
8703b11a16aSHongbin Zheng   // Create two maps that store the mapping from the original instructions of
8713b11a16aSHongbin Zheng   // the old basic block to their copies in the new basic block. Those maps
8723b11a16aSHongbin Zheng   // are basic block local.
8733b11a16aSHongbin Zheng   //
8743b11a16aSHongbin Zheng   // As vector code generation is supported there is one map for scalar values
8753b11a16aSHongbin Zheng   // and one for vector values.
8763b11a16aSHongbin Zheng   //
8773b11a16aSHongbin Zheng   // In case we just do scalar code generation, the vectorMap is not used and
8783b11a16aSHongbin Zheng   // the scalarMap has just one dimension, which contains the mapping.
8793b11a16aSHongbin Zheng   //
8803b11a16aSHongbin Zheng   // In case vector code generation is done, an instruction may either appear
8813b11a16aSHongbin Zheng   // in the vector map once (as it is calculating >vectorwidth< values at a
8823b11a16aSHongbin Zheng   // time. Or (if the values are calculated using scalar operations), it
8833b11a16aSHongbin Zheng   // appears once in every dimension of the scalarMap.
8843b11a16aSHongbin Zheng   VectorValueMapT ScalarBlockMap(getVectorWidth());
8853b11a16aSHongbin Zheng   ValueMapT VectorBlockMap;
8863b11a16aSHongbin Zheng 
8873b11a16aSHongbin Zheng   for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end();
8883b11a16aSHongbin Zheng        II != IE; ++II)
8893b11a16aSHongbin Zheng       copyInstruction(II, VectorBlockMap, ScalarBlockMap);
8903b11a16aSHongbin Zheng }
891