1 //===- ScopHelper.cpp - Some Helper Functions for Scop. ------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
27 using namespace polly
;
29 #define DEBUG_TYPE "polly-scop-helper"
31 static cl::list
<std::string
> DebugFunctions(
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
40 // The identity of the region entry node is preserved.
41 static void simplifyRegionEntry(Region
*R
, DominatorTree
*DT
, LoopInfo
*LI
,
43 BasicBlock
*EnteringBB
= R
->getEnteringBlock();
44 BasicBlock
*Entry
= R
->getEntry();
52 // Entry <--\ Entry <--\ //
56 // Create single entry edge if the region has multiple entry edges.
58 SmallVector
<BasicBlock
*, 4> Preds
;
59 for (BasicBlock
*P
: predecessors(Entry
))
63 BasicBlock
*NewEntering
=
64 SplitBlockPredecessors(Entry
, Preds
, ".region_entering", DT
, LI
);
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
)
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
);
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
,
107 BasicBlock
*ExitBB
= R
->getExit();
108 BasicBlock
*ExitingBB
= R
->getExitingBlock();
112 // (Region) ______/ //
118 SmallVector
<BasicBlock
*, 4> Preds
;
119 for (BasicBlock
*P
: predecessors(ExitBB
))
123 // Preds[0] Preds[1] otherBB //
128 SplitBlockPredecessors(ExitBB
, Preds
, ".region_exiting", DT
, LI
);
129 // Preds[0] Preds[1] otherBB //
131 // BB.region_exiting / //
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());
147 // ExitingBB _____/ //
153 void polly::simplifyRegion(Region
*R
, DominatorTree
*DT
, LoopInfo
*LI
,
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
,
171 assert(Old
&& SplitPt
);
179 BasicBlock
*NewBlock
= llvm::SplitBlock(Old
, SplitPt
, DT
, LI
);
182 Region
*R
= RI
->getRegionFor(Old
);
183 RI
->setRegionFor(NewBlock
, R
);
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
))
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
,
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.
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
))
261 const SCEV
*Result
= SCEVVisitor::visit(E
);
262 SCEVCache
[E
] = Result
;
267 SCEVExpander Expander
;
273 DenseMap
<const SCEV
*, const SCEV
*> SCEVCache
;
275 const SCEV
*visitGenericInst(const SCEVUnknown
*E
, Instruction
*Inst
,
277 if (!Inst
|| !R
.contains(Inst
))
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;
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.
309 Instruction
*Inst
= dyn_cast
<Instruction
>(E
->getValue());
311 if (Inst
&& !R
.contains(Inst
))
313 else if (Inst
&& RTCBB
->getParent() == Inst
->getFunction())
314 IP
= RTCBB
->getTerminator();
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.
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());
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
,
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();
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());
441 bool AllContained
= true;
442 for (auto *BB
: S
.blocks())
443 AllContained
&= L
->contains(BB
);
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()))
464 unsigned polly::getNumBlocksInRegionNode(RegionNode
*RN
) {
465 if (!RN
->isSubRegion())
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++) {
490 // abort(); <- this abort might be translated to an
495 if (!L
&& isa
<UnreachableInst
>(BB
->getTerminator()) && BB
->getPrevNode())
496 L
= LI
.getLoopFor(BB
->getPrevNode());
500 Region
*NonAffineSubRegion
= RN
->getNodeAs
<Region
>();
501 Loop
*L
= LI
.getLoopFor(NonAffineSubRegion
->getEntry());
502 while (L
&& NonAffineSubRegion
->contains(L
))
503 L
= L
->getParentLoop();
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
))
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
))
541 const SCEV
*PtrSCEV
= SE
.getSCEVAtScope(Ptr
, L
);
542 while (L
&& R
.contains(L
)) {
543 if (!SE
.isLoopInvariant(PtrSCEV
, L
))
545 L
= L
->getParentLoop();
548 for (auto *User
: Ptr
->users()) {
549 auto *UserI
= dyn_cast
<Instruction
>(User
);
550 if (!UserI
|| !R
.contains(UserI
))
552 if (!UserI
->mayWriteToMemory())
555 auto &BB
= *UserI
->getParent();
556 if (DT
.dominates(&BB
, LInst
->getParent()))
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;
565 for (auto Pred
: predecessors(R
.getExit()))
566 if (R
.contains(Pred
) && !DT
.dominates(&BB
, Pred
))
567 DominatesAllPredecessors
= false;
570 if (!DominatesAllPredecessors
)
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
:
605 bool polly::canSynthesize(const Value
*V
, const Scop
&S
, ScalarEvolution
*SE
,
607 if (!V
|| !SE
->isSCEVable(V
->getType()))
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
))
619 llvm::BasicBlock
*polly::getUseBlock(const llvm::Use
&U
) {
620 Instruction
*UI
= dyn_cast
<Instruction
>(U
.getUser());
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();
637 llvm::Loop
*polly::getFirstNonBoxedLoopFor(llvm::BasicBlock
*BB
,
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
);
649 Function
*CF
= CI
->getCalledFunction();
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
))
665 bool polly::hasDebugCall(ScopStmt
*Stmt
) {
666 // Quick skip if no debug functions have been defined.
667 if (DebugFunctions
.empty())
673 for (Instruction
*Inst
: Stmt
->getInstructions())
674 if (isDebugCall(Inst
))
677 if (Stmt
->isRegionStmt()) {
678 for (BasicBlock
*RBB
: Stmt
->getRegion()->blocks())
679 if (RBB
!= Stmt
->getEntryBlock() && ::hasDebugCall(RBB
))
686 /// Find a property in a LoopID.
687 static MDNode
*findNamedMetadataNode(MDNode
*LoopMD
, StringRef Name
) {
690 for (const MDOperand
&X
: drop_begin(LoopMD
->operands(), 1)) {
691 auto *OpNode
= dyn_cast
<MDNode
>(X
.get());
695 auto *OpName
= dyn_cast
<MDString
>(OpNode
->getOperand(0));
698 if (OpName
->getString() == Name
)
704 static std::optional
<const MDOperand
*> findNamedMetadataArg(MDNode
*LoopID
,
706 MDNode
*MD
= findNamedMetadataNode(LoopID
, Name
);
709 switch (MD
->getNumOperands()) {
713 return &MD
->getOperand(1);
715 llvm_unreachable("loop metadata has 0 or 1 operand");
719 std::optional
<Metadata
*> polly::findMetadataOperand(MDNode
*LoopMD
,
721 MDNode
*MD
= findNamedMetadataNode(LoopMD
, Name
);
724 switch (MD
->getNumOperands()) {
728 return MD
->getOperand(1).get();
730 llvm_unreachable("loop metadata must have 0 or 1 operands");
734 static std::optional
<bool> getOptionalBoolLoopAttribute(MDNode
*LoopID
,
736 MDNode
*MD
= findNamedMetadataNode(LoopID
, Name
);
739 switch (MD
->getNumOperands()) {
743 if (ConstantInt
*IntMD
=
744 mdconst::extract_or_null
<ConstantInt
>(MD
->getOperand(1).get()))
745 return IntMD
->getZExtValue();
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
,
757 const MDOperand
*AttrMD
=
758 findNamedMetadataArg(LoopID
, Name
).value_or(nullptr);
762 ConstantInt
*IntMD
= mdconst::extract_or_null
<ConstantInt
>(AttrMD
->get());
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
);
791 isl::id
polly::createIslLoopAttr(isl::ctx Ctx
, Loop
*L
) {
795 // A loop without metadata does not need to be annotated.
796 MDNode
*LoopID
= L
->getLoopID();
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
) {
811 return Id
.get_name() == "Loop with Metadata";
814 BandAttr
*polly::getLoopAttr(const isl::id
&Id
) {
818 return reinterpret_cast<BandAttr
*>(Id
.get_user());