blob: 6e01c948edba66a6fe0654e50765c485f76c8fa7 [file] [log] [blame]
Hongbin Zheng3b11a162012-04-25 13:16:49 +00001//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the BlockGenerator and VectorBlockGenerator classes,
11// which generate sequential code and vectorized code for a polyhedral
12// statement, respectively.
13//
14//===----------------------------------------------------------------------===//
15
16#include "polly/ScopInfo.h"
Hongbin Zheng8a846612012-04-25 13:18:28 +000017#include "polly/CodeGen/BlockGenerators.h"
Tobias Grosser83628182013-05-07 08:11:54 +000018#include "polly/CodeGen/CodeGeneration.h"
Johannes Doerferta63b2572014-08-03 01:51:59 +000019#include "polly/CodeGen/IslExprBuilder.h"
Tobias Grosser86bc93a2015-09-06 08:47:57 +000020#include "polly/CodeGen/RuntimeDebugBuilder.h"
Tobias Grosser637bd632013-05-07 07:31:10 +000021#include "polly/Options.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000022#include "polly/Support/GICHelper.h"
Sebastian Pop97cb8132013-03-18 20:21:13 +000023#include "polly/Support/SCEVValidator.h"
Tobias Grosserecfe21b2013-03-20 18:03:18 +000024#include "polly/Support/ScopHelper.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000025#include "llvm/Analysis/LoopInfo.h"
Johannes Doerfertf32d6512015-03-01 18:45:58 +000026#include "llvm/Analysis/RegionInfo.h"
Tobias Grossere71c6ab2012-04-27 16:36:14 +000027#include "llvm/Analysis/ScalarEvolution.h"
Tobias Grosser030237d2014-02-21 15:06:05 +000028#include "llvm/IR/IntrinsicInst.h"
Tobias Grosserc9895062015-03-10 15:24:33 +000029#include "llvm/IR/Module.h"
Hongbin Zheng3b11a162012-04-25 13:16:49 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
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 {
Tobias Grosser683b8e42014-11-30 14:33:31 +000066 if (SE.isSCEVable(Old->getType()))
Tobias Grosser369430f2013-03-22 23:42:53 +000067 if (const SCEV *Scev = SE.getSCEVAtScope(const_cast<Value *>(Old), L)) {
Tobias Grossere71c6ab2012-04-27 16:36:14 +000068 if (!isa<SCEVCouldNotCompute>(Scev)) {
Sebastian Pop637b23d2013-02-15 20:56:01 +000069 const SCEV *NewScev = apply(Scev, LTS, SE);
Johannes Doerfert09e36972015-10-07 20:17:36 +000070 ValueMapT VTV;
Sebastian Pop637b23d2013-02-15 20:56:01 +000071 VTV.insert(BBMap.begin(), BBMap.end());
72 VTV.insert(GlobalMap.begin(), GlobalMap.end());
Johannes Doerferte69e1142015-08-18 11:56:00 +000073
74 Scop &S = *Stmt.getParent();
75 const DataLayout &DL =
76 S.getRegion().getEntry()->getParent()->getParent()->getDataLayout();
77 auto IP = Builder.GetInsertPoint();
78
79 assert(IP != Builder.GetInsertBlock()->end() &&
Tobias Grosser45e79442015-08-01 09:07:57 +000080 "Only instructions can be insert points for SCEVExpander");
Johannes Doerfertc0729a32015-09-30 16:52:03 +000081 Value *Expanded = expandCodeFor(S, SE, DL, "polly", NewScev,
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +000082 Old->getType(), &*IP, &VTV);
Tobias Grossere71c6ab2012-04-27 16:36:14 +000083
84 BBMap[Old] = Expanded;
85 return Expanded;
86 }
Tobias Grosser369430f2013-03-22 23:42:53 +000087 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +000088
Tobias Grosser33cb9f92015-09-30 11:56:19 +000089 return nullptr;
90}
91
Tobias Grosser2f1acac2015-10-04 10:18:45 +000092Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
93 LoopToScevMapT &LTS, Loop *L) const {
Tobias Grosser33cb9f92015-09-30 11:56:19 +000094 // We assume constants never change.
95 // This avoids map lookups for many calls to this function.
96 if (isa<Constant>(Old))
97 return const_cast<Value *>(Old);
98
99 if (Value *New = GlobalMap.lookup(Old)) {
100 if (Value *NewRemapped = GlobalMap.lookup(New))
101 New = NewRemapped;
102 if (Old->getType()->getScalarSizeInBits() <
103 New->getType()->getScalarSizeInBits())
104 New = Builder.CreateTruncOrBitCast(New, Old->getType());
105
106 return New;
107 }
108
109 if (Value *New = BBMap.lookup(Old))
110 return New;
111
112 if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
113 return New;
114
Tobias Grosser16371ac2014-11-05 20:48:56 +0000115 // A scop-constant value defined by a global or a function parameter.
116 if (isa<GlobalValue>(Old) || isa<Argument>(Old))
117 return const_cast<Value *>(Old);
118
119 // A scop-constant value defined by an instruction executed outside the scop.
120 if (const Instruction *Inst = dyn_cast<Instruction>(Old))
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000121 if (!Stmt.getParent()->getRegion().contains(Inst->getParent()))
Tobias Grosser16371ac2014-11-05 20:48:56 +0000122 return const_cast<Value *>(Old);
123
124 // The scalar dependence is neither available nor SCEVCodegenable.
Hongbin Zheng5b463ce2013-07-25 09:12:07 +0000125 llvm_unreachable("Unexpected scalar dependence in region!");
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000126 return nullptr;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000127}
128
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000129void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000130 ValueMapT &BBMap, LoopToScevMapT &LTS) {
Tobias Grosser030237d2014-02-21 15:06:05 +0000131 // We do not generate debug intrinsics as we did not investigate how to
132 // copy them correctly. At the current state, they just crash the code
133 // generation as the meta-data operands are not correctly copied.
134 if (isa<DbgInfoIntrinsic>(Inst))
135 return;
136
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000137 Instruction *NewInst = Inst->clone();
138
139 // Replace old operands with the new ones.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000140 for (Value *OldOperand : Inst->operands()) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000141 Value *NewOperand =
142 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000143
144 if (!NewOperand) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000145 assert(!isa<StoreInst>(NewInst) &&
146 "Store instructions are always needed!");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000147 delete NewInst;
148 return;
149 }
150
151 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
152 }
153
154 Builder.Insert(NewInst);
155 BBMap[Inst] = NewInst;
156
157 if (!NewInst->getType()->isVoidTy())
158 NewInst->setName("p_" + Inst->getName());
159}
160
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000161Value *BlockGenerator::generateLocationAccessed(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000162 ScopStmt &Stmt, const Instruction *Inst, Value *Pointer, ValueMapT &BBMap,
163 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000164 const MemoryAccess &MA = Stmt.getAccessFor(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000165
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000166 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, MA.getId());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000167
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000168 if (AccessExpr) {
169 AccessExpr = isl_ast_expr_address_of(AccessExpr);
Tobias Grosser98b3ee52015-09-29 06:44:38 +0000170 auto Address = ExprBuilder->create(AccessExpr);
171
172 // Cast the address of this memory access to a pointer type that has the
173 // same element type as the original access, but uses the address space of
174 // the newly generated pointer.
175 auto OldPtrTy = MA.getAccessValue()->getType()->getPointerTo();
176 auto NewPtrTy = Address->getType();
177 OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
178 NewPtrTy->getPointerAddressSpace());
179
180 if (OldPtrTy != NewPtrTy) {
181 assert(OldPtrTy->getPointerElementType()->getPrimitiveSizeInBits() ==
182 NewPtrTy->getPointerElementType()->getPrimitiveSizeInBits() &&
183 "Pointer types to elements with different size found");
184 Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
185 }
186 return Address;
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000187 }
188
Tobias Grosserbc132602015-09-05 09:56:54 +0000189 return getNewValue(Stmt, Pointer, BBMap, LTS, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000190}
191
Tobias Grosser4d96c8d2013-03-23 01:05:07 +0000192Loop *BlockGenerator::getLoopForInst(const llvm::Instruction *Inst) {
Johannes Doerfert2ef3f4f2014-08-07 17:14:54 +0000193 return LI.getLoopFor(Inst->getParent());
Tobias Grosser369430f2013-03-22 23:42:53 +0000194}
195
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000196Value *BlockGenerator::generateScalarLoad(ScopStmt &Stmt, LoadInst *Load,
Tobias Grosserbc132602015-09-05 09:56:54 +0000197 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000198 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000199 if (Value *PreloadLoad = GlobalMap.lookup(Load))
200 return PreloadLoad;
201
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000202 auto *Pointer = Load->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000203 Value *NewPointer =
204 generateLocationAccessed(Stmt, Load, Pointer, BBMap, LTS, NewAccesses);
Johannes Doerfert87901452014-10-02 16:22:19 +0000205 Value *ScalarLoad = Builder.CreateAlignedLoad(
206 NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000207
208 if (DebugPrinting)
209 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
210 ": ", ScalarLoad, "\n");
211
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000212 return ScalarLoad;
213}
214
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000215void BlockGenerator::generateScalarStore(ScopStmt &Stmt, StoreInst *Store,
Tobias Grosserbc132602015-09-05 09:56:54 +0000216 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000217 isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000218 auto *Pointer = Store->getPointerOperand();
Tobias Grosserbc132602015-09-05 09:56:54 +0000219 Value *NewPointer =
220 generateLocationAccessed(Stmt, Store, Pointer, BBMap, LTS, NewAccesses);
221 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
222 getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000223
Tobias Grosser86bc93a2015-09-06 08:47:57 +0000224 if (DebugPrinting)
225 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
226 ": ", ValueOperand, "\n");
227
Tobias Grosserc186ac72015-08-11 08:13:15 +0000228 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000229}
230
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000231void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000232 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000233 isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000234 // Terminator instructions control the control flow. They are explicitly
235 // expressed in the clast and do not need to be copied.
236 if (Inst->isTerminator())
237 return;
238
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000239 Loop *L = getLoopForInst(Inst);
240 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
241 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
Tobias Grosseraff56c82015-09-30 13:36:54 +0000242 // Synthesizable statements will be generated on-demand.
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000243 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000244 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000245
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000246 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000247 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000248 // Compute NewLoad before its insertion in BBMap to make the insertion
249 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000250 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000251 return;
252 }
253
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000254 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000255 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000256 return;
257 }
258
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000259 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000260 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000261 return;
262 }
263
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000264 // Skip some special intrinsics for which we do not adjust the semantics to
265 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000266 if (isIgnoredIntrinsic(Inst))
267 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000268
Tobias Grosserbc132602015-09-05 09:56:54 +0000269 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000270}
271
Tobias Grosserbc132602015-09-05 09:56:54 +0000272void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000273 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000274 assert(Stmt.isBlockStmt() &&
275 "Only block statements can be copied by the block generator");
276
277 ValueMapT BBMap;
278
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000279 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000280 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000281}
282
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000283BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000284 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
285 &*Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000286 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000287 return CopyBB;
288}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000289
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000290BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000291 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000292 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000293 BasicBlock *CopyBB = splitBB(BB);
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000294 Builder.SetInsertPoint(&CopyBB->front());
Michael Kruse225f0d12015-10-17 21:36:00 +0000295 generateScalarLoads(Stmt, BBMap);
296
Tobias Grosserbc132602015-09-05 09:56:54 +0000297 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Michael Kruse225f0d12015-10-17 21:36:00 +0000298
299 // After a basic block was copied store all scalars that escape this block in
300 // their alloca.
301 generateScalarStores(Stmt, LTS, BBMap);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000302 return CopyBB;
303}
304
305void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000306 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000307 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000308 EntryBB = &CopyBB->getParent()->getEntryBlock();
309
Tobias Grosser91f5b262014-06-04 08:06:40 +0000310 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000311 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000312}
313
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000314Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
315 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000316 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000317 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000318 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000319 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000320 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000321 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000322 NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000323 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000324 }
325
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000326 auto Addr = Map[ScalarBase];
327
Tobias Grosserbc132602015-09-05 09:56:54 +0000328 if (GlobalMap.count(Addr))
329 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000330
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000331 return Addr;
332}
333
Tobias Grosserbc132602015-09-05 09:56:54 +0000334Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grosserb8d27aa2015-10-18 00:51:13 +0000335 if (Access.isPHI())
336 return getOrCreatePHIAlloca(Access.getBaseAddr());
337 else
338 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grossera4f09882015-10-17 22:16:00 +0000339}
340
341Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
342 if (Array->isPHI())
343 return getOrCreatePHIAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000344 else
Tobias Grossera4f09882015-10-17 22:16:00 +0000345 return getOrCreateScalarAlloca(Array->getBasePtr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000346}
347
Tobias Grosserbc132602015-09-05 09:56:54 +0000348Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
349 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000350}
351
Tobias Grosserbc132602015-09-05 09:56:54 +0000352Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
353 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000354}
355
Tobias Grosserbc132602015-09-05 09:56:54 +0000356void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000357 Value *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000358 // If there are escape users we get the alloca for this instruction and put it
359 // in the EscapeMap for later finalization. Lastly, if the instruction was
360 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000361 if (EscapeMap.count(Inst))
362 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000363
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000364 EscapeUserVectorTy EscapeUsers;
365 for (User *U : Inst->users()) {
366
367 // Non-instruction user will never escape.
368 Instruction *UI = dyn_cast<Instruction>(U);
369 if (!UI)
370 continue;
371
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000372 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000373 continue;
374
375 EscapeUsers.push_back(UI);
376 }
377
378 // Exit if no escape uses were found.
379 if (EscapeUsers.empty())
380 return;
381
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000382 // Get or create an escape alloca for this instruction.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000383 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000384
385 // Remember that this instruction has escape uses and the escape alloca.
386 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000387}
388
Michael Kruse225f0d12015-10-17 21:36:00 +0000389void BlockGenerator::generateScalarLoads(ScopStmt &Stmt, ValueMapT &BBMap) {
390 for (MemoryAccess *MA : Stmt) {
391 if (MA->isExplicit() || MA->isWrite())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000392 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000393
Michael Krusee2bccbb2015-09-18 19:59:43 +0000394 auto *Address = getOrCreateAlloca(*MA);
395 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000396 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000397 }
398}
399
400Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000401 ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000402 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000403 // If the value we want to store is an instruction we might have demoted it
404 // in order to make it accessible here. In such a case a reload is
405 // necessary. If it is no instruction it will always be a value that
406 // dominates the current point and we can just use it. In total there are 4
407 // options:
408 // (1) The value is no instruction ==> use the value.
409 // (2) The value is an instruction that was split out of the region prior to
410 // code generation ==> use the instruction as it dominates the region.
411 // (3) The value is an instruction:
412 // (a) The value was defined in the current block, thus a copy is in
413 // the BBMap ==> use the mapped value.
414 // (b) The value was defined in a previous block, thus we demoted it
415 // earlier ==> use the reloaded value.
416 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
417 if (!ScalarValueInst)
418 return ScalarValue;
419
420 if (!R.contains(ScalarValueInst)) {
421 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
422 return /* Case (3a) */ ScalarValueCopy;
423 else
424 return /* Case 2 */ ScalarValue;
425 }
426
427 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
428 return /* Case (3a) */ ScalarValueCopy;
429
Tobias Grosseraff56c82015-09-30 13:36:54 +0000430 if ((Stmt.isBlockStmt() &&
431 Stmt.getBasicBlock() == ScalarValueInst->getParent()) ||
432 (Stmt.isRegionStmt() && Stmt.getRegion()->contains(ScalarValueInst))) {
433 auto SynthesizedValue = trySynthesizeNewValue(
434 Stmt, ScalarValueInst, BBMap, LTS, getLoopForInst(ScalarValueInst));
435
436 if (SynthesizedValue)
437 return SynthesizedValue;
438 }
439
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000440 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000441 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000442 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000443
444 return ScalarValue;
445}
446
Michael Kruse225f0d12015-10-17 21:36:00 +0000447void BlockGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000448 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000449 const Region &R = Stmt.getParent()->getRegion();
450
Michael Kruse225f0d12015-10-17 21:36:00 +0000451 assert(Stmt.isBlockStmt() && "Region statements need to use the "
452 "generateScalarStores() function in the "
453 "RegionGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000454
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000455 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000456 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000457 continue;
458
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000459 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000460 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000461
Tobias Grosseraff56c82015-09-30 13:36:54 +0000462 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000463 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000464 }
465}
466
Tobias Grosserc0091a72015-08-30 19:19:34 +0000467void BlockGenerator::createScalarInitialization(Scop &S) {
468 Region &R = S.getRegion();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000469 // The split block __just before__ the region and optimized region.
470 BasicBlock *SplitBB = R.getEnteringBlock();
471 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
472 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
473
474 // Get the start block of the __optimized__ region.
475 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
476 if (StartBB == R.getEntry())
477 StartBB = SplitBBTerm->getSuccessor(1);
478
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000479 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000480
Tobias Grosserc0091a72015-08-30 19:19:34 +0000481 for (auto &Pair : S.arrays()) {
482 auto &Array = Pair.second;
483 if (Array->getNumberOfDimensions() != 0)
484 continue;
485 if (Array->isPHI()) {
486 // For PHI nodes, the only values we need to store are the ones that
487 // reach the PHI node from outside the region. In general there should
488 // only be one such incoming edge and this edge should enter through
489 // 'SplitBB'.
490 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000491
Tobias Grosserc0091a72015-08-30 19:19:34 +0000492 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
493 if (!R.contains(*BI) && *BI != SplitBB)
494 llvm_unreachable("Incoming edges from outside the scop should always "
495 "come from SplitBB");
496
497 int Idx = PHI->getBasicBlockIndex(SplitBB);
498 if (Idx < 0)
499 continue;
500
501 Value *ScalarValue = PHI->getIncomingValue(Idx);
502
Tobias Grosserbc132602015-09-05 09:56:54 +0000503 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000504 continue;
505 }
506
507 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
508
509 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000510 continue;
511
Johannes Doerfert717b8662015-09-08 21:44:27 +0000512 // PHI nodes that are not marked as such in their SAI object are exit PHI
513 // nodes we model as common scalars but do not need to initialize.
514 if (Inst && isa<PHINode>(Inst))
515 continue;
516
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000517 ValueMapT EmptyMap;
Tobias Grosserc0091a72015-08-30 19:19:34 +0000518 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000519 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000520 }
521}
522
523void BlockGenerator::createScalarFinalization(Region &R) {
524 // The exit block of the __unoptimized__ region.
525 BasicBlock *ExitBB = R.getExitingBlock();
526 // The merge block __just after__ the region and the optimized region.
527 BasicBlock *MergeBB = R.getExit();
528
529 // The exit block of the __optimized__ region.
530 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
531 if (OptExitBB == ExitBB)
532 OptExitBB = *(++pred_begin(MergeBB));
533
534 Builder.SetInsertPoint(OptExitBB->getTerminator());
535 for (const auto &EscapeMapping : EscapeMap) {
536 // Extract the escaping instruction and the escaping users as well as the
537 // alloca the instruction was demoted to.
538 Instruction *EscapeInst = EscapeMapping.getFirst();
539 const auto &EscapeMappingValue = EscapeMapping.getSecond();
540 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000541 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000542
543 // Reload the demoted instruction in the optimized version of the SCoP.
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000544 Value *EscapeInstReload =
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000545 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
Johannes Doerfertd8b6ad22015-10-18 12:36:42 +0000546 EscapeInstReload =
547 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000548
549 // Create the merge PHI that merges the optimized and unoptimized version.
550 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
551 EscapeInst->getName() + ".merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000552 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000553
554 // Add the respective values to the merge PHI.
555 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
556 MergePHI->addIncoming(EscapeInst, ExitBB);
557
558 // The information of scalar evolution about the escaping instruction needs
559 // to be revoked so the new merged instruction will be used.
560 if (SE.isSCEVable(EscapeInst->getType()))
561 SE.forgetValue(EscapeInst);
562
563 // Replace all uses of the demoted instruction with the merge PHI.
564 for (Instruction *EUser : EscapeUsers)
565 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
566 }
567}
568
Tobias Grosserffa24462015-10-17 08:54:13 +0000569void BlockGenerator::findOutsideUsers(Scop &S) {
570 auto &R = S.getRegion();
Tobias Grosserffa24462015-10-17 08:54:13 +0000571 for (auto &Pair : S.arrays()) {
572 auto &Array = Pair.second;
573
574 if (Array->getNumberOfDimensions() != 0)
575 continue;
576
577 if (Array->isPHI())
578 continue;
579
580 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
581
582 if (!Inst)
583 continue;
584
585 // Scop invariant hoisting moves some of the base pointers out of the scop.
586 // We can ignore these, as the invariant load hoisting already registers the
587 // relevant outside users.
588 if (!R.contains(Inst))
589 continue;
590
591 handleOutsideUsers(R, Inst, nullptr);
592 }
593}
594
Tobias Grosser27d742d2015-10-24 17:41:29 +0000595void BlockGenerator::createExitPHINodeMerges(Scop &S) {
596 if (S.hasSingleExitEdge())
597 return;
598
599 Region &R = S.getRegion();
600
601 auto *ExitBB = R.getExitingBlock();
602 auto *MergeBB = R.getExit();
603 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
604 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
605 if (OptExitBB == ExitBB)
606 OptExitBB = *(++pred_begin(MergeBB));
607
608 Builder.SetInsertPoint(OptExitBB->getTerminator());
609
610 for (auto &Pair : S.arrays()) {
611 auto &SAI = Pair.second;
612 auto *Val = SAI->getBasePtr();
613
614 PHINode *PHI = dyn_cast<PHINode>(Val);
615 if (!PHI)
616 continue;
617
Tobias Grossera3f6eda2015-10-24 19:01:09 +0000618 if (PHI->getParent() != AfterMergeBB)
Tobias Grosser27d742d2015-10-24 17:41:29 +0000619 continue;
Tobias Grosser27d742d2015-10-24 17:41:29 +0000620
621 std::string Name = PHI->getName();
622 Value *ScalarAddr = getOrCreateScalarAlloca(PHI);
623 Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
624 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
625 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
626 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +0000627 MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
Tobias Grosser27d742d2015-10-24 17:41:29 +0000628 MergePHI->addIncoming(Reload, OptExitBB);
629 MergePHI->addIncoming(OriginalValue, ExitBB);
630 int Idx = PHI->getBasicBlockIndex(MergeBB);
631 PHI->setIncomingValue(Idx, MergePHI);
632 }
633}
634
Tobias Grosserffa24462015-10-17 08:54:13 +0000635void BlockGenerator::finalizeSCoP(Scop &S) {
636 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000637 createScalarInitialization(S);
Tobias Grosser27d742d2015-10-24 17:41:29 +0000638 createExitPHINodeMerges(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000639 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000640}
641
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000642VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000643 std::vector<LoopToScevMapT> &VLTS,
644 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000645 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000646 assert(Schedule && "No statement domain provided");
647}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000648
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000649Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000650 ValueMapT &VectorMap,
651 VectorValueMapT &ScalarMaps,
652 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000653 if (Value *NewValue = VectorMap.lookup(Old))
654 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000655
656 int Width = getVectorWidth();
657
658 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
659
660 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000661 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000662 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000663 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000664
665 VectorMap[Old] = Vector;
666
667 return Vector;
668}
669
670Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
671 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
672 assert(PointerTy && "PointerType expected");
673
674 Type *ScalarType = PointerTy->getElementType();
675 VectorType *VectorType = VectorType::get(ScalarType, Width);
676
677 return PointerType::getUnqual(VectorType);
678}
679
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000680Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000681 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000682 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000683 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000684 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000685 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
686 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
687
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000688 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000689 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
690 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000691 Value *VectorPtr =
692 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
693 LoadInst *VecLoad =
694 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000695 if (!Aligned)
696 VecLoad->setAlignment(8);
697
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000698 if (NegativeStride) {
699 SmallVector<Constant *, 16> Indices;
700 for (int i = VectorWidth - 1; i >= 0; i--)
701 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
702 Constant *SV = llvm::ConstantVector::get(Indices);
703 Value *RevVecLoad = Builder.CreateShuffleVector(
704 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
705 return RevVecLoad;
706 }
707
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000708 return VecLoad;
709}
710
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000711Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000712 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000713 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000714 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000715 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000716 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
717 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000718 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
719 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000720 LoadInst *ScalarLoad =
721 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000722
723 if (!Aligned)
724 ScalarLoad->setAlignment(8);
725
Tobias Grosserc14582f2013-02-05 18:01:29 +0000726 Constant *SplatVector = Constant::getNullValue(
727 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000728
Tobias Grosserc14582f2013-02-05 18:01:29 +0000729 Value *VectorLoad = Builder.CreateShuffleVector(
730 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000731 return VectorLoad;
732}
733
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000734Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000735 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000736 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000737 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000738 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000739 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000740 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000741
742 Value *Vector = UndefValue::get(VectorType);
743
744 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000745 Value *NewPointer = generateLocationAccessed(
746 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000747 Value *ScalarLoad =
748 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
749 Vector = Builder.CreateInsertElement(
750 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000751 }
752
753 return Vector;
754}
755
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000756void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000757 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000758 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000759 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
760 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
761 Load->getName() + "_p");
762 return;
763 }
764
Tobias Grosser28736452015-03-23 07:00:36 +0000765 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000766 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000767 ScalarMaps[i][Load] =
768 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000769 return;
770 }
771
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000772 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000773
Tobias Grosser95493982014-04-18 09:46:35 +0000774 // Make sure we have scalar values available to access the pointer to
775 // the data location.
776 extractScalarValues(Load, VectorMap, ScalarMaps);
777
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000778 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000779 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000780 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000781 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000782 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000783 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000784 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000785 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000786 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000787
788 VectorMap[Load] = NewLoad;
789}
790
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000791void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000792 ValueMapT &VectorMap,
793 VectorValueMapT &ScalarMaps) {
794 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000795 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
796 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000797
798 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
799
800 const CastInst *Cast = dyn_cast<CastInst>(Inst);
801 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
802 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
803}
804
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000805void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000806 ValueMapT &VectorMap,
807 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000808 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000809 Value *OpZero = Inst->getOperand(0);
810 Value *OpOne = Inst->getOperand(1);
811
812 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000813 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
814 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000815
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000816 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000817 Inst->getName() + "p_vec");
818 VectorMap[Inst] = NewInst;
819}
820
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000821void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000822 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000823 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000824 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000825
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000826 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000827 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000828 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000829
Tobias Grosser50fd7012014-04-17 23:13:49 +0000830 // Make sure we have scalar values available to access the pointer to
831 // the data location.
832 extractScalarValues(Store, VectorMap, ScalarMaps);
833
Sebastian Popa00a0292012-12-18 07:46:06 +0000834 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000835 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000836 Value *NewPointer = generateLocationAccessed(
837 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000838
Tobias Grosserc14582f2013-02-05 18:01:29 +0000839 Value *VectorPtr =
840 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000841 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
842
843 if (!Aligned)
844 Store->setAlignment(8);
845 } else {
846 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000847 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000848 Value *NewPointer = generateLocationAccessed(
849 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000850 Builder.CreateStore(Scalar, NewPointer);
851 }
852 }
853}
854
855bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
856 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000857 for (Value *Operand : Inst->operands())
858 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000859 return true;
860 return false;
861}
862
863bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
864 ValueMapT &VectorMap,
865 VectorValueMapT &ScalarMaps) {
866 bool HasVectorOperand = false;
867 int VectorWidth = getVectorWidth();
868
Tobias Grosser91f5b262014-06-04 08:06:40 +0000869 for (Value *Operand : Inst->operands()) {
870 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000871
872 if (VecOp == VectorMap.end())
873 continue;
874
875 HasVectorOperand = true;
876 Value *NewVector = VecOp->second;
877
878 for (int i = 0; i < VectorWidth; ++i) {
879 ValueMapT &SM = ScalarMaps[i];
880
881 // If there is one scalar extracted, all scalar elements should have
882 // already been extracted by the code here. So no need to check for the
883 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000884 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000885 break;
886
Tobias Grosser91f5b262014-06-04 08:06:40 +0000887 SM[Operand] =
888 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000889 }
890 }
891
892 return HasVectorOperand;
893}
894
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000895void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000896 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000897 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000898 bool HasVectorOperand;
899 int VectorWidth = getVectorWidth();
900
901 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
902
903 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000904 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000905 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000906
907 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
908 return;
909
910 // Make the result available as vector value.
911 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
912 Value *Vector = UndefValue::get(VectorType);
913
914 for (int i = 0; i < VectorWidth; i++)
915 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
916 Builder.getInt32(i));
917
918 VectorMap[Inst] = Vector;
919}
920
Tobias Grosserbc132602015-09-05 09:56:54 +0000921int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000922
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000923void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000924 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000925 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000926 // Terminator instructions control the control flow. They are explicitly
927 // expressed in the clast and do not need to be copied.
928 if (Inst->isTerminator())
929 return;
930
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000931 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000932 return;
933
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000934 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000935 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000936 return;
937 }
938
939 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000940 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000941 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000942 return;
943 }
944
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000945 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000946 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000947 return;
948 }
949
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000950 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000951 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000952 return;
953 }
954
955 // Falltrough: We generate scalar instructions, if we don't know how to
956 // generate vector code.
957 }
958
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000959 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000960}
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 Grosser91f5b262014-06-04 08:06:40 +0000990 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000991 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000992}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000993
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000994BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
995 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000996
997 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
998 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
999
1000 if (BBCopyIDom)
1001 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1002
1003 return BBCopyIDom;
1004}
1005
Tobias Grosserbc132602015-09-05 09:56:54 +00001006void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +00001007 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +00001008 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +00001009 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +00001010
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001011 // Forget all old mappings.
1012 BlockMap.clear();
1013 RegionMaps.clear();
1014 IncompletePHINodeMap.clear();
1015
Michael Kruse225f0d12015-10-17 21:36:00 +00001016 // Collection of all values related to this subregion.
1017 ValueMapT ValueMap;
1018
Johannes Doerfert275a1752015-02-24 16:16:32 +00001019 // The region represented by the statement.
1020 Region *R = Stmt.getRegion();
1021
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001022 // Create a dedicated entry for the region where we can reload all demoted
1023 // inputs.
1024 BasicBlock *EntryBB = R->getEntry();
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001025 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1026 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001027 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001028 Builder.SetInsertPoint(&EntryBBCopy->front());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001029
Michael Kruse225f0d12015-10-17 21:36:00 +00001030 generateScalarLoads(Stmt, RegionMaps[EntryBBCopy]);
1031
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001032 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1033 if (!R->contains(*PI))
1034 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001035
1036 // Iterate over all blocks in the region in a breadth-first search.
1037 std::deque<BasicBlock *> Blocks;
1038 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001039 Blocks.push_back(EntryBB);
1040 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001041
1042 while (!Blocks.empty()) {
1043 BasicBlock *BB = Blocks.front();
1044 Blocks.pop_front();
1045
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001046 // First split the block and update dominance information.
1047 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001048 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1049
1050 // In order to remap PHI nodes we store also basic block mappings.
1051 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001052
1053 // Get the mapping for this block and initialize it with the mapping
1054 // available at its immediate dominator (in the new region).
1055 ValueMapT &RegionMap = RegionMaps[BBCopy];
Michael Kruse225f0d12015-10-17 21:36:00 +00001056 if (BBCopy != EntryBBCopy)
1057 RegionMap = RegionMaps[BBCopyIDom];
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001058
Johannes Doerfert275a1752015-02-24 16:16:32 +00001059 // Copy the block with the BlockGenerator.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001060 Builder.SetInsertPoint(&BBCopy->front());
Tobias Grosserbc132602015-09-05 09:56:54 +00001061 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001062
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001063 // In order to remap PHI nodes we store also basic block mappings.
1064 BlockMap[BB] = BBCopy;
1065
1066 // Add values to incomplete PHI nodes waiting for this block to be copied.
1067 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001068 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001069 IncompletePHINodeMap[BB].clear();
1070
Johannes Doerfert275a1752015-02-24 16:16:32 +00001071 // And continue with new successors inside the region.
1072 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1073 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1074 Blocks.push_back(*SI);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001075 }
1076
1077 // 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 +00001078 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1079 &*Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001080 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001081 BlockMap[R->getExit()] = ExitBBCopy;
1082
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001083 repairDominance(R->getExit(), ExitBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001084
Michael Kruse06514802015-11-07 00:36:50 +00001085 // Remember value in case it is visible after this subregion. Only values that
1086 // dominate the exit node can be visible.
1087 for (auto &Pair : RegionMaps)
1088 if (DT.properlyDominates(Pair.first, ExitBBCopy))
1089 ValueMap.insert(Pair.second.begin(), Pair.second.end());
1090
Johannes Doerfert275a1752015-02-24 16:16:32 +00001091 // As the block generator doesn't handle control flow we need to add the
1092 // region control flow by hand after all blocks have been copied.
1093 for (BasicBlock *BB : SeenBlocks) {
1094
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001095 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001096 TerminatorInst *TI = BB->getTerminator();
1097 if (isa<UnreachableInst>(TI)) {
1098 while (!BBCopy->empty())
1099 BBCopy->begin()->eraseFromParent();
1100 new UnreachableInst(BBCopy->getContext(), BBCopy);
1101 continue;
1102 }
1103
Johannes Doerfert275a1752015-02-24 16:16:32 +00001104 Instruction *BICopy = BBCopy->getTerminator();
1105
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001106 ValueMapT &RegionMap = RegionMaps[BBCopy];
1107 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1108
Tobias Grosser45e79442015-08-01 09:07:57 +00001109 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001110 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001111 BICopy->eraseFromParent();
1112 }
1113
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001114 // Add counting PHI nodes to all loops in the region that can be used as
1115 // replacement for SCEVs refering to the old loop.
1116 for (BasicBlock *BB : SeenBlocks) {
1117 Loop *L = LI.getLoopFor(BB);
1118 if (L == nullptr || L->getHeader() != BB)
1119 continue;
1120
1121 BasicBlock *BBCopy = BlockMap[BB];
1122 Value *NullVal = Builder.getInt32(0);
1123 PHINode *LoopPHI =
1124 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1125 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1126 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001127 LoopPHI->insertBefore(&BBCopy->front());
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001128 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1129
1130 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1131 if (!R->contains(PredBB))
1132 continue;
1133 if (L->contains(PredBB))
1134 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1135 else
1136 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1137 }
1138
1139 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1140 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1141 LoopPHI->addIncoming(NullVal, PredBBCopy);
1142
1143 LTS[L] = SE.getUnknown(LoopPHI);
1144 }
1145
Michael Kruse225f0d12015-10-17 21:36:00 +00001146 // Continue generating code in the exit block.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001147 Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
Michael Kruse225f0d12015-10-17 21:36:00 +00001148
1149 // Write values visible to other statements.
1150 generateScalarStores(Stmt, LTS, ValueMap);
Tobias Grosser3e956022015-10-26 20:41:53 +00001151 BlockMap.clear();
1152 RegionMaps.clear();
1153 IncompletePHINodeMap.clear();
Johannes Doerfert275a1752015-02-24 16:16:32 +00001154}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001155
Michael Kruse225f0d12015-10-17 21:36:00 +00001156void RegionGenerator::generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001157 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001158 const Region &R = Stmt.getParent()->getRegion();
1159
Tobias Grosser75296902015-08-21 19:23:21 +00001160 assert(Stmt.getRegion() &&
1161 "Block statements need to use the generateScalarStores() "
1162 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001163
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001164 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +00001165 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001166 continue;
1167
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001168 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001169 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001170
Michael Kruse225f0d12015-10-17 21:36:00 +00001171 // In case we add the store into an exiting block, we need to restore the
1172 // position for stores in the exit node.
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001173 BasicBlock *SavedInsertBB = Builder.GetInsertBlock();
Michael Kruse225f0d12015-10-17 21:36:00 +00001174 auto SavedInsertionPoint = Builder.GetInsertPoint();
Michael Kruse27149cf2015-11-05 16:17:17 +00001175 ValueMapT *LocalBBMap = &BBMap;
Michael Kruse225f0d12015-10-17 21:36:00 +00001176
1177 // Implicit writes induced by PHIs must be written in the incoming blocks.
1178 if (isa<TerminatorInst>(ScalarInst)) {
1179 BasicBlock *ExitingBB = ScalarInst->getParent();
1180 BasicBlock *ExitingBBCopy = BlockMap[ExitingBB];
1181 Builder.SetInsertPoint(ExitingBBCopy->getTerminator());
Michael Kruse27149cf2015-11-05 16:17:17 +00001182
1183 // For the incoming blocks, use the block's BBMap instead of the one for
1184 // the entire region.
1185 LocalBBMap = &RegionMaps[ExitingBBCopy];
Michael Kruse225f0d12015-10-17 21:36:00 +00001186 }
1187
Tobias Grosserbc132602015-09-05 09:56:54 +00001188 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001189
Michael Kruse27149cf2015-11-05 16:17:17 +00001190 Val = getNewScalarValue(Val, R, Stmt, LTS, *LocalBBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001191 Builder.CreateStore(Val, Address);
Michael Kruse225f0d12015-10-17 21:36:00 +00001192
1193 // Restore the insertion point if necessary.
1194 if (isa<TerminatorInst>(ScalarInst))
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001195 Builder.SetInsertPoint(SavedInsertBB, SavedInsertionPoint);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001196 }
1197}
1198
1199void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1200 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001201 LoopToScevMapT &LTS) {
1202 Region *StmtR = Stmt.getRegion();
1203
1204 // If the incoming block was not yet copied mark this PHI as incomplete.
1205 // Once the block will be copied the incoming value will be added.
1206 BasicBlock *BBCopy = BlockMap[IncomingBB];
1207 if (!BBCopy) {
1208 assert(StmtR->contains(IncomingBB) &&
1209 "Bad incoming block for PHI in non-affine region");
1210 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1211 return;
1212 }
1213
1214 Value *OpCopy = nullptr;
1215 if (StmtR->contains(IncomingBB)) {
1216 assert(RegionMaps.count(BBCopy) &&
1217 "Incoming PHI block did not have a BBMap");
1218 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1219
1220 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Michael Krusedc122222015-10-19 09:19:25 +00001221
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001222 BasicBlock *OldBlock = Builder.GetInsertBlock();
Michael Krusedc122222015-10-19 09:19:25 +00001223 auto OldIP = Builder.GetInsertPoint();
1224 Builder.SetInsertPoint(BBCopy->getTerminator());
Tobias Grosserbc132602015-09-05 09:56:54 +00001225 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Duncan P. N. Exon Smithb8f58b52015-11-06 22:56:54 +00001226 Builder.SetInsertPoint(OldBlock, OldIP);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001227 } else {
1228
1229 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1230 return;
1231
Tobias Grosserbc132602015-09-05 09:56:54 +00001232 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001233 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1234 BlockMap[IncomingBB]->getTerminator());
1235 }
1236
1237 assert(OpCopy && "Incoming PHI value was not copied properly");
1238 assert(BBCopy && "Incoming PHI block was not copied properly");
1239 PHICopy->addIncoming(OpCopy, BBCopy);
1240}
1241
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001242Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001243 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001244 LoopToScevMapT &LTS) {
1245 unsigned NumIncoming = PHI->getNumIncomingValues();
1246 PHINode *PHICopy =
1247 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1248 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1249 BBMap[PHI] = PHICopy;
1250
1251 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001252 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001253 return PHICopy;
1254}