blob: d8755def05d7f19afeb466a01dbfc24ffbfeadbc [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,
82 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) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000234
235 // First check for possible scalar dependences for this instruction.
Tobias Grosserbc132602015-09-05 09:56:54 +0000236 generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000237
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000238 // Terminator instructions control the control flow. They are explicitly
239 // expressed in the clast and do not need to be copied.
240 if (Inst->isTerminator())
241 return;
242
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000243 Loop *L = getLoopForInst(Inst);
244 if ((Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
245 canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion())) {
Tobias Grosseraff56c82015-09-30 13:36:54 +0000246 // Synthesizable statements will be generated on-demand.
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000247 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000248 }
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000249
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000250 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000251 Value *NewLoad = generateScalarLoad(Stmt, Load, BBMap, LTS, NewAccesses);
Sebastian Pop3d94fed2013-05-24 18:46:02 +0000252 // Compute NewLoad before its insertion in BBMap to make the insertion
253 // deterministic.
Sebastian Pop753d43f2013-05-24 17:16:02 +0000254 BBMap[Load] = NewLoad;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000255 return;
256 }
257
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000258 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000259 generateScalarStore(Stmt, Store, BBMap, LTS, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000260 return;
261 }
262
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000263 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000264 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000265 return;
266 }
267
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000268 // Skip some special intrinsics for which we do not adjust the semantics to
269 // the new schedule. All others are handled like every other instruction.
Tobias Grosser9c0ffe32015-08-30 16:57:15 +0000270 if (isIgnoredIntrinsic(Inst))
271 return;
Johannes Doerfert3f500fa2015-01-25 18:07:30 +0000272
Tobias Grosserbc132602015-09-05 09:56:54 +0000273 copyInstScalar(Stmt, Inst, BBMap, LTS);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000274}
275
Tobias Grosserbc132602015-09-05 09:56:54 +0000276void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000277 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000278 assert(Stmt.isBlockStmt() &&
279 "Only block statements can be copied by the block generator");
280
281 ValueMapT BBMap;
282
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000283 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserbc132602015-09-05 09:56:54 +0000284 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000285}
286
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000287BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
Tobias Grosserc14582f2013-02-05 18:01:29 +0000288 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000289 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000290 CopyBB->setName("polly.stmt." + BB->getName());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000291 return CopyBB;
292}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000293
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000294BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000295 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000296 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000297 BasicBlock *CopyBB = splitBB(BB);
Tobias Grosserbc132602015-09-05 09:56:54 +0000298 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000299 return CopyBB;
300}
301
302void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
Tobias Grosserbc132602015-09-05 09:56:54 +0000303 ValueMapT &BBMap, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000304 isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000305 Builder.SetInsertPoint(CopyBB->begin());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000306 EntryBB = &CopyBB->getParent()->getEntryBlock();
307
Tobias Grosser91f5b262014-06-04 08:06:40 +0000308 for (Instruction &Inst : *BB)
Tobias Grosserbc132602015-09-05 09:56:54 +0000309 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000310
311 // After a basic block was copied store all scalars that escape this block
312 // in their alloca. First the scalars that have dependences inside the SCoP,
313 // then the ones that might escape the SCoP.
Tobias Grosseraff56c82015-09-30 13:36:54 +0000314 generateScalarStores(Stmt, BB, LTS, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000315
316 const Region &R = Stmt.getParent()->getRegion();
317 for (Instruction &Inst : *BB)
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000318 handleOutsideUsers(R, &Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000319}
320
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000321Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
322 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000323 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000324 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000325 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000326 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000327 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000328 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000329 NewAddr->insertBefore(EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000330 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000331 }
332
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000333 auto Addr = Map[ScalarBase];
334
Tobias Grosserbc132602015-09-05 09:56:54 +0000335 if (GlobalMap.count(Addr))
336 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000337
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000338 return Addr;
339}
340
Tobias Grosserbc132602015-09-05 09:56:54 +0000341Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000342 if (Access.getScopArrayInfo()->isPHI())
Tobias Grosserbc132602015-09-05 09:56:54 +0000343 return getOrCreatePHIAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000344 else
Tobias Grosserbc132602015-09-05 09:56:54 +0000345 return getOrCreateScalarAlloca(Access.getBaseAddr());
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
389void BlockGenerator::generateScalarLoads(ScopStmt &Stmt,
390 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000391 ValueMapT &BBMap) {
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000392 auto *MAL = Stmt.lookupAccessesFor(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000393
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000394 if (!MAL)
395 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000396
Michael Krusee2bccbb2015-09-18 19:59:43 +0000397 for (MemoryAccess *MA : *MAL) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000398 if (MA->isExplicit() || !MA->isRead())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000399 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000400
Michael Krusee2bccbb2015-09-18 19:59:43 +0000401 auto *Address = getOrCreateAlloca(*MA);
402 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000403 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000404 }
405}
406
407Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000408 ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000409 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000410 // If the value we want to store is an instruction we might have demoted it
411 // in order to make it accessible here. In such a case a reload is
412 // necessary. If it is no instruction it will always be a value that
413 // dominates the current point and we can just use it. In total there are 4
414 // options:
415 // (1) The value is no instruction ==> use the value.
416 // (2) The value is an instruction that was split out of the region prior to
417 // code generation ==> use the instruction as it dominates the region.
418 // (3) The value is an instruction:
419 // (a) The value was defined in the current block, thus a copy is in
420 // the BBMap ==> use the mapped value.
421 // (b) The value was defined in a previous block, thus we demoted it
422 // earlier ==> use the reloaded value.
423 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
424 if (!ScalarValueInst)
425 return ScalarValue;
426
427 if (!R.contains(ScalarValueInst)) {
428 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
429 return /* Case (3a) */ ScalarValueCopy;
430 else
431 return /* Case 2 */ ScalarValue;
432 }
433
434 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
435 return /* Case (3a) */ ScalarValueCopy;
436
Tobias Grosseraff56c82015-09-30 13:36:54 +0000437 if ((Stmt.isBlockStmt() &&
438 Stmt.getBasicBlock() == ScalarValueInst->getParent()) ||
439 (Stmt.isRegionStmt() && Stmt.getRegion()->contains(ScalarValueInst))) {
440 auto SynthesizedValue = trySynthesizeNewValue(
441 Stmt, ScalarValueInst, BBMap, LTS, getLoopForInst(ScalarValueInst));
442
443 if (SynthesizedValue)
444 return SynthesizedValue;
445 }
446
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000447 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000448 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000449 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000450
451 return ScalarValue;
452}
453
454void BlockGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000455 LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000456 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000457 const Region &R = Stmt.getParent()->getRegion();
458
459 assert(Stmt.isBlockStmt() && BB == Stmt.getBasicBlock() &&
460 "Region statements need to use the generateScalarStores() "
461 "function in the RegionGenerator");
462
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000463 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000464 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000465 continue;
466
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000467 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000468 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000469
Tobias Grosseraff56c82015-09-30 13:36:54 +0000470 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000471 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000472 }
473}
474
Tobias Grosserc0091a72015-08-30 19:19:34 +0000475void BlockGenerator::createScalarInitialization(Scop &S) {
476 Region &R = S.getRegion();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000477 // The split block __just before__ the region and optimized region.
478 BasicBlock *SplitBB = R.getEnteringBlock();
479 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
480 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
481
482 // Get the start block of the __optimized__ region.
483 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
484 if (StartBB == R.getEntry())
485 StartBB = SplitBBTerm->getSuccessor(1);
486
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000487 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000488
Tobias Grosserc0091a72015-08-30 19:19:34 +0000489 for (auto &Pair : S.arrays()) {
490 auto &Array = Pair.second;
491 if (Array->getNumberOfDimensions() != 0)
492 continue;
493 if (Array->isPHI()) {
494 // For PHI nodes, the only values we need to store are the ones that
495 // reach the PHI node from outside the region. In general there should
496 // only be one such incoming edge and this edge should enter through
497 // 'SplitBB'.
498 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000499
Tobias Grosserc0091a72015-08-30 19:19:34 +0000500 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
501 if (!R.contains(*BI) && *BI != SplitBB)
502 llvm_unreachable("Incoming edges from outside the scop should always "
503 "come from SplitBB");
504
505 int Idx = PHI->getBasicBlockIndex(SplitBB);
506 if (Idx < 0)
507 continue;
508
509 Value *ScalarValue = PHI->getIncomingValue(Idx);
510
Tobias Grosserbc132602015-09-05 09:56:54 +0000511 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000512 continue;
513 }
514
515 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
516
517 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000518 continue;
519
Johannes Doerfert717b8662015-09-08 21:44:27 +0000520 // PHI nodes that are not marked as such in their SAI object are exit PHI
521 // nodes we model as common scalars but do not need to initialize.
522 if (Inst && isa<PHINode>(Inst))
523 continue;
524
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000525 ValueMapT EmptyMap;
Tobias Grosserc0091a72015-08-30 19:19:34 +0000526 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000527 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000528 }
529}
530
531void BlockGenerator::createScalarFinalization(Region &R) {
532 // The exit block of the __unoptimized__ region.
533 BasicBlock *ExitBB = R.getExitingBlock();
534 // The merge block __just after__ the region and the optimized region.
535 BasicBlock *MergeBB = R.getExit();
536
537 // The exit block of the __optimized__ region.
538 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
539 if (OptExitBB == ExitBB)
540 OptExitBB = *(++pred_begin(MergeBB));
541
542 Builder.SetInsertPoint(OptExitBB->getTerminator());
543 for (const auto &EscapeMapping : EscapeMap) {
544 // Extract the escaping instruction and the escaping users as well as the
545 // alloca the instruction was demoted to.
546 Instruction *EscapeInst = EscapeMapping.getFirst();
547 const auto &EscapeMappingValue = EscapeMapping.getSecond();
548 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000549 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000550
551 // Reload the demoted instruction in the optimized version of the SCoP.
552 Instruction *EscapeInstReload =
553 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
554
555 // Create the merge PHI that merges the optimized and unoptimized version.
556 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
557 EscapeInst->getName() + ".merge");
558 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
559
560 // Add the respective values to the merge PHI.
561 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
562 MergePHI->addIncoming(EscapeInst, ExitBB);
563
564 // The information of scalar evolution about the escaping instruction needs
565 // to be revoked so the new merged instruction will be used.
566 if (SE.isSCEVable(EscapeInst->getType()))
567 SE.forgetValue(EscapeInst);
568
569 // Replace all uses of the demoted instruction with the merge PHI.
570 for (Instruction *EUser : EscapeUsers)
571 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
572 }
573}
574
Tobias Grosser655a4572015-08-30 17:32:39 +0000575void BlockGenerator::finalizeSCoP(Scop &S) {
Johannes Doerfert717b8662015-09-08 21:44:27 +0000576
577 // Handle PHI nodes that were in the original exit and are now
578 // moved into the region exiting block.
579 if (!S.hasSingleExitEdge()) {
580 for (Instruction &I : *S.getRegion().getExitingBlock()) {
581 PHINode *PHI = dyn_cast<PHINode>(&I);
582 if (!PHI)
583 break;
584
585 assert(PHI->getNumUses() == 1);
586 assert(ScalarMap.count(PHI->user_back()));
587
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000588 handleOutsideUsers(S.getRegion(), PHI, ScalarMap[PHI->user_back()]);
Johannes Doerfert717b8662015-09-08 21:44:27 +0000589 }
590 }
591
Tobias Grosserc0091a72015-08-30 19:19:34 +0000592 createScalarInitialization(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000593 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000594}
595
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000596VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000597 std::vector<LoopToScevMapT> &VLTS,
598 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000599 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000600 assert(Schedule && "No statement domain provided");
601}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000602
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000603Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000604 ValueMapT &VectorMap,
605 VectorValueMapT &ScalarMaps,
606 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000607 if (Value *NewValue = VectorMap.lookup(Old))
608 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000609
610 int Width = getVectorWidth();
611
612 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
613
614 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000615 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000616 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000617 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000618
619 VectorMap[Old] = Vector;
620
621 return Vector;
622}
623
624Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
625 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
626 assert(PointerTy && "PointerType expected");
627
628 Type *ScalarType = PointerTy->getElementType();
629 VectorType *VectorType = VectorType::get(ScalarType, Width);
630
631 return PointerType::getUnqual(VectorType);
632}
633
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000634Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000635 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000636 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000637 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000638 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000639 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
640 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
641
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000642 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000643 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
644 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000645 Value *VectorPtr =
646 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
647 LoadInst *VecLoad =
648 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000649 if (!Aligned)
650 VecLoad->setAlignment(8);
651
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000652 if (NegativeStride) {
653 SmallVector<Constant *, 16> Indices;
654 for (int i = VectorWidth - 1; i >= 0; i--)
655 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
656 Constant *SV = llvm::ConstantVector::get(Indices);
657 Value *RevVecLoad = Builder.CreateShuffleVector(
658 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
659 return RevVecLoad;
660 }
661
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000662 return VecLoad;
663}
664
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000665Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000666 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000667 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000668 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000669 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000670 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
671 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000672 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
673 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000674 LoadInst *ScalarLoad =
675 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000676
677 if (!Aligned)
678 ScalarLoad->setAlignment(8);
679
Tobias Grosserc14582f2013-02-05 18:01:29 +0000680 Constant *SplatVector = Constant::getNullValue(
681 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000682
Tobias Grosserc14582f2013-02-05 18:01:29 +0000683 Value *VectorLoad = Builder.CreateShuffleVector(
684 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000685 return VectorLoad;
686}
687
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000688Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000689 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000690 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000691 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000692 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000693 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000694 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000695
696 Value *Vector = UndefValue::get(VectorType);
697
698 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000699 Value *NewPointer = generateLocationAccessed(
700 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000701 Value *ScalarLoad =
702 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
703 Vector = Builder.CreateInsertElement(
704 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000705 }
706
707 return Vector;
708}
709
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000710void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000711 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000712 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000713 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
714 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
715 Load->getName() + "_p");
716 return;
717 }
718
Tobias Grosser28736452015-03-23 07:00:36 +0000719 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000720 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000721 ScalarMaps[i][Load] =
722 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000723 return;
724 }
725
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000726 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000727
Tobias Grosser95493982014-04-18 09:46:35 +0000728 // Make sure we have scalar values available to access the pointer to
729 // the data location.
730 extractScalarValues(Load, VectorMap, ScalarMaps);
731
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000732 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000733 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000734 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000735 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000736 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000737 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000738 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000739 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000740 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000741
742 VectorMap[Load] = NewLoad;
743}
744
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000745void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000746 ValueMapT &VectorMap,
747 VectorValueMapT &ScalarMaps) {
748 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000749 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
750 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000751
752 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
753
754 const CastInst *Cast = dyn_cast<CastInst>(Inst);
755 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
756 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
757}
758
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000759void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000760 ValueMapT &VectorMap,
761 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000762 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000763 Value *OpZero = Inst->getOperand(0);
764 Value *OpOne = Inst->getOperand(1);
765
766 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000767 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
768 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000769
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000770 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000771 Inst->getName() + "p_vec");
772 VectorMap[Inst] = NewInst;
773}
774
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000775void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000776 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000777 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000778 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000779
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000780 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000781 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000782 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000783
Tobias Grosser50fd7012014-04-17 23:13:49 +0000784 // Make sure we have scalar values available to access the pointer to
785 // the data location.
786 extractScalarValues(Store, VectorMap, ScalarMaps);
787
Sebastian Popa00a0292012-12-18 07:46:06 +0000788 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000789 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000790 Value *NewPointer = generateLocationAccessed(
791 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000792
Tobias Grosserc14582f2013-02-05 18:01:29 +0000793 Value *VectorPtr =
794 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000795 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
796
797 if (!Aligned)
798 Store->setAlignment(8);
799 } else {
800 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000801 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000802 Value *NewPointer = generateLocationAccessed(
803 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000804 Builder.CreateStore(Scalar, NewPointer);
805 }
806 }
807}
808
809bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
810 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000811 for (Value *Operand : Inst->operands())
812 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000813 return true;
814 return false;
815}
816
817bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
818 ValueMapT &VectorMap,
819 VectorValueMapT &ScalarMaps) {
820 bool HasVectorOperand = false;
821 int VectorWidth = getVectorWidth();
822
Tobias Grosser91f5b262014-06-04 08:06:40 +0000823 for (Value *Operand : Inst->operands()) {
824 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000825
826 if (VecOp == VectorMap.end())
827 continue;
828
829 HasVectorOperand = true;
830 Value *NewVector = VecOp->second;
831
832 for (int i = 0; i < VectorWidth; ++i) {
833 ValueMapT &SM = ScalarMaps[i];
834
835 // If there is one scalar extracted, all scalar elements should have
836 // already been extracted by the code here. So no need to check for the
837 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000838 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000839 break;
840
Tobias Grosser91f5b262014-06-04 08:06:40 +0000841 SM[Operand] =
842 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000843 }
844 }
845
846 return HasVectorOperand;
847}
848
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000849void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000850 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000851 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000852 bool HasVectorOperand;
853 int VectorWidth = getVectorWidth();
854
855 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
856
857 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000858 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000859 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000860
861 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
862 return;
863
864 // Make the result available as vector value.
865 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
866 Value *Vector = UndefValue::get(VectorType);
867
868 for (int i = 0; i < VectorWidth; i++)
869 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
870 Builder.getInt32(i));
871
872 VectorMap[Inst] = Vector;
873}
874
Tobias Grosserbc132602015-09-05 09:56:54 +0000875int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000876
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000877void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000878 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000879 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000880 // Terminator instructions control the control flow. They are explicitly
881 // expressed in the clast and do not need to be copied.
882 if (Inst->isTerminator())
883 return;
884
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000885 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000886 return;
887
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000888 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000889 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000890 return;
891 }
892
893 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000894 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000895 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000896 return;
897 }
898
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000899 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000900 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000901 return;
902 }
903
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000904 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000905 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000906 return;
907 }
908
909 // Falltrough: We generate scalar instructions, if we don't know how to
910 // generate vector code.
911 }
912
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000913 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000914}
915
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000916void VectorBlockGenerator::copyStmt(
917 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000918 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
919 "the vector block generator");
920
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000921 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000922 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000923 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000924 CopyBB->setName("polly.stmt." + BB->getName());
925 Builder.SetInsertPoint(CopyBB->begin());
926
927 // Create two maps that store the mapping from the original instructions of
928 // the old basic block to their copies in the new basic block. Those maps
929 // are basic block local.
930 //
931 // As vector code generation is supported there is one map for scalar values
932 // and one for vector values.
933 //
934 // In case we just do scalar code generation, the vectorMap is not used and
935 // the scalarMap has just one dimension, which contains the mapping.
936 //
937 // In case vector code generation is done, an instruction may either appear
938 // in the vector map once (as it is calculating >vectorwidth< values at a
939 // time. Or (if the values are calculated using scalar operations), it
940 // appears once in every dimension of the scalarMap.
941 VectorValueMapT ScalarBlockMap(getVectorWidth());
942 ValueMapT VectorBlockMap;
943
Tobias Grosser91f5b262014-06-04 08:06:40 +0000944 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000945 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000946}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000947
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000948BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
949 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000950
951 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
952 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
953
954 if (BBCopyIDom)
955 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
956
957 return BBCopyIDom;
958}
959
Tobias Grosserbc132602015-09-05 09:56:54 +0000960void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000961 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000962 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +0000963 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +0000964
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000965 // Forget all old mappings.
966 BlockMap.clear();
967 RegionMaps.clear();
968 IncompletePHINodeMap.clear();
969
Johannes Doerfert275a1752015-02-24 16:16:32 +0000970 // The region represented by the statement.
971 Region *R = Stmt.getRegion();
972
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000973 // Create a dedicated entry for the region where we can reload all demoted
974 // inputs.
975 BasicBlock *EntryBB = R->getEntry();
976 BasicBlock *EntryBBCopy =
977 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
978 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
979 Builder.SetInsertPoint(EntryBBCopy->begin());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000980
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000981 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
982 if (!R->contains(*PI))
983 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +0000984
985 // Iterate over all blocks in the region in a breadth-first search.
986 std::deque<BasicBlock *> Blocks;
987 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000988 Blocks.push_back(EntryBB);
989 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +0000990
991 while (!Blocks.empty()) {
992 BasicBlock *BB = Blocks.front();
993 Blocks.pop_front();
994
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000995 // First split the block and update dominance information.
996 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000997 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
998
999 // In order to remap PHI nodes we store also basic block mappings.
1000 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001001
1002 // Get the mapping for this block and initialize it with the mapping
1003 // available at its immediate dominator (in the new region).
1004 ValueMapT &RegionMap = RegionMaps[BBCopy];
1005 RegionMap = RegionMaps[BBCopyIDom];
1006
Johannes Doerfert275a1752015-02-24 16:16:32 +00001007 // Copy the block with the BlockGenerator.
Tobias Grosserbc132602015-09-05 09:56:54 +00001008 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001009
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001010 // In order to remap PHI nodes we store also basic block mappings.
1011 BlockMap[BB] = BBCopy;
1012
1013 // Add values to incomplete PHI nodes waiting for this block to be copied.
1014 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001015 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001016 IncompletePHINodeMap[BB].clear();
1017
Johannes Doerfert275a1752015-02-24 16:16:32 +00001018 // And continue with new successors inside the region.
1019 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1020 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1021 Blocks.push_back(*SI);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001022 }
1023
1024 // Now create a new dedicated region exit block and add it to the region map.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001025 BasicBlock *ExitBBCopy =
Johannes Doerfert275a1752015-02-24 16:16:32 +00001026 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001027 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001028 BlockMap[R->getExit()] = ExitBBCopy;
1029
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001030 repairDominance(R->getExit(), ExitBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001031
1032 // As the block generator doesn't handle control flow we need to add the
1033 // region control flow by hand after all blocks have been copied.
1034 for (BasicBlock *BB : SeenBlocks) {
1035
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001036 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001037 TerminatorInst *TI = BB->getTerminator();
1038 if (isa<UnreachableInst>(TI)) {
1039 while (!BBCopy->empty())
1040 BBCopy->begin()->eraseFromParent();
1041 new UnreachableInst(BBCopy->getContext(), BBCopy);
1042 continue;
1043 }
1044
Johannes Doerfert275a1752015-02-24 16:16:32 +00001045 Instruction *BICopy = BBCopy->getTerminator();
1046
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001047 ValueMapT &RegionMap = RegionMaps[BBCopy];
1048 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1049
Tobias Grosser45e79442015-08-01 09:07:57 +00001050 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001051 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001052 BICopy->eraseFromParent();
1053 }
1054
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001055 // Add counting PHI nodes to all loops in the region that can be used as
1056 // replacement for SCEVs refering to the old loop.
1057 for (BasicBlock *BB : SeenBlocks) {
1058 Loop *L = LI.getLoopFor(BB);
1059 if (L == nullptr || L->getHeader() != BB)
1060 continue;
1061
1062 BasicBlock *BBCopy = BlockMap[BB];
1063 Value *NullVal = Builder.getInt32(0);
1064 PHINode *LoopPHI =
1065 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1066 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1067 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1068 LoopPHI->insertBefore(BBCopy->begin());
1069 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1070
1071 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1072 if (!R->contains(PredBB))
1073 continue;
1074 if (L->contains(PredBB))
1075 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1076 else
1077 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1078 }
1079
1080 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1081 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1082 LoopPHI->addIncoming(NullVal, PredBBCopy);
1083
1084 LTS[L] = SE.getUnknown(LoopPHI);
1085 }
1086
Johannes Doerfert275a1752015-02-24 16:16:32 +00001087 // Reset the old insert point for the build.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001088 Builder.SetInsertPoint(ExitBBCopy->begin());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001089}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001090
1091void RegionGenerator::generateScalarLoads(ScopStmt &Stmt,
1092 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +00001093 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001094
1095 // Inside a non-affine region PHI nodes are copied not demoted. Once the
1096 // phi is copied it will reload all inputs from outside the region, hence
1097 // we do not need to generate code for the read access of the operands of a
1098 // PHI.
1099 if (isa<PHINode>(Inst))
1100 return;
1101
Tobias Grosserbc132602015-09-05 09:56:54 +00001102 return BlockGenerator::generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001103}
1104
1105void RegionGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosseraff56c82015-09-30 13:36:54 +00001106 LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001107 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001108 const Region &R = Stmt.getParent()->getRegion();
1109
Tobias Grosser75296902015-08-21 19:23:21 +00001110 assert(Stmt.getRegion() &&
1111 "Block statements need to use the generateScalarStores() "
1112 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001113
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001114 for (MemoryAccess *MA : Stmt) {
1115
Michael Kruse8d0b7342015-09-25 21:21:00 +00001116 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001117 continue;
1118
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001119 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001120
Tobias Grosser62139132015-08-02 16:17:41 +00001121 // Only generate accesses that belong to this basic block.
1122 if (ScalarInst->getParent() != BB)
1123 continue;
1124
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001125 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001126
Tobias Grosserbc132602015-09-05 09:56:54 +00001127 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001128
Tobias Grosseraff56c82015-09-30 13:36:54 +00001129 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001130 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001131 }
1132}
1133
1134void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1135 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001136 LoopToScevMapT &LTS) {
1137 Region *StmtR = Stmt.getRegion();
1138
1139 // If the incoming block was not yet copied mark this PHI as incomplete.
1140 // Once the block will be copied the incoming value will be added.
1141 BasicBlock *BBCopy = BlockMap[IncomingBB];
1142 if (!BBCopy) {
1143 assert(StmtR->contains(IncomingBB) &&
1144 "Bad incoming block for PHI in non-affine region");
1145 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1146 return;
1147 }
1148
1149 Value *OpCopy = nullptr;
1150 if (StmtR->contains(IncomingBB)) {
1151 assert(RegionMaps.count(BBCopy) &&
1152 "Incoming PHI block did not have a BBMap");
1153 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1154
1155 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Tobias Grosserbc132602015-09-05 09:56:54 +00001156 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001157 } else {
1158
1159 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1160 return;
1161
Tobias Grosserbc132602015-09-05 09:56:54 +00001162 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001163 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1164 BlockMap[IncomingBB]->getTerminator());
1165 }
1166
1167 assert(OpCopy && "Incoming PHI value was not copied properly");
1168 assert(BBCopy && "Incoming PHI block was not copied properly");
1169 PHICopy->addIncoming(OpCopy, BBCopy);
1170}
1171
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001172Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001173 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001174 LoopToScevMapT &LTS) {
1175 unsigned NumIncoming = PHI->getNumIncomingValues();
1176 PHINode *PHICopy =
1177 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1178 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1179 BBMap[PHI] = PHICopy;
1180
1181 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001182 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001183 return PHICopy;
1184}