175805378STobias Grosser //===- ScopHelper.cpp - Some Helper Functions for Scop.  ------------------===//
275805378STobias Grosser //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
675805378STobias Grosser //
775805378STobias Grosser //===----------------------------------------------------------------------===//
875805378STobias Grosser //
975805378STobias Grosser // Small functions that help with Scop and LLVM-IR.
1075805378STobias Grosser //
1175805378STobias Grosser //===----------------------------------------------------------------------===//
1275805378STobias Grosser 
1375805378STobias Grosser #include "polly/Support/ScopHelper.h"
14f80f3b04SJohannes Doerfert #include "polly/Options.h"
158edce4eeSTobias Grosser #include "polly/ScopInfo.h"
16f363ed98SJohannes Doerfert #include "polly/Support/SCEVValidator.h"
1775805378STobias Grosser #include "llvm/Analysis/LoopInfo.h"
1875805378STobias Grosser #include "llvm/Analysis/RegionInfo.h"
1975805378STobias Grosser #include "llvm/Analysis/ScalarEvolution.h"
2075805378STobias Grosser #include "llvm/Analysis/ScalarEvolutionExpressions.h"
2175805378STobias Grosser #include "llvm/Transforms/Utils/BasicBlockUtils.h"
223f170eb1SMichael Kruse #include "llvm/Transforms/Utils/LoopUtils.h"
237004a621SFlorian Hahn #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
2475805378STobias Grosser 
2575805378STobias Grosser using namespace llvm;
26e69e1141SJohannes Doerfert using namespace polly;
2775805378STobias Grosser 
2895fef944SChandler Carruth #define DEBUG_TYPE "polly-scop-helper"
2995fef944SChandler Carruth 
305369ea5dSMichael Kruse static cl::list<std::string> DebugFunctions(
315369ea5dSMichael Kruse     "polly-debug-func",
325369ea5dSMichael Kruse     cl::desc("Allow calls to the specified functions in SCoPs even if their "
335369ea5dSMichael Kruse              "side-effects are unknown. This can be used to do debug output in "
345369ea5dSMichael Kruse              "Polly-transformed code."),
35d86a206fSFangrui Song     cl::Hidden, cl::CommaSeparated, cl::cat(PollyCategory));
365369ea5dSMichael Kruse 
3722370884SMichael Kruse // Ensures that there is just one predecessor to the entry node from outside the
3822370884SMichael Kruse // region.
3922370884SMichael Kruse // The identity of the region entry node is preserved.
simplifyRegionEntry(Region * R,DominatorTree * DT,LoopInfo * LI,RegionInfo * RI)4022370884SMichael Kruse static void simplifyRegionEntry(Region *R, DominatorTree *DT, LoopInfo *LI,
4122370884SMichael Kruse                                 RegionInfo *RI) {
420fe35dd0SJohannes Doerfert   BasicBlock *EnteringBB = R->getEnteringBlock();
4322370884SMichael Kruse   BasicBlock *Entry = R->getEntry();
440fe35dd0SJohannes Doerfert 
4522370884SMichael Kruse   // Before (one of):
4622370884SMichael Kruse   //
4722370884SMichael Kruse   //                       \    /            //
4822370884SMichael Kruse   //                      EnteringBB         //
4922370884SMichael Kruse   //                        |    \------>    //
5022370884SMichael Kruse   //   \   /                |                //
5122370884SMichael Kruse   //   Entry <--\         Entry <--\         //
5222370884SMichael Kruse   //   /   \    /         /   \    /         //
5322370884SMichael Kruse   //        ....               ....          //
545ec3333dSChandler Carruth 
5562975f55SChandler Carruth   // Create single entry edge if the region has multiple entry edges.
5662975f55SChandler Carruth   if (!EnteringBB) {
5722370884SMichael Kruse     SmallVector<BasicBlock *, 4> Preds;
5822370884SMichael Kruse     for (BasicBlock *P : predecessors(Entry))
5922370884SMichael Kruse       if (!R->contains(P))
6022370884SMichael Kruse         Preds.push_back(P);
6122370884SMichael Kruse 
6222370884SMichael Kruse     BasicBlock *NewEntering =
6322370884SMichael Kruse         SplitBlockPredecessors(Entry, Preds, ".region_entering", DT, LI);
6422370884SMichael Kruse 
6522370884SMichael Kruse     if (RI) {
6622370884SMichael Kruse       // The exit block of predecessing regions must be changed to NewEntering
6722370884SMichael Kruse       for (BasicBlock *ExitPred : predecessors(NewEntering)) {
6822370884SMichael Kruse         Region *RegionOfPred = RI->getRegionFor(ExitPred);
6922370884SMichael Kruse         if (RegionOfPred->getExit() != Entry)
7022370884SMichael Kruse           continue;
7122370884SMichael Kruse 
7222370884SMichael Kruse         while (!RegionOfPred->isTopLevelRegion() &&
7322370884SMichael Kruse                RegionOfPred->getExit() == Entry) {
7422370884SMichael Kruse           RegionOfPred->replaceExit(NewEntering);
7522370884SMichael Kruse           RegionOfPred = RegionOfPred->getParent();
7622370884SMichael Kruse         }
7738262244SJohannes Doerfert       }
7838262244SJohannes Doerfert 
7922370884SMichael Kruse       // Make all ancestors use EnteringBB as entry; there might be edges to it
8022370884SMichael Kruse       Region *AncestorR = R->getParent();
8122370884SMichael Kruse       RI->setRegionFor(NewEntering, AncestorR);
8222370884SMichael Kruse       while (!AncestorR->isTopLevelRegion() && AncestorR->getEntry() == Entry) {
8322370884SMichael Kruse         AncestorR->replaceEntry(NewEntering);
8422370884SMichael Kruse         AncestorR = AncestorR->getParent();
8522370884SMichael Kruse       }
8622370884SMichael Kruse     }
870fe35dd0SJohannes Doerfert 
8822370884SMichael Kruse     EnteringBB = NewEntering;
8922370884SMichael Kruse   }
9022370884SMichael Kruse   assert(R->getEnteringBlock() == EnteringBB);
9122370884SMichael Kruse 
9222370884SMichael Kruse   // After:
930fe35dd0SJohannes Doerfert   //
9422370884SMichael Kruse   //    \    /       //
9522370884SMichael Kruse   //  EnteringBB     //
9622370884SMichael Kruse   //      |          //
9722370884SMichael Kruse   //      |          //
9822370884SMichael Kruse   //    Entry <--\   //
9922370884SMichael Kruse   //    /   \    /   //
10022370884SMichael Kruse   //         ....    //
10122370884SMichael Kruse }
10222370884SMichael Kruse 
10322370884SMichael Kruse // Ensure that the region has a single block that branches to the exit node.
simplifyRegionExit(Region * R,DominatorTree * DT,LoopInfo * LI,RegionInfo * RI)10422370884SMichael Kruse static void simplifyRegionExit(Region *R, DominatorTree *DT, LoopInfo *LI,
10522370884SMichael Kruse                                RegionInfo *RI) {
10622370884SMichael Kruse   BasicBlock *ExitBB = R->getExit();
10722370884SMichael Kruse   BasicBlock *ExitingBB = R->getExitingBlock();
10822370884SMichael Kruse 
10922370884SMichael Kruse   // Before:
1100fe35dd0SJohannes Doerfert   //
11122370884SMichael Kruse   //   (Region)   ______/  //
11222370884SMichael Kruse   //      \  |   /         //
11322370884SMichael Kruse   //       ExitBB          //
11422370884SMichael Kruse   //       /    \          //
1150fe35dd0SJohannes Doerfert 
11622370884SMichael Kruse   if (!ExitingBB) {
11722370884SMichael Kruse     SmallVector<BasicBlock *, 4> Preds;
11822370884SMichael Kruse     for (BasicBlock *P : predecessors(ExitBB))
11922370884SMichael Kruse       if (R->contains(P))
12022370884SMichael Kruse         Preds.push_back(P);
12122370884SMichael Kruse 
12222370884SMichael Kruse     //  Preds[0] Preds[1]      otherBB //
12322370884SMichael Kruse     //         \  |  ________/         //
12422370884SMichael Kruse     //          \ | /                  //
12522370884SMichael Kruse     //           BB                    //
12622370884SMichael Kruse     ExitingBB =
12722370884SMichael Kruse         SplitBlockPredecessors(ExitBB, Preds, ".region_exiting", DT, LI);
12822370884SMichael Kruse     // Preds[0] Preds[1]      otherBB  //
12922370884SMichael Kruse     //        \  /           /         //
13022370884SMichael Kruse     // BB.region_exiting    /          //
13122370884SMichael Kruse     //                  \  /           //
13222370884SMichael Kruse     //                   BB            //
13322370884SMichael Kruse 
13422370884SMichael Kruse     if (RI)
13522370884SMichael Kruse       RI->setRegionFor(ExitingBB, R);
13622370884SMichael Kruse 
13722370884SMichael Kruse     // Change the exit of nested regions, but not the region itself,
13822370884SMichael Kruse     R->replaceExitRecursive(ExitingBB);
13922370884SMichael Kruse     R->replaceExit(ExitBB);
14022370884SMichael Kruse   }
14122370884SMichael Kruse   assert(ExitingBB == R->getExitingBlock());
14222370884SMichael Kruse 
14322370884SMichael Kruse   // After:
14422370884SMichael Kruse   //
14522370884SMichael Kruse   //     \   /                //
14622370884SMichael Kruse   //    ExitingBB     _____/  //
14722370884SMichael Kruse   //          \      /        //
14822370884SMichael Kruse   //           ExitBB         //
14922370884SMichael Kruse   //           /    \         //
1500fe35dd0SJohannes Doerfert }
1510fe35dd0SJohannes Doerfert 
simplifyRegion(Region * R,DominatorTree * DT,LoopInfo * LI,RegionInfo * RI)15222370884SMichael Kruse void polly::simplifyRegion(Region *R, DominatorTree *DT, LoopInfo *LI,
15322370884SMichael Kruse                            RegionInfo *RI) {
15422370884SMichael Kruse   assert(R && !R->isTopLevelRegion());
15522370884SMichael Kruse   assert(!RI || RI == R->getRegionInfo());
15622370884SMichael Kruse   assert((!RI || DT) &&
15722370884SMichael Kruse          "RegionInfo requires DominatorTree to be updated as well");
1588edce4eeSTobias Grosser 
15922370884SMichael Kruse   simplifyRegionEntry(R, DT, LI, RI);
16022370884SMichael Kruse   simplifyRegionExit(R, DT, LI, RI);
16122370884SMichael Kruse   assert(R->isSimple());
1628edce4eeSTobias Grosser }
1638edce4eeSTobias Grosser 
16423d0e83aSMichael Kruse // Split the block into two successive blocks.
16523d0e83aSMichael Kruse //
16623d0e83aSMichael Kruse // Like llvm::SplitBlock, but also preserves RegionInfo
splitBlock(BasicBlock * Old,Instruction * SplitPt,DominatorTree * DT,llvm::LoopInfo * LI,RegionInfo * RI)16723d0e83aSMichael Kruse static BasicBlock *splitBlock(BasicBlock *Old, Instruction *SplitPt,
16823d0e83aSMichael Kruse                               DominatorTree *DT, llvm::LoopInfo *LI,
16923d0e83aSMichael Kruse                               RegionInfo *RI) {
17023d0e83aSMichael Kruse   assert(Old && SplitPt);
17123d0e83aSMichael Kruse 
17223d0e83aSMichael Kruse   // Before:
17323d0e83aSMichael Kruse   //
17423d0e83aSMichael Kruse   //  \   /  //
17523d0e83aSMichael Kruse   //   Old   //
17623d0e83aSMichael Kruse   //  /   \  //
17723d0e83aSMichael Kruse 
17823d0e83aSMichael Kruse   BasicBlock *NewBlock = llvm::SplitBlock(Old, SplitPt, DT, LI);
17923d0e83aSMichael Kruse 
18023d0e83aSMichael Kruse   if (RI) {
18123d0e83aSMichael Kruse     Region *R = RI->getRegionFor(Old);
18223d0e83aSMichael Kruse     RI->setRegionFor(NewBlock, R);
18323d0e83aSMichael Kruse   }
18423d0e83aSMichael Kruse 
18523d0e83aSMichael Kruse   // After:
18623d0e83aSMichael Kruse   //
18723d0e83aSMichael Kruse   //   \   /    //
18823d0e83aSMichael Kruse   //    Old     //
18923d0e83aSMichael Kruse   //     |      //
19023d0e83aSMichael Kruse   //  NewBlock  //
19123d0e83aSMichael Kruse   //   /   \    //
19223d0e83aSMichael Kruse 
19323d0e83aSMichael Kruse   return NewBlock;
19423d0e83aSMichael Kruse }
19523d0e83aSMichael Kruse 
splitEntryBlockForAlloca(BasicBlock * EntryBlock,DominatorTree * DT,LoopInfo * LI,RegionInfo * RI)196a70e2649SPhilip Pfaffe void polly::splitEntryBlockForAlloca(BasicBlock *EntryBlock, DominatorTree *DT,
197a70e2649SPhilip Pfaffe                                      LoopInfo *LI, RegionInfo *RI) {
198a6d48f59SMichael Kruse   // Find first non-alloca instruction. Every basic block has a non-alloca
19975805378STobias Grosser   // instruction, as every well formed basic block has a terminator.
20075805378STobias Grosser   BasicBlock::iterator I = EntryBlock->begin();
201d535f551STobias Grosser   while (isa<AllocaInst>(I))
202d535f551STobias Grosser     ++I;
20375805378STobias Grosser 
204a70e2649SPhilip Pfaffe   // splitBlock updates DT, LI and RI.
205a70e2649SPhilip Pfaffe   splitBlock(EntryBlock, &*I, DT, LI, RI);
206a70e2649SPhilip Pfaffe }
207a70e2649SPhilip Pfaffe 
splitEntryBlockForAlloca(BasicBlock * EntryBlock,Pass * P)208a70e2649SPhilip Pfaffe void polly::splitEntryBlockForAlloca(BasicBlock *EntryBlock, Pass *P) {
2095ec3333dSChandler Carruth   auto *DTWP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
2105ec3333dSChandler Carruth   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
2115ec3333dSChandler Carruth   auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
2125ec3333dSChandler Carruth   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
21323d0e83aSMichael Kruse   RegionInfoPass *RIP = P->getAnalysisIfAvailable<RegionInfoPass>();
21423d0e83aSMichael Kruse   RegionInfo *RI = RIP ? &RIP->getRegionInfo() : nullptr;
2155ec3333dSChandler Carruth 
21623d0e83aSMichael Kruse   // splitBlock updates DT, LI and RI.
217a70e2649SPhilip Pfaffe   polly::splitEntryBlockForAlloca(EntryBlock, DT, LI, RI);
21875805378STobias Grosser }
219e69e1141SJohannes Doerfert 
recordAssumption(polly::RecordedAssumptionsTy * RecordedAssumptions,polly::AssumptionKind Kind,isl::set Set,DebugLoc Loc,polly::AssumptionSign Sign,BasicBlock * BB,bool RTC)22071544135SDominik Adamski void polly::recordAssumption(polly::RecordedAssumptionsTy *RecordedAssumptions,
22171544135SDominik Adamski                              polly::AssumptionKind Kind, isl::set Set,
22271544135SDominik Adamski                              DebugLoc Loc, polly::AssumptionSign Sign,
2233b9677e1SMichael Kruse                              BasicBlock *BB, bool RTC) {
22471544135SDominik Adamski   assert((Set.is_params() || BB) &&
22571544135SDominik Adamski          "Assumptions without a basic block must be parameter sets");
22671544135SDominik Adamski   if (RecordedAssumptions)
2273b9677e1SMichael Kruse     RecordedAssumptions->push_back({Kind, Sign, Set, Loc, BB, RTC});
22871544135SDominik Adamski }
22971544135SDominik Adamski 
230e69e1141SJohannes Doerfert /// The SCEVExpander will __not__ generate any code for an existing SDiv/SRem
231e69e1141SJohannes Doerfert /// instruction but just use it, if it is referenced as a SCEVUnknown. We want
232e69e1141SJohannes Doerfert /// however to generate new code if the instruction is in the analyzed region
233e69e1141SJohannes Doerfert /// and we generate code outside/in front of that region. Hence, we generate the
234e69e1141SJohannes Doerfert /// code for the SDiv/SRem operands in front of the analyzed region and then
235e69e1141SJohannes Doerfert /// create a new SDiv/SRem operation there too.
236bd93df93SMichael Kruse struct ScopExpander final : SCEVVisitor<ScopExpander, const SCEV *> {
237e69e1141SJohannes Doerfert   friend struct SCEVVisitor<ScopExpander, const SCEV *>;
238e69e1141SJohannes Doerfert 
ScopExpanderScopExpander239b3410db2SJohannes Doerfert   explicit ScopExpander(const Region &R, ScalarEvolution &SE,
240acf80064SEli Friedman                         const DataLayout &DL, const char *Name, ValueMapT *VMap,
241acf80064SEli Friedman                         BasicBlock *RTCBB)
242f75564adSFlorian Hahn       : Expander(SE, DL, Name, /*PreserveLCSSA=*/false), SE(SE), Name(Name),
243f75564adSFlorian Hahn         R(R), VMap(VMap), RTCBB(RTCBB) {}
244e69e1141SJohannes Doerfert 
expandCodeForScopExpander245e69e1141SJohannes Doerfert   Value *expandCodeFor(const SCEV *E, Type *Ty, Instruction *I) {
246e69e1141SJohannes Doerfert     // If we generate code in the region we will immediately fall back to the
247e69e1141SJohannes Doerfert     // SCEVExpander, otherwise we will stop at all unknowns in the SCEV and if
248e69e1141SJohannes Doerfert     // needed replace them by copies computed in the entering block.
249e69e1141SJohannes Doerfert     if (!R.contains(I))
250e69e1141SJohannes Doerfert       E = visit(E);
251e69e1141SJohannes Doerfert     return Expander.expandCodeFor(E, Ty, I);
252e69e1141SJohannes Doerfert   }
253e69e1141SJohannes Doerfert 
visitScopExpander254199caa2eSEli Friedman   const SCEV *visit(const SCEV *E) {
255199caa2eSEli Friedman     // Cache the expansion results for intermediate SCEV expressions. A SCEV
256199caa2eSEli Friedman     // expression can refer to an operand multiple times (e.g. "x*x), so
257199caa2eSEli Friedman     // a naive visitor takes exponential time.
258199caa2eSEli Friedman     if (SCEVCache.count(E))
259199caa2eSEli Friedman       return SCEVCache[E];
260199caa2eSEli Friedman     const SCEV *Result = SCEVVisitor::visit(E);
261199caa2eSEli Friedman     SCEVCache[E] = Result;
262199caa2eSEli Friedman     return Result;
263199caa2eSEli Friedman   }
264199caa2eSEli Friedman 
265e69e1141SJohannes Doerfert private:
266e69e1141SJohannes Doerfert   SCEVExpander Expander;
267e69e1141SJohannes Doerfert   ScalarEvolution &SE;
268e69e1141SJohannes Doerfert   const char *Name;
269e69e1141SJohannes Doerfert   const Region &R;
270c0729a32SJohannes Doerfert   ValueMapT *VMap;
271acf80064SEli Friedman   BasicBlock *RTCBB;
272199caa2eSEli Friedman   DenseMap<const SCEV *, const SCEV *> SCEVCache;
273e69e1141SJohannes Doerfert 
visitGenericInstScopExpander274423642a5STobias Grosser   const SCEV *visitGenericInst(const SCEVUnknown *E, Instruction *Inst,
275423642a5STobias Grosser                                Instruction *IP) {
276423642a5STobias Grosser     if (!Inst || !R.contains(Inst))
277423642a5STobias Grosser       return E;
278423642a5STobias Grosser 
279423642a5STobias Grosser     assert(!Inst->mayThrow() && !Inst->mayReadOrWriteMemory() &&
280423642a5STobias Grosser            !isa<PHINode>(Inst));
281423642a5STobias Grosser 
282423642a5STobias Grosser     auto *InstClone = Inst->clone();
283423642a5STobias Grosser     for (auto &Op : Inst->operands()) {
284423642a5STobias Grosser       assert(SE.isSCEVable(Op->getType()));
285423642a5STobias Grosser       auto *OpSCEV = SE.getSCEV(Op);
286423642a5STobias Grosser       auto *OpClone = expandCodeFor(OpSCEV, Op->getType(), IP);
287423642a5STobias Grosser       InstClone->replaceUsesOfWith(Op, OpClone);
288423642a5STobias Grosser     }
289423642a5STobias Grosser 
290423642a5STobias Grosser     InstClone->setName(Name + Inst->getName());
291423642a5STobias Grosser     InstClone->insertBefore(IP);
292423642a5STobias Grosser     return SE.getSCEV(InstClone);
293423642a5STobias Grosser   }
294423642a5STobias Grosser 
visitUnknownScopExpander295e69e1141SJohannes Doerfert   const SCEV *visitUnknown(const SCEVUnknown *E) {
296c0729a32SJohannes Doerfert 
297c0729a32SJohannes Doerfert     // If a value mapping was given try if the underlying value is remapped.
29885b04dedSJohannes Doerfert     Value *NewVal = VMap ? VMap->lookup(E->getValue()) : nullptr;
29985b04dedSJohannes Doerfert     if (NewVal) {
30085b04dedSJohannes Doerfert       auto *NewE = SE.getSCEV(NewVal);
30185b04dedSJohannes Doerfert 
30285b04dedSJohannes Doerfert       // While the mapped value might be different the SCEV representation might
30385b04dedSJohannes Doerfert       // not be. To this end we will check before we go into recursion here.
30485b04dedSJohannes Doerfert       if (E != NewE)
30585b04dedSJohannes Doerfert         return visit(NewE);
30685b04dedSJohannes Doerfert     }
307c0729a32SJohannes Doerfert 
308e69e1141SJohannes Doerfert     Instruction *Inst = dyn_cast<Instruction>(E->getValue());
309971336d3STobias Grosser     Instruction *IP;
310971336d3STobias Grosser     if (Inst && !R.contains(Inst))
311971336d3STobias Grosser       IP = Inst;
312acf80064SEli Friedman     else if (Inst && RTCBB->getParent() == Inst->getFunction())
313acf80064SEli Friedman       IP = RTCBB->getTerminator();
314971336d3STobias Grosser     else
315acf80064SEli Friedman       IP = RTCBB->getParent()->getEntryBlock().getTerminator();
316971336d3STobias Grosser 
317ff40087aSTobias Grosser     if (!Inst || (Inst->getOpcode() != Instruction::SRem &&
318e69e1141SJohannes Doerfert                   Inst->getOpcode() != Instruction::SDiv))
319971336d3STobias Grosser       return visitGenericInst(E, Inst, IP);
320e69e1141SJohannes Doerfert 
3211a4ad8f7SJohannes Doerfert     const SCEV *LHSScev = SE.getSCEV(Inst->getOperand(0));
3221a4ad8f7SJohannes Doerfert     const SCEV *RHSScev = SE.getSCEV(Inst->getOperand(1));
323e69e1141SJohannes Doerfert 
3241a4ad8f7SJohannes Doerfert     if (!SE.isKnownNonZero(RHSScev))
3251a4ad8f7SJohannes Doerfert       RHSScev = SE.getUMaxExpr(RHSScev, SE.getConstant(E->getType(), 1));
3261a4ad8f7SJohannes Doerfert 
327971336d3STobias Grosser     Value *LHS = expandCodeFor(LHSScev, E->getType(), IP);
328971336d3STobias Grosser     Value *RHS = expandCodeFor(RHSScev, E->getType(), IP);
329e69e1141SJohannes Doerfert 
330e69e1141SJohannes Doerfert     Inst = BinaryOperator::Create((Instruction::BinaryOps)Inst->getOpcode(),
331971336d3STobias Grosser                                   LHS, RHS, Inst->getName() + Name, IP);
332e69e1141SJohannes Doerfert     return SE.getSCEV(Inst);
333e69e1141SJohannes Doerfert   }
334e69e1141SJohannes Doerfert 
335e69e1141SJohannes Doerfert   /// The following functions will just traverse the SCEV and rebuild it with
336e69e1141SJohannes Doerfert   /// the new operands returned by the traversal.
337e69e1141SJohannes Doerfert   ///
338e69e1141SJohannes Doerfert   ///{
visitConstantScopExpander339e69e1141SJohannes Doerfert   const SCEV *visitConstant(const SCEVConstant *E) { return E; }
visitPtrToIntExprScopExpander34081fc53a3SRoman Lebedev   const SCEV *visitPtrToIntExpr(const SCEVPtrToIntExpr *E) {
34181fc53a3SRoman Lebedev     return SE.getPtrToIntExpr(visit(E->getOperand()), E->getType());
34281fc53a3SRoman Lebedev   }
visitTruncateExprScopExpander343e69e1141SJohannes Doerfert   const SCEV *visitTruncateExpr(const SCEVTruncateExpr *E) {
344e69e1141SJohannes Doerfert     return SE.getTruncateExpr(visit(E->getOperand()), E->getType());
345e69e1141SJohannes Doerfert   }
visitZeroExtendExprScopExpander346e69e1141SJohannes Doerfert   const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *E) {
347e69e1141SJohannes Doerfert     return SE.getZeroExtendExpr(visit(E->getOperand()), E->getType());
348e69e1141SJohannes Doerfert   }
visitSignExtendExprScopExpander349e69e1141SJohannes Doerfert   const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *E) {
350e69e1141SJohannes Doerfert     return SE.getSignExtendExpr(visit(E->getOperand()), E->getType());
351e69e1141SJohannes Doerfert   }
visitUDivExprScopExpander352e69e1141SJohannes Doerfert   const SCEV *visitUDivExpr(const SCEVUDivExpr *E) {
353bfaa63a8SJohannes Doerfert     auto *RHSScev = visit(E->getRHS());
354b71900b8SJohannes Doerfert     if (!SE.isKnownNonZero(RHSScev))
3551a4ad8f7SJohannes Doerfert       RHSScev = SE.getUMaxExpr(RHSScev, SE.getConstant(E->getType(), 1));
3561a4ad8f7SJohannes Doerfert     return SE.getUDivExpr(visit(E->getLHS()), RHSScev);
357e69e1141SJohannes Doerfert   }
visitAddExprScopExpander358e69e1141SJohannes Doerfert   const SCEV *visitAddExpr(const SCEVAddExpr *E) {
359e69e1141SJohannes Doerfert     SmallVector<const SCEV *, 4> NewOps;
360e69e1141SJohannes Doerfert     for (const SCEV *Op : E->operands())
361e69e1141SJohannes Doerfert       NewOps.push_back(visit(Op));
362e69e1141SJohannes Doerfert     return SE.getAddExpr(NewOps);
363e69e1141SJohannes Doerfert   }
visitMulExprScopExpander364e69e1141SJohannes Doerfert   const SCEV *visitMulExpr(const SCEVMulExpr *E) {
365e69e1141SJohannes Doerfert     SmallVector<const SCEV *, 4> NewOps;
366e69e1141SJohannes Doerfert     for (const SCEV *Op : E->operands())
367e69e1141SJohannes Doerfert       NewOps.push_back(visit(Op));
368e69e1141SJohannes Doerfert     return SE.getMulExpr(NewOps);
369e69e1141SJohannes Doerfert   }
visitUMaxExprScopExpander370e69e1141SJohannes Doerfert   const SCEV *visitUMaxExpr(const SCEVUMaxExpr *E) {
371e69e1141SJohannes Doerfert     SmallVector<const SCEV *, 4> NewOps;
372e69e1141SJohannes Doerfert     for (const SCEV *Op : E->operands())
373e69e1141SJohannes Doerfert       NewOps.push_back(visit(Op));
374e69e1141SJohannes Doerfert     return SE.getUMaxExpr(NewOps);
375e69e1141SJohannes Doerfert   }
visitSMaxExprScopExpander376e69e1141SJohannes Doerfert   const SCEV *visitSMaxExpr(const SCEVSMaxExpr *E) {
377e69e1141SJohannes Doerfert     SmallVector<const SCEV *, 4> NewOps;
378e69e1141SJohannes Doerfert     for (const SCEV *Op : E->operands())
379e69e1141SJohannes Doerfert       NewOps.push_back(visit(Op));
380e69e1141SJohannes Doerfert     return SE.getSMaxExpr(NewOps);
381e69e1141SJohannes Doerfert   }
visitUMinExprScopExpander382aa1b6f1cSKeno Fischer   const SCEV *visitUMinExpr(const SCEVUMinExpr *E) {
383aa1b6f1cSKeno Fischer     SmallVector<const SCEV *, 4> NewOps;
384aa1b6f1cSKeno Fischer     for (const SCEV *Op : E->operands())
385aa1b6f1cSKeno Fischer       NewOps.push_back(visit(Op));
386aa1b6f1cSKeno Fischer     return SE.getUMinExpr(NewOps);
387aa1b6f1cSKeno Fischer   }
visitSMinExprScopExpander388aa1b6f1cSKeno Fischer   const SCEV *visitSMinExpr(const SCEVSMinExpr *E) {
389aa1b6f1cSKeno Fischer     SmallVector<const SCEV *, 4> NewOps;
390aa1b6f1cSKeno Fischer     for (const SCEV *Op : E->operands())
391aa1b6f1cSKeno Fischer       NewOps.push_back(visit(Op));
392aa1b6f1cSKeno Fischer     return SE.getSMinExpr(NewOps);
393aa1b6f1cSKeno Fischer   }
visitSequentialUMinExprScopExpander39482fb4f4bSRoman Lebedev   const SCEV *visitSequentialUMinExpr(const SCEVSequentialUMinExpr *E) {
39582fb4f4bSRoman Lebedev     SmallVector<const SCEV *, 4> NewOps;
39682fb4f4bSRoman Lebedev     for (const SCEV *Op : E->operands())
39782fb4f4bSRoman Lebedev       NewOps.push_back(visit(Op));
39882fb4f4bSRoman Lebedev     return SE.getUMinExpr(NewOps, /*Sequential=*/true);
39982fb4f4bSRoman Lebedev   }
visitAddRecExprScopExpander400e69e1141SJohannes Doerfert   const SCEV *visitAddRecExpr(const SCEVAddRecExpr *E) {
401e69e1141SJohannes Doerfert     SmallVector<const SCEV *, 4> NewOps;
402e69e1141SJohannes Doerfert     for (const SCEV *Op : E->operands())
403e69e1141SJohannes Doerfert       NewOps.push_back(visit(Op));
404e69e1141SJohannes Doerfert     return SE.getAddRecExpr(NewOps, E->getLoop(), E->getNoWrapFlags());
405e69e1141SJohannes Doerfert   }
406e69e1141SJohannes Doerfert   ///}
407e69e1141SJohannes Doerfert };
408e69e1141SJohannes Doerfert 
expandCodeFor(Scop & S,ScalarEvolution & SE,const DataLayout & DL,const char * Name,const SCEV * E,Type * Ty,Instruction * IP,ValueMapT * VMap,BasicBlock * RTCBB)40909e3697fSJohannes Doerfert Value *polly::expandCodeFor(Scop &S, ScalarEvolution &SE, const DataLayout &DL,
41009e3697fSJohannes Doerfert                             const char *Name, const SCEV *E, Type *Ty,
411acf80064SEli Friedman                             Instruction *IP, ValueMapT *VMap,
412acf80064SEli Friedman                             BasicBlock *RTCBB) {
413acf80064SEli Friedman   ScopExpander Expander(S.getRegion(), SE, DL, Name, VMap, RTCBB);
414e69e1141SJohannes Doerfert   return Expander.expandCodeFor(E, Ty, IP);
415e69e1141SJohannes Doerfert }
41690db75edSJohannes Doerfert 
getConditionFromTerminator(Instruction * TI)417e303c87eSChandler Carruth Value *polly::getConditionFromTerminator(Instruction *TI) {
4189a132f36SJohannes Doerfert   if (BranchInst *BR = dyn_cast<BranchInst>(TI)) {
4199a132f36SJohannes Doerfert     if (BR->isUnconditional())
4209a132f36SJohannes Doerfert       return ConstantInt::getTrue(Type::getInt1Ty(TI->getContext()));
4219a132f36SJohannes Doerfert 
4229a132f36SJohannes Doerfert     return BR->getCondition();
4239a132f36SJohannes Doerfert   }
4249a132f36SJohannes Doerfert 
4259a132f36SJohannes Doerfert   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI))
4269a132f36SJohannes Doerfert     return SI->getCondition();
4279a132f36SJohannes Doerfert 
4289a132f36SJohannes Doerfert   return nullptr;
4299a132f36SJohannes Doerfert }
43009e3697fSJohannes Doerfert 
getLoopSurroundingScop(Scop & S,LoopInfo & LI)431d0ac007fSDominik Adamski Loop *polly::getLoopSurroundingScop(Scop &S, LoopInfo &LI) {
432d0ac007fSDominik Adamski   // Start with the smallest loop containing the entry and expand that
433d0ac007fSDominik Adamski   // loop until it contains all blocks in the region. If there is a loop
434d0ac007fSDominik Adamski   // containing all blocks in the region check if it is itself contained
435d0ac007fSDominik Adamski   // and if so take the parent loop as it will be the smallest containing
436d0ac007fSDominik Adamski   // the region but not contained by it.
437d0ac007fSDominik Adamski   Loop *L = LI.getLoopFor(S.getEntry());
438d0ac007fSDominik Adamski   while (L) {
439d0ac007fSDominik Adamski     bool AllContained = true;
440d0ac007fSDominik Adamski     for (auto *BB : S.blocks())
441d0ac007fSDominik Adamski       AllContained &= L->contains(BB);
442d0ac007fSDominik Adamski     if (AllContained)
443d0ac007fSDominik Adamski       break;
444d0ac007fSDominik Adamski     L = L->getParentLoop();
445d0ac007fSDominik Adamski   }
446d0ac007fSDominik Adamski 
447d0ac007fSDominik Adamski   return L ? (S.contains(L) ? L->getParentLoop() : L) : nullptr;
448d0ac007fSDominik Adamski }
449d0ac007fSDominik Adamski 
getNumBlocksInLoop(Loop * L)450d0ac007fSDominik Adamski unsigned polly::getNumBlocksInLoop(Loop *L) {
451d0ac007fSDominik Adamski   unsigned NumBlocks = L->getNumBlocks();
452d0ac007fSDominik Adamski   SmallVector<BasicBlock *, 4> ExitBlocks;
453d0ac007fSDominik Adamski   L->getExitBlocks(ExitBlocks);
454d0ac007fSDominik Adamski 
455d0ac007fSDominik Adamski   for (auto ExitBlock : ExitBlocks) {
456d0ac007fSDominik Adamski     if (isa<UnreachableInst>(ExitBlock->getTerminator()))
457d0ac007fSDominik Adamski       NumBlocks++;
458d0ac007fSDominik Adamski   }
459d0ac007fSDominik Adamski   return NumBlocks;
460d0ac007fSDominik Adamski }
461d0ac007fSDominik Adamski 
getNumBlocksInRegionNode(RegionNode * RN)462d0ac007fSDominik Adamski unsigned polly::getNumBlocksInRegionNode(RegionNode *RN) {
463d0ac007fSDominik Adamski   if (!RN->isSubRegion())
464d0ac007fSDominik Adamski     return 1;
465d0ac007fSDominik Adamski 
466d0ac007fSDominik Adamski   Region *R = RN->getNodeAs<Region>();
467d0ac007fSDominik Adamski   return std::distance(R->block_begin(), R->block_end());
468d0ac007fSDominik Adamski }
469d0ac007fSDominik Adamski 
getRegionNodeLoop(RegionNode * RN,LoopInfo & LI)470d0ac007fSDominik Adamski Loop *polly::getRegionNodeLoop(RegionNode *RN, LoopInfo &LI) {
471d0ac007fSDominik Adamski   if (!RN->isSubRegion()) {
472d0ac007fSDominik Adamski     BasicBlock *BB = RN->getNodeAs<BasicBlock>();
473d0ac007fSDominik Adamski     Loop *L = LI.getLoopFor(BB);
474d0ac007fSDominik Adamski 
475d0ac007fSDominik Adamski     // Unreachable statements are not considered to belong to a LLVM loop, as
476d0ac007fSDominik Adamski     // they are not part of an actual loop in the control flow graph.
477d0ac007fSDominik Adamski     // Nevertheless, we handle certain unreachable statements that are common
478d0ac007fSDominik Adamski     // when modeling run-time bounds checks as being part of the loop to be
479d0ac007fSDominik Adamski     // able to model them and to later eliminate the run-time bounds checks.
480d0ac007fSDominik Adamski     //
481d0ac007fSDominik Adamski     // Specifically, for basic blocks that terminate in an unreachable and
482d0ac007fSDominik Adamski     // where the immediate predecessor is part of a loop, we assume these
483d0ac007fSDominik Adamski     // basic blocks belong to the loop the predecessor belongs to. This
484d0ac007fSDominik Adamski     // allows us to model the following code.
485d0ac007fSDominik Adamski     //
486d0ac007fSDominik Adamski     // for (i = 0; i < N; i++) {
487d0ac007fSDominik Adamski     //   if (i > 1024)
488d0ac007fSDominik Adamski     //     abort();            <- this abort might be translated to an
489d0ac007fSDominik Adamski     //                            unreachable
490d0ac007fSDominik Adamski     //
491d0ac007fSDominik Adamski     //   A[i] = ...
492d0ac007fSDominik Adamski     // }
493d0ac007fSDominik Adamski     if (!L && isa<UnreachableInst>(BB->getTerminator()) && BB->getPrevNode())
494d0ac007fSDominik Adamski       L = LI.getLoopFor(BB->getPrevNode());
495d0ac007fSDominik Adamski     return L;
496d0ac007fSDominik Adamski   }
497d0ac007fSDominik Adamski 
498d0ac007fSDominik Adamski   Region *NonAffineSubRegion = RN->getNodeAs<Region>();
499d0ac007fSDominik Adamski   Loop *L = LI.getLoopFor(NonAffineSubRegion->getEntry());
500d0ac007fSDominik Adamski   while (L && NonAffineSubRegion->contains(L))
501d0ac007fSDominik Adamski     L = L->getParentLoop();
502d0ac007fSDominik Adamski   return L;
503d0ac007fSDominik Adamski }
504d0ac007fSDominik Adamski 
hasVariantIndex(GetElementPtrInst * Gep,Loop * L,Region & R,ScalarEvolution & SE)505ec1a3048SPhilip Pfaffe static bool hasVariantIndex(GetElementPtrInst *Gep, Loop *L, Region &R,
506ec1a3048SPhilip Pfaffe                             ScalarEvolution &SE) {
507ec1a3048SPhilip Pfaffe   for (const Use &Val : llvm::drop_begin(Gep->operands(), 1)) {
508ec1a3048SPhilip Pfaffe     const SCEV *PtrSCEV = SE.getSCEVAtScope(Val, L);
509ec1a3048SPhilip Pfaffe     Loop *OuterLoop = R.outermostLoopInRegion(L);
510ec1a3048SPhilip Pfaffe     if (!SE.isLoopInvariant(PtrSCEV, OuterLoop))
511ec1a3048SPhilip Pfaffe       return true;
512ec1a3048SPhilip Pfaffe   }
513ec1a3048SPhilip Pfaffe   return false;
514ec1a3048SPhilip Pfaffe }
515ec1a3048SPhilip Pfaffe 
isHoistableLoad(LoadInst * LInst,Region & R,LoopInfo & LI,ScalarEvolution & SE,const DominatorTree & DT,const InvariantLoadsSetTy & KnownInvariantLoads)51609e3697fSJohannes Doerfert bool polly::isHoistableLoad(LoadInst *LInst, Region &R, LoopInfo &LI,
517ec1a3048SPhilip Pfaffe                             ScalarEvolution &SE, const DominatorTree &DT,
518ec1a3048SPhilip Pfaffe                             const InvariantLoadsSetTy &KnownInvariantLoads) {
51909e3697fSJohannes Doerfert   Loop *L = LI.getLoopFor(LInst->getParent());
5206cd59e90SJohannes Doerfert   auto *Ptr = LInst->getPointerOperand();
521ec1a3048SPhilip Pfaffe 
522ec1a3048SPhilip Pfaffe   // A LoadInst is hoistable if the address it is loading from is also
523ec1a3048SPhilip Pfaffe   // invariant; in this case: another invariant load (whether that address
524ec1a3048SPhilip Pfaffe   // is also not written to has to be checked separately)
525ec1a3048SPhilip Pfaffe   // TODO: This only checks for a LoadInst->GetElementPtrInst->LoadInst
526ec1a3048SPhilip Pfaffe   // pattern generated by the Chapel frontend, but generally this applies
527ec1a3048SPhilip Pfaffe   // for any chain of instruction that does not also depend on any
528ec1a3048SPhilip Pfaffe   // induction variable
529ec1a3048SPhilip Pfaffe   if (auto *GepInst = dyn_cast<GetElementPtrInst>(Ptr)) {
530ec1a3048SPhilip Pfaffe     if (!hasVariantIndex(GepInst, L, R, SE)) {
531ec1a3048SPhilip Pfaffe       if (auto *DecidingLoad =
532ec1a3048SPhilip Pfaffe               dyn_cast<LoadInst>(GepInst->getPointerOperand())) {
533ec1a3048SPhilip Pfaffe         if (KnownInvariantLoads.count(DecidingLoad))
534ec1a3048SPhilip Pfaffe           return true;
535ec1a3048SPhilip Pfaffe       }
536ec1a3048SPhilip Pfaffe     }
537ec1a3048SPhilip Pfaffe   }
538ec1a3048SPhilip Pfaffe 
5396cd59e90SJohannes Doerfert   const SCEV *PtrSCEV = SE.getSCEVAtScope(Ptr, L);
54009e3697fSJohannes Doerfert   while (L && R.contains(L)) {
54109e3697fSJohannes Doerfert     if (!SE.isLoopInvariant(PtrSCEV, L))
54209e3697fSJohannes Doerfert       return false;
54309e3697fSJohannes Doerfert     L = L->getParentLoop();
54409e3697fSJohannes Doerfert   }
54509e3697fSJohannes Doerfert 
5466cd59e90SJohannes Doerfert   for (auto *User : Ptr->users()) {
5476cd59e90SJohannes Doerfert     auto *UserI = dyn_cast<Instruction>(User);
5486cd59e90SJohannes Doerfert     if (!UserI || !R.contains(UserI))
5496cd59e90SJohannes Doerfert       continue;
5506cd59e90SJohannes Doerfert     if (!UserI->mayWriteToMemory())
5516cd59e90SJohannes Doerfert       continue;
5526cd59e90SJohannes Doerfert 
5536cd59e90SJohannes Doerfert     auto &BB = *UserI->getParent();
554b6c5a5ddSJohannes Doerfert     if (DT.dominates(&BB, LInst->getParent()))
555b6c5a5ddSJohannes Doerfert       return false;
556b6c5a5ddSJohannes Doerfert 
5576cd59e90SJohannes Doerfert     bool DominatesAllPredecessors = true;
5584fe21814SPhilip Pfaffe     if (R.isTopLevelRegion()) {
5594fe21814SPhilip Pfaffe       for (BasicBlock &I : *R.getEntry()->getParent())
5604fe21814SPhilip Pfaffe         if (isa<ReturnInst>(I.getTerminator()) && !DT.dominates(&BB, &I))
5614fe21814SPhilip Pfaffe           DominatesAllPredecessors = false;
5624fe21814SPhilip Pfaffe     } else {
5636cd59e90SJohannes Doerfert       for (auto Pred : predecessors(R.getExit()))
5646cd59e90SJohannes Doerfert         if (R.contains(Pred) && !DT.dominates(&BB, Pred))
5656cd59e90SJohannes Doerfert           DominatesAllPredecessors = false;
5664fe21814SPhilip Pfaffe     }
5676cd59e90SJohannes Doerfert 
5686cd59e90SJohannes Doerfert     if (!DominatesAllPredecessors)
5696cd59e90SJohannes Doerfert       continue;
5706cd59e90SJohannes Doerfert 
5716cd59e90SJohannes Doerfert     return false;
5726cd59e90SJohannes Doerfert   }
5736cd59e90SJohannes Doerfert 
57409e3697fSJohannes Doerfert   return true;
57509e3697fSJohannes Doerfert }
576f363ed98SJohannes Doerfert 
isIgnoredIntrinsic(const Value * V)577f363ed98SJohannes Doerfert bool polly::isIgnoredIntrinsic(const Value *V) {
578f363ed98SJohannes Doerfert   if (auto *IT = dyn_cast<IntrinsicInst>(V)) {
579f363ed98SJohannes Doerfert     switch (IT->getIntrinsicID()) {
580f363ed98SJohannes Doerfert     // Lifetime markers are supported/ignored.
581f363ed98SJohannes Doerfert     case llvm::Intrinsic::lifetime_start:
582f363ed98SJohannes Doerfert     case llvm::Intrinsic::lifetime_end:
583f363ed98SJohannes Doerfert     // Invariant markers are supported/ignored.
584f363ed98SJohannes Doerfert     case llvm::Intrinsic::invariant_start:
585f363ed98SJohannes Doerfert     case llvm::Intrinsic::invariant_end:
586f363ed98SJohannes Doerfert     // Some misc annotations are supported/ignored.
587f363ed98SJohannes Doerfert     case llvm::Intrinsic::var_annotation:
588f363ed98SJohannes Doerfert     case llvm::Intrinsic::ptr_annotation:
589f363ed98SJohannes Doerfert     case llvm::Intrinsic::annotation:
590f363ed98SJohannes Doerfert     case llvm::Intrinsic::donothing:
591f363ed98SJohannes Doerfert     case llvm::Intrinsic::assume:
592a6d48f59SMichael Kruse     // Some debug info intrinsics are supported/ignored.
593f363ed98SJohannes Doerfert     case llvm::Intrinsic::dbg_value:
594f363ed98SJohannes Doerfert     case llvm::Intrinsic::dbg_declare:
595f363ed98SJohannes Doerfert       return true;
596f363ed98SJohannes Doerfert     default:
597f363ed98SJohannes Doerfert       break;
598f363ed98SJohannes Doerfert     }
599f363ed98SJohannes Doerfert   }
600f363ed98SJohannes Doerfert   return false;
601f363ed98SJohannes Doerfert }
602f363ed98SJohannes Doerfert 
canSynthesize(const Value * V,const Scop & S,ScalarEvolution * SE,Loop * Scope)60311c5e079SMichael Kruse bool polly::canSynthesize(const Value *V, const Scop &S, ScalarEvolution *SE,
6040f0d209bSJohannes Doerfert                           Loop *Scope) {
605f363ed98SJohannes Doerfert   if (!V || !SE->isSCEVable(V->getType()))
606f363ed98SJohannes Doerfert     return false;
607f363ed98SJohannes Doerfert 
608a1b2086aSSiddharth Bhat   const InvariantLoadsSetTy &ILS = S.getRequiredInvariantLoads();
609c7e0d9c2SMichael Kruse   if (const SCEV *Scev = SE->getSCEVAtScope(const_cast<Value *>(V), Scope))
610f363ed98SJohannes Doerfert     if (!isa<SCEVCouldNotCompute>(Scev))
611a1b2086aSSiddharth Bhat       if (!hasScalarDepsInsideRegion(Scev, &S.getRegion(), Scope, false, ILS))
612f363ed98SJohannes Doerfert         return true;
613f363ed98SJohannes Doerfert 
614f363ed98SJohannes Doerfert   return false;
615f363ed98SJohannes Doerfert }
6162e02d560SMichael Kruse 
getUseBlock(const llvm::Use & U)61789da6bbcSMichael Kruse llvm::BasicBlock *polly::getUseBlock(const llvm::Use &U) {
6182e02d560SMichael Kruse   Instruction *UI = dyn_cast<Instruction>(U.getUser());
6192e02d560SMichael Kruse   if (!UI)
6202e02d560SMichael Kruse     return nullptr;
6212e02d560SMichael Kruse 
6222e02d560SMichael Kruse   if (PHINode *PHI = dyn_cast<PHINode>(UI))
6232e02d560SMichael Kruse     return PHI->getIncomingBlock(U);
6242e02d560SMichael Kruse 
6252e02d560SMichael Kruse   return UI->getParent();
6262e02d560SMichael Kruse }
6276ff419c2SMichael Kruse 
getFirstNonBoxedLoopFor(llvm::Loop * L,llvm::LoopInfo & LI,const BoxedLoopsSetTy & BoxedLoops)628476f855eSMichael Kruse llvm::Loop *polly::getFirstNonBoxedLoopFor(llvm::Loop *L, llvm::LoopInfo &LI,
629476f855eSMichael Kruse                                            const BoxedLoopsSetTy &BoxedLoops) {
630476f855eSMichael Kruse   while (BoxedLoops.count(L))
631476f855eSMichael Kruse     L = L->getParentLoop();
632476f855eSMichael Kruse   return L;
633476f855eSMichael Kruse }
634476f855eSMichael Kruse 
getFirstNonBoxedLoopFor(llvm::BasicBlock * BB,llvm::LoopInfo & LI,const BoxedLoopsSetTy & BoxedLoops)635476f855eSMichael Kruse llvm::Loop *polly::getFirstNonBoxedLoopFor(llvm::BasicBlock *BB,
636476f855eSMichael Kruse                                            llvm::LoopInfo &LI,
637476f855eSMichael Kruse                                            const BoxedLoopsSetTy &BoxedLoops) {
638476f855eSMichael Kruse   Loop *L = LI.getLoopFor(BB);
639476f855eSMichael Kruse   return getFirstNonBoxedLoopFor(L, LI, BoxedLoops);
640476f855eSMichael Kruse }
6415369ea5dSMichael Kruse 
isDebugCall(Instruction * Inst)6425369ea5dSMichael Kruse bool polly::isDebugCall(Instruction *Inst) {
6435369ea5dSMichael Kruse   auto *CI = dyn_cast<CallInst>(Inst);
6445369ea5dSMichael Kruse   if (!CI)
6455369ea5dSMichael Kruse     return false;
6465369ea5dSMichael Kruse 
6475369ea5dSMichael Kruse   Function *CF = CI->getCalledFunction();
6485369ea5dSMichael Kruse   if (!CF)
6495369ea5dSMichael Kruse     return false;
6505369ea5dSMichael Kruse 
6515369ea5dSMichael Kruse   return std::find(DebugFunctions.begin(), DebugFunctions.end(),
6525369ea5dSMichael Kruse                    CF->getName()) != DebugFunctions.end();
6535369ea5dSMichael Kruse }
6545369ea5dSMichael Kruse 
hasDebugCall(BasicBlock * BB)6555369ea5dSMichael Kruse static bool hasDebugCall(BasicBlock *BB) {
6565369ea5dSMichael Kruse   for (Instruction &Inst : *BB) {
6575369ea5dSMichael Kruse     if (isDebugCall(&Inst))
6585369ea5dSMichael Kruse       return true;
6595369ea5dSMichael Kruse   }
6605369ea5dSMichael Kruse   return false;
6615369ea5dSMichael Kruse }
6625369ea5dSMichael Kruse 
hasDebugCall(ScopStmt * Stmt)6635369ea5dSMichael Kruse bool polly::hasDebugCall(ScopStmt *Stmt) {
6645369ea5dSMichael Kruse   // Quick skip if no debug functions have been defined.
6655369ea5dSMichael Kruse   if (DebugFunctions.empty())
6665369ea5dSMichael Kruse     return false;
6675369ea5dSMichael Kruse 
6685369ea5dSMichael Kruse   if (!Stmt)
6695369ea5dSMichael Kruse     return false;
6705369ea5dSMichael Kruse 
6715369ea5dSMichael Kruse   for (Instruction *Inst : Stmt->getInstructions())
6725369ea5dSMichael Kruse     if (isDebugCall(Inst))
6735369ea5dSMichael Kruse       return true;
6745369ea5dSMichael Kruse 
6755369ea5dSMichael Kruse   if (Stmt->isRegionStmt()) {
6765369ea5dSMichael Kruse     for (BasicBlock *RBB : Stmt->getRegion()->blocks())
6775369ea5dSMichael Kruse       if (RBB != Stmt->getEntryBlock() && ::hasDebugCall(RBB))
6785369ea5dSMichael Kruse         return true;
6795369ea5dSMichael Kruse   }
6805369ea5dSMichael Kruse 
6815369ea5dSMichael Kruse   return false;
6825369ea5dSMichael Kruse }
6833f170eb1SMichael Kruse 
6843f170eb1SMichael Kruse /// Find a property in a LoopID.
findNamedMetadataNode(MDNode * LoopMD,StringRef Name)6853f170eb1SMichael Kruse static MDNode *findNamedMetadataNode(MDNode *LoopMD, StringRef Name) {
6863f170eb1SMichael Kruse   if (!LoopMD)
6873f170eb1SMichael Kruse     return nullptr;
6883f170eb1SMichael Kruse   for (const MDOperand &X : drop_begin(LoopMD->operands(), 1)) {
6893f170eb1SMichael Kruse     auto *OpNode = dyn_cast<MDNode>(X.get());
6903f170eb1SMichael Kruse     if (!OpNode)
6913f170eb1SMichael Kruse       continue;
6923f170eb1SMichael Kruse 
6933f170eb1SMichael Kruse     auto *OpName = dyn_cast<MDString>(OpNode->getOperand(0));
6943f170eb1SMichael Kruse     if (!OpName)
6953f170eb1SMichael Kruse       continue;
6963f170eb1SMichael Kruse     if (OpName->getString() == Name)
6973f170eb1SMichael Kruse       return OpNode;
6983f170eb1SMichael Kruse   }
6993f170eb1SMichael Kruse   return nullptr;
7003f170eb1SMichael Kruse }
7013f170eb1SMichael Kruse 
findNamedMetadataArg(MDNode * LoopID,StringRef Name)70228667787SMichael Kruse static Optional<const MDOperand *> findNamedMetadataArg(MDNode *LoopID,
70328667787SMichael Kruse                                                         StringRef Name) {
70428667787SMichael Kruse   MDNode *MD = findNamedMetadataNode(LoopID, Name);
70528667787SMichael Kruse   if (!MD)
70628667787SMichael Kruse     return None;
70728667787SMichael Kruse   switch (MD->getNumOperands()) {
70828667787SMichael Kruse   case 1:
70928667787SMichael Kruse     return nullptr;
71028667787SMichael Kruse   case 2:
71128667787SMichael Kruse     return &MD->getOperand(1);
71228667787SMichael Kruse   default:
71328667787SMichael Kruse     llvm_unreachable("loop metadata has 0 or 1 operand");
71428667787SMichael Kruse   }
71528667787SMichael Kruse }
71628667787SMichael Kruse 
findMetadataOperand(MDNode * LoopMD,StringRef Name)7173f170eb1SMichael Kruse Optional<Metadata *> polly::findMetadataOperand(MDNode *LoopMD,
7183f170eb1SMichael Kruse                                                 StringRef Name) {
7193f170eb1SMichael Kruse   MDNode *MD = findNamedMetadataNode(LoopMD, Name);
7203f170eb1SMichael Kruse   if (!MD)
7213f170eb1SMichael Kruse     return None;
7223f170eb1SMichael Kruse   switch (MD->getNumOperands()) {
7233f170eb1SMichael Kruse   case 1:
7243f170eb1SMichael Kruse     return nullptr;
7253f170eb1SMichael Kruse   case 2:
7263f170eb1SMichael Kruse     return MD->getOperand(1).get();
7273f170eb1SMichael Kruse   default:
7283f170eb1SMichael Kruse     llvm_unreachable("loop metadata must have 0 or 1 operands");
7293f170eb1SMichael Kruse   }
7303f170eb1SMichael Kruse }
7313f170eb1SMichael Kruse 
getOptionalBoolLoopAttribute(MDNode * LoopID,StringRef Name)73228667787SMichael Kruse static Optional<bool> getOptionalBoolLoopAttribute(MDNode *LoopID,
73328667787SMichael Kruse                                                    StringRef Name) {
73428667787SMichael Kruse   MDNode *MD = findNamedMetadataNode(LoopID, Name);
73528667787SMichael Kruse   if (!MD)
73628667787SMichael Kruse     return None;
73728667787SMichael Kruse   switch (MD->getNumOperands()) {
73828667787SMichael Kruse   case 1:
73928667787SMichael Kruse     return true;
74028667787SMichael Kruse   case 2:
74128667787SMichael Kruse     if (ConstantInt *IntMD =
74228667787SMichael Kruse             mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
74328667787SMichael Kruse       return IntMD->getZExtValue();
74428667787SMichael Kruse     return true;
74528667787SMichael Kruse   }
74628667787SMichael Kruse   llvm_unreachable("unexpected number of options");
74728667787SMichael Kruse }
74828667787SMichael Kruse 
getBooleanLoopAttribute(MDNode * LoopID,StringRef Name)74928667787SMichael Kruse bool polly::getBooleanLoopAttribute(MDNode *LoopID, StringRef Name) {
750*30c67587SKazu Hirata   return getOptionalBoolLoopAttribute(LoopID, Name).value_or(false);
75128667787SMichael Kruse }
75228667787SMichael Kruse 
getOptionalIntLoopAttribute(MDNode * LoopID,StringRef Name)75328667787SMichael Kruse llvm::Optional<int> polly::getOptionalIntLoopAttribute(MDNode *LoopID,
75428667787SMichael Kruse                                                        StringRef Name) {
75528667787SMichael Kruse   const MDOperand *AttrMD =
756*30c67587SKazu Hirata       findNamedMetadataArg(LoopID, Name).value_or(nullptr);
75728667787SMichael Kruse   if (!AttrMD)
75828667787SMichael Kruse     return None;
75928667787SMichael Kruse 
76028667787SMichael Kruse   ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
76128667787SMichael Kruse   if (!IntMD)
76228667787SMichael Kruse     return None;
76328667787SMichael Kruse 
76428667787SMichael Kruse   return IntMD->getSExtValue();
76528667787SMichael Kruse }
76628667787SMichael Kruse 
hasDisableAllTransformsHint(Loop * L)7673f170eb1SMichael Kruse bool polly::hasDisableAllTransformsHint(Loop *L) {
7683f170eb1SMichael Kruse   return llvm::hasDisableAllTransformsHint(L);
7693f170eb1SMichael Kruse }
7703f170eb1SMichael Kruse 
hasDisableAllTransformsHint(llvm::MDNode * LoopID)77128667787SMichael Kruse bool polly::hasDisableAllTransformsHint(llvm::MDNode *LoopID) {
77228667787SMichael Kruse   return getBooleanLoopAttribute(LoopID, "llvm.loop.disable_nonforced");
77328667787SMichael Kruse }
77428667787SMichael Kruse 
getIslLoopAttr(isl::ctx Ctx,BandAttr * Attr)7753f170eb1SMichael Kruse isl::id polly::getIslLoopAttr(isl::ctx Ctx, BandAttr *Attr) {
7763f170eb1SMichael Kruse   assert(Attr && "Must be a valid BandAttr");
7773f170eb1SMichael Kruse 
7783f170eb1SMichael Kruse   // The name "Loop" signals that this id contains a pointer to a BandAttr.
7793f170eb1SMichael Kruse   // The ScheduleOptimizer also uses the string "Inter iteration alias-free" in
7803f170eb1SMichael Kruse   // markers, but it's user pointer is an llvm::Value.
7813f170eb1SMichael Kruse   isl::id Result = isl::id::alloc(Ctx, "Loop with Metadata", Attr);
7823f170eb1SMichael Kruse   Result = isl::manage(isl_id_set_free_user(Result.release(), [](void *Ptr) {
7833f170eb1SMichael Kruse     BandAttr *Attr = reinterpret_cast<BandAttr *>(Ptr);
7843f170eb1SMichael Kruse     delete Attr;
7853f170eb1SMichael Kruse   }));
7863f170eb1SMichael Kruse   return Result;
7873f170eb1SMichael Kruse }
7883f170eb1SMichael Kruse 
createIslLoopAttr(isl::ctx Ctx,Loop * L)7893f170eb1SMichael Kruse isl::id polly::createIslLoopAttr(isl::ctx Ctx, Loop *L) {
7903f170eb1SMichael Kruse   if (!L)
7913f170eb1SMichael Kruse     return {};
7923f170eb1SMichael Kruse 
7933f170eb1SMichael Kruse   // A loop without metadata does not need to be annotated.
7943f170eb1SMichael Kruse   MDNode *LoopID = L->getLoopID();
7953f170eb1SMichael Kruse   if (!LoopID)
7963f170eb1SMichael Kruse     return {};
7973f170eb1SMichael Kruse 
7983f170eb1SMichael Kruse   BandAttr *Attr = new BandAttr();
7993f170eb1SMichael Kruse   Attr->OriginalLoop = L;
8003f170eb1SMichael Kruse   Attr->Metadata = L->getLoopID();
8013f170eb1SMichael Kruse 
8023f170eb1SMichael Kruse   return getIslLoopAttr(Ctx, Attr);
8033f170eb1SMichael Kruse }
8043f170eb1SMichael Kruse 
isLoopAttr(const isl::id & Id)8053f170eb1SMichael Kruse bool polly::isLoopAttr(const isl::id &Id) {
8063f170eb1SMichael Kruse   if (Id.is_null())
8073f170eb1SMichael Kruse     return false;
8083f170eb1SMichael Kruse 
8093f170eb1SMichael Kruse   return Id.get_name() == "Loop with Metadata";
8103f170eb1SMichael Kruse }
8113f170eb1SMichael Kruse 
getLoopAttr(const isl::id & Id)8123f170eb1SMichael Kruse BandAttr *polly::getLoopAttr(const isl::id &Id) {
8133f170eb1SMichael Kruse   if (!isLoopAttr(Id))
8143f170eb1SMichael Kruse     return nullptr;
8153f170eb1SMichael Kruse 
8163f170eb1SMichael Kruse   return reinterpret_cast<BandAttr *>(Id.get_user());
8173f170eb1SMichael Kruse }
818