blob: d6be497b8dc783e39cf91eb92411292970b9e786 [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
Johannes Doerfert42df8d12015-12-22 19:08:01 +000076 const SCEV *NewScev = apply(Scev, LTS, SE);
77 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();
82 const DataLayout &DL =
83 S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
84 auto IP = Builder.GetInsertPoint();
85
86 assert(IP != Builder.GetInsertBlock()->end() &&
87 "Only instructions can be insert points for SCEVExpander");
88 Value *Expanded =
89 expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV);
90
91 BBMap[Old] = Expanded;
92 return Expanded;
Tobias Grosser33cb9f92015-09-30 11:56:19 +000093}
94
Tobias Grosser2f1acac2015-10-04 10:18:45 +000095Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
96 LoopToScevMapT &LTS, Loop *L) const {
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000097 // Constants that do not reference any named value can always remain
Michael Kruse5bbc0e12015-12-14 23:41:32 +000098 // unchanged. Handle them early to avoid expensive map lookups. We do not take
Tobias Grosser9bd0dad2015-12-14 16:19:59 +000099 // the fast-path for external constants which are referenced through globals
100 // as these may need to be rewritten when distributing code accross different
101 // LLVM modules.
102 if (isa<Constant>(Old) && !isa<GlobalValue>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000103 return Old;
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000104
Johannes Doerfert28f8ac12015-12-22 19:08:24 +0000105 // Inline asm is like a constant to us.
106 if (isa<InlineAsm>(Old))
107 return Old;
108
Tobias Grosser33cb9f92015-09-30 11:56:19 +0000109 if (Value *New = GlobalMap.lookup(Old)) {
110 if (Value *NewRemapped = GlobalMap.lookup(New))
111 New = NewRemapped;
112 if (Old->getType()->getScalarSizeInBits() <
113 New->getType()->getScalarSizeInBits())
114 New = Builder.CreateTruncOrBitCast(New, Old->getType());
115
116 return New;
117 }
118
119 if (Value *New = BBMap.lookup(Old))
120 return New;
121
122 if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
123 return New;
124
Tobias Grosser16371ac2014-11-05 20:48:56 +0000125 // A scop-constant value defined by a global or a function parameter.
126 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000127 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000128
129 // A scop-constant value defined by an instruction executed outside the scop.
130 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000131 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser6f764bb2015-12-14 16:19:54 +0000132 return Old;
Tobias Grosser16371ac2014-11-05 20:48:56 +0000133
134 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000135 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000136 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000137}
138
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000139void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000140 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000141 // We do not generate debug intrinsics as we did not investigate how to
142 // copy them correctly. At the current state, they just crash the code
143 // generation as the meta-data operands are not correctly copied.
144 if (isa<DbgInfoIntrinsic>(Inst))
145 return;
146
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000147 Instruction *NewInst = Inst->clone();
148
149 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000150 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000151 Value *NewOperand =
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000152 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000153
154 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000155 assert(!isa<StoreInst>(NewInst) &&
156 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000157 delete NewInst;
158 return;
159 }
160
161 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
162 }
163
164 Builder.Insert(NewInst);
165 BBMap[Inst] = NewInst;
166
167 if (!NewInst->getType()->isVoidTy())
168 NewInst->setName("p_" + Inst->getName());
169}
170
Michael Kruse70131d32016-01-27 17:09:17 +0000171Value *
172BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
173 ValueMapT &BBMap, LoopToScevMapT &LTS,
174 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser09214772015-12-15 23:49:53 +0000175 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000176
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000177 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000178
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000179 if (AccessExpr) {
180 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000181 auto Address = ExprBuilder->create(AccessExpr);
182
183 // Cast the address of this memory access to a pointer type that has the
184 // same element type as the original access, but uses the address space of
185 // the newly generated pointer.
186 auto OldPtrTy = MA.getAccessValue()->getType()->getPointerTo();
187 auto NewPtrTy = Address->getType();
188 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
189 NewPtrTy->getPointerAddressSpace());
190
Tobias Grosserd840fc72016-02-04 13:18:42 +0000191 if (OldPtrTy != NewPtrTy)
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000192 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000193 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000194 }
195
Michael Kruse70131d32016-01-27 17:09:17 +0000196 return getNewValue(Stmt, Inst.getPointerOperand(), BBMap, LTS,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000197 getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000198}
199
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000200Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
201 auto *StmtBB =
202 Stmt.isBlockStmt() ? Stmt.getBasicBlock() : Stmt.getRegion()->getEntry();
203 return LI.getLoopFor(StmtBB);
Tobias Grosser369430f2013-03-22 23:42:53 +0000204}
205
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000206Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000207 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000208 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000209 if (Value *PreloadLoad = GlobalMap.lookup(Load))
210 return PreloadLoad;
211
Tobias Grosserbc132602015-09-05 09:56:54 +0000212 Value *NewPointer =
Michael Kruse70131d32016-01-27 17:09:17 +0000213 generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000214 Value *ScalarLoad = Builder.CreateAlignedLoad(
215 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000216
217 if (DebugPrinting)
218 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
219 ": ", ScalarLoad, "\n");
220
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000221 return ScalarLoad;
222}
223
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000224void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000225 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000226 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000227 Value *NewPointer =
Michael Kruse70131d32016-01-27 17:09:17 +0000228 generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
Tobias Grosserbc132602015-09-05 09:56:54 +0000229 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000230 getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000231
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000232 if (DebugPrinting)
233 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
234 ": ", ValueOperand, "\n");
235
Tobias Grosserc186ac72015-08-11 08:13:15 +0000236 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000237}
238
Johannes Doerfert5dced262015-12-22 19:08:49 +0000239bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000240 Loop *L = getLoopForStmt(Stmt);
Johannes Doerfert5dced262015-12-22 19:08:49 +0000241 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
242 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion());
243}
244
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000245void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000246 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000247 isl_id_to_ast_expr *NewAccesses) {
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 Doerfert5dced262015-12-22 19:08:49 +0000253 // Synthesizable statements will be generated on-demand.
254 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000255 return;
256
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000257 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000258 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000259 // Compute NewLoad before its insertion in BBMap to make the insertion
260 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000261 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000262 return;
263 }
264
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000265 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000266 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000267 return;
268 }
269
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000270 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000271 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000272 return;
273 }
274
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000275 // Skip some special intrinsics for which we do not adjust the semantics to
276 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000277 if (isIgnoredIntrinsic(Inst))
278 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000279
Tobias Grosserbc132602015-09-05 09:56:54 +0000280 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000281}
282
Tobias Grosserbc132602015-09-05 09:56:54 +0000283void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000284 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000285 assert(Stmt.isBlockStmt() &&
286 "Only block statements can be copied by the block generator");
287
288 ValueMapT BBMap;
289
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000290 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000291 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000292}
293
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000294BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000295 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
296 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000297 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000298 return CopyBB;
299}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000300
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000301BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000302 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000303 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000304 BasicBlock *CopyBB = splitBB(BB);
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000305 Builder.SetInsertPoint(&CopyBB->front());
Michael Kruse225f0d12015-10-17 21:36:00 +0000306 generateScalarLoads(Stmt, BBMap);
307
Tobias Grosserbc132602015-09-05 09:56:54 +0000308 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000309
310 // After a basic block was copied store all scalars that escape this block in
311 // their alloca.
312 generateScalarStores(Stmt, LTS, BBMap);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000313 return CopyBB;
314}
315
316void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000317 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000318 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000319 EntryBB = &CopyBB->getParent()->getEntryBlock();
320
Tobias Grosser91f5b262014-06-04 08:06:40 +0000321 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000322 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000323}
324
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000325Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
326 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000327 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000328 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000329 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000330 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000331 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000332 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000333 NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000334 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000335 }
336
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000337 auto Addr = Map[ScalarBase];
338
Tobias Grosser5c7f16b2016-01-24 14:16:59 +0000339 if (auto NewAddr = GlobalMap.lookup(Addr))
340 return NewAddr;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000341
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000342 return Addr;
343}
344
Johannes Doerfert800e17a2016-02-02 14:16:01 +0000345Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000346 if (Access.isPHIKind())
Tobias Grosserb8d27aa2015-10-18 00:51:13 +0000347 return getOrCreatePHIAlloca(Access.getBaseAddr());
348 else
349 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grossera4f09882015-10-17 22:16:00 +0000350}
351
352Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000353 if (Array->isPHIKind())
Tobias Grossera4f09882015-10-17 22:16:00 +0000354 return getOrCreatePHIAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000355 else
Tobias Grossera4f09882015-10-17 22:16:00 +0000356 return getOrCreateScalarAlloca(Array->getBasePtr());
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,
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000368 Value *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.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000394 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000395
396 // Remember that this instruction has escape uses and the escape alloca.
397 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000398}
399
Michael Kruse225f0d12015-10-17 21:36:00 +0000400void BlockGenerator::generateScalarLoads(ScopStmt &Stmt, ValueMapT &BBMap) {
401 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000402 if (MA->isArrayKind() || MA->isWrite())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000403 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000404
Michael Krusee2bccbb2015-09-18 19:59:43 +0000405 auto *Address = getOrCreateAlloca(*MA);
Michael Kruseeac97262016-02-24 22:08:14 +0000406 assert((!isa<Instruction>(Address) ||
407 DT.dominates(cast<Instruction>(Address)->getParent(),
408 Builder.GetInsertBlock())) &&
409 "Domination violation");
Michael Krusee2bccbb2015-09-18 19:59:43 +0000410 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000411 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000412 }
413}
414
Michael Kruse225f0d12015-10-17 21:36:00 +0000415void BlockGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000416 ValueMapT &BBMap) {
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000417 Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000418
Michael Kruse225f0d12015-10-17 21:36:00 +0000419 assert(Stmt.isBlockStmt() && "Region statements need to use the "
420 "generateScalarStores() function in the "
421 "RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000422
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000423 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000424 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000425 continue;
426
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000427 Value *Val = MA->getAccessValue();
Michael Kruseee6a4fc2016-01-26 13:33:27 +0000428 if (MA->isAnyPHIKind()) {
429 assert(MA->getIncoming().size() >= 1 &&
430 "Block statements have exactly one exiting block, or multiple but "
431 "with same incoming block and value");
432 assert(std::all_of(MA->getIncoming().begin(), MA->getIncoming().end(),
433 [&](std::pair<BasicBlock *, Value *> p) -> bool {
434 return p.first == Stmt.getBasicBlock();
435 }) &&
436 "Incoming block must be statement's block");
437 Val = MA->getIncoming()[0].second;
438 }
Tobias Grosserbc132602015-09-05 09:56:54 +0000439 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000440
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000441 Val = getNewValue(Stmt, Val, BBMap, LTS, L);
Michael Kruseeac97262016-02-24 22:08:14 +0000442 assert((!isa<Instruction>(Val) ||
443 DT.dominates(cast<Instruction>(Val)->getParent(),
444 Builder.GetInsertBlock())) &&
445 "Domination violation");
446 assert((!isa<Instruction>(Address) ||
447 DT.dominates(cast<Instruction>(Address)->getParent(),
448 Builder.GetInsertBlock())) &&
449 "Domination violation");
Tobias Grosser92245222015-07-28 14:53:44 +0000450 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000451 }
452}
453
Tobias Grosserc0091a72015-08-30 19:19:34 +0000454void BlockGenerator::createScalarInitialization(Scop &S) {
455 Region &R = S.getRegion();
Johannes Doerfert188542f2015-11-09 00:21:21 +0000456 BasicBlock *ExitBB = R.getExit();
457
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000458 // The split block __just before__ the region and optimized region.
459 BasicBlock *SplitBB = R.getEnteringBlock();
460 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
461 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
462
463 // Get the start block of the __optimized__ region.
464 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
465 if (StartBB == R.getEntry())
466 StartBB = SplitBBTerm->getSuccessor(1);
467
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000468 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000469
Tobias Grosserc0091a72015-08-30 19:19:34 +0000470 for (auto &Pair : S.arrays()) {
471 auto &Array = Pair.second;
472 if (Array->getNumberOfDimensions() != 0)
473 continue;
Tobias Grossera535dff2015-12-13 19:59:01 +0000474 if (Array->isPHIKind()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000475 // For PHI nodes, the only values we need to store are the ones that
476 // reach the PHI node from outside the region. In general there should
477 // only be one such incoming edge and this edge should enter through
478 // 'SplitBB'.
479 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000480
Tobias Grosserc0091a72015-08-30 19:19:34 +0000481 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
482 if (!R.contains(*BI) && *BI != SplitBB)
483 llvm_unreachable("Incoming edges from outside the scop should always "
484 "come from SplitBB");
485
486 int Idx = PHI->getBasicBlockIndex(SplitBB);
487 if (Idx < 0)
488 continue;
489
490 Value *ScalarValue = PHI->getIncomingValue(Idx);
491
Tobias Grosserbc132602015-09-05 09:56:54 +0000492 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000493 continue;
494 }
495
496 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
497
498 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000499 continue;
500
Johannes Doerfert188542f2015-11-09 00:21:21 +0000501 // PHI nodes that are not marked as such in their SAI object are either exit
502 // PHI nodes we model as common scalars but without initialization, or
503 // incoming phi nodes that need to be initialized. Check if the first is the
504 // case for Inst and do not create and initialize memory if so.
505 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
506 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
507 continue;
Johannes Doerfert717b8662015-09-08 21:44:27 +0000508
Tobias Grosserc0091a72015-08-30 19:19:34 +0000509 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000510 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000511 }
512}
513
514void BlockGenerator::createScalarFinalization(Region &R) {
515 // The exit block of the __unoptimized__ region.
516 BasicBlock *ExitBB = R.getExitingBlock();
517 // The merge block __just after__ the region and the optimized region.
518 BasicBlock *MergeBB = R.getExit();
519
520 // The exit block of the __optimized__ region.
521 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
522 if (OptExitBB == ExitBB)
523 OptExitBB = *(++pred_begin(MergeBB));
524
525 Builder.SetInsertPoint(OptExitBB->getTerminator());
526 for (const auto &EscapeMapping : EscapeMap) {
527 // Extract the escaping instruction and the escaping users as well as the
528 // alloca the instruction was demoted to.
529 Instruction *EscapeInst = EscapeMapping.getFirst();
530 const auto &EscapeMappingValue = EscapeMapping.getSecond();
531 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000532 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000533
534 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000535 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000536 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000537 EscapeInstReload =
538 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000539
540 // Create the merge PHI that merges the optimized and unoptimized version.
541 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
542 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000543 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000544
545 // Add the respective values to the merge PHI.
546 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
547 MergePHI->addIncoming(EscapeInst, ExitBB);
548
549 // The information of scalar evolution about the escaping instruction needs
550 // to be revoked so the new merged instruction will be used.
551 if (SE.isSCEVable(EscapeInst->getType()))
552 SE.forgetValue(EscapeInst);
553
554 // Replace all uses of the demoted instruction with the merge PHI.
555 for (Instruction *EUser : EscapeUsers)
556 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
557 }
558}
559
Tobias Grosserffa24462015-10-17 08:54:13 +0000560void BlockGenerator::findOutsideUsers(Scop &S) {
561 auto &R = S.getRegion();
Tobias Grosserffa24462015-10-17 08:54:13 +0000562 for (auto &Pair : S.arrays()) {
563 auto &Array = Pair.second;
564
565 if (Array->getNumberOfDimensions() != 0)
566 continue;
567
Tobias Grossera535dff2015-12-13 19:59:01 +0000568 if (Array->isPHIKind())
Tobias Grosserffa24462015-10-17 08:54:13 +0000569 continue;
570
571 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
572
573 if (!Inst)
574 continue;
575
576 // Scop invariant hoisting moves some of the base pointers out of the scop.
577 // We can ignore these, as the invariant load hoisting already registers the
578 // relevant outside users.
579 if (!R.contains(Inst))
580 continue;
581
582 handleOutsideUsers(R, Inst, nullptr);
583 }
584}
585
Tobias Grosser27d742d2015-10-24 17:41:29 +0000586void BlockGenerator::createExitPHINodeMerges(Scop &S) {
587 if (S.hasSingleExitEdge())
588 return;
589
590 Region &R = S.getRegion();
591
592 auto *ExitBB = R.getExitingBlock();
593 auto *MergeBB = R.getExit();
594 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
595 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
596 if (OptExitBB == ExitBB)
597 OptExitBB = *(++pred_begin(MergeBB));
598
599 Builder.SetInsertPoint(OptExitBB->getTerminator());
600
601 for (auto &Pair : S.arrays()) {
602 auto &SAI = Pair.second;
603 auto *Val = SAI->getBasePtr();
604
605 PHINode *PHI = dyn_cast<PHINode>(Val);
606 if (!PHI)
607 continue;
608
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000609 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000610 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000611
612 std::string Name = PHI->getName();
613 Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
614 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
615 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
616 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
617 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000618 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000619 MergePHI->addIncoming(Reload, OptExitBB);
620 MergePHI->addIncoming(OriginalValue, ExitBB);
621 int Idx = PHI->getBasicBlockIndex(MergeBB);
622 PHI->setIncomingValue(Idx, MergePHI);
623 }
624}
625
Tobias Grosserffa24462015-10-17 08:54:13 +0000626void BlockGenerator::finalizeSCoP(Scop &S) {
627 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000628 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000629 createExitPHINodeMerges(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000630 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000631}
632
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000633VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000634 std::vector<LoopToScevMapT> &VLTS,
635 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000636 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000637 assert(Schedule && "No statement domain provided");
638}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000639
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000640Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000641 ValueMapT &VectorMap,
642 VectorValueMapT &ScalarMaps,
643 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000644 if (Value *NewValue = VectorMap.lookup(Old))
645 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000646
647 int Width = getVectorWidth();
648
649 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
650
651 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000652 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000653 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000654 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000655
656 VectorMap[Old] = Vector;
657
658 return Vector;
659}
660
661Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
662 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
663 assert(PointerTy && "PointerType expected");
664
665 Type *ScalarType = PointerTy->getElementType();
666 VectorType *VectorType = VectorType::get(ScalarType, Width);
667
668 return PointerType::getUnqual(VectorType);
669}
670
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000671Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000672 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000673 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000674 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000675 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000676 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
677 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
678
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000679 Value *NewPointer = nullptr;
Michael Kruse70131d32016-01-27 17:09:17 +0000680 NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
Tobias Grosserbc132602015-09-05 09:56:54 +0000681 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000682 Value *VectorPtr =
683 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
684 LoadInst *VecLoad =
685 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000686 if (!Aligned)
687 VecLoad->setAlignment(8);
688
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000689 if (NegativeStride) {
690 SmallVector<Constant *, 16> Indices;
691 for (int i = VectorWidth - 1; i >= 0; i--)
692 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
693 Constant *SV = llvm::ConstantVector::get(Indices);
694 Value *RevVecLoad = Builder.CreateShuffleVector(
695 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
696 return RevVecLoad;
697 }
698
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000699 return VecLoad;
700}
701
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000702Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000703 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000704 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000705 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000706 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Michael Kruse70131d32016-01-27 17:09:17 +0000707 Value *NewPointer =
708 generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000709 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
710 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000711 LoadInst *ScalarLoad =
712 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000713
714 if (!Aligned)
715 ScalarLoad->setAlignment(8);
716
Tobias Grosserc14582f2013-02-05 18:01:29 +0000717 Constant *SplatVector = Constant::getNullValue(
718 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000719
Tobias Grosserc14582f2013-02-05 18:01:29 +0000720 Value *VectorLoad = Builder.CreateShuffleVector(
721 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000722 return VectorLoad;
723}
724
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000725Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000726 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000727 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000728 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000729 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000730 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000731 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000732
733 Value *Vector = UndefValue::get(VectorType);
734
735 for (int i = 0; i < VectorWidth; i++) {
Michael Kruse70131d32016-01-27 17:09:17 +0000736 Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
737 VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000738 Value *ScalarLoad =
739 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
740 Vector = Builder.CreateInsertElement(
741 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000742 }
743
744 return Vector;
745}
746
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000747void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000748 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000749 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000750 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
751 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
752 Load->getName() + "_p");
753 return;
754 }
755
Tobias Grosser28736452015-03-23 07:00:36 +0000756 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000757 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000758 ScalarMaps[i][Load] =
759 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000760 return;
761 }
762
Tobias Grosser184a4922015-12-15 23:50:01 +0000763 const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000764
Tobias Grosser95493982014-04-18 09:46:35 +0000765 // Make sure we have scalar values available to access the pointer to
766 // the data location.
767 extractScalarValues(Load, VectorMap, ScalarMaps);
768
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000769 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000770 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000771 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000772 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000773 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000774 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000775 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000776 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000777 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000778
779 VectorMap[Load] = NewLoad;
780}
781
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000782void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000783 ValueMapT &VectorMap,
784 VectorValueMapT &ScalarMaps) {
785 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000786 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000787 ScalarMaps, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000788
789 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
790
791 const CastInst *Cast = dyn_cast<CastInst>(Inst);
792 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
793 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
794}
795
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000796void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000797 ValueMapT &VectorMap,
798 VectorValueMapT &ScalarMaps) {
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000799 Loop *L = getLoopForStmt(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000800 Value *OpZero = Inst->getOperand(0);
801 Value *OpOne = Inst->getOperand(1);
802
803 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000804 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
805 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000806
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000807 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000808 Inst->getName() + "p_vec");
809 VectorMap[Inst] = NewInst;
810}
811
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000812void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000813 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000814 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser184a4922015-12-15 23:50:01 +0000815 const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000816
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000817 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000818 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +0000819 ScalarMaps, getLoopForStmt(Stmt));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000820
Tobias Grosser50fd7012014-04-17 23:13:49 +0000821 // Make sure we have scalar values available to access the pointer to
822 // the data location.
823 extractScalarValues(Store, VectorMap, ScalarMaps);
824
Sebastian Popa00a0292012-12-18 07:46:06 +0000825 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000826 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Michael Kruse70131d32016-01-27 17:09:17 +0000827 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
828 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000829
Tobias Grosserc14582f2013-02-05 18:01:29 +0000830 Value *VectorPtr =
831 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000832 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
833
834 if (!Aligned)
835 Store->setAlignment(8);
836 } else {
837 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000838 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Michael Kruse70131d32016-01-27 17:09:17 +0000839 Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
840 VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000841 Builder.CreateStore(Scalar, NewPointer);
842 }
843 }
844}
845
846bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
847 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000848 for (Value *Operand : Inst->operands())
849 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000850 return true;
851 return false;
852}
853
854bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
855 ValueMapT &VectorMap,
856 VectorValueMapT &ScalarMaps) {
857 bool HasVectorOperand = false;
858 int VectorWidth = getVectorWidth();
859
Tobias Grosser91f5b262014-06-04 08:06:40 +0000860 for (Value *Operand : Inst->operands()) {
861 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000862
863 if (VecOp == VectorMap.end())
864 continue;
865
866 HasVectorOperand = true;
867 Value *NewVector = VecOp->second;
868
869 for (int i = 0; i < VectorWidth; ++i) {
870 ValueMapT &SM = ScalarMaps[i];
871
872 // If there is one scalar extracted, all scalar elements should have
873 // already been extracted by the code here. So no need to check for the
874 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000875 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000876 break;
877
Tobias Grosser91f5b262014-06-04 08:06:40 +0000878 SM[Operand] =
879 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000880 }
881 }
882
883 return HasVectorOperand;
884}
885
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000886void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000887 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000888 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000889 bool HasVectorOperand;
890 int VectorWidth = getVectorWidth();
891
892 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
893
894 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000895 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000896 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000897
898 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
899 return;
900
901 // Make the result available as vector value.
902 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
903 Value *Vector = UndefValue::get(VectorType);
904
905 for (int i = 0; i < VectorWidth; i++)
906 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
907 Builder.getInt32(i));
908
909 VectorMap[Inst] = Vector;
910}
911
Tobias Grosserbc132602015-09-05 09:56:54 +0000912int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000913
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000914void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000915 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000916 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000917 // Terminator instructions control the control flow. They are explicitly
918 // expressed in the clast and do not need to be copied.
919 if (Inst->isTerminator())
920 return;
921
Johannes Doerfert5dced262015-12-22 19:08:49 +0000922 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000923 return;
924
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000925 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000926 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000927 return;
928 }
929
930 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000931 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000932 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000933 return;
934 }
935
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000936 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000937 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000938 return;
939 }
940
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000941 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000942 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000943 return;
944 }
945
946 // Falltrough: We generate scalar instructions, if we don't know how to
947 // generate vector code.
948 }
949
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000950 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000951}
952
Tobias Grossera69d4f02015-12-15 23:49:58 +0000953void VectorBlockGenerator::generateScalarVectorLoads(
954 ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
955 for (MemoryAccess *MA : Stmt) {
956 if (MA->isArrayKind() || MA->isWrite())
957 continue;
958
959 auto *Address = getOrCreateAlloca(*MA);
960 Type *VectorPtrType = getVectorPtrTy(Address, 1);
961 Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
962 Address->getName() + "_p_vec_p");
963 auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
964 Constant *SplatVector = Constant::getNullValue(
965 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
966
967 Value *VectorVal = Builder.CreateShuffleVector(
968 Val, Val, SplatVector, Address->getName() + "_p_splat");
969 VectorBlockMap[MA->getBaseAddr()] = VectorVal;
970 VectorVal->dump();
971 }
972}
973
974void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
975 for (MemoryAccess *MA : Stmt) {
976 if (MA->isArrayKind() || MA->isRead())
977 continue;
978
979 llvm_unreachable("Scalar stores not expected in vector loop");
980 }
981}
982
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000983void VectorBlockGenerator::copyStmt(
984 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000985 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
986 "the vector block generator");
987
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000988 BasicBlock *BB = Stmt.getBasicBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000989 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
990 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000991 CopyBB->setName("polly.stmt." + BB->getName());
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000992 Builder.SetInsertPoint(&CopyBB->front());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000993
994 // Create two maps that store the mapping from the original instructions of
995 // the old basic block to their copies in the new basic block. Those maps
996 // are basic block local.
997 //
998 // As vector code generation is supported there is one map for scalar values
999 // and one for vector values.
1000 //
1001 // In case we just do scalar code generation, the vectorMap is not used and
1002 // the scalarMap has just one dimension, which contains the mapping.
1003 //
1004 // In case vector code generation is done, an instruction may either appear
1005 // in the vector map once (as it is calculating >vectorwidth< values at a
1006 // time. Or (if the values are calculated using scalar operations), it
1007 // appears once in every dimension of the scalarMap.
1008 VectorValueMapT ScalarBlockMap(getVectorWidth());
1009 ValueMapT VectorBlockMap;
1010
Tobias Grossera69d4f02015-12-15 23:49:58 +00001011 generateScalarVectorLoads(Stmt, VectorBlockMap);
1012
Tobias Grosser91f5b262014-06-04 08:06:40 +00001013 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001014 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Tobias Grossera69d4f02015-12-15 23:49:58 +00001015
1016 verifyNoScalarStores(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001017}
Johannes Doerfert275a1752015-02-24 16:16:32 +00001018
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001019BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1020 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001021
1022 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1023 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1024
1025 if (BBCopyIDom)
1026 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1027
1028 return BBCopyIDom;
1029}
1030
Tobias Grosserbc132602015-09-05 09:56:54 +00001031void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001032 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001033 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001034 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001035
Michael Krused6fb6f12015-11-09 23:07:38 +00001036 Scop *S = Stmt.getParent();
1037
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001038 // Forget all old mappings.
1039 BlockMap.clear();
1040 RegionMaps.clear();
1041 IncompletePHINodeMap.clear();
1042
Michael Kruse225f0d12015-10-17 21:36:00 +00001043 // Collection of all values related to this subregion.
1044 ValueMapT ValueMap;
1045
Johannes Doerfert275a1752015-02-24 16:16:32 +00001046 // The region represented by the statement.
1047 Region *R = Stmt.getRegion();
1048
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001049 // Create a dedicated entry for the region where we can reload all demoted
1050 // inputs.
1051 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001052 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1053 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001054 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001055 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001056
Michael Krusec9937392015-11-09 23:33:40 +00001057 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1058 generateScalarLoads(Stmt, EntryBBMap);
Michael Kruse225f0d12015-10-17 21:36:00 +00001059
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001060 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1061 if (!R->contains(*PI))
1062 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001063
Michael Krused6fb6f12015-11-09 23:07:38 +00001064 // Determine the original exit block of this subregion. If it the exit block
1065 // is also the scop's exit, it it has been changed to polly.merge_new_and_old.
1066 // We move one block back to find the original block. This only happens if the
1067 // scop required simplification.
1068 // If the whole scop consists of only this non-affine region, then they share
1069 // the same Region object, such that we cannot change the exit of one and not
1070 // the other.
1071 BasicBlock *ExitBB = R->getExit();
1072 if (!S->hasSingleExitEdge() && ExitBB == S->getRegion().getExit())
1073 ExitBB = *(++pred_begin(ExitBB));
1074
Johannes Doerfert275a1752015-02-24 16:16:32 +00001075 // Iterate over all blocks in the region in a breadth-first search.
1076 std::deque<BasicBlock *> Blocks;
1077 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001078 Blocks.push_back(EntryBB);
1079 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001080
1081 while (!Blocks.empty()) {
1082 BasicBlock *BB = Blocks.front();
1083 Blocks.pop_front();
1084
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001085 // First split the block and update dominance information.
1086 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001087 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1088
1089 // In order to remap PHI nodes we store also basic block mappings.
1090 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001091
Michael Krusec9937392015-11-09 23:33:40 +00001092 // Get the mapping for this block and initialize it with either the scalar
1093 // loads from the generated entering block (which dominates all blocks of
1094 // this subregion) or the maps of the immediate dominator, if part of the
1095 // subregion. The latter necessarily includes the former.
1096 ValueMapT *InitBBMap;
1097 if (BBCopyIDom) {
1098 assert(RegionMaps.count(BBCopyIDom));
1099 InitBBMap = &RegionMaps[BBCopyIDom];
1100 } else
1101 InitBBMap = &EntryBBMap;
1102 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1103 ValueMapT &RegionMap = Inserted.first->second;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001104
Johannes Doerfert275a1752015-02-24 16:16:32 +00001105 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001106 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001107 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001108
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001109 // In order to remap PHI nodes we store also basic block mappings.
1110 BlockMap[BB] = BBCopy;
1111
1112 // Add values to incomplete PHI nodes waiting for this block to be copied.
1113 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001114 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001115 IncompletePHINodeMap[BB].clear();
1116
Johannes Doerfert275a1752015-02-24 16:16:32 +00001117 // And continue with new successors inside the region.
1118 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1119 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1120 Blocks.push_back(*SI);
Michael Kruseebffcbe2015-11-09 22:37:29 +00001121
1122 // Remember value in case it is visible after this subregion.
Michael Krused6fb6f12015-11-09 23:07:38 +00001123 if (DT.dominates(BB, ExitBB))
Michael Kruseebffcbe2015-11-09 22:37:29 +00001124 ValueMap.insert(RegionMap.begin(), RegionMap.end());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001125 }
1126
1127 // 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 +00001128 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1129 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001130 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001131 BlockMap[R->getExit()] = ExitBBCopy;
1132
Michael Krused6fb6f12015-11-09 23:07:38 +00001133 if (ExitBB == R->getExit())
1134 repairDominance(ExitBB, ExitBBCopy);
1135 else
1136 DT.changeImmediateDominator(ExitBBCopy, BlockMap.lookup(ExitBB));
Johannes Doerfert275a1752015-02-24 16:16:32 +00001137
1138 // As the block generator doesn't handle control flow we need to add the
1139 // region control flow by hand after all blocks have been copied.
1140 for (BasicBlock *BB : SeenBlocks) {
1141
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001142 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001143 TerminatorInst *TI = BB->getTerminator();
1144 if (isa<UnreachableInst>(TI)) {
1145 while (!BBCopy->empty())
1146 BBCopy->begin()->eraseFromParent();
1147 new UnreachableInst(BBCopy->getContext(), BBCopy);
1148 continue;
1149 }
1150
Johannes Doerfert275a1752015-02-24 16:16:32 +00001151 Instruction *BICopy = BBCopy->getTerminator();
1152
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001153 ValueMapT &RegionMap = RegionMaps[BBCopy];
1154 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1155
Tobias Grosser45e79442015-08-01 09:07:57 +00001156 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001157 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001158 BICopy->eraseFromParent();
1159 }
1160
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001161 // Add counting PHI nodes to all loops in the region that can be used as
1162 // replacement for SCEVs refering to the old loop.
1163 for (BasicBlock *BB : SeenBlocks) {
1164 Loop *L = LI.getLoopFor(BB);
Tobias Grosserbc29e0b2015-11-12 07:34:09 +00001165 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001166 continue;
1167
1168 BasicBlock *BBCopy = BlockMap[BB];
1169 Value *NullVal = Builder.getInt32(0);
1170 PHINode *LoopPHI =
1171 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1172 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1173 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001174 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001175 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1176
1177 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1178 if (!R->contains(PredBB))
1179 continue;
1180 if (L->contains(PredBB))
1181 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1182 else
1183 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1184 }
1185
1186 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1187 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1188 LoopPHI->addIncoming(NullVal, PredBBCopy);
1189
1190 LTS[L] = SE.getUnknown(LoopPHI);
1191 }
1192
Michael Kruse225f0d12015-10-17 21:36:00 +00001193 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001194 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001195
1196 // Write values visible to other statements.
1197 generateScalarStores(Stmt, LTS, ValueMap);
Tobias Grosser3e956022015-10-26 20:41:53 +00001198 BlockMap.clear();
1199 RegionMaps.clear();
1200 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001201}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001202
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001203PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1204 ValueMapT &BBMap, Loop *L) {
1205 ScopStmt *Stmt = MA->getStatement();
1206 Region *SubR = Stmt->getRegion();
1207 auto Incoming = MA->getIncoming();
1208
1209 PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1210 PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1211 BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1212
1213 // This can happen if the subregion is simplified after the ScopStmts
1214 // have been created; simplification happens as part of CodeGeneration.
1215 if (OrigPHI->getParent() != SubR->getExit()) {
1216 BasicBlock *FormerExit = SubR->getExitingBlock();
1217 if (FormerExit)
1218 NewSubregionExit = BlockMap.lookup(FormerExit);
1219 }
1220
1221 PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1222 "polly." + OrigPHI->getName(),
1223 NewSubregionExit->getFirstNonPHI());
1224
1225 // Add the incoming values to the PHI.
1226 for (auto &Pair : Incoming) {
1227 BasicBlock *OrigIncomingBlock = Pair.first;
1228 BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock);
1229 Builder.SetInsertPoint(NewIncomingBlock->getTerminator());
1230 assert(RegionMaps.count(NewIncomingBlock));
1231 ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock];
1232
1233 Value *OrigIncomingValue = Pair.second;
1234 Value *NewIncomingValue =
1235 getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1236 NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock);
1237 }
1238
1239 return NewPHI;
1240}
1241
1242Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1243 ValueMapT &BBMap) {
1244 ScopStmt *Stmt = MA->getStatement();
1245
1246 // TODO: Add some test cases that ensure this is really the right choice.
1247 Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1248
1249 if (MA->isAnyPHIKind()) {
1250 auto Incoming = MA->getIncoming();
1251 assert(!Incoming.empty() &&
1252 "PHI WRITEs must have originate from at least one incoming block");
1253
1254 // If there is only one incoming value, we do not need to create a PHI.
1255 if (Incoming.size() == 1) {
1256 Value *OldVal = Incoming[0].second;
1257 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1258 }
1259
1260 return buildExitPHI(MA, LTS, BBMap, L);
1261 }
1262
1263 // MK_Value accesses leaving the subregion must dominate the exit block; just
1264 // pass the copied value
1265 Value *OldVal = MA->getAccessValue();
1266 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1267}
1268
Michael Kruse225f0d12015-10-17 21:36:00 +00001269void RegionGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001270 ValueMapT &BBMap) {
Tobias Grosser75296902015-08-21 19:23:21 +00001271 assert(Stmt.getRegion() &&
1272 "Block statements need to use the generateScalarStores() "
1273 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001274
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001275 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00001276 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001277 continue;
1278
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001279 Value *NewVal = getExitScalar(MA, LTS, BBMap);
1280 Value *Address = getOrCreateAlloca(*MA);
Michael Kruseeac97262016-02-24 22:08:14 +00001281 assert((!isa<Instruction>(NewVal) ||
1282 DT.dominates(cast<Instruction>(NewVal)->getParent(),
1283 Builder.GetInsertBlock())) &&
1284 "Domination violation");
1285 assert((!isa<Instruction>(Address) ||
1286 DT.dominates(cast<Instruction>(Address)->getParent(),
1287 Builder.GetInsertBlock())) &&
1288 "Domination violation");
Michael Kruseee6a4fc2016-01-26 13:33:27 +00001289 Builder.CreateStore(NewVal, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001290 }
1291}
1292
1293void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1294 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001295 LoopToScevMapT &LTS) {
1296 Region *StmtR = Stmt.getRegion();
1297
1298 // If the incoming block was not yet copied mark this PHI as incomplete.
1299 // Once the block will be copied the incoming value will be added.
1300 BasicBlock *BBCopy = BlockMap[IncomingBB];
1301 if (!BBCopy) {
1302 assert(StmtR->contains(IncomingBB) &&
1303 "Bad incoming block for PHI in non-affine region");
1304 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1305 return;
1306 }
1307
1308 Value *OpCopy = nullptr;
1309 if (StmtR->contains(IncomingBB)) {
1310 assert(RegionMaps.count(BBCopy) &&
1311 "Incoming PHI block did not have a BBMap");
1312 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1313
1314 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001315
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001316 BasicBlock *OldBlock = Builder.GetInsertBlock();
Michael Krusedc122222015-10-19 09:19:25 +00001317 auto OldIP = Builder.GetInsertPoint();
1318 Builder.SetInsertPoint(BBCopy->getTerminator());
Johannes Doerfert2c3ffc02016-02-16 12:36:14 +00001319 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001320 Builder.SetInsertPoint(OldBlock, OldIP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001321 } else {
1322
1323 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1324 return;
1325
Tobias Grosserbc132602015-09-05 09:56:54 +00001326 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001327 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1328 BlockMap[IncomingBB]->getTerminator());
1329 }
1330
1331 assert(OpCopy && "Incoming PHI value was not copied properly");
1332 assert(BBCopy && "Incoming PHI block was not copied properly");
1333 PHICopy->addIncoming(OpCopy, BBCopy);
1334}
1335
Tobias Grosser2b809d12016-02-21 15:44:34 +00001336void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1337 ValueMapT &BBMap,
1338 LoopToScevMapT &LTS) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001339 unsigned NumIncoming = PHI->getNumIncomingValues();
1340 PHINode *PHICopy =
1341 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1342 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1343 BBMap[PHI] = PHICopy;
1344
1345 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001346 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001347}