Polly 24.0.0git
BlockGenerators.cpp
Go to the documentation of this file.
1//===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the BlockGenerator and VectorBlockGenerator classes,
10// which generate sequential code and vectorized code for a polyhedral
11// statement, respectively.
12//
13//===----------------------------------------------------------------------===//
14
18#include "polly/Options.h"
19#include "polly/ScopInfo.h"
23#include "llvm/Analysis/DomTreeUpdater.h"
24#include "llvm/Analysis/LoopInfo.h"
25#include "llvm/Analysis/RegionInfo.h"
26#include "llvm/Analysis/ScalarEvolution.h"
27#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28#include "llvm/Transforms/Utils/Local.h"
29#include "isl/ast.h"
30#include <deque>
31
32using namespace llvm;
33using namespace polly;
34
35static cl::opt<bool> Aligned("enable-polly-aligned",
36 cl::desc("Assumed aligned memory accesses."),
37 cl::Hidden, cl::cat(PollyCategory));
38
40static cl::opt<bool, true> DebugPrintingX(
41 "polly-codegen-add-debug-printing",
42 cl::desc("Add printf calls that show the values loaded/stored."),
43 cl::location(PollyDebugPrinting), cl::Hidden, cl::cat(PollyCategory));
44
46static cl::opt<bool, true> TraceStmtsX(
47 "polly-codegen-trace-stmts",
48 cl::desc("Add printf calls that print the statement being executed"),
49 cl::location(TraceStmts), cl::Hidden, cl::cat(PollyCategory));
50
51static cl::opt<bool> TraceScalars(
52 "polly-codegen-trace-scalars",
53 cl::desc("Add printf calls that print the values of all scalar values "
54 "used in a statement. Requires -polly-codegen-trace-stmts."),
55 cl::Hidden, cl::cat(PollyCategory));
56
64
66 ValueMapT &BBMap,
67 LoopToScevMapT &LTS,
68 Loop *L) const {
69 if (!SE.isSCEVable(Old->getType()))
70 return nullptr;
71
72 const SCEV *Scev = SE.getSCEVAtScope(Old, L);
73 if (!Scev)
74 return nullptr;
75
76 if (isa<SCEVCouldNotCompute>(Scev))
77 return nullptr;
78
79 ValueMapT VTV;
80 VTV.insert_range(BBMap);
81 VTV.insert_range(GlobalMap);
82
83 Scop &S = *Stmt.getParent();
84 const DataLayout &DL = S.getFunction().getDataLayout();
85 auto IP = Builder.GetInsertPoint();
86
87 assert(IP != Builder.GetInsertBlock()->end() &&
88 "Only instructions can be insert points for SCEVExpander");
89 Value *Expanded = expandCodeFor(
90 S, SE, Builder.GetInsertBlock()->getParent(), *GenSE, DL, "polly", Scev,
91 Old->getType(), IP, &VTV, &LTS, StartBlock->getSinglePredecessor());
92
93 BBMap[Old] = Expanded;
94 return Expanded;
95}
96
98 LoopToScevMapT &LTS, Loop *L) const {
99
100 auto lookupGlobally = [this](Value *Old) -> Value * {
101 Value *New = GlobalMap.lookup(Old);
102 if (!New)
103 return nullptr;
104
105 // Required by:
106 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded.ll
107 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_different_bb.ll
108 // * Isl/CodeGen/OpenMP/invariant_base_pointer_preloaded_pass_only_needed.ll
109 // * Isl/CodeGen/OpenMP/invariant_base_pointers_preloaded.ll
110 // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
111 // * Isl/CodeGen/OpenMP/single_loop_with_loop_invariant_baseptr.ll
112 // GlobalMap should be a mapping from (value in original SCoP) to (copied
113 // value in generated SCoP), without intermediate mappings, which might
114 // easily require transitiveness as well.
115 if (Value *NewRemapped = GlobalMap.lookup(New))
116 New = NewRemapped;
117
118 // No test case for this code.
119 if (Old->getType()->getScalarSizeInBits() <
120 New->getType()->getScalarSizeInBits())
121 New = Builder.CreateTruncOrBitCast(New, Old->getType());
122
123 return New;
124 };
125
126 Value *New = nullptr;
127 auto VUse = VirtualUse::create(&Stmt, L, Old, true);
128 switch (VUse.getKind()) {
130 // BasicBlock are constants, but the BlockGenerator copies them.
131 New = BBMap.lookup(Old);
132 break;
133
135 // Used by:
136 // * Isl/CodeGen/OpenMP/reference-argument-from-non-affine-region.ll
137 // Constants should not be redefined. In this case, the GlobalMap just
138 // contains a mapping to the same constant, which is unnecessary, but
139 // harmless.
140 if ((New = lookupGlobally(Old)))
141 break;
142
143 assert(!BBMap.count(Old));
144 New = Old;
145 break;
146
148 assert(!GlobalMap.count(Old));
149
150 // Required for:
151 // * Isl/CodeGen/MemAccess/create_arrays.ll
152 // * Isl/CodeGen/read-only-scalars.ll
153 // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
154 // For some reason these reload a read-only value. The reloaded value ends
155 // up in BBMap, buts its value should be identical.
156 //
157 // Required for:
158 // * Isl/CodeGen/OpenMP/single_loop_with_param.ll
159 // The parallel subfunctions need to reference the read-only value from the
160 // parent function, this is done by reloading them locally.
161 if ((New = BBMap.lookup(Old)))
162 break;
163
164 New = Old;
165 break;
166
168 // Used by:
169 // * Isl/CodeGen/OpenMP/loop-body-references-outer-values-3.ll
170 // * Isl/CodeGen/OpenMP/recomputed-srem.ll
171 // * Isl/CodeGen/OpenMP/reference-other-bb.ll
172 // * Isl/CodeGen/OpenMP/two-parallel-loops-reference-outer-indvar.ll
173 // For some reason synthesizable values end up in GlobalMap. Their values
174 // are the same as trySynthesizeNewValue would return. The legacy
175 // implementation prioritized GlobalMap, so this is what we do here as well.
176 // Ideally, synthesizable values should not end up in GlobalMap.
177 if ((New = lookupGlobally(Old)))
178 break;
179
180 // Required for:
181 // * Isl/CodeGen/RuntimeDebugBuilder/combine_different_values.ll
182 // * Isl/CodeGen/getNumberOfIterations.ll
183 // * Isl/CodeGen/non_affine_float_compare.ll
184 // * ScheduleOptimizer/pattern-matching-based-opts_10.ll
185 // Ideally, synthesizable values are synthesized by trySynthesizeNewValue,
186 // not precomputed (SCEVExpander has its own caching mechanism).
187 // These tests fail without this, but I think trySynthesizeNewValue would
188 // just re-synthesize the same instructions.
189 if ((New = BBMap.lookup(Old)))
190 break;
191
192 New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L);
193 break;
194
196 // TODO: Hoisted invariant loads should be found in GlobalMap only, but not
197 // redefined locally (which will be ignored anyway). That is, the following
198 // assertion should apply: assert(!BBMap.count(Old))
199
200 New = lookupGlobally(Old);
201 break;
202
205 assert(!GlobalMap.count(Old) &&
206 "Intra and inter-stmt values are never global");
207 New = BBMap.lookup(Old);
208 break;
209 }
210 assert(New && "Unexpected scalar dependence in region!");
211 return New;
212}
213
214void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
215 ValueMapT &BBMap, LoopToScevMapT &LTS) {
216 // We do not generate debug intrinsics as we did not investigate how to
217 // copy them correctly. At the current state, they just crash the code
218 // generation as the meta-data operands are not correctly copied.
219 if (isa<DbgInfoIntrinsic>(Inst))
220 return;
221
222 Instruction *NewInst = Inst->clone();
223
224 // Replace old operands with the new ones.
225 for (Value *OldOperand : Inst->operands()) {
226 Value *NewOperand =
227 getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
228
229 if (!NewOperand) {
230 assert(!isa<StoreInst>(NewInst) &&
231 "Store instructions are always needed!");
232 NewInst->deleteValue();
233 return;
234 }
235
236 // FIXME: We will encounter "NewOperand" again if used twice. getNewValue()
237 // is meant to be called on old values only.
238 NewInst->replaceUsesOfWith(OldOperand, NewOperand);
239 }
240
241 Builder.Insert(NewInst);
242 BBMap[Inst] = NewInst;
243
244 assert(NewInst->getModule() == Inst->getModule() &&
245 "Expecting instructions to be in the same module");
246
247 if (!NewInst->getType()->isVoidTy())
248 NewInst->setName("p_" + Inst->getName());
249}
250
251Value *
253 ValueMapT &BBMap, LoopToScevMapT &LTS,
254 isl_id_to_ast_expr *NewAccesses) {
255 const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
257 Stmt, getLoopForStmt(Stmt),
258 Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS,
259 NewAccesses, MA.getId().release(), MA.getAccessValue()->getType());
260}
261
263 ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
264 LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
265 Type *ExpectedType) {
266 isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
267
268 if (AccessExpr) {
269 AccessExpr = isl_ast_expr_address_of(AccessExpr);
270 return ExprBuilder->create(AccessExpr);
271 }
272 assert(
273 Pointer &&
274 "If expression was not generated, must use the original pointer value");
275 return getNewValue(Stmt, Pointer, BBMap, LTS, L);
276}
277
278Value *
280 LoopToScevMapT &LTS, ValueMapT &BBMap,
281 __isl_keep isl_id_to_ast_expr *NewAccesses) {
282 if (Access.isLatestArrayKind())
283 return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
284 LTS, NewAccesses, Access.getId().release(),
285 Access.getAccessValue()->getType());
286
287 return getOrCreateAlloca(Access);
288}
289
290Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
291 auto *StmtBB = Stmt.getEntryBlock();
292 return LI.getLoopFor(StmtBB);
293}
294
296 ValueMapT &BBMap, LoopToScevMapT &LTS,
297 isl_id_to_ast_expr *NewAccesses) {
298 if (Value *PreloadLoad = GlobalMap.lookup(Load))
299 return PreloadLoad;
300
301 Value *NewPointer =
302 generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
303 Value *ScalarLoad =
304 Builder.CreateAlignedLoad(Load->getType(), NewPointer, Load->getAlign(),
305 Load->getName() + "_p_scalar_");
306
308 RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
309 ": ", ScalarLoad, "\n");
310
311 return ScalarLoad;
312}
313
314void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
315 ValueMapT &BBMap, LoopToScevMapT &LTS,
316 isl_id_to_ast_expr *NewAccesses) {
317 MemoryAccess &MA = Stmt.getArrayAccessFor(Store);
318 isl::set AccDom = MA.getAccessRelation().domain();
319 std::string Subject = MA.getId().get_name();
320
321 generateConditionalExecution(Stmt, AccDom, Subject.c_str(), [&, this]() {
322 Value *NewPointer =
323 generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
324 Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap,
325 LTS, getLoopForStmt(Stmt));
326
327 if (PollyDebugPrinting)
328 RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer,
329 ": ", ValueOperand, "\n");
330
331 Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlign());
332 });
333}
334
335bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
336 Loop *L = getLoopForStmt(Stmt);
337 return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
338 canSynthesize(Inst, *Stmt.getParent(), &SE, L);
339}
340
341void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
342 ValueMapT &BBMap, LoopToScevMapT &LTS,
343 isl_id_to_ast_expr *NewAccesses) {
344 // Terminator instructions control the control flow. They are explicitly
345 // expressed in the clast and do not need to be copied.
346 if (Inst->isTerminator())
347 return;
348
349 // Synthesizable statements will be generated on-demand.
350 if (canSyntheziseInStmt(Stmt, Inst))
351 return;
352
353 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
354 Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
355 // Compute NewLoad before its insertion in BBMap to make the insertion
356 // deterministic.
357 BBMap[Load] = NewLoad;
358 return;
359 }
360
361 if (auto *Store = dyn_cast<StoreInst>(Inst)) {
362 // Identified as redundant by -polly-simplify.
363 if (!Stmt.getArrayAccessOrNULLFor(Store))
364 return;
365
366 generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
367 return;
368 }
369
370 if (auto *PHI = dyn_cast<PHINode>(Inst)) {
371 copyPHIInstruction(Stmt, PHI, BBMap, LTS);
372 return;
373 }
374
375 // Skip some special intrinsics for which we do not adjust the semantics to
376 // the new schedule. All others are handled like every other instruction.
377 if (isIgnoredIntrinsic(Inst))
378 return;
379
380 copyInstScalar(Stmt, Inst, BBMap, LTS);
381}
382
384 auto NewBB = Builder.GetInsertBlock();
385 for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) {
386 Instruction *NewInst = &*I;
387
388 if (!isInstructionTriviallyDead(NewInst))
389 continue;
390
391 BBMap.remove_if([&](const auto &Pair) { return Pair.second == NewInst; });
392
393 NewInst->eraseFromParent();
394 I = NewBB->rbegin();
395 }
396}
397
399 __isl_keep isl_id_to_ast_expr *NewAccesses) {
400 assert(Stmt.isBlockStmt() &&
401 "Only block statements can be copied by the block generator");
402
403 ValueMapT BBMap;
404
405 BasicBlock *BB = Stmt.getBasicBlock();
406 copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
407 removeDeadInstructions(BB, BBMap);
408}
409
410BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
411 BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
412 Builder.GetInsertPoint(), GenDT, GenLI);
413 CopyBB->setName("polly.stmt." + BB->getName());
414 return CopyBB;
415}
416
417BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
418 ValueMapT &BBMap, LoopToScevMapT &LTS,
419 isl_id_to_ast_expr *NewAccesses) {
420 BasicBlock *CopyBB = splitBB(BB);
421 Builder.SetInsertPoint(CopyBB, CopyBB->begin());
422 generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
423 generateBeginStmtTrace(Stmt, LTS, BBMap);
424
425 copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
426
427 // After a basic block was copied store all scalars that escape this block in
428 // their alloca.
429 generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
430 return CopyBB;
431}
432
433void BlockGenerator::switchGeneratedFunc(Function *GenFn, DominatorTree *GenDT,
434 LoopInfo *GenLI,
435 ScalarEvolution *GenSE) {
436 assert(GenFn == GenDT->getRoot()->getParent());
437 assert(GenLI->getTopLevelLoops().empty() ||
438 GenFn == GenLI->getTopLevelLoops().front()->getHeader()->getParent());
439 this->GenDT = GenDT;
440 this->GenLI = GenLI;
441 this->GenSE = GenSE;
442}
443
444void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
445 ValueMapT &BBMap, LoopToScevMapT &LTS,
446 isl_id_to_ast_expr *NewAccesses) {
447 // Block statements and the entry blocks of region statement are code
448 // generated from instruction lists. This allow us to optimize the
449 // instructions that belong to a certain scop statement. As the code
450 // structure of region statements might be arbitrary complex, optimizing the
451 // instruction list is not yet supported.
452 if (Stmt.isBlockStmt() || (Stmt.isRegionStmt() && Stmt.getEntryBlock() == BB))
453 for (Instruction *Inst : Stmt.getInstructions())
454 copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses);
455 else
456 for (Instruction &Inst : *BB)
457 copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
458}
459
461 assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
462
464}
465
467 assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
468
469 auto &Addr = ScalarMap[Array];
470
471 if (Addr) {
472 // Allow allocas to be (temporarily) redirected once by adding a new
473 // old-alloca-addr to new-addr mapping to GlobalMap. This functionality
474 // is used for example by the OpenMP code generation where a first use
475 // of a scalar while still in the host code allocates a normal alloca with
476 // getOrCreateAlloca. When the values of this scalar are accessed during
477 // the generation of the parallel subfunction, these values are copied over
478 // to the parallel subfunction and each request for a scalar alloca slot
479 // must be forwarded to the temporary in-subfunction slot. This mapping is
480 // removed when the subfunction has been generated and again normal host
481 // code is generated. Due to the following reasons it is not possible to
482 // perform the GlobalMap lookup right after creating the alloca below, but
483 // instead we need to check GlobalMap at each call to getOrCreateAlloca:
484 //
485 // 1) GlobalMap may be changed multiple times (for each parallel loop),
486 // 2) The temporary mapping is commonly only known after the initial
487 // alloca has already been generated, and
488 // 3) The original alloca value must be restored after leaving the
489 // sub-function.
490 if (Value *NewAddr = GlobalMap.lookup(&*Addr))
491 return NewAddr;
492 return Addr;
493 }
494
495 Type *Ty = Array->getElementType();
496 Value *ScalarBase = Array->getBasePtr();
497 std::string NameExt;
498 if (Array->isPHIKind())
499 NameExt = ".phiops";
500 else
501 NameExt = ".s2a";
502
503 const DataLayout &DL = Builder.GetInsertBlock()->getDataLayout();
504
505 Addr =
506 new AllocaInst(Ty, DL.getAllocaAddrSpace(), nullptr,
507 DL.getPrefTypeAlign(Ty), ScalarBase->getName() + NameExt);
508 BasicBlock *EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
509 Addr->insertBefore(EntryBB->getFirstInsertionPt());
510
511 return Addr;
512}
513
515 Instruction *Inst = cast<Instruction>(Array->getBasePtr());
516
517 // If there are escape users we get the alloca for this instruction and put it
518 // in the EscapeMap for later finalization. Lastly, if the instruction was
519 // copied multiple times we already did this and can exit.
520 if (EscapeMap.count(Inst))
521 return;
522
523 EscapeUserVectorTy EscapeUsers;
524 for (User *U : Inst->users()) {
525
526 // Non-instruction user will never escape.
527 Instruction *UI = dyn_cast<Instruction>(U);
528 if (!UI)
529 continue;
530
531 if (S.contains(UI))
532 continue;
533
534 EscapeUsers.push_back(UI);
535 }
536
537 // Exit if no escape uses were found.
538 if (EscapeUsers.empty())
539 return;
540
541 // Get or create an escape alloca for this instruction.
542 auto *ScalarAddr = getOrCreateAlloca(Array);
543
544 // Remember that this instruction has escape uses and the escape alloca.
545 EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
546}
547
549 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
550 __isl_keep isl_id_to_ast_expr *NewAccesses) {
551 for (MemoryAccess *MA : Stmt) {
552 if (MA->isOriginalArrayKind() || MA->isWrite())
553 continue;
554
555#ifndef NDEBUG
556 auto StmtDom =
558 // Restrict to defined behavior context to match DeLICM's contract:
559 // new read accesses are only required to cover the defined-behavior
560 // subset of the domain.
561 StmtDom = StmtDom.intersect_params(
563 auto AccDom = MA->getAccessRelation().domain();
564 assert(!StmtDom.is_subset(AccDom).is_false() &&
565 "Scalar must be loaded in all statement instances");
566#endif
567
568 auto *Address =
569 getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
570 BBMap[MA->getAccessValue()] = Builder.CreateLoad(
571 MA->getElementType(), Address, Address->getName() + ".reload");
572 }
573}
574
576 const isl::set &Subdomain) {
577 isl::ast_build AstBuild = Stmt.getAstBuild();
578 isl::set Domain = Stmt.getDomain();
579
580 isl::union_map USchedule = AstBuild.get_schedule();
581 USchedule = USchedule.intersect_domain(Domain);
582
583 assert(!USchedule.is_empty());
584 isl::map Schedule = isl::map::from_union_map(USchedule);
585
586 isl::set ScheduledDomain = Schedule.range();
587 isl::set ScheduledSet = Subdomain.apply(Schedule);
588
589 isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
590
591 isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
592 Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
593 IsInSetExpr = Builder.CreateICmpNE(
594 IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
595
596 return IsInSetExpr;
597}
598
600 ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
601 const std::function<void()> &GenThenFunc) {
602 isl::set StmtDom = Stmt.getDomain();
603
604 // If the condition is a tautology, don't generate a condition around the
605 // code.
606 bool IsPartialWrite =
607 !StmtDom.intersect_params(Stmt.getParent()->getContext())
608 .is_subset(Subdomain);
609 if (!IsPartialWrite) {
610 GenThenFunc();
611 return;
612 }
613
614 // Generate the condition.
615 Value *Cond = buildContainsCondition(Stmt, Subdomain);
616
617 // Don't call GenThenFunc if it is never executed. An ast index expression
618 // might not be defined in this case.
619 if (auto *Const = dyn_cast<ConstantInt>(Cond))
620 if (Const->isZero())
621 return;
622
623 BasicBlock *HeadBlock = Builder.GetInsertBlock();
624 StringRef BlockName = HeadBlock->getName();
625
626 // Generate the conditional block.
627 DomTreeUpdater DTU(GenDT, DomTreeUpdater::UpdateStrategy::Eager);
628 SplitBlockAndInsertIfThen(Cond, Builder.GetInsertPoint(), false, nullptr,
629 &DTU, GenLI);
630 CondBrInst *Branch = cast<CondBrInst>(HeadBlock->getTerminator());
631 BasicBlock *ThenBlock = Branch->getSuccessor(0);
632 BasicBlock *TailBlock = Branch->getSuccessor(1);
633
634 // Assign descriptive names.
635 if (auto *CondInst = dyn_cast<Instruction>(Cond))
636 CondInst->setName("polly." + Subject + ".cond");
637 ThenBlock->setName(BlockName + "." + Subject + ".partial");
638 TailBlock->setName(BlockName + ".cont");
639
640 // Put the client code into the conditional block and continue in the merge
641 // block afterwards.
642 Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt());
643 GenThenFunc();
644 Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt());
645}
646
647static std::string getInstName(Value *Val) {
648 std::string Result;
649 raw_string_ostream OS(Result);
650 Val->printAsOperand(OS, false);
651 return Result;
652}
653
655 ValueMapT &BBMap) {
656 if (!TraceStmts)
657 return;
658
659 Scop *S = Stmt.getParent();
660 const char *BaseName = Stmt.getBaseName();
661
662 isl::ast_build AstBuild = Stmt.getAstBuild();
663 isl::set Domain = Stmt.getDomain();
664
665 isl::union_map USchedule = AstBuild.get_schedule().intersect_domain(Domain);
666 isl::map Schedule = isl::map::from_union_map(USchedule);
667 assert(Schedule.is_empty().is_false() &&
668 "The stmt must have a valid instance");
669
670 isl::multi_pw_aff ScheduleMultiPwAff =
672 isl::ast_build RestrictedBuild = AstBuild.restrict(Schedule.range());
673
674 // Sequence of strings to print.
675 SmallVector<llvm::Value *, 8> Values;
676
677 // Print the name of the statement.
678 // TODO: Indent by the depth of the statement instance in the schedule tree.
679 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, BaseName));
680 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "("));
681
682 // Add the coordinate of the statement instance.
683 for (unsigned i : rangeIslSize(0, ScheduleMultiPwAff.dim(isl::dim::out))) {
684 if (i > 0)
685 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ","));
686
687 isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduleMultiPwAff.at(i));
688 Values.push_back(ExprBuilder->create(IsInSet.copy()));
689 }
690
691 if (TraceScalars) {
692 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")"));
693 DenseSet<Instruction *> Encountered;
694
695 // Add the value of each scalar (and the result of PHIs) used in the
696 // statement.
697 // TODO: Values used in region-statements.
698 for (Instruction *Inst : Stmt.insts()) {
699 if (!RuntimeDebugBuilder::isPrintable(Inst->getType()))
700 continue;
701
702 if (isa<PHINode>(Inst)) {
703 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, " "));
705 Builder, getInstName(Inst)));
706 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "="));
707 Values.push_back(getNewValue(Stmt, Inst, BBMap, LTS,
708 LI.getLoopFor(Inst->getParent())));
709 } else {
710 for (Value *Op : Inst->operand_values()) {
711 // Do not print values that cannot change during the execution of the
712 // SCoP.
713 auto *OpInst = dyn_cast<Instruction>(Op);
714 if (!OpInst)
715 continue;
716 if (!S->contains(OpInst))
717 continue;
718
719 // Print each scalar at most once, and exclude values defined in the
720 // statement itself.
721 if (Encountered.count(OpInst))
722 continue;
723
724 Values.push_back(
727 Builder, getInstName(OpInst)));
728 Values.push_back(
730 Values.push_back(getNewValue(Stmt, OpInst, BBMap, LTS,
731 LI.getLoopFor(Inst->getParent())));
732 Encountered.insert(OpInst);
733 }
734 }
735
736 Encountered.insert(Inst);
737 }
738
739 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, "\n"));
740 } else {
741 Values.push_back(RuntimeDebugBuilder::getPrintableString(Builder, ")\n"));
742 }
743
744 RuntimeDebugBuilder::createCPUPrinter(Builder, ArrayRef<Value *>(Values));
745}
746
748 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
749 __isl_keep isl_id_to_ast_expr *NewAccesses) {
750 Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
751
752 assert(Stmt.isBlockStmt() &&
753 "Region statements need to use the generateScalarStores() function in "
754 "the RegionGenerator");
755
756 for (MemoryAccess *MA : Stmt) {
757 if (MA->isOriginalArrayKind() || MA->isRead())
758 continue;
759
760 isl::set AccDom = MA->getAccessRelation().domain();
761 std::string Subject = MA->getId().get_name();
762
764 Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
765 Value *Val = MA->getAccessValue();
766 if (MA->isAnyPHIKind()) {
767 assert(MA->getIncoming().size() >= 1 &&
768 "Block statements have exactly one exiting block, or "
769 "multiple but "
770 "with same incoming block and value");
771 assert(std::all_of(MA->getIncoming().begin(),
772 MA->getIncoming().end(),
773 [&](std::pair<BasicBlock *, Value *> p) -> bool {
774 return p.first == Stmt.getBasicBlock();
775 }) &&
776 "Incoming block must be statement's block");
777 Val = MA->getIncoming()[0].second;
778 }
779 auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
780 BBMap, NewAccesses);
781
782 Val = getNewValue(Stmt, Val, BBMap, LTS, L);
783 assert((!isa<Instruction>(Val) ||
784 GenDT->dominates(cast<Instruction>(Val)->getParent(),
785 Builder.GetInsertBlock())) &&
786 "Domination violation");
787 assert((!isa<Instruction>(Address) ||
788 GenDT->dominates(cast<Instruction>(Address)->getParent(),
789 Builder.GetInsertBlock())) &&
790 "Domination violation");
791
792 Builder.CreateStore(Val, Address);
793 });
794 }
795}
796
798 BasicBlock *ExitBB = S.getExit();
799 BasicBlock *PreEntryBB = S.getEnteringBlock();
800
801 Builder.SetInsertPoint(StartBlock, StartBlock->begin());
802
803 for (auto &Array : S.arrays()) {
804 if (Array->getNumberOfDimensions() != 0)
805 continue;
806 if (Array->isPHIKind()) {
807 // For PHI nodes, the only values we need to store are the ones that
808 // reach the PHI node from outside the region. In general there should
809 // only be one such incoming edge and this edge should enter through
810 // 'PreEntryBB'.
811 auto PHI = cast<PHINode>(Array->getBasePtr());
812
813 for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
814 if (!S.contains(*BI) && *BI != PreEntryBB)
815 llvm_unreachable("Incoming edges from outside the scop should always "
816 "come from PreEntryBB");
817
818 int Idx = PHI->getBasicBlockIndex(PreEntryBB);
819 if (Idx < 0)
820 continue;
821
822 Value *ScalarValue = PHI->getIncomingValue(Idx);
823
824 Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
825 continue;
826 }
827
828 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
829
830 if (Inst && S.contains(Inst))
831 continue;
832
833 // PHI nodes that are not marked as such in their SAI object are either exit
834 // PHI nodes we model as common scalars but without initialization, or
835 // incoming phi nodes that need to be initialized. Check if the first is the
836 // case for Inst and do not create and initialize memory if so.
837 if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
838 if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
839 continue;
840
841 Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
842 }
843}
844
846 // The exit block of the __unoptimized__ region.
847 BasicBlock *ExitBB = S.getExitingBlock();
848 // The merge block __just after__ the region and the optimized region.
849 BasicBlock *MergeBB = S.getExit();
850
851 // The exit block of the __optimized__ region.
852 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
853 if (OptExitBB == ExitBB)
854 OptExitBB = *(++pred_begin(MergeBB));
855
856 Builder.SetInsertPoint(OptExitBB, OptExitBB->getTerminator()->getIterator());
857 for (const auto &EscapeMapping : EscapeMap) {
858 // Extract the escaping instruction and the escaping users as well as the
859 // alloca the instruction was demoted to.
860 Instruction *EscapeInst = EscapeMapping.first;
861 const auto &EscapeMappingValue = EscapeMapping.second;
862 const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
863 auto *ScalarAddr = cast<AllocaInst>(&*EscapeMappingValue.first);
864
865 // Reload the demoted instruction in the optimized version of the SCoP.
866 Value *EscapeInstReload =
867 Builder.CreateLoad(ScalarAddr->getAllocatedType(), ScalarAddr,
868 EscapeInst->getName() + ".final_reload");
869 EscapeInstReload =
870 Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
871
872 // Create the merge PHI that merges the optimized and unoptimized version.
873 PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
874 EscapeInst->getName() + ".merge");
875 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
876
877 // Add the respective values to the merge PHI.
878 MergePHI->addIncoming(EscapeInstReload, OptExitBB);
879 MergePHI->addIncoming(EscapeInst, ExitBB);
880
881 // The information of scalar evolution about the escaping instruction needs
882 // to be revoked so the new merged instruction will be used.
883 if (SE.isSCEVable(EscapeInst->getType()))
884 SE.forgetValue(EscapeInst);
885
886 // Replace all uses of the demoted instruction with the merge PHI.
887 for (Instruction *EUser : EscapeUsers)
888 EUser->replaceUsesOfWith(EscapeInst, MergePHI);
889 }
890}
891
893 for (auto &Array : S.arrays()) {
894
895 if (Array->getNumberOfDimensions() != 0)
896 continue;
897
898 if (Array->isPHIKind())
899 continue;
900
901 auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
902
903 if (!Inst)
904 continue;
905
906 // Scop invariant hoisting moves some of the base pointers out of the scop.
907 // We can ignore these, as the invariant load hoisting already registers the
908 // relevant outside users.
909 if (!S.contains(Inst))
910 continue;
911
913 }
914}
915
917 if (S.hasSingleExitEdge())
918 return;
919
920 auto *ExitBB = S.getExitingBlock();
921 auto *MergeBB = S.getExit();
922 auto *AfterMergeBB = MergeBB->getSingleSuccessor();
923 BasicBlock *OptExitBB = *(pred_begin(MergeBB));
924 if (OptExitBB == ExitBB)
925 OptExitBB = *(++pred_begin(MergeBB));
926
927 Builder.SetInsertPoint(OptExitBB, OptExitBB->getTerminator()->getIterator());
928
929 for (auto &SAI : S.arrays()) {
930 auto *Val = SAI->getBasePtr();
931
932 // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
933 // the original PHI's value or the reloaded incoming values from the
934 // generated code. An llvm::Value is merged between the original code's
935 // value or the generated one.
936 if (!SAI->isExitPHIKind())
937 continue;
938
939 PHINode *PHI = dyn_cast<PHINode>(Val);
940 if (!PHI)
941 continue;
942
943 if (PHI->getParent() != AfterMergeBB)
944 continue;
945
946 std::string Name = PHI->getName().str();
947 Value *ScalarAddr = getOrCreateAlloca(SAI);
948 Value *Reload = Builder.CreateLoad(SAI->getElementType(), ScalarAddr,
949 Name + ".ph.final_reload");
950 Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
951 Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
952 assert((!isa<Instruction>(OriginalValue) ||
953 cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
954 "Original value must no be one we just generated.");
955 auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
956 MergePHI->insertBefore(MergeBB->getFirstInsertionPt());
957 MergePHI->addIncoming(Reload, OptExitBB);
958 MergePHI->addIncoming(OriginalValue, ExitBB);
959 int Idx = PHI->getBasicBlockIndex(MergeBB);
960 PHI->setIncomingValue(Idx, MergePHI);
961 }
962}
963
965 for (auto &Stmt : S)
966 if (Stmt.isCopyStmt())
967 continue;
968 else if (Stmt.isBlockStmt())
969 for (auto &Inst : *Stmt.getBasicBlock())
970 SE.forgetValue(&Inst);
971 else if (Stmt.isRegionStmt())
972 for (auto *BB : Stmt.getRegion()->blocks())
973 for (auto &Inst : *BB)
974 SE.forgetValue(&Inst);
975 else
976 llvm_unreachable("Unexpected statement type found");
977
978 // Invalidate SCEV of loops surrounding the EscapeUsers.
979 for (const auto &EscapeMapping : EscapeMap) {
980 const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
981 for (Instruction *EUser : EscapeUsers) {
982 if (Loop *L = LI.getLoopFor(EUser->getParent()))
983 while (L) {
984 SE.forgetLoop(L);
985 L = L->getParentLoop();
986 }
987 }
988 }
989}
990
998
999BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1000 BasicBlock *BBCopy) {
1001
1002 BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1003 BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
1004
1005 if (BBCopyIDom)
1006 GenDT->changeImmediateDominator(BBCopy, BBCopyIDom);
1007
1008 return StartBlockMap.lookup(BBIDom);
1009}
1010
1011// This is to determine whether an llvm::Value (defined in @p BB) is usable when
1012// leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1013// does not work in cases where the exit block has edges from outside the
1014// region. In that case the llvm::Value would never be usable in in the exit
1015// block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1016// for the subregion's exiting edges only. We need to determine whether an
1017// llvm::Value is usable in there. We do this by checking whether it dominates
1018// all exiting blocks individually.
1019static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1020 BasicBlock *BB) {
1021 for (auto ExitingBB : predecessors(R->getExit())) {
1022 // Check for non-subregion incoming edges.
1023 if (!R->contains(ExitingBB))
1024 continue;
1025
1026 if (!DT.dominates(BB, ExitingBB))
1027 return false;
1028 }
1029
1030 return true;
1031}
1032
1033// Find the direct dominator of the subregion's exit block if the subregion was
1034// simplified.
1035static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1036 BasicBlock *Common = nullptr;
1037 for (auto ExitingBB : predecessors(R->getExit())) {
1038 // Check for non-subregion incoming edges.
1039 if (!R->contains(ExitingBB))
1040 continue;
1041
1042 // First exiting edge.
1043 if (!Common) {
1044 Common = ExitingBB;
1045 continue;
1046 }
1047
1048 Common = DT.findNearestCommonDominator(Common, ExitingBB);
1049 }
1050
1051 assert(Common && R->contains(Common));
1052 return Common;
1053}
1054
1056 __isl_keep isl_id_to_ast_expr *IdToAstExp) {
1057 assert(Stmt.isRegionStmt() &&
1058 "Only region statements can be copied by the region generator");
1059
1060 // Forget all old mappings.
1061 StartBlockMap.clear();
1062 EndBlockMap.clear();
1063 RegionMaps.clear();
1064 IncompletePHINodeMap.clear();
1065
1066 // Collection of all values related to this subregion.
1067 ValueMapT ValueMap;
1068
1069 // The region represented by the statement.
1070 Region *R = Stmt.getRegion();
1071
1072 // Create a dedicated entry for the region where we can reload all demoted
1073 // inputs.
1074 BasicBlock *EntryBB = R->getEntry();
1075 BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1076 Builder.GetInsertPoint(), GenDT, GenLI);
1077 EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1078 Builder.SetInsertPoint(EntryBBCopy, EntryBBCopy->begin());
1079
1080 ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1081 generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1082 generateBeginStmtTrace(Stmt, LTS, EntryBBMap);
1083
1084 for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1085 if (!R->contains(*PI)) {
1086 StartBlockMap[*PI] = EntryBBCopy;
1087 EndBlockMap[*PI] = EntryBBCopy;
1088 }
1089
1090 // Iterate over all blocks in the region in a breadth-first search.
1091 std::deque<BasicBlock *> Blocks;
1092 SmallSetVector<BasicBlock *, 8> SeenBlocks;
1093 Blocks.push_back(EntryBB);
1094 SeenBlocks.insert(EntryBB);
1095
1096 while (!Blocks.empty()) {
1097 BasicBlock *BB = Blocks.front();
1098 Blocks.pop_front();
1099
1100 // First split the block and update dominance information.
1101 BasicBlock *BBCopy = splitBB(BB);
1102 BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1103
1104 // Get the mapping for this block and initialize it with either the scalar
1105 // loads from the generated entering block (which dominates all blocks of
1106 // this subregion) or the maps of the immediate dominator, if part of the
1107 // subregion. The latter necessarily includes the former.
1108 ValueMapT *InitBBMap;
1109 if (BBCopyIDom) {
1110 assert(RegionMaps.count(BBCopyIDom));
1111 InitBBMap = &RegionMaps[BBCopyIDom];
1112 } else
1113 InitBBMap = &EntryBBMap;
1114 auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1115 ValueMapT &RegionMap = Inserted.first->second;
1116
1117 // Copy the block with the BlockGenerator.
1118 Builder.SetInsertPoint(BBCopy, BBCopy->begin());
1119 copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1120
1121 // In order to remap PHI nodes we store also basic block mappings.
1122 StartBlockMap[BB] = BBCopy;
1123 EndBlockMap[BB] = Builder.GetInsertBlock();
1124
1125 // Add values to incomplete PHI nodes waiting for this block to be copied.
1126 for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1127 addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1128 IncompletePHINodeMap[BB].clear();
1129
1130 // And continue with new successors inside the region.
1131 for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1132 if (R->contains(*SI) && SeenBlocks.insert(*SI))
1133 Blocks.push_back(*SI);
1134
1135 // Remember value in case it is visible after this subregion.
1136 if (isDominatingSubregionExit(DT, R, BB))
1137 ValueMap.insert_range(RegionMap);
1138 }
1139
1140 // Now create a new dedicated region exit block and add it to the region map.
1141 BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1142 Builder.GetInsertPoint(), GenDT, GenLI);
1143 ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1144 StartBlockMap[R->getExit()] = ExitBBCopy;
1145 EndBlockMap[R->getExit()] = ExitBBCopy;
1146
1147 BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
1148 assert(ExitDomBBCopy &&
1149 "Common exit dominator must be within region; at least the entry node "
1150 "must match");
1151 GenDT->changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1152
1153 // As the block generator doesn't handle control flow we need to add the
1154 // region control flow by hand after all blocks have been copied.
1155 for (BasicBlock *BB : SeenBlocks) {
1156
1157 BasicBlock *BBCopyStart = StartBlockMap[BB];
1158 BasicBlock *BBCopyEnd = EndBlockMap[BB];
1159 Instruction *TI = BB->getTerminator();
1160 if (isa<UnreachableInst>(TI)) {
1161 while (!BBCopyEnd->empty())
1162 BBCopyEnd->begin()->eraseFromParent();
1163 new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1164 continue;
1165 }
1166
1167 Instruction *BICopy = BBCopyEnd->getTerminator();
1168
1169 ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1170 RegionMap.insert_range(StartBlockMap);
1171
1172 Builder.SetInsertPoint(BBCopyEnd, BICopy->getIterator());
1173 copyInstScalar(Stmt, TI, RegionMap, LTS);
1174 BICopy->eraseFromParent();
1175 }
1176
1177 // Add counting PHI nodes to all loops in the region that can be used as
1178 // replacement for SCEVs referring to the old loop.
1179 for (BasicBlock *BB : SeenBlocks) {
1180 Loop *L = LI.getLoopFor(BB);
1181 if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1182 continue;
1183
1184 BasicBlock *BBCopy = StartBlockMap[BB];
1185 Value *NullVal = Builder.getInt32(0);
1186 PHINode *LoopPHI =
1187 PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1188 Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1189 LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1190 LoopPHI->insertBefore(BBCopy->begin());
1191 LoopPHIInc->insertBefore(BBCopy->getTerminator()->getIterator());
1192
1193 for (auto *PredBB : predecessors(BB)) {
1194 if (!R->contains(PredBB))
1195 continue;
1196 if (L->contains(PredBB))
1197 LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1198 else
1199 LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1200 }
1201
1202 for (auto *PredBBCopy : predecessors(BBCopy))
1203 if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1204 LoopPHI->addIncoming(NullVal, PredBBCopy);
1205
1206 LTS[L] = SE.getUnknown(LoopPHI);
1207 }
1208
1209 // Continue generating code in the exit block.
1210 Builder.SetInsertPoint(ExitBBCopy, ExitBBCopy->getFirstInsertionPt());
1211
1212 // Write values visible to other statements.
1213 generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1214 StartBlockMap.clear();
1215 EndBlockMap.clear();
1216 RegionMaps.clear();
1217 IncompletePHINodeMap.clear();
1218}
1219
1221 ValueMapT &BBMap, Loop *L) {
1222 ScopStmt *Stmt = MA->getStatement();
1223 Region *SubR = Stmt->getRegion();
1224 auto Incoming = MA->getIncoming();
1225
1226 PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1227 PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1228 BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1229
1230 // This can happen if the subregion is simplified after the ScopStmts
1231 // have been created; simplification happens as part of CodeGeneration.
1232 if (OrigPHI->getParent() != SubR->getExit()) {
1233 BasicBlock *FormerExit = SubR->getExitingBlock();
1234 if (FormerExit)
1235 NewSubregionExit = StartBlockMap.lookup(FormerExit);
1236 }
1237
1238 PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1239 "polly." + OrigPHI->getName(),
1240 NewSubregionExit->getFirstNonPHIIt());
1241
1242 // Add the incoming values to the PHI.
1243 for (auto &Pair : Incoming) {
1244 BasicBlock *OrigIncomingBlock = Pair.first;
1245 BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1246 BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1247 Builder.SetInsertPoint(NewIncomingBlockEnd,
1248 NewIncomingBlockEnd->getTerminator()->getIterator());
1249 assert(RegionMaps.count(NewIncomingBlockStart));
1250 assert(RegionMaps.count(NewIncomingBlockEnd));
1251 ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1252
1253 Value *OrigIncomingValue = Pair.second;
1254 Value *NewIncomingValue =
1255 getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1256 NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1257 }
1258
1259 return NewPHI;
1260}
1261
1263 ValueMapT &BBMap) {
1264 ScopStmt *Stmt = MA->getStatement();
1265
1266 // TODO: Add some test cases that ensure this is really the right choice.
1267 Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1268
1269 if (MA->isAnyPHIKind()) {
1270 auto Incoming = MA->getIncoming();
1271 assert(!Incoming.empty() &&
1272 "PHI WRITEs must have originate from at least one incoming block");
1273
1274 // If there is only one incoming value, we do not need to create a PHI.
1275 if (Incoming.size() == 1) {
1276 Value *OldVal = Incoming[0].second;
1277 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1278 }
1279
1280 return buildExitPHI(MA, LTS, BBMap, L);
1281 }
1282
1283 // MemoryKind::Value accesses leaving the subregion must dominate the exit
1284 // block; just pass the copied value.
1285 Value *OldVal = MA->getAccessValue();
1286 return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1287}
1288
1290 ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1291 __isl_keep isl_id_to_ast_expr *NewAccesses) {
1292 assert(Stmt.getRegion() &&
1293 "Block statements need to use the generateScalarStores() "
1294 "function in the BlockGenerator");
1295
1296 // Get the exit scalar values before generating the writes.
1297 // This is necessary because RegionGenerator::getExitScalar may insert
1298 // PHINodes that depend on the region's exiting blocks. But
1299 // BlockGenerator::generateConditionalExecution may insert a new basic block
1300 // such that the current basic block is not a direct successor of the exiting
1301 // blocks anymore. Hence, build the PHINodes while the current block is still
1302 // the direct successor.
1303 SmallDenseMap<MemoryAccess *, Value *> NewExitScalars;
1304 for (MemoryAccess *MA : Stmt) {
1305 if (MA->isOriginalArrayKind() || MA->isRead())
1306 continue;
1307
1308 Value *NewVal = getExitScalar(MA, LTS, BBMap);
1309 NewExitScalars[MA] = NewVal;
1310 }
1311
1312 for (MemoryAccess *MA : Stmt) {
1313 if (MA->isOriginalArrayKind() || MA->isRead())
1314 continue;
1315
1316 isl::set AccDom = MA->getAccessRelation().domain();
1317 std::string Subject = MA->getId().get_name();
1319 Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1320 Value *NewVal = NewExitScalars.lookup(MA);
1321 assert(NewVal && "The exit scalar must be determined before");
1322 Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1323 BBMap, NewAccesses);
1324 assert((!isa<Instruction>(NewVal) ||
1325 GenDT->dominates(cast<Instruction>(NewVal)->getParent(),
1326 Builder.GetInsertBlock())) &&
1327 "Domination violation");
1328 assert((!isa<Instruction>(Address) ||
1329 GenDT->dominates(cast<Instruction>(Address)->getParent(),
1330 Builder.GetInsertBlock())) &&
1331 "Domination violation");
1332 Builder.CreateStore(NewVal, Address);
1333 });
1334 }
1335}
1336
1338 PHINode *PHICopy, BasicBlock *IncomingBB,
1339 LoopToScevMapT &LTS) {
1340 // If the incoming block was not yet copied mark this PHI as incomplete.
1341 // Once the block will be copied the incoming value will be added.
1342 BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1343 BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1344 if (!BBCopyStart) {
1345 assert(!BBCopyEnd);
1346 assert(Stmt.represents(IncomingBB) &&
1347 "Bad incoming block for PHI in non-affine region");
1348 IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1349 return;
1350 }
1351
1352 assert(RegionMaps.count(BBCopyStart) &&
1353 "Incoming PHI block did not have a BBMap");
1354 ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1355
1356 Value *OpCopy = nullptr;
1357
1358 if (Stmt.represents(IncomingBB)) {
1359 Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1360
1361 // If the current insert block is different from the PHIs incoming block
1362 // change it, otherwise do not.
1363 auto IP = Builder.GetInsertPoint();
1364 if (IP->getParent() != BBCopyEnd)
1365 Builder.SetInsertPoint(BBCopyEnd,
1366 BBCopyEnd->getTerminator()->getIterator());
1367 OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1368 if (IP->getParent() != BBCopyEnd)
1369 Builder.SetInsertPoint(IP);
1370 } else {
1371 // All edges from outside the non-affine region become a single edge
1372 // in the new copy of the non-affine region. Make sure to only add the
1373 // corresponding edge the first time we encounter a basic block from
1374 // outside the non-affine region.
1375 if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1376 return;
1377
1378 // Get the reloaded value.
1379 OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1380 }
1381
1382 assert(OpCopy && "Incoming PHI value was not copied properly");
1383 PHICopy->addIncoming(OpCopy, BBCopyEnd);
1384}
1385
1387 ValueMapT &BBMap,
1388 LoopToScevMapT &LTS) {
1389 unsigned NumIncoming = PHI->getNumIncomingValues();
1390 PHINode *PHICopy =
1391 Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1392 PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHIIt());
1393 BBMap[PHI] = PHICopy;
1394
1395 for (BasicBlock *IncomingBB : PHI->blocks())
1396 addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1397}
static cl::opt< bool > Aligned("enable-polly-aligned", cl::desc("Assumed aligned memory accesses."), cl::Hidden, cl::cat(PollyCategory))
static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R, BasicBlock *BB)
static BasicBlock * findExitDominator(DominatorTree &DT, Region *R)
static cl::opt< bool, true > TraceStmtsX("polly-codegen-trace-stmts", cl::desc("Add printf calls that print the statement being executed"), cl::location(TraceStmts), cl::Hidden, cl::cat(PollyCategory))
static cl::opt< bool, true > DebugPrintingX("polly-codegen-add-debug-printing", cl::desc("Add printf calls that show the values loaded/stored."), cl::location(PollyDebugPrinting), cl::Hidden, cl::cat(PollyCategory))
static std::string getInstName(Value *Val)
static cl::opt< bool > TraceScalars("polly-codegen-trace-scalars", cl::desc("Add printf calls that print the values of all scalar values " "used in a statement. Requires -polly-codegen-trace-stmts."), cl::Hidden, cl::cat(PollyCategory))
llvm::cl::OptionCategory PollyCategory
bool TraceStmts
bool PollyDebugPrinting
__isl_give isl_ast_expr * isl_ast_expr_address_of(__isl_take isl_ast_expr *expr)
Definition isl_ast.c:649
isl::checked::union_map get_schedule() const
isl::checked::ast_expr expr_from(isl::checked::pw_aff pa) const
__isl_give isl_ast_expr * copy() const &
bool is_false() const
Definition cpp-checked.h:76
__isl_give isl_id * release()
std::string get_name() const
isl::checked::map reverse() const
isl::checked::set range() const
isl::checked::set domain() const
boolean is_empty() const
isl::checked::pw_aff at(int pos) const
isl::checked::set intersect_params(isl::checked::set params) const
boolean is_subset(const isl::checked::set &set2) const
isl::checked::set apply(isl::checked::map map) const
isl::checked::union_map intersect_domain(isl::checked::space space) const
boolean is_empty() const
static isl::map from_union_map(isl::union_map umap)
static isl::pw_multi_aff from_map(isl::map map)
Loop * getLoopForStmt(const ScopStmt &Stmt) const
Get the innermost loop that surrounds the statement Stmt.
EscapeUsersAllocaMapTy & EscapeMap
Map from instructions to their escape users as well as the alloca.
Value * getImplicitAddress(MemoryAccess &Access, Loop *L, LoopToScevMapT &LTS, ValueMapT &BBMap, __isl_keep isl_id_to_ast_expr *NewAccesses)
Generate the pointer value that is accesses by Access.
DominatorTree & DT
The dominator tree of this function.
BasicBlock * splitBB(BasicBlock *BB)
Split BB to create a new one we can use to clone BB in.
void generateBeginStmtTrace(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap)
When statement tracing is enabled, build the print instructions for printing the current statement in...
Value * trySynthesizeNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap, LoopToScevMapT &LTS, Loop *L) const
Try to synthesize a new value.
void generateScalarLoads(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap, __isl_keep isl_id_to_ast_expr *NewAccesses)
Generate reload of scalars demoted to memory and needed by Stmt.
AllocaMapTy & ScalarMap
Map to resolve scalar dependences for PHI operands and scalars.
PollyIRBuilder & Builder
DenseMap< const ScopArrayInfo *, AssertingVH< AllocaInst > > AllocaMapTy
Map types to resolve scalar dependences.
void createExitPHINodeMerges(Scop &S)
Create exit PHI node merges for PHI nodes with more than two edges from inside the scop.
void copyInstScalar(ScopStmt &Stmt, Instruction *Inst, ValueMapT &BBMap, LoopToScevMapT &LTS)
Value * generateArrayLoad(ScopStmt &Stmt, LoadInst *load, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Value * buildContainsCondition(ScopStmt &Stmt, const isl::set &Subdomain)
Generate instructions that compute whether one instance of Set is executed.
void finalizeSCoP(Scop &S)
Finalize the code generation for the SCoP S.
void createScalarInitialization(Scop &S)
Initialize the memory of demoted scalars.
SmallVector< Instruction *, 4 > EscapeUserVectorTy
Simple vector of instructions to store escape users.
bool canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst)
Helper to determine if Inst can be synthesized in Stmt.
virtual void generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap, __isl_keep isl_id_to_ast_expr *NewAccesses)
Generate the scalar stores for the given statement.
ScalarEvolution & SE
IslExprBuilder * ExprBuilder
void handleOutsideUsers(const Scop &S, ScopArrayInfo *Array)
Handle users of Array outside the SCoP.
void createScalarFinalization(Scop &S)
Promote the values of demoted scalars after the SCoP.
void switchGeneratedFunc(Function *GenFn, DominatorTree *GenDT, LoopInfo *GenLI, ScalarEvolution *GenSE)
Change the function that code is emitted into.
Value * getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap, LoopToScevMapT &LTS, Loop *L) const
Get the new version of a value.
ValueMapT & GlobalMap
A map from llvm::Values referenced in the old code to a new set of llvm::Values, which is used to rep...
void findOutsideUsers(Scop &S)
Find scalar statements that have outside users.
void generateArrayStore(ScopStmt &Stmt, StoreInst *store, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
DominatorTree * GenDT
Relates to the region where the code is emitted into.
MapVector< Instruction *, std::pair< AssertingVH< Value >, EscapeUserVectorTy > > EscapeUsersAllocaMapTy
Map type to resolve escaping users for scalar instructions.
BasicBlock * copyBB(ScopStmt &Stmt, BasicBlock *BB, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Copy the given basic block.
virtual void copyPHIInstruction(ScopStmt &, PHINode *, ValueMapT &, LoopToScevMapT &)
Copy a single PHI instruction.
void copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Copy the basic block.
BasicBlock * StartBlock
The first basic block after the RTC.
void copyInstruction(ScopStmt &Stmt, Instruction *Inst, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Copy a single Instruction.
void invalidateScalarEvolution(Scop &S)
Invalidate the scalar evolution expressions for a scop.
BlockGenerator(PollyIRBuilder &Builder, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT, AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap, ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock)
Create a generator for basic blocks.
ScalarEvolution * GenSE
void removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap)
Remove dead instructions generated for BB.
Value * generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst, ValueMapT &BBMap, LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses)
Generate the operand address.
Value * getOrCreateAlloca(const MemoryAccess &Access)
Return the alloca for Access.
void generateConditionalExecution(ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject, const std::function< void()> &GenThenFunc)
Generate code that executes in a subset of Stmt's domain.
LLVM-IR generator for isl_ast_expr[essions].
Utility proxy to wrap the common members of LoadInst and StoreInst.
Definition ScopHelper.h:141
bool isNull() const
Definition ScopHelper.h:306
llvm::Value * getPointerOperand() const
Definition ScopHelper.h:249
Represent memory accesses in statements.
Definition ScopInfo.h:427
const ScopArrayInfo * getLatestScopArrayInfo() const
Get the ScopArrayInfo object for the base address, or the one set by setNewAccessRelation().
Definition ScopInfo.cpp:557
bool isAnyPHIKind() const
Old name of isOriginalAnyPHIKind().
Definition ScopInfo.h:1024
bool isLatestArrayKind() const
Whether storage memory is either an custom .s2a/.phiops alloca (false) or an existing pointer into an...
Definition ScopInfo.h:946
Instruction * getAccessInstruction() const
Return the access instruction of this memory access.
Definition ScopInfo.h:881
isl::id getId() const
Get identifier for the memory access.
Definition ScopInfo.cpp:914
ArrayRef< std::pair< BasicBlock *, Value * > > getIncoming() const
Return the list of possible PHI/ExitPHI values.
Definition ScopInfo.h:744
ScopStmt * getStatement() const
Get the statement that contains this memory access.
Definition ScopInfo.h:1027
isl::map getAccessRelation() const
Old name of getLatestAccessRelation().
Definition ScopInfo.h:791
Value * getAccessValue() const
Return the access value of this memory access.
Definition ScopInfo.h:863
std::pair< PHINode *, PHINode * > PHINodePairTy
Mapping to remember PHI nodes that still need incoming values.
void copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS, __isl_keep isl_id_to_ast_expr *IdToAstExp)
Copy the region statement Stmt.
DenseMap< BasicBlock *, SmallVector< PHINodePairTy, 4 > > IncompletePHINodeMap
void addOperandToPHI(ScopStmt &Stmt, PHINode *PHI, PHINode *PHICopy, BasicBlock *IncomingBB, LoopToScevMapT &LTS)
Add the new operand from the copy of IncomingBB to PHICopy.
void copyPHIInstruction(ScopStmt &Stmt, PHINode *Inst, ValueMapT &BBMap, LoopToScevMapT &LTS) override
Copy a single PHI instruction.
DenseMap< BasicBlock *, BasicBlock * > EndBlockMap
A map from old to the last new block in the region, that was created to model the old basic block.
Value * getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS, ValueMapT &BBMap)
DenseMap< BasicBlock *, BasicBlock * > StartBlockMap
A map from old to the first new block in the region, that was created to model the old basic block.
void generateScalarStores(ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMAp, __isl_keep isl_id_to_ast_expr *NewAccesses) override
Generate the scalar stores for the given statement.
DenseMap< BasicBlock *, ValueMapT > RegionMaps
The "BBMaps" for the whole region (one for each block).
PHINode * buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS, ValueMapT &BBMap, Loop *L)
Create a PHI that combines the incoming values from all incoming blocks that are in the subregion.
BasicBlock * repairDominance(BasicBlock *BB, BasicBlock *BBCopy)
Repair the dominance tree after we created a copy block for BB.
A class to store information about arrays in the SCoP.
Definition ScopInfo.h:215
Statement of the Scop.
Definition ScopInfo.h:1136
MemoryAccess & getArrayAccessFor(const Instruction *Inst) const
Return the only array access for Inst.
Definition ScopInfo.h:1430
Scop * getParent()
Definition ScopInfo.h:1524
BasicBlock * getEntryBlock() const
Return a BasicBlock from this statement.
const std::vector< Instruction * > & getInstructions() const
Definition ScopInfo.h:1527
bool isBlockStmt() const
Return true if this statement represents a single basic block.
Definition ScopInfo.h:1317
Region * getRegion() const
Get the region represented by this ScopStmt (if any).
Definition ScopInfo.h:1326
bool represents(BasicBlock *BB) const
Return whether this statement represents BB.
Definition ScopInfo.h:1347
iterator_range< std::vector< Instruction * >::const_iterator > insts() const
The range of instructions in this statement.
Definition ScopInfo.h:1546
BasicBlock * getBasicBlock() const
Get the BasicBlock represented by this ScopStmt (if any).
Definition ScopInfo.h:1314
const char * getBaseName() const
isl::ast_build getAstBuild() const
Get the isl AST build.
Definition ScopInfo.h:1561
MemoryAccess * getArrayAccessOrNULLFor(const Instruction *Inst) const
Return the only array access for Inst, if existing.
Definition ScopInfo.h:1407
bool isRegionStmt() const
Return true if this statement represents a whole region.
Definition ScopInfo.h:1329
isl::set getDomain() const
Get the iteration domain of this ScopStmt.
Static Control Part.
Definition ScopInfo.h:1626
isl::set getBestKnownDefinedBehaviorContext() const
Return the define behavior context, or if not available, its approximation from all other contexts.
Definition ScopInfo.h:2170
isl::set getContext() const
Get the constraint on parameter of this Scop.
static VirtualUse create(Scop *S, const Use &U, LoopInfo *LI, bool Virtual)
Get a VirtualUse for an llvm::Use.
#define __isl_take
Definition ctx.h:23
#define __isl_keep
Definition ctx.h:26
B()
#define assert(exp)
llvm::Value * expandCodeFor(Scop &S, llvm::ScalarEvolution &SE, llvm::Function *GenFn, llvm::ScalarEvolution &GenSE, const llvm::DataLayout &DL, const char *Name, const llvm::SCEV *E, llvm::Type *Ty, llvm::BasicBlock::iterator IP, ValueMapT *VMap, LoopToScevMapT *LoopMap, llvm::BasicBlock *RTCBB)
Wrapper for SCEVExpander extended to all Polly features.
@ Array
MemoryKind::Array: Models a one or multi-dimensional array.
Definition ScopInfo.h:111
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:150
@ PHI
MemoryKind::PHI: Models PHI nodes within the SCoP.
Definition ScopInfo.h:187
llvm::iota_range< unsigned > rangeIslSize(unsigned Begin, isl::size End)
Check that End is valid and return an iterator from Begin to End.
Definition ISLTools.cpp:597
llvm::IRBuilder< llvm::ConstantFolder, IRInserter > PollyIRBuilder
Definition IRBuilder.h:143
llvm::DenseMap< const llvm::Loop *, llvm::SCEVUse > LoopToScevMapT
Same as llvm/Analysis/ScalarEvolutionExpressions.h.
Definition ScopHelper.h:41
llvm::DenseMap< llvm::AssertingVH< llvm::Value >, llvm::AssertingVH< llvm::Value > > ValueMapT
Type to remap values.
Definition ScopHelper.h:106
bool isIgnoredIntrinsic(const llvm::Value *V)
Return true iff V is an intrinsic that we ignore during code generation.
bool canSynthesize(const llvm::Value *V, const Scop &S, llvm::ScalarEvolution *SE, llvm::Loop *Scope)
Check whether a value an be synthesized by the code generator.
static void createCPUPrinter(PollyIRBuilder &Builder, Args... args)
Print a set of LLVM-IR Values or StringRefs via printf.
static bool isPrintable(llvm::Type *Ty)
Return whether an llvm::Value of the type Ty is printable for debugging.
static llvm::Value * getPrintableString(PollyIRBuilder &Builder, llvm::StringRef Str)
Generate a constant string into the builder's llvm::Module which can be passed to createCPUPrinter().
static TupleKindPtr Domain("Domain")