blob: 6480a3aac4c378a7a5b6e7aacb53c12b819e0b68 [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
Hongbin Zheng8a846612012-04-25 13:18:28 +000016#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser83628182013-05-07 08:11:54 +000017#include "polly/CodeGen/CodeGeneration.h"
Johannes Doerferta63b2572014-08-03 01:51:59 +000018#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser86bc93a2015-09-06 08:47:57 +000019#include "polly/CodeGen/RuntimeDebugBuilder.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000020#include "polly/Options.h"
Tobias Grosser5624d3c2015-12-21 12:38:56 +000021#include "polly/ScopInfo.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"
Tobias Grosser1b9d25a2015-09-27 11:17:22 +000031#include "llvm/Transforms/Utils/Local.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000032#include "isl/aff.h"
33#include "isl/ast.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000034#include "isl/ast_build.h"
Tobias Grosserba0d0922015-05-09 09:13:42 +000035#include "isl/set.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000036#include <deque>
37
Hongbin Zheng3b11a162012-04-25 13:16:49 +000038using namespace llvm;
39using namespace polly;
40
Tobias Grosser878aba42014-10-22 23:22:41 +000041static cl::opt<bool> Aligned("enable-polly-aligned",
42 cl::desc("Assumed aligned memory accesses."),
43 cl::Hidden, cl::init(false), cl::ZeroOrMore,
44 cl::cat(PollyCategory));
Hongbin Zheng3b11a162012-04-25 13:16:49 +000045
Tobias Grosser86bc93a2015-09-06 08:47:57 +000046static cl::opt<bool> DebugPrinting(
47 "polly-codegen-add-debug-printing",
48 cl::desc("Add printf calls that show the values loaded/stored."),
49 cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory));
50
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000051BlockGenerator::BlockGenerator(PollyIRBuilder &B, LoopInfo &LI,
52 ScalarEvolution &SE, DominatorTree &DT,
Johannes Doerfertecff11d2015-05-22 23:43:58 +000053 ScalarAllocaMapTy &ScalarMap,
54 ScalarAllocaMapTy &PHIOpMap,
55 EscapeUsersAllocaMapTy &EscapeMap,
Tobias Grosserf4bb7a62015-10-04 10:18:32 +000056 ValueMapT &GlobalMap,
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +000057 IslExprBuilder *ExprBuilder)
Johannes Doerfertecff11d2015-05-22 23:43:58 +000058 : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
59 EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap),
Tobias Grosserbc132602015-09-05 09:56:54 +000060 EscapeMap(EscapeMap), GlobalMap(GlobalMap) {}
Tobias Grossere71c6ab2012-04-27 16:36:14 +000061
Tobias Grosser2f1acac2015-10-04 10:18:45 +000062Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
Tobias Grosser33cb9f92015-09-30 11:56:19 +000063 ValueMapT &BBMap,
64 LoopToScevMapT &LTS,
65 Loop *L) const {
Johannes Doerfert42df8d12015-12-22 19:08:01 +000066 if (!SE.isSCEVable(Old->getType()))
67 return nullptr;
Johannes Doerferte69e1142015-08-18 11:56:00 +000068
Johannes Doerfert42df8d12015-12-22 19:08:01 +000069 const SCEV *Scev = SE.getSCEVAtScope(Old, L);
70 if (!Scev)
71 return nullptr;
Johannes Doerferte69e1142015-08-18 11:56:00 +000072
Johannes Doerfert42df8d12015-12-22 19:08:01 +000073 if (isa<SCEVCouldNotCompute>(Scev))
74 return nullptr;
Tobias Grossere71c6ab2012-04-27 16:36:14 +000075
Sanjoy Das03bcb912016-05-29 07:33:16 +000076 const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE);
Johannes Doerfert42df8d12015-12-22 19:08:01 +000077 ValueMapT VTV;
78 VTV.insert(BBMap.begin(), BBMap.end());
79 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Tobias Grossere71c6ab2012-04-27 16:36:14 +000080
Johannes Doerfert42df8d12015-12-22 19:08:01 +000081 Scop &S = *Stmt.getParent();
Johannes Doerfert3f52e352016-05-23 12:38:05 +000082 const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
Johannes Doerfert42df8d12015-12-22 19:08:01 +000083 auto IP = Builder.GetInsertPoint();
84
85 assert(IP != Builder.GetInsertBlock()->end() &&
86 "Only instructions can be insert points for SCEVExpander");
87 Value *Expanded =
88 expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV);
89
90 BBMap[Old] = Expanded;
91 return Expanded;
Tobias Grosser33cb9f92015-09-30 11:56:19 +000092}
93
Tobias Grosser2f1acac2015-10-04 10:18:45 +000094Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
95 LoopToScevMapT &LTS, Loop *L) const {
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000096 // Constants that do not reference any named value can always remain
Michael Kruse5bbc0e12015-12-14 23:41:32 +000097 // unchanged. Handle them early to avoid expensive map lookups. We do not take
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000098 // the fast-path for external constants which are referenced through globals
99 // as these may need to be rewritten when distributing code accross different
100 // LLVM modules.
101 if (isa<Constant>(Old) && !isa<GlobalValue>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000102 return Old;
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000103
Johannes Doerfert28f8ac12015-12-22 19:08:24 +0000104 // Inline asm is like a constant to us.
105 if (isa<InlineAsm>(Old))
106 return Old;
107
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000108 if (Value *New = GlobalMap.lookup(Old)) {
109 if (Value *NewRemapped = GlobalMap.lookup(New))
110 New = NewRemapped;
111 if (Old->getType()->getScalarSizeInBits() <
112 New->getType()->getScalarSizeInBits())
113 New = Builder.CreateTruncOrBitCast(New, Old->getType());
114
115 return New;
116 }
117
118 if (Value *New = BBMap.lookup(Old))
119 return New;
120
121 if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
122 return New;
123
Tobias Grosser16371ac2014-11-05 20:48:56 +0000124 // A scop-constant value defined by a global or a function parameter.
125 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000126 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000127
128 // A scop-constant value defined by an instruction executed outside the scop.
129 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfert952b5302016-05-23 12:40:48 +0000130 if (!Stmt.getParent()->contains(Inst->getParent()))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000131 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000132
133 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000134 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000135 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000136}
137
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000138void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000139 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000140 // We do not generate debug intrinsics as we did not investigate how to
141 // copy them correctly. At the current state, they just crash the code
142 // generation as the meta-data operands are not correctly copied.
143 if (isa<DbgInfoIntrinsic>(Inst))
144 return;
145
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000146 Instruction *NewInst = Inst->clone();
147
148 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000149 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000150 Value *NewOperand =
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000151 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000152
153 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000154 assert(!isa<StoreInst>(NewInst) &&
155 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000156 delete NewInst;
157 return;
158 }
159
160 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
161 }
162
163 Builder.Insert(NewInst);
164 BBMap[Inst] = NewInst;
165
166 if (!NewInst->getType()->isVoidTy())
167 NewInst->setName("p_" + Inst->getName());
168}
169
Michael Kruse70131d32016-01-27 17:09:17 +0000170Value *
171BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
172 ValueMapT &BBMap, LoopToScevMapT &LTS,
173 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser09214772015-12-15 23:49:53 +0000174 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
Michael Kruse2fa35192016-09-01 19:53:31 +0000175 return generateLocationAccessed(
176 Stmt, getLoopForStmt(Stmt),
177 Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS,
178 NewAccesses, MA.getId(), MA.getAccessValue()->getType());
179}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000180
Michael Kruse2fa35192016-09-01 19:53:31 +0000181Value *BlockGenerator::generateLocationAccessed(
182 ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
183 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
184 Type *ExpectedType) {
185 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000186
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000187 if (AccessExpr) {
188 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000189 auto Address = ExprBuilder->create(AccessExpr);
190
191 // Cast the address of this memory access to a pointer type that has the
192 // same element type as the original access, but uses the address space of
193 // the newly generated pointer.
Michael Kruse2fa35192016-09-01 19:53:31 +0000194 auto OldPtrTy = ExpectedType->getPointerTo();
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000195 auto NewPtrTy = Address->getType();
196 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
197 NewPtrTy->getPointerAddressSpace());
198
Tobias Grosserd840fc72016-02-04 13:18:42 +0000199 if (OldPtrTy != NewPtrTy)
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000200 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000201 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000202 }
Michael Kruse2fa35192016-09-01 19:53:31 +0000203 assert(
204 Pointer &&
205 "If expression was not generated, must use the original pointer value");
206 return getNewValue(Stmt, Pointer, BBMap, LTS, L);
207}
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000208
Michael Kruse2fa35192016-09-01 19:53:31 +0000209Value *
210BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L,
211 LoopToScevMapT &LTS, ValueMapT &BBMap,
212 __isl_keep isl_id_to_ast_expr *NewAccesses) {
213 if (Access.isLatestArrayKind())
214 return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
215 LTS, NewAccesses, Access.getId(),
216 Access.getAccessValue()->getType());
217
218 if (Access.isLatestValueKind() || Access.isLatestExitPHIKind())
219 return getOrCreateScalarAlloca(Access.getBaseAddr());
220
221 if (Access.isLatestPHIKind())
222 return getOrCreatePHIAlloca(Access.getBaseAddr());
223
224 llvm_unreachable("Unknown access type");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000225}
226
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000227Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
Michael Kruse375cb5f2016-02-24 22:08:24 +0000228 auto *StmtBB = Stmt.getEntryBlock();
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000229 return LI.getLoopFor(StmtBB);
Tobias Grosser369430f2013-03-22 23:42:53 +0000230}
231
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000232Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000233 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000234 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000235 if (Value *PreloadLoad = GlobalMap.lookup(Load))
236 return PreloadLoad;
237
Tobias Grosserbc132602015-09-05 09:56:54 +0000238 Value *NewPointer =
Michael Kruse70131d32016-01-27 17:09:17 +0000239 generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000240 Value *ScalarLoad = Builder.CreateAlignedLoad(
241 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000242
243 if (DebugPrinting)
244 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
245 ": ", ScalarLoad, "\n");
246
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000247 return ScalarLoad;
248}
249
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000250void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000251 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000252 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000253 Value *NewPointer =
Michael Kruse70131d32016-01-27 17:09:17 +0000254 generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
Tobias Grosserbc132602015-09-05 09:56:54 +0000255 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000256 getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000257
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000258 if (DebugPrinting)
259 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
260 ": ", ValueOperand, "\n");
261
Tobias Grosserc186ac72015-08-11 08:13:15 +0000262 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000263}
264
Johannes Doerfert5dced262015-12-22 19:08:49 +0000265bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000266 Loop *L = getLoopForStmt(Stmt);
Johannes Doerfert5dced262015-12-22 19:08:49 +0000267 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
Johannes Doerfert0f0d209b2016-05-23 12:47:09 +0000268 canSynthesize(Inst, *Stmt.getParent(), &LI, &SE, L);
Johannes Doerfert5dced262015-12-22 19:08:49 +0000269}
270
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000271void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000272 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000273 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000274 // Terminator instructions control the control flow. They are explicitly
275 // expressed in the clast and do not need to be copied.
276 if (Inst->isTerminator())
277 return;
278
Johannes Doerfert5dced262015-12-22 19:08:49 +0000279 // Synthesizable statements will be generated on-demand.
280 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000281 return;
282
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000283 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000284 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000285 // Compute NewLoad before its insertion in BBMap to make the insertion
286 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000287 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000288 return;
289 }
290
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000291 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000292 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000293 return;
294 }
295
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000296 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000297 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000298 return;
299 }
300
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000301 // Skip some special intrinsics for which we do not adjust the semantics to
302 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000303 if (isIgnoredIntrinsic(Inst))
304 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000305
Tobias Grosserbc132602015-09-05 09:56:54 +0000306 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000307}
308
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000309void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) {
Tobias Grosserc59b3ce2016-08-09 08:59:05 +0000310 auto NewBB = Builder.GetInsertBlock();
311 for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) {
312 Instruction *NewInst = &*I;
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000313
314 if (!isInstructionTriviallyDead(NewInst))
315 continue;
316
Tobias Grosserc59b3ce2016-08-09 08:59:05 +0000317 for (auto Pair : BBMap)
318 if (Pair.second == NewInst) {
319 BBMap.erase(Pair.first);
320 }
321
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000322 NewInst->eraseFromParent();
Tobias Grosserc59b3ce2016-08-09 08:59:05 +0000323 I = NewBB->rbegin();
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000324 }
325}
326
Tobias Grosserbc132602015-09-05 09:56:54 +0000327void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000328 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000329 assert(Stmt.isBlockStmt() &&
330 "Only block statements can be copied by the block generator");
331
332 ValueMapT BBMap;
333
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000334 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000335 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Tobias Grosser9d12d8a2016-07-21 11:48:36 +0000336 removeDeadInstructions(BB, BBMap);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000337}
338
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000339BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000340 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
341 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000342 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000343 return CopyBB;
344}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000345
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000346BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000347 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000348 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000349 BasicBlock *CopyBB = splitBB(BB);
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000350 Builder.SetInsertPoint(&CopyBB->front());
Michael Kruse2fa35192016-09-01 19:53:31 +0000351 generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000352
Tobias Grosserbc132602015-09-05 09:56:54 +0000353 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000354
355 // After a basic block was copied store all scalars that escape this block in
356 // their alloca.
Michael Kruse2fa35192016-09-01 19:53:31 +0000357 generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000358 return CopyBB;
359}
360
361void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000362 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000363 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000364 EntryBB = &CopyBB->getParent()->getEntryBlock();
365
Tobias Grosser91f5b262014-06-04 08:06:40 +0000366 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000367 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000368}
369
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000370Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
371 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000372 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000373 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000374 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000375 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000376 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000377 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000378 NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000379 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000380 }
381
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000382 auto Addr = Map[ScalarBase];
383
Tobias Grosser5c7f16b2016-01-24 14:16:59 +0000384 if (auto NewAddr = GlobalMap.lookup(Addr))
385 return NewAddr;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000386
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000387 return Addr;
388}
389
Johannes Doerfert800e17a2016-02-02 14:16:01 +0000390Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
Tobias Grosser3216f852016-08-04 06:55:53 +0000391 assert(!Access.isArrayKind() && "Trying to get alloca for array kind");
392
Tobias Grossera535dff2015-12-13 19:59:01 +0000393 if (Access.isPHIKind())
Tobias Grosserb8d27aa2015-10-18 00:51:13 +0000394 return getOrCreatePHIAlloca(Access.getBaseAddr());
395 else
396 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grossera4f09882015-10-17 22:16:00 +0000397}
398
399Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
Tobias Grosser3216f852016-08-04 06:55:53 +0000400 assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
401
Tobias Grossera535dff2015-12-13 19:59:01 +0000402 if (Array->isPHIKind())
Tobias Grossera4f09882015-10-17 22:16:00 +0000403 return getOrCreatePHIAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000404 else
Tobias Grossera4f09882015-10-17 22:16:00 +0000405 return getOrCreateScalarAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000406}
407
Tobias Grosserbc132602015-09-05 09:56:54 +0000408Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
409 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000410}
411
Tobias Grosserbc132602015-09-05 09:56:54 +0000412Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
413 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000414}
415
Johannes Doerfert38a012c2016-05-23 09:14:07 +0000416void BlockGenerator::handleOutsideUsers(const Scop &S, Instruction *Inst) {
Tobias Grosser29854002015-08-30 15:03:59 +0000417 // If there are escape users we get the alloca for this instruction and put it
418 // in the EscapeMap for later finalization. Lastly, if the instruction was
419 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000420 if (EscapeMap.count(Inst))
421 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000422
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000423 EscapeUserVectorTy EscapeUsers;
424 for (User *U : Inst->users()) {
425
426 // Non-instruction user will never escape.
427 Instruction *UI = dyn_cast<Instruction>(U);
428 if (!UI)
429 continue;
430
Johannes Doerfert952b5302016-05-23 12:40:48 +0000431 if (S.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000432 continue;
433
434 EscapeUsers.push_back(UI);
435 }
436
437 // Exit if no escape uses were found.
438 if (EscapeUsers.empty())
439 return;
440
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000441 // Get or create an escape alloca for this instruction.
Johannes Doerfert38a012c2016-05-23 09:14:07 +0000442 auto *ScalarAddr = getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000443
444 // Remember that this instruction has escape uses and the escape alloca.
445 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000446}
447
Michael Kruse2fa35192016-09-01 19:53:31 +0000448void BlockGenerator::generateScalarLoads(
449 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
450 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Michael Kruse225f0d12015-10-17 21:36:00 +0000451 for (MemoryAccess *MA : Stmt) {
Michael Kruse2fa35192016-09-01 19:53:31 +0000452 if (MA->isOriginalArrayKind() || MA->isWrite())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000453 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000454
Michael Kruse2fa35192016-09-01 19:53:31 +0000455 auto *Address =
456 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
Michael Kruseeac97262016-02-24 22:08:14 +0000457 assert((!isa<Instruction>(Address) ||
458 DT.dominates(cast<Instruction>(Address)->getParent(),
459 Builder.GetInsertBlock())) &&
460 "Domination violation");
Michael Krusee2bccbb2015-09-18 19:59:43 +0000461 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000462 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000463 }
464}
465
Michael Kruse2fa35192016-09-01 19:53:31 +0000466void BlockGenerator::generateScalarStores(
467 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
468 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000469 Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000470
Michael Kruse225f0d12015-10-17 21:36:00 +0000471 assert(Stmt.isBlockStmt() && "Region statements need to use the "
472 "generateScalarStores() function in the "
473 "RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000474
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000475 for (MemoryAccess *MA : Stmt) {
Michael Kruse2fa35192016-09-01 19:53:31 +0000476 if (MA->isOriginalArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000477 continue;
478
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000479 Value *Val = MA->getAccessValue();
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000480 if (MA->isAnyPHIKind()) {
481 assert(MA->getIncoming().size() >= 1 &&
482 "Block statements have exactly one exiting block, or multiple but "
483 "with same incoming block and value");
484 assert(std::all_of(MA->getIncoming().begin(), MA->getIncoming().end(),
485 [&](std::pair<BasicBlock *, Value *> p) -> bool {
486 return p.first == Stmt.getBasicBlock();
487 }) &&
488 "Incoming block must be statement's block");
489 Val = MA->getIncoming()[0].second;
490 }
Michael Kruse2fa35192016-09-01 19:53:31 +0000491 auto Address =
492 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000493
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000494 Val = getNewValue(Stmt, Val, BBMap, LTS, L);
Michael Kruseeac97262016-02-24 22:08:14 +0000495 assert((!isa<Instruction>(Val) ||
496 DT.dominates(cast<Instruction>(Val)->getParent(),
497 Builder.GetInsertBlock())) &&
498 "Domination violation");
499 assert((!isa<Instruction>(Address) ||
500 DT.dominates(cast<Instruction>(Address)->getParent(),
501 Builder.GetInsertBlock())) &&
502 "Domination violation");
Tobias Grosser92245222015-07-28 14:53:44 +0000503 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000504 }
505}
506
Tobias Grosserc0091a72015-08-30 19:19:34 +0000507void BlockGenerator::createScalarInitialization(Scop &S) {
Johannes Doerfertef744432016-05-23 12:42:38 +0000508 BasicBlock *ExitBB = S.getExit();
Johannes Doerfert188542f2015-11-09 00:21:21 +0000509
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000510 // The split block __just before__ the region and optimized region.
Johannes Doerfertef744432016-05-23 12:42:38 +0000511 BasicBlock *SplitBB = S.getEnteringBlock();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000512 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
513 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
514
515 // Get the start block of the __optimized__ region.
516 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
Johannes Doerfertef744432016-05-23 12:42:38 +0000517 if (StartBB == S.getEntry())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000518 StartBB = SplitBBTerm->getSuccessor(1);
519
Tobias Grosser776700d2016-08-09 15:34:59 +0000520 Builder.SetInsertPoint(&*StartBB->begin());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000521
Roman Gareevd7754a12016-07-30 09:25:51 +0000522 for (auto &Array : S.arrays()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000523 if (Array->getNumberOfDimensions() != 0)
524 continue;
Tobias Grossera535dff2015-12-13 19:59:01 +0000525 if (Array->isPHIKind()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000526 // For PHI nodes, the only values we need to store are the ones that
527 // reach the PHI node from outside the region. In general there should
528 // only be one such incoming edge and this edge should enter through
529 // 'SplitBB'.
530 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000531
Tobias Grosserc0091a72015-08-30 19:19:34 +0000532 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
Johannes Doerfert952b5302016-05-23 12:40:48 +0000533 if (!S.contains(*BI) && *BI != SplitBB)
Tobias Grosserc0091a72015-08-30 19:19:34 +0000534 llvm_unreachable("Incoming edges from outside the scop should always "
535 "come from SplitBB");
536
537 int Idx = PHI->getBasicBlockIndex(SplitBB);
538 if (Idx < 0)
539 continue;
540
541 Value *ScalarValue = PHI->getIncomingValue(Idx);
542
Tobias Grosserbc132602015-09-05 09:56:54 +0000543 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000544 continue;
545 }
546
547 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
548
Johannes Doerfert952b5302016-05-23 12:40:48 +0000549 if (Inst && S.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000550 continue;
551
Johannes Doerfert188542f2015-11-09 00:21:21 +0000552 // PHI nodes that are not marked as such in their SAI object are either exit
553 // PHI nodes we model as common scalars but without initialization, or
554 // incoming phi nodes that need to be initialized. Check if the first is the
555 // case for Inst and do not create and initialize memory if so.
556 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
557 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
558 continue;
Johannes Doerfert717b8662015-09-08 21:44:27 +0000559
Tobias Grosserc0091a72015-08-30 19:19:34 +0000560 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000561 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000562 }
563}
564
Johannes Doerfertef744432016-05-23 12:42:38 +0000565void BlockGenerator::createScalarFinalization(Scop &S) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000566 // The exit block of the __unoptimized__ region.
Johannes Doerfertef744432016-05-23 12:42:38 +0000567 BasicBlock *ExitBB = S.getExitingBlock();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000568 // The merge block __just after__ the region and the optimized region.
Johannes Doerfertef744432016-05-23 12:42:38 +0000569 BasicBlock *MergeBB = S.getExit();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000570
571 // The exit block of the __optimized__ region.
572 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
573 if (OptExitBB == ExitBB)
574 OptExitBB = *(++pred_begin(MergeBB));
575
576 Builder.SetInsertPoint(OptExitBB->getTerminator());
577 for (const auto &EscapeMapping : EscapeMap) {
578 // Extract the escaping instruction and the escaping users as well as the
579 // alloca the instruction was demoted to.
Michael Krusefbde4352016-08-05 16:45:51 +0000580 Instruction *EscapeInst = EscapeMapping.first;
581 const auto &EscapeMappingValue = EscapeMapping.second;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000582 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000583 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000584
585 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000586 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000587 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000588 EscapeInstReload =
589 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000590
591 // Create the merge PHI that merges the optimized and unoptimized version.
592 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
593 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000594 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000595
596 // Add the respective values to the merge PHI.
597 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
598 MergePHI->addIncoming(EscapeInst, ExitBB);
599
600 // The information of scalar evolution about the escaping instruction needs
601 // to be revoked so the new merged instruction will be used.
602 if (SE.isSCEVable(EscapeInst->getType()))
603 SE.forgetValue(EscapeInst);
604
605 // Replace all uses of the demoted instruction with the merge PHI.
606 for (Instruction *EUser : EscapeUsers)
607 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
608 }
609}
610
Tobias Grosserffa24462015-10-17 08:54:13 +0000611void BlockGenerator::findOutsideUsers(Scop &S) {
Roman Gareevd7754a12016-07-30 09:25:51 +0000612 for (auto &Array : S.arrays()) {
Tobias Grosserffa24462015-10-17 08:54:13 +0000613
614 if (Array->getNumberOfDimensions() != 0)
615 continue;
616
Tobias Grossera535dff2015-12-13 19:59:01 +0000617 if (Array->isPHIKind())
Tobias Grosserffa24462015-10-17 08:54:13 +0000618 continue;
619
620 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
621
622 if (!Inst)
623 continue;
624
625 // Scop invariant hoisting moves some of the base pointers out of the scop.
626 // We can ignore these, as the invariant load hoisting already registers the
627 // relevant outside users.
Johannes Doerfert952b5302016-05-23 12:40:48 +0000628 if (!S.contains(Inst))
Tobias Grosserffa24462015-10-17 08:54:13 +0000629 continue;
630
Johannes Doerfert38a012c2016-05-23 09:14:07 +0000631 handleOutsideUsers(S, Inst);
Tobias Grosserffa24462015-10-17 08:54:13 +0000632 }
633}
634
Tobias Grosser27d742d2015-10-24 17:41:29 +0000635void BlockGenerator::createExitPHINodeMerges(Scop &S) {
636 if (S.hasSingleExitEdge())
637 return;
638
Johannes Doerfertef744432016-05-23 12:42:38 +0000639 auto *ExitBB = S.getExitingBlock();
640 auto *MergeBB = S.getExit();
Tobias Grosser27d742d2015-10-24 17:41:29 +0000641 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
642 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
643 if (OptExitBB == ExitBB)
644 OptExitBB = *(++pred_begin(MergeBB));
645
646 Builder.SetInsertPoint(OptExitBB->getTerminator());
647
Roman Gareevd7754a12016-07-30 09:25:51 +0000648 for (auto &SAI : S.arrays()) {
Tobias Grosser27d742d2015-10-24 17:41:29 +0000649 auto *Val = SAI->getBasePtr();
650
Michael Krusefaedfcb2016-03-03 17:20:43 +0000651 // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
652 // the original PHI's value or the reloaded incoming values from the
653 // generated code. An llvm::Value is merged between the original code's
654 // value or the generated one.
655 if (!SAI->isValueKind() && !SAI->isExitPHIKind())
656 continue;
657
Tobias Grosser27d742d2015-10-24 17:41:29 +0000658 PHINode *PHI = dyn_cast<PHINode>(Val);
659 if (!PHI)
660 continue;
661
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000662 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000663 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000664
665 std::string Name = PHI->getName();
666 Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
667 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
668 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
669 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
Michael Krusefaedfcb2016-03-03 17:20:43 +0000670 assert((!isa<Instruction>(OriginalValue) ||
671 cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
672 "Original value must no be one we just generated.");
Tobias Grosser27d742d2015-10-24 17:41:29 +0000673 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000674 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000675 MergePHI->addIncoming(Reload, OptExitBB);
676 MergePHI->addIncoming(OriginalValue, ExitBB);
677 int Idx = PHI->getBasicBlockIndex(MergeBB);
678 PHI->setIncomingValue(Idx, MergePHI);
679 }
680}
681
Tobias Grosser1c184402016-08-18 10:45:57 +0000682void BlockGenerator::invalidateScalarEvolution(Scop &S) {
683 for (auto &Stmt : S)
684 if (Stmt.isBlockStmt())
685 for (auto &Inst : *Stmt.getBasicBlock())
686 SE.forgetValue(&Inst);
687 else if (Stmt.isRegionStmt())
688 for (auto *BB : Stmt.getRegion()->blocks())
689 for (auto &Inst : *BB)
690 SE.forgetValue(&Inst);
691 else
692 llvm_unreachable("Unexpected statement type found");
693}
694
Tobias Grosserffa24462015-10-17 08:54:13 +0000695void BlockGenerator::finalizeSCoP(Scop &S) {
696 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000697 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000698 createExitPHINodeMerges(S);
Johannes Doerfertef744432016-05-23 12:42:38 +0000699 createScalarFinalization(S);
Tobias Grosser1c184402016-08-18 10:45:57 +0000700 invalidateScalarEvolution(S);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000701}
702
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000703VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000704 std::vector<LoopToScevMapT> &VLTS,
705 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000706 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000707 assert(Schedule && "No statement domain provided");
708}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000709
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000710Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000711 ValueMapT &VectorMap,
712 VectorValueMapT &ScalarMaps,
713 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000714 if (Value *NewValue = VectorMap.lookup(Old))
715 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000716
717 int Width = getVectorWidth();
718
719 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
720
721 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000722 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000723 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000724 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000725
726 VectorMap[Old] = Vector;
727
728 return Vector;
729}
730
731Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
732 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
733 assert(PointerTy && "PointerType expected");
734
735 Type *ScalarType = PointerTy->getElementType();
736 VectorType *VectorType = VectorType::get(ScalarType, Width);
737
738 return PointerType::getUnqual(VectorType);
739}
740
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000741Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000742 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000743 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000744 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000745 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000746 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
747 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
748
Michael Kruse8f25b0c2016-02-25 15:52:43 +0000749 Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
750 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000751 Value *VectorPtr =
752 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
753 LoadInst *VecLoad =
754 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000755 if (!Aligned)
756 VecLoad->setAlignment(8);
757
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000758 if (NegativeStride) {
759 SmallVector<Constant *, 16> Indices;
760 for (int i = VectorWidth - 1; i >= 0; i--)
761 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
762 Constant *SV = llvm::ConstantVector::get(Indices);
763 Value *RevVecLoad = Builder.CreateShuffleVector(
764 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
765 return RevVecLoad;
766 }
767
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000768 return VecLoad;
769}
770
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000771Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000772 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000773 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000774 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000775 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Michael Kruse70131d32016-01-27 17:09:17 +0000776 Value *NewPointer =
777 generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000778 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
779 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000780 LoadInst *ScalarLoad =
781 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000782
783 if (!Aligned)
784 ScalarLoad->setAlignment(8);
785
Tobias Grosserc14582f2013-02-05 18:01:29 +0000786 Constant *SplatVector = Constant::getNullValue(
787 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000788
Tobias Grosserc14582f2013-02-05 18:01:29 +0000789 Value *VectorLoad = Builder.CreateShuffleVector(
790 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000791 return VectorLoad;
792}
793
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000794Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000795 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000796 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000797 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000798 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000799 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000800 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000801
802 Value *Vector = UndefValue::get(VectorType);
803
804 for (int i = 0; i < VectorWidth; i++) {
Michael Kruse70131d32016-01-27 17:09:17 +0000805 Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
806 VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000807 Value *ScalarLoad =
808 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
809 Vector = Builder.CreateInsertElement(
810 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000811 }
812
813 return Vector;
814}
815
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000816void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000817 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000818 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000819 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
820 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
821 Load->getName() + "_p");
822 return;
823 }
824
Tobias Grosser28736452015-03-23 07:00:36 +0000825 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000826 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000827 ScalarMaps[i][Load] =
828 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000829 return;
830 }
831
Tobias Grosser184a4922015-12-15 23:50:01 +0000832 const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000833
Tobias Grosser95493982014-04-18 09:46:35 +0000834 // Make sure we have scalar values available to access the pointer to
835 // the data location.
836 extractScalarValues(Load, VectorMap, ScalarMaps);
837
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000838 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000839 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000840 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000841 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000842 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000843 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000844 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000845 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000846 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000847
848 VectorMap[Load] = NewLoad;
849}
850
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000851void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000852 ValueMapT &VectorMap,
853 VectorValueMapT &ScalarMaps) {
854 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000855 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000856 ScalarMaps, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000857
858 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
859
860 const CastInst *Cast = dyn_cast<CastInst>(Inst);
861 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
862 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
863}
864
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000865void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000866 ValueMapT &VectorMap,
867 VectorValueMapT &ScalarMaps) {
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000868 Loop *L = getLoopForStmt(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000869 Value *OpZero = Inst->getOperand(0);
870 Value *OpOne = Inst->getOperand(1);
871
872 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000873 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
874 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000875
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000876 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000877 Inst->getName() + "p_vec");
878 VectorMap[Inst] = NewInst;
879}
880
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000881void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000882 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000883 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser184a4922015-12-15 23:50:01 +0000884 const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000885
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000886 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000887 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000888 ScalarMaps, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000889
Tobias Grosser50fd7012014-04-17 23:13:49 +0000890 // Make sure we have scalar values available to access the pointer to
891 // the data location.
892 extractScalarValues(Store, VectorMap, ScalarMaps);
893
Sebastian Popa00a0292012-12-18 07:46:06 +0000894 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000895 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Michael Kruse70131d32016-01-27 17:09:17 +0000896 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
897 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000898
Tobias Grosserc14582f2013-02-05 18:01:29 +0000899 Value *VectorPtr =
900 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000901 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
902
903 if (!Aligned)
904 Store->setAlignment(8);
905 } else {
906 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000907 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Michael Kruse70131d32016-01-27 17:09:17 +0000908 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
909 VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000910 Builder.CreateStore(Scalar, NewPointer);
911 }
912 }
913}
914
915bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
916 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000917 for (Value *Operand : Inst->operands())
918 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000919 return true;
920 return false;
921}
922
923bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
924 ValueMapT &VectorMap,
925 VectorValueMapT &ScalarMaps) {
926 bool HasVectorOperand = false;
927 int VectorWidth = getVectorWidth();
928
Tobias Grosser91f5b262014-06-04 08:06:40 +0000929 for (Value *Operand : Inst->operands()) {
930 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000931
932 if (VecOp == VectorMap.end())
933 continue;
934
935 HasVectorOperand = true;
936 Value *NewVector = VecOp->second;
937
938 for (int i = 0; i < VectorWidth; ++i) {
939 ValueMapT &SM = ScalarMaps[i];
940
941 // If there is one scalar extracted, all scalar elements should have
942 // already been extracted by the code here. So no need to check for the
Tobias Grosser2219d152016-08-03 05:28:09 +0000943 // existence of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000944 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000945 break;
946
Tobias Grosser91f5b262014-06-04 08:06:40 +0000947 SM[Operand] =
948 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000949 }
950 }
951
952 return HasVectorOperand;
953}
954
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000955void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000956 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000957 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000958 bool HasVectorOperand;
959 int VectorWidth = getVectorWidth();
960
961 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
962
963 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000964 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000965 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000966
967 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
968 return;
969
970 // Make the result available as vector value.
971 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
972 Value *Vector = UndefValue::get(VectorType);
973
974 for (int i = 0; i < VectorWidth; i++)
975 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
976 Builder.getInt32(i));
977
978 VectorMap[Inst] = Vector;
979}
980
Tobias Grosserbc132602015-09-05 09:56:54 +0000981int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000982
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000983void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000984 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000985 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000986 // Terminator instructions control the control flow. They are explicitly
987 // expressed in the clast and do not need to be copied.
988 if (Inst->isTerminator())
989 return;
990
Johannes Doerfert5dced262015-12-22 19:08:49 +0000991 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000992 return;
993
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000994 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000995 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000996 return;
997 }
998
999 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +00001000 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001001 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001002 return;
1003 }
1004
Tobias Grosser9646e3f2015-10-04 10:18:39 +00001005 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +00001006 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001007 return;
1008 }
1009
Tobias Grosser9646e3f2015-10-04 10:18:39 +00001010 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +00001011 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001012 return;
1013 }
1014
1015 // Falltrough: We generate scalar instructions, if we don't know how to
1016 // generate vector code.
1017 }
1018
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001019 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001020}
1021
Tobias Grossera69d4f02015-12-15 23:49:58 +00001022void VectorBlockGenerator::generateScalarVectorLoads(
1023 ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1024 for (MemoryAccess *MA : Stmt) {
1025 if (MA->isArrayKind() || MA->isWrite())
1026 continue;
1027
1028 auto *Address = getOrCreateAlloca(*MA);
1029 Type *VectorPtrType = getVectorPtrTy(Address, 1);
1030 Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1031 Address->getName() + "_p_vec_p");
1032 auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1033 Constant *SplatVector = Constant::getNullValue(
1034 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1035
1036 Value *VectorVal = Builder.CreateShuffleVector(
1037 Val, Val, SplatVector, Address->getName() + "_p_splat");
1038 VectorBlockMap[MA->getBaseAddr()] = VectorVal;
Tobias Grossera69d4f02015-12-15 23:49:58 +00001039 }
1040}
1041
1042void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1043 for (MemoryAccess *MA : Stmt) {
1044 if (MA->isArrayKind() || MA->isRead())
1045 continue;
1046
1047 llvm_unreachable("Scalar stores not expected in vector loop");
1048 }
1049}
1050
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001051void VectorBlockGenerator::copyStmt(
1052 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001053 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
1054 "the vector block generator");
1055
Johannes Doerfertbe9c9112015-02-06 21:39:31 +00001056 BasicBlock *BB = Stmt.getBasicBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001057 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1058 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001059 CopyBB->setName("polly.stmt." + BB->getName());
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001060 Builder.SetInsertPoint(&CopyBB->front());
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001061
1062 // Create two maps that store the mapping from the original instructions of
1063 // the old basic block to their copies in the new basic block. Those maps
1064 // are basic block local.
1065 //
1066 // As vector code generation is supported there is one map for scalar values
1067 // and one for vector values.
1068 //
1069 // In case we just do scalar code generation, the vectorMap is not used and
1070 // the scalarMap has just one dimension, which contains the mapping.
1071 //
1072 // In case vector code generation is done, an instruction may either appear
1073 // in the vector map once (as it is calculating >vectorwidth< values at a
1074 // time. Or (if the values are calculated using scalar operations), it
1075 // appears once in every dimension of the scalarMap.
1076 VectorValueMapT ScalarBlockMap(getVectorWidth());
1077 ValueMapT VectorBlockMap;
1078
Tobias Grossera69d4f02015-12-15 23:49:58 +00001079 generateScalarVectorLoads(Stmt, VectorBlockMap);
1080
Tobias Grosser91f5b262014-06-04 08:06:40 +00001081 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001082 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Tobias Grossera69d4f02015-12-15 23:49:58 +00001083
1084 verifyNoScalarStores(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001085}
Johannes Doerfert275a1752015-02-24 16:16:32 +00001086
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001087BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1088 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001089
1090 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1091 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1092
1093 if (BBCopyIDom)
1094 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1095
1096 return BBCopyIDom;
1097}
1098
Michael Krusef33c1252016-02-25 14:08:48 +00001099// This is to determine whether an llvm::Value (defined in @p BB) is usable when
1100// leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1101// does not work in cases where the exit block has edges from outside the
1102// region. In that case the llvm::Value would never be usable in in the exit
1103// block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1104// for the subregion's exiting edges only. We need to determine whether an
1105// llvm::Value is usable in there. We do this by checking whether it dominates
1106// all exiting blocks individually.
1107static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1108 BasicBlock *BB) {
1109 for (auto ExitingBB : predecessors(R->getExit())) {
1110 // Check for non-subregion incoming edges.
1111 if (!R->contains(ExitingBB))
1112 continue;
1113
1114 if (!DT.dominates(BB, ExitingBB))
1115 return false;
1116 }
1117
1118 return true;
1119}
1120
1121// Find the direct dominator of the subregion's exit block if the subregion was
1122// simplified.
1123static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1124 BasicBlock *Common = nullptr;
1125 for (auto ExitingBB : predecessors(R->getExit())) {
1126 // Check for non-subregion incoming edges.
1127 if (!R->contains(ExitingBB))
1128 continue;
1129
1130 // First exiting edge.
1131 if (!Common) {
1132 Common = ExitingBB;
1133 continue;
1134 }
1135
1136 Common = DT.findNearestCommonDominator(Common, ExitingBB);
1137 }
1138
1139 assert(Common && R->contains(Common));
1140 return Common;
1141}
1142
Tobias Grosserbc132602015-09-05 09:56:54 +00001143void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001144 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001145 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001146 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001147
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001148 // Forget all old mappings.
1149 BlockMap.clear();
1150 RegionMaps.clear();
1151 IncompletePHINodeMap.clear();
1152
Michael Kruse225f0d12015-10-17 21:36:00 +00001153 // Collection of all values related to this subregion.
1154 ValueMapT ValueMap;
1155
Johannes Doerfert275a1752015-02-24 16:16:32 +00001156 // The region represented by the statement.
1157 Region *R = Stmt.getRegion();
1158
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001159 // Create a dedicated entry for the region where we can reload all demoted
1160 // inputs.
1161 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001162 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1163 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001164 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001165 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001166
Michael Krusec9937392015-11-09 23:33:40 +00001167 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
Michael Kruse2fa35192016-09-01 19:53:31 +00001168 generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
Michael Kruse225f0d12015-10-17 21:36:00 +00001169
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001170 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1171 if (!R->contains(*PI))
1172 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001173
1174 // Iterate over all blocks in the region in a breadth-first search.
1175 std::deque<BasicBlock *> Blocks;
1176 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001177 Blocks.push_back(EntryBB);
1178 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001179
1180 while (!Blocks.empty()) {
1181 BasicBlock *BB = Blocks.front();
1182 Blocks.pop_front();
1183
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001184 // First split the block and update dominance information.
1185 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001186 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1187
Michael Krusec9937392015-11-09 23:33:40 +00001188 // Get the mapping for this block and initialize it with either the scalar
1189 // loads from the generated entering block (which dominates all blocks of
1190 // this subregion) or the maps of the immediate dominator, if part of the
1191 // subregion. The latter necessarily includes the former.
1192 ValueMapT *InitBBMap;
1193 if (BBCopyIDom) {
1194 assert(RegionMaps.count(BBCopyIDom));
1195 InitBBMap = &RegionMaps[BBCopyIDom];
1196 } else
1197 InitBBMap = &EntryBBMap;
1198 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1199 ValueMapT &RegionMap = Inserted.first->second;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001200
Johannes Doerfert275a1752015-02-24 16:16:32 +00001201 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001202 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001203 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001204
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001205 // In order to remap PHI nodes we store also basic block mappings.
1206 BlockMap[BB] = BBCopy;
1207
1208 // Add values to incomplete PHI nodes waiting for this block to be copied.
1209 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001210 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001211 IncompletePHINodeMap[BB].clear();
1212
Johannes Doerfert275a1752015-02-24 16:16:32 +00001213 // And continue with new successors inside the region.
1214 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1215 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1216 Blocks.push_back(*SI);
Michael Kruseebffcbe2015-11-09 22:37:29 +00001217
1218 // Remember value in case it is visible after this subregion.
Michael Krusef33c1252016-02-25 14:08:48 +00001219 if (isDominatingSubregionExit(DT, R, BB))
Michael Kruseebffcbe2015-11-09 22:37:29 +00001220 ValueMap.insert(RegionMap.begin(), RegionMap.end());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001221 }
1222
1223 // Now create a new dedicated region exit block and add it to the region map.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001224 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1225 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001226 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001227 BlockMap[R->getExit()] = ExitBBCopy;
1228
Michael Krusef33c1252016-02-25 14:08:48 +00001229 BasicBlock *ExitDomBBCopy = BlockMap.lookup(findExitDominator(DT, R));
1230 assert(ExitDomBBCopy && "Common exit dominator must be within region; at "
1231 "least the entry node must match");
1232 DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001233
1234 // As the block generator doesn't handle control flow we need to add the
1235 // region control flow by hand after all blocks have been copied.
1236 for (BasicBlock *BB : SeenBlocks) {
1237
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001238 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001239 TerminatorInst *TI = BB->getTerminator();
1240 if (isa<UnreachableInst>(TI)) {
1241 while (!BBCopy->empty())
1242 BBCopy->begin()->eraseFromParent();
1243 new UnreachableInst(BBCopy->getContext(), BBCopy);
1244 continue;
1245 }
1246
Johannes Doerfert275a1752015-02-24 16:16:32 +00001247 Instruction *BICopy = BBCopy->getTerminator();
1248
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001249 ValueMapT &RegionMap = RegionMaps[BBCopy];
1250 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1251
Tobias Grosser45e79442015-08-01 09:07:57 +00001252 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001253 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001254 BICopy->eraseFromParent();
1255 }
1256
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001257 // Add counting PHI nodes to all loops in the region that can be used as
1258 // replacement for SCEVs refering to the old loop.
1259 for (BasicBlock *BB : SeenBlocks) {
1260 Loop *L = LI.getLoopFor(BB);
Tobias Grosserbc29e0b2015-11-12 07:34:09 +00001261 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001262 continue;
1263
1264 BasicBlock *BBCopy = BlockMap[BB];
1265 Value *NullVal = Builder.getInt32(0);
1266 PHINode *LoopPHI =
1267 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1268 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1269 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001270 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001271 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1272
1273 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1274 if (!R->contains(PredBB))
1275 continue;
1276 if (L->contains(PredBB))
1277 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1278 else
1279 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1280 }
1281
1282 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1283 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1284 LoopPHI->addIncoming(NullVal, PredBBCopy);
1285
1286 LTS[L] = SE.getUnknown(LoopPHI);
1287 }
1288
Michael Kruse225f0d12015-10-17 21:36:00 +00001289 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001290 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001291
1292 // Write values visible to other statements.
Michael Kruse2fa35192016-09-01 19:53:31 +00001293 generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
Tobias Grosser3e956022015-10-26 20:41:53 +00001294 BlockMap.clear();
1295 RegionMaps.clear();
1296 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001297}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001298
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001299PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1300 ValueMapT &BBMap, Loop *L) {
1301 ScopStmt *Stmt = MA->getStatement();
1302 Region *SubR = Stmt->getRegion();
1303 auto Incoming = MA->getIncoming();
1304
1305 PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1306 PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1307 BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1308
1309 // This can happen if the subregion is simplified after the ScopStmts
1310 // have been created; simplification happens as part of CodeGeneration.
1311 if (OrigPHI->getParent() != SubR->getExit()) {
1312 BasicBlock *FormerExit = SubR->getExitingBlock();
1313 if (FormerExit)
1314 NewSubregionExit = BlockMap.lookup(FormerExit);
1315 }
1316
1317 PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1318 "polly." + OrigPHI->getName(),
1319 NewSubregionExit->getFirstNonPHI());
1320
1321 // Add the incoming values to the PHI.
1322 for (auto &Pair : Incoming) {
1323 BasicBlock *OrigIncomingBlock = Pair.first;
1324 BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock);
1325 Builder.SetInsertPoint(NewIncomingBlock->getTerminator());
1326 assert(RegionMaps.count(NewIncomingBlock));
1327 ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock];
1328
1329 Value *OrigIncomingValue = Pair.second;
1330 Value *NewIncomingValue =
1331 getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1332 NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock);
1333 }
1334
1335 return NewPHI;
1336}
1337
1338Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1339 ValueMapT &BBMap) {
1340 ScopStmt *Stmt = MA->getStatement();
1341
1342 // TODO: Add some test cases that ensure this is really the right choice.
1343 Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1344
1345 if (MA->isAnyPHIKind()) {
1346 auto Incoming = MA->getIncoming();
1347 assert(!Incoming.empty() &&
1348 "PHI WRITEs must have originate from at least one incoming block");
1349
1350 // If there is only one incoming value, we do not need to create a PHI.
1351 if (Incoming.size() == 1) {
1352 Value *OldVal = Incoming[0].second;
1353 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1354 }
1355
1356 return buildExitPHI(MA, LTS, BBMap, L);
1357 }
1358
1359 // MK_Value accesses leaving the subregion must dominate the exit block; just
1360 // pass the copied value
1361 Value *OldVal = MA->getAccessValue();
1362 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1363}
1364
Michael Kruse2fa35192016-09-01 19:53:31 +00001365void RegionGenerator::generateScalarStores(
1366 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1367 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser75296902015-08-21 19:23:21 +00001368 assert(Stmt.getRegion() &&
1369 "Block statements need to use the generateScalarStores() "
1370 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001371
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001372 for (MemoryAccess *MA : Stmt) {
Michael Kruse2fa35192016-09-01 19:53:31 +00001373 if (MA->isOriginalArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001374 continue;
1375
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001376 Value *NewVal = getExitScalar(MA, LTS, BBMap);
Michael Kruse2fa35192016-09-01 19:53:31 +00001377 Value *Address =
1378 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
Michael Kruseeac97262016-02-24 22:08:14 +00001379 assert((!isa<Instruction>(NewVal) ||
1380 DT.dominates(cast<Instruction>(NewVal)->getParent(),
1381 Builder.GetInsertBlock())) &&
1382 "Domination violation");
1383 assert((!isa<Instruction>(Address) ||
1384 DT.dominates(cast<Instruction>(Address)->getParent(),
1385 Builder.GetInsertBlock())) &&
1386 "Domination violation");
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001387 Builder.CreateStore(NewVal, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001388 }
1389}
1390
1391void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1392 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001393 LoopToScevMapT &LTS) {
1394 Region *StmtR = Stmt.getRegion();
1395
1396 // If the incoming block was not yet copied mark this PHI as incomplete.
1397 // Once the block will be copied the incoming value will be added.
1398 BasicBlock *BBCopy = BlockMap[IncomingBB];
1399 if (!BBCopy) {
1400 assert(StmtR->contains(IncomingBB) &&
1401 "Bad incoming block for PHI in non-affine region");
1402 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1403 return;
1404 }
1405
1406 Value *OpCopy = nullptr;
1407 if (StmtR->contains(IncomingBB)) {
1408 assert(RegionMaps.count(BBCopy) &&
1409 "Incoming PHI block did not have a BBMap");
1410 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1411
1412 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001413
Johannes Doerfert6ba92712016-04-01 11:25:47 +00001414 // If the current insert block is different from the PHIs incoming block
1415 // change it, otherwise do not.
1416 auto IP = Builder.GetInsertPoint();
1417 if (IP->getParent() != BBCopy)
1418 Builder.SetInsertPoint(BBCopy->getTerminator());
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +00001419 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
Johannes Doerfert6ba92712016-04-01 11:25:47 +00001420 if (IP->getParent() != BBCopy)
1421 Builder.SetInsertPoint(&*IP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001422 } else {
1423
1424 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1425 return;
1426
Tobias Grosserbc132602015-09-05 09:56:54 +00001427 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001428 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1429 BlockMap[IncomingBB]->getTerminator());
1430 }
1431
1432 assert(OpCopy && "Incoming PHI value was not copied properly");
1433 assert(BBCopy && "Incoming PHI block was not copied properly");
1434 PHICopy->addIncoming(OpCopy, BBCopy);
1435}
1436
Tobias Grosser2b809d12016-02-21 15:44:34 +00001437void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1438 ValueMapT &BBMap,
1439 LoopToScevMapT &LTS) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001440 unsigned NumIncoming = PHI->getNumIncomingValues();
1441 PHINode *PHICopy =
1442 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1443 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1444 BBMap[PHI] = PHICopy;
1445
1446 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001447 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001448}