Polly 23.0.0git
ScopHelper.cpp
Go to the documentation of this file.
1//===- ScopHelper.cpp - Some Helper Functions for Scop. ------------------===//
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// Small functions that help with Scop and LLVM-IR.
10//
11//===----------------------------------------------------------------------===//
12
14#include "polly/Options.h"
15#include "polly/ScopInfo.h"
17#include "llvm/Analysis/LoopInfo.h"
18#include "llvm/Analysis/RegionInfo.h"
19#include "llvm/Analysis/ScalarEvolution.h"
20#include "llvm/Analysis/ScalarEvolutionExpressions.h"
21#include "llvm/Transforms/Utils/BasicBlockUtils.h"
22#include "llvm/Transforms/Utils/LoopUtils.h"
23#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
24#include <optional>
25
26using namespace llvm;
27using namespace polly;
28
29#define DEBUG_TYPE "polly-scop-helper"
30
31static cl::list<std::string> DebugFunctions(
32 "polly-debug-func",
33 cl::desc("Allow calls to the specified functions in SCoPs even if their "
34 "side-effects are unknown. This can be used to do debug output in "
35 "Polly-transformed code."),
36 cl::Hidden, cl::CommaSeparated, cl::cat(PollyCategory));
37
38// Ensures that there is just one predecessor to the entry node from outside the
39// region.
40// The identity of the region entry node is preserved.
41static void simplifyRegionEntry(Region *R, DominatorTree *DT, LoopInfo *LI,
42 RegionInfo *RI) {
43 BasicBlock *EnteringBB = R->getEnteringBlock();
44 BasicBlock *Entry = R->getEntry();
45
46 // Before (one of):
47 //
48 // \ / //
49 // EnteringBB //
50 // | \------> //
51 // \ / | //
52 // Entry <--\ Entry <--\ //
53 // / \ / / \ / //
54 // .... .... //
55
56 // Create single entry edge if the region has multiple entry edges.
57 if (!EnteringBB) {
58 SmallVector<BasicBlock *, 4> Preds;
59 for (BasicBlock *P : predecessors(Entry))
60 if (!R->contains(P))
61 Preds.push_back(P);
62
63 BasicBlock *NewEntering =
64 SplitBlockPredecessors(Entry, Preds, ".region_entering", DT, LI);
65
66 if (RI) {
67 // The exit block of predecessing regions must be changed to NewEntering
68 for (BasicBlock *ExitPred : predecessors(NewEntering)) {
69 Region *RegionOfPred = RI->getRegionFor(ExitPred);
70 if (RegionOfPred->getExit() != Entry)
71 continue;
72
73 while (!RegionOfPred->isTopLevelRegion() &&
74 RegionOfPred->getExit() == Entry) {
75 RegionOfPred->replaceExit(NewEntering);
76 RegionOfPred = RegionOfPred->getParent();
77 }
78 }
79
80 // Make all ancestors use EnteringBB as entry; there might be edges to it
81 Region *AncestorR = R->getParent();
82 RI->setRegionFor(NewEntering, AncestorR);
83 while (!AncestorR->isTopLevelRegion() && AncestorR->getEntry() == Entry) {
84 AncestorR->replaceEntry(NewEntering);
85 AncestorR = AncestorR->getParent();
86 }
87 }
88
89 EnteringBB = NewEntering;
90 }
91 assert(R->getEnteringBlock() == EnteringBB);
92
93 // After:
94 //
95 // \ / //
96 // EnteringBB //
97 // | //
98 // | //
99 // Entry <--\ //
100 // / \ / //
101 // .... //
102}
103
104// Ensure that the region has a single block that branches to the exit node.
105static void simplifyRegionExit(Region *R, DominatorTree *DT, LoopInfo *LI,
106 RegionInfo *RI) {
107 BasicBlock *ExitBB = R->getExit();
108 BasicBlock *ExitingBB = R->getExitingBlock();
109
110 // Before:
111 //
112 // (Region) ______/ //
113 // \ | / //
114 // ExitBB //
115 // / \ //
116
117 if (!ExitingBB) {
118 SmallVector<BasicBlock *, 4> Preds;
119 for (BasicBlock *P : predecessors(ExitBB))
120 if (R->contains(P))
121 Preds.push_back(P);
122
123 // Preds[0] Preds[1] otherBB //
124 // \ | ________/ //
125 // \ | / //
126 // BB //
127 ExitingBB =
128 SplitBlockPredecessors(ExitBB, Preds, ".region_exiting", DT, LI);
129 // Preds[0] Preds[1] otherBB //
130 // \ / / //
131 // BB.region_exiting / //
132 // \ / //
133 // BB //
134
135 if (RI)
136 RI->setRegionFor(ExitingBB, R);
137
138 // Change the exit of nested regions, but not the region itself,
139 R->replaceExitRecursive(ExitingBB);
140 R->replaceExit(ExitBB);
141 }
142 assert(ExitingBB == R->getExitingBlock());
143
144 // After:
145 //
146 // \ / //
147 // ExitingBB _____/ //
148 // \ / //
149 // ExitBB //
150 // / \ //
151}
152
153void polly::simplifyRegion(Region *R, DominatorTree *DT, LoopInfo *LI,
154 RegionInfo *RI) {
155 assert(R && !R->isTopLevelRegion());
156 assert(!RI || RI == R->getRegionInfo());
157 assert((!RI || DT) &&
158 "RegionInfo requires DominatorTree to be updated as well");
159
160 simplifyRegionEntry(R, DT, LI, RI);
161 simplifyRegionExit(R, DT, LI, RI);
162 assert(R->isSimple());
163}
164
165// Split the block into two successive blocks.
166//
167// Like llvm::SplitBlock, but also preserves RegionInfo
168static BasicBlock *splitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt,
169 DominatorTree *DT, llvm::LoopInfo *LI,
170 RegionInfo *RI) {
171 assert(Old);
172
173 // Before:
174 //
175 // \ / //
176 // Old //
177 // / \ //
178
179 BasicBlock *NewBlock = llvm::SplitBlock(Old, SplitPt, DT, LI);
180
181 if (RI) {
182 Region *R = RI->getRegionFor(Old);
183 RI->setRegionFor(NewBlock, R);
184 }
185
186 // After:
187 //
188 // \ / //
189 // Old //
190 // | //
191 // NewBlock //
192 // / \ //
193
194 return NewBlock;
195}
196
197void polly::splitEntryBlockForAlloca(BasicBlock *EntryBlock, DominatorTree *DT,
198 LoopInfo *LI, RegionInfo *RI) {
199 // Find first non-alloca instruction. Every basic block has a non-alloca
200 // instruction, as every well formed basic block has a terminator.
201 BasicBlock::iterator I = EntryBlock->begin();
202 while (isa<AllocaInst>(I))
203 ++I;
204
205 // splitBlock updates DT, LI and RI.
206 splitBlock(EntryBlock, I, DT, LI, RI);
207}
208
211 DebugLoc Loc, polly::AssumptionSign Sign,
212 BasicBlock *BB, bool RTC) {
213 assert((Set.is_params() || BB) &&
214 "Assumptions without a basic block must be parameter sets");
215 if (RecordedAssumptions)
216 RecordedAssumptions->push_back({Kind, Sign, Set, Loc, BB, RTC});
217}
218
219/// ScopExpander generates IR the the value of a SCEV that represents a value
220/// from a SCoP.
221///
222/// IMPORTANT: There are two ScalarEvolutions at play here. First, the SE that
223/// was used to analyze the original SCoP (not actually referenced anywhere
224/// here, but passed as argument to make the distinction clear). Second, GenSE
225/// which is the SE for the function that the code is emitted into. SE and GenSE
226/// may be different when the generated code is to be emitted into an outlined
227/// function, e.g. for a parallel loop. That is, each SCEV is to be used only by
228/// the SE that "owns" it and ScopExpander handles the translation between them.
229/// The SCEVVisitor methods are only to be called on SCEVs of the original SE.
230/// Their job is to create a new SCEV for GenSE. The nested SCEVExpander is to
231/// be used only with SCEVs belonging to GenSE. Currently SCEVs do not store a
232/// reference to the ScalarEvolution they belong to, so a mixup does not
233/// immediately cause a crash but certainly is a violation of its interface.
234///
235/// The SCEVExpander will __not__ generate any code for an existing SDiv/SRem
236/// instruction but just use it, if it is referenced as a SCEVUnknown. We want
237/// however to generate new code if the instruction is in the analyzed region
238/// and we generate code outside/in front of that region. Hence, we generate the
239/// code for the SDiv/SRem operands in front of the analyzed region and then
240/// create a new SDiv/SRem operation there too.
241struct ScopExpander final : SCEVVisitor<ScopExpander, const SCEV *> {
242 friend struct SCEVVisitor<ScopExpander, const SCEV *>;
243
244 explicit ScopExpander(const Region &R, ScalarEvolution &SE, Function *GenFn,
245 ScalarEvolution &GenSE, const char *Name,
247 BasicBlock *RTCBB)
248 : Expander(GenSE, Name, /*PreserveLCSSA=*/false), Name(Name), R(R),
250 }
251
252 Value *expandCodeFor(const SCEV *E, Type *Ty, BasicBlock::iterator IP) {
253 assert(isInGenRegion(&*IP) &&
254 "ScopExpander assumes to be applied to generated code region");
255 const SCEV *GenE = visit(E);
256 return Expander.expandCodeFor(GenE, Ty, IP);
257 }
258
259 const SCEV *visit(const SCEV *E) {
260 // Cache the expansion results for intermediate SCEV expressions. A SCEV
261 // expression can refer to an operand multiple times (e.g. "x*x), so
262 // a naive visitor takes exponential time.
263 if (SCEVCache.count(E))
264 return SCEVCache[E];
265 const SCEV *Result = SCEVVisitor::visit(E);
266 SCEVCache[E] = Result;
267 return Result;
268 }
269
270private:
271 SCEVExpander Expander;
272 const char *Name;
273 const Region &R;
276 BasicBlock *RTCBB;
277 DenseMap<const SCEV *, const SCEV *> SCEVCache;
278
279 ScalarEvolution &GenSE;
280 Function *GenFn;
281
282 /// Is the instruction part of the original SCoP (in contrast to be located in
283 /// the code-generated region)?
284 bool isInOrigRegion(Instruction *Inst) {
285 Function *Fn = R.getEntry()->getParent();
286 bool isInOrigRegion = Inst->getFunction() == Fn && R.contains(Inst);
287 assert((isInOrigRegion || GenFn == Inst->getFunction()) &&
288 "Instruction expected to be either in the SCoP or the translated "
289 "region");
290 return isInOrigRegion;
291 }
292
293 bool isInGenRegion(Instruction *Inst) { return !isInOrigRegion(Inst); }
294
295 const SCEV *visitGenericInst(const SCEVUnknown *E, Instruction *Inst,
296 BasicBlock::iterator IP) {
297 if (!Inst || isInGenRegion(Inst))
298 return E;
299
300 assert(!Inst->mayThrow() && !Inst->mayReadOrWriteMemory() &&
301 !isa<PHINode>(Inst));
302
303 auto *InstClone = Inst->clone();
304 for (auto &Op : Inst->operands()) {
305 assert(GenSE.isSCEVable(Op->getType()));
306 const SCEV *OpSCEV = GenSE.getSCEV(Op);
307 auto *OpClone = expandCodeFor(OpSCEV, Op->getType(), IP);
308 InstClone->replaceUsesOfWith(Op, OpClone);
309 }
310
311 InstClone->setName(Name + Inst->getName());
312 InstClone->insertBefore(IP);
313 return GenSE.getSCEV(InstClone);
314 }
315
316 const SCEV *visitUnknown(const SCEVUnknown *E) {
317
318 // If a value mapping was given try if the underlying value is remapped.
319 Value *NewVal = VMap ? VMap->lookup(E->getValue()) : nullptr;
320 if (NewVal) {
321 const SCEV *NewE = GenSE.getSCEV(NewVal);
322
323 // While the mapped value might be different the SCEV representation might
324 // not be. To this end we will check before we go into recursion here.
325 // FIXME: SCEVVisitor must only visit SCEVs that belong to the original
326 // SE. This calls it on SCEVs that belong GenSE.
327 if (E != NewE)
328 return visit(NewE);
329 }
330
331 Instruction *Inst = dyn_cast<Instruction>(E->getValue());
332 BasicBlock::iterator IP;
333 if (Inst && isInGenRegion(Inst))
334 IP = Inst->getIterator();
335 else if (R.getEntry()->getParent() != GenFn) {
336 // RTCBB is in the original function, but we are generating for a
337 // subfunction so we cannot emit to RTCBB. Usually, we land here only
338 // because E->getValue() is not an instruction but a global or constant
339 // which do not need to emit anything.
340 IP = GenFn->getEntryBlock().getTerminator()->getIterator();
341 } else if (Inst && RTCBB->getParent() == Inst->getFunction())
342 IP = RTCBB->getTerminator()->getIterator();
343 else
344 IP = RTCBB->getParent()->getEntryBlock().getTerminator()->getIterator();
345
346 if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
347 Inst->getOpcode() != Instruction::SDiv))
348 return visitGenericInst(E, Inst, IP);
349
350 const SCEV *LHSScev = GenSE.getSCEV(Inst->getOperand(0));
351 const SCEV *RHSScev = GenSE.getSCEV(Inst->getOperand(1));
352
353 if (!GenSE.isKnownNonZero(RHSScev))
354 RHSScev = GenSE.getUMaxExpr(RHSScev, GenSE.getConstant(E->getType(), 1));
355
356 Value *LHS = expandCodeFor(LHSScev, E->getType(), IP);
357 Value *RHS = expandCodeFor(RHSScev, E->getType(), IP);
358
359 Inst = BinaryOperator::Create((Instruction::BinaryOps)Inst->getOpcode(),
360 LHS, RHS, Inst->getName() + Name, IP);
361 return GenSE.getSCEV(Inst);
362 }
363
364 /// The following functions will just traverse the SCEV and rebuild it using
365 /// GenSE and the new operands returned by the traversal.
366 ///
367 ///{
368 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
369 const SCEV *visitVScale(const SCEVVScale *E) { return E; }
370 const SCEV *visitPtrToAddrExpr(const SCEVPtrToAddrExpr *E) {
371 return GenSE.getPtrToAddrExpr(visit(E->getOperand()));
372 }
373 const SCEV *visitPtrToIntExpr(const SCEVPtrToIntExpr *E) {
374 return GenSE.getPtrToIntExpr(visit(E->getOperand()), E->getType());
375 }
376 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
377 return GenSE.getTruncateExpr(visit(E->getOperand()), E->getType());
378 }
379 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
380 return GenSE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
381 }
382 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
383 return GenSE.getSignExtendExpr(visit(E->getOperand()), E->getType());
384 }
385 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
386 auto *RHSScev = visit(E->getRHS());
387 if (!GenSE.isKnownNonZero(RHSScev))
388 RHSScev = GenSE.getUMaxExpr(RHSScev, GenSE.getConstant(E->getType(), 1));
389 return GenSE.getUDivExpr(visit(E->getLHS()), RHSScev);
390 }
391 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
392 SmallVector<const SCEV *, 4> NewOps;
393 for (const SCEV *Op : E->operands())
394 NewOps.push_back(visit(Op));
395 return GenSE.getAddExpr(NewOps);
396 }
397 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
398 SmallVector<const SCEV *, 4> NewOps;
399 for (const SCEV *Op : E->operands())
400 NewOps.push_back(visit(Op));
401 return GenSE.getMulExpr(NewOps);
402 }
403 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
404 SmallVector<const SCEV *, 4> NewOps;
405 for (const SCEV *Op : E->operands())
406 NewOps.push_back(visit(Op));
407 return GenSE.getUMaxExpr(NewOps);
408 }
409 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
410 SmallVector<const SCEV *, 4> NewOps;
411 for (const SCEV *Op : E->operands())
412 NewOps.push_back(visit(Op));
413 return GenSE.getSMaxExpr(NewOps);
414 }
415 const SCEV *visitUMinExpr(const SCEVUMinExpr *E) {
416 SmallVector<const SCEV *, 4> NewOps;
417 for (const SCEV *Op : E->operands())
418 NewOps.push_back(visit(Op));
419 return GenSE.getUMinExpr(NewOps);
420 }
421 const SCEV *visitSMinExpr(const SCEVSMinExpr *E) {
422 SmallVector<const SCEV *, 4> NewOps;
423 for (const SCEV *Op : E->operands())
424 NewOps.push_back(visit(Op));
425 return GenSE.getSMinExpr(NewOps);
426 }
427 const SCEV *visitSequentialUMinExpr(const SCEVSequentialUMinExpr *E) {
428 SmallVector<const SCEV *, 4> NewOps;
429 for (const SCEV *Op : E->operands())
430 NewOps.push_back(visit(Op));
431 return GenSE.getUMinExpr(NewOps, /*Sequential=*/true);
432 }
433 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
434 SmallVector<const SCEV *, 4> NewOps;
435 for (const SCEV *Op : E->operands())
436 NewOps.push_back(visit(Op));
437
438 const Loop *L = E->getLoop();
439 const SCEV *GenLRepl = LoopMap ? LoopMap->lookup(L) : nullptr;
440 if (!GenLRepl)
441 return GenSE.getAddRecExpr(NewOps, L, E->getNoWrapFlags());
442
443 // evaluateAtIteration replaces the SCEVAddrExpr with a direct calculation.
444 const SCEV *Evaluated =
445 SCEVAddRecExpr::evaluateAtIteration(NewOps, GenLRepl, GenSE);
446
447 // FIXME: This emits a SCEV for GenSE (since GenLRepl will refer to the
448 // induction variable of a generated loop), so we should not use SCEVVisitor
449 // with it. However, it still contains references to the SCoP region.
450 return visit(Evaluated);
451 }
452 ///}
453};
454
455Value *polly::expandCodeFor(Scop &S, llvm::ScalarEvolution &SE,
456 llvm::Function *GenFn, ScalarEvolution &GenSE,
457 const DataLayout &DL, const char *Name,
458 const SCEV *E, Type *Ty, BasicBlock::iterator IP,
459 ValueMapT *VMap, LoopToScevMapT *LoopMap,
460 BasicBlock *RTCBB) {
461 ScopExpander Expander(S.getRegion(), SE, GenFn, GenSE, Name, VMap, LoopMap,
462 RTCBB);
463 return Expander.expandCodeFor(E, Ty, IP);
464}
465
467 if (BranchInst *BR = dyn_cast<BranchInst>(TI)) {
468 if (BR->isUnconditional())
469 return ConstantInt::getTrue(Type::getInt1Ty(TI->getContext()));
470
471 return BR->getCondition();
472 }
473
474 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
475 return SI->getCondition();
476
477 return nullptr;
478}
479
480Loop *polly::getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
481 // Start with the smallest loop containing the entry and expand that
482 // loop until it contains all blocks in the region. If there is a loop
483 // containing all blocks in the region check if it is itself contained
484 // and if so take the parent loop as it will be the smallest containing
485 // the region but not contained by it.
486 Loop *L = LI.getLoopFor(S.getEntry());
487 while (L) {
488 bool AllContained = true;
489 for (auto *BB : S.blocks())
490 AllContained &= L->contains(BB);
491 if (AllContained)
492 break;
493 L = L->getParentLoop();
494 }
495
496 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
497}
498
499unsigned polly::getNumBlocksInLoop(Loop *L) {
500 unsigned NumBlocks = L->getNumBlocks();
501 SmallVector<BasicBlock *, 4> ExitBlocks;
502 L->getExitBlocks(ExitBlocks);
503
504 for (auto ExitBlock : ExitBlocks) {
505 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
506 NumBlocks++;
507 }
508 return NumBlocks;
509}
510
511unsigned polly::getNumBlocksInRegionNode(RegionNode *RN) {
512 if (!RN->isSubRegion())
513 return 1;
514
515 Region *R = RN->getNodeAs<Region>();
516 return std::distance(R->block_begin(), R->block_end());
517}
518
519Loop *polly::getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
520 if (!RN->isSubRegion()) {
521 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
522 Loop *L = LI.getLoopFor(BB);
523
524 // Unreachable statements are not considered to belong to a LLVM loop, as
525 // they are not part of an actual loop in the control flow graph.
526 // Nevertheless, we handle certain unreachable statements that are common
527 // when modeling run-time bounds checks as being part of the loop to be
528 // able to model them and to later eliminate the run-time bounds checks.
529 //
530 // Specifically, for basic blocks that terminate in an unreachable and
531 // where the immediate predecessor is part of a loop, we assume these
532 // basic blocks belong to the loop the predecessor belongs to. This
533 // allows us to model the following code.
534 //
535 // for (i = 0; i < N; i++) {
536 // if (i > 1024)
537 // abort(); <- this abort might be translated to an
538 // unreachable
539 //
540 // A[i] = ...
541 // }
542 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
543 L = LI.getLoopFor(BB->getPrevNode());
544 return L;
545 }
546
547 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
548 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
549 while (L && NonAffineSubRegion->contains(L))
550 L = L->getParentLoop();
551 return L;
552}
553
554static bool hasVariantIndex(GetElementPtrInst *Gep, Loop *L, Region &R,
555 ScalarEvolution &SE) {
556 for (const Use &Val : llvm::drop_begin(Gep->operands(), 1)) {
557 const SCEV *PtrSCEV = SE.getSCEVAtScope(Val, L);
558 Loop *OuterLoop = R.outermostLoopInRegion(L);
559 if (!SE.isLoopInvariant(PtrSCEV, OuterLoop))
560 return true;
561 }
562 return false;
563}
564
565bool polly::isHoistableLoad(LoadInst *LInst, Region &R, LoopInfo &LI,
566 ScalarEvolution &SE, const DominatorTree &DT,
567 const InvariantLoadsSetTy &KnownInvariantLoads) {
568 Loop *L = LI.getLoopFor(LInst->getParent());
569 auto *Ptr = LInst->getPointerOperand();
570
571 // A LoadInst is hoistable if the address it is loading from is also
572 // invariant; in this case: another invariant load (whether that address
573 // is also not written to has to be checked separately)
574 // TODO: This only checks for a LoadInst->GetElementPtrInst->LoadInst
575 // pattern generated by the Chapel frontend, but generally this applies
576 // for any chain of instruction that does not also depend on any
577 // induction variable
578 if (auto *GepInst = dyn_cast<GetElementPtrInst>(Ptr)) {
579 if (!hasVariantIndex(GepInst, L, R, SE)) {
580 if (auto *DecidingLoad =
581 dyn_cast<LoadInst>(GepInst->getPointerOperand())) {
582 if (KnownInvariantLoads.count(DecidingLoad))
583 return true;
584 }
585 }
586 }
587
588 const SCEV *PtrSCEV = SE.getSCEVAtScope(Ptr, L);
589 while (L && R.contains(L)) {
590 if (!SE.isLoopInvariant(PtrSCEV, L))
591 return false;
592 L = L->getParentLoop();
593 }
594
595 if (!Ptr->hasUseList())
596 return true;
597
598 for (auto *User : Ptr->users()) {
599 auto *UserI = dyn_cast<Instruction>(User);
600 if (!UserI || UserI->getFunction() != LInst->getFunction() ||
601 !R.contains(UserI))
602 continue;
603 if (!UserI->mayWriteToMemory())
604 continue;
605
606 auto &BB = *UserI->getParent();
607 if (DT.dominates(&BB, LInst->getParent()))
608 return false;
609
610 bool DominatesAllPredecessors = true;
611 if (R.isTopLevelRegion()) {
612 for (BasicBlock &I : *R.getEntry()->getParent())
613 if (isa<ReturnInst>(I.getTerminator()) && !DT.dominates(&BB, &I))
614 DominatesAllPredecessors = false;
615 } else {
616 for (auto Pred : predecessors(R.getExit()))
617 if (R.contains(Pred) && !DT.dominates(&BB, Pred))
618 DominatesAllPredecessors = false;
619 }
620
621 if (!DominatesAllPredecessors)
622 continue;
623
624 return false;
625 }
626
627 return true;
628}
629
630bool polly::isIgnoredIntrinsic(const Value *V) {
631 if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
632 switch (IT->getIntrinsicID()) {
633 // Lifetime markers are supported/ignored.
634 case llvm::Intrinsic::lifetime_start:
635 case llvm::Intrinsic::lifetime_end:
636 // Invariant markers are supported/ignored.
637 case llvm::Intrinsic::invariant_start:
638 case llvm::Intrinsic::invariant_end:
639 // Some misc annotations are supported/ignored.
640 case llvm::Intrinsic::var_annotation:
641 case llvm::Intrinsic::ptr_annotation:
642 case llvm::Intrinsic::annotation:
643 case llvm::Intrinsic::donothing:
644 case llvm::Intrinsic::assume:
645 // Some debug info intrinsics are supported/ignored.
646 case llvm::Intrinsic::dbg_value:
647 case llvm::Intrinsic::dbg_declare:
648 return true;
649 default:
650 break;
651 }
652 }
653 return false;
654}
655
656bool polly::canSynthesize(const Value *V, const Scop &S, ScalarEvolution *SE,
657 Loop *Scope) {
658 if (!V || !SE->isSCEVable(V->getType()))
659 return false;
660
661 const InvariantLoadsSetTy &ILS = S.getRequiredInvariantLoads();
662 if (const SCEV *Scev = SE->getSCEVAtScope(const_cast<Value *>(V), Scope))
663 if (!isa<SCEVCouldNotCompute>(Scev))
664 if (!hasScalarDepsInsideRegion(Scev, &S.getRegion(), Scope, false, ILS))
665 return true;
666
667 return false;
668}
669
670llvm::BasicBlock *polly::getUseBlock(const llvm::Use &U) {
671 Instruction *UI = dyn_cast<Instruction>(U.getUser());
672 if (!UI)
673 return nullptr;
674
675 if (PHINode *PHI = dyn_cast<PHINode>(UI))
676 return PHI->getIncomingBlock(U);
677
678 return UI->getParent();
679}
680
681llvm::Loop *polly::getFirstNonBoxedLoopFor(llvm::Loop *L, llvm::LoopInfo &LI,
682 const BoxedLoopsSetTy &BoxedLoops) {
683 while (BoxedLoops.count(L))
684 L = L->getParentLoop();
685 return L;
686}
687
688llvm::Loop *polly::getFirstNonBoxedLoopFor(llvm::BasicBlock *BB,
689 llvm::LoopInfo &LI,
690 const BoxedLoopsSetTy &BoxedLoops) {
691 Loop *L = LI.getLoopFor(BB);
692 return getFirstNonBoxedLoopFor(L, LI, BoxedLoops);
693}
694
695bool polly::isDebugCall(Instruction *Inst) {
696 auto *CI = dyn_cast<CallInst>(Inst);
697 if (!CI)
698 return false;
699
700 Function *CF = CI->getCalledFunction();
701 if (!CF)
702 return false;
703
704 return std::find(DebugFunctions.begin(), DebugFunctions.end(),
705 CF->getName()) != DebugFunctions.end();
706}
707
708static bool hasDebugCall(BasicBlock *BB) {
709 for (Instruction &Inst : *BB) {
710 if (isDebugCall(&Inst))
711 return true;
712 }
713 return false;
714}
715
717 // Quick skip if no debug functions have been defined.
718 if (DebugFunctions.empty())
719 return false;
720
721 if (!Stmt)
722 return false;
723
724 for (Instruction *Inst : Stmt->getInstructions())
725 if (isDebugCall(Inst))
726 return true;
727
728 if (Stmt->isRegionStmt()) {
729 for (BasicBlock *RBB : Stmt->getRegion()->blocks())
730 if (RBB != Stmt->getEntryBlock() && ::hasDebugCall(RBB))
731 return true;
732 }
733
734 return false;
735}
736
737/// Find a property in a LoopID.
738static MDNode *findNamedMetadataNode(MDNode *LoopMD, StringRef Name) {
739 if (!LoopMD)
740 return nullptr;
741 for (const MDOperand &X : drop_begin(LoopMD->operands(), 1)) {
742 auto *OpNode = dyn_cast<MDNode>(X.get());
743 if (!OpNode)
744 continue;
745
746 auto *OpName = dyn_cast<MDString>(OpNode->getOperand(0));
747 if (!OpName)
748 continue;
749 if (OpName->getString() == Name)
750 return OpNode;
751 }
752 return nullptr;
753}
754
755static std::optional<const MDOperand *> findNamedMetadataArg(MDNode *LoopID,
756 StringRef Name) {
757 MDNode *MD = findNamedMetadataNode(LoopID, Name);
758 if (!MD)
759 return std::nullopt;
760 switch (MD->getNumOperands()) {
761 case 1:
762 return nullptr;
763 case 2:
764 return &MD->getOperand(1);
765 default:
766 llvm_unreachable("loop metadata has 0 or 1 operand");
767 }
768}
769
770std::optional<Metadata *> polly::findMetadataOperand(MDNode *LoopMD,
771 StringRef Name) {
772 MDNode *MD = findNamedMetadataNode(LoopMD, Name);
773 if (!MD)
774 return std::nullopt;
775 switch (MD->getNumOperands()) {
776 case 1:
777 return nullptr;
778 case 2:
779 return MD->getOperand(1).get();
780 default:
781 llvm_unreachable("loop metadata must have 0 or 1 operands");
782 }
783}
784
785static std::optional<bool> getOptionalBoolLoopAttribute(MDNode *LoopID,
786 StringRef Name) {
787 MDNode *MD = findNamedMetadataNode(LoopID, Name);
788 if (!MD)
789 return std::nullopt;
790 switch (MD->getNumOperands()) {
791 case 1:
792 return true;
793 case 2:
794 if (ConstantInt *IntMD =
795 mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
796 return IntMD->getZExtValue();
797 return true;
798 }
799 llvm_unreachable("unexpected number of options");
800}
801
802bool polly::getBooleanLoopAttribute(MDNode *LoopID, StringRef Name) {
803 return getOptionalBoolLoopAttribute(LoopID, Name).value_or(false);
804}
805
806std::optional<int> polly::getOptionalIntLoopAttribute(MDNode *LoopID,
807 StringRef Name) {
808 const MDOperand *AttrMD =
809 findNamedMetadataArg(LoopID, Name).value_or(nullptr);
810 if (!AttrMD)
811 return std::nullopt;
812
813 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
814 if (!IntMD)
815 return std::nullopt;
816
817 return IntMD->getSExtValue();
818}
819
821 return llvm::hasDisableAllTransformsHint(L);
822}
823
824bool polly::hasDisableAllTransformsHint(llvm::MDNode *LoopID) {
825 return getBooleanLoopAttribute(LoopID, "llvm.loop.disable_nonforced");
826}
827
829 assert(Attr && "Must be a valid BandAttr");
830
831 // The name "Loop" signals that this id contains a pointer to a BandAttr.
832 // The ScheduleOptimizer also uses the string "Inter iteration alias-free" in
833 // markers, but it's user pointer is an llvm::Value.
834 isl::id Result = isl::id::alloc(Ctx, "Loop with Metadata", Attr);
835 Result = isl::manage(isl_id_set_free_user(Result.release(), [](void *Ptr) {
836 BandAttr *Attr = reinterpret_cast<BandAttr *>(Ptr);
837 delete Attr;
838 }));
839 return Result;
840}
841
843 if (!L)
844 return {};
845
846 // A loop without metadata does not need to be annotated.
847 MDNode *LoopID = L->getLoopID();
848 if (!LoopID)
849 return {};
850
851 BandAttr *Attr = new BandAttr();
852 Attr->OriginalLoop = L;
853 Attr->Metadata = L->getLoopID();
854
855 return getIslLoopAttr(Ctx, Attr);
856}
857
858bool polly::isLoopAttr(const isl::id &Id) {
859 if (Id.is_null())
860 return false;
861
862 return Id.get_name() == "Loop with Metadata";
863}
864
866 if (!isLoopAttr(Id))
867 return nullptr;
868
869 return reinterpret_cast<BandAttr *>(Id.get_user());
870}
llvm::cl::OptionCategory PollyCategory
static std::optional< bool > getOptionalBoolLoopAttribute(MDNode *LoopID, StringRef Name)
static BasicBlock * splitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, llvm::LoopInfo *LI, RegionInfo *RI)
static void simplifyRegionEntry(Region *R, DominatorTree *DT, LoopInfo *LI, RegionInfo *RI)
static std::optional< const MDOperand * > findNamedMetadataArg(MDNode *LoopID, StringRef Name)
static cl::list< std::string > DebugFunctions("polly-debug-func", cl::desc("Allow calls to the specified functions in SCoPs even if their " "side-effects are unknown. This can be used to do debug output in " "Polly-transformed code."), cl::Hidden, cl::CommaSeparated, cl::cat(PollyCategory))
static MDNode * findNamedMetadataNode(MDNode *LoopMD, StringRef Name)
Find a property in a LoopID.
static void simplifyRegionExit(Region *R, DominatorTree *DT, LoopInfo *LI, RegionInfo *RI)
static bool hasVariantIndex(GetElementPtrInst *Gep, Loop *L, Region &R, ScalarEvolution &SE)
__isl_give isl_id * release()
bool is_null() const
std::string get_name() const
static isl::id alloc(isl::ctx ctx, const std::string &name, void *user)
Statement of the Scop.
Definition ScopInfo.h:1135
BasicBlock * getEntryBlock() const
Return a BasicBlock from this statement.
const std::vector< Instruction * > & getInstructions() const
Definition ScopInfo.h:1526
Region * getRegion() const
Get the region represented by this ScopStmt (if any).
Definition ScopInfo.h:1325
bool isRegionStmt() const
Return true if this statement represents a whole region.
Definition ScopInfo.h:1328
Static Control Part.
Definition ScopInfo.h:1625
__isl_give isl_id * isl_id_set_free_user(__isl_take isl_id *id, void(*free_user)(void *user))
Definition isl_id.c:183
#define S(TYPE, NAME)
#define assert(exp)
boolean manage(isl_bool val)
Definition cpp-checked.h:98
llvm::Loop * getRegionNodeLoop(llvm::RegionNode *RN, llvm::LoopInfo &LI)
Return the smallest loop surrounding RN.
llvm::Value * getConditionFromTerminator(llvm::Instruction *TI)
Return the condition for the terminator TI.
llvm::DenseMap< const llvm::Loop *, const llvm::SCEV * > LoopToScevMapT
Same as llvm/Analysis/ScalarEvolutionExpressions.h.
Definition ScopHelper.h:40
bool isLoopAttr(const isl::id &Id)
Is Id representing a loop?
std::optional< llvm::Metadata * > findMetadataOperand(llvm::MDNode *LoopMD, llvm::StringRef Name)
Find a property value in a LoopID.
llvm::SetVector< llvm::AssertingVH< llvm::LoadInst > > InvariantLoadsSetTy
Type for a set of invariant loads.
Definition ScopHelper.h:109
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.
unsigned getNumBlocksInRegionNode(llvm::RegionNode *RN)
Get the number of blocks in RN.
llvm::Loop * getFirstNonBoxedLoopFor(llvm::Loop *L, llvm::LoopInfo &LI, const BoxedLoopsSetTy &BoxedLoops)
AssumptionSign
Enum to distinguish between assumptions and restrictions.
Definition ScopHelper.h:57
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:149
@ PHI
MemoryKind::PHI: Models PHI nodes within the SCoP.
Definition ScopInfo.h:186
void splitEntryBlockForAlloca(llvm::BasicBlock *EntryBlock, llvm::DominatorTree *DT, llvm::LoopInfo *LI, llvm::RegionInfo *RI)
Split the entry block of a function to store the newly inserted allocations outside of all Scops.
bool hasDisableAllTransformsHint(llvm::Loop *L)
Does the loop's LoopID contain a 'llvm.loop.disable_heuristics' property?
std::optional< int > getOptionalIntLoopAttribute(llvm::MDNode *LoopID, llvm::StringRef Name)
Find an integers property value in a LoopID.
bool isDebugCall(llvm::Instruction *Inst)
Is the given instruction a call to a debug function?
bool hasDebugCall(ScopStmt *Stmt)
Does the statement contain a call to a debug function?
BandAttr * getLoopAttr(const isl::id &Id)
Return the BandAttr of a loop's isl::id.
llvm::BasicBlock * getUseBlock(const llvm::Use &U)
Return the block in which a value is used.
llvm::Loop * getLoopSurroundingScop(Scop &S, llvm::LoopInfo &LI)
Get the smallest loop that contains S but is not in S.
void recordAssumption(RecordedAssumptionsTy *RecordedAssumptions, AssumptionKind Kind, isl::set Set, llvm::DebugLoc Loc, AssumptionSign Sign, llvm::BasicBlock *BB=nullptr, bool RTC=true)
Record an assumption for later addition to the assumed context.
isl::id getIslLoopAttr(isl::ctx Ctx, BandAttr *Attr)
Get an isl::id representing a loop.
llvm::SetVector< const llvm::Loop * > BoxedLoopsSetTy
Set of loops (used to remember loops in non-affine subregions).
Definition ScopHelper.h:115
bool isHoistableLoad(llvm::LoadInst *LInst, llvm::Region &R, llvm::LoopInfo &LI, llvm::ScalarEvolution &SE, const llvm::DominatorTree &DT, const InvariantLoadsSetTy &KnownInvariantLoads)
Check if LInst can be hoisted in R.
isl::id createIslLoopAttr(isl::ctx Ctx, llvm::Loop *L)
Create an isl::id that identifies an original loop.
bool hasScalarDepsInsideRegion(const llvm::SCEV *Expr, const llvm::Region *R, llvm::Loop *Scope, bool AllowLoops, const InvariantLoadsSetTy &ILS)
Returns true when the SCEV contains references to instructions within the region.
llvm::SmallVector< Assumption, 8 > RecordedAssumptionsTy
Definition ScopHelper.h:80
llvm::DenseMap< llvm::AssertingVH< llvm::Value >, llvm::AssertingVH< llvm::Value > > ValueMapT
Type to remap values.
Definition ScopHelper.h:105
AssumptionKind
Enumeration of assumptions Polly can take.
Definition ScopHelper.h:43
bool isIgnoredIntrinsic(const llvm::Value *V)
Return true iff V is an intrinsic that we ignore during code generation.
void simplifyRegion(llvm::Region *R, llvm::DominatorTree *DT, llvm::LoopInfo *LI, llvm::RegionInfo *RI)
Simplify the region to have a single unconditional entry edge and a single exit edge.
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.
bool getBooleanLoopAttribute(llvm::MDNode *LoopID, llvm::StringRef Name)
Find a boolean property value in a LoopID.
unsigned getNumBlocksInLoop(llvm::Loop *L)
Get the number of blocks in L.
ScopExpander generates IR the the value of a SCEV that represents a value from a SCoP.
const SCEV * visit(const SCEV *E)
const SCEV * visitAddExpr(const SCEVAddExpr *E)
ValueMapT * VMap
SCEVExpander Expander
ScalarEvolution & GenSE
const SCEV * visitUMaxExpr(const SCEVUMaxExpr *E)
Function * GenFn
const SCEV * visitUMinExpr(const SCEVUMinExpr *E)
const SCEV * visitUnknown(const SCEVUnknown *E)
const Region & R
const char * Name
const SCEV * visitAddRecExpr(const SCEVAddRecExpr *E)
const SCEV * visitPtrToIntExpr(const SCEVPtrToIntExpr *E)
Value * expandCodeFor(const SCEV *E, Type *Ty, BasicBlock::iterator IP)
const SCEV * visitSMaxExpr(const SCEVSMaxExpr *E)
const SCEV * visitConstant(const SCEVConstant *E)
The following functions will just traverse the SCEV and rebuild it using GenSE and the new operands r...
const SCEV * visitSequentialUMinExpr(const SCEVSequentialUMinExpr *E)
const SCEV * visitZeroExtendExpr(const SCEVZeroExtendExpr *E)
const SCEV * visitUDivExpr(const SCEVUDivExpr *E)
const SCEV * visitGenericInst(const SCEVUnknown *E, Instruction *Inst, BasicBlock::iterator IP)
DenseMap< const SCEV *, const SCEV * > SCEVCache
BasicBlock * RTCBB
const SCEV * visitSignExtendExpr(const SCEVSignExtendExpr *E)
bool isInOrigRegion(Instruction *Inst)
Is the instruction part of the original SCoP (in contrast to be located in the code-generated region)...
const SCEV * visitSMinExpr(const SCEVSMinExpr *E)
const SCEV * visitMulExpr(const SCEVMulExpr *E)
const SCEV * visitVScale(const SCEVVScale *E)
bool isInGenRegion(Instruction *Inst)
const SCEV * visitPtrToAddrExpr(const SCEVPtrToAddrExpr *E)
ScopExpander(const Region &R, ScalarEvolution &SE, Function *GenFn, ScalarEvolution &GenSE, const char *Name, ValueMapT *VMap, LoopToScevMapT *LoopMap, BasicBlock *RTCBB)
LoopToScevMapT * LoopMap
const SCEV * visitTruncateExpr(const SCEVTruncateExpr *E)
Represent the attributes of a loop.
Definition ScopHelper.h:546
llvm::MDNode * Metadata
LoopID which stores the properties of the loop, such as transformations to apply and the metadata of ...
Definition ScopHelper.h:552
llvm::Loop * OriginalLoop
The LoopInfo reference for this loop.
Definition ScopHelper.h:558
static TupleKindPtr Ctx