1 //===- LoopVersioning.cpp - Utility to version a loop ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines a utility class to perform loop versioning. The versioned 10 // loop speculates that otherwise may-aliasing memory accesses don't overlap and 11 // emits checks to prove this. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Utils/LoopVersioning.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/Analysis/LoopAccessAnalysis.h" 18 #include "llvm/Analysis/LoopInfo.h" 19 #include "llvm/Analysis/ScalarEvolution.h" 20 #include "llvm/IR/Dominators.h" 21 #include "llvm/IR/MDBuilder.h" 22 #include "llvm/IR/PassManager.h" 23 #include "llvm/InitializePasses.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Transforms/Scalar/LoopPassManager.h" 26 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 27 #include "llvm/Transforms/Utils/Cloning.h" 28 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 29 30 using namespace llvm; 31 32 static cl::opt<bool> 33 AnnotateNoAlias("loop-version-annotate-no-alias", cl::init(true), 34 cl::Hidden, 35 cl::desc("Add no-alias annotation for instructions that " 36 "are disambiguated by memchecks")); 37 38 LoopVersioning::LoopVersioning(const LoopAccessInfo &LAI, Loop *L, LoopInfo *LI, 39 DominatorTree *DT, ScalarEvolution *SE, 40 bool UseLAIChecks) 41 : VersionedLoop(L), NonVersionedLoop(nullptr), LAI(LAI), LI(LI), DT(DT), 42 SE(SE) { 43 assert(L->getExitBlock() && "No single exit block"); 44 assert(L->isLoopSimplifyForm() && "Loop is not in loop-simplify form"); 45 if (UseLAIChecks) { 46 setAliasChecks(LAI.getRuntimePointerChecking()->getChecks()); 47 setSCEVChecks(LAI.getPSE().getUnionPredicate()); 48 } 49 } 50 51 void LoopVersioning::setAliasChecks(ArrayRef<RuntimePointerCheck> Checks) { 52 AliasChecks = {Checks.begin(), Checks.end()}; 53 } 54 55 void LoopVersioning::setSCEVChecks(SCEVUnionPredicate Check) { 56 Preds = std::move(Check); 57 } 58 59 void LoopVersioning::versionLoop( 60 const SmallVectorImpl<Instruction *> &DefsUsedOutside) { 61 Instruction *FirstCheckInst; 62 Instruction *MemRuntimeCheck; 63 Value *SCEVRuntimeCheck; 64 Value *RuntimeCheck = nullptr; 65 66 // Add the memcheck in the original preheader (this is empty initially). 67 BasicBlock *RuntimeCheckBB = VersionedLoop->getLoopPreheader(); 68 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking(); 69 std::tie(FirstCheckInst, MemRuntimeCheck) = 70 addRuntimeChecks(RuntimeCheckBB->getTerminator(), VersionedLoop, 71 AliasChecks, RtPtrChecking.getSE()); 72 73 const SCEVUnionPredicate &Pred = LAI.getPSE().getUnionPredicate(); 74 SCEVExpander Exp(*SE, RuntimeCheckBB->getModule()->getDataLayout(), 75 "scev.check"); 76 SCEVRuntimeCheck = 77 Exp.expandCodeForPredicate(&Pred, RuntimeCheckBB->getTerminator()); 78 auto *CI = dyn_cast<ConstantInt>(SCEVRuntimeCheck); 79 80 // Discard the SCEV runtime check if it is always true. 81 if (CI && CI->isZero()) 82 SCEVRuntimeCheck = nullptr; 83 84 if (MemRuntimeCheck && SCEVRuntimeCheck) { 85 RuntimeCheck = BinaryOperator::Create(Instruction::Or, MemRuntimeCheck, 86 SCEVRuntimeCheck, "lver.safe"); 87 if (auto *I = dyn_cast<Instruction>(RuntimeCheck)) 88 I->insertBefore(RuntimeCheckBB->getTerminator()); 89 } else 90 RuntimeCheck = MemRuntimeCheck ? MemRuntimeCheck : SCEVRuntimeCheck; 91 92 assert(RuntimeCheck && "called even though we don't need " 93 "any runtime checks"); 94 95 // Rename the block to make the IR more readable. 96 RuntimeCheckBB->setName(VersionedLoop->getHeader()->getName() + 97 ".lver.check"); 98 99 // Create empty preheader for the loop (and after cloning for the 100 // non-versioned loop). 101 BasicBlock *PH = 102 SplitBlock(RuntimeCheckBB, RuntimeCheckBB->getTerminator(), DT, LI, 103 nullptr, VersionedLoop->getHeader()->getName() + ".ph"); 104 105 // Clone the loop including the preheader. 106 // 107 // FIXME: This does not currently preserve SimplifyLoop because the exit 108 // block is a join between the two loops. 109 SmallVector<BasicBlock *, 8> NonVersionedLoopBlocks; 110 NonVersionedLoop = 111 cloneLoopWithPreheader(PH, RuntimeCheckBB, VersionedLoop, VMap, 112 ".lver.orig", LI, DT, NonVersionedLoopBlocks); 113 remapInstructionsInBlocks(NonVersionedLoopBlocks, VMap); 114 115 // Insert the conditional branch based on the result of the memchecks. 116 Instruction *OrigTerm = RuntimeCheckBB->getTerminator(); 117 BranchInst::Create(NonVersionedLoop->getLoopPreheader(), 118 VersionedLoop->getLoopPreheader(), RuntimeCheck, OrigTerm); 119 OrigTerm->eraseFromParent(); 120 121 // The loops merge in the original exit block. This is now dominated by the 122 // memchecking block. 123 DT->changeImmediateDominator(VersionedLoop->getExitBlock(), RuntimeCheckBB); 124 125 // Adds the necessary PHI nodes for the versioned loops based on the 126 // loop-defined values used outside of the loop. 127 addPHINodes(DefsUsedOutside); 128 } 129 130 void LoopVersioning::addPHINodes( 131 const SmallVectorImpl<Instruction *> &DefsUsedOutside) { 132 BasicBlock *PHIBlock = VersionedLoop->getExitBlock(); 133 assert(PHIBlock && "No single successor to loop exit block"); 134 PHINode *PN; 135 136 // First add a single-operand PHI for each DefsUsedOutside if one does not 137 // exists yet. 138 for (auto *Inst : DefsUsedOutside) { 139 // See if we have a single-operand PHI with the value defined by the 140 // original loop. 141 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) { 142 if (PN->getIncomingValue(0) == Inst) 143 break; 144 } 145 // If not create it. 146 if (!PN) { 147 PN = PHINode::Create(Inst->getType(), 2, Inst->getName() + ".lver", 148 &PHIBlock->front()); 149 SmallVector<User*, 8> UsersToUpdate; 150 for (User *U : Inst->users()) 151 if (!VersionedLoop->contains(cast<Instruction>(U)->getParent())) 152 UsersToUpdate.push_back(U); 153 for (User *U : UsersToUpdate) 154 U->replaceUsesOfWith(Inst, PN); 155 PN->addIncoming(Inst, VersionedLoop->getExitingBlock()); 156 } 157 } 158 159 // Then for each PHI add the operand for the edge from the cloned loop. 160 for (auto I = PHIBlock->begin(); (PN = dyn_cast<PHINode>(I)); ++I) { 161 assert(PN->getNumOperands() == 1 && 162 "Exit block should only have on predecessor"); 163 164 // If the definition was cloned used that otherwise use the same value. 165 Value *ClonedValue = PN->getIncomingValue(0); 166 auto Mapped = VMap.find(ClonedValue); 167 if (Mapped != VMap.end()) 168 ClonedValue = Mapped->second; 169 170 PN->addIncoming(ClonedValue, NonVersionedLoop->getExitingBlock()); 171 } 172 } 173 174 void LoopVersioning::prepareNoAliasMetadata() { 175 // We need to turn the no-alias relation between pointer checking groups into 176 // no-aliasing annotations between instructions. 177 // 178 // We accomplish this by mapping each pointer checking group (a set of 179 // pointers memchecked together) to an alias scope and then also mapping each 180 // group to the list of scopes it can't alias. 181 182 const RuntimePointerChecking *RtPtrChecking = LAI.getRuntimePointerChecking(); 183 LLVMContext &Context = VersionedLoop->getHeader()->getContext(); 184 185 // First allocate an aliasing scope for each pointer checking group. 186 // 187 // While traversing through the checking groups in the loop, also create a 188 // reverse map from pointers to the pointer checking group they were assigned 189 // to. 190 MDBuilder MDB(Context); 191 MDNode *Domain = MDB.createAnonymousAliasScopeDomain("LVerDomain"); 192 193 for (const auto &Group : RtPtrChecking->CheckingGroups) { 194 GroupToScope[&Group] = MDB.createAnonymousAliasScope(Domain); 195 196 for (unsigned PtrIdx : Group.Members) 197 PtrToGroup[RtPtrChecking->getPointerInfo(PtrIdx).PointerValue] = &Group; 198 } 199 200 // Go through the checks and for each pointer group, collect the scopes for 201 // each non-aliasing pointer group. 202 DenseMap<const RuntimeCheckingPtrGroup *, SmallVector<Metadata *, 4>> 203 GroupToNonAliasingScopes; 204 205 for (const auto &Check : AliasChecks) 206 GroupToNonAliasingScopes[Check.first].push_back(GroupToScope[Check.second]); 207 208 // Finally, transform the above to actually map to scope list which is what 209 // the metadata uses. 210 211 for (auto Pair : GroupToNonAliasingScopes) 212 GroupToNonAliasingScopeList[Pair.first] = MDNode::get(Context, Pair.second); 213 } 214 215 void LoopVersioning::annotateLoopWithNoAlias() { 216 if (!AnnotateNoAlias) 217 return; 218 219 // First prepare the maps. 220 prepareNoAliasMetadata(); 221 222 // Add the scope and no-alias metadata to the instructions. 223 for (Instruction *I : LAI.getDepChecker().getMemoryInstructions()) { 224 annotateInstWithNoAlias(I); 225 } 226 } 227 228 void LoopVersioning::annotateInstWithNoAlias(Instruction *VersionedInst, 229 const Instruction *OrigInst) { 230 if (!AnnotateNoAlias) 231 return; 232 233 LLVMContext &Context = VersionedLoop->getHeader()->getContext(); 234 const Value *Ptr = isa<LoadInst>(OrigInst) 235 ? cast<LoadInst>(OrigInst)->getPointerOperand() 236 : cast<StoreInst>(OrigInst)->getPointerOperand(); 237 238 // Find the group for the pointer and then add the scope metadata. 239 auto Group = PtrToGroup.find(Ptr); 240 if (Group != PtrToGroup.end()) { 241 VersionedInst->setMetadata( 242 LLVMContext::MD_alias_scope, 243 MDNode::concatenate( 244 VersionedInst->getMetadata(LLVMContext::MD_alias_scope), 245 MDNode::get(Context, GroupToScope[Group->second]))); 246 247 // Add the no-alias metadata. 248 auto NonAliasingScopeList = GroupToNonAliasingScopeList.find(Group->second); 249 if (NonAliasingScopeList != GroupToNonAliasingScopeList.end()) 250 VersionedInst->setMetadata( 251 LLVMContext::MD_noalias, 252 MDNode::concatenate( 253 VersionedInst->getMetadata(LLVMContext::MD_noalias), 254 NonAliasingScopeList->second)); 255 } 256 } 257 258 namespace { 259 bool runImpl(LoopInfo *LI, function_ref<const LoopAccessInfo &(Loop &)> GetLAA, 260 DominatorTree *DT, ScalarEvolution *SE) { 261 // Build up a worklist of inner-loops to version. This is necessary as the 262 // act of versioning a loop creates new loops and can invalidate iterators 263 // across the loops. 264 SmallVector<Loop *, 8> Worklist; 265 266 for (Loop *TopLevelLoop : *LI) 267 for (Loop *L : depth_first(TopLevelLoop)) 268 // We only handle inner-most loops. 269 if (L->empty()) 270 Worklist.push_back(L); 271 272 // Now walk the identified inner loops. 273 bool Changed = false; 274 for (Loop *L : Worklist) { 275 const LoopAccessInfo &LAI = GetLAA(*L); 276 if (L->isLoopSimplifyForm() && !LAI.hasConvergentOp() && 277 (LAI.getNumRuntimePointerChecks() || 278 !LAI.getPSE().getUnionPredicate().isAlwaysTrue())) { 279 LoopVersioning LVer(LAI, L, LI, DT, SE); 280 LVer.versionLoop(); 281 LVer.annotateLoopWithNoAlias(); 282 Changed = true; 283 } 284 } 285 286 return Changed; 287 } 288 289 /// Also expose this is a pass. Currently this is only used for 290 /// unit-testing. It adds all memchecks necessary to remove all may-aliasing 291 /// array accesses from the loop. 292 class LoopVersioningLegacyPass : public FunctionPass { 293 public: 294 LoopVersioningLegacyPass() : FunctionPass(ID) { 295 initializeLoopVersioningLegacyPassPass(*PassRegistry::getPassRegistry()); 296 } 297 298 bool runOnFunction(Function &F) override { 299 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 300 auto GetLAA = [&](Loop &L) -> const LoopAccessInfo & { 301 return getAnalysis<LoopAccessLegacyAnalysis>().getInfo(&L); 302 }; 303 304 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 305 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 306 307 return runImpl(LI, GetLAA, DT, SE); 308 } 309 310 void getAnalysisUsage(AnalysisUsage &AU) const override { 311 AU.addRequired<LoopInfoWrapperPass>(); 312 AU.addPreserved<LoopInfoWrapperPass>(); 313 AU.addRequired<LoopAccessLegacyAnalysis>(); 314 AU.addRequired<DominatorTreeWrapperPass>(); 315 AU.addPreserved<DominatorTreeWrapperPass>(); 316 AU.addRequired<ScalarEvolutionWrapperPass>(); 317 } 318 319 static char ID; 320 }; 321 } 322 323 #define LVER_OPTION "loop-versioning" 324 #define DEBUG_TYPE LVER_OPTION 325 326 char LoopVersioningLegacyPass::ID; 327 static const char LVer_name[] = "Loop Versioning"; 328 329 INITIALIZE_PASS_BEGIN(LoopVersioningLegacyPass, LVER_OPTION, LVer_name, false, 330 false) 331 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 332 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis) 333 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 334 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 335 INITIALIZE_PASS_END(LoopVersioningLegacyPass, LVER_OPTION, LVer_name, false, 336 false) 337 338 namespace llvm { 339 FunctionPass *createLoopVersioningLegacyPass() { 340 return new LoopVersioningLegacyPass(); 341 } 342 343 PreservedAnalyses LoopVersioningPass::run(Function &F, 344 FunctionAnalysisManager &AM) { 345 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 346 auto &LI = AM.getResult<LoopAnalysis>(F); 347 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 348 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 349 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 350 auto &AA = AM.getResult<AAManager>(F); 351 auto &AC = AM.getResult<AssumptionAnalysis>(F); 352 MemorySSA *MSSA = EnableMSSALoopDependency 353 ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() 354 : nullptr; 355 356 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager(); 357 auto GetLAA = [&](Loop &L) -> const LoopAccessInfo & { 358 LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, MSSA}; 359 return LAM.getResult<LoopAccessAnalysis>(L, AR); 360 }; 361 362 if (runImpl(&LI, GetLAA, &DT, &SE)) 363 return PreservedAnalyses::none(); 364 return PreservedAnalyses::all(); 365 } 366 } // namespace llvm 367