LoopUtils.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877
  1. //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
  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 common loop utility functions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Utils/LoopUtils.h"
  13. #include "llvm/ADT/DenseSet.h"
  14. #include "llvm/ADT/PriorityWorklist.h"
  15. #include "llvm/ADT/ScopeExit.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/BasicAliasAnalysis.h"
  21. #include "llvm/Analysis/DomTreeUpdater.h"
  22. #include "llvm/Analysis/GlobalsModRef.h"
  23. #include "llvm/Analysis/InstSimplifyFolder.h"
  24. #include "llvm/Analysis/LoopAccessAnalysis.h"
  25. #include "llvm/Analysis/LoopInfo.h"
  26. #include "llvm/Analysis/LoopPass.h"
  27. #include "llvm/Analysis/MemorySSA.h"
  28. #include "llvm/Analysis/MemorySSAUpdater.h"
  29. #include "llvm/Analysis/ScalarEvolution.h"
  30. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  31. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  32. #include "llvm/IR/DIBuilder.h"
  33. #include "llvm/IR/Dominators.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/MDBuilder.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/IR/PatternMatch.h"
  39. #include "llvm/IR/ProfDataUtils.h"
  40. #include "llvm/IR/ValueHandle.h"
  41. #include "llvm/InitializePasses.h"
  42. #include "llvm/Pass.h"
  43. #include "llvm/Support/Debug.h"
  44. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  45. #include "llvm/Transforms/Utils/Local.h"
  46. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  47. using namespace llvm;
  48. using namespace llvm::PatternMatch;
  49. #define DEBUG_TYPE "loop-utils"
  50. static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
  51. static const char *LLVMLoopDisableLICM = "llvm.licm.disable";
  52. bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
  53. MemorySSAUpdater *MSSAU,
  54. bool PreserveLCSSA) {
  55. bool Changed = false;
  56. // We re-use a vector for the in-loop predecesosrs.
  57. SmallVector<BasicBlock *, 4> InLoopPredecessors;
  58. auto RewriteExit = [&](BasicBlock *BB) {
  59. assert(InLoopPredecessors.empty() &&
  60. "Must start with an empty predecessors list!");
  61. auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
  62. // See if there are any non-loop predecessors of this exit block and
  63. // keep track of the in-loop predecessors.
  64. bool IsDedicatedExit = true;
  65. for (auto *PredBB : predecessors(BB))
  66. if (L->contains(PredBB)) {
  67. if (isa<IndirectBrInst>(PredBB->getTerminator()))
  68. // We cannot rewrite exiting edges from an indirectbr.
  69. return false;
  70. InLoopPredecessors.push_back(PredBB);
  71. } else {
  72. IsDedicatedExit = false;
  73. }
  74. assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
  75. // Nothing to do if this is already a dedicated exit.
  76. if (IsDedicatedExit)
  77. return false;
  78. auto *NewExitBB = SplitBlockPredecessors(
  79. BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
  80. if (!NewExitBB)
  81. LLVM_DEBUG(
  82. dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
  83. << *L << "\n");
  84. else
  85. LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
  86. << NewExitBB->getName() << "\n");
  87. return true;
  88. };
  89. // Walk the exit blocks directly rather than building up a data structure for
  90. // them, but only visit each one once.
  91. SmallPtrSet<BasicBlock *, 4> Visited;
  92. for (auto *BB : L->blocks())
  93. for (auto *SuccBB : successors(BB)) {
  94. // We're looking for exit blocks so skip in-loop successors.
  95. if (L->contains(SuccBB))
  96. continue;
  97. // Visit each exit block exactly once.
  98. if (!Visited.insert(SuccBB).second)
  99. continue;
  100. Changed |= RewriteExit(SuccBB);
  101. }
  102. return Changed;
  103. }
  104. /// Returns the instructions that use values defined in the loop.
  105. SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
  106. SmallVector<Instruction *, 8> UsedOutside;
  107. for (auto *Block : L->getBlocks())
  108. // FIXME: I believe that this could use copy_if if the Inst reference could
  109. // be adapted into a pointer.
  110. for (auto &Inst : *Block) {
  111. auto Users = Inst.users();
  112. if (any_of(Users, [&](User *U) {
  113. auto *Use = cast<Instruction>(U);
  114. return !L->contains(Use->getParent());
  115. }))
  116. UsedOutside.push_back(&Inst);
  117. }
  118. return UsedOutside;
  119. }
  120. void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
  121. // By definition, all loop passes need the LoopInfo analysis and the
  122. // Dominator tree it depends on. Because they all participate in the loop
  123. // pass manager, they must also preserve these.
  124. AU.addRequired<DominatorTreeWrapperPass>();
  125. AU.addPreserved<DominatorTreeWrapperPass>();
  126. AU.addRequired<LoopInfoWrapperPass>();
  127. AU.addPreserved<LoopInfoWrapperPass>();
  128. // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
  129. // here because users shouldn't directly get them from this header.
  130. extern char &LoopSimplifyID;
  131. extern char &LCSSAID;
  132. AU.addRequiredID(LoopSimplifyID);
  133. AU.addPreservedID(LoopSimplifyID);
  134. AU.addRequiredID(LCSSAID);
  135. AU.addPreservedID(LCSSAID);
  136. // This is used in the LPPassManager to perform LCSSA verification on passes
  137. // which preserve lcssa form
  138. AU.addRequired<LCSSAVerificationPass>();
  139. AU.addPreserved<LCSSAVerificationPass>();
  140. // Loop passes are designed to run inside of a loop pass manager which means
  141. // that any function analyses they require must be required by the first loop
  142. // pass in the manager (so that it is computed before the loop pass manager
  143. // runs) and preserved by all loop pasess in the manager. To make this
  144. // reasonably robust, the set needed for most loop passes is maintained here.
  145. // If your loop pass requires an analysis not listed here, you will need to
  146. // carefully audit the loop pass manager nesting structure that results.
  147. AU.addRequired<AAResultsWrapperPass>();
  148. AU.addPreserved<AAResultsWrapperPass>();
  149. AU.addPreserved<BasicAAWrapperPass>();
  150. AU.addPreserved<GlobalsAAWrapperPass>();
  151. AU.addPreserved<SCEVAAWrapperPass>();
  152. AU.addRequired<ScalarEvolutionWrapperPass>();
  153. AU.addPreserved<ScalarEvolutionWrapperPass>();
  154. // FIXME: When all loop passes preserve MemorySSA, it can be required and
  155. // preserved here instead of the individual handling in each pass.
  156. }
  157. /// Manually defined generic "LoopPass" dependency initialization. This is used
  158. /// to initialize the exact set of passes from above in \c
  159. /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
  160. /// with:
  161. ///
  162. /// INITIALIZE_PASS_DEPENDENCY(LoopPass)
  163. ///
  164. /// As-if "LoopPass" were a pass.
  165. void llvm::initializeLoopPassPass(PassRegistry &Registry) {
  166. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  167. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  168. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  169. INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
  170. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  171. INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
  172. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  173. INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
  174. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  175. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  176. }
  177. /// Create MDNode for input string.
  178. static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
  179. LLVMContext &Context = TheLoop->getHeader()->getContext();
  180. Metadata *MDs[] = {
  181. MDString::get(Context, Name),
  182. ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
  183. return MDNode::get(Context, MDs);
  184. }
  185. /// Set input string into loop metadata by keeping other values intact.
  186. /// If the string is already in loop metadata update value if it is
  187. /// different.
  188. void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *StringMD,
  189. unsigned V) {
  190. SmallVector<Metadata *, 4> MDs(1);
  191. // If the loop already has metadata, retain it.
  192. MDNode *LoopID = TheLoop->getLoopID();
  193. if (LoopID) {
  194. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  195. MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
  196. // If it is of form key = value, try to parse it.
  197. if (Node->getNumOperands() == 2) {
  198. MDString *S = dyn_cast<MDString>(Node->getOperand(0));
  199. if (S && S->getString().equals(StringMD)) {
  200. ConstantInt *IntMD =
  201. mdconst::extract_or_null<ConstantInt>(Node->getOperand(1));
  202. if (IntMD && IntMD->getSExtValue() == V)
  203. // It is already in place. Do nothing.
  204. return;
  205. // We need to update the value, so just skip it here and it will
  206. // be added after copying other existed nodes.
  207. continue;
  208. }
  209. }
  210. MDs.push_back(Node);
  211. }
  212. }
  213. // Add new metadata.
  214. MDs.push_back(createStringMetadata(TheLoop, StringMD, V));
  215. // Replace current metadata node with new one.
  216. LLVMContext &Context = TheLoop->getHeader()->getContext();
  217. MDNode *NewLoopID = MDNode::get(Context, MDs);
  218. // Set operand 0 to refer to the loop id itself.
  219. NewLoopID->replaceOperandWith(0, NewLoopID);
  220. TheLoop->setLoopID(NewLoopID);
  221. }
  222. std::optional<ElementCount>
  223. llvm::getOptionalElementCountLoopAttribute(const Loop *TheLoop) {
  224. std::optional<int> Width =
  225. getOptionalIntLoopAttribute(TheLoop, "llvm.loop.vectorize.width");
  226. if (Width) {
  227. std::optional<int> IsScalable = getOptionalIntLoopAttribute(
  228. TheLoop, "llvm.loop.vectorize.scalable.enable");
  229. return ElementCount::get(*Width, IsScalable.value_or(false));
  230. }
  231. return std::nullopt;
  232. }
  233. std::optional<MDNode *> llvm::makeFollowupLoopID(
  234. MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
  235. const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
  236. if (!OrigLoopID) {
  237. if (AlwaysNew)
  238. return nullptr;
  239. return std::nullopt;
  240. }
  241. assert(OrigLoopID->getOperand(0) == OrigLoopID);
  242. bool InheritAllAttrs = !InheritOptionsExceptPrefix;
  243. bool InheritSomeAttrs =
  244. InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
  245. SmallVector<Metadata *, 8> MDs;
  246. MDs.push_back(nullptr);
  247. bool Changed = false;
  248. if (InheritAllAttrs || InheritSomeAttrs) {
  249. for (const MDOperand &Existing : drop_begin(OrigLoopID->operands())) {
  250. MDNode *Op = cast<MDNode>(Existing.get());
  251. auto InheritThisAttribute = [InheritSomeAttrs,
  252. InheritOptionsExceptPrefix](MDNode *Op) {
  253. if (!InheritSomeAttrs)
  254. return false;
  255. // Skip malformatted attribute metadata nodes.
  256. if (Op->getNumOperands() == 0)
  257. return true;
  258. Metadata *NameMD = Op->getOperand(0).get();
  259. if (!isa<MDString>(NameMD))
  260. return true;
  261. StringRef AttrName = cast<MDString>(NameMD)->getString();
  262. // Do not inherit excluded attributes.
  263. return !AttrName.startswith(InheritOptionsExceptPrefix);
  264. };
  265. if (InheritThisAttribute(Op))
  266. MDs.push_back(Op);
  267. else
  268. Changed = true;
  269. }
  270. } else {
  271. // Modified if we dropped at least one attribute.
  272. Changed = OrigLoopID->getNumOperands() > 1;
  273. }
  274. bool HasAnyFollowup = false;
  275. for (StringRef OptionName : FollowupOptions) {
  276. MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
  277. if (!FollowupNode)
  278. continue;
  279. HasAnyFollowup = true;
  280. for (const MDOperand &Option : drop_begin(FollowupNode->operands())) {
  281. MDs.push_back(Option.get());
  282. Changed = true;
  283. }
  284. }
  285. // Attributes of the followup loop not specified explicity, so signal to the
  286. // transformation pass to add suitable attributes.
  287. if (!AlwaysNew && !HasAnyFollowup)
  288. return std::nullopt;
  289. // If no attributes were added or remove, the previous loop Id can be reused.
  290. if (!AlwaysNew && !Changed)
  291. return OrigLoopID;
  292. // No attributes is equivalent to having no !llvm.loop metadata at all.
  293. if (MDs.size() == 1)
  294. return nullptr;
  295. // Build the new loop ID.
  296. MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
  297. FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
  298. return FollowupLoopID;
  299. }
  300. bool llvm::hasDisableAllTransformsHint(const Loop *L) {
  301. return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
  302. }
  303. bool llvm::hasDisableLICMTransformsHint(const Loop *L) {
  304. return getBooleanLoopAttribute(L, LLVMLoopDisableLICM);
  305. }
  306. TransformationMode llvm::hasUnrollTransformation(const Loop *L) {
  307. if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
  308. return TM_SuppressedByUser;
  309. std::optional<int> Count =
  310. getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
  311. if (Count)
  312. return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
  313. if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
  314. return TM_ForcedByUser;
  315. if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
  316. return TM_ForcedByUser;
  317. if (hasDisableAllTransformsHint(L))
  318. return TM_Disable;
  319. return TM_Unspecified;
  320. }
  321. TransformationMode llvm::hasUnrollAndJamTransformation(const Loop *L) {
  322. if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
  323. return TM_SuppressedByUser;
  324. std::optional<int> Count =
  325. getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
  326. if (Count)
  327. return *Count == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
  328. if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
  329. return TM_ForcedByUser;
  330. if (hasDisableAllTransformsHint(L))
  331. return TM_Disable;
  332. return TM_Unspecified;
  333. }
  334. TransformationMode llvm::hasVectorizeTransformation(const Loop *L) {
  335. std::optional<bool> Enable =
  336. getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
  337. if (Enable == false)
  338. return TM_SuppressedByUser;
  339. std::optional<ElementCount> VectorizeWidth =
  340. getOptionalElementCountLoopAttribute(L);
  341. std::optional<int> InterleaveCount =
  342. getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
  343. // 'Forcing' vector width and interleave count to one effectively disables
  344. // this tranformation.
  345. if (Enable == true && VectorizeWidth && VectorizeWidth->isScalar() &&
  346. InterleaveCount == 1)
  347. return TM_SuppressedByUser;
  348. if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
  349. return TM_Disable;
  350. if (Enable == true)
  351. return TM_ForcedByUser;
  352. if ((VectorizeWidth && VectorizeWidth->isScalar()) && InterleaveCount == 1)
  353. return TM_Disable;
  354. if ((VectorizeWidth && VectorizeWidth->isVector()) || InterleaveCount > 1)
  355. return TM_Enable;
  356. if (hasDisableAllTransformsHint(L))
  357. return TM_Disable;
  358. return TM_Unspecified;
  359. }
  360. TransformationMode llvm::hasDistributeTransformation(const Loop *L) {
  361. if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
  362. return TM_ForcedByUser;
  363. if (hasDisableAllTransformsHint(L))
  364. return TM_Disable;
  365. return TM_Unspecified;
  366. }
  367. TransformationMode llvm::hasLICMVersioningTransformation(const Loop *L) {
  368. if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
  369. return TM_SuppressedByUser;
  370. if (hasDisableAllTransformsHint(L))
  371. return TM_Disable;
  372. return TM_Unspecified;
  373. }
  374. /// Does a BFS from a given node to all of its children inside a given loop.
  375. /// The returned vector of nodes includes the starting point.
  376. SmallVector<DomTreeNode *, 16>
  377. llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
  378. SmallVector<DomTreeNode *, 16> Worklist;
  379. auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
  380. // Only include subregions in the top level loop.
  381. BasicBlock *BB = DTN->getBlock();
  382. if (CurLoop->contains(BB))
  383. Worklist.push_back(DTN);
  384. };
  385. AddRegionToWorklist(N);
  386. for (size_t I = 0; I < Worklist.size(); I++) {
  387. for (DomTreeNode *Child : Worklist[I]->children())
  388. AddRegionToWorklist(Child);
  389. }
  390. return Worklist;
  391. }
  392. void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE,
  393. LoopInfo *LI, MemorySSA *MSSA) {
  394. assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
  395. auto *Preheader = L->getLoopPreheader();
  396. assert(Preheader && "Preheader should exist!");
  397. std::unique_ptr<MemorySSAUpdater> MSSAU;
  398. if (MSSA)
  399. MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
  400. // Now that we know the removal is safe, remove the loop by changing the
  401. // branch from the preheader to go to the single exit block.
  402. //
  403. // Because we're deleting a large chunk of code at once, the sequence in which
  404. // we remove things is very important to avoid invalidation issues.
  405. // Tell ScalarEvolution that the loop is deleted. Do this before
  406. // deleting the loop so that ScalarEvolution can look at the loop
  407. // to determine what it needs to clean up.
  408. if (SE) {
  409. SE->forgetLoop(L);
  410. SE->forgetBlockAndLoopDispositions();
  411. }
  412. Instruction *OldTerm = Preheader->getTerminator();
  413. assert(!OldTerm->mayHaveSideEffects() &&
  414. "Preheader must end with a side-effect-free terminator");
  415. assert(OldTerm->getNumSuccessors() == 1 &&
  416. "Preheader must have a single successor");
  417. // Connect the preheader to the exit block. Keep the old edge to the header
  418. // around to perform the dominator tree update in two separate steps
  419. // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
  420. // preheader -> header.
  421. //
  422. //
  423. // 0. Preheader 1. Preheader 2. Preheader
  424. // | | | |
  425. // V | V |
  426. // Header <--\ | Header <--\ | Header <--\
  427. // | | | | | | | | | | |
  428. // | V | | | V | | | V |
  429. // | Body --/ | | Body --/ | | Body --/
  430. // V V V V V
  431. // Exit Exit Exit
  432. //
  433. // By doing this is two separate steps we can perform the dominator tree
  434. // update without using the batch update API.
  435. //
  436. // Even when the loop is never executed, we cannot remove the edge from the
  437. // source block to the exit block. Consider the case where the unexecuted loop
  438. // branches back to an outer loop. If we deleted the loop and removed the edge
  439. // coming to this inner loop, this will break the outer loop structure (by
  440. // deleting the backedge of the outer loop). If the outer loop is indeed a
  441. // non-loop, it will be deleted in a future iteration of loop deletion pass.
  442. IRBuilder<> Builder(OldTerm);
  443. auto *ExitBlock = L->getUniqueExitBlock();
  444. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  445. if (ExitBlock) {
  446. assert(ExitBlock && "Should have a unique exit block!");
  447. assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
  448. Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
  449. // Remove the old branch. The conditional branch becomes a new terminator.
  450. OldTerm->eraseFromParent();
  451. // Rewrite phis in the exit block to get their inputs from the Preheader
  452. // instead of the exiting block.
  453. for (PHINode &P : ExitBlock->phis()) {
  454. // Set the zero'th element of Phi to be from the preheader and remove all
  455. // other incoming values. Given the loop has dedicated exits, all other
  456. // incoming values must be from the exiting blocks.
  457. int PredIndex = 0;
  458. P.setIncomingBlock(PredIndex, Preheader);
  459. // Removes all incoming values from all other exiting blocks (including
  460. // duplicate values from an exiting block).
  461. // Nuke all entries except the zero'th entry which is the preheader entry.
  462. // NOTE! We need to remove Incoming Values in the reverse order as done
  463. // below, to keep the indices valid for deletion (removeIncomingValues
  464. // updates getNumIncomingValues and shifts all values down into the
  465. // operand being deleted).
  466. for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
  467. P.removeIncomingValue(e - i, false);
  468. assert((P.getNumIncomingValues() == 1 &&
  469. P.getIncomingBlock(PredIndex) == Preheader) &&
  470. "Should have exactly one value and that's from the preheader!");
  471. }
  472. if (DT) {
  473. DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}});
  474. if (MSSA) {
  475. MSSAU->applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}},
  476. *DT);
  477. if (VerifyMemorySSA)
  478. MSSA->verifyMemorySSA();
  479. }
  480. }
  481. // Disconnect the loop body by branching directly to its exit.
  482. Builder.SetInsertPoint(Preheader->getTerminator());
  483. Builder.CreateBr(ExitBlock);
  484. // Remove the old branch.
  485. Preheader->getTerminator()->eraseFromParent();
  486. } else {
  487. assert(L->hasNoExitBlocks() &&
  488. "Loop should have either zero or one exit blocks.");
  489. Builder.SetInsertPoint(OldTerm);
  490. Builder.CreateUnreachable();
  491. Preheader->getTerminator()->eraseFromParent();
  492. }
  493. if (DT) {
  494. DTU.applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}});
  495. if (MSSA) {
  496. MSSAU->applyUpdates({{DominatorTree::Delete, Preheader, L->getHeader()}},
  497. *DT);
  498. SmallSetVector<BasicBlock *, 8> DeadBlockSet(L->block_begin(),
  499. L->block_end());
  500. MSSAU->removeBlocks(DeadBlockSet);
  501. if (VerifyMemorySSA)
  502. MSSA->verifyMemorySSA();
  503. }
  504. }
  505. // Use a map to unique and a vector to guarantee deterministic ordering.
  506. llvm::SmallDenseSet<DebugVariable, 4> DeadDebugSet;
  507. llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
  508. if (ExitBlock) {
  509. // Given LCSSA form is satisfied, we should not have users of instructions
  510. // within the dead loop outside of the loop. However, LCSSA doesn't take
  511. // unreachable uses into account. We handle them here.
  512. // We could do it after drop all references (in this case all users in the
  513. // loop will be already eliminated and we have less work to do but according
  514. // to API doc of User::dropAllReferences only valid operation after dropping
  515. // references, is deletion. So let's substitute all usages of
  516. // instruction from the loop with poison value of corresponding type first.
  517. for (auto *Block : L->blocks())
  518. for (Instruction &I : *Block) {
  519. auto *Poison = PoisonValue::get(I.getType());
  520. for (Use &U : llvm::make_early_inc_range(I.uses())) {
  521. if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
  522. if (L->contains(Usr->getParent()))
  523. continue;
  524. // If we have a DT then we can check that uses outside a loop only in
  525. // unreachable block.
  526. if (DT)
  527. assert(!DT->isReachableFromEntry(U) &&
  528. "Unexpected user in reachable block");
  529. U.set(Poison);
  530. }
  531. auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
  532. if (!DVI)
  533. continue;
  534. if (!DeadDebugSet.insert(DebugVariable(DVI)).second)
  535. continue;
  536. DeadDebugInst.push_back(DVI);
  537. }
  538. // After the loop has been deleted all the values defined and modified
  539. // inside the loop are going to be unavailable.
  540. // Since debug values in the loop have been deleted, inserting an undef
  541. // dbg.value truncates the range of any dbg.value before the loop where the
  542. // loop used to be. This is particularly important for constant values.
  543. Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
  544. assert(InsertDbgValueBefore &&
  545. "There should be a non-PHI instruction in exit block, else these "
  546. "instructions will have no parent.");
  547. for (auto *DVI : DeadDebugInst) {
  548. DVI->setKillLocation();
  549. DVI->moveBefore(InsertDbgValueBefore);
  550. }
  551. }
  552. // Remove the block from the reference counting scheme, so that we can
  553. // delete it freely later.
  554. for (auto *Block : L->blocks())
  555. Block->dropAllReferences();
  556. if (MSSA && VerifyMemorySSA)
  557. MSSA->verifyMemorySSA();
  558. if (LI) {
  559. // Erase the instructions and the blocks without having to worry
  560. // about ordering because we already dropped the references.
  561. // NOTE: This iteration is safe because erasing the block does not remove
  562. // its entry from the loop's block list. We do that in the next section.
  563. for (BasicBlock *BB : L->blocks())
  564. BB->eraseFromParent();
  565. // Finally, the blocks from loopinfo. This has to happen late because
  566. // otherwise our loop iterators won't work.
  567. SmallPtrSet<BasicBlock *, 8> blocks;
  568. blocks.insert(L->block_begin(), L->block_end());
  569. for (BasicBlock *BB : blocks)
  570. LI->removeBlock(BB);
  571. // The last step is to update LoopInfo now that we've eliminated this loop.
  572. // Note: LoopInfo::erase remove the given loop and relink its subloops with
  573. // its parent. While removeLoop/removeChildLoop remove the given loop but
  574. // not relink its subloops, which is what we want.
  575. if (Loop *ParentLoop = L->getParentLoop()) {
  576. Loop::iterator I = find(*ParentLoop, L);
  577. assert(I != ParentLoop->end() && "Couldn't find loop");
  578. ParentLoop->removeChildLoop(I);
  579. } else {
  580. Loop::iterator I = find(*LI, L);
  581. assert(I != LI->end() && "Couldn't find loop");
  582. LI->removeLoop(I);
  583. }
  584. LI->destroy(L);
  585. }
  586. }
  587. void llvm::breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE,
  588. LoopInfo &LI, MemorySSA *MSSA) {
  589. auto *Latch = L->getLoopLatch();
  590. assert(Latch && "multiple latches not yet supported");
  591. auto *Header = L->getHeader();
  592. Loop *OutermostLoop = L->getOutermostLoop();
  593. SE.forgetLoop(L);
  594. SE.forgetBlockAndLoopDispositions();
  595. std::unique_ptr<MemorySSAUpdater> MSSAU;
  596. if (MSSA)
  597. MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
  598. // Update the CFG and domtree. We chose to special case a couple of
  599. // of common cases for code quality and test readability reasons.
  600. [&]() -> void {
  601. if (auto *BI = dyn_cast<BranchInst>(Latch->getTerminator())) {
  602. if (!BI->isConditional()) {
  603. DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
  604. (void)changeToUnreachable(BI, /*PreserveLCSSA*/ true, &DTU,
  605. MSSAU.get());
  606. return;
  607. }
  608. // Conditional latch/exit - note that latch can be shared by inner
  609. // and outer loop so the other target doesn't need to an exit
  610. if (L->isLoopExiting(Latch)) {
  611. // TODO: Generalize ConstantFoldTerminator so that it can be used
  612. // here without invalidating LCSSA or MemorySSA. (Tricky case for
  613. // LCSSA: header is an exit block of a preceeding sibling loop w/o
  614. // dedicated exits.)
  615. const unsigned ExitIdx = L->contains(BI->getSuccessor(0)) ? 1 : 0;
  616. BasicBlock *ExitBB = BI->getSuccessor(ExitIdx);
  617. DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
  618. Header->removePredecessor(Latch, true);
  619. IRBuilder<> Builder(BI);
  620. auto *NewBI = Builder.CreateBr(ExitBB);
  621. // Transfer the metadata to the new branch instruction (minus the
  622. // loop info since this is no longer a loop)
  623. NewBI->copyMetadata(*BI, {LLVMContext::MD_dbg,
  624. LLVMContext::MD_annotation});
  625. BI->eraseFromParent();
  626. DTU.applyUpdates({{DominatorTree::Delete, Latch, Header}});
  627. if (MSSA)
  628. MSSAU->applyUpdates({{DominatorTree::Delete, Latch, Header}}, DT);
  629. return;
  630. }
  631. }
  632. // General case. By splitting the backedge, and then explicitly making it
  633. // unreachable we gracefully handle corner cases such as switch and invoke
  634. // termiantors.
  635. auto *BackedgeBB = SplitEdge(Latch, Header, &DT, &LI, MSSAU.get());
  636. DomTreeUpdater DTU(&DT, DomTreeUpdater::UpdateStrategy::Eager);
  637. (void)changeToUnreachable(BackedgeBB->getTerminator(),
  638. /*PreserveLCSSA*/ true, &DTU, MSSAU.get());
  639. }();
  640. // Erase (and destroy) this loop instance. Handles relinking sub-loops
  641. // and blocks within the loop as needed.
  642. LI.erase(L);
  643. // If the loop we broke had a parent, then changeToUnreachable might have
  644. // caused a block to be removed from the parent loop (see loop_nest_lcssa
  645. // test case in zero-btc.ll for an example), thus changing the parent's
  646. // exit blocks. If that happened, we need to rebuild LCSSA on the outermost
  647. // loop which might have a had a block removed.
  648. if (OutermostLoop != L)
  649. formLCSSARecursively(*OutermostLoop, DT, &LI, &SE);
  650. }
  651. /// Checks if \p L has an exiting latch branch. There may also be other
  652. /// exiting blocks. Returns branch instruction terminating the loop
  653. /// latch if above check is successful, nullptr otherwise.
  654. static BranchInst *getExpectedExitLoopLatchBranch(Loop *L) {
  655. BasicBlock *Latch = L->getLoopLatch();
  656. if (!Latch)
  657. return nullptr;
  658. BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
  659. if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
  660. return nullptr;
  661. assert((LatchBR->getSuccessor(0) == L->getHeader() ||
  662. LatchBR->getSuccessor(1) == L->getHeader()) &&
  663. "At least one edge out of the latch must go to the header");
  664. return LatchBR;
  665. }
  666. /// Return the estimated trip count for any exiting branch which dominates
  667. /// the loop latch.
  668. static std::optional<uint64_t> getEstimatedTripCount(BranchInst *ExitingBranch,
  669. Loop *L,
  670. uint64_t &OrigExitWeight) {
  671. // To estimate the number of times the loop body was executed, we want to
  672. // know the number of times the backedge was taken, vs. the number of times
  673. // we exited the loop.
  674. uint64_t LoopWeight, ExitWeight;
  675. if (!extractBranchWeights(*ExitingBranch, LoopWeight, ExitWeight))
  676. return std::nullopt;
  677. if (L->contains(ExitingBranch->getSuccessor(1)))
  678. std::swap(LoopWeight, ExitWeight);
  679. if (!ExitWeight)
  680. // Don't have a way to return predicated infinite
  681. return std::nullopt;
  682. OrigExitWeight = ExitWeight;
  683. // Estimated exit count is a ratio of the loop weight by the weight of the
  684. // edge exiting the loop, rounded to nearest.
  685. uint64_t ExitCount = llvm::divideNearest(LoopWeight, ExitWeight);
  686. // Estimated trip count is one plus estimated exit count.
  687. return ExitCount + 1;
  688. }
  689. std::optional<unsigned>
  690. llvm::getLoopEstimatedTripCount(Loop *L,
  691. unsigned *EstimatedLoopInvocationWeight) {
  692. // Currently we take the estimate exit count only from the loop latch,
  693. // ignoring other exiting blocks. This can overestimate the trip count
  694. // if we exit through another exit, but can never underestimate it.
  695. // TODO: incorporate information from other exits
  696. if (BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L)) {
  697. uint64_t ExitWeight;
  698. if (std::optional<uint64_t> EstTripCount =
  699. getEstimatedTripCount(LatchBranch, L, ExitWeight)) {
  700. if (EstimatedLoopInvocationWeight)
  701. *EstimatedLoopInvocationWeight = ExitWeight;
  702. return *EstTripCount;
  703. }
  704. }
  705. return std::nullopt;
  706. }
  707. bool llvm::setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
  708. unsigned EstimatedloopInvocationWeight) {
  709. // At the moment, we currently support changing the estimate trip count of
  710. // the latch branch only. We could extend this API to manipulate estimated
  711. // trip counts for any exit.
  712. BranchInst *LatchBranch = getExpectedExitLoopLatchBranch(L);
  713. if (!LatchBranch)
  714. return false;
  715. // Calculate taken and exit weights.
  716. unsigned LatchExitWeight = 0;
  717. unsigned BackedgeTakenWeight = 0;
  718. if (EstimatedTripCount > 0) {
  719. LatchExitWeight = EstimatedloopInvocationWeight;
  720. BackedgeTakenWeight = (EstimatedTripCount - 1) * LatchExitWeight;
  721. }
  722. // Make a swap if back edge is taken when condition is "false".
  723. if (LatchBranch->getSuccessor(0) != L->getHeader())
  724. std::swap(BackedgeTakenWeight, LatchExitWeight);
  725. MDBuilder MDB(LatchBranch->getContext());
  726. // Set/Update profile metadata.
  727. LatchBranch->setMetadata(
  728. LLVMContext::MD_prof,
  729. MDB.createBranchWeights(BackedgeTakenWeight, LatchExitWeight));
  730. return true;
  731. }
  732. bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
  733. ScalarEvolution &SE) {
  734. Loop *OuterL = InnerLoop->getParentLoop();
  735. if (!OuterL)
  736. return true;
  737. // Get the backedge taken count for the inner loop
  738. BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
  739. const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
  740. if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
  741. !InnerLoopBECountSC->getType()->isIntegerTy())
  742. return false;
  743. // Get whether count is invariant to the outer loop
  744. ScalarEvolution::LoopDisposition LD =
  745. SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
  746. if (LD != ScalarEvolution::LoopInvariant)
  747. return false;
  748. return true;
  749. }
  750. CmpInst::Predicate llvm::getMinMaxReductionPredicate(RecurKind RK) {
  751. switch (RK) {
  752. default:
  753. llvm_unreachable("Unknown min/max recurrence kind");
  754. case RecurKind::UMin:
  755. return CmpInst::ICMP_ULT;
  756. case RecurKind::UMax:
  757. return CmpInst::ICMP_UGT;
  758. case RecurKind::SMin:
  759. return CmpInst::ICMP_SLT;
  760. case RecurKind::SMax:
  761. return CmpInst::ICMP_SGT;
  762. case RecurKind::FMin:
  763. return CmpInst::FCMP_OLT;
  764. case RecurKind::FMax:
  765. return CmpInst::FCMP_OGT;
  766. }
  767. }
  768. Value *llvm::createSelectCmpOp(IRBuilderBase &Builder, Value *StartVal,
  769. RecurKind RK, Value *Left, Value *Right) {
  770. if (auto VTy = dyn_cast<VectorType>(Left->getType()))
  771. StartVal = Builder.CreateVectorSplat(VTy->getElementCount(), StartVal);
  772. Value *Cmp =
  773. Builder.CreateCmp(CmpInst::ICMP_NE, Left, StartVal, "rdx.select.cmp");
  774. return Builder.CreateSelect(Cmp, Left, Right, "rdx.select");
  775. }
  776. Value *llvm::createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
  777. Value *Right) {
  778. CmpInst::Predicate Pred = getMinMaxReductionPredicate(RK);
  779. Value *Cmp = Builder.CreateCmp(Pred, Left, Right, "rdx.minmax.cmp");
  780. Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
  781. return Select;
  782. }
  783. // Helper to generate an ordered reduction.
  784. Value *llvm::getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
  785. unsigned Op, RecurKind RdxKind) {
  786. unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
  787. // Extract and apply reduction ops in ascending order:
  788. // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
  789. Value *Result = Acc;
  790. for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
  791. Value *Ext =
  792. Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
  793. if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
  794. Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
  795. "bin.rdx");
  796. } else {
  797. assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
  798. "Invalid min/max");
  799. Result = createMinMaxOp(Builder, RdxKind, Result, Ext);
  800. }
  801. }
  802. return Result;
  803. }
  804. // Helper to generate a log2 shuffle reduction.
  805. Value *llvm::getShuffleReduction(IRBuilderBase &Builder, Value *Src,
  806. unsigned Op, RecurKind RdxKind) {
  807. unsigned VF = cast<FixedVectorType>(Src->getType())->getNumElements();
  808. // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
  809. // and vector ops, reducing the set of values being computed by half each
  810. // round.
  811. assert(isPowerOf2_32(VF) &&
  812. "Reduction emission only supported for pow2 vectors!");
  813. // Note: fast-math-flags flags are controlled by the builder configuration
  814. // and are assumed to apply to all generated arithmetic instructions. Other
  815. // poison generating flags (nsw/nuw/inbounds/inrange/exact) are not part
  816. // of the builder configuration, and since they're not passed explicitly,
  817. // will never be relevant here. Note that it would be generally unsound to
  818. // propagate these from an intrinsic call to the expansion anyways as we/
  819. // change the order of operations.
  820. Value *TmpVec = Src;
  821. SmallVector<int, 32> ShuffleMask(VF);
  822. for (unsigned i = VF; i != 1; i >>= 1) {
  823. // Move the upper half of the vector to the lower half.
  824. for (unsigned j = 0; j != i / 2; ++j)
  825. ShuffleMask[j] = i / 2 + j;
  826. // Fill the rest of the mask with undef.
  827. std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), -1);
  828. Value *Shuf = Builder.CreateShuffleVector(TmpVec, ShuffleMask, "rdx.shuf");
  829. if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
  830. TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
  831. "bin.rdx");
  832. } else {
  833. assert(RecurrenceDescriptor::isMinMaxRecurrenceKind(RdxKind) &&
  834. "Invalid min/max");
  835. TmpVec = createMinMaxOp(Builder, RdxKind, TmpVec, Shuf);
  836. }
  837. }
  838. // The result is in the first element of the vector.
  839. return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
  840. }
  841. Value *llvm::createSelectCmpTargetReduction(IRBuilderBase &Builder,
  842. const TargetTransformInfo *TTI,
  843. Value *Src,
  844. const RecurrenceDescriptor &Desc,
  845. PHINode *OrigPhi) {
  846. assert(RecurrenceDescriptor::isSelectCmpRecurrenceKind(
  847. Desc.getRecurrenceKind()) &&
  848. "Unexpected reduction kind");
  849. Value *InitVal = Desc.getRecurrenceStartValue();
  850. Value *NewVal = nullptr;
  851. // First use the original phi to determine the new value we're trying to
  852. // select from in the loop.
  853. SelectInst *SI = nullptr;
  854. for (auto *U : OrigPhi->users()) {
  855. if ((SI = dyn_cast<SelectInst>(U)))
  856. break;
  857. }
  858. assert(SI && "One user of the original phi should be a select");
  859. if (SI->getTrueValue() == OrigPhi)
  860. NewVal = SI->getFalseValue();
  861. else {
  862. assert(SI->getFalseValue() == OrigPhi &&
  863. "At least one input to the select should be the original Phi");
  864. NewVal = SI->getTrueValue();
  865. }
  866. // Create a splat vector with the new value and compare this to the vector
  867. // we want to reduce.
  868. ElementCount EC = cast<VectorType>(Src->getType())->getElementCount();
  869. Value *Right = Builder.CreateVectorSplat(EC, InitVal);
  870. Value *Cmp =
  871. Builder.CreateCmp(CmpInst::ICMP_NE, Src, Right, "rdx.select.cmp");
  872. // If any predicate is true it means that we want to select the new value.
  873. Cmp = Builder.CreateOrReduce(Cmp);
  874. return Builder.CreateSelect(Cmp, NewVal, InitVal, "rdx.select");
  875. }
  876. Value *llvm::createSimpleTargetReduction(IRBuilderBase &Builder,
  877. const TargetTransformInfo *TTI,
  878. Value *Src, RecurKind RdxKind) {
  879. auto *SrcVecEltTy = cast<VectorType>(Src->getType())->getElementType();
  880. switch (RdxKind) {
  881. case RecurKind::Add:
  882. return Builder.CreateAddReduce(Src);
  883. case RecurKind::Mul:
  884. return Builder.CreateMulReduce(Src);
  885. case RecurKind::And:
  886. return Builder.CreateAndReduce(Src);
  887. case RecurKind::Or:
  888. return Builder.CreateOrReduce(Src);
  889. case RecurKind::Xor:
  890. return Builder.CreateXorReduce(Src);
  891. case RecurKind::FMulAdd:
  892. case RecurKind::FAdd:
  893. return Builder.CreateFAddReduce(ConstantFP::getNegativeZero(SrcVecEltTy),
  894. Src);
  895. case RecurKind::FMul:
  896. return Builder.CreateFMulReduce(ConstantFP::get(SrcVecEltTy, 1.0), Src);
  897. case RecurKind::SMax:
  898. return Builder.CreateIntMaxReduce(Src, true);
  899. case RecurKind::SMin:
  900. return Builder.CreateIntMinReduce(Src, true);
  901. case RecurKind::UMax:
  902. return Builder.CreateIntMaxReduce(Src, false);
  903. case RecurKind::UMin:
  904. return Builder.CreateIntMinReduce(Src, false);
  905. case RecurKind::FMax:
  906. return Builder.CreateFPMaxReduce(Src);
  907. case RecurKind::FMin:
  908. return Builder.CreateFPMinReduce(Src);
  909. default:
  910. llvm_unreachable("Unhandled opcode");
  911. }
  912. }
  913. Value *llvm::createTargetReduction(IRBuilderBase &B,
  914. const TargetTransformInfo *TTI,
  915. const RecurrenceDescriptor &Desc, Value *Src,
  916. PHINode *OrigPhi) {
  917. // TODO: Support in-order reductions based on the recurrence descriptor.
  918. // All ops in the reduction inherit fast-math-flags from the recurrence
  919. // descriptor.
  920. IRBuilderBase::FastMathFlagGuard FMFGuard(B);
  921. B.setFastMathFlags(Desc.getFastMathFlags());
  922. RecurKind RK = Desc.getRecurrenceKind();
  923. if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
  924. return createSelectCmpTargetReduction(B, TTI, Src, Desc, OrigPhi);
  925. return createSimpleTargetReduction(B, TTI, Src, RK);
  926. }
  927. Value *llvm::createOrderedReduction(IRBuilderBase &B,
  928. const RecurrenceDescriptor &Desc,
  929. Value *Src, Value *Start) {
  930. assert((Desc.getRecurrenceKind() == RecurKind::FAdd ||
  931. Desc.getRecurrenceKind() == RecurKind::FMulAdd) &&
  932. "Unexpected reduction kind");
  933. assert(Src->getType()->isVectorTy() && "Expected a vector type");
  934. assert(!Start->getType()->isVectorTy() && "Expected a scalar type");
  935. return B.CreateFAddReduce(Start, Src);
  936. }
  937. void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue,
  938. bool IncludeWrapFlags) {
  939. auto *VecOp = dyn_cast<Instruction>(I);
  940. if (!VecOp)
  941. return;
  942. auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
  943. : dyn_cast<Instruction>(OpValue);
  944. if (!Intersection)
  945. return;
  946. const unsigned Opcode = Intersection->getOpcode();
  947. VecOp->copyIRFlags(Intersection, IncludeWrapFlags);
  948. for (auto *V : VL) {
  949. auto *Instr = dyn_cast<Instruction>(V);
  950. if (!Instr)
  951. continue;
  952. if (OpValue == nullptr || Opcode == Instr->getOpcode())
  953. VecOp->andIRFlags(V);
  954. }
  955. }
  956. bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
  957. ScalarEvolution &SE) {
  958. const SCEV *Zero = SE.getZero(S->getType());
  959. return SE.isAvailableAtLoopEntry(S, L) &&
  960. SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
  961. }
  962. bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
  963. ScalarEvolution &SE) {
  964. const SCEV *Zero = SE.getZero(S->getType());
  965. return SE.isAvailableAtLoopEntry(S, L) &&
  966. SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
  967. }
  968. bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
  969. bool Signed) {
  970. unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
  971. APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
  972. APInt::getMinValue(BitWidth);
  973. auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  974. return SE.isAvailableAtLoopEntry(S, L) &&
  975. SE.isLoopEntryGuardedByCond(L, Predicate, S,
  976. SE.getConstant(Min));
  977. }
  978. bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
  979. bool Signed) {
  980. unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
  981. APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
  982. APInt::getMaxValue(BitWidth);
  983. auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
  984. return SE.isAvailableAtLoopEntry(S, L) &&
  985. SE.isLoopEntryGuardedByCond(L, Predicate, S,
  986. SE.getConstant(Max));
  987. }
  988. //===----------------------------------------------------------------------===//
  989. // rewriteLoopExitValues - Optimize IV users outside the loop.
  990. // As a side effect, reduces the amount of IV processing within the loop.
  991. //===----------------------------------------------------------------------===//
  992. static bool hasHardUserWithinLoop(const Loop *L, const Instruction *I) {
  993. SmallPtrSet<const Instruction *, 8> Visited;
  994. SmallVector<const Instruction *, 8> WorkList;
  995. Visited.insert(I);
  996. WorkList.push_back(I);
  997. while (!WorkList.empty()) {
  998. const Instruction *Curr = WorkList.pop_back_val();
  999. // This use is outside the loop, nothing to do.
  1000. if (!L->contains(Curr))
  1001. continue;
  1002. // Do we assume it is a "hard" use which will not be eliminated easily?
  1003. if (Curr->mayHaveSideEffects())
  1004. return true;
  1005. // Otherwise, add all its users to worklist.
  1006. for (const auto *U : Curr->users()) {
  1007. auto *UI = cast<Instruction>(U);
  1008. if (Visited.insert(UI).second)
  1009. WorkList.push_back(UI);
  1010. }
  1011. }
  1012. return false;
  1013. }
  1014. // Collect information about PHI nodes which can be transformed in
  1015. // rewriteLoopExitValues.
  1016. struct RewritePhi {
  1017. PHINode *PN; // For which PHI node is this replacement?
  1018. unsigned Ith; // For which incoming value?
  1019. const SCEV *ExpansionSCEV; // The SCEV of the incoming value we are rewriting.
  1020. Instruction *ExpansionPoint; // Where we'd like to expand that SCEV?
  1021. bool HighCost; // Is this expansion a high-cost?
  1022. RewritePhi(PHINode *P, unsigned I, const SCEV *Val, Instruction *ExpansionPt,
  1023. bool H)
  1024. : PN(P), Ith(I), ExpansionSCEV(Val), ExpansionPoint(ExpansionPt),
  1025. HighCost(H) {}
  1026. };
  1027. // Check whether it is possible to delete the loop after rewriting exit
  1028. // value. If it is possible, ignore ReplaceExitValue and do rewriting
  1029. // aggressively.
  1030. static bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
  1031. BasicBlock *Preheader = L->getLoopPreheader();
  1032. // If there is no preheader, the loop will not be deleted.
  1033. if (!Preheader)
  1034. return false;
  1035. // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
  1036. // We obviate multiple ExitingBlocks case for simplicity.
  1037. // TODO: If we see testcase with multiple ExitingBlocks can be deleted
  1038. // after exit value rewriting, we can enhance the logic here.
  1039. SmallVector<BasicBlock *, 4> ExitingBlocks;
  1040. L->getExitingBlocks(ExitingBlocks);
  1041. SmallVector<BasicBlock *, 8> ExitBlocks;
  1042. L->getUniqueExitBlocks(ExitBlocks);
  1043. if (ExitBlocks.size() != 1 || ExitingBlocks.size() != 1)
  1044. return false;
  1045. BasicBlock *ExitBlock = ExitBlocks[0];
  1046. BasicBlock::iterator BI = ExitBlock->begin();
  1047. while (PHINode *P = dyn_cast<PHINode>(BI)) {
  1048. Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
  1049. // If the Incoming value of P is found in RewritePhiSet, we know it
  1050. // could be rewritten to use a loop invariant value in transformation
  1051. // phase later. Skip it in the loop invariant check below.
  1052. bool found = false;
  1053. for (const RewritePhi &Phi : RewritePhiSet) {
  1054. unsigned i = Phi.Ith;
  1055. if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
  1056. found = true;
  1057. break;
  1058. }
  1059. }
  1060. Instruction *I;
  1061. if (!found && (I = dyn_cast<Instruction>(Incoming)))
  1062. if (!L->hasLoopInvariantOperands(I))
  1063. return false;
  1064. ++BI;
  1065. }
  1066. for (auto *BB : L->blocks())
  1067. if (llvm::any_of(*BB, [](Instruction &I) {
  1068. return I.mayHaveSideEffects();
  1069. }))
  1070. return false;
  1071. return true;
  1072. }
  1073. /// Checks if it is safe to call InductionDescriptor::isInductionPHI for \p Phi,
  1074. /// and returns true if this Phi is an induction phi in the loop. When
  1075. /// isInductionPHI returns true, \p ID will be also be set by isInductionPHI.
  1076. static bool checkIsIndPhi(PHINode *Phi, Loop *L, ScalarEvolution *SE,
  1077. InductionDescriptor &ID) {
  1078. if (!Phi)
  1079. return false;
  1080. if (!L->getLoopPreheader())
  1081. return false;
  1082. if (Phi->getParent() != L->getHeader())
  1083. return false;
  1084. return InductionDescriptor::isInductionPHI(Phi, L, SE, ID);
  1085. }
  1086. int llvm::rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
  1087. ScalarEvolution *SE,
  1088. const TargetTransformInfo *TTI,
  1089. SCEVExpander &Rewriter, DominatorTree *DT,
  1090. ReplaceExitVal ReplaceExitValue,
  1091. SmallVector<WeakTrackingVH, 16> &DeadInsts) {
  1092. // Check a pre-condition.
  1093. assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
  1094. "Indvars did not preserve LCSSA!");
  1095. SmallVector<BasicBlock*, 8> ExitBlocks;
  1096. L->getUniqueExitBlocks(ExitBlocks);
  1097. SmallVector<RewritePhi, 8> RewritePhiSet;
  1098. // Find all values that are computed inside the loop, but used outside of it.
  1099. // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
  1100. // the exit blocks of the loop to find them.
  1101. for (BasicBlock *ExitBB : ExitBlocks) {
  1102. // If there are no PHI nodes in this exit block, then no values defined
  1103. // inside the loop are used on this path, skip it.
  1104. PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
  1105. if (!PN) continue;
  1106. unsigned NumPreds = PN->getNumIncomingValues();
  1107. // Iterate over all of the PHI nodes.
  1108. BasicBlock::iterator BBI = ExitBB->begin();
  1109. while ((PN = dyn_cast<PHINode>(BBI++))) {
  1110. if (PN->use_empty())
  1111. continue; // dead use, don't replace it
  1112. if (!SE->isSCEVable(PN->getType()))
  1113. continue;
  1114. // Iterate over all of the values in all the PHI nodes.
  1115. for (unsigned i = 0; i != NumPreds; ++i) {
  1116. // If the value being merged in is not integer or is not defined
  1117. // in the loop, skip it.
  1118. Value *InVal = PN->getIncomingValue(i);
  1119. if (!isa<Instruction>(InVal))
  1120. continue;
  1121. // If this pred is for a subloop, not L itself, skip it.
  1122. if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
  1123. continue; // The Block is in a subloop, skip it.
  1124. // Check that InVal is defined in the loop.
  1125. Instruction *Inst = cast<Instruction>(InVal);
  1126. if (!L->contains(Inst))
  1127. continue;
  1128. // Find exit values which are induction variables in the loop, and are
  1129. // unused in the loop, with the only use being the exit block PhiNode,
  1130. // and the induction variable update binary operator.
  1131. // The exit value can be replaced with the final value when it is cheap
  1132. // to do so.
  1133. if (ReplaceExitValue == UnusedIndVarInLoop) {
  1134. InductionDescriptor ID;
  1135. PHINode *IndPhi = dyn_cast<PHINode>(Inst);
  1136. if (IndPhi) {
  1137. if (!checkIsIndPhi(IndPhi, L, SE, ID))
  1138. continue;
  1139. // This is an induction PHI. Check that the only users are PHI
  1140. // nodes, and induction variable update binary operators.
  1141. if (llvm::any_of(Inst->users(), [&](User *U) {
  1142. if (!isa<PHINode>(U) && !isa<BinaryOperator>(U))
  1143. return true;
  1144. BinaryOperator *B = dyn_cast<BinaryOperator>(U);
  1145. if (B && B != ID.getInductionBinOp())
  1146. return true;
  1147. return false;
  1148. }))
  1149. continue;
  1150. } else {
  1151. // If it is not an induction phi, it must be an induction update
  1152. // binary operator with an induction phi user.
  1153. BinaryOperator *B = dyn_cast<BinaryOperator>(Inst);
  1154. if (!B)
  1155. continue;
  1156. if (llvm::any_of(Inst->users(), [&](User *U) {
  1157. PHINode *Phi = dyn_cast<PHINode>(U);
  1158. if (Phi != PN && !checkIsIndPhi(Phi, L, SE, ID))
  1159. return true;
  1160. return false;
  1161. }))
  1162. continue;
  1163. if (B != ID.getInductionBinOp())
  1164. continue;
  1165. }
  1166. }
  1167. // Okay, this instruction has a user outside of the current loop
  1168. // and varies predictably *inside* the loop. Evaluate the value it
  1169. // contains when the loop exits, if possible. We prefer to start with
  1170. // expressions which are true for all exits (so as to maximize
  1171. // expression reuse by the SCEVExpander), but resort to per-exit
  1172. // evaluation if that fails.
  1173. const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
  1174. if (isa<SCEVCouldNotCompute>(ExitValue) ||
  1175. !SE->isLoopInvariant(ExitValue, L) ||
  1176. !Rewriter.isSafeToExpand(ExitValue)) {
  1177. // TODO: This should probably be sunk into SCEV in some way; maybe a
  1178. // getSCEVForExit(SCEV*, L, ExitingBB)? It can be generalized for
  1179. // most SCEV expressions and other recurrence types (e.g. shift
  1180. // recurrences). Is there existing code we can reuse?
  1181. const SCEV *ExitCount = SE->getExitCount(L, PN->getIncomingBlock(i));
  1182. if (isa<SCEVCouldNotCompute>(ExitCount))
  1183. continue;
  1184. if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
  1185. if (AddRec->getLoop() == L)
  1186. ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
  1187. if (isa<SCEVCouldNotCompute>(ExitValue) ||
  1188. !SE->isLoopInvariant(ExitValue, L) ||
  1189. !Rewriter.isSafeToExpand(ExitValue))
  1190. continue;
  1191. }
  1192. // Computing the value outside of the loop brings no benefit if it is
  1193. // definitely used inside the loop in a way which can not be optimized
  1194. // away. Avoid doing so unless we know we have a value which computes
  1195. // the ExitValue already. TODO: This should be merged into SCEV
  1196. // expander to leverage its knowledge of existing expressions.
  1197. if (ReplaceExitValue != AlwaysRepl && !isa<SCEVConstant>(ExitValue) &&
  1198. !isa<SCEVUnknown>(ExitValue) && hasHardUserWithinLoop(L, Inst))
  1199. continue;
  1200. // Check if expansions of this SCEV would count as being high cost.
  1201. bool HighCost = Rewriter.isHighCostExpansion(
  1202. ExitValue, L, SCEVCheapExpansionBudget, TTI, Inst);
  1203. // Note that we must not perform expansions until after
  1204. // we query *all* the costs, because if we perform temporary expansion
  1205. // inbetween, one that we might not intend to keep, said expansion
  1206. // *may* affect cost calculation of the the next SCEV's we'll query,
  1207. // and next SCEV may errneously get smaller cost.
  1208. // Collect all the candidate PHINodes to be rewritten.
  1209. Instruction *InsertPt =
  1210. (isa<PHINode>(Inst) || isa<LandingPadInst>(Inst)) ?
  1211. &*Inst->getParent()->getFirstInsertionPt() : Inst;
  1212. RewritePhiSet.emplace_back(PN, i, ExitValue, InsertPt, HighCost);
  1213. }
  1214. }
  1215. }
  1216. // TODO: evaluate whether it is beneficial to change how we calculate
  1217. // high-cost: if we have SCEV 'A' which we know we will expand, should we
  1218. // calculate the cost of other SCEV's after expanding SCEV 'A', thus
  1219. // potentially giving cost bonus to those other SCEV's?
  1220. bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
  1221. int NumReplaced = 0;
  1222. // Transformation.
  1223. for (const RewritePhi &Phi : RewritePhiSet) {
  1224. PHINode *PN = Phi.PN;
  1225. // Only do the rewrite when the ExitValue can be expanded cheaply.
  1226. // If LoopCanBeDel is true, rewrite exit value aggressively.
  1227. if ((ReplaceExitValue == OnlyCheapRepl ||
  1228. ReplaceExitValue == UnusedIndVarInLoop) &&
  1229. !LoopCanBeDel && Phi.HighCost)
  1230. continue;
  1231. Value *ExitVal = Rewriter.expandCodeFor(
  1232. Phi.ExpansionSCEV, Phi.PN->getType(), Phi.ExpansionPoint);
  1233. LLVM_DEBUG(dbgs() << "rewriteLoopExitValues: AfterLoopVal = " << *ExitVal
  1234. << '\n'
  1235. << " LoopVal = " << *(Phi.ExpansionPoint) << "\n");
  1236. #ifndef NDEBUG
  1237. // If we reuse an instruction from a loop which is neither L nor one of
  1238. // its containing loops, we end up breaking LCSSA form for this loop by
  1239. // creating a new use of its instruction.
  1240. if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
  1241. if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
  1242. if (EVL != L)
  1243. assert(EVL->contains(L) && "LCSSA breach detected!");
  1244. #endif
  1245. NumReplaced++;
  1246. Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
  1247. PN->setIncomingValue(Phi.Ith, ExitVal);
  1248. // It's necessary to tell ScalarEvolution about this explicitly so that
  1249. // it can walk the def-use list and forget all SCEVs, as it may not be
  1250. // watching the PHI itself. Once the new exit value is in place, there
  1251. // may not be a def-use connection between the loop and every instruction
  1252. // which got a SCEVAddRecExpr for that loop.
  1253. SE->forgetValue(PN);
  1254. // If this instruction is dead now, delete it. Don't do it now to avoid
  1255. // invalidating iterators.
  1256. if (isInstructionTriviallyDead(Inst, TLI))
  1257. DeadInsts.push_back(Inst);
  1258. // Replace PN with ExitVal if that is legal and does not break LCSSA.
  1259. if (PN->getNumIncomingValues() == 1 &&
  1260. LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
  1261. PN->replaceAllUsesWith(ExitVal);
  1262. PN->eraseFromParent();
  1263. }
  1264. }
  1265. // The insertion point instruction may have been deleted; clear it out
  1266. // so that the rewriter doesn't trip over it later.
  1267. Rewriter.clearInsertPoint();
  1268. return NumReplaced;
  1269. }
  1270. /// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
  1271. /// \p OrigLoop.
  1272. void llvm::setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
  1273. Loop *RemainderLoop, uint64_t UF) {
  1274. assert(UF > 0 && "Zero unrolled factor is not supported");
  1275. assert(UnrolledLoop != RemainderLoop &&
  1276. "Unrolled and Remainder loops are expected to distinct");
  1277. // Get number of iterations in the original scalar loop.
  1278. unsigned OrigLoopInvocationWeight = 0;
  1279. std::optional<unsigned> OrigAverageTripCount =
  1280. getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
  1281. if (!OrigAverageTripCount)
  1282. return;
  1283. // Calculate number of iterations in unrolled loop.
  1284. unsigned UnrolledAverageTripCount = *OrigAverageTripCount / UF;
  1285. // Calculate number of iterations for remainder loop.
  1286. unsigned RemainderAverageTripCount = *OrigAverageTripCount % UF;
  1287. setLoopEstimatedTripCount(UnrolledLoop, UnrolledAverageTripCount,
  1288. OrigLoopInvocationWeight);
  1289. setLoopEstimatedTripCount(RemainderLoop, RemainderAverageTripCount,
  1290. OrigLoopInvocationWeight);
  1291. }
  1292. /// Utility that implements appending of loops onto a worklist.
  1293. /// Loops are added in preorder (analogous for reverse postorder for trees),
  1294. /// and the worklist is processed LIFO.
  1295. template <typename RangeT>
  1296. void llvm::appendReversedLoopsToWorklist(
  1297. RangeT &&Loops, SmallPriorityWorklist<Loop *, 4> &Worklist) {
  1298. // We use an internal worklist to build up the preorder traversal without
  1299. // recursion.
  1300. SmallVector<Loop *, 4> PreOrderLoops, PreOrderWorklist;
  1301. // We walk the initial sequence of loops in reverse because we generally want
  1302. // to visit defs before uses and the worklist is LIFO.
  1303. for (Loop *RootL : Loops) {
  1304. assert(PreOrderLoops.empty() && "Must start with an empty preorder walk.");
  1305. assert(PreOrderWorklist.empty() &&
  1306. "Must start with an empty preorder walk worklist.");
  1307. PreOrderWorklist.push_back(RootL);
  1308. do {
  1309. Loop *L = PreOrderWorklist.pop_back_val();
  1310. PreOrderWorklist.append(L->begin(), L->end());
  1311. PreOrderLoops.push_back(L);
  1312. } while (!PreOrderWorklist.empty());
  1313. Worklist.insert(std::move(PreOrderLoops));
  1314. PreOrderLoops.clear();
  1315. }
  1316. }
  1317. template <typename RangeT>
  1318. void llvm::appendLoopsToWorklist(RangeT &&Loops,
  1319. SmallPriorityWorklist<Loop *, 4> &Worklist) {
  1320. appendReversedLoopsToWorklist(reverse(Loops), Worklist);
  1321. }
  1322. template void llvm::appendLoopsToWorklist<ArrayRef<Loop *> &>(
  1323. ArrayRef<Loop *> &Loops, SmallPriorityWorklist<Loop *, 4> &Worklist);
  1324. template void
  1325. llvm::appendLoopsToWorklist<Loop &>(Loop &L,
  1326. SmallPriorityWorklist<Loop *, 4> &Worklist);
  1327. void llvm::appendLoopsToWorklist(LoopInfo &LI,
  1328. SmallPriorityWorklist<Loop *, 4> &Worklist) {
  1329. appendReversedLoopsToWorklist(LI, Worklist);
  1330. }
  1331. Loop *llvm::cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
  1332. LoopInfo *LI, LPPassManager *LPM) {
  1333. Loop &New = *LI->AllocateLoop();
  1334. if (PL)
  1335. PL->addChildLoop(&New);
  1336. else
  1337. LI->addTopLevelLoop(&New);
  1338. if (LPM)
  1339. LPM->addLoop(New);
  1340. // Add all of the blocks in L to the new loop.
  1341. for (BasicBlock *BB : L->blocks())
  1342. if (LI->getLoopFor(BB) == L)
  1343. New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), *LI);
  1344. // Add all of the subloops to the new loop.
  1345. for (Loop *I : *L)
  1346. cloneLoop(I, &New, VM, LI, LPM);
  1347. return &New;
  1348. }
  1349. /// IR Values for the lower and upper bounds of a pointer evolution. We
  1350. /// need to use value-handles because SCEV expansion can invalidate previously
  1351. /// expanded values. Thus expansion of a pointer can invalidate the bounds for
  1352. /// a previous one.
  1353. struct PointerBounds {
  1354. TrackingVH<Value> Start;
  1355. TrackingVH<Value> End;
  1356. };
  1357. /// Expand code for the lower and upper bound of the pointer group \p CG
  1358. /// in \p TheLoop. \return the values for the bounds.
  1359. static PointerBounds expandBounds(const RuntimeCheckingPtrGroup *CG,
  1360. Loop *TheLoop, Instruction *Loc,
  1361. SCEVExpander &Exp) {
  1362. LLVMContext &Ctx = Loc->getContext();
  1363. Type *PtrArithTy = Type::getInt8PtrTy(Ctx, CG->AddressSpace);
  1364. Value *Start = nullptr, *End = nullptr;
  1365. LLVM_DEBUG(dbgs() << "LAA: Adding RT check for range:\n");
  1366. Start = Exp.expandCodeFor(CG->Low, PtrArithTy, Loc);
  1367. End = Exp.expandCodeFor(CG->High, PtrArithTy, Loc);
  1368. if (CG->NeedsFreeze) {
  1369. IRBuilder<> Builder(Loc);
  1370. Start = Builder.CreateFreeze(Start, Start->getName() + ".fr");
  1371. End = Builder.CreateFreeze(End, End->getName() + ".fr");
  1372. }
  1373. LLVM_DEBUG(dbgs() << "Start: " << *CG->Low << " End: " << *CG->High << "\n");
  1374. return {Start, End};
  1375. }
  1376. /// Turns a collection of checks into a collection of expanded upper and
  1377. /// lower bounds for both pointers in the check.
  1378. static SmallVector<std::pair<PointerBounds, PointerBounds>, 4>
  1379. expandBounds(const SmallVectorImpl<RuntimePointerCheck> &PointerChecks, Loop *L,
  1380. Instruction *Loc, SCEVExpander &Exp) {
  1381. SmallVector<std::pair<PointerBounds, PointerBounds>, 4> ChecksWithBounds;
  1382. // Here we're relying on the SCEV Expander's cache to only emit code for the
  1383. // same bounds once.
  1384. transform(PointerChecks, std::back_inserter(ChecksWithBounds),
  1385. [&](const RuntimePointerCheck &Check) {
  1386. PointerBounds First = expandBounds(Check.first, L, Loc, Exp),
  1387. Second = expandBounds(Check.second, L, Loc, Exp);
  1388. return std::make_pair(First, Second);
  1389. });
  1390. return ChecksWithBounds;
  1391. }
  1392. Value *llvm::addRuntimeChecks(
  1393. Instruction *Loc, Loop *TheLoop,
  1394. const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
  1395. SCEVExpander &Exp) {
  1396. // TODO: Move noalias annotation code from LoopVersioning here and share with LV if possible.
  1397. // TODO: Pass RtPtrChecking instead of PointerChecks and SE separately, if possible
  1398. auto ExpandedChecks = expandBounds(PointerChecks, TheLoop, Loc, Exp);
  1399. LLVMContext &Ctx = Loc->getContext();
  1400. IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx,
  1401. Loc->getModule()->getDataLayout());
  1402. ChkBuilder.SetInsertPoint(Loc);
  1403. // Our instructions might fold to a constant.
  1404. Value *MemoryRuntimeCheck = nullptr;
  1405. for (const auto &Check : ExpandedChecks) {
  1406. const PointerBounds &A = Check.first, &B = Check.second;
  1407. // Check if two pointers (A and B) conflict where conflict is computed as:
  1408. // start(A) <= end(B) && start(B) <= end(A)
  1409. unsigned AS0 = A.Start->getType()->getPointerAddressSpace();
  1410. unsigned AS1 = B.Start->getType()->getPointerAddressSpace();
  1411. assert((AS0 == B.End->getType()->getPointerAddressSpace()) &&
  1412. (AS1 == A.End->getType()->getPointerAddressSpace()) &&
  1413. "Trying to bounds check pointers with different address spaces");
  1414. Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
  1415. Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
  1416. Value *Start0 = ChkBuilder.CreateBitCast(A.Start, PtrArithTy0, "bc");
  1417. Value *Start1 = ChkBuilder.CreateBitCast(B.Start, PtrArithTy1, "bc");
  1418. Value *End0 = ChkBuilder.CreateBitCast(A.End, PtrArithTy1, "bc");
  1419. Value *End1 = ChkBuilder.CreateBitCast(B.End, PtrArithTy0, "bc");
  1420. // [A|B].Start points to the first accessed byte under base [A|B].
  1421. // [A|B].End points to the last accessed byte, plus one.
  1422. // There is no conflict when the intervals are disjoint:
  1423. // NoConflict = (B.Start >= A.End) || (A.Start >= B.End)
  1424. //
  1425. // bound0 = (B.Start < A.End)
  1426. // bound1 = (A.Start < B.End)
  1427. // IsConflict = bound0 & bound1
  1428. Value *Cmp0 = ChkBuilder.CreateICmpULT(Start0, End1, "bound0");
  1429. Value *Cmp1 = ChkBuilder.CreateICmpULT(Start1, End0, "bound1");
  1430. Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
  1431. if (MemoryRuntimeCheck) {
  1432. IsConflict =
  1433. ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
  1434. }
  1435. MemoryRuntimeCheck = IsConflict;
  1436. }
  1437. return MemoryRuntimeCheck;
  1438. }
  1439. Value *llvm::addDiffRuntimeChecks(
  1440. Instruction *Loc, ArrayRef<PointerDiffInfo> Checks, SCEVExpander &Expander,
  1441. function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC) {
  1442. LLVMContext &Ctx = Loc->getContext();
  1443. IRBuilder<InstSimplifyFolder> ChkBuilder(Ctx,
  1444. Loc->getModule()->getDataLayout());
  1445. ChkBuilder.SetInsertPoint(Loc);
  1446. // Our instructions might fold to a constant.
  1447. Value *MemoryRuntimeCheck = nullptr;
  1448. for (const auto &C : Checks) {
  1449. Type *Ty = C.SinkStart->getType();
  1450. // Compute VF * IC * AccessSize.
  1451. auto *VFTimesUFTimesSize =
  1452. ChkBuilder.CreateMul(GetVF(ChkBuilder, Ty->getScalarSizeInBits()),
  1453. ConstantInt::get(Ty, IC * C.AccessSize));
  1454. Value *Sink = Expander.expandCodeFor(C.SinkStart, Ty, Loc);
  1455. Value *Src = Expander.expandCodeFor(C.SrcStart, Ty, Loc);
  1456. if (C.NeedsFreeze) {
  1457. IRBuilder<> Builder(Loc);
  1458. Sink = Builder.CreateFreeze(Sink, Sink->getName() + ".fr");
  1459. Src = Builder.CreateFreeze(Src, Src->getName() + ".fr");
  1460. }
  1461. Value *Diff = ChkBuilder.CreateSub(Sink, Src);
  1462. Value *IsConflict =
  1463. ChkBuilder.CreateICmpULT(Diff, VFTimesUFTimesSize, "diff.check");
  1464. if (MemoryRuntimeCheck) {
  1465. IsConflict =
  1466. ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, "conflict.rdx");
  1467. }
  1468. MemoryRuntimeCheck = IsConflict;
  1469. }
  1470. return MemoryRuntimeCheck;
  1471. }
  1472. std::optional<IVConditionInfo>
  1473. llvm::hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold,
  1474. const MemorySSA &MSSA, AAResults &AA) {
  1475. auto *TI = dyn_cast<BranchInst>(L.getHeader()->getTerminator());
  1476. if (!TI || !TI->isConditional())
  1477. return {};
  1478. auto *CondI = dyn_cast<CmpInst>(TI->getCondition());
  1479. // The case with the condition outside the loop should already be handled
  1480. // earlier.
  1481. if (!CondI || !L.contains(CondI))
  1482. return {};
  1483. SmallVector<Instruction *> InstToDuplicate;
  1484. InstToDuplicate.push_back(CondI);
  1485. SmallVector<Value *, 4> WorkList;
  1486. WorkList.append(CondI->op_begin(), CondI->op_end());
  1487. SmallVector<MemoryAccess *, 4> AccessesToCheck;
  1488. SmallVector<MemoryLocation, 4> AccessedLocs;
  1489. while (!WorkList.empty()) {
  1490. Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val());
  1491. if (!I || !L.contains(I))
  1492. continue;
  1493. // TODO: support additional instructions.
  1494. if (!isa<LoadInst>(I) && !isa<GetElementPtrInst>(I))
  1495. return {};
  1496. // Do not duplicate volatile and atomic loads.
  1497. if (auto *LI = dyn_cast<LoadInst>(I))
  1498. if (LI->isVolatile() || LI->isAtomic())
  1499. return {};
  1500. InstToDuplicate.push_back(I);
  1501. if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
  1502. if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
  1503. // Queue the defining access to check for alias checks.
  1504. AccessesToCheck.push_back(MemUse->getDefiningAccess());
  1505. AccessedLocs.push_back(MemoryLocation::get(I));
  1506. } else {
  1507. // MemoryDefs may clobber the location or may be atomic memory
  1508. // operations. Bail out.
  1509. return {};
  1510. }
  1511. }
  1512. WorkList.append(I->op_begin(), I->op_end());
  1513. }
  1514. if (InstToDuplicate.empty())
  1515. return {};
  1516. SmallVector<BasicBlock *, 4> ExitingBlocks;
  1517. L.getExitingBlocks(ExitingBlocks);
  1518. auto HasNoClobbersOnPath =
  1519. [&L, &AA, &AccessedLocs, &ExitingBlocks, &InstToDuplicate,
  1520. MSSAThreshold](BasicBlock *Succ, BasicBlock *Header,
  1521. SmallVector<MemoryAccess *, 4> AccessesToCheck)
  1522. -> std::optional<IVConditionInfo> {
  1523. IVConditionInfo Info;
  1524. // First, collect all blocks in the loop that are on a patch from Succ
  1525. // to the header.
  1526. SmallVector<BasicBlock *, 4> WorkList;
  1527. WorkList.push_back(Succ);
  1528. WorkList.push_back(Header);
  1529. SmallPtrSet<BasicBlock *, 4> Seen;
  1530. Seen.insert(Header);
  1531. Info.PathIsNoop &=
  1532. all_of(*Header, [](Instruction &I) { return !I.mayHaveSideEffects(); });
  1533. while (!WorkList.empty()) {
  1534. BasicBlock *Current = WorkList.pop_back_val();
  1535. if (!L.contains(Current))
  1536. continue;
  1537. const auto &SeenIns = Seen.insert(Current);
  1538. if (!SeenIns.second)
  1539. continue;
  1540. Info.PathIsNoop &= all_of(
  1541. *Current, [](Instruction &I) { return !I.mayHaveSideEffects(); });
  1542. WorkList.append(succ_begin(Current), succ_end(Current));
  1543. }
  1544. // Require at least 2 blocks on a path through the loop. This skips
  1545. // paths that directly exit the loop.
  1546. if (Seen.size() < 2)
  1547. return {};
  1548. // Next, check if there are any MemoryDefs that are on the path through
  1549. // the loop (in the Seen set) and they may-alias any of the locations in
  1550. // AccessedLocs. If that is the case, they may modify the condition and
  1551. // partial unswitching is not possible.
  1552. SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
  1553. while (!AccessesToCheck.empty()) {
  1554. MemoryAccess *Current = AccessesToCheck.pop_back_val();
  1555. auto SeenI = SeenAccesses.insert(Current);
  1556. if (!SeenI.second || !Seen.contains(Current->getBlock()))
  1557. continue;
  1558. // Bail out if exceeded the threshold.
  1559. if (SeenAccesses.size() >= MSSAThreshold)
  1560. return {};
  1561. // MemoryUse are read-only accesses.
  1562. if (isa<MemoryUse>(Current))
  1563. continue;
  1564. // For a MemoryDef, check if is aliases any of the location feeding
  1565. // the original condition.
  1566. if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
  1567. if (any_of(AccessedLocs, [&AA, CurrentDef](MemoryLocation &Loc) {
  1568. return isModSet(
  1569. AA.getModRefInfo(CurrentDef->getMemoryInst(), Loc));
  1570. }))
  1571. return {};
  1572. }
  1573. for (Use &U : Current->uses())
  1574. AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
  1575. }
  1576. // We could also allow loops with known trip counts without mustprogress,
  1577. // but ScalarEvolution may not be available.
  1578. Info.PathIsNoop &= isMustProgress(&L);
  1579. // If the path is considered a no-op so far, check if it reaches a
  1580. // single exit block without any phis. This ensures no values from the
  1581. // loop are used outside of the loop.
  1582. if (Info.PathIsNoop) {
  1583. for (auto *Exiting : ExitingBlocks) {
  1584. if (!Seen.contains(Exiting))
  1585. continue;
  1586. for (auto *Succ : successors(Exiting)) {
  1587. if (L.contains(Succ))
  1588. continue;
  1589. Info.PathIsNoop &= Succ->phis().empty() &&
  1590. (!Info.ExitForPath || Info.ExitForPath == Succ);
  1591. if (!Info.PathIsNoop)
  1592. break;
  1593. assert((!Info.ExitForPath || Info.ExitForPath == Succ) &&
  1594. "cannot have multiple exit blocks");
  1595. Info.ExitForPath = Succ;
  1596. }
  1597. }
  1598. }
  1599. if (!Info.ExitForPath)
  1600. Info.PathIsNoop = false;
  1601. Info.InstToDuplicate = InstToDuplicate;
  1602. return Info;
  1603. };
  1604. // If we branch to the same successor, partial unswitching will not be
  1605. // beneficial.
  1606. if (TI->getSuccessor(0) == TI->getSuccessor(1))
  1607. return {};
  1608. if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(0), L.getHeader(),
  1609. AccessesToCheck)) {
  1610. Info->KnownValue = ConstantInt::getTrue(TI->getContext());
  1611. return Info;
  1612. }
  1613. if (auto Info = HasNoClobbersOnPath(TI->getSuccessor(1), L.getHeader(),
  1614. AccessesToCheck)) {
  1615. Info->KnownValue = ConstantInt::getFalse(TI->getContext());
  1616. return Info;
  1617. }
  1618. return {};
  1619. }