blob: d0dddb18301b1b08d2b8eefbd147d7235851f579 [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 Grosser86bc93a2015-09-06 08:47:57 +000020#include "polly/CodeGen/RuntimeDebugBuilder.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"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000026#include "llvm/Analysis/RegionInfo.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000027#include "llvm/Analysis/ScalarEvolution.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 Grosser86bc93a2015-09-06 08:47:57 +000045static cl::opt<bool> DebugPrinting(
46 "polly-codegen-add-debug-printing",
47 cl::desc("Add printf calls that show the values loaded/stored."),
48 cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
49
Tobias Grosserdcc3b432015-08-04 13:54:20 +000050bool polly::canSynthesize(const Value *V, const llvm::LoopInfo *LI,
Tobias Grosserecfe21b2013-03-20 18:03:18 +000051 ScalarEvolution *SE, const Region *R) {
Tobias Grosserdcc3b432015-08-04 13:54:20 +000052 if (!V || !SE->isSCEVable(V->getType()))
Tobias Grosserecfe21b2013-03-20 18:03:18 +000053 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000054
Tobias Grosserdcc3b432015-08-04 13:54:20 +000055 if (const SCEV *Scev = SE->getSCEV(const_cast<Value *>(V)))
Tobias Grosser683b8e42014-11-30 14:33:31 +000056 if (!isa<SCEVCouldNotCompute>(Scev))
57 if (!hasScalarDepsInsideRegion(Scev, R))
58 return true;
59
60 return false;
Tobias Grosserecfe21b2013-03-20 18:03:18 +000061}
62
Johannes Doerfert9e3a5db2015-01-26 15:55:54 +000063bool polly::isIgnoredIntrinsic(const Value *V) {
64 if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
65 switch (IT->getIntrinsicID()) {
66 // Lifetime markers are supported/ignored.
67 case llvm::Intrinsic::lifetime_start:
68 case llvm::Intrinsic::lifetime_end:
69 // Invariant markers are supported/ignored.
70 case llvm::Intrinsic::invariant_start:
71 case llvm::Intrinsic::invariant_end:
72 // Some misc annotations are supported/ignored.
73 case llvm::Intrinsic::var_annotation:
74 case llvm::Intrinsic::ptr_annotation:
75 case llvm::Intrinsic::annotation:
76 case llvm::Intrinsic::donothing:
77 case llvm::Intrinsic::assume:
78 case llvm::Intrinsic::expect:
Tobias Grossere83a3962015-08-30 16:57:20 +000079 // Some debug info intrisics are supported/ignored.
80 case llvm::Intrinsic::dbg_value:
81 case llvm::Intrinsic::dbg_declare:
Johannes Doerfert9e3a5db2015-01-26 15:55:54 +000082 return true;
83 default:
84 break;
85 }
86 }
87 return false;
88}
89
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000090BlockGenerator::BlockGenerator(PollyIRBuilder &B, LoopInfo &LI,
91 ScalarEvolution &SE, DominatorTree &DT,
Johannes Doerfertecff11d2015-05-22 23:43:58 +000092 ScalarAllocaMapTy &ScalarMap,
93 ScalarAllocaMapTy &PHIOpMap,
94 EscapeUsersAllocaMapTy &EscapeMap,
Tobias Grosserbc132602015-09-05 09:56:54 +000095 ValueToValueMap &GlobalMap,
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000096 IslExprBuilder *ExprBuilder)
Johannes Doerfertecff11d2015-05-22 23:43:58 +000097 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
98 EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap),
Tobias Grosserbc132602015-09-05 09:56:54 +000099 EscapeMap(EscapeMap), GlobalMap(GlobalMap) {}
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000100
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000101Value *BlockGenerator::getNewValue(ScopStmt &Stmt, const Value *Old,
Tobias Grosserbc132602015-09-05 09:56:54 +0000102 ValueMapT &BBMap, LoopToScevMapT &LTS,
103 Loop *L) const {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000104 // We assume constants never change.
105 // This avoids map lookups for many calls to this function.
106 if (isa<Constant>(Old))
Tobias Grosserc14582f2013-02-05 18:01:29 +0000107 return const_cast<Value *>(Old);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000108
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000109 if (Value *New = GlobalMap.lookup(Old)) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000110 if (Old->getType()->getScalarSizeInBits() <
Tobias Grosserd7e58642013-04-10 06:55:45 +0000111 New->getType()->getScalarSizeInBits())
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000112 New = Builder.CreateTruncOrBitCast(New, Old->getType());
113
114 return New;
115 }
116
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000117 if (Value *New = BBMap.lookup(Old))
118 return New;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000119
Tobias Grosser683b8e42014-11-30 14:33:31 +0000120 if (SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +0000121 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000122 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +0000123 const SCEV *NewScev = apply(Scev, LTS, SE);
124 ValueToValueMap VTV;
125 VTV.insert(BBMap.begin(), BBMap.end());
126 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Sebastian Pop47d4ee32013-02-15 21:26:53 +0000127 NewScev = SCEVParameterRewriter::rewrite(NewScev, SE, VTV);
Johannes Doerferte69e1142015-08-18 11:56:00 +0000128
129 Scop &S = *Stmt.getParent();
130 const DataLayout &DL =
131 S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
132 auto IP = Builder.GetInsertPoint();
133
134 assert(IP != Builder.GetInsertBlock()->end() &&
Tobias Grosser45e79442015-08-01 09:07:57 +0000135 "Only instructions can be insert points for SCEVExpander");
Johannes Doerferte69e1142015-08-18 11:56:00 +0000136 Value *Expanded =
137 expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), IP);
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000138
139 BBMap[Old] = Expanded;
140 return Expanded;
141 }
Tobias Grosser369430f2013-03-22 23:42:53 +0000142 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000143
Tobias Grosser16371ac2014-11-05 20:48:56 +0000144 // A scop-constant value defined by a global or a function parameter.
145 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
146 return const_cast<Value *>(Old);
147
148 // A scop-constant value defined by an instruction executed outside the scop.
149 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000150 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser16371ac2014-11-05 20:48:56 +0000151 return const_cast<Value *>(Old);
152
153 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000154 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000155 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000156}
157
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000158void BlockGenerator::copyInstScalar(ScopStmt &Stmt, const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000159 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000160 // We do not generate debug intrinsics as we did not investigate how to
161 // copy them correctly. At the current state, they just crash the code
162 // generation as the meta-data operands are not correctly copied.
163 if (isa<DbgInfoIntrinsic>(Inst))
164 return;
165
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000166 Instruction *NewInst = Inst->clone();
167
168 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000169 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000170 Value *NewOperand =
171 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000172
173 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000174 assert(!isa<StoreInst>(NewInst) &&
175 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000176 delete NewInst;
177 return;
178 }
179
180 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
181 }
182
183 Builder.Insert(NewInst);
184 BBMap[Inst] = NewInst;
185
186 if (!NewInst->getType()->isVoidTy())
187 NewInst->setName("p_" + Inst->getName());
188}
189
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000190Value *BlockGenerator::generateLocationAccessed(
191 ScopStmt &Stmt, const Instruction *Inst, const Value *Pointer,
Tobias Grosserbc132602015-09-05 09:56:54 +0000192 ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000193 const MemoryAccess &MA = Stmt.getAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000194
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000195 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000196
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000197 if (AccessExpr) {
198 AccessExpr = isl_ast_expr_address_of(AccessExpr);
199 return ExprBuilder->create(AccessExpr);
200 }
201
Tobias Grosserbc132602015-09-05 09:56:54 +0000202 return getNewValue(Stmt, Pointer, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000203}
204
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000205Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000206 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000207}
208
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000209Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, const LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000210 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000211 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000212 const Value *Pointer = Load->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000213 Value *NewPointer =
214 generateLocationAccessed(Stmt, Load, Pointer, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000215 Value *ScalarLoad = Builder.CreateAlignedLoad(
216 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000217
218 if (DebugPrinting)
219 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
220 ": ", ScalarLoad, "\n");
221
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000222 return ScalarLoad;
223}
224
Tobias Grosserc186ac72015-08-11 08:13:15 +0000225void BlockGenerator::generateScalarStore(ScopStmt &Stmt, const StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000226 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000227 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000228 const Value *Pointer = Store->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000229 Value *NewPointer =
230 generateLocationAccessed(Stmt, Store, Pointer, BBMap, LTS, NewAccesses);
231 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
232 getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000233
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000234 if (DebugPrinting)
235 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
236 ": ", ValueOperand, "\n");
237
Tobias Grosserc186ac72015-08-11 08:13:15 +0000238 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000239}
240
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000241void BlockGenerator::copyInstruction(ScopStmt &Stmt, const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000242 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000243 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000244
245 // First check for possible scalar dependences for this instruction.
Tobias Grosserbc132602015-09-05 09:56:54 +0000246 generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000247
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000248 // Terminator instructions control the control flow. They are explicitly
249 // expressed in the clast and do not need to be copied.
250 if (Inst->isTerminator())
251 return;
252
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000253 Loop *L = getLoopForInst(Inst);
254 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
255 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000256 Value *NewValue = getNewValue(Stmt, Inst, BBMap, LTS, L);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000257 BBMap[Inst] = NewValue;
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000258 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000259 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000260
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000261 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000262 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000263 // Compute NewLoad before its insertion in BBMap to make the insertion
264 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000265 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000266 return;
267 }
268
269 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000270 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000271 return;
272 }
273
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000274 if (const PHINode *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000275 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000276 return;
277 }
278
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000279 // Skip some special intrinsics for which we do not adjust the semantics to
280 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000281 if (isIgnoredIntrinsic(Inst))
282 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000283
Tobias Grosserbc132602015-09-05 09:56:54 +0000284 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000285}
286
Tobias Grosserbc132602015-09-05 09:56:54 +0000287void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000288 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000289 assert(Stmt.isBlockStmt() &&
290 "Only block statements can be copied by the block generator");
291
292 ValueMapT BBMap;
293
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000294 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000295 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000296}
297
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000298BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000299 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000300 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000301 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000302 return CopyBB;
303}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000304
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000305BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000306 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000307 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000308 BasicBlock *CopyBB = splitBB(BB);
Tobias Grosserbc132602015-09-05 09:56:54 +0000309 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000310 return CopyBB;
311}
312
313void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000314 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000315 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000316 Builder.SetInsertPoint(CopyBB->begin());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000317 EntryBB = &CopyBB->getParent()->getEntryBlock();
318
Tobias Grosser91f5b262014-06-04 08:06:40 +0000319 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000320 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000321
322 // After a basic block was copied store all scalars that escape this block
323 // in their alloca. First the scalars that have dependences inside the SCoP,
324 // then the ones that might escape the SCoP.
Tobias Grosserbc132602015-09-05 09:56:54 +0000325 generateScalarStores(Stmt, BB, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000326
327 const Region &R = Stmt.getParent()->getRegion();
328 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000329 handleOutsideUsers(R, &Inst, BBMap[&Inst]);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000330}
331
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000332Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
333 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000334 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000335 // Check if an alloca was cached for the base instruction.
336 AllocaInst *&Addr = Map[ScalarBase];
337
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000338 // If no alloca was found create one and insert it in the entry block.
339 if (!Addr) {
340 auto *Ty = ScalarBase->getType();
341 Addr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000342 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000343 Addr->insertBefore(EntryBB->getFirstInsertionPt());
344 }
345
Tobias Grosserbc132602015-09-05 09:56:54 +0000346 if (GlobalMap.count(Addr))
347 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000348
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000349 return Addr;
350}
351
Tobias Grosserbc132602015-09-05 09:56:54 +0000352Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000353 if (Access.getScopArrayInfo()->isPHI())
Tobias Grosserbc132602015-09-05 09:56:54 +0000354 return getOrCreatePHIAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000355 else
Tobias Grosserbc132602015-09-05 09:56:54 +0000356 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000357}
358
Tobias Grosserbc132602015-09-05 09:56:54 +0000359Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
360 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000361}
362
Tobias Grosserbc132602015-09-05 09:56:54 +0000363Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
364 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000365}
366
Tobias Grosserbc132602015-09-05 09:56:54 +0000367void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Johannes Doerfert717b8662015-09-08 21:44:27 +0000368 Value *InstCopy, AllocaInst *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000369 // If there are escape users we get the alloca for this instruction and put it
370 // in the EscapeMap for later finalization. Lastly, if the instruction was
371 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000372 if (EscapeMap.count(Inst))
373 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000374
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000375 EscapeUserVectorTy EscapeUsers;
376 for (User *U : Inst->users()) {
377
378 // Non-instruction user will never escape.
379 Instruction *UI = dyn_cast<Instruction>(U);
380 if (!UI)
381 continue;
382
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000383 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000384 continue;
385
386 EscapeUsers.push_back(UI);
387 }
388
389 // Exit if no escape uses were found.
390 if (EscapeUsers.empty())
391 return;
392
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000393 // Get or create an escape alloca for this instruction.
Johannes Doerfert717b8662015-09-08 21:44:27 +0000394 auto *ScalarAddr =
395 Address ? Address : cast<AllocaInst>(getOrCreateScalarAlloca(Inst));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000396
397 // Remember that this instruction has escape uses and the escape alloca.
398 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000399}
400
401void BlockGenerator::generateScalarLoads(ScopStmt &Stmt,
402 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000403 ValueMapT &BBMap) {
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000404 auto *MAL = Stmt.lookupAccessesFor(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000405
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000406 if (!MAL)
407 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000408
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000409 for (MemoryAccess &MA : *MAL) {
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000410 if (!MA.isScalar() || !MA.isRead())
411 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000412
Tobias Grosserbc132602015-09-05 09:56:54 +0000413 auto *Address = getOrCreateAlloca(MA);
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000414 BBMap[MA.getBaseAddr()] =
415 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000416 }
417}
418
419Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosserbc132602015-09-05 09:56:54 +0000420 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000421 // If the value we want to store is an instruction we might have demoted it
422 // in order to make it accessible here. In such a case a reload is
423 // necessary. If it is no instruction it will always be a value that
424 // dominates the current point and we can just use it. In total there are 4
425 // options:
426 // (1) The value is no instruction ==> use the value.
427 // (2) The value is an instruction that was split out of the region prior to
428 // code generation ==> use the instruction as it dominates the region.
429 // (3) The value is an instruction:
430 // (a) The value was defined in the current block, thus a copy is in
431 // the BBMap ==> use the mapped value.
432 // (b) The value was defined in a previous block, thus we demoted it
433 // earlier ==> use the reloaded value.
434 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
435 if (!ScalarValueInst)
436 return ScalarValue;
437
438 if (!R.contains(ScalarValueInst)) {
439 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
440 return /* Case (3a) */ ScalarValueCopy;
441 else
442 return /* Case 2 */ ScalarValue;
443 }
444
445 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
446 return /* Case (3a) */ ScalarValueCopy;
447
448 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000449 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000450 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000451
452 return ScalarValue;
453}
454
455void BlockGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000456 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000457 const Region &R = Stmt.getParent()->getRegion();
458
459 assert(Stmt.isBlockStmt() && BB == Stmt.getBasicBlock() &&
460 "Region statements need to use the generateScalarStores() "
461 "function in the RegionGenerator");
462
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000463 for (MemoryAccess *MA : Stmt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000464 if (!MA->isScalar() || MA->isRead())
465 continue;
466
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000467 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000468 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000469
Tobias Grosserbc132602015-09-05 09:56:54 +0000470 Val = getNewScalarValue(Val, R, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000471 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000472 }
473}
474
Tobias Grosserc0091a72015-08-30 19:19:34 +0000475void BlockGenerator::createScalarInitialization(Scop &S) {
476 Region &R = S.getRegion();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000477 // The split block __just before__ the region and optimized region.
478 BasicBlock *SplitBB = R.getEnteringBlock();
479 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
480 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
481
482 // Get the start block of the __optimized__ region.
483 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
484 if (StartBB == R.getEntry())
485 StartBB = SplitBBTerm->getSuccessor(1);
486
Tobias Grosser9f3d55c2015-08-31 11:06:19 +0000487 Builder.SetInsertPoint(StartBB->begin());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000488
Tobias Grosserc0091a72015-08-30 19:19:34 +0000489 for (auto &Pair : S.arrays()) {
490 auto &Array = Pair.second;
491 if (Array->getNumberOfDimensions() != 0)
492 continue;
493 if (Array->isPHI()) {
494 // For PHI nodes, the only values we need to store are the ones that
495 // reach the PHI node from outside the region. In general there should
496 // only be one such incoming edge and this edge should enter through
497 // 'SplitBB'.
498 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000499
Tobias Grosserc0091a72015-08-30 19:19:34 +0000500 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
501 if (!R.contains(*BI) && *BI != SplitBB)
502 llvm_unreachable("Incoming edges from outside the scop should always "
503 "come from SplitBB");
504
505 int Idx = PHI->getBasicBlockIndex(SplitBB);
506 if (Idx < 0)
507 continue;
508
509 Value *ScalarValue = PHI->getIncomingValue(Idx);
510
Tobias Grosserbc132602015-09-05 09:56:54 +0000511 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000512 continue;
513 }
514
515 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
516
517 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000518 continue;
519
Johannes Doerfert717b8662015-09-08 21:44:27 +0000520 // PHI nodes that are not marked as such in their SAI object are exit PHI
521 // nodes we model as common scalars but do not need to initialize.
522 if (Inst && isa<PHINode>(Inst))
523 continue;
524
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000525 ValueMapT EmptyMap;
Tobias Grosserc0091a72015-08-30 19:19:34 +0000526 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000527 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000528 }
529}
530
531void BlockGenerator::createScalarFinalization(Region &R) {
532 // The exit block of the __unoptimized__ region.
533 BasicBlock *ExitBB = R.getExitingBlock();
534 // The merge block __just after__ the region and the optimized region.
535 BasicBlock *MergeBB = R.getExit();
536
537 // The exit block of the __optimized__ region.
538 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
539 if (OptExitBB == ExitBB)
540 OptExitBB = *(++pred_begin(MergeBB));
541
542 Builder.SetInsertPoint(OptExitBB->getTerminator());
543 for (const auto &EscapeMapping : EscapeMap) {
544 // Extract the escaping instruction and the escaping users as well as the
545 // alloca the instruction was demoted to.
546 Instruction *EscapeInst = EscapeMapping.getFirst();
547 const auto &EscapeMappingValue = EscapeMapping.getSecond();
548 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000549 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000550
551 // Reload the demoted instruction in the optimized version of the SCoP.
552 Instruction *EscapeInstReload =
553 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
554
555 // Create the merge PHI that merges the optimized and unoptimized version.
556 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
557 EscapeInst->getName() + ".merge");
558 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
559
560 // Add the respective values to the merge PHI.
561 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
562 MergePHI->addIncoming(EscapeInst, ExitBB);
563
564 // The information of scalar evolution about the escaping instruction needs
565 // to be revoked so the new merged instruction will be used.
566 if (SE.isSCEVable(EscapeInst->getType()))
567 SE.forgetValue(EscapeInst);
568
569 // Replace all uses of the demoted instruction with the merge PHI.
570 for (Instruction *EUser : EscapeUsers)
571 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
572 }
573}
574
Tobias Grosser655a4572015-08-30 17:32:39 +0000575void BlockGenerator::finalizeSCoP(Scop &S) {
Johannes Doerfert717b8662015-09-08 21:44:27 +0000576
577 // Handle PHI nodes that were in the original exit and are now
578 // moved into the region exiting block.
579 if (!S.hasSingleExitEdge()) {
580 for (Instruction &I : *S.getRegion().getExitingBlock()) {
581 PHINode *PHI = dyn_cast<PHINode>(&I);
582 if (!PHI)
583 break;
584
585 assert(PHI->getNumUses() == 1);
586 assert(ScalarMap.count(PHI->user_back()));
587
588 handleOutsideUsers(S.getRegion(), PHI, nullptr,
589 ScalarMap[PHI->user_back()]);
590 }
591 }
592
Tobias Grosserc0091a72015-08-30 19:19:34 +0000593 createScalarInitialization(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000594 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000595}
596
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000597VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000598 std::vector<LoopToScevMapT> &VLTS,
599 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000600 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000601 assert(Schedule && "No statement domain provided");
602}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000603
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000604Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, const Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000605 ValueMapT &VectorMap,
606 VectorValueMapT &ScalarMaps,
607 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000608 if (Value *NewValue = VectorMap.lookup(Old))
609 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000610
611 int Width = getVectorWidth();
612
613 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
614
615 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000616 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000617 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000618 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000619
620 VectorMap[Old] = Vector;
621
622 return Vector;
623}
624
625Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
626 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
627 assert(PointerTy && "PointerType expected");
628
629 Type *ScalarType = PointerTy->getElementType();
630 VectorType *VectorType = VectorType::get(ScalarType, Width);
631
632 return PointerType::getUnqual(VectorType);
633}
634
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000635Value *VectorBlockGenerator::generateStrideOneLoad(
636 ScopStmt &Stmt, const LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000637 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000638 unsigned VectorWidth = getVectorWidth();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000639 const Value *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000640 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
641 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
642
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000643 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000644 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
645 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000646 Value *VectorPtr =
647 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
648 LoadInst *VecLoad =
649 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000650 if (!Aligned)
651 VecLoad->setAlignment(8);
652
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000653 if (NegativeStride) {
654 SmallVector<Constant *, 16> Indices;
655 for (int i = VectorWidth - 1; i >= 0; i--)
656 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
657 Constant *SV = llvm::ConstantVector::get(Indices);
658 Value *RevVecLoad = Builder.CreateShuffleVector(
659 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
660 return RevVecLoad;
661 }
662
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000663 return VecLoad;
664}
665
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000666Value *VectorBlockGenerator::generateStrideZeroLoad(
667 ScopStmt &Stmt, const LoadInst *Load, ValueMapT &BBMap,
668 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000669 const Value *Pointer = Load->getPointerOperand();
670 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000671 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
672 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000673 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
674 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000675 LoadInst *ScalarLoad =
676 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000677
678 if (!Aligned)
679 ScalarLoad->setAlignment(8);
680
Tobias Grosserc14582f2013-02-05 18:01:29 +0000681 Constant *SplatVector = Constant::getNullValue(
682 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000683
Tobias Grosserc14582f2013-02-05 18:01:29 +0000684 Value *VectorLoad = Builder.CreateShuffleVector(
685 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000686 return VectorLoad;
687}
688
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000689Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000690 ScopStmt &Stmt, const LoadInst *Load, VectorValueMapT &ScalarMaps,
691 __isl_keep isl_id_to_ast_expr *NewAccesses
692
693 ) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000694 int VectorWidth = getVectorWidth();
695 const Value *Pointer = Load->getPointerOperand();
696 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000697 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000698
699 Value *Vector = UndefValue::get(VectorType);
700
701 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000702 Value *NewPointer = generateLocationAccessed(
703 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000704 Value *ScalarLoad =
705 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
706 Vector = Builder.CreateInsertElement(
707 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000708 }
709
710 return Vector;
711}
712
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000713void VectorBlockGenerator::generateLoad(
714 ScopStmt &Stmt, const LoadInst *Load, ValueMapT &VectorMap,
715 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser28736452015-03-23 07:00:36 +0000716 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000717 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000718 ScalarMaps[i][Load] =
719 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000720 return;
721 }
722
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000723 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000724
Tobias Grosser95493982014-04-18 09:46:35 +0000725 // Make sure we have scalar values available to access the pointer to
726 // the data location.
727 extractScalarValues(Load, VectorMap, ScalarMaps);
728
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000729 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000730 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000731 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000732 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000733 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000734 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000735 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000736 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000737 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000738
739 VectorMap[Load] = NewLoad;
740}
741
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000742void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt,
743 const UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000744 ValueMapT &VectorMap,
745 VectorValueMapT &ScalarMaps) {
746 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000747 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
748 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000749
750 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
751
752 const CastInst *Cast = dyn_cast<CastInst>(Inst);
753 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
754 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
755}
756
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000757void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt,
758 const BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000759 ValueMapT &VectorMap,
760 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000761 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000762 Value *OpZero = Inst->getOperand(0);
763 Value *OpOne = Inst->getOperand(1);
764
765 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000766 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
767 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000768
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000769 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000770 Inst->getName() + "p_vec");
771 VectorMap[Inst] = NewInst;
772}
773
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000774void VectorBlockGenerator::copyStore(
775 ScopStmt &Stmt, const StoreInst *Store, ValueMapT &VectorMap,
776 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000777 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000778
779 const Value *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000780 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000781 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000782
Tobias Grosser50fd7012014-04-17 23:13:49 +0000783 // Make sure we have scalar values available to access the pointer to
784 // the data location.
785 extractScalarValues(Store, VectorMap, ScalarMaps);
786
Sebastian Popa00a0292012-12-18 07:46:06 +0000787 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000788 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000789 Value *NewPointer = generateLocationAccessed(
790 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000791
Tobias Grosserc14582f2013-02-05 18:01:29 +0000792 Value *VectorPtr =
793 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000794 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
795
796 if (!Aligned)
797 Store->setAlignment(8);
798 } else {
799 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000800 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000801 Value *NewPointer = generateLocationAccessed(
802 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000803 Builder.CreateStore(Scalar, NewPointer);
804 }
805 }
806}
807
808bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
809 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000810 for (Value *Operand : Inst->operands())
811 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000812 return true;
813 return false;
814}
815
816bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
817 ValueMapT &VectorMap,
818 VectorValueMapT &ScalarMaps) {
819 bool HasVectorOperand = false;
820 int VectorWidth = getVectorWidth();
821
Tobias Grosser91f5b262014-06-04 08:06:40 +0000822 for (Value *Operand : Inst->operands()) {
823 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000824
825 if (VecOp == VectorMap.end())
826 continue;
827
828 HasVectorOperand = true;
829 Value *NewVector = VecOp->second;
830
831 for (int i = 0; i < VectorWidth; ++i) {
832 ValueMapT &SM = ScalarMaps[i];
833
834 // If there is one scalar extracted, all scalar elements should have
835 // already been extracted by the code here. So no need to check for the
836 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000837 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000838 break;
839
Tobias Grosser91f5b262014-06-04 08:06:40 +0000840 SM[Operand] =
841 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000842 }
843 }
844
845 return HasVectorOperand;
846}
847
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000848void VectorBlockGenerator::copyInstScalarized(
849 ScopStmt &Stmt, const Instruction *Inst, ValueMapT &VectorMap,
850 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000851 bool HasVectorOperand;
852 int VectorWidth = getVectorWidth();
853
854 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
855
856 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000857 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000858 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000859
860 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
861 return;
862
863 // Make the result available as vector value.
864 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
865 Value *Vector = UndefValue::get(VectorType);
866
867 for (int i = 0; i < VectorWidth; i++)
868 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
869 Builder.getInt32(i));
870
871 VectorMap[Inst] = Vector;
872}
873
Tobias Grosserbc132602015-09-05 09:56:54 +0000874int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000875
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000876void VectorBlockGenerator::copyInstruction(
877 ScopStmt &Stmt, const Instruction *Inst, ValueMapT &VectorMap,
878 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000879 // Terminator instructions control the control flow. They are explicitly
880 // expressed in the clast and do not need to be copied.
881 if (Inst->isTerminator())
882 return;
883
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000884 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000885 return;
886
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000887 if (const LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000888 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000889 return;
890 }
891
892 if (hasVectorOperands(Inst, VectorMap)) {
893 if (const StoreInst *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000894 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000895 return;
896 }
897
898 if (const UnaryInstruction *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000899 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000900 return;
901 }
902
903 if (const BinaryOperator *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000904 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000905 return;
906 }
907
908 // Falltrough: We generate scalar instructions, if we don't know how to
909 // generate vector code.
910 }
911
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000912 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000913}
914
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000915void VectorBlockGenerator::copyStmt(
916 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000917 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
918 "the vector block generator");
919
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000920 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000921 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000922 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000923 CopyBB->setName("polly.stmt." + BB->getName());
924 Builder.SetInsertPoint(CopyBB->begin());
925
926 // Create two maps that store the mapping from the original instructions of
927 // the old basic block to their copies in the new basic block. Those maps
928 // are basic block local.
929 //
930 // As vector code generation is supported there is one map for scalar values
931 // and one for vector values.
932 //
933 // In case we just do scalar code generation, the vectorMap is not used and
934 // the scalarMap has just one dimension, which contains the mapping.
935 //
936 // In case vector code generation is done, an instruction may either appear
937 // in the vector map once (as it is calculating >vectorwidth< values at a
938 // time. Or (if the values are calculated using scalar operations), it
939 // appears once in every dimension of the scalarMap.
940 VectorValueMapT ScalarBlockMap(getVectorWidth());
941 ValueMapT VectorBlockMap;
942
Tobias Grosser91f5b262014-06-04 08:06:40 +0000943 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000944 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000945}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000946
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000947BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
948 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000949
950 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
951 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
952
953 if (BBCopyIDom)
954 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
955
956 return BBCopyIDom;
957}
958
Tobias Grosserbc132602015-09-05 09:56:54 +0000959void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000960 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000961 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +0000962 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +0000963
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000964 // Forget all old mappings.
965 BlockMap.clear();
966 RegionMaps.clear();
967 IncompletePHINodeMap.clear();
968
Johannes Doerfert275a1752015-02-24 16:16:32 +0000969 // The region represented by the statement.
970 Region *R = Stmt.getRegion();
971
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000972 // Create a dedicated entry for the region where we can reload all demoted
973 // inputs.
974 BasicBlock *EntryBB = R->getEntry();
975 BasicBlock *EntryBBCopy =
976 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
977 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
978 Builder.SetInsertPoint(EntryBBCopy->begin());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000979
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000980 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
981 if (!R->contains(*PI))
982 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +0000983
984 // Iterate over all blocks in the region in a breadth-first search.
985 std::deque<BasicBlock *> Blocks;
986 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000987 Blocks.push_back(EntryBB);
988 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000989
990 while (!Blocks.empty()) {
991 BasicBlock *BB = Blocks.front();
992 Blocks.pop_front();
993
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000994 // First split the block and update dominance information.
995 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000996 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
997
998 // In order to remap PHI nodes we store also basic block mappings.
999 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001000
1001 // Get the mapping for this block and initialize it with the mapping
1002 // available at its immediate dominator (in the new region).
1003 ValueMapT &RegionMap = RegionMaps[BBCopy];
1004 RegionMap = RegionMaps[BBCopyIDom];
1005
Johannes Doerfert275a1752015-02-24 16:16:32 +00001006 // Copy the block with the BlockGenerator.
Tobias Grosserbc132602015-09-05 09:56:54 +00001007 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001008
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001009 // In order to remap PHI nodes we store also basic block mappings.
1010 BlockMap[BB] = BBCopy;
1011
1012 // Add values to incomplete PHI nodes waiting for this block to be copied.
1013 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001014 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001015 IncompletePHINodeMap[BB].clear();
1016
Johannes Doerfert275a1752015-02-24 16:16:32 +00001017 // And continue with new successors inside the region.
1018 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1019 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1020 Blocks.push_back(*SI);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001021 }
1022
1023 // Now create a new dedicated region exit block and add it to the region map.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001024 BasicBlock *ExitBBCopy =
Johannes Doerfert275a1752015-02-24 16:16:32 +00001025 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001026 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001027 BlockMap[R->getExit()] = ExitBBCopy;
1028
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001029 repairDominance(R->getExit(), ExitBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001030
1031 // As the block generator doesn't handle control flow we need to add the
1032 // region control flow by hand after all blocks have been copied.
1033 for (BasicBlock *BB : SeenBlocks) {
1034
1035 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1036
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001037 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerfert275a1752015-02-24 16:16:32 +00001038 Instruction *BICopy = BBCopy->getTerminator();
1039
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001040 ValueMapT &RegionMap = RegionMaps[BBCopy];
1041 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1042
Tobias Grosser45e79442015-08-01 09:07:57 +00001043 Builder.SetInsertPoint(BICopy);
Tobias Grosserbc132602015-09-05 09:56:54 +00001044 copyInstScalar(Stmt, BI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001045 BICopy->eraseFromParent();
1046 }
1047
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001048 // Add counting PHI nodes to all loops in the region that can be used as
1049 // replacement for SCEVs refering to the old loop.
1050 for (BasicBlock *BB : SeenBlocks) {
1051 Loop *L = LI.getLoopFor(BB);
1052 if (L == nullptr || L->getHeader() != BB)
1053 continue;
1054
1055 BasicBlock *BBCopy = BlockMap[BB];
1056 Value *NullVal = Builder.getInt32(0);
1057 PHINode *LoopPHI =
1058 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1059 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1060 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1061 LoopPHI->insertBefore(BBCopy->begin());
1062 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1063
1064 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1065 if (!R->contains(PredBB))
1066 continue;
1067 if (L->contains(PredBB))
1068 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1069 else
1070 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1071 }
1072
1073 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1074 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1075 LoopPHI->addIncoming(NullVal, PredBBCopy);
1076
1077 LTS[L] = SE.getUnknown(LoopPHI);
1078 }
1079
Johannes Doerfert275a1752015-02-24 16:16:32 +00001080 // Reset the old insert point for the build.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001081 Builder.SetInsertPoint(ExitBBCopy->begin());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001082}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001083
1084void RegionGenerator::generateScalarLoads(ScopStmt &Stmt,
1085 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +00001086 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001087
1088 // Inside a non-affine region PHI nodes are copied not demoted. Once the
1089 // phi is copied it will reload all inputs from outside the region, hence
1090 // we do not need to generate code for the read access of the operands of a
1091 // PHI.
1092 if (isa<PHINode>(Inst))
1093 return;
1094
Tobias Grosserbc132602015-09-05 09:56:54 +00001095 return BlockGenerator::generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001096}
1097
1098void RegionGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +00001099 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001100 const Region &R = Stmt.getParent()->getRegion();
1101
Tobias Grosser75296902015-08-21 19:23:21 +00001102 assert(Stmt.getRegion() &&
1103 "Block statements need to use the generateScalarStores() "
1104 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001105
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001106 for (MemoryAccess *MA : Stmt) {
1107
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001108 if (!MA->isScalar() || MA->isRead())
1109 continue;
1110
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001111 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001112
Tobias Grosser62139132015-08-02 16:17:41 +00001113 // Only generate accesses that belong to this basic block.
1114 if (ScalarInst->getParent() != BB)
1115 continue;
1116
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001117 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001118
Tobias Grosserbc132602015-09-05 09:56:54 +00001119 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001120
Tobias Grosserbc132602015-09-05 09:56:54 +00001121 Val = getNewScalarValue(Val, R, BBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001122 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001123 }
1124}
1125
1126void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1127 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001128 LoopToScevMapT &LTS) {
1129 Region *StmtR = Stmt.getRegion();
1130
1131 // If the incoming block was not yet copied mark this PHI as incomplete.
1132 // Once the block will be copied the incoming value will be added.
1133 BasicBlock *BBCopy = BlockMap[IncomingBB];
1134 if (!BBCopy) {
1135 assert(StmtR->contains(IncomingBB) &&
1136 "Bad incoming block for PHI in non-affine region");
1137 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1138 return;
1139 }
1140
1141 Value *OpCopy = nullptr;
1142 if (StmtR->contains(IncomingBB)) {
1143 assert(RegionMaps.count(BBCopy) &&
1144 "Incoming PHI block did not have a BBMap");
1145 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1146
1147 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Tobias Grosserbc132602015-09-05 09:56:54 +00001148 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001149 } else {
1150
1151 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1152 return;
1153
Tobias Grosserbc132602015-09-05 09:56:54 +00001154 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001155 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1156 BlockMap[IncomingBB]->getTerminator());
1157 }
1158
1159 assert(OpCopy && "Incoming PHI value was not copied properly");
1160 assert(BBCopy && "Incoming PHI block was not copied properly");
1161 PHICopy->addIncoming(OpCopy, BBCopy);
1162}
1163
1164Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, const PHINode *PHI,
1165 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001166 LoopToScevMapT &LTS) {
1167 unsigned NumIncoming = PHI->getNumIncomingValues();
1168 PHINode *PHICopy =
1169 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1170 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1171 BBMap[PHI] = PHICopy;
1172
1173 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001174 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001175 return PHICopy;
1176}