blob: 9e735b3970bd54091607ed56ab10f00527a5e443 [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"
Hongbin Zheng8a846612012-04-25 13:18:28 +000017#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser83628182013-05-07 08:11:54 +000018#include "polly/CodeGen/CodeGeneration.h"
Johannes Doerferta63b2572014-08-03 01:51:59 +000019#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000020#include "polly/Options.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000021#include "polly/Support/GICHelper.h"
Sebastian Pop97cb8132013-03-18 20:21:13 +000022#include "polly/Support/SCEVValidator.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000023#include "polly/Support/ScopHelper.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000024#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000025#include "llvm/Analysis/RegionInfo.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000026#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Analysis/ScalarEvolutionExpander.h"
Tobias Grosser030237d2014-02-21 15:06:05 +000028#include "llvm/IR/IntrinsicInst.h"
Tobias Grosserc9895062015-03-10 15:24:33 +000029#include "llvm/IR/Module.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000031#include "isl/aff.h"
32#include "isl/ast.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000033#include "isl/ast_build.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000034#include "isl/set.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000035#include <deque>
36
Hongbin Zheng3b11a162012-04-25 13:16:49 +000037using namespace llvm;
38using namespace polly;
39
Tobias Grosser878aba42014-10-22 23:22:41 +000040static cl::opt<bool> Aligned("enable-polly-aligned",
41 cl::desc("Assumed aligned memory accesses."),
42 cl::Hidden, cl::init(false), cl::ZeroOrMore,
43 cl::cat(PollyCategory));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000044
Tobias Grosserdcc3b432015-08-04 13:54:20 +000045bool polly::canSynthesize(const Value *V, const llvm::LoopInfo *LI,
Tobias Grosserecfe21b2013-03-20 18:03:18 +000046 ScalarEvolution *SE, const Region *R) {
Tobias Grosserdcc3b432015-08-04 13:54:20 +000047 if (!V || !SE->isSCEVable(V->getType()))
Tobias Grosserecfe21b2013-03-20 18:03:18 +000048 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000049
Tobias Grosserdcc3b432015-08-04 13:54:20 +000050 if (const SCEV *Scev = SE->getSCEV(const_cast<Value *>(V)))
Tobias Grosser683b8e42014-11-30 14:33:31 +000051 if (!isa<SCEVCouldNotCompute>(Scev))
52 if (!hasScalarDepsInsideRegion(Scev, R))
53 return true;
54
55 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000056}
57
Johannes Doerfert9e3a5db2015-01-26 15:55:54 +000058bool polly::isIgnoredIntrinsic(const Value *V) {
59 if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
60 switch (IT->getIntrinsicID()) {
61 // Lifetime markers are supported/ignored.
62 case llvm::Intrinsic::lifetime_start:
63 case llvm::Intrinsic::lifetime_end:
64 // Invariant markers are supported/ignored.
65 case llvm::Intrinsic::invariant_start:
66 case llvm::Intrinsic::invariant_end:
67 // Some misc annotations are supported/ignored.
68 case llvm::Intrinsic::var_annotation:
69 case llvm::Intrinsic::ptr_annotation:
70 case llvm::Intrinsic::annotation:
71 case llvm::Intrinsic::donothing:
72 case llvm::Intrinsic::assume:
73 case llvm::Intrinsic::expect:
74 return true;
75 default:
76 break;
77 }
78 }
79 return false;
80}
81
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000082BlockGenerator::BlockGenerator(PollyIRBuilder &B, LoopInfo &LI,
83 ScalarEvolution &SE, DominatorTree &DT,
Johannes Doerfertecff11d2015-05-22 23:43:58 +000084 ScalarAllocaMapTy &ScalarMap,
85 ScalarAllocaMapTy &PHIOpMap,
86 EscapeUsersAllocaMapTy &EscapeMap,
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000087 IslExprBuilder *ExprBuilder)
Johannes Doerfertecff11d2015-05-22 23:43:58 +000088 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
89 EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap),
90 EscapeMap(EscapeMap) {}
Tobias Grossere71c6ab2012-04-27 16:36:14 +000091
Johannes Doerfertbe9c9112015-02-06 21:39:31 +000092Value *BlockGenerator::getNewValue(ScopStmt &Stmt, const Value *Old,
93 ValueMapT &BBMap, ValueMapT &GlobalMap,
94 LoopToScevMapT &LTS, Loop *L) const {
Hongbin Zheng3b11a162012-04-25 13:16:49 +000095 // We assume constants never change.
96 // This avoids map lookups for many calls to this function.
97 if (isa<Constant>(Old))
Tobias Grosserc14582f2013-02-05 18:01:29 +000098 return const_cast<Value *>(Old);
Hongbin Zheng3b11a162012-04-25 13:16:49 +000099
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000100 if (Value *New = GlobalMap.lookup(Old)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000101 if (Old->getType()->getScalarSizeInBits() <
Tobias Grosserd7e58642013-04-10 06:55:45 +0000102 New->getType()->getScalarSizeInBits())
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000103 New = Builder.CreateTruncOrBitCast(New, Old->getType());
104
105 return New;
106 }
107
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000108 if (Value *New = BBMap.lookup(Old))
109 return New;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000110
Tobias Grosser683b8e42014-11-30 14:33:31 +0000111 if (SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +0000112 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000113 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +0000114 const SCEV *NewScev = apply(Scev, LTS, SE);
115 ValueToValueMap VTV;
116 VTV.insert(BBMap.begin(), BBMap.end());
117 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Sebastian Pop47d4ee32013-02-15 21:26:53 +0000118 NewScev = SCEVParameterRewriter::rewrite(NewScev, SE, VTV);
Tobias Grosserc9895062015-03-10 15:24:33 +0000119 SCEVExpander Expander(SE, Stmt.getParent()
120 ->getRegion()
121 .getEntry()
122 ->getParent()
123 ->getParent()
124 ->getDataLayout(),
125 "polly");
Tobias Grosser45e79442015-08-01 09:07:57 +0000126 assert(Builder.GetInsertPoint() != Builder.GetInsertBlock()->end() &&
127 "Only instructions can be insert points for SCEVExpander");
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000128 Value *Expanded = Expander.expandCodeFor(NewScev, Old->getType(),
129 Builder.GetInsertPoint());
130
131 BBMap[Old] = Expanded;
132 return Expanded;
133 }
Tobias Grosser369430f2013-03-22 23:42:53 +0000134 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000135
Tobias Grosser16371ac2014-11-05 20:48:56 +0000136 // A scop-constant value defined by a global or a function parameter.
137 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
138 return const_cast<Value *>(Old);
139
140 // A scop-constant value defined by an instruction executed outside the scop.
141 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000142 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser16371ac2014-11-05 20:48:56 +0000143 return const_cast<Value *>(Old);
144
145 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000146 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000147 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000148}
149
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000150void BlockGenerator::copyInstScalar(ScopStmt &Stmt, const Instruction *Inst,
151 ValueMapT &BBMap, ValueMapT &GlobalMap,
152 LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000153 // We do not generate debug intrinsics as we did not investigate how to
154 // copy them correctly. At the current state, they just crash the code
155 // generation as the meta-data operands are not correctly copied.
156 if (isa<DbgInfoIntrinsic>(Inst))
157 return;
158
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000159 Instruction *NewInst = Inst->clone();
160
161 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000162 for (Value *OldOperand : Inst->operands()) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000163 Value *NewOperand = getNewValue(Stmt, OldOperand, BBMap, GlobalMap, LTS,
164 getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000165
166 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000167 assert(!isa<StoreInst>(NewInst) &&
168 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000169 delete NewInst;
170 return;
171 }
172
173 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
174 }
175
176 Builder.Insert(NewInst);
177 BBMap[Inst] = NewInst;
178
179 if (!NewInst->getType()->isVoidTy())
180 NewInst->setName("p_" + Inst->getName());
181}
182
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000183Value *BlockGenerator::getNewAccessOperand(ScopStmt &Stmt,
184 const MemoryAccess &MA) {
Johannes Doerferta99130f2014-10-13 12:58:03 +0000185 isl_pw_multi_aff *PWAccRel;
186 isl_union_map *Schedule;
Johannes Doerferta63b2572014-08-03 01:51:59 +0000187 isl_ast_expr *Expr;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000188 isl_ast_build *Build = Stmt.getAstBuild();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000189
Johannes Doerferta63b2572014-08-03 01:51:59 +0000190 assert(ExprBuilder && Build &&
191 "Cannot generate new value without IslExprBuilder!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000192
Johannes Doerferta99130f2014-10-13 12:58:03 +0000193 Schedule = isl_ast_build_get_schedule(Build);
194 PWAccRel = MA.applyScheduleToAccessRelation(Schedule);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000195
Johannes Doerferta63b2572014-08-03 01:51:59 +0000196 Expr = isl_ast_build_access_from_pw_multi_aff(Build, PWAccRel);
Johannes Doerfertdcb5f1d2014-09-18 11:14:30 +0000197 Expr = isl_ast_expr_address_of(Expr);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000198
199 return ExprBuilder->create(Expr);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000200}
201
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000202Value *BlockGenerator::generateLocationAccessed(
203 ScopStmt &Stmt, const Instruction *Inst, const Value *Pointer,
204 ValueMapT &BBMap, ValueMapT &GlobalMap, LoopToScevMapT &LTS) {
205 const MemoryAccess &MA = Stmt.getAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000206
207 Value *NewPointer;
Johannes Doerferta99130f2014-10-13 12:58:03 +0000208 if (MA.hasNewAccessRelation())
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000209 NewPointer = getNewAccessOperand(Stmt, MA);
Johannes Doerferta63b2572014-08-03 01:51:59 +0000210 else
Tobias Grosser369430f2013-03-22 23:42:53 +0000211 NewPointer =
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000212 getNewValue(Stmt, Pointer, BBMap, GlobalMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000213
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000214 return NewPointer;
215}
216
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000217Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000218 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000219}
220
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000221Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, const LoadInst *Load,
Tobias Grossere602a072013-05-07 07:30:56 +0000222 ValueMapT &BBMap,
223 ValueMapT &GlobalMap,
224 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000225 const Value *Pointer = Load->getPointerOperand();
Tobias Grosser7242ad92013-02-22 08:07:06 +0000226 Value *NewPointer =
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000227 generateLocationAccessed(Stmt, Load, Pointer, BBMap, GlobalMap, LTS);
Johannes Doerfert87901452014-10-02 16:22:19 +0000228 Value *ScalarLoad = Builder.CreateAlignedLoad(
229 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000230 return ScalarLoad;
231}
232
Tobias Grosserc186ac72015-08-11 08:13:15 +0000233void BlockGenerator::generateScalarStore(ScopStmt &Stmt, const StoreInst *Store,
234 ValueMapT &BBMap, ValueMapT &GlobalMap,
235 LoopToScevMapT &LTS) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000236 const Value *Pointer = Store->getPointerOperand();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000237 Value *NewPointer =
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000238 generateLocationAccessed(Stmt, Store, Pointer, BBMap, GlobalMap, LTS);
239 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap,
240 GlobalMap, LTS, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000241
Tobias Grosserc186ac72015-08-11 08:13:15 +0000242 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000243}
244
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000245void BlockGenerator::copyInstruction(ScopStmt &Stmt, const Instruction *Inst,
246 ValueMapT &BBMap, ValueMapT &GlobalMap,
Tobias Grossere602a072013-05-07 07:30:56 +0000247 LoopToScevMapT &LTS) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000248
249 // First check for possible scalar dependences for this instruction.
250 generateScalarLoads(Stmt, Inst, BBMap);
251
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000252 // Terminator instructions control the control flow. They are explicitly
253 // expressed in the clast and do not need to be copied.
254 if (Inst->isTerminator())
255 return;
256
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000257 Loop *L = getLoopForInst(Inst);
258 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
259 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
260 Value *NewValue = getNewValue(Stmt, Inst, BBMap, GlobalMap, LTS, L);
261 BBMap[Inst] = NewValue;
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000262 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000263 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000264
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000265 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000266 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, GlobalMap, LTS);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000267 // Compute NewLoad before its insertion in BBMap to make the insertion
268 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000269 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000270 return;
271 }
272
273 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserc186ac72015-08-11 08:13:15 +0000274 generateScalarStore(Stmt, Store, BBMap, GlobalMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000275 return;
276 }
277
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000278 if (const PHINode *PHI = dyn_cast<PHINode>(Inst)) {
279 copyPHIInstruction(Stmt, PHI, BBMap, GlobalMap, LTS);
280 return;
281 }
282
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000283 // Skip some special intrinsics for which we do not adjust the semantics to
284 // the new schedule. All others are handled like every other instruction.
285 if (auto *IT = dyn_cast<IntrinsicInst>(Inst)) {
286 switch (IT->getIntrinsicID()) {
287 // Lifetime markers are ignored.
288 case llvm::Intrinsic::lifetime_start:
289 case llvm::Intrinsic::lifetime_end:
290 // Invariant markers are ignored.
291 case llvm::Intrinsic::invariant_start:
292 case llvm::Intrinsic::invariant_end:
293 // Some misc annotations are ignored.
294 case llvm::Intrinsic::var_annotation:
295 case llvm::Intrinsic::ptr_annotation:
296 case llvm::Intrinsic::annotation:
297 case llvm::Intrinsic::donothing:
298 case llvm::Intrinsic::assume:
299 case llvm::Intrinsic::expect:
300 return;
301 default:
302 // Other intrinsics are copied.
303 break;
304 }
305 }
306
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000307 copyInstScalar(Stmt, Inst, BBMap, GlobalMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000308}
309
Johannes Doerfert275a1752015-02-24 16:16:32 +0000310void BlockGenerator::copyStmt(ScopStmt &Stmt, ValueMapT &GlobalMap,
311 LoopToScevMapT &LTS) {
312 assert(Stmt.isBlockStmt() &&
313 "Only block statements can be copied by the block generator");
314
315 ValueMapT BBMap;
316
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000317 BasicBlock *BB = Stmt.getBasicBlock();
Johannes Doerfert275a1752015-02-24 16:16:32 +0000318 copyBB(Stmt, BB, BBMap, GlobalMap, LTS);
319}
320
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000321BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000322 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000323 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000324 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000325 return CopyBB;
326}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000327
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000328BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
329 ValueMapT &BBMap, ValueMapT &GlobalMap,
330 LoopToScevMapT &LTS) {
331 BasicBlock *CopyBB = splitBB(BB);
332 copyBB(Stmt, BB, CopyBB, BBMap, GlobalMap, LTS);
333 return CopyBB;
334}
335
336void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
337 ValueMapT &BBMap, ValueMapT &GlobalMap,
338 LoopToScevMapT &LTS) {
339 Builder.SetInsertPoint(CopyBB->begin());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000340 EntryBB = &CopyBB->getParent()->getEntryBlock();
341
Tobias Grosser91f5b262014-06-04 08:06:40 +0000342 for (Instruction &Inst : *BB)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000343 copyInstruction(Stmt, &Inst, BBMap, GlobalMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000344
345 // After a basic block was copied store all scalars that escape this block
346 // in their alloca. First the scalars that have dependences inside the SCoP,
347 // then the ones that might escape the SCoP.
348 generateScalarStores(Stmt, BB, BBMap, GlobalMap);
349
350 const Region &R = Stmt.getParent()->getRegion();
351 for (Instruction &Inst : *BB)
352 handleOutsideUsers(R, &Inst, BBMap[&Inst]);
353}
354
Tobias Grosser0164b8f2015-08-13 08:07:39 +0000355AllocaInst *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000356 ScalarAllocaMapTy &Map,
357 const char *NameExt,
358 bool *IsNew) {
359
360 // Check if an alloca was cached for the base instruction.
361 AllocaInst *&Addr = Map[ScalarBase];
362
363 // If needed indicate if it was found already or will be created.
364 if (IsNew)
365 *IsNew = (Addr == nullptr);
366
367 // If no alloca was found create one and insert it in the entry block.
368 if (!Addr) {
369 auto *Ty = ScalarBase->getType();
370 Addr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
371 Addr->insertBefore(EntryBB->getFirstInsertionPt());
372 }
373
374 return Addr;
375}
376
377void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
378 Value *InstCopy) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000379 EscapeUserVectorTy EscapeUsers;
380 for (User *U : Inst->users()) {
381
382 // Non-instruction user will never escape.
383 Instruction *UI = dyn_cast<Instruction>(U);
384 if (!UI)
385 continue;
386
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000387 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000388 continue;
389
390 EscapeUsers.push_back(UI);
391 }
392
393 // Exit if no escape uses were found.
394 if (EscapeUsers.empty())
395 return;
396
397 // If there are escape users we get the alloca for this instruction and put
398 // it in the EscapeMap for later finalization. However, if the alloca was not
399 // created by an already handled scalar dependence we have to initialize it
400 // also. Lastly, if the instruction was copied multiple times we already did
401 // this and can exit.
402 if (EscapeMap.count(Inst))
403 return;
404
405 // Get or create an escape alloca for this instruction.
406 bool IsNew;
407 AllocaInst *ScalarAddr =
408 getOrCreateAlloca(Inst, ScalarMap, ".escape", &IsNew);
409
410 // Remember that this instruction has escape uses and the escape alloca.
411 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
412
413 // If the escape alloca was just created store the instruction in there,
414 // otherwise that happened already.
415 if (IsNew) {
416 assert(InstCopy && "Except PHIs every instruction should have a copy!");
417 Builder.CreateStore(InstCopy, ScalarAddr);
418 }
419}
420
421void BlockGenerator::generateScalarLoads(ScopStmt &Stmt,
422 const Instruction *Inst,
423 ValueMapT &BBMap) {
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000424 auto *MAL = Stmt.lookupAccessesFor(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000425
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000426 if (!MAL)
427 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000428
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000429 for (MemoryAccess &MA : *MAL) {
430 AllocaInst *Address;
431 if (!MA.isScalar() || !MA.isRead())
432 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000433
Tobias Grosser0164b8f2015-08-13 08:07:39 +0000434 auto Base = MA.getBaseAddr();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000435
Tobias Grosser92245222015-07-28 14:53:44 +0000436 if (MA.getScopArrayInfo()->isPHI())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000437 Address = getOrCreateAlloca(Base, PHIOpMap, ".phiops");
438 else
439 Address = getOrCreateAlloca(Base, ScalarMap, ".s2a");
440
441 BBMap[Base] = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000442 }
443}
444
445Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
446 ScalarAllocaMapTy &ReloadMap,
447 ValueMapT &BBMap,
448 ValueMapT &GlobalMap) {
449 // If the value we want to store is an instruction we might have demoted it
450 // in order to make it accessible here. In such a case a reload is
451 // necessary. If it is no instruction it will always be a value that
452 // dominates the current point and we can just use it. In total there are 4
453 // options:
454 // (1) The value is no instruction ==> use the value.
455 // (2) The value is an instruction that was split out of the region prior to
456 // code generation ==> use the instruction as it dominates the region.
457 // (3) The value is an instruction:
458 // (a) The value was defined in the current block, thus a copy is in
459 // the BBMap ==> use the mapped value.
460 // (b) The value was defined in a previous block, thus we demoted it
461 // earlier ==> use the reloaded value.
462 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
463 if (!ScalarValueInst)
464 return ScalarValue;
465
466 if (!R.contains(ScalarValueInst)) {
467 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
468 return /* Case (3a) */ ScalarValueCopy;
469 else
470 return /* Case 2 */ ScalarValue;
471 }
472
473 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
474 return /* Case (3a) */ ScalarValueCopy;
475
476 // Case (3b)
477 assert(ReloadMap.count(ScalarValueInst) &&
478 "ScalarInst not mapped in the block and not in the given reload map!");
479 Value *ReloadAddr = ReloadMap[ScalarValueInst];
480 ScalarValue =
481 Builder.CreateLoad(ReloadAddr, ReloadAddr->getName() + ".reload");
482
483 return ScalarValue;
484}
485
486void BlockGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
487 ValueMapT &BBMap,
488 ValueMapT &GlobalMap) {
489 const Region &R = Stmt.getParent()->getRegion();
490
491 assert(Stmt.isBlockStmt() && BB == Stmt.getBasicBlock() &&
492 "Region statements need to use the generateScalarStores() "
493 "function in the RegionGenerator");
494
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000495 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000496 if (!MA->isScalar() || MA->isRead())
497 continue;
498
Tobias Grosser92245222015-07-28 14:53:44 +0000499 Instruction *Base = cast<Instruction>(MA->getBaseAddr());
500 Instruction *Inst = MA->getAccessInstruction();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000501
Tobias Grosser92245222015-07-28 14:53:44 +0000502 Value *Val = nullptr;
503 AllocaInst *Address = nullptr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000504
Tobias Grosser92245222015-07-28 14:53:44 +0000505 if (MA->getScopArrayInfo()->isPHI()) {
506 PHINode *BasePHI = dyn_cast<PHINode>(Base);
507 int PHIIdx = BasePHI->getBasicBlockIndex(BB);
Michael Kruse9bb8ef032015-08-08 18:10:54 +0000508 assert(PHIIdx >= 0);
Tobias Grosser92245222015-07-28 14:53:44 +0000509 Address = getOrCreateAlloca(Base, PHIOpMap, ".phiops");
510 Val = BasePHI->getIncomingValue(PHIIdx);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000511 } else {
Tobias Grosser92245222015-07-28 14:53:44 +0000512 Address = getOrCreateAlloca(Base, ScalarMap, ".s2a");
513 Val = Inst;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000514 }
Tobias Grosser92245222015-07-28 14:53:44 +0000515 Val = getNewScalarValue(Val, R, ScalarMap, BBMap, GlobalMap);
516 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000517 }
518}
519
520void BlockGenerator::createScalarInitialization(Region &R,
521 ValueMapT &GlobalMap) {
522 // The split block __just before__ the region and optimized region.
523 BasicBlock *SplitBB = R.getEnteringBlock();
524 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
525 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
526
527 // Get the start block of the __optimized__ region.
528 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
529 if (StartBB == R.getEntry())
530 StartBB = SplitBBTerm->getSuccessor(1);
531
532 // For each PHI predecessor outside the region store the incoming operand
533 // value prior to entering the optimized region.
534 Builder.SetInsertPoint(StartBB->getTerminator());
535
536 ScalarAllocaMapTy EmptyMap;
537 for (const auto &PHIOpMapping : PHIOpMap) {
538 const PHINode *PHI = cast<PHINode>(PHIOpMapping.getFirst());
539
540 // Check if this PHI has the split block as predecessor (that is the only
541 // possible predecessor outside the SCoP).
542 int idx = PHI->getBasicBlockIndex(SplitBB);
543 if (idx < 0)
544 continue;
545
546 Value *ScalarValue = PHI->getIncomingValue(idx);
547 ScalarValue =
548 getNewScalarValue(ScalarValue, R, EmptyMap, GlobalMap, GlobalMap);
549
550 // If the split block is the predecessor initialize the PHI operator alloca.
551 Builder.CreateStore(ScalarValue, PHIOpMapping.getSecond());
552 }
553}
554
555void BlockGenerator::createScalarFinalization(Region &R) {
556 // The exit block of the __unoptimized__ region.
557 BasicBlock *ExitBB = R.getExitingBlock();
558 // The merge block __just after__ the region and the optimized region.
559 BasicBlock *MergeBB = R.getExit();
560
561 // The exit block of the __optimized__ region.
562 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
563 if (OptExitBB == ExitBB)
564 OptExitBB = *(++pred_begin(MergeBB));
565
566 Builder.SetInsertPoint(OptExitBB->getTerminator());
567 for (const auto &EscapeMapping : EscapeMap) {
568 // Extract the escaping instruction and the escaping users as well as the
569 // alloca the instruction was demoted to.
570 Instruction *EscapeInst = EscapeMapping.getFirst();
571 const auto &EscapeMappingValue = EscapeMapping.getSecond();
572 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
573 AllocaInst *ScalarAddr = EscapeMappingValue.first;
574
575 // Reload the demoted instruction in the optimized version of the SCoP.
576 Instruction *EscapeInstReload =
577 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
578
579 // Create the merge PHI that merges the optimized and unoptimized version.
580 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
581 EscapeInst->getName() + ".merge");
582 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
583
584 // Add the respective values to the merge PHI.
585 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
586 MergePHI->addIncoming(EscapeInst, ExitBB);
587
588 // The information of scalar evolution about the escaping instruction needs
589 // to be revoked so the new merged instruction will be used.
590 if (SE.isSCEVable(EscapeInst->getType()))
591 SE.forgetValue(EscapeInst);
592
593 // Replace all uses of the demoted instruction with the merge PHI.
594 for (Instruction *EUser : EscapeUsers)
595 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
596 }
597}
598
599void BlockGenerator::finalizeSCoP(Scop &S, ValueMapT &GlobalMap) {
600 createScalarInitialization(S.getRegion(), GlobalMap);
601 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000602}
603
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000604VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
605 VectorValueMapT &GlobalMaps,
606 std::vector<LoopToScevMapT> &VLTS,
607 isl_map *Schedule)
608 : BlockGenerator(BlockGen), GlobalMaps(GlobalMaps), VLTS(VLTS),
609 Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000610 assert(GlobalMaps.size() > 1 && "Only one vector lane found");
611 assert(Schedule && "No statement domain provided");
612}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000613
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000614Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, const Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000615 ValueMapT &VectorMap,
616 VectorValueMapT &ScalarMaps,
617 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000618 if (Value *NewValue = VectorMap.lookup(Old))
619 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000620
621 int Width = getVectorWidth();
622
623 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
624
625 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000626 Vector = Builder.CreateInsertElement(
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000627 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], GlobalMaps[Lane],
628 VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000629 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000630
631 VectorMap[Old] = Vector;
632
633 return Vector;
634}
635
636Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
637 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
638 assert(PointerTy && "PointerType expected");
639
640 Type *ScalarType = PointerTy->getElementType();
641 VectorType *VectorType = VectorType::get(ScalarType, Width);
642
643 return PointerType::getUnqual(VectorType);
644}
645
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000646Value *VectorBlockGenerator::generateStrideOneLoad(
647 ScopStmt &Stmt, const LoadInst *Load, VectorValueMapT &ScalarMaps,
648 bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000649 unsigned VectorWidth = getVectorWidth();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000650 const Value *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000651 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
652 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
653
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000654 Value *NewPointer = nullptr;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000655 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
Johannes Doerfert731685e2014-10-08 17:25:30 +0000656 GlobalMaps[Offset], VLTS[Offset]);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000657 Value *VectorPtr =
658 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
659 LoadInst *VecLoad =
660 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000661 if (!Aligned)
662 VecLoad->setAlignment(8);
663
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000664 if (NegativeStride) {
665 SmallVector<Constant *, 16> Indices;
666 for (int i = VectorWidth - 1; i >= 0; i--)
667 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
668 Constant *SV = llvm::ConstantVector::get(Indices);
669 Value *RevVecLoad = Builder.CreateShuffleVector(
670 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
671 return RevVecLoad;
672 }
673
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000674 return VecLoad;
675}
676
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000677Value *VectorBlockGenerator::generateStrideZeroLoad(ScopStmt &Stmt,
678 const LoadInst *Load,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000679 ValueMapT &BBMap) {
680 const Value *Pointer = Load->getPointerOperand();
681 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000682 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
683 GlobalMaps[0], VLTS[0]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000684 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
685 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000686 LoadInst *ScalarLoad =
687 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000688
689 if (!Aligned)
690 ScalarLoad->setAlignment(8);
691
Tobias Grosserc14582f2013-02-05 18:01:29 +0000692 Constant *SplatVector = Constant::getNullValue(
693 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000694
Tobias Grosserc14582f2013-02-05 18:01:29 +0000695 Value *VectorLoad = Builder.CreateShuffleVector(
696 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000697 return VectorLoad;
698}
699
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000700Value *VectorBlockGenerator::generateUnknownStrideLoad(
701 ScopStmt &Stmt, const LoadInst *Load, VectorValueMapT &ScalarMaps) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000702 int VectorWidth = getVectorWidth();
703 const Value *Pointer = Load->getPointerOperand();
704 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000705 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000706
707 Value *Vector = UndefValue::get(VectorType);
708
709 for (int i = 0; i < VectorWidth; i++) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000710 Value *NewPointer = generateLocationAccessed(
711 Stmt, Load, Pointer, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000712 Value *ScalarLoad =
713 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
714 Vector = Builder.CreateInsertElement(
715 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000716 }
717
718 return Vector;
719}
720
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000721void VectorBlockGenerator::generateLoad(ScopStmt &Stmt, const LoadInst *Load,
Tobias Grossere602a072013-05-07 07:30:56 +0000722 ValueMapT &VectorMap,
723 VectorValueMapT &ScalarMaps) {
Tobias Grosser28736452015-03-23 07:00:36 +0000724 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000725 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000726 ScalarMaps[i][Load] =
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000727 generateScalarLoad(Stmt, Load, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000728 return;
729 }
730
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000731 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000732
Tobias Grosser95493982014-04-18 09:46:35 +0000733 // Make sure we have scalar values available to access the pointer to
734 // the data location.
735 extractScalarValues(Load, VectorMap, ScalarMaps);
736
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000737 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000738 if (Access.isStrideZero(isl_map_copy(Schedule)))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000739 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0]);
Sebastian Popa00a0292012-12-18 07:46:06 +0000740 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000741 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000742 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000743 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000744 else
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000745 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000746
747 VectorMap[Load] = NewLoad;
748}
749
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000750void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt,
751 const UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000752 ValueMapT &VectorMap,
753 VectorValueMapT &ScalarMaps) {
754 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000755 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
756 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000757
758 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
759
760 const CastInst *Cast = dyn_cast<CastInst>(Inst);
761 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
762 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
763}
764
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000765void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt,
766 const BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000767 ValueMapT &VectorMap,
768 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000769 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000770 Value *OpZero = Inst->getOperand(0);
771 Value *OpOne = Inst->getOperand(1);
772
773 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000774 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
775 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000776
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000777 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000778 Inst->getName() + "p_vec");
779 VectorMap[Inst] = NewInst;
780}
781
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000782void VectorBlockGenerator::copyStore(ScopStmt &Stmt, const StoreInst *Store,
Tobias Grossere602a072013-05-07 07:30:56 +0000783 ValueMapT &VectorMap,
784 VectorValueMapT &ScalarMaps) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000785 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000786
787 const Value *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000788 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000789 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000790
Tobias Grosser50fd7012014-04-17 23:13:49 +0000791 // Make sure we have scalar values available to access the pointer to
792 // the data location.
793 extractScalarValues(Store, VectorMap, ScalarMaps);
794
Sebastian Popa00a0292012-12-18 07:46:06 +0000795 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000796 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000797 Value *NewPointer = generateLocationAccessed(
798 Stmt, Store, Pointer, ScalarMaps[0], GlobalMaps[0], VLTS[0]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000799
Tobias Grosserc14582f2013-02-05 18:01:29 +0000800 Value *VectorPtr =
801 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000802 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
803
804 if (!Aligned)
805 Store->setAlignment(8);
806 } else {
807 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000808 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Johannes Doerfert731685e2014-10-08 17:25:30 +0000809 Value *NewPointer = generateLocationAccessed(
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000810 Stmt, Store, Pointer, ScalarMaps[i], GlobalMaps[i], VLTS[i]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000811 Builder.CreateStore(Scalar, NewPointer);
812 }
813 }
814}
815
816bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
817 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000818 for (Value *Operand : Inst->operands())
819 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000820 return true;
821 return false;
822}
823
824bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
825 ValueMapT &VectorMap,
826 VectorValueMapT &ScalarMaps) {
827 bool HasVectorOperand = false;
828 int VectorWidth = getVectorWidth();
829
Tobias Grosser91f5b262014-06-04 08:06:40 +0000830 for (Value *Operand : Inst->operands()) {
831 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000832
833 if (VecOp == VectorMap.end())
834 continue;
835
836 HasVectorOperand = true;
837 Value *NewVector = VecOp->second;
838
839 for (int i = 0; i < VectorWidth; ++i) {
840 ValueMapT &SM = ScalarMaps[i];
841
842 // If there is one scalar extracted, all scalar elements should have
843 // already been extracted by the code here. So no need to check for the
844 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000845 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000846 break;
847
Tobias Grosser91f5b262014-06-04 08:06:40 +0000848 SM[Operand] =
849 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000850 }
851 }
852
853 return HasVectorOperand;
854}
855
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000856void VectorBlockGenerator::copyInstScalarized(ScopStmt &Stmt,
857 const Instruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000858 ValueMapT &VectorMap,
859 VectorValueMapT &ScalarMaps) {
860 bool HasVectorOperand;
861 int VectorWidth = getVectorWidth();
862
863 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
864
865 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000866 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Johannes Doerfert731685e2014-10-08 17:25:30 +0000867 GlobalMaps[VectorLane], VLTS[VectorLane]);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000868
869 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
870 return;
871
872 // Make the result available as vector value.
873 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
874 Value *Vector = UndefValue::get(VectorType);
875
876 for (int i = 0; i < VectorWidth; i++)
877 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
878 Builder.getInt32(i));
879
880 VectorMap[Inst] = Vector;
881}
882
Tobias Grosserc14582f2013-02-05 18:01:29 +0000883int VectorBlockGenerator::getVectorWidth() { return GlobalMaps.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000884
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000885void VectorBlockGenerator::copyInstruction(ScopStmt &Stmt,
886 const Instruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000887 ValueMapT &VectorMap,
888 VectorValueMapT &ScalarMaps) {
889 // Terminator instructions control the control flow. They are explicitly
890 // expressed in the clast and do not need to be copied.
891 if (Inst->isTerminator())
892 return;
893
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000894 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000895 return;
896
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000897 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000898 generateLoad(Stmt, Load, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000899 return;
900 }
901
902 if (hasVectorOperands(Inst, VectorMap)) {
903 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000904 copyStore(Stmt, Store, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000905 return;
906 }
907
908 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000909 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000910 return;
911 }
912
913 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000914 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000915 return;
916 }
917
918 // Falltrough: We generate scalar instructions, if we don't know how to
919 // generate vector code.
920 }
921
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000922 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000923}
924
Johannes Doerfert275a1752015-02-24 16:16:32 +0000925void VectorBlockGenerator::copyStmt(ScopStmt &Stmt) {
926 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
927 "the vector block generator");
928
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000929 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000930 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000931 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000932 CopyBB->setName("polly.stmt." + BB->getName());
933 Builder.SetInsertPoint(CopyBB->begin());
934
935 // Create two maps that store the mapping from the original instructions of
936 // the old basic block to their copies in the new basic block. Those maps
937 // are basic block local.
938 //
939 // As vector code generation is supported there is one map for scalar values
940 // and one for vector values.
941 //
942 // In case we just do scalar code generation, the vectorMap is not used and
943 // the scalarMap has just one dimension, which contains the mapping.
944 //
945 // In case vector code generation is done, an instruction may either appear
946 // in the vector map once (as it is calculating >vectorwidth< values at a
947 // time. Or (if the values are calculated using scalar operations), it
948 // appears once in every dimension of the scalarMap.
949 VectorValueMapT ScalarBlockMap(getVectorWidth());
950 ValueMapT VectorBlockMap;
951
Tobias Grosser91f5b262014-06-04 08:06:40 +0000952 for (Instruction &Inst : *BB)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000953 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000954}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000955
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000956BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
957 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000958
959 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
960 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
961
962 if (BBCopyIDom)
963 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
964
965 return BBCopyIDom;
966}
967
Johannes Doerfert275a1752015-02-24 16:16:32 +0000968void RegionGenerator::copyStmt(ScopStmt &Stmt, ValueMapT &GlobalMap,
969 LoopToScevMapT &LTS) {
970 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +0000971 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +0000972
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000973 // Forget all old mappings.
974 BlockMap.clear();
975 RegionMaps.clear();
976 IncompletePHINodeMap.clear();
977
Johannes Doerfert275a1752015-02-24 16:16:32 +0000978 // The region represented by the statement.
979 Region *R = Stmt.getRegion();
980
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000981 // Create a dedicated entry for the region where we can reload all demoted
982 // inputs.
983 BasicBlock *EntryBB = R->getEntry();
984 BasicBlock *EntryBBCopy =
985 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
986 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
987 Builder.SetInsertPoint(EntryBBCopy->begin());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000988
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000989 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
990 if (!R->contains(*PI))
991 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +0000992
993 // Iterate over all blocks in the region in a breadth-first search.
994 std::deque<BasicBlock *> Blocks;
995 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000996 Blocks.push_back(EntryBB);
997 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000998
999 while (!Blocks.empty()) {
1000 BasicBlock *BB = Blocks.front();
1001 Blocks.pop_front();
1002
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001003 // First split the block and update dominance information.
1004 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001005 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1006
1007 // In order to remap PHI nodes we store also basic block mappings.
1008 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001009
1010 // Get the mapping for this block and initialize it with the mapping
1011 // available at its immediate dominator (in the new region).
1012 ValueMapT &RegionMap = RegionMaps[BBCopy];
1013 RegionMap = RegionMaps[BBCopyIDom];
1014
Johannes Doerfert275a1752015-02-24 16:16:32 +00001015 // Copy the block with the BlockGenerator.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001016 copyBB(Stmt, BB, BBCopy, RegionMap, GlobalMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001017
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001018 // In order to remap PHI nodes we store also basic block mappings.
1019 BlockMap[BB] = BBCopy;
1020
1021 // Add values to incomplete PHI nodes waiting for this block to be copied.
1022 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1023 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB,
1024 GlobalMap, LTS);
1025 IncompletePHINodeMap[BB].clear();
1026
Johannes Doerfert275a1752015-02-24 16:16:32 +00001027 // And continue with new successors inside the region.
1028 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1029 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1030 Blocks.push_back(*SI);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001031 }
1032
1033 // Now create a new dedicated region exit block and add it to the region map.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001034 BasicBlock *ExitBBCopy =
Johannes Doerfert275a1752015-02-24 16:16:32 +00001035 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001036 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001037 BlockMap[R->getExit()] = ExitBBCopy;
1038
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001039 repairDominance(R->getExit(), ExitBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001040
1041 // As the block generator doesn't handle control flow we need to add the
1042 // region control flow by hand after all blocks have been copied.
1043 for (BasicBlock *BB : SeenBlocks) {
1044
1045 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1046
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001047 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerfert275a1752015-02-24 16:16:32 +00001048 Instruction *BICopy = BBCopy->getTerminator();
1049
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001050 ValueMapT &RegionMap = RegionMaps[BBCopy];
1051 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1052
Tobias Grosser45e79442015-08-01 09:07:57 +00001053 Builder.SetInsertPoint(BICopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001054 copyInstScalar(Stmt, BI, RegionMap, GlobalMap, LTS);
1055 BICopy->eraseFromParent();
1056 }
1057
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001058 // Add counting PHI nodes to all loops in the region that can be used as
1059 // replacement for SCEVs refering to the old loop.
1060 for (BasicBlock *BB : SeenBlocks) {
1061 Loop *L = LI.getLoopFor(BB);
1062 if (L == nullptr || L->getHeader() != BB)
1063 continue;
1064
1065 BasicBlock *BBCopy = BlockMap[BB];
1066 Value *NullVal = Builder.getInt32(0);
1067 PHINode *LoopPHI =
1068 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1069 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1070 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1071 LoopPHI->insertBefore(BBCopy->begin());
1072 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1073
1074 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1075 if (!R->contains(PredBB))
1076 continue;
1077 if (L->contains(PredBB))
1078 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1079 else
1080 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1081 }
1082
1083 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1084 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1085 LoopPHI->addIncoming(NullVal, PredBBCopy);
1086
1087 LTS[L] = SE.getUnknown(LoopPHI);
1088 }
1089
1090 // Add all mappings from the region to the global map so outside uses will use
1091 // the copied instructions.
1092 for (auto &BBMap : RegionMaps)
1093 GlobalMap.insert(BBMap.second.begin(), BBMap.second.end());
1094
Johannes Doerfert275a1752015-02-24 16:16:32 +00001095 // Reset the old insert point for the build.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001096 Builder.SetInsertPoint(ExitBBCopy->begin());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001097}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001098
1099void RegionGenerator::generateScalarLoads(ScopStmt &Stmt,
1100 const Instruction *Inst,
1101 ValueMapT &BBMap) {
1102
1103 // Inside a non-affine region PHI nodes are copied not demoted. Once the
1104 // phi is copied it will reload all inputs from outside the region, hence
1105 // we do not need to generate code for the read access of the operands of a
1106 // PHI.
1107 if (isa<PHINode>(Inst))
1108 return;
1109
1110 return BlockGenerator::generateScalarLoads(Stmt, Inst, BBMap);
1111}
1112
1113void RegionGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
1114 ValueMapT &BBMap,
1115 ValueMapT &GlobalMap) {
1116 const Region &R = Stmt.getParent()->getRegion();
1117
1118 Region *StmtR = Stmt.getRegion();
1119 assert(StmtR && "Block statements need to use the generateScalarStores() "
1120 "function in the BlockGenerator");
1121
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001122 for (MemoryAccess *MA : Stmt) {
1123
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001124 if (!MA->isScalar() || MA->isRead())
1125 continue;
1126
1127 Instruction *ScalarBase = cast<Instruction>(MA->getBaseAddr());
1128 Instruction *ScalarInst = MA->getAccessInstruction();
1129 PHINode *ScalarBasePHI = dyn_cast<PHINode>(ScalarBase);
1130
Tobias Grosser62139132015-08-02 16:17:41 +00001131 // Only generate accesses that belong to this basic block.
1132 if (ScalarInst->getParent() != BB)
1133 continue;
1134
Tobias Grosser92245222015-07-28 14:53:44 +00001135 Value *Val = nullptr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001136 AllocaInst *ScalarAddr = nullptr;
1137
Tobias Grosser92245222015-07-28 14:53:44 +00001138 if (MA->getScopArrayInfo()->isPHI()) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001139 int PHIIdx = ScalarBasePHI->getBasicBlockIndex(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001140 ScalarAddr = getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosser92245222015-07-28 14:53:44 +00001141 Val = ScalarBasePHI->getIncomingValue(PHIIdx);
1142 } else {
1143 ScalarAddr = getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
1144 Val = ScalarInst;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001145 }
1146
Tobias Grosser92245222015-07-28 14:53:44 +00001147 Val = getNewScalarValue(Val, R, ScalarMap, BBMap, GlobalMap);
1148 Builder.CreateStore(Val, ScalarAddr);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001149 }
1150}
1151
1152void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1153 PHINode *PHICopy, BasicBlock *IncomingBB,
1154 ValueMapT &GlobalMap,
1155 LoopToScevMapT &LTS) {
1156 Region *StmtR = Stmt.getRegion();
1157
1158 // If the incoming block was not yet copied mark this PHI as incomplete.
1159 // Once the block will be copied the incoming value will be added.
1160 BasicBlock *BBCopy = BlockMap[IncomingBB];
1161 if (!BBCopy) {
1162 assert(StmtR->contains(IncomingBB) &&
1163 "Bad incoming block for PHI in non-affine region");
1164 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1165 return;
1166 }
1167
1168 Value *OpCopy = nullptr;
1169 if (StmtR->contains(IncomingBB)) {
1170 assert(RegionMaps.count(BBCopy) &&
1171 "Incoming PHI block did not have a BBMap");
1172 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1173
1174 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1175 OpCopy =
1176 getNewValue(Stmt, Op, BBCopyMap, GlobalMap, LTS, getLoopForInst(PHI));
1177 } else {
1178
1179 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1180 return;
1181
1182 AllocaInst *PHIOpAddr =
1183 getOrCreateAlloca(const_cast<PHINode *>(PHI), PHIOpMap, ".phiops");
1184 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1185 BlockMap[IncomingBB]->getTerminator());
1186 }
1187
1188 assert(OpCopy && "Incoming PHI value was not copied properly");
1189 assert(BBCopy && "Incoming PHI block was not copied properly");
1190 PHICopy->addIncoming(OpCopy, BBCopy);
1191}
1192
1193Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, const PHINode *PHI,
1194 ValueMapT &BBMap,
1195 ValueMapT &GlobalMap,
1196 LoopToScevMapT &LTS) {
1197 unsigned NumIncoming = PHI->getNumIncomingValues();
1198 PHINode *PHICopy =
1199 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1200 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1201 BBMap[PHI] = PHICopy;
1202
1203 for (unsigned u = 0; u < NumIncoming; u++)
1204 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), GlobalMap,
1205 LTS);
1206 return PHICopy;
1207}