blob: b66b03494a993608f442463a2415ef4a475ea002 [file] [log] [blame]
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
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// This file implements the BlockGenerator and VectorBlockGenerator classes,
11// which generate sequential code and vectorized code for a polyhedral
12// statement, respectively.
13//
14//===----------------------------------------------------------------------===//
15
16#include "polly/ScopInfo.h"
Tobias Grosser83628182013-05-07 08:11:54 +000017#include "isl/aff.h"
18#include "isl/set.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000019#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser83628182013-05-07 08:11:54 +000020#include "polly/CodeGen/CodeGeneration.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000021#include "polly/Options.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000022#include "polly/Support/GICHelper.h"
Sebastian Pop97cb8132013-03-18 20:21:13 +000023#include "polly/Support/SCEVValidator.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000024#include "polly/Support/ScopHelper.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000025#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/ScalarEvolutionExpander.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000029
Hongbin Zheng3b11a162012-04-25 13:16:49 +000030using namespace llvm;
31using namespace polly;
32
33static cl::opt<bool>
Tobias Grosserc14582f2013-02-05 18:01:29 +000034Aligned("enable-polly-aligned", cl::desc("Assumed aligned memory accesses."),
35 cl::Hidden, cl::value_desc("OpenMP code generation enabled if true"),
Tobias Grosser637bd632013-05-07 07:31:10 +000036 cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000037
Tobias Grossere602a072013-05-07 07:30:56 +000038static cl::opt<bool, true>
39SCEVCodegenF("polly-codegen-scev", cl::desc("Use SCEV based code generation."),
40 cl::Hidden, cl::location(SCEVCodegen), cl::init(false),
Tobias Grosser637bd632013-05-07 07:31:10 +000041 cl::ZeroOrMore, cl::cat(PollyCategory));
Tobias Grosserecfe21b2013-03-20 18:03:18 +000042
43bool polly::SCEVCodegen;
44
45bool polly::canSynthesize(const Instruction *I, const llvm::LoopInfo *LI,
46 ScalarEvolution *SE, const Region *R) {
47 if (SCEVCodegen) {
48 if (!I || !SE->isSCEVable(I->getType()))
49 return false;
50
51 if (const SCEV *Scev = SE->getSCEV(const_cast<Instruction *>(I)))
52 if (!isa<SCEVCouldNotCompute>(Scev))
53 if (!hasScalarDepsInsideRegion(Scev, R))
54 return true;
55
56 return false;
57 }
58
59 Loop *L = LI->getLoopFor(I->getParent());
Tobias Grossere8df5bd2013-04-17 07:20:36 +000060 return L && I == L->getCanonicalInductionVariable() && R->contains(L);
Tobias Grosserecfe21b2013-03-20 18:03:18 +000061}
62
Hongbin Zheng3b11a162012-04-25 13:16:49 +000063// Helper class to generate memory location.
64namespace {
65class IslGenerator {
66public:
Tobias Grosser7242ad92013-02-22 08:07:06 +000067 IslGenerator(IRBuilder<> &Builder, std::vector<Value *> &IVS)
68 : Builder(Builder), IVS(IVS) {}
Tobias Grosseredab1352013-06-21 06:41:31 +000069 Value *generateIslVal(__isl_take isl_val *Val);
Hongbin Zheng3b11a162012-04-25 13:16:49 +000070 Value *generateIslAff(__isl_take isl_aff *Aff);
71 Value *generateIslPwAff(__isl_take isl_pw_aff *PwAff);
72
73private:
74 typedef struct {
75 Value *Result;
76 class IslGenerator *Generator;
77 } IslGenInfo;
78
79 IRBuilder<> &Builder;
80 std::vector<Value *> &IVS;
Tobias Grosser1bb59b02012-12-29 23:47:38 +000081 static int mergeIslAffValues(__isl_take isl_set *Set, __isl_take isl_aff *Aff,
82 void *User);
Hongbin Zheng3b11a162012-04-25 13:16:49 +000083};
84}
85
Tobias Grosseredab1352013-06-21 06:41:31 +000086Value *IslGenerator::generateIslVal(__isl_take isl_val *Val) {
87 Value *IntValue = Builder.getInt(APIntFromVal(Val));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000088 return IntValue;
89}
90
91Value *IslGenerator::generateIslAff(__isl_take isl_aff *Aff) {
92 Value *Result;
93 Value *ConstValue;
Tobias Grosseredab1352013-06-21 06:41:31 +000094 isl_val *Val;
Hongbin Zheng3b11a162012-04-25 13:16:49 +000095
Tobias Grosseredab1352013-06-21 06:41:31 +000096 Val = isl_aff_get_constant_val(Aff);
97 ConstValue = generateIslVal(Val);
Hongbin Zheng3b11a162012-04-25 13:16:49 +000098 Type *Ty = Builder.getInt64Ty();
99
100 // FIXME: We should give the constant and coefficients the right type. Here
101 // we force it into i64.
102 Result = Builder.CreateSExtOrBitCast(ConstValue, Ty);
103
104 unsigned int NbInputDims = isl_aff_dim(Aff, isl_dim_in);
105
Tobias Grosser7242ad92013-02-22 08:07:06 +0000106 assert((IVS.size() == NbInputDims) &&
107 "The Dimension of Induction Variables must match the dimension of the "
108 "affine space.");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000109
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000110 for (unsigned int i = 0; i < NbInputDims; ++i) {
111 Value *CoefficientValue;
Tobias Grosseredab1352013-06-21 06:41:31 +0000112 Val = isl_aff_get_coefficient_val(Aff, isl_dim_in, i);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000113
Tobias Grosseredab1352013-06-21 06:41:31 +0000114 if (isl_val_is_zero(Val)) {
115 isl_val_free(Val);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000116 continue;
Tobias Grosseredab1352013-06-21 06:41:31 +0000117 }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000118
Tobias Grosseredab1352013-06-21 06:41:31 +0000119 CoefficientValue = generateIslVal(Val);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000120 CoefficientValue = Builder.CreateIntCast(CoefficientValue, Ty, true);
121 Value *IV = Builder.CreateIntCast(IVS[i], Ty, true);
122 Value *PAdd = Builder.CreateMul(CoefficientValue, IV, "p_mul_coeff");
123 Result = Builder.CreateAdd(Result, PAdd, "p_sum_coeff");
124 }
125
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000126 isl_aff_free(Aff);
127
128 return Result;
129}
130
131int IslGenerator::mergeIslAffValues(__isl_take isl_set *Set,
132 __isl_take isl_aff *Aff, void *User) {
133 IslGenInfo *GenInfo = (IslGenInfo *)User;
134
Tobias Grosser7242ad92013-02-22 08:07:06 +0000135 assert((GenInfo->Result == NULL) &&
136 "Result is already set. Currently only single isl_aff is supported");
137 assert(isl_set_plain_is_universe(Set) &&
138 "Code generation failed because the set is not universe");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000139
140 GenInfo->Result = GenInfo->Generator->generateIslAff(Aff);
141
142 isl_set_free(Set);
143 return 0;
144}
145
146Value *IslGenerator::generateIslPwAff(__isl_take isl_pw_aff *PwAff) {
147 IslGenInfo User;
148 User.Result = NULL;
149 User.Generator = this;
150 isl_pw_aff_foreach_piece(PwAff, mergeIslAffValues, &User);
151 assert(User.Result && "Code generation for isl_pw_aff failed");
152
153 isl_pw_aff_free(PwAff);
154 return User.Result;
155}
156
Tobias Grosser7242ad92013-02-22 08:07:06 +0000157BlockGenerator::BlockGenerator(IRBuilder<> &B, ScopStmt &Stmt, Pass *P)
158 : Builder(B), Statement(Stmt), P(P), SE(P->getAnalysis<ScalarEvolution>()) {
159}
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000160
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000161Value *BlockGenerator::lookupAvailableValue(const Value *Old, ValueMapT &BBMap,
162 ValueMapT &GlobalMap) const {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000163 // We assume constants never change.
164 // This avoids map lookups for many calls to this function.
165 if (isa<Constant>(Old))
Tobias Grosserc14582f2013-02-05 18:01:29 +0000166 return const_cast<Value *>(Old);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000167
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000168 if (Value *New = GlobalMap.lookup(Old)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000169 if (Old->getType()->getScalarSizeInBits() <
Tobias Grosserd7e58642013-04-10 06:55:45 +0000170 New->getType()->getScalarSizeInBits())
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000171 New = Builder.CreateTruncOrBitCast(New, Old->getType());
172
173 return New;
174 }
175
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000176 // Or it is probably a scop-constant value defined as global, function
177 // parameter or an instruction not within the scop.
178 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
179 return const_cast<Value *>(Old);
180
181 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
182 if (!Statement.getParent()->getRegion().contains(Inst->getParent()))
183 return const_cast<Value *>(Old);
184
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000185 if (Value *New = BBMap.lookup(Old))
186 return New;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000187
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000188 return NULL;
189}
190
191Value *BlockGenerator::getNewValue(const Value *Old, ValueMapT &BBMap,
192 ValueMapT &GlobalMap, LoopToScevMapT &LTS,
193 Loop *L) {
194 if (Value *New = lookupAvailableValue(Old, BBMap, GlobalMap))
195 return New;
196
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000197 if (SCEVCodegen && SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +0000198 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000199 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +0000200 const SCEV *NewScev = apply(Scev, LTS, SE);
201 ValueToValueMap VTV;
202 VTV.insert(BBMap.begin(), BBMap.end());
203 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Sebastian Pop47d4ee32013-02-15 21:26:53 +0000204 NewScev = SCEVParameterRewriter::rewrite(NewScev, SE, VTV);
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000205 SCEVExpander Expander(SE, "polly");
206 Value *Expanded = Expander.expandCodeFor(NewScev, Old->getType(),
207 Builder.GetInsertPoint());
208
209 BBMap[Old] = Expanded;
210 return Expanded;
211 }
Tobias Grosser369430f2013-03-22 23:42:53 +0000212 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000213
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000214 // Now the scalar dependence is neither available nor SCEVCodegenable, this
215 // should never happen in the current code generator.
216 llvm_unreachable("Unexpected scalar dependence in region!");
217 return NULL;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000218}
219
220void BlockGenerator::copyInstScalar(const Instruction *Inst, ValueMapT &BBMap,
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000221 ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000222 Instruction *NewInst = Inst->clone();
223
224 // Replace old operands with the new ones.
225 for (Instruction::const_op_iterator OI = Inst->op_begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000226 OE = Inst->op_end();
227 OI != OE; ++OI) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000228 Value *OldOperand = *OI;
Tobias Grosser369430f2013-03-22 23:42:53 +0000229 Value *NewOperand =
230 getNewValue(OldOperand, BBMap, GlobalMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000231
232 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000233 assert(!isa<StoreInst>(NewInst) &&
234 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000235 delete NewInst;
236 return;
237 }
238
239 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
240 }
241
242 Builder.Insert(NewInst);
243 BBMap[Inst] = NewInst;
244
245 if (!NewInst->getType()->isVoidTy())
246 NewInst->setName("p_" + Inst->getName());
247}
248
Tobias Grosserc14582f2013-02-05 18:01:29 +0000249std::vector<Value *> BlockGenerator::getMemoryAccessIndex(
250 __isl_keep isl_map *AccessRelation, Value *BaseAddress, ValueMapT &BBMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000251 ValueMapT &GlobalMap, LoopToScevMapT &LTS, Loop *L) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000252
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000253 assert((isl_map_dim(AccessRelation, isl_dim_out) == 1) &&
254 "Only single dimensional access functions supported");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000255
256 std::vector<Value *> IVS;
257 for (unsigned i = 0; i < Statement.getNumIterators(); ++i) {
258 const Value *OriginalIV = Statement.getInductionVariableForDimension(i);
Tobias Grosser369430f2013-03-22 23:42:53 +0000259 Value *NewIV = getNewValue(OriginalIV, BBMap, GlobalMap, LTS, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000260 IVS.push_back(NewIV);
261 }
262
263 isl_pw_aff *PwAff = isl_map_dim_max(isl_map_copy(AccessRelation), 0);
264 IslGenerator IslGen(Builder, IVS);
265 Value *OffsetValue = IslGen.generateIslPwAff(PwAff);
266
267 Type *Ty = Builder.getInt64Ty();
268 OffsetValue = Builder.CreateIntCast(OffsetValue, Ty, true);
269
Tobias Grosserc14582f2013-02-05 18:01:29 +0000270 std::vector<Value *> IndexArray;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000271 Value *NullValue = Constant::getNullValue(Ty);
272 IndexArray.push_back(NullValue);
273 IndexArray.push_back(OffsetValue);
274 return IndexArray;
275}
276
277Value *BlockGenerator::getNewAccessOperand(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000278 __isl_keep isl_map *NewAccessRelation, Value *BaseAddress, ValueMapT &BBMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000279 ValueMapT &GlobalMap, LoopToScevMapT &LTS, Loop *L) {
Tobias Grosser7242ad92013-02-22 08:07:06 +0000280 std::vector<Value *> IndexArray = getMemoryAccessIndex(
Tobias Grosser369430f2013-03-22 23:42:53 +0000281 NewAccessRelation, BaseAddress, BBMap, GlobalMap, LTS, L);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000282 Value *NewOperand =
283 Builder.CreateGEP(BaseAddress, IndexArray, "p_newarrayidx_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000284 return NewOperand;
285}
286
Tobias Grossere602a072013-05-07 07:30:56 +0000287Value *BlockGenerator::generateLocationAccessed(const Instruction *Inst,
288 const Value *Pointer,
289 ValueMapT &BBMap,
290 ValueMapT &GlobalMap,
291 LoopToScevMapT &LTS) {
Hongbin Zhengb5f24a62013-06-29 06:31:39 +0000292 const MemoryAccess &Access = Statement.getAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000293 isl_map *CurrentAccessRelation = Access.getAccessRelation();
294 isl_map *NewAccessRelation = Access.getNewAccessRelation();
295
Tobias Grosserae2d83e2012-12-29 23:57:18 +0000296 assert(isl_map_has_equal_space(CurrentAccessRelation, NewAccessRelation) &&
297 "Current and new access function use different spaces");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000298
299 Value *NewPointer;
300
301 if (!NewAccessRelation) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000302 NewPointer =
303 getNewValue(Pointer, BBMap, GlobalMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000304 } else {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000305 Value *BaseAddress = const_cast<Value *>(Access.getBaseAddr());
Tobias Grosser7242ad92013-02-22 08:07:06 +0000306 NewPointer = getNewAccessOperand(NewAccessRelation, BaseAddress, BBMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000307 GlobalMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000308 }
309
310 isl_map_free(CurrentAccessRelation);
311 isl_map_free(NewAccessRelation);
312 return NewPointer;
313}
314
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000315Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000316 return P->getAnalysis<LoopInfo>().getLoopFor(Inst->getParent());
317}
318
Tobias Grossere602a072013-05-07 07:30:56 +0000319Value *BlockGenerator::generateScalarLoad(const LoadInst *Load,
320 ValueMapT &BBMap,
321 ValueMapT &GlobalMap,
322 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000323 const Value *Pointer = Load->getPointerOperand();
324 const Instruction *Inst = dyn_cast<Instruction>(Load);
Tobias Grosser7242ad92013-02-22 08:07:06 +0000325 Value *NewPointer =
326 generateLocationAccessed(Inst, Pointer, BBMap, GlobalMap, LTS);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000327 Value *ScalarLoad =
328 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000329 return ScalarLoad;
330}
331
Tobias Grossere602a072013-05-07 07:30:56 +0000332Value *BlockGenerator::generateScalarStore(const StoreInst *Store,
333 ValueMapT &BBMap,
334 ValueMapT &GlobalMap,
335 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000336 const Value *Pointer = Store->getPointerOperand();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000337 Value *NewPointer =
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000338 generateLocationAccessed(Store, Pointer, BBMap, GlobalMap, LTS);
Tobias Grosser369430f2013-03-22 23:42:53 +0000339 Value *ValueOperand = getNewValue(Store->getValueOperand(), BBMap, GlobalMap,
340 LTS, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000341
342 return Builder.CreateStore(ValueOperand, NewPointer);
343}
344
Tobias Grossere602a072013-05-07 07:30:56 +0000345void BlockGenerator::copyInstruction(const Instruction *Inst, ValueMapT &BBMap,
346 ValueMapT &GlobalMap,
347 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000348 // Terminator instructions control the control flow. They are explicitly
349 // expressed in the clast and do not need to be copied.
350 if (Inst->isTerminator())
351 return;
352
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000353 if (canSynthesize(Inst, &P->getAnalysis<LoopInfo>(), &SE,
354 &Statement.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000355 return;
356
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000357 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Sebastian Pop753d43f2013-05-24 17:16:02 +0000358 Value *NewLoad = generateScalarLoad(Load, BBMap, GlobalMap, LTS);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000359 // Compute NewLoad before its insertion in BBMap to make the insertion
360 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000361 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000362 return;
363 }
364
365 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Sebastian Pop753d43f2013-05-24 17:16:02 +0000366 Value *NewStore = generateScalarStore(Store, BBMap, GlobalMap, LTS);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000367 // Compute NewStore before its insertion in BBMap to make the insertion
368 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000369 BBMap[Store] = NewStore;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000370 return;
371 }
372
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000373 copyInstScalar(Inst, BBMap, GlobalMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000374}
375
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000376void BlockGenerator::copyBB(ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000377 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000378 BasicBlock *CopyBB =
379 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000380 CopyBB->setName("polly.stmt." + BB->getName());
381 Builder.SetInsertPoint(CopyBB->begin());
382
383 ValueMapT BBMap;
384
385 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
386 ++II)
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000387 copyInstruction(II, BBMap, GlobalMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000388}
389
Tobias Grossere602a072013-05-07 07:30:56 +0000390VectorBlockGenerator::VectorBlockGenerator(IRBuilder<> &B,
391 VectorValueMapT &GlobalMaps,
392 std::vector<LoopToScevMapT> &VLTS,
393 ScopStmt &Stmt,
394 __isl_keep isl_map *Schedule,
395 Pass *P)
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000396 : BlockGenerator(B, Stmt, P), GlobalMaps(GlobalMaps), VLTS(VLTS),
397 Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000398 assert(GlobalMaps.size() > 1 && "Only one vector lane found");
399 assert(Schedule && "No statement domain provided");
400}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000401
Tobias Grossere602a072013-05-07 07:30:56 +0000402Value *VectorBlockGenerator::getVectorValue(const Value *Old,
403 ValueMapT &VectorMap,
404 VectorValueMapT &ScalarMaps,
405 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000406 if (Value *NewValue = VectorMap.lookup(Old))
407 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000408
409 int Width = getVectorWidth();
410
411 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
412
413 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000414 Vector = Builder.CreateInsertElement(
Tobias Grosser7242ad92013-02-22 08:07:06 +0000415 Vector,
Tobias Grosser369430f2013-03-22 23:42:53 +0000416 getNewValue(Old, ScalarMaps[Lane], GlobalMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000417 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000418
419 VectorMap[Old] = Vector;
420
421 return Vector;
422}
423
424Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
425 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
426 assert(PointerTy && "PointerType expected");
427
428 Type *ScalarType = PointerTy->getElementType();
429 VectorType *VectorType = VectorType::get(ScalarType, Width);
430
431 return PointerType::getUnqual(VectorType);
432}
433
434Value *VectorBlockGenerator::generateStrideOneLoad(const LoadInst *Load,
435 ValueMapT &BBMap) {
436 const Value *Pointer = Load->getPointerOperand();
437 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosser369430f2013-03-22 23:42:53 +0000438 Value *NewPointer =
439 getNewValue(Pointer, BBMap, GlobalMaps[0], VLTS[0], getLoopForInst(Load));
Tobias Grosserc14582f2013-02-05 18:01:29 +0000440 Value *VectorPtr =
441 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
442 LoadInst *VecLoad =
443 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000444 if (!Aligned)
445 VecLoad->setAlignment(8);
446
447 return VecLoad;
448}
449
450Value *VectorBlockGenerator::generateStrideZeroLoad(const LoadInst *Load,
451 ValueMapT &BBMap) {
452 const Value *Pointer = Load->getPointerOperand();
453 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosser369430f2013-03-22 23:42:53 +0000454 Value *NewPointer =
455 getNewValue(Pointer, BBMap, GlobalMaps[0], VLTS[0], getLoopForInst(Load));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000456 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
457 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000458 LoadInst *ScalarLoad =
459 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000460
461 if (!Aligned)
462 ScalarLoad->setAlignment(8);
463
Tobias Grosserc14582f2013-02-05 18:01:29 +0000464 Constant *SplatVector = Constant::getNullValue(
465 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000466
Tobias Grosserc14582f2013-02-05 18:01:29 +0000467 Value *VectorLoad = Builder.CreateShuffleVector(
468 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000469 return VectorLoad;
470}
471
Tobias Grossere602a072013-05-07 07:30:56 +0000472Value *
473VectorBlockGenerator::generateUnknownStrideLoad(const LoadInst *Load,
474 VectorValueMapT &ScalarMaps) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000475 int VectorWidth = getVectorWidth();
476 const Value *Pointer = Load->getPointerOperand();
477 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000478 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000479
480 Value *Vector = UndefValue::get(VectorType);
481
482 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000483 Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i],
484 VLTS[i], getLoopForInst(Load));
Tobias Grosserc14582f2013-02-05 18:01:29 +0000485 Value *ScalarLoad =
486 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
487 Vector = Builder.CreateInsertElement(
488 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000489 }
490
491 return Vector;
492}
493
Tobias Grossere602a072013-05-07 07:30:56 +0000494void VectorBlockGenerator::generateLoad(const LoadInst *Load,
495 ValueMapT &VectorMap,
496 VectorValueMapT &ScalarMaps) {
Hongbin Zheng68794212012-05-06 10:22:19 +0000497 if (PollyVectorizerChoice >= VECTORIZER_FIRST_NEED_GROUPED_UNROLL ||
498 !VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000499 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000500 ScalarMaps[i][Load] =
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000501 generateScalarLoad(Load, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000502 return;
503 }
504
Hongbin Zhengb5f24a62013-06-29 06:31:39 +0000505 const MemoryAccess &Access = Statement.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000506
507 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000508 if (Access.isStrideZero(isl_map_copy(Schedule)))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000509 NewLoad = generateStrideZeroLoad(Load, ScalarMaps[0]);
Sebastian Popa00a0292012-12-18 07:46:06 +0000510 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000511 NewLoad = generateStrideOneLoad(Load, ScalarMaps[0]);
512 else
513 NewLoad = generateUnknownStrideLoad(Load, ScalarMaps);
514
515 VectorMap[Load] = NewLoad;
516}
517
518void VectorBlockGenerator::copyUnaryInst(const UnaryInstruction *Inst,
519 ValueMapT &VectorMap,
520 VectorValueMapT &ScalarMaps) {
521 int VectorWidth = getVectorWidth();
Tobias Grosser369430f2013-03-22 23:42:53 +0000522 Value *NewOperand = getVectorValue(Inst->getOperand(0), VectorMap, ScalarMaps,
523 getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000524
525 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
526
527 const CastInst *Cast = dyn_cast<CastInst>(Inst);
528 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
529 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
530}
531
532void VectorBlockGenerator::copyBinaryInst(const BinaryOperator *Inst,
533 ValueMapT &VectorMap,
534 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000535 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000536 Value *OpZero = Inst->getOperand(0);
537 Value *OpOne = Inst->getOperand(1);
538
539 Value *NewOpZero, *NewOpOne;
Tobias Grosser369430f2013-03-22 23:42:53 +0000540 NewOpZero = getVectorValue(OpZero, VectorMap, ScalarMaps, L);
541 NewOpOne = getVectorValue(OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000542
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000543 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000544 Inst->getName() + "p_vec");
545 VectorMap[Inst] = NewInst;
546}
547
Tobias Grossere602a072013-05-07 07:30:56 +0000548void VectorBlockGenerator::copyStore(const StoreInst *Store,
549 ValueMapT &VectorMap,
550 VectorValueMapT &ScalarMaps) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000551 int VectorWidth = getVectorWidth();
552
Hongbin Zhengb5f24a62013-06-29 06:31:39 +0000553 const MemoryAccess &Access = Statement.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000554
555 const Value *Pointer = Store->getPointerOperand();
Tobias Grosser369430f2013-03-22 23:42:53 +0000556 Value *Vector = getVectorValue(Store->getValueOperand(), VectorMap,
557 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000558
Sebastian Popa00a0292012-12-18 07:46:06 +0000559 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000560 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
Tobias Grosser369430f2013-03-22 23:42:53 +0000561 Value *NewPointer = getNewValue(Pointer, ScalarMaps[0], GlobalMaps[0],
562 VLTS[0], getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000563
Tobias Grosserc14582f2013-02-05 18:01:29 +0000564 Value *VectorPtr =
565 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000566 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
567
568 if (!Aligned)
569 Store->setAlignment(8);
570 } else {
571 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000572 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosser369430f2013-03-22 23:42:53 +0000573 Value *NewPointer = getNewValue(Pointer, ScalarMaps[i], GlobalMaps[i],
574 VLTS[i], getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000575 Builder.CreateStore(Scalar, NewPointer);
576 }
577 }
578}
579
580bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
581 ValueMapT &VectorMap) {
582 for (Instruction::const_op_iterator OI = Inst->op_begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000583 OE = Inst->op_end();
584 OI != OE; ++OI)
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000585 if (VectorMap.count(*OI))
586 return true;
587 return false;
588}
589
590bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
591 ValueMapT &VectorMap,
592 VectorValueMapT &ScalarMaps) {
593 bool HasVectorOperand = false;
594 int VectorWidth = getVectorWidth();
595
596 for (Instruction::const_op_iterator OI = Inst->op_begin(),
Tobias Grosserc14582f2013-02-05 18:01:29 +0000597 OE = Inst->op_end();
598 OI != OE; ++OI) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000599 ValueMapT::iterator VecOp = VectorMap.find(*OI);
600
601 if (VecOp == VectorMap.end())
602 continue;
603
604 HasVectorOperand = true;
605 Value *NewVector = VecOp->second;
606
607 for (int i = 0; i < VectorWidth; ++i) {
608 ValueMapT &SM = ScalarMaps[i];
609
610 // If there is one scalar extracted, all scalar elements should have
611 // already been extracted by the code here. So no need to check for the
612 // existance of all of them.
613 if (SM.count(*OI))
614 break;
615
616 SM[*OI] = Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
617 }
618 }
619
620 return HasVectorOperand;
621}
622
623void VectorBlockGenerator::copyInstScalarized(const Instruction *Inst,
624 ValueMapT &VectorMap,
625 VectorValueMapT &ScalarMaps) {
626 bool HasVectorOperand;
627 int VectorWidth = getVectorWidth();
628
629 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
630
631 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Sebastian Pop9d10fff2013-02-15 20:55:59 +0000632 copyInstScalar(Inst, ScalarMaps[VectorLane], GlobalMaps[VectorLane],
633 VLTS[VectorLane]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000634
635 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
636 return;
637
638 // Make the result available as vector value.
639 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
640 Value *Vector = UndefValue::get(VectorType);
641
642 for (int i = 0; i < VectorWidth; i++)
643 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
644 Builder.getInt32(i));
645
646 VectorMap[Inst] = Vector;
647}
648
Tobias Grosserc14582f2013-02-05 18:01:29 +0000649int VectorBlockGenerator::getVectorWidth() { return GlobalMaps.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000650
651void VectorBlockGenerator::copyInstruction(const Instruction *Inst,
652 ValueMapT &VectorMap,
653 VectorValueMapT &ScalarMaps) {
654 // Terminator instructions control the control flow. They are explicitly
655 // expressed in the clast and do not need to be copied.
656 if (Inst->isTerminator())
657 return;
658
Tobias Grosserecfe21b2013-03-20 18:03:18 +0000659 if (canSynthesize(Inst, &P->getAnalysis<LoopInfo>(), &SE,
660 &Statement.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000661 return;
662
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000663 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
664 generateLoad(Load, VectorMap, ScalarMaps);
665 return;
666 }
667
668 if (hasVectorOperands(Inst, VectorMap)) {
669 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
670 copyStore(Store, VectorMap, ScalarMaps);
671 return;
672 }
673
674 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
675 copyUnaryInst(Unary, VectorMap, ScalarMaps);
676 return;
677 }
678
679 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
680 copyBinaryInst(Binary, VectorMap, ScalarMaps);
681 return;
682 }
683
684 // Falltrough: We generate scalar instructions, if we don't know how to
685 // generate vector code.
686 }
687
688 copyInstScalarized(Inst, VectorMap, ScalarMaps);
689}
690
691void VectorBlockGenerator::copyBB() {
692 BasicBlock *BB = Statement.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000693 BasicBlock *CopyBB =
694 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), P);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000695 CopyBB->setName("polly.stmt." + BB->getName());
696 Builder.SetInsertPoint(CopyBB->begin());
697
698 // Create two maps that store the mapping from the original instructions of
699 // the old basic block to their copies in the new basic block. Those maps
700 // are basic block local.
701 //
702 // As vector code generation is supported there is one map for scalar values
703 // and one for vector values.
704 //
705 // In case we just do scalar code generation, the vectorMap is not used and
706 // the scalarMap has just one dimension, which contains the mapping.
707 //
708 // In case vector code generation is done, an instruction may either appear
709 // in the vector map once (as it is calculating >vectorwidth< values at a
710 // time. Or (if the values are calculated using scalar operations), it
711 // appears once in every dimension of the scalarMap.
712 VectorValueMapT ScalarBlockMap(getVectorWidth());
713 ValueMapT VectorBlockMap;
714
Tobias Grosserc14582f2013-02-05 18:01:29 +0000715 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
716 ++II)
717 copyInstruction(II, VectorBlockMap, ScalarBlockMap);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000718}