[RISCV] Fix mgather -> riscv.masked.strided.load combine not extending indices (...
[llvm-project.git] / polly / lib / Support / ScopHelper.cpp
blobafdb61f25b6c12febb9dd34b1018c1a06c7627d1
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.
11 //===----------------------------------------------------------------------===//
13 #include "polly/Support/ScopHelper.h"
14 #include "polly/Options.h"
15 #include "polly/ScopInfo.h"
16 #include "polly/Support/SCEVValidator.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>
26 using namespace llvm;
27 using namespace polly;
29 #define DEBUG_TYPE "polly-scop-helper"
31 static 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));
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.
41 static void simplifyRegionEntry(Region *R, DominatorTree *DT, LoopInfo *LI,
42 RegionInfo *RI) {
43 BasicBlock *EnteringBB = R->getEnteringBlock();
44 BasicBlock *Entry = R->getEntry();
46 // Before (one of):
48 // \ / //
49 // EnteringBB //
50 // | \------> //
51 // \ / | //
52 // Entry <--\ Entry <--\ //
53 // / \ / / \ / //
54 // .... .... //
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);
63 BasicBlock *NewEntering =
64 SplitBlockPredecessors(Entry, Preds, ".region_entering", DT, LI);
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;
73 while (!RegionOfPred->isTopLevelRegion() &&
74 RegionOfPred->getExit() == Entry) {
75 RegionOfPred->replaceExit(NewEntering);
76 RegionOfPred = RegionOfPred->getParent();
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();
89 EnteringBB = NewEntering;
91 assert(R->getEnteringBlock() == EnteringBB);
93 // After:
95 // \ / //
96 // EnteringBB //
97 // | //
98 // | //
99 // Entry <--\ //
100 // / \ / //
101 // .... //
104 // Ensure that the region has a single block that branches to the exit node.
105 static void simplifyRegionExit(Region *R, DominatorTree *DT, LoopInfo *LI,
106 RegionInfo *RI) {
107 BasicBlock *ExitBB = R->getExit();
108 BasicBlock *ExitingBB = R->getExitingBlock();
110 // Before:
112 // (Region) ______/ //
113 // \ | / //
114 // ExitBB //
115 // / \ //
117 if (!ExitingBB) {
118 SmallVector<BasicBlock *, 4> Preds;
119 for (BasicBlock *P : predecessors(ExitBB))
120 if (R->contains(P))
121 Preds.push_back(P);
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 //
135 if (RI)
136 RI->setRegionFor(ExitingBB, R);
138 // Change the exit of nested regions, but not the region itself,
139 R->replaceExitRecursive(ExitingBB);
140 R->replaceExit(ExitBB);
142 assert(ExitingBB == R->getExitingBlock());
144 // After:
146 // \ / //
147 // ExitingBB _____/ //
148 // \ / //
149 // ExitBB //
150 // / \ //
153 void 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");
160 simplifyRegionEntry(R, DT, LI, RI);
161 simplifyRegionExit(R, DT, LI, RI);
162 assert(R->isSimple());
165 // Split the block into two successive blocks.
167 // Like llvm::SplitBlock, but also preserves RegionInfo
168 static BasicBlock *splitBlock(BasicBlock *Old, Instruction *SplitPt,
169 DominatorTree *DT, llvm::LoopInfo *LI,
170 RegionInfo *RI) {
171 assert(Old && SplitPt);
173 // Before:
175 // \ / //
176 // Old //
177 // / \ //
179 BasicBlock *NewBlock = llvm::SplitBlock(Old, SplitPt, DT, LI);
181 if (RI) {
182 Region *R = RI->getRegionFor(Old);
183 RI->setRegionFor(NewBlock, R);
186 // After:
188 // \ / //
189 // Old //
190 // | //
191 // NewBlock //
192 // / \ //
194 return NewBlock;
197 void 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;
205 // splitBlock updates DT, LI and RI.
206 splitBlock(EntryBlock, &*I, DT, LI, RI);
209 void polly::splitEntryBlockForAlloca(BasicBlock *EntryBlock, Pass *P) {
210 auto *DTWP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
211 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
212 auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
213 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
214 RegionInfoPass *RIP = P->getAnalysisIfAvailable<RegionInfoPass>();
215 RegionInfo *RI = RIP ? &RIP->getRegionInfo() : nullptr;
217 // splitBlock updates DT, LI and RI.
218 polly::splitEntryBlockForAlloca(EntryBlock, DT, LI, RI);
221 void polly::recordAssumption(polly::RecordedAssumptionsTy *RecordedAssumptions,
222 polly::AssumptionKind Kind, isl::set Set,
223 DebugLoc Loc, polly::AssumptionSign Sign,
224 BasicBlock *BB, bool RTC) {
225 assert((Set.is_params() || BB) &&
226 "Assumptions without a basic block must be parameter sets");
227 if (RecordedAssumptions)
228 RecordedAssumptions->push_back({Kind, Sign, Set, Loc, BB, RTC});
231 /// The SCEVExpander will __not__ generate any code for an existing SDiv/SRem
232 /// instruction but just use it, if it is referenced as a SCEVUnknown. We want
233 /// however to generate new code if the instruction is in the analyzed region
234 /// and we generate code outside/in front of that region. Hence, we generate the
235 /// code for the SDiv/SRem operands in front of the analyzed region and then
236 /// create a new SDiv/SRem operation there too.
237 struct ScopExpander final : SCEVVisitor<ScopExpander, const SCEV *> {
238 friend struct SCEVVisitor<ScopExpander, const SCEV *>;
240 explicit ScopExpander(const Region &R, ScalarEvolution &SE,
241 const DataLayout &DL, const char *Name, ValueMapT *VMap,
242 BasicBlock *RTCBB)
243 : Expander(SE, DL, Name, /*PreserveLCSSA=*/false), SE(SE), Name(Name),
244 R(R), VMap(VMap), RTCBB(RTCBB) {}
246 Value *expandCodeFor(const SCEV *E, Type *Ty, Instruction *I) {
247 // If we generate code in the region we will immediately fall back to the
248 // SCEVExpander, otherwise we will stop at all unknowns in the SCEV and if
249 // needed replace them by copies computed in the entering block.
250 if (!R.contains(I))
251 E = visit(E);
252 return Expander.expandCodeFor(E, Ty, I);
255 const SCEV *visit(const SCEV *E) {
256 // Cache the expansion results for intermediate SCEV expressions. A SCEV
257 // expression can refer to an operand multiple times (e.g. "x*x), so
258 // a naive visitor takes exponential time.
259 if (SCEVCache.count(E))
260 return SCEVCache[E];
261 const SCEV *Result = SCEVVisitor::visit(E);
262 SCEVCache[E] = Result;
263 return Result;
266 private:
267 SCEVExpander Expander;
268 ScalarEvolution &SE;
269 const char *Name;
270 const Region &R;
271 ValueMapT *VMap;
272 BasicBlock *RTCBB;
273 DenseMap<const SCEV *, const SCEV *> SCEVCache;
275 const SCEV *visitGenericInst(const SCEVUnknown *E, Instruction *Inst,
276 Instruction *IP) {
277 if (!Inst || !R.contains(Inst))
278 return E;
280 assert(!Inst->mayThrow() && !Inst->mayReadOrWriteMemory() &&
281 !isa<PHINode>(Inst));
283 auto *InstClone = Inst->clone();
284 for (auto &Op : Inst->operands()) {
285 assert(SE.isSCEVable(Op->getType()));
286 auto *OpSCEV = SE.getSCEV(Op);
287 auto *OpClone = expandCodeFor(OpSCEV, Op->getType(), IP);
288 InstClone->replaceUsesOfWith(Op, OpClone);
291 InstClone->setName(Name + Inst->getName());
292 InstClone->insertBefore(IP);
293 return SE.getSCEV(InstClone);
296 const SCEV *visitUnknown(const SCEVUnknown *E) {
298 // If a value mapping was given try if the underlying value is remapped.
299 Value *NewVal = VMap ? VMap->lookup(E->getValue()) : nullptr;
300 if (NewVal) {
301 auto *NewE = SE.getSCEV(NewVal);
303 // While the mapped value might be different the SCEV representation might
304 // not be. To this end we will check before we go into recursion here.
305 if (E != NewE)
306 return visit(NewE);
309 Instruction *Inst = dyn_cast<Instruction>(E->getValue());
310 Instruction *IP;
311 if (Inst && !R.contains(Inst))
312 IP = Inst;
313 else if (Inst && RTCBB->getParent() == Inst->getFunction())
314 IP = RTCBB->getTerminator();
315 else
316 IP = RTCBB->getParent()->getEntryBlock().getTerminator();
318 if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
319 Inst->getOpcode() != Instruction::SDiv))
320 return visitGenericInst(E, Inst, IP);
322 const SCEV *LHSScev = SE.getSCEV(Inst->getOperand(0));
323 const SCEV *RHSScev = SE.getSCEV(Inst->getOperand(1));
325 if (!SE.isKnownNonZero(RHSScev))
326 RHSScev = SE.getUMaxExpr(RHSScev, SE.getConstant(E->getType(), 1));
328 Value *LHS = expandCodeFor(LHSScev, E->getType(), IP);
329 Value *RHS = expandCodeFor(RHSScev, E->getType(), IP);
331 Inst = BinaryOperator::Create((Instruction::BinaryOps)Inst->getOpcode(),
332 LHS, RHS, Inst->getName() + Name, IP);
333 return SE.getSCEV(Inst);
336 /// The following functions will just traverse the SCEV and rebuild it with
337 /// the new operands returned by the traversal.
339 ///{
340 const SCEV *visitConstant(const SCEVConstant *E) { return E; }
341 const SCEV *visitVScale(const SCEVVScale *E) { return E; }
342 const SCEV *visitPtrToIntExpr(const SCEVPtrToIntExpr *E) {
343 return SE.getPtrToIntExpr(visit(E->getOperand()), E->getType());
345 const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
346 return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
348 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
349 return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
351 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
352 return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
354 const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
355 auto *RHSScev = visit(E->getRHS());
356 if (!SE.isKnownNonZero(RHSScev))
357 RHSScev = SE.getUMaxExpr(RHSScev, SE.getConstant(E->getType(), 1));
358 return SE.getUDivExpr(visit(E->getLHS()), RHSScev);
360 const SCEV *visitAddExpr(const SCEVAddExpr *E) {
361 SmallVector<const SCEV *, 4> NewOps;
362 for (const SCEV *Op : E->operands())
363 NewOps.push_back(visit(Op));
364 return SE.getAddExpr(NewOps);
366 const SCEV *visitMulExpr(const SCEVMulExpr *E) {
367 SmallVector<const SCEV *, 4> NewOps;
368 for (const SCEV *Op : E->operands())
369 NewOps.push_back(visit(Op));
370 return SE.getMulExpr(NewOps);
372 const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
373 SmallVector<const SCEV *, 4> NewOps;
374 for (const SCEV *Op : E->operands())
375 NewOps.push_back(visit(Op));
376 return SE.getUMaxExpr(NewOps);
378 const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
379 SmallVector<const SCEV *, 4> NewOps;
380 for (const SCEV *Op : E->operands())
381 NewOps.push_back(visit(Op));
382 return SE.getSMaxExpr(NewOps);
384 const SCEV *visitUMinExpr(const SCEVUMinExpr *E) {
385 SmallVector<const SCEV *, 4> NewOps;
386 for (const SCEV *Op : E->operands())
387 NewOps.push_back(visit(Op));
388 return SE.getUMinExpr(NewOps);
390 const SCEV *visitSMinExpr(const SCEVSMinExpr *E) {
391 SmallVector<const SCEV *, 4> NewOps;
392 for (const SCEV *Op : E->operands())
393 NewOps.push_back(visit(Op));
394 return SE.getSMinExpr(NewOps);
396 const SCEV *visitSequentialUMinExpr(const SCEVSequentialUMinExpr *E) {
397 SmallVector<const SCEV *, 4> NewOps;
398 for (const SCEV *Op : E->operands())
399 NewOps.push_back(visit(Op));
400 return SE.getUMinExpr(NewOps, /*Sequential=*/true);
402 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
403 SmallVector<const SCEV *, 4> NewOps;
404 for (const SCEV *Op : E->operands())
405 NewOps.push_back(visit(Op));
406 return SE.getAddRecExpr(NewOps, E->getLoop(), E->getNoWrapFlags());
408 ///}
411 Value *polly::expandCodeFor(Scop &S, ScalarEvolution &SE, const DataLayout &DL,
412 const char *Name, const SCEV *E, Type *Ty,
413 Instruction *IP, ValueMapT *VMap,
414 BasicBlock *RTCBB) {
415 ScopExpander Expander(S.getRegion(), SE, DL, Name, VMap, RTCBB);
416 return Expander.expandCodeFor(E, Ty, IP);
419 Value *polly::getConditionFromTerminator(Instruction *TI) {
420 if (BranchInst *BR = dyn_cast<BranchInst>(TI)) {
421 if (BR->isUnconditional())
422 return ConstantInt::getTrue(Type::getInt1Ty(TI->getContext()));
424 return BR->getCondition();
427 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
428 return SI->getCondition();
430 return nullptr;
433 Loop *polly::getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
434 // Start with the smallest loop containing the entry and expand that
435 // loop until it contains all blocks in the region. If there is a loop
436 // containing all blocks in the region check if it is itself contained
437 // and if so take the parent loop as it will be the smallest containing
438 // the region but not contained by it.
439 Loop *L = LI.getLoopFor(S.getEntry());
440 while (L) {
441 bool AllContained = true;
442 for (auto *BB : S.blocks())
443 AllContained &= L->contains(BB);
444 if (AllContained)
445 break;
446 L = L->getParentLoop();
449 return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
452 unsigned polly::getNumBlocksInLoop(Loop *L) {
453 unsigned NumBlocks = L->getNumBlocks();
454 SmallVector<BasicBlock *, 4> ExitBlocks;
455 L->getExitBlocks(ExitBlocks);
457 for (auto ExitBlock : ExitBlocks) {
458 if (isa<UnreachableInst>(ExitBlock->getTerminator()))
459 NumBlocks++;
461 return NumBlocks;
464 unsigned polly::getNumBlocksInRegionNode(RegionNode *RN) {
465 if (!RN->isSubRegion())
466 return 1;
468 Region *R = RN->getNodeAs<Region>();
469 return std::distance(R->block_begin(), R->block_end());
472 Loop *polly::getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
473 if (!RN->isSubRegion()) {
474 BasicBlock *BB = RN->getNodeAs<BasicBlock>();
475 Loop *L = LI.getLoopFor(BB);
477 // Unreachable statements are not considered to belong to a LLVM loop, as
478 // they are not part of an actual loop in the control flow graph.
479 // Nevertheless, we handle certain unreachable statements that are common
480 // when modeling run-time bounds checks as being part of the loop to be
481 // able to model them and to later eliminate the run-time bounds checks.
483 // Specifically, for basic blocks that terminate in an unreachable and
484 // where the immediate predecessor is part of a loop, we assume these
485 // basic blocks belong to the loop the predecessor belongs to. This
486 // allows us to model the following code.
488 // for (i = 0; i < N; i++) {
489 // if (i > 1024)
490 // abort(); <- this abort might be translated to an
491 // unreachable
493 // A[i] = ...
494 // }
495 if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
496 L = LI.getLoopFor(BB->getPrevNode());
497 return L;
500 Region *NonAffineSubRegion = RN->getNodeAs<Region>();
501 Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
502 while (L && NonAffineSubRegion->contains(L))
503 L = L->getParentLoop();
504 return L;
507 static bool hasVariantIndex(GetElementPtrInst *Gep, Loop *L, Region &R,
508 ScalarEvolution &SE) {
509 for (const Use &Val : llvm::drop_begin(Gep->operands(), 1)) {
510 const SCEV *PtrSCEV = SE.getSCEVAtScope(Val, L);
511 Loop *OuterLoop = R.outermostLoopInRegion(L);
512 if (!SE.isLoopInvariant(PtrSCEV, OuterLoop))
513 return true;
515 return false;
518 bool polly::isHoistableLoad(LoadInst *LInst, Region &R, LoopInfo &LI,
519 ScalarEvolution &SE, const DominatorTree &DT,
520 const InvariantLoadsSetTy &KnownInvariantLoads) {
521 Loop *L = LI.getLoopFor(LInst->getParent());
522 auto *Ptr = LInst->getPointerOperand();
524 // A LoadInst is hoistable if the address it is loading from is also
525 // invariant; in this case: another invariant load (whether that address
526 // is also not written to has to be checked separately)
527 // TODO: This only checks for a LoadInst->GetElementPtrInst->LoadInst
528 // pattern generated by the Chapel frontend, but generally this applies
529 // for any chain of instruction that does not also depend on any
530 // induction variable
531 if (auto *GepInst = dyn_cast<GetElementPtrInst>(Ptr)) {
532 if (!hasVariantIndex(GepInst, L, R, SE)) {
533 if (auto *DecidingLoad =
534 dyn_cast<LoadInst>(GepInst->getPointerOperand())) {
535 if (KnownInvariantLoads.count(DecidingLoad))
536 return true;
541 const SCEV *PtrSCEV = SE.getSCEVAtScope(Ptr, L);
542 while (L && R.contains(L)) {
543 if (!SE.isLoopInvariant(PtrSCEV, L))
544 return false;
545 L = L->getParentLoop();
548 for (auto *User : Ptr->users()) {
549 auto *UserI = dyn_cast<Instruction>(User);
550 if (!UserI || !R.contains(UserI))
551 continue;
552 if (!UserI->mayWriteToMemory())
553 continue;
555 auto &BB = *UserI->getParent();
556 if (DT.dominates(&BB, LInst->getParent()))
557 return false;
559 bool DominatesAllPredecessors = true;
560 if (R.isTopLevelRegion()) {
561 for (BasicBlock &I : *R.getEntry()->getParent())
562 if (isa<ReturnInst>(I.getTerminator()) && !DT.dominates(&BB, &I))
563 DominatesAllPredecessors = false;
564 } else {
565 for (auto Pred : predecessors(R.getExit()))
566 if (R.contains(Pred) && !DT.dominates(&BB, Pred))
567 DominatesAllPredecessors = false;
570 if (!DominatesAllPredecessors)
571 continue;
573 return false;
576 return true;
579 bool polly::isIgnoredIntrinsic(const Value *V) {
580 if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
581 switch (IT->getIntrinsicID()) {
582 // Lifetime markers are supported/ignored.
583 case llvm::Intrinsic::lifetime_start:
584 case llvm::Intrinsic::lifetime_end:
585 // Invariant markers are supported/ignored.
586 case llvm::Intrinsic::invariant_start:
587 case llvm::Intrinsic::invariant_end:
588 // Some misc annotations are supported/ignored.
589 case llvm::Intrinsic::var_annotation:
590 case llvm::Intrinsic::ptr_annotation:
591 case llvm::Intrinsic::annotation:
592 case llvm::Intrinsic::donothing:
593 case llvm::Intrinsic::assume:
594 // Some debug info intrinsics are supported/ignored.
595 case llvm::Intrinsic::dbg_value:
596 case llvm::Intrinsic::dbg_declare:
597 return true;
598 default:
599 break;
602 return false;
605 bool polly::canSynthesize(const Value *V, const Scop &S, ScalarEvolution *SE,
606 Loop *Scope) {
607 if (!V || !SE->isSCEVable(V->getType()))
608 return false;
610 const InvariantLoadsSetTy &ILS = S.getRequiredInvariantLoads();
611 if (const SCEV *Scev = SE->getSCEVAtScope(const_cast<Value *>(V), Scope))
612 if (!isa<SCEVCouldNotCompute>(Scev))
613 if (!hasScalarDepsInsideRegion(Scev, &S.getRegion(), Scope, false, ILS))
614 return true;
616 return false;
619 llvm::BasicBlock *polly::getUseBlock(const llvm::Use &U) {
620 Instruction *UI = dyn_cast<Instruction>(U.getUser());
621 if (!UI)
622 return nullptr;
624 if (PHINode *PHI = dyn_cast<PHINode>(UI))
625 return PHI->getIncomingBlock(U);
627 return UI->getParent();
630 llvm::Loop *polly::getFirstNonBoxedLoopFor(llvm::Loop *L, llvm::LoopInfo &LI,
631 const BoxedLoopsSetTy &BoxedLoops) {
632 while (BoxedLoops.count(L))
633 L = L->getParentLoop();
634 return L;
637 llvm::Loop *polly::getFirstNonBoxedLoopFor(llvm::BasicBlock *BB,
638 llvm::LoopInfo &LI,
639 const BoxedLoopsSetTy &BoxedLoops) {
640 Loop *L = LI.getLoopFor(BB);
641 return getFirstNonBoxedLoopFor(L, LI, BoxedLoops);
644 bool polly::isDebugCall(Instruction *Inst) {
645 auto *CI = dyn_cast<CallInst>(Inst);
646 if (!CI)
647 return false;
649 Function *CF = CI->getCalledFunction();
650 if (!CF)
651 return false;
653 return std::find(DebugFunctions.begin(), DebugFunctions.end(),
654 CF->getName()) != DebugFunctions.end();
657 static bool hasDebugCall(BasicBlock *BB) {
658 for (Instruction &Inst : *BB) {
659 if (isDebugCall(&Inst))
660 return true;
662 return false;
665 bool polly::hasDebugCall(ScopStmt *Stmt) {
666 // Quick skip if no debug functions have been defined.
667 if (DebugFunctions.empty())
668 return false;
670 if (!Stmt)
671 return false;
673 for (Instruction *Inst : Stmt->getInstructions())
674 if (isDebugCall(Inst))
675 return true;
677 if (Stmt->isRegionStmt()) {
678 for (BasicBlock *RBB : Stmt->getRegion()->blocks())
679 if (RBB != Stmt->getEntryBlock() && ::hasDebugCall(RBB))
680 return true;
683 return false;
686 /// Find a property in a LoopID.
687 static MDNode *findNamedMetadataNode(MDNode *LoopMD, StringRef Name) {
688 if (!LoopMD)
689 return nullptr;
690 for (const MDOperand &X : drop_begin(LoopMD->operands(), 1)) {
691 auto *OpNode = dyn_cast<MDNode>(X.get());
692 if (!OpNode)
693 continue;
695 auto *OpName = dyn_cast<MDString>(OpNode->getOperand(0));
696 if (!OpName)
697 continue;
698 if (OpName->getString() == Name)
699 return OpNode;
701 return nullptr;
704 static std::optional<const MDOperand *> findNamedMetadataArg(MDNode *LoopID,
705 StringRef Name) {
706 MDNode *MD = findNamedMetadataNode(LoopID, Name);
707 if (!MD)
708 return std::nullopt;
709 switch (MD->getNumOperands()) {
710 case 1:
711 return nullptr;
712 case 2:
713 return &MD->getOperand(1);
714 default:
715 llvm_unreachable("loop metadata has 0 or 1 operand");
719 std::optional<Metadata *> polly::findMetadataOperand(MDNode *LoopMD,
720 StringRef Name) {
721 MDNode *MD = findNamedMetadataNode(LoopMD, Name);
722 if (!MD)
723 return std::nullopt;
724 switch (MD->getNumOperands()) {
725 case 1:
726 return nullptr;
727 case 2:
728 return MD->getOperand(1).get();
729 default:
730 llvm_unreachable("loop metadata must have 0 or 1 operands");
734 static std::optional<bool> getOptionalBoolLoopAttribute(MDNode *LoopID,
735 StringRef Name) {
736 MDNode *MD = findNamedMetadataNode(LoopID, Name);
737 if (!MD)
738 return std::nullopt;
739 switch (MD->getNumOperands()) {
740 case 1:
741 return true;
742 case 2:
743 if (ConstantInt *IntMD =
744 mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
745 return IntMD->getZExtValue();
746 return true;
748 llvm_unreachable("unexpected number of options");
751 bool polly::getBooleanLoopAttribute(MDNode *LoopID, StringRef Name) {
752 return getOptionalBoolLoopAttribute(LoopID, Name).value_or(false);
755 std::optional<int> polly::getOptionalIntLoopAttribute(MDNode *LoopID,
756 StringRef Name) {
757 const MDOperand *AttrMD =
758 findNamedMetadataArg(LoopID, Name).value_or(nullptr);
759 if (!AttrMD)
760 return std::nullopt;
762 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
763 if (!IntMD)
764 return std::nullopt;
766 return IntMD->getSExtValue();
769 bool polly::hasDisableAllTransformsHint(Loop *L) {
770 return llvm::hasDisableAllTransformsHint(L);
773 bool polly::hasDisableAllTransformsHint(llvm::MDNode *LoopID) {
774 return getBooleanLoopAttribute(LoopID, "llvm.loop.disable_nonforced");
777 isl::id polly::getIslLoopAttr(isl::ctx Ctx, BandAttr *Attr) {
778 assert(Attr && "Must be a valid BandAttr");
780 // The name "Loop" signals that this id contains a pointer to a BandAttr.
781 // The ScheduleOptimizer also uses the string "Inter iteration alias-free" in
782 // markers, but it's user pointer is an llvm::Value.
783 isl::id Result = isl::id::alloc(Ctx, "Loop with Metadata", Attr);
784 Result = isl::manage(isl_id_set_free_user(Result.release(), [](void *Ptr) {
785 BandAttr *Attr = reinterpret_cast<BandAttr *>(Ptr);
786 delete Attr;
787 }));
788 return Result;
791 isl::id polly::createIslLoopAttr(isl::ctx Ctx, Loop *L) {
792 if (!L)
793 return {};
795 // A loop without metadata does not need to be annotated.
796 MDNode *LoopID = L->getLoopID();
797 if (!LoopID)
798 return {};
800 BandAttr *Attr = new BandAttr();
801 Attr->OriginalLoop = L;
802 Attr->Metadata = L->getLoopID();
804 return getIslLoopAttr(Ctx, Attr);
807 bool polly::isLoopAttr(const isl::id &Id) {
808 if (Id.is_null())
809 return false;
811 return Id.get_name() == "Loop with Metadata";
814 BandAttr *polly::getLoopAttr(const isl::id &Id) {
815 if (!isLoopAttr(Id))
816 return nullptr;
818 return reinterpret_cast<BandAttr *>(Id.get_user());