blob: 4596ce7da1b15d3bd99ce917426a6a7f71618bc6 [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
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000317Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase,
318 ScalarAllocaMapTy &Map,
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000319 const char *NameExt) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000320 // If no alloca was found create one and insert it in the entry block.
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000321 if (!Map.count(ScalarBase)) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000322 auto *Ty = ScalarBase->getType();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000323 auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000324 EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
Tobias Grosserb09455d2015-09-18 06:01:11 +0000325 NewAddr->insertBefore(EntryBB->getFirstInsertionPt());
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000326 Map[ScalarBase] = NewAddr;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000327 }
328
Tobias Grossere9cb5a02015-10-03 17:19:49 +0000329 auto Addr = Map[ScalarBase];
330
Tobias Grosserbc132602015-09-05 09:56:54 +0000331 if (GlobalMap.count(Addr))
332 return GlobalMap[Addr];
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000333
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000334 return Addr;
335}
336
Tobias Grosserbc132602015-09-05 09:56:54 +0000337Value *BlockGenerator::getOrCreateAlloca(MemoryAccess &Access) {
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000338 if (Access.getScopArrayInfo()->isPHI())
Tobias Grosserbc132602015-09-05 09:56:54 +0000339 return getOrCreatePHIAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000340 else
Tobias Grosserbc132602015-09-05 09:56:54 +0000341 return getOrCreateScalarAlloca(Access.getBaseAddr());
Tobias Grosserf8d55f72015-08-29 18:12:03 +0000342}
343
Tobias Grosserbc132602015-09-05 09:56:54 +0000344Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) {
345 return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000346}
347
Tobias Grosserbc132602015-09-05 09:56:54 +0000348Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) {
349 return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops");
Tobias Grosserb79a67d2015-08-28 08:23:35 +0000350}
351
Tobias Grosserbc132602015-09-05 09:56:54 +0000352void BlockGenerator::handleOutsideUsers(const Region &R, Instruction *Inst,
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000353 Value *Address) {
Tobias Grosser29854002015-08-30 15:03:59 +0000354 // If there are escape users we get the alloca for this instruction and put it
355 // in the EscapeMap for later finalization. Lastly, if the instruction was
356 // copied multiple times we already did this and can exit.
Michael Kruseacb6ade2015-08-18 17:25:48 +0000357 if (EscapeMap.count(Inst))
358 return;
Johannes Doerferte69e1142015-08-18 11:56:00 +0000359
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000360 EscapeUserVectorTy EscapeUsers;
361 for (User *U : Inst->users()) {
362
363 // Non-instruction user will never escape.
364 Instruction *UI = dyn_cast<Instruction>(U);
365 if (!UI)
366 continue;
367
Johannes Doerfertddb83d02015-08-16 08:35:40 +0000368 if (R.contains(UI))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000369 continue;
370
371 EscapeUsers.push_back(UI);
372 }
373
374 // Exit if no escape uses were found.
375 if (EscapeUsers.empty())
376 return;
377
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000378 // Get or create an escape alloca for this instruction.
Tobias Grosserb09455d2015-09-18 06:01:11 +0000379 auto *ScalarAddr = Address ? Address : getOrCreateScalarAlloca(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000380
381 // Remember that this instruction has escape uses and the escape alloca.
382 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000383}
384
385void BlockGenerator::generateScalarLoads(ScopStmt &Stmt,
386 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +0000387 ValueMapT &BBMap) {
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000388 auto *MAL = Stmt.lookupAccessesFor(Inst);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000389
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000390 if (!MAL)
391 return;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000392
Michael Krusee2bccbb2015-09-18 19:59:43 +0000393 for (MemoryAccess *MA : *MAL) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000394 if (MA->isExplicit() || !MA->isRead())
Tobias Grosserd4dd6ec2015-07-27 17:57:58 +0000395 continue;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000396
Michael Krusee2bccbb2015-09-18 19:59:43 +0000397 auto *Address = getOrCreateAlloca(*MA);
398 BBMap[MA->getBaseAddr()] =
Tobias Grosser2fc50df2015-08-30 19:51:01 +0000399 Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000400 }
401}
402
403Value *BlockGenerator::getNewScalarValue(Value *ScalarValue, const Region &R,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000404 ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000405 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000406 // If the value we want to store is an instruction we might have demoted it
407 // in order to make it accessible here. In such a case a reload is
408 // necessary. If it is no instruction it will always be a value that
409 // dominates the current point and we can just use it. In total there are 4
410 // options:
411 // (1) The value is no instruction ==> use the value.
412 // (2) The value is an instruction that was split out of the region prior to
413 // code generation ==> use the instruction as it dominates the region.
414 // (3) The value is an instruction:
415 // (a) The value was defined in the current block, thus a copy is in
416 // the BBMap ==> use the mapped value.
417 // (b) The value was defined in a previous block, thus we demoted it
418 // earlier ==> use the reloaded value.
419 Instruction *ScalarValueInst = dyn_cast<Instruction>(ScalarValue);
420 if (!ScalarValueInst)
421 return ScalarValue;
422
423 if (!R.contains(ScalarValueInst)) {
424 if (Value *ScalarValueCopy = GlobalMap.lookup(ScalarValueInst))
425 return /* Case (3a) */ ScalarValueCopy;
426 else
427 return /* Case 2 */ ScalarValue;
428 }
429
430 if (Value *ScalarValueCopy = BBMap.lookup(ScalarValueInst))
431 return /* Case (3a) */ ScalarValueCopy;
432
Tobias Grosseraff56c82015-09-30 13:36:54 +0000433 if ((Stmt.isBlockStmt() &&
434 Stmt.getBasicBlock() == ScalarValueInst->getParent()) ||
435 (Stmt.isRegionStmt() && Stmt.getRegion()->contains(ScalarValueInst))) {
436 auto SynthesizedValue = trySynthesizeNewValue(
437 Stmt, ScalarValueInst, BBMap, LTS, getLoopForInst(ScalarValueInst));
438
439 if (SynthesizedValue)
440 return SynthesizedValue;
441 }
442
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000443 // Case (3b)
Tobias Grosserbc132602015-09-05 09:56:54 +0000444 Value *Address = getOrCreateScalarAlloca(ScalarValueInst);
Tobias Grosserb649e262015-08-30 17:37:55 +0000445 ScalarValue = Builder.CreateLoad(Address, Address->getName() + ".reload");
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000446
447 return ScalarValue;
448}
449
450void BlockGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosseraff56c82015-09-30 13:36:54 +0000451 LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +0000452 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000453 const Region &R = Stmt.getParent()->getRegion();
454
455 assert(Stmt.isBlockStmt() && BB == Stmt.getBasicBlock() &&
456 "Region statements need to use the generateScalarStores() "
457 "function in the RegionGenerator");
458
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000459 for (MemoryAccess *MA : Stmt) {
Michael Kruse8d0b7342015-09-25 21:21:00 +0000460 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000461 continue;
462
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000463 Value *Val = MA->getAccessValue();
Tobias Grosserbc132602015-09-05 09:56:54 +0000464 auto *Address = getOrCreateAlloca(*MA);
Johannes Doerfertd86f2152015-08-17 10:58:17 +0000465
Tobias Grosseraff56c82015-09-30 13:36:54 +0000466 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosser92245222015-07-28 14:53:44 +0000467 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000468 }
469}
470
Tobias Grosserc0091a72015-08-30 19:19:34 +0000471void BlockGenerator::createScalarInitialization(Scop &S) {
472 Region &R = S.getRegion();
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000473 // The split block __just before__ the region and optimized region.
474 BasicBlock *SplitBB = R.getEnteringBlock();
475 BranchInst *SplitBBTerm = cast<BranchInst>(SplitBB->getTerminator());
476 assert(SplitBBTerm->getNumSuccessors() == 2 && "Bad region entering block!");
477
478 // Get the start block of the __optimized__ region.
479 BasicBlock *StartBB = SplitBBTerm->getSuccessor(0);
480 if (StartBB == R.getEntry())
481 StartBB = SplitBBTerm->getSuccessor(1);
482
Johannes Doerfertfb19dd62015-09-26 20:57:59 +0000483 Builder.SetInsertPoint(StartBB->getTerminator());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000484
Tobias Grosserc0091a72015-08-30 19:19:34 +0000485 for (auto &Pair : S.arrays()) {
486 auto &Array = Pair.second;
487 if (Array->getNumberOfDimensions() != 0)
488 continue;
489 if (Array->isPHI()) {
490 // For PHI nodes, the only values we need to store are the ones that
491 // reach the PHI node from outside the region. In general there should
492 // only be one such incoming edge and this edge should enter through
493 // 'SplitBB'.
494 auto PHI = cast<PHINode>(Array->getBasePtr());
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000495
Tobias Grosserc0091a72015-08-30 19:19:34 +0000496 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
497 if (!R.contains(*BI) && *BI != SplitBB)
498 llvm_unreachable("Incoming edges from outside the scop should always "
499 "come from SplitBB");
500
501 int Idx = PHI->getBasicBlockIndex(SplitBB);
502 if (Idx < 0)
503 continue;
504
505 Value *ScalarValue = PHI->getIncomingValue(Idx);
506
Tobias Grosserbc132602015-09-05 09:56:54 +0000507 Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI));
Tobias Grosserc0091a72015-08-30 19:19:34 +0000508 continue;
509 }
510
511 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
512
513 if (Inst && R.contains(Inst))
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000514 continue;
515
Johannes Doerfert717b8662015-09-08 21:44:27 +0000516 // PHI nodes that are not marked as such in their SAI object are exit PHI
517 // nodes we model as common scalars but do not need to initialize.
518 if (Inst && isa<PHINode>(Inst))
519 continue;
520
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000521 ValueMapT EmptyMap;
Tobias Grosserc0091a72015-08-30 19:19:34 +0000522 Builder.CreateStore(Array->getBasePtr(),
Tobias Grosserbc132602015-09-05 09:56:54 +0000523 getOrCreateScalarAlloca(Array->getBasePtr()));
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000524 }
525}
526
527void BlockGenerator::createScalarFinalization(Region &R) {
528 // The exit block of the __unoptimized__ region.
529 BasicBlock *ExitBB = R.getExitingBlock();
530 // The merge block __just after__ the region and the optimized region.
531 BasicBlock *MergeBB = R.getExit();
532
533 // The exit block of the __optimized__ region.
534 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
535 if (OptExitBB == ExitBB)
536 OptExitBB = *(++pred_begin(MergeBB));
537
538 Builder.SetInsertPoint(OptExitBB->getTerminator());
539 for (const auto &EscapeMapping : EscapeMap) {
540 // Extract the escaping instruction and the escaping users as well as the
541 // alloca the instruction was demoted to.
542 Instruction *EscapeInst = EscapeMapping.getFirst();
543 const auto &EscapeMappingValue = EscapeMapping.getSecond();
544 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
Tobias Grosser64c0ff42015-08-31 05:52:24 +0000545 Value *ScalarAddr = EscapeMappingValue.first;
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000546
547 // Reload the demoted instruction in the optimized version of the SCoP.
548 Instruction *EscapeInstReload =
549 Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
550
551 // Create the merge PHI that merges the optimized and unoptimized version.
552 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
553 EscapeInst->getName() + ".merge");
554 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
555
556 // Add the respective values to the merge PHI.
557 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
558 MergePHI->addIncoming(EscapeInst, ExitBB);
559
560 // The information of scalar evolution about the escaping instruction needs
561 // to be revoked so the new merged instruction will be used.
562 if (SE.isSCEVable(EscapeInst->getType()))
563 SE.forgetValue(EscapeInst);
564
565 // Replace all uses of the demoted instruction with the merge PHI.
566 for (Instruction *EUser : EscapeUsers)
567 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
568 }
569}
570
Tobias Grosserffa24462015-10-17 08:54:13 +0000571void BlockGenerator::findOutsideUsers(Scop &S) {
572 auto &R = S.getRegion();
Johannes Doerfert717b8662015-09-08 21:44:27 +0000573
574 // Handle PHI nodes that were in the original exit and are now
575 // moved into the region exiting block.
576 if (!S.hasSingleExitEdge()) {
577 for (Instruction &I : *S.getRegion().getExitingBlock()) {
578 PHINode *PHI = dyn_cast<PHINode>(&I);
579 if (!PHI)
580 break;
581
582 assert(PHI->getNumUses() == 1);
583 assert(ScalarMap.count(PHI->user_back()));
584
Tobias Grosser26e59ee2015-10-17 08:25:54 +0000585 handleOutsideUsers(S.getRegion(), PHI, ScalarMap[PHI->user_back()]);
Johannes Doerfert717b8662015-09-08 21:44:27 +0000586 }
587 }
588
Tobias Grosserffa24462015-10-17 08:54:13 +0000589 for (auto &Pair : S.arrays()) {
590 auto &Array = Pair.second;
591
592 if (Array->getNumberOfDimensions() != 0)
593 continue;
594
595 if (Array->isPHI())
596 continue;
597
598 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
599
600 if (!Inst)
601 continue;
602
603 // Scop invariant hoisting moves some of the base pointers out of the scop.
604 // We can ignore these, as the invariant load hoisting already registers the
605 // relevant outside users.
606 if (!R.contains(Inst))
607 continue;
608
609 handleOutsideUsers(R, Inst, nullptr);
610 }
611}
612
613void BlockGenerator::finalizeSCoP(Scop &S) {
614 findOutsideUsers(S);
Tobias Grosserc0091a72015-08-30 19:19:34 +0000615 createScalarInitialization(S);
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000616 createScalarFinalization(S.getRegion());
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000617}
618
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000619VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000620 std::vector<LoopToScevMapT> &VLTS,
621 isl_map *Schedule)
Tobias Grosserbc132602015-09-05 09:56:54 +0000622 : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
Sebastian Popa00a0292012-12-18 07:46:06 +0000623 assert(Schedule && "No statement domain provided");
624}
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000625
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000626Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
Tobias Grossere602a072013-05-07 07:30:56 +0000627 ValueMapT &VectorMap,
628 VectorValueMapT &ScalarMaps,
629 Loop *L) {
Hongbin Zhengfe11e282013-06-29 13:22:15 +0000630 if (Value *NewValue = VectorMap.lookup(Old))
631 return NewValue;
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000632
633 int Width = getVectorWidth();
634
635 Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
636
637 for (int Lane = 0; Lane < Width; Lane++)
Tobias Grosserc14582f2013-02-05 18:01:29 +0000638 Vector = Builder.CreateInsertElement(
Tobias Grosserbc132602015-09-05 09:56:54 +0000639 Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
Tobias Grosser7242ad92013-02-22 08:07:06 +0000640 Builder.getInt32(Lane));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000641
642 VectorMap[Old] = Vector;
643
644 return Vector;
645}
646
647Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
648 PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
649 assert(PointerTy && "PointerType expected");
650
651 Type *ScalarType = PointerTy->getElementType();
652 VectorType *VectorType = VectorType::get(ScalarType, Width);
653
654 return PointerType::getUnqual(VectorType);
655}
656
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000657Value *VectorBlockGenerator::generateStrideOneLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000658 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000659 __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000660 unsigned VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000661 auto *Pointer = Load->getPointerOperand();
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000662 Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
663 unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
664
Tobias Grosser5a56cbf2014-04-16 07:33:47 +0000665 Value *NewPointer = nullptr;
Tobias Grosserbc132602015-09-05 09:56:54 +0000666 NewPointer = generateLocationAccessed(Stmt, Load, Pointer, ScalarMaps[Offset],
667 VLTS[Offset], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000668 Value *VectorPtr =
669 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
670 LoadInst *VecLoad =
671 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000672 if (!Aligned)
673 VecLoad->setAlignment(8);
674
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000675 if (NegativeStride) {
676 SmallVector<Constant *, 16> Indices;
677 for (int i = VectorWidth - 1; i >= 0; i--)
678 Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
679 Constant *SV = llvm::ConstantVector::get(Indices);
680 Value *RevVecLoad = Builder.CreateShuffleVector(
681 VecLoad, VecLoad, SV, Load->getName() + "_reverse");
682 return RevVecLoad;
683 }
684
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000685 return VecLoad;
686}
687
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000688Value *VectorBlockGenerator::generateStrideZeroLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000689 ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000690 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000691 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000692 Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
Tobias Grosserbc132602015-09-05 09:56:54 +0000693 Value *NewPointer = generateLocationAccessed(Stmt, Load, Pointer, BBMap,
694 VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000695 Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
696 Load->getName() + "_p_vec_p");
Tobias Grosserc14582f2013-02-05 18:01:29 +0000697 LoadInst *ScalarLoad =
698 Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000699
700 if (!Aligned)
701 ScalarLoad->setAlignment(8);
702
Tobias Grosserc14582f2013-02-05 18:01:29 +0000703 Constant *SplatVector = Constant::getNullValue(
704 VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000705
Tobias Grosserc14582f2013-02-05 18:01:29 +0000706 Value *VectorLoad = Builder.CreateShuffleVector(
707 ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000708 return VectorLoad;
709}
710
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000711Value *VectorBlockGenerator::generateUnknownStrideLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000712 ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
Johannes Doerfert09e36972015-10-07 20:17:36 +0000713 __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000714 int VectorWidth = getVectorWidth();
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000715 auto *Pointer = Load->getPointerOperand();
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000716 VectorType *VectorType = VectorType::get(
Tobias Grosserc14582f2013-02-05 18:01:29 +0000717 dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000718
719 Value *Vector = UndefValue::get(VectorType);
720
721 for (int i = 0; i < VectorWidth; i++) {
Tobias Grosserbc132602015-09-05 09:56:54 +0000722 Value *NewPointer = generateLocationAccessed(
723 Stmt, Load, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Tobias Grosserc14582f2013-02-05 18:01:29 +0000724 Value *ScalarLoad =
725 Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
726 Vector = Builder.CreateInsertElement(
727 Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000728 }
729
730 return Vector;
731}
732
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000733void VectorBlockGenerator::generateLoad(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000734 ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000735 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertc1db67e2015-09-29 23:47:21 +0000736 if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
737 VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
738 Load->getName() + "_p");
739 return;
740 }
741
Tobias Grosser28736452015-03-23 07:00:36 +0000742 if (!VectorType::isValidElementType(Load->getType())) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000743 for (int i = 0; i < getVectorWidth(); i++)
Tobias Grosserbc132602015-09-05 09:56:54 +0000744 ScalarMaps[i][Load] =
745 generateScalarLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000746 return;
747 }
748
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000749 const MemoryAccess &Access = Stmt.getAccessFor(Load);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000750
Tobias Grosser95493982014-04-18 09:46:35 +0000751 // Make sure we have scalar values available to access the pointer to
752 // the data location.
753 extractScalarValues(Load, VectorMap, ScalarMaps);
754
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000755 Value *NewLoad;
Sebastian Popa00a0292012-12-18 07:46:06 +0000756 if (Access.isStrideZero(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000757 NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
Sebastian Popa00a0292012-12-18 07:46:06 +0000758 else if (Access.isStrideOne(isl_map_copy(Schedule)))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000759 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
Tobias Grosser0dd463f2014-03-19 19:27:24 +0000760 else if (Access.isStrideX(isl_map_copy(Schedule), -1))
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000761 NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000762 else
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000763 NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000764
765 VectorMap[Load] = NewLoad;
766}
767
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000768void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000769 ValueMapT &VectorMap,
770 VectorValueMapT &ScalarMaps) {
771 int VectorWidth = getVectorWidth();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000772 Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
773 ScalarMaps, getLoopForInst(Inst));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000774
775 assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
776
777 const CastInst *Cast = dyn_cast<CastInst>(Inst);
778 VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
779 VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
780}
781
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000782void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000783 ValueMapT &VectorMap,
784 VectorValueMapT &ScalarMaps) {
Tobias Grosser369430f2013-03-22 23:42:53 +0000785 Loop *L = getLoopForInst(Inst);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000786 Value *OpZero = Inst->getOperand(0);
787 Value *OpOne = Inst->getOperand(1);
788
789 Value *NewOpZero, *NewOpOne;
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000790 NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
791 NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000792
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000793 Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000794 Inst->getName() + "p_vec");
795 VectorMap[Inst] = NewInst;
796}
797
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000798void VectorBlockGenerator::copyStore(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000799 ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000800 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000801 const MemoryAccess &Access = Stmt.getAccessFor(Store);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000802
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000803 auto *Pointer = Store->getPointerOperand();
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000804 Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
Tobias Grosser369430f2013-03-22 23:42:53 +0000805 ScalarMaps, getLoopForInst(Store));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000806
Tobias Grosser50fd7012014-04-17 23:13:49 +0000807 // Make sure we have scalar values available to access the pointer to
808 // the data location.
809 extractScalarValues(Store, VectorMap, ScalarMaps);
810
Sebastian Popa00a0292012-12-18 07:46:06 +0000811 if (Access.isStrideOne(isl_map_copy(Schedule))) {
Johannes Doerfert1947f862014-10-08 20:18:32 +0000812 Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
Tobias Grosserbc132602015-09-05 09:56:54 +0000813 Value *NewPointer = generateLocationAccessed(
814 Stmt, Store, Pointer, ScalarMaps[0], VLTS[0], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000815
Tobias Grosserc14582f2013-02-05 18:01:29 +0000816 Value *VectorPtr =
817 Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000818 StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
819
820 if (!Aligned)
821 Store->setAlignment(8);
822 } else {
823 for (unsigned i = 0; i < ScalarMaps.size(); i++) {
Tobias Grosser1bb59b02012-12-29 23:47:38 +0000824 Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
Tobias Grosserbc132602015-09-05 09:56:54 +0000825 Value *NewPointer = generateLocationAccessed(
826 Stmt, Store, Pointer, ScalarMaps[i], VLTS[i], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000827 Builder.CreateStore(Scalar, NewPointer);
828 }
829 }
830}
831
832bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
833 ValueMapT &VectorMap) {
Tobias Grosser91f5b262014-06-04 08:06:40 +0000834 for (Value *Operand : Inst->operands())
835 if (VectorMap.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000836 return true;
837 return false;
838}
839
840bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
841 ValueMapT &VectorMap,
842 VectorValueMapT &ScalarMaps) {
843 bool HasVectorOperand = false;
844 int VectorWidth = getVectorWidth();
845
Tobias Grosser91f5b262014-06-04 08:06:40 +0000846 for (Value *Operand : Inst->operands()) {
847 ValueMapT::iterator VecOp = VectorMap.find(Operand);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000848
849 if (VecOp == VectorMap.end())
850 continue;
851
852 HasVectorOperand = true;
853 Value *NewVector = VecOp->second;
854
855 for (int i = 0; i < VectorWidth; ++i) {
856 ValueMapT &SM = ScalarMaps[i];
857
858 // If there is one scalar extracted, all scalar elements should have
859 // already been extracted by the code here. So no need to check for the
860 // existance of all of them.
Tobias Grosser91f5b262014-06-04 08:06:40 +0000861 if (SM.count(Operand))
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000862 break;
863
Tobias Grosser91f5b262014-06-04 08:06:40 +0000864 SM[Operand] =
865 Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000866 }
867 }
868
869 return HasVectorOperand;
870}
871
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000872void VectorBlockGenerator::copyInstScalarized(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000873 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000874 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000875 bool HasVectorOperand;
876 int VectorWidth = getVectorWidth();
877
878 HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
879
880 for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000881 BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
Tobias Grosserbc132602015-09-05 09:56:54 +0000882 VLTS[VectorLane], NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000883
884 if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
885 return;
886
887 // Make the result available as vector value.
888 VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
889 Value *Vector = UndefValue::get(VectorType);
890
891 for (int i = 0; i < VectorWidth; i++)
892 Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
893 Builder.getInt32(i));
894
895 VectorMap[Inst] = Vector;
896}
897
Tobias Grosserbc132602015-09-05 09:56:54 +0000898int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000899
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000900void VectorBlockGenerator::copyInstruction(
Tobias Grosser2f1acac2015-10-04 10:18:45 +0000901 ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000902 VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000903 // Terminator instructions control the control flow. They are explicitly
904 // expressed in the clast and do not need to be copied.
905 if (Inst->isTerminator())
906 return;
907
Johannes Doerfert1ef52332015-02-08 20:50:42 +0000908 if (canSynthesize(Inst, &LI, &SE, &Stmt.getParent()->getRegion()))
Tobias Grossere71c6ab2012-04-27 16:36:14 +0000909 return;
910
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000911 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000912 generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000913 return;
914 }
915
916 if (hasVectorOperands(Inst, VectorMap)) {
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000917 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000918 copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000919 return;
920 }
921
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000922 if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000923 copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000924 return;
925 }
926
Tobias Grosser9646e3f2015-10-04 10:18:39 +0000927 if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000928 copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000929 return;
930 }
931
932 // Falltrough: We generate scalar instructions, if we don't know how to
933 // generate vector code.
934 }
935
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000936 copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000937}
938
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000939void VectorBlockGenerator::copyStmt(
940 ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000941 assert(Stmt.isBlockStmt() && "TODO: Only block statements can be copied by "
942 "the vector block generator");
943
Johannes Doerfertbe9c9112015-02-06 21:39:31 +0000944 BasicBlock *BB = Stmt.getBasicBlock();
Tobias Grosserc14582f2013-02-05 18:01:29 +0000945 BasicBlock *CopyBB =
Johannes Doerfertb4f08eb2015-02-23 13:51:35 +0000946 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000947 CopyBB->setName("polly.stmt." + BB->getName());
948 Builder.SetInsertPoint(CopyBB->begin());
949
950 // Create two maps that store the mapping from the original instructions of
951 // the old basic block to their copies in the new basic block. Those maps
952 // are basic block local.
953 //
954 // As vector code generation is supported there is one map for scalar values
955 // and one for vector values.
956 //
957 // In case we just do scalar code generation, the vectorMap is not used and
958 // the scalarMap has just one dimension, which contains the mapping.
959 //
960 // In case vector code generation is done, an instruction may either appear
961 // in the vector map once (as it is calculating >vectorwidth< values at a
962 // time. Or (if the values are calculated using scalar operations), it
963 // appears once in every dimension of the scalarMap.
964 VectorValueMapT ScalarBlockMap(getVectorWidth());
965 ValueMapT VectorBlockMap;
966
Tobias Grosser91f5b262014-06-04 08:06:40 +0000967 for (Instruction &Inst : *BB)
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000968 copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
Hongbin Zheng3b11a162012-04-25 13:16:49 +0000969}
Johannes Doerfert275a1752015-02-24 16:16:32 +0000970
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000971BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
972 BasicBlock *BBCopy) {
Johannes Doerfert514f6ef2015-02-27 18:29:04 +0000973
974 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
975 BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
976
977 if (BBCopyIDom)
978 DT.changeImmediateDominator(BBCopy, BBCopyIDom);
979
980 return BBCopyIDom;
981}
982
Tobias Grosserbc132602015-09-05 09:56:54 +0000983void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
Tobias Grosser2d1ed0b2015-08-27 07:28:16 +0000984 isl_id_to_ast_expr *IdToAstExp) {
Johannes Doerfert275a1752015-02-24 16:16:32 +0000985 assert(Stmt.isRegionStmt() &&
Tobias Grosserd3f21832015-08-01 06:26:51 +0000986 "Only region statements can be copied by the region generator");
Johannes Doerfert275a1752015-02-24 16:16:32 +0000987
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000988 // Forget all old mappings.
989 BlockMap.clear();
990 RegionMaps.clear();
991 IncompletePHINodeMap.clear();
992
Johannes Doerfert275a1752015-02-24 16:16:32 +0000993 // The region represented by the statement.
994 Region *R = Stmt.getRegion();
995
Johannes Doerfertecff11d2015-05-22 23:43:58 +0000996 // Create a dedicated entry for the region where we can reload all demoted
997 // inputs.
998 BasicBlock *EntryBB = R->getEntry();
999 BasicBlock *EntryBBCopy =
1000 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
1001 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1002 Builder.SetInsertPoint(EntryBBCopy->begin());
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001003
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001004 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1005 if (!R->contains(*PI))
1006 BlockMap[*PI] = EntryBBCopy;
Johannes Doerfert275a1752015-02-24 16:16:32 +00001007
1008 // Iterate over all blocks in the region in a breadth-first search.
1009 std::deque<BasicBlock *> Blocks;
1010 SmallPtrSet<BasicBlock *, 8> SeenBlocks;
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001011 Blocks.push_back(EntryBB);
1012 SeenBlocks.insert(EntryBB);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001013
1014 while (!Blocks.empty()) {
1015 BasicBlock *BB = Blocks.front();
1016 Blocks.pop_front();
1017
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001018 // First split the block and update dominance information.
1019 BasicBlock *BBCopy = splitBB(BB);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001020 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1021
1022 // In order to remap PHI nodes we store also basic block mappings.
1023 BlockMap[BB] = BBCopy;
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001024
1025 // Get the mapping for this block and initialize it with the mapping
1026 // available at its immediate dominator (in the new region).
1027 ValueMapT &RegionMap = RegionMaps[BBCopy];
1028 RegionMap = RegionMaps[BBCopyIDom];
1029
Johannes Doerfert275a1752015-02-24 16:16:32 +00001030 // Copy the block with the BlockGenerator.
Tobias Grosserbc132602015-09-05 09:56:54 +00001031 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001032
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001033 // In order to remap PHI nodes we store also basic block mappings.
1034 BlockMap[BB] = BBCopy;
1035
1036 // Add values to incomplete PHI nodes waiting for this block to be copied.
1037 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
Tobias Grosserbc132602015-09-05 09:56:54 +00001038 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001039 IncompletePHINodeMap[BB].clear();
1040
Johannes Doerfert275a1752015-02-24 16:16:32 +00001041 // And continue with new successors inside the region.
1042 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1043 if (R->contains(*SI) && SeenBlocks.insert(*SI).second)
1044 Blocks.push_back(*SI);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001045 }
1046
1047 // Now create a new dedicated region exit block and add it to the region map.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001048 BasicBlock *ExitBBCopy =
Johannes Doerfert275a1752015-02-24 16:16:32 +00001049 SplitBlock(Builder.GetInsertBlock(), Builder.GetInsertPoint(), &DT, &LI);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001050 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001051 BlockMap[R->getExit()] = ExitBBCopy;
1052
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001053 repairDominance(R->getExit(), ExitBBCopy);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001054
1055 // As the block generator doesn't handle control flow we need to add the
1056 // region control flow by hand after all blocks have been copied.
1057 for (BasicBlock *BB : SeenBlocks) {
1058
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001059 BasicBlock *BBCopy = BlockMap[BB];
Johannes Doerferte114dc02015-09-14 11:15:58 +00001060 TerminatorInst *TI = BB->getTerminator();
1061 if (isa<UnreachableInst>(TI)) {
1062 while (!BBCopy->empty())
1063 BBCopy->begin()->eraseFromParent();
1064 new UnreachableInst(BBCopy->getContext(), BBCopy);
1065 continue;
1066 }
1067
Johannes Doerfert275a1752015-02-24 16:16:32 +00001068 Instruction *BICopy = BBCopy->getTerminator();
1069
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001070 ValueMapT &RegionMap = RegionMaps[BBCopy];
1071 RegionMap.insert(BlockMap.begin(), BlockMap.end());
1072
Tobias Grosser45e79442015-08-01 09:07:57 +00001073 Builder.SetInsertPoint(BICopy);
Johannes Doerfert9a132f32015-09-28 09:33:22 +00001074 copyInstScalar(Stmt, TI, RegionMap, LTS);
Johannes Doerfert275a1752015-02-24 16:16:32 +00001075 BICopy->eraseFromParent();
1076 }
1077
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001078 // Add counting PHI nodes to all loops in the region that can be used as
1079 // replacement for SCEVs refering to the old loop.
1080 for (BasicBlock *BB : SeenBlocks) {
1081 Loop *L = LI.getLoopFor(BB);
1082 if (L == nullptr || L->getHeader() != BB)
1083 continue;
1084
1085 BasicBlock *BBCopy = BlockMap[BB];
1086 Value *NullVal = Builder.getInt32(0);
1087 PHINode *LoopPHI =
1088 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1089 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1090 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1091 LoopPHI->insertBefore(BBCopy->begin());
1092 LoopPHIInc->insertBefore(BBCopy->getTerminator());
1093
1094 for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1095 if (!R->contains(PredBB))
1096 continue;
1097 if (L->contains(PredBB))
1098 LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1099 else
1100 LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1101 }
1102
1103 for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1104 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1105 LoopPHI->addIncoming(NullVal, PredBBCopy);
1106
1107 LTS[L] = SE.getUnknown(LoopPHI);
1108 }
1109
Johannes Doerfert275a1752015-02-24 16:16:32 +00001110 // Reset the old insert point for the build.
Johannes Doerfert514f6ef2015-02-27 18:29:04 +00001111 Builder.SetInsertPoint(ExitBBCopy->begin());
Johannes Doerfert275a1752015-02-24 16:16:32 +00001112}
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001113
1114void RegionGenerator::generateScalarLoads(ScopStmt &Stmt,
1115 const Instruction *Inst,
Tobias Grosserbc132602015-09-05 09:56:54 +00001116 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001117
1118 // Inside a non-affine region PHI nodes are copied not demoted. Once the
1119 // phi is copied it will reload all inputs from outside the region, hence
1120 // we do not need to generate code for the read access of the operands of a
1121 // PHI.
1122 if (isa<PHINode>(Inst))
1123 return;
1124
Tobias Grosserbc132602015-09-05 09:56:54 +00001125 return BlockGenerator::generateScalarLoads(Stmt, Inst, BBMap);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001126}
1127
1128void RegionGenerator::generateScalarStores(ScopStmt &Stmt, BasicBlock *BB,
Tobias Grosseraff56c82015-09-30 13:36:54 +00001129 LoopToScevMapT &LTS,
Tobias Grosserbc132602015-09-05 09:56:54 +00001130 ValueMapT &BBMap) {
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001131 const Region &R = Stmt.getParent()->getRegion();
1132
Tobias Grosser75296902015-08-21 19:23:21 +00001133 assert(Stmt.getRegion() &&
1134 "Block statements need to use the generateScalarStores() "
1135 "function in the BlockGenerator");
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001136
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001137 for (MemoryAccess *MA : Stmt) {
1138
Michael Kruse8d0b7342015-09-25 21:21:00 +00001139 if (MA->isExplicit() || MA->isRead())
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001140 continue;
1141
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001142 Instruction *ScalarInst = MA->getAccessInstruction();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001143
Tobias Grosser62139132015-08-02 16:17:41 +00001144 // Only generate accesses that belong to this basic block.
1145 if (ScalarInst->getParent() != BB)
1146 continue;
1147
Johannes Doerfertd86f2152015-08-17 10:58:17 +00001148 Value *Val = MA->getAccessValue();
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001149
Tobias Grosserbc132602015-09-05 09:56:54 +00001150 auto Address = getOrCreateAlloca(*MA);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001151
Tobias Grosseraff56c82015-09-30 13:36:54 +00001152 Val = getNewScalarValue(Val, R, Stmt, LTS, BBMap);
Tobias Grosserf8d55f72015-08-29 18:12:03 +00001153 Builder.CreateStore(Val, Address);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001154 }
1155}
1156
1157void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, const PHINode *PHI,
1158 PHINode *PHICopy, BasicBlock *IncomingBB,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001159 LoopToScevMapT &LTS) {
1160 Region *StmtR = Stmt.getRegion();
1161
1162 // If the incoming block was not yet copied mark this PHI as incomplete.
1163 // Once the block will be copied the incoming value will be added.
1164 BasicBlock *BBCopy = BlockMap[IncomingBB];
1165 if (!BBCopy) {
1166 assert(StmtR->contains(IncomingBB) &&
1167 "Bad incoming block for PHI in non-affine region");
1168 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1169 return;
1170 }
1171
1172 Value *OpCopy = nullptr;
1173 if (StmtR->contains(IncomingBB)) {
1174 assert(RegionMaps.count(BBCopy) &&
1175 "Incoming PHI block did not have a BBMap");
1176 ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1177
1178 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
Tobias Grosserbc132602015-09-05 09:56:54 +00001179 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForInst(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001180 } else {
1181
1182 if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1183 return;
1184
Tobias Grosserbc132602015-09-05 09:56:54 +00001185 Value *PHIOpAddr = getOrCreatePHIAlloca(const_cast<PHINode *>(PHI));
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001186 OpCopy = new LoadInst(PHIOpAddr, PHIOpAddr->getName() + ".reload",
1187 BlockMap[IncomingBB]->getTerminator());
1188 }
1189
1190 assert(OpCopy && "Incoming PHI value was not copied properly");
1191 assert(BBCopy && "Incoming PHI block was not copied properly");
1192 PHICopy->addIncoming(OpCopy, BBCopy);
1193}
1194
Tobias Grosser2f1acac2015-10-04 10:18:45 +00001195Value *RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001196 ValueMapT &BBMap,
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001197 LoopToScevMapT &LTS) {
1198 unsigned NumIncoming = PHI->getNumIncomingValues();
1199 PHINode *PHICopy =
1200 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1201 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1202 BBMap[PHI] = PHICopy;
1203
1204 for (unsigned u = 0; u < NumIncoming; u++)
Tobias Grosserbc132602015-09-05 09:56:54 +00001205 addOperandToPHI(Stmt, PHI, PHICopy, PHI->getIncomingBlock(u), LTS);
Johannes Doerfertecff11d2015-05-22 23:43:58 +00001206 return PHICopy;
1207}