blob: 921b5a8458acc199c585529d54d8c08bc48258cc [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 =
152 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForInst(Inst));
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
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000171Value *BlockGenerator::generateLocationAccessed(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000172 ScopStmt &Stmt, const Instruction *Inst, Value *Pointer, ValueMapT &BBMap,
173 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser09214772015-12-15 23:49:53 +0000174 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000175
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000176 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000177
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000178 if (AccessExpr) {
179 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000180 auto Address = ExprBuilder->create(AccessExpr);
181
182 // Cast the address of this memory access to a pointer type that has the
183 // same element type as the original access, but uses the address space of
184 // the newly generated pointer.
185 auto OldPtrTy = MA.getAccessValue()->getType()->getPointerTo();
186 auto NewPtrTy = Address->getType();
187 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
188 NewPtrTy->getPointerAddressSpace());
189
190 if (OldPtrTy != NewPtrTy) {
191 assert(OldPtrTy->getPointerElementType()->getPrimitiveSizeInBits() ==
192 NewPtrTy->getPointerElementType()->getPrimitiveSizeInBits() &&
193 "Pointer types to elements with different size found");
194 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
195 }
196 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000197 }
198
Tobias Grosserbc132602015-09-05 09:56:54 +0000199 return getNewValue(Stmt, Pointer, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000200}
201
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000202Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000203 return LI.getLoopFor(Inst->getParent());
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 Grosser9646e3f2015-10-04 10:18:39 +0000212 auto *Pointer = Load->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000213 Value *NewPointer =
214 generateLocationAccessed(Stmt, Load, Pointer, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000215 Value *ScalarLoad = Builder.CreateAlignedLoad(
216 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000217
218 if (DebugPrinting)
219 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
220 ": ", ScalarLoad, "\n");
221
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000222 return ScalarLoad;
223}
224
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000225void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000226 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000227 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000228 auto *Pointer = Store->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000229 Value *NewPointer =
230 generateLocationAccessed(Stmt, Store, Pointer, BBMap, LTS, NewAccesses);
231 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
232 getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000233
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000234 if (DebugPrinting)
235 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
236 ": ", ValueOperand, "\n");
237
Tobias Grosserc186ac72015-08-11 08:13:15 +0000238 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000239}
240
Johannes Doerfert5dced262015-12-22 19:08:49 +0000241bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
242 Loop *L = getLoopForInst(Inst);
243 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
244 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion());
245}
246
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000247void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000248 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000249 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000250 // Terminator instructions control the control flow. They are explicitly
251 // expressed in the clast and do not need to be copied.
252 if (Inst->isTerminator())
253 return;
254
Johannes Doerfert5dced262015-12-22 19:08:49 +0000255 // Synthesizable statements will be generated on-demand.
256 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000257 return;
258
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000259 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000260 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000261 // Compute NewLoad before its insertion in BBMap to make the insertion
262 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000263 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000264 return;
265 }
266
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000267 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000268 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000269 return;
270 }
271
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000272 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000273 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000274 return;
275 }
276
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000277 // Skip some special intrinsics for which we do not adjust the semantics to
278 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000279 if (isIgnoredIntrinsic(Inst))
280 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000281
Tobias Grosserbc132602015-09-05 09:56:54 +0000282 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000283}
284
Tobias Grosserbc132602015-09-05 09:56:54 +0000285void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000286 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000287 assert(Stmt.isBlockStmt() &&
288 "Only block statements can be copied by the block generator");
289
290 ValueMapT BBMap;
291
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000292 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000293 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000294}
295
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000296BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000297 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
298 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000299 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000300 return CopyBB;
301}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000302
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000303BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000304 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000305 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000306 BasicBlock *CopyBB = splitBB(BB);
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000307 Builder.SetInsertPoint(&CopyBB->front());
Michael Kruse225f0d12015-10-17 21:36:00 +0000308 generateScalarLoads(Stmt, BBMap);
309
Tobias Grosserbc132602015-09-05 09:56:54 +0000310 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000311
312 // After a basic block was copied store all scalars that escape this block in
313 // their alloca.
314 generateScalarStores(Stmt, LTS, BBMap);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000315 return CopyBB;
316}
317
318void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000319 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000320 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000321 EntryBB = &CopyBB->getParent()->getEntryBlock();
322
Tobias Grosser91f5b262014-06-04 08:06:40 +0000323 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000324 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000325}
326
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000327Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
328 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000329 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000330 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000331 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000332 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000333 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000334 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000335 NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000336 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000337 }
338
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000339 auto Addr = Map[ScalarBase];
340
Tobias Grosser5c7f16b2016-01-24 14:16:59 +0000341 if (auto NewAddr = GlobalMap.lookup(Addr))
342 return NewAddr;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000343
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000344 return Addr;
345}
346
Tobias Grosserbc132602015-09-05 09:56:54 +0000347Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000348 if (Access.isPHIKind())
Tobias Grosserb8d27aa2015-10-18 00:51:13 +0000349 return getOrCreatePHIAlloca(Access.getBaseAddr());
350 else
351 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grossera4f09882015-10-17 22:16:00 +0000352}
353
354Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000355 if (Array->isPHIKind())
Tobias Grossera4f09882015-10-17 22:16:00 +0000356 return getOrCreatePHIAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000357 else
Tobias Grossera4f09882015-10-17 22:16:00 +0000358 return getOrCreateScalarAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000359}
360
Tobias Grosserbc132602015-09-05 09:56:54 +0000361Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
362 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000363}
364
Tobias Grosserbc132602015-09-05 09:56:54 +0000365Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
366 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000367}
368
Tobias Grosserbc132602015-09-05 09:56:54 +0000369void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000370 Value *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000371 // If there are escape users we get the alloca for this instruction and put it
372 // in the EscapeMap for later finalization. Lastly, if the instruction was
373 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000374 if (EscapeMap.count(Inst))
375 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000376
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000377 EscapeUserVectorTy EscapeUsers;
378 for (User *U : Inst->users()) {
379
380 // Non-instruction user will never escape.
381 Instruction *UI = dyn_cast<Instruction>(U);
382 if (!UI)
383 continue;
384
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000385 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000386 continue;
387
388 EscapeUsers.push_back(UI);
389 }
390
391 // Exit if no escape uses were found.
392 if (EscapeUsers.empty())
393 return;
394
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000395 // Get or create an escape alloca for this instruction.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000396 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000397
398 // Remember that this instruction has escape uses and the escape alloca.
399 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000400}
401
Michael Kruse225f0d12015-10-17 21:36:00 +0000402void BlockGenerator::generateScalarLoads(ScopStmt &Stmt, ValueMapT &BBMap) {
403 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000404 if (MA->isArrayKind() || MA->isWrite())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000405 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000406
Michael Krusee2bccbb2015-09-18 19:59:43 +0000407 auto *Address = getOrCreateAlloca(*MA);
408 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000409 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000410 }
411}
412
Michael Kruse225f0d12015-10-17 21:36:00 +0000413void BlockGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000414 ValueMapT &BBMap) {
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000415 Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000416
Michael Kruse225f0d12015-10-17 21:36:00 +0000417 assert(Stmt.isBlockStmt() && "Region statements need to use the "
418 "generateScalarStores() function in the "
419 "RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000420
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000421 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +0000422 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000423 continue;
424
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000425 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000426 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000427
Tobias Grosserf2cdd142016-01-26 10:01:35 +0000428 Val = getNewValue(Stmt, Val, BBMap, LTS, L);
Tobias Grosser92245222015-07-28 14:53:44 +0000429 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000430 }
431}
432
Tobias Grosserc0091a72015-08-30 19:19:34 +0000433void BlockGenerator::createScalarInitialization(Scop &S) {
434 Region &R = S.getRegion();
Johannes Doerfert188542f2015-11-09 00:21:21 +0000435 BasicBlock *ExitBB = R.getExit();
436
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000437 // The split block __just before__ the region and optimized region.
438 BasicBlock *SplitBB = R.getEnteringBlock();
439 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
440 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
441
442 // Get the start block of the __optimized__ region.
443 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
444 if (StartBB == R.getEntry())
445 StartBB = SplitBBTerm->getSuccessor(1);
446
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000447 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000448
Tobias Grosserc0091a72015-08-30 19:19:34 +0000449 for (auto &Pair : S.arrays()) {
450 auto &Array = Pair.second;
451 if (Array->getNumberOfDimensions() != 0)
452 continue;
Tobias Grossera535dff2015-12-13 19:59:01 +0000453 if (Array->isPHIKind()) {
Tobias Grosserc0091a72015-08-30 19:19:34 +0000454 // For PHI nodes, the only values we need to store are the ones that
455 // reach the PHI node from outside the region. In general there should
456 // only be one such incoming edge and this edge should enter through
457 // 'SplitBB'.
458 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000459
Tobias Grosserc0091a72015-08-30 19:19:34 +0000460 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
461 if (!R.contains(*BI) && *BI != SplitBB)
462 llvm_unreachable("Incoming edges from outside the scop should always "
463 "come from SplitBB");
464
465 int Idx = PHI->getBasicBlockIndex(SplitBB);
466 if (Idx < 0)
467 continue;
468
469 Value *ScalarValue = PHI->getIncomingValue(Idx);
470
Tobias Grosserbc132602015-09-05 09:56:54 +0000471 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000472 continue;
473 }
474
475 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
476
477 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000478 continue;
479
Johannes Doerfert188542f2015-11-09 00:21:21 +0000480 // PHI nodes that are not marked as such in their SAI object are either exit
481 // PHI nodes we model as common scalars but without initialization, or
482 // incoming phi nodes that need to be initialized. Check if the first is the
483 // case for Inst and do not create and initialize memory if so.
484 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
485 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
486 continue;
Johannes Doerfert717b8662015-09-08 21:44:27 +0000487
Tobias Grosserc0091a72015-08-30 19:19:34 +0000488 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000489 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000490 }
491}
492
493void BlockGenerator::createScalarFinalization(Region &R) {
494 // The exit block of the __unoptimized__ region.
495 BasicBlock *ExitBB = R.getExitingBlock();
496 // The merge block __just after__ the region and the optimized region.
497 BasicBlock *MergeBB = R.getExit();
498
499 // The exit block of the __optimized__ region.
500 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
501 if (OptExitBB == ExitBB)
502 OptExitBB = *(++pred_begin(MergeBB));
503
504 Builder.SetInsertPoint(OptExitBB->getTerminator());
505 for (const auto &EscapeMapping : EscapeMap) {
506 // Extract the escaping instruction and the escaping users as well as the
507 // alloca the instruction was demoted to.
508 Instruction *EscapeInst = EscapeMapping.getFirst();
509 const auto &EscapeMappingValue = EscapeMapping.getSecond();
510 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000511 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000512
513 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000514 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000515 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000516 EscapeInstReload =
517 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000518
519 // Create the merge PHI that merges the optimized and unoptimized version.
520 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
521 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000522 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000523
524 // Add the respective values to the merge PHI.
525 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
526 MergePHI->addIncoming(EscapeInst, ExitBB);
527
528 // The information of scalar evolution about the escaping instruction needs
529 // to be revoked so the new merged instruction will be used.
530 if (SE.isSCEVable(EscapeInst->getType()))
531 SE.forgetValue(EscapeInst);
532
533 // Replace all uses of the demoted instruction with the merge PHI.
534 for (Instruction *EUser : EscapeUsers)
535 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
536 }
537}
538
Tobias Grosserffa24462015-10-17 08:54:13 +0000539void BlockGenerator::findOutsideUsers(Scop &S) {
540 auto &R = S.getRegion();
Tobias Grosserffa24462015-10-17 08:54:13 +0000541 for (auto &Pair : S.arrays()) {
542 auto &Array = Pair.second;
543
544 if (Array->getNumberOfDimensions() != 0)
545 continue;
546
Tobias Grossera535dff2015-12-13 19:59:01 +0000547 if (Array->isPHIKind())
Tobias Grosserffa24462015-10-17 08:54:13 +0000548 continue;
549
550 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
551
552 if (!Inst)
553 continue;
554
555 // Scop invariant hoisting moves some of the base pointers out of the scop.
556 // We can ignore these, as the invariant load hoisting already registers the
557 // relevant outside users.
558 if (!R.contains(Inst))
559 continue;
560
561 handleOutsideUsers(R, Inst, nullptr);
562 }
563}
564
Tobias Grosser27d742d2015-10-24 17:41:29 +0000565void BlockGenerator::createExitPHINodeMerges(Scop &S) {
566 if (S.hasSingleExitEdge())
567 return;
568
569 Region &R = S.getRegion();
570
571 auto *ExitBB = R.getExitingBlock();
572 auto *MergeBB = R.getExit();
573 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
574 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
575 if (OptExitBB == ExitBB)
576 OptExitBB = *(++pred_begin(MergeBB));
577
578 Builder.SetInsertPoint(OptExitBB->getTerminator());
579
580 for (auto &Pair : S.arrays()) {
581 auto &SAI = Pair.second;
582 auto *Val = SAI->getBasePtr();
583
584 PHINode *PHI = dyn_cast<PHINode>(Val);
585 if (!PHI)
586 continue;
587
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000588 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000589 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000590
591 std::string Name = PHI->getName();
592 Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
593 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
594 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
595 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
596 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000597 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000598 MergePHI->addIncoming(Reload, OptExitBB);
599 MergePHI->addIncoming(OriginalValue, ExitBB);
600 int Idx = PHI->getBasicBlockIndex(MergeBB);
601 PHI->setIncomingValue(Idx, MergePHI);
602 }
603}
604
Tobias Grosserffa24462015-10-17 08:54:13 +0000605void BlockGenerator::finalizeSCoP(Scop &S) {
606 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000607 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000608 createExitPHINodeMerges(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000609 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000610}
611
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000612VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000613 std::vector<LoopToScevMapT> &VLTS,
614 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000615 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000616 assert(Schedule && "No statement domain provided");
617}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000618
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000619Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000620 ValueMapT &VectorMap,
621 VectorValueMapT &ScalarMaps,
622 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000623 if (Value *NewValue = VectorMap.lookup(Old))
624 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000625
626 int Width = getVectorWidth();
627
628 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
629
630 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000631 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000632 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000633 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000634
635 VectorMap[Old] = Vector;
636
637 return Vector;
638}
639
640Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
641 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
642 assert(PointerTy && "PointerType expected");
643
644 Type *ScalarType = PointerTy->getElementType();
645 VectorType *VectorType = VectorType::get(ScalarType, Width);
646
647 return PointerType::getUnqual(VectorType);
648}
649
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000650Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000651 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000652 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000653 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000654 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000655 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
656 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
657
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000658 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000659 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
660 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000661 Value *VectorPtr =
662 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
663 LoadInst *VecLoad =
664 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000665 if (!Aligned)
666 VecLoad->setAlignment(8);
667
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000668 if (NegativeStride) {
669 SmallVector<Constant *, 16> Indices;
670 for (int i = VectorWidth - 1; i >= 0; i--)
671 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
672 Constant *SV = llvm::ConstantVector::get(Indices);
673 Value *RevVecLoad = Builder.CreateShuffleVector(
674 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
675 return RevVecLoad;
676 }
677
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000678 return VecLoad;
679}
680
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000681Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000682 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000683 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000684 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000685 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000686 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
687 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000688 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
689 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000690 LoadInst *ScalarLoad =
691 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000692
693 if (!Aligned)
694 ScalarLoad->setAlignment(8);
695
Tobias Grosserc14582f2013-02-05 18:01:29 +0000696 Constant *SplatVector = Constant::getNullValue(
697 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000698
Tobias Grosserc14582f2013-02-05 18:01:29 +0000699 Value *VectorLoad = Builder.CreateShuffleVector(
700 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000701 return VectorLoad;
702}
703
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000704Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000705 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000706 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000707 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000708 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000709 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000710 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000711
712 Value *Vector = UndefValue::get(VectorType);
713
714 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000715 Value *NewPointer = generateLocationAccessed(
716 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000717 Value *ScalarLoad =
718 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
719 Vector = Builder.CreateInsertElement(
720 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000721 }
722
723 return Vector;
724}
725
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000726void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000727 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000728 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000729 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
730 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
731 Load->getName() + "_p");
732 return;
733 }
734
Tobias Grosser28736452015-03-23 07:00:36 +0000735 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000736 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000737 ScalarMaps[i][Load] =
738 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000739 return;
740 }
741
Tobias Grosser184a4922015-12-15 23:50:01 +0000742 const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000743
Tobias Grosser95493982014-04-18 09:46:35 +0000744 // Make sure we have scalar values available to access the pointer to
745 // the data location.
746 extractScalarValues(Load, VectorMap, ScalarMaps);
747
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000748 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000749 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000750 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000751 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000752 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000753 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000754 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000755 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000756 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000757
758 VectorMap[Load] = NewLoad;
759}
760
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000761void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000762 ValueMapT &VectorMap,
763 VectorValueMapT &ScalarMaps) {
764 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000765 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
766 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000767
768 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
769
770 const CastInst *Cast = dyn_cast<CastInst>(Inst);
771 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
772 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
773}
774
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000775void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000776 ValueMapT &VectorMap,
777 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000778 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000779 Value *OpZero = Inst->getOperand(0);
780 Value *OpOne = Inst->getOperand(1);
781
782 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000783 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
784 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000785
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000786 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000787 Inst->getName() + "p_vec");
788 VectorMap[Inst] = NewInst;
789}
790
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000791void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000792 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000793 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser184a4922015-12-15 23:50:01 +0000794 const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000795
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000796 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000797 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000798 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000799
Tobias Grosser50fd7012014-04-17 23:13:49 +0000800 // Make sure we have scalar values available to access the pointer to
801 // the data location.
802 extractScalarValues(Store, VectorMap, ScalarMaps);
803
Sebastian Popa00a0292012-12-18 07:46:06 +0000804 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000805 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000806 Value *NewPointer = generateLocationAccessed(
807 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000808
Tobias Grosserc14582f2013-02-05 18:01:29 +0000809 Value *VectorPtr =
810 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000811 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
812
813 if (!Aligned)
814 Store->setAlignment(8);
815 } else {
816 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000817 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000818 Value *NewPointer = generateLocationAccessed(
819 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000820 Builder.CreateStore(Scalar, NewPointer);
821 }
822 }
823}
824
825bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
826 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000827 for (Value *Operand : Inst->operands())
828 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000829 return true;
830 return false;
831}
832
833bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
834 ValueMapT &VectorMap,
835 VectorValueMapT &ScalarMaps) {
836 bool HasVectorOperand = false;
837 int VectorWidth = getVectorWidth();
838
Tobias Grosser91f5b262014-06-04 08:06:40 +0000839 for (Value *Operand : Inst->operands()) {
840 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000841
842 if (VecOp == VectorMap.end())
843 continue;
844
845 HasVectorOperand = true;
846 Value *NewVector = VecOp->second;
847
848 for (int i = 0; i < VectorWidth; ++i) {
849 ValueMapT &SM = ScalarMaps[i];
850
851 // If there is one scalar extracted, all scalar elements should have
852 // already been extracted by the code here. So no need to check for the
853 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000854 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000855 break;
856
Tobias Grosser91f5b262014-06-04 08:06:40 +0000857 SM[Operand] =
858 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000859 }
860 }
861
862 return HasVectorOperand;
863}
864
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000865void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000866 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000867 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000868 bool HasVectorOperand;
869 int VectorWidth = getVectorWidth();
870
871 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
872
873 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000874 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000875 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000876
877 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
878 return;
879
880 // Make the result available as vector value.
881 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
882 Value *Vector = UndefValue::get(VectorType);
883
884 for (int i = 0; i < VectorWidth; i++)
885 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
886 Builder.getInt32(i));
887
888 VectorMap[Inst] = Vector;
889}
890
Tobias Grosserbc132602015-09-05 09:56:54 +0000891int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000892
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000893void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000894 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000895 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000896 // Terminator instructions control the control flow. They are explicitly
897 // expressed in the clast and do not need to be copied.
898 if (Inst->isTerminator())
899 return;
900
Johannes Doerfert5dced262015-12-22 19:08:49 +0000901 if (canSyntheziseInStmt(Stmt, Inst))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000902 return;
903
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000904 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000905 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000906 return;
907 }
908
909 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000910 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000911 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000912 return;
913 }
914
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000915 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000916 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000917 return;
918 }
919
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000920 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000921 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000922 return;
923 }
924
925 // Falltrough: We generate scalar instructions, if we don't know how to
926 // generate vector code.
927 }
928
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000929 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000930}
931
Tobias Grossera69d4f02015-12-15 23:49:58 +0000932void VectorBlockGenerator::generateScalarVectorLoads(
933 ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
934 for (MemoryAccess *MA : Stmt) {
935 if (MA->isArrayKind() || MA->isWrite())
936 continue;
937
938 auto *Address = getOrCreateAlloca(*MA);
939 Type *VectorPtrType = getVectorPtrTy(Address, 1);
940 Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
941 Address->getName() + "_p_vec_p");
942 auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
943 Constant *SplatVector = Constant::getNullValue(
944 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
945
946 Value *VectorVal = Builder.CreateShuffleVector(
947 Val, Val, SplatVector, Address->getName() + "_p_splat");
948 VectorBlockMap[MA->getBaseAddr()] = VectorVal;
949 VectorVal->dump();
950 }
951}
952
953void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
954 for (MemoryAccess *MA : Stmt) {
955 if (MA->isArrayKind() || MA->isRead())
956 continue;
957
958 llvm_unreachable("Scalar stores not expected in vector loop");
959 }
960}
961
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000962void VectorBlockGenerator::copyStmt(
963 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000964 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
965 "the vector block generator");
966
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000967 BasicBlock *BB = Stmt.getBasicBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000968 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
969 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000970 CopyBB->setName("polly.stmt." + BB->getName());
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000971 Builder.SetInsertPoint(&CopyBB->front());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000972
973 // Create two maps that store the mapping from the original instructions of
974 // the old basic block to their copies in the new basic block. Those maps
975 // are basic block local.
976 //
977 // As vector code generation is supported there is one map for scalar values
978 // and one for vector values.
979 //
980 // In case we just do scalar code generation, the vectorMap is not used and
981 // the scalarMap has just one dimension, which contains the mapping.
982 //
983 // In case vector code generation is done, an instruction may either appear
984 // in the vector map once (as it is calculating >vectorwidth< values at a
985 // time. Or (if the values are calculated using scalar operations), it
986 // appears once in every dimension of the scalarMap.
987 VectorValueMapT ScalarBlockMap(getVectorWidth());
988 ValueMapT VectorBlockMap;
989
Tobias Grossera69d4f02015-12-15 23:49:58 +0000990 generateScalarVectorLoads(Stmt, VectorBlockMap);
991
Tobias Grosser91f5b262014-06-04 08:06:40 +0000992 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000993 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Tobias Grossera69d4f02015-12-15 23:49:58 +0000994
995 verifyNoScalarStores(Stmt);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000996}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000997
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000998BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
999 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001000
1001 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1002 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1003
1004 if (BBCopyIDom)
1005 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1006
1007 return BBCopyIDom;
1008}
1009
Tobias Grosserbc132602015-09-05 09:56:54 +00001010void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001011 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001012 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001013 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001014
Michael Krused6fb6f12015-11-09 23:07:38 +00001015 Scop *S = Stmt.getParent();
1016
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001017 // Forget all old mappings.
1018 BlockMap.clear();
1019 RegionMaps.clear();
1020 IncompletePHINodeMap.clear();
1021
Michael Kruse225f0d12015-10-17 21:36:00 +00001022 // Collection of all values related to this subregion.
1023 ValueMapT ValueMap;
1024
Johannes Doerfert275a1752015-02-24 16:16:32 +00001025 // The region represented by the statement.
1026 Region *R = Stmt.getRegion();
1027
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001028 // Create a dedicated entry for the region where we can reload all demoted
1029 // inputs.
1030 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001031 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1032 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001033 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001034 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001035
Michael Krusec9937392015-11-09 23:33:40 +00001036 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1037 generateScalarLoads(Stmt, EntryBBMap);
Michael Kruse225f0d12015-10-17 21:36:00 +00001038
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001039 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1040 if (!R->contains(*PI))
1041 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001042
Michael Krused6fb6f12015-11-09 23:07:38 +00001043 // Determine the original exit block of this subregion. If it the exit block
1044 // is also the scop's exit, it it has been changed to polly.merge_new_and_old.
1045 // We move one block back to find the original block. This only happens if the
1046 // scop required simplification.
1047 // If the whole scop consists of only this non-affine region, then they share
1048 // the same Region object, such that we cannot change the exit of one and not
1049 // the other.
1050 BasicBlock *ExitBB = R->getExit();
1051 if (!S->hasSingleExitEdge() && ExitBB == S->getRegion().getExit())
1052 ExitBB = *(++pred_begin(ExitBB));
1053
Johannes Doerfert275a1752015-02-24 16:16:32 +00001054 // Iterate over all blocks in the region in a breadth-first search.
1055 std::deque<BasicBlock *> Blocks;
1056 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001057 Blocks.push_back(EntryBB);
1058 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001059
1060 while (!Blocks.empty()) {
1061 BasicBlock *BB = Blocks.front();
1062 Blocks.pop_front();
1063
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001064 // First split the block and update dominance information.
1065 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001066 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1067
1068 // In order to remap PHI nodes we store also basic block mappings.
1069 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001070
Michael Krusec9937392015-11-09 23:33:40 +00001071 // Get the mapping for this block and initialize it with either the scalar
1072 // loads from the generated entering block (which dominates all blocks of
1073 // this subregion) or the maps of the immediate dominator, if part of the
1074 // subregion. The latter necessarily includes the former.
1075 ValueMapT *InitBBMap;
1076 if (BBCopyIDom) {
1077 assert(RegionMaps.count(BBCopyIDom));
1078 InitBBMap = &RegionMaps[BBCopyIDom];
1079 } else
1080 InitBBMap = &EntryBBMap;
1081 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1082 ValueMapT &RegionMap = Inserted.first->second;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001083
Johannes Doerfert275a1752015-02-24 16:16:32 +00001084 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001085 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001086 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001087
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001088 // In order to remap PHI nodes we store also basic block mappings.
1089 BlockMap[BB] = BBCopy;
1090
1091 // Add values to incomplete PHI nodes waiting for this block to be copied.
1092 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001093 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001094 IncompletePHINodeMap[BB].clear();
1095
Johannes Doerfert275a1752015-02-24 16:16:32 +00001096 // And continue with new successors inside the region.
1097 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1098 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1099 Blocks.push_back(*SI);
Michael Kruseebffcbe2015-11-09 22:37:29 +00001100
1101 // Remember value in case it is visible after this subregion.
Michael Krused6fb6f12015-11-09 23:07:38 +00001102 if (DT.dominates(BB, ExitBB))
Michael Kruseebffcbe2015-11-09 22:37:29 +00001103 ValueMap.insert(RegionMap.begin(), RegionMap.end());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001104 }
1105
1106 // 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 +00001107 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1108 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001109 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001110 BlockMap[R->getExit()] = ExitBBCopy;
1111
Michael Krused6fb6f12015-11-09 23:07:38 +00001112 if (ExitBB == R->getExit())
1113 repairDominance(ExitBB, ExitBBCopy);
1114 else
1115 DT.changeImmediateDominator(ExitBBCopy, BlockMap.lookup(ExitBB));
Johannes Doerfert275a1752015-02-24 16:16:32 +00001116
1117 // As the block generator doesn't handle control flow we need to add the
1118 // region control flow by hand after all blocks have been copied.
1119 for (BasicBlock *BB : SeenBlocks) {
1120
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001121 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001122 TerminatorInst *TI = BB->getTerminator();
1123 if (isa<UnreachableInst>(TI)) {
1124 while (!BBCopy->empty())
1125 BBCopy->begin()->eraseFromParent();
1126 new UnreachableInst(BBCopy->getContext(), BBCopy);
1127 continue;
1128 }
1129
Johannes Doerfert275a1752015-02-24 16:16:32 +00001130 Instruction *BICopy = BBCopy->getTerminator();
1131
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001132 ValueMapT &RegionMap = RegionMaps[BBCopy];
1133 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1134
Tobias Grosser45e79442015-08-01 09:07:57 +00001135 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001136 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001137 BICopy->eraseFromParent();
1138 }
1139
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001140 // Add counting PHI nodes to all loops in the region that can be used as
1141 // replacement for SCEVs refering to the old loop.
1142 for (BasicBlock *BB : SeenBlocks) {
1143 Loop *L = LI.getLoopFor(BB);
Tobias Grosserbc29e0b2015-11-12 07:34:09 +00001144 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001145 continue;
1146
1147 BasicBlock *BBCopy = BlockMap[BB];
1148 Value *NullVal = Builder.getInt32(0);
1149 PHINode *LoopPHI =
1150 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1151 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1152 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001153 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001154 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1155
1156 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1157 if (!R->contains(PredBB))
1158 continue;
1159 if (L->contains(PredBB))
1160 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1161 else
1162 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1163 }
1164
1165 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1166 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1167 LoopPHI->addIncoming(NullVal, PredBBCopy);
1168
1169 LTS[L] = SE.getUnknown(LoopPHI);
1170 }
1171
Michael Kruse225f0d12015-10-17 21:36:00 +00001172 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001173 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001174
1175 // Write values visible to other statements.
1176 generateScalarStores(Stmt, LTS, ValueMap);
Tobias Grosser3e956022015-10-26 20:41:53 +00001177 BlockMap.clear();
1178 RegionMaps.clear();
1179 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001180}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001181
Michael Kruse225f0d12015-10-17 21:36:00 +00001182void RegionGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001183 ValueMapT &BBMap) {
Tobias Grosser75296902015-08-21 19:23:21 +00001184 assert(Stmt.getRegion() &&
1185 "Block statements need to use the generateScalarStores() "
1186 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001187
Tobias Grosserf2cdd142016-01-26 10:01:35 +00001188 // TODO: Add some test cases that ensure this is really the right choice.
1189 Loop *L = LI.getLoopFor(Stmt.getRegion()->getExit());
1190
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001191 for (MemoryAccess *MA : Stmt) {
Tobias Grossera535dff2015-12-13 19:59:01 +00001192 if (MA->isArrayKind() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001193 continue;
1194
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001195 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001196 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001197
Michael Kruse225f0d12015-10-17 21:36:00 +00001198 // In case we add the store into an exiting block, we need to restore the
1199 // position for stores in the exit node.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001200 BasicBlock *SavedInsertBB = Builder.GetInsertBlock();
Michael Kruse225f0d12015-10-17 21:36:00 +00001201 auto SavedInsertionPoint = Builder.GetInsertPoint();
Michael Kruse27149cf2015-11-05 16:17:17 +00001202 ValueMapT *LocalBBMap = &BBMap;
Michael Kruse225f0d12015-10-17 21:36:00 +00001203
Tobias Grossera535dff2015-12-13 19:59:01 +00001204 // Scalar writes induced by PHIs must be written in the incoming blocks.
1205 if (MA->isPHIKind() || MA->isExitPHIKind()) {
Michael Kruse225f0d12015-10-17 21:36:00 +00001206 BasicBlock *ExitingBB = ScalarInst->getParent();
1207 BasicBlock *ExitingBBCopy = BlockMap[ExitingBB];
1208 Builder.SetInsertPoint(ExitingBBCopy->getTerminator());
Michael Kruse27149cf2015-11-05 16:17:17 +00001209
1210 // For the incoming blocks, use the block's BBMap instead of the one for
1211 // the entire region.
1212 LocalBBMap = &RegionMaps[ExitingBBCopy];
Michael Kruse225f0d12015-10-17 21:36:00 +00001213 }
1214
Tobias Grosserbc132602015-09-05 09:56:54 +00001215 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001216
Tobias Grosserf2cdd142016-01-26 10:01:35 +00001217 Val = getNewValue(Stmt, Val, *LocalBBMap, LTS, L);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001218 Builder.CreateStore(Val, Address);
Michael Kruse225f0d12015-10-17 21:36:00 +00001219
1220 // Restore the insertion point if necessary.
Tobias Grossera535dff2015-12-13 19:59:01 +00001221 if (MA->isPHIKind() || MA->isExitPHIKind())
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001222 Builder.SetInsertPoint(SavedInsertBB, SavedInsertionPoint);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001223 }
1224}
1225
1226void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1227 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001228 LoopToScevMapT &LTS) {
1229 Region *StmtR = Stmt.getRegion();
1230
1231 // If the incoming block was not yet copied mark this PHI as incomplete.
1232 // Once the block will be copied the incoming value will be added.
1233 BasicBlock *BBCopy = BlockMap[IncomingBB];
1234 if (!BBCopy) {
1235 assert(StmtR->contains(IncomingBB) &&
1236 "Bad incoming block for PHI in non-affine region");
1237 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1238 return;
1239 }
1240
1241 Value *OpCopy = nullptr;
1242 if (StmtR->contains(IncomingBB)) {
1243 assert(RegionMaps.count(BBCopy) &&
1244 "Incoming PHI block did not have a BBMap");
1245 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1246
1247 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001248
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001249 BasicBlock *OldBlock = Builder.GetInsertBlock();
Michael Krusedc122222015-10-19 09:19:25 +00001250 auto OldIP = Builder.GetInsertPoint();
1251 Builder.SetInsertPoint(BBCopy->getTerminator());
Tobias Grosserbc132602015-09-05 09:56:54 +00001252 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001253 Builder.SetInsertPoint(OldBlock, OldIP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001254 } else {
1255
1256 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1257 return;
1258
Tobias Grosserbc132602015-09-05 09:56:54 +00001259 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001260 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1261 BlockMap[IncomingBB]->getTerminator());
1262 }
1263
1264 assert(OpCopy && "Incoming PHI value was not copied properly");
1265 assert(BBCopy && "Incoming PHI block was not copied properly");
1266 PHICopy->addIncoming(OpCopy, BBCopy);
1267}
1268
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001269Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001270 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001271 LoopToScevMapT &LTS) {
1272 unsigned NumIncoming = PHI->getNumIncomingValues();
1273 PHINode *PHICopy =
1274 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1275 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1276 BBMap[PHI] = PHICopy;
1277
1278 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001279 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001280 return PHICopy;
1281}