DependenceAnalysis.cpp 154 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136
  1. //===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
  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. // DependenceAnalysis is an LLVM pass that analyses dependences between memory
  10. // accesses. Currently, it is an (incomplete) implementation of the approach
  11. // described in
  12. //
  13. // Practical Dependence Testing
  14. // Goff, Kennedy, Tseng
  15. // PLDI 1991
  16. //
  17. // There's a single entry point that analyzes the dependence between a pair
  18. // of memory references in a function, returning either NULL, for no dependence,
  19. // or a more-or-less detailed description of the dependence between them.
  20. //
  21. // Currently, the implementation cannot propagate constraints between
  22. // coupled RDIV subscripts and lacks a multi-subscript MIV test.
  23. // Both of these are conservative weaknesses;
  24. // that is, not a source of correctness problems.
  25. //
  26. // Since Clang linearizes some array subscripts, the dependence
  27. // analysis is using SCEV->delinearize to recover the representation of multiple
  28. // subscripts, and thus avoid the more expensive and less precise MIV tests. The
  29. // delinearization is controlled by the flag -da-delinearize.
  30. //
  31. // We should pay some careful attention to the possibility of integer overflow
  32. // in the implementation of the various tests. This could happen with Add,
  33. // Subtract, or Multiply, with both APInt's and SCEV's.
  34. //
  35. // Some non-linear subscript pairs can be handled by the GCD test
  36. // (and perhaps other tests).
  37. // Should explore how often these things occur.
  38. //
  39. // Finally, it seems like certain test cases expose weaknesses in the SCEV
  40. // simplification, especially in the handling of sign and zero extensions.
  41. // It could be useful to spend time exploring these.
  42. //
  43. // Please note that this is work in progress and the interface is subject to
  44. // change.
  45. //
  46. //===----------------------------------------------------------------------===//
  47. // //
  48. // In memory of Ken Kennedy, 1945 - 2007 //
  49. // //
  50. //===----------------------------------------------------------------------===//
  51. #include "llvm/Analysis/DependenceAnalysis.h"
  52. #include "llvm/ADT/STLExtras.h"
  53. #include "llvm/ADT/Statistic.h"
  54. #include "llvm/Analysis/AliasAnalysis.h"
  55. #include "llvm/Analysis/Delinearization.h"
  56. #include "llvm/Analysis/LoopInfo.h"
  57. #include "llvm/Analysis/ScalarEvolution.h"
  58. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  59. #include "llvm/Analysis/ValueTracking.h"
  60. #include "llvm/Config/llvm-config.h"
  61. #include "llvm/IR/InstIterator.h"
  62. #include "llvm/IR/Module.h"
  63. #include "llvm/IR/Operator.h"
  64. #include "llvm/InitializePasses.h"
  65. #include "llvm/Support/CommandLine.h"
  66. #include "llvm/Support/Debug.h"
  67. #include "llvm/Support/ErrorHandling.h"
  68. #include "llvm/Support/raw_ostream.h"
  69. using namespace llvm;
  70. #define DEBUG_TYPE "da"
  71. //===----------------------------------------------------------------------===//
  72. // statistics
  73. STATISTIC(TotalArrayPairs, "Array pairs tested");
  74. STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs");
  75. STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs");
  76. STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
  77. STATISTIC(ZIVapplications, "ZIV applications");
  78. STATISTIC(ZIVindependence, "ZIV independence");
  79. STATISTIC(StrongSIVapplications, "Strong SIV applications");
  80. STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
  81. STATISTIC(StrongSIVindependence, "Strong SIV independence");
  82. STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
  83. STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
  84. STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
  85. STATISTIC(ExactSIVapplications, "Exact SIV applications");
  86. STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
  87. STATISTIC(ExactSIVindependence, "Exact SIV independence");
  88. STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
  89. STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
  90. STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
  91. STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
  92. STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
  93. STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
  94. STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
  95. STATISTIC(DeltaApplications, "Delta applications");
  96. STATISTIC(DeltaSuccesses, "Delta successes");
  97. STATISTIC(DeltaIndependence, "Delta independence");
  98. STATISTIC(DeltaPropagations, "Delta propagations");
  99. STATISTIC(GCDapplications, "GCD applications");
  100. STATISTIC(GCDsuccesses, "GCD successes");
  101. STATISTIC(GCDindependence, "GCD independence");
  102. STATISTIC(BanerjeeApplications, "Banerjee applications");
  103. STATISTIC(BanerjeeIndependence, "Banerjee independence");
  104. STATISTIC(BanerjeeSuccesses, "Banerjee successes");
  105. static cl::opt<bool>
  106. Delinearize("da-delinearize", cl::init(true), cl::Hidden, cl::ZeroOrMore,
  107. cl::desc("Try to delinearize array references."));
  108. static cl::opt<bool> DisableDelinearizationChecks(
  109. "da-disable-delinearization-checks", cl::init(false), cl::Hidden,
  110. cl::ZeroOrMore,
  111. cl::desc(
  112. "Disable checks that try to statically verify validity of "
  113. "delinearized subscripts. Enabling this option may result in incorrect "
  114. "dependence vectors for languages that allow the subscript of one "
  115. "dimension to underflow or overflow into another dimension."));
  116. static cl::opt<unsigned> MIVMaxLevelThreshold(
  117. "da-miv-max-level-threshold", cl::init(7), cl::Hidden, cl::ZeroOrMore,
  118. cl::desc("Maximum depth allowed for the recursive algorithm used to "
  119. "explore MIV direction vectors."));
  120. //===----------------------------------------------------------------------===//
  121. // basics
  122. DependenceAnalysis::Result
  123. DependenceAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
  124. auto &AA = FAM.getResult<AAManager>(F);
  125. auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
  126. auto &LI = FAM.getResult<LoopAnalysis>(F);
  127. return DependenceInfo(&F, &AA, &SE, &LI);
  128. }
  129. AnalysisKey DependenceAnalysis::Key;
  130. INITIALIZE_PASS_BEGIN(DependenceAnalysisWrapperPass, "da",
  131. "Dependence Analysis", true, true)
  132. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  133. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  134. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  135. INITIALIZE_PASS_END(DependenceAnalysisWrapperPass, "da", "Dependence Analysis",
  136. true, true)
  137. char DependenceAnalysisWrapperPass::ID = 0;
  138. DependenceAnalysisWrapperPass::DependenceAnalysisWrapperPass()
  139. : FunctionPass(ID) {
  140. initializeDependenceAnalysisWrapperPassPass(*PassRegistry::getPassRegistry());
  141. }
  142. FunctionPass *llvm::createDependenceAnalysisWrapperPass() {
  143. return new DependenceAnalysisWrapperPass();
  144. }
  145. bool DependenceAnalysisWrapperPass::runOnFunction(Function &F) {
  146. auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
  147. auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  148. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  149. info.reset(new DependenceInfo(&F, &AA, &SE, &LI));
  150. return false;
  151. }
  152. DependenceInfo &DependenceAnalysisWrapperPass::getDI() const { return *info; }
  153. void DependenceAnalysisWrapperPass::releaseMemory() { info.reset(); }
  154. void DependenceAnalysisWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  155. AU.setPreservesAll();
  156. AU.addRequiredTransitive<AAResultsWrapperPass>();
  157. AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
  158. AU.addRequiredTransitive<LoopInfoWrapperPass>();
  159. }
  160. // Used to test the dependence analyzer.
  161. // Looks through the function, noting instructions that may access memory.
  162. // Calls depends() on every possible pair and prints out the result.
  163. // Ignores all other instructions.
  164. static void dumpExampleDependence(raw_ostream &OS, DependenceInfo *DA) {
  165. auto *F = DA->getFunction();
  166. for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); SrcI != SrcE;
  167. ++SrcI) {
  168. if (SrcI->mayReadOrWriteMemory()) {
  169. for (inst_iterator DstI = SrcI, DstE = inst_end(F);
  170. DstI != DstE; ++DstI) {
  171. if (DstI->mayReadOrWriteMemory()) {
  172. OS << "Src:" << *SrcI << " --> Dst:" << *DstI << "\n";
  173. OS << " da analyze - ";
  174. if (auto D = DA->depends(&*SrcI, &*DstI, true)) {
  175. D->dump(OS);
  176. for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
  177. if (D->isSplitable(Level)) {
  178. OS << " da analyze - split level = " << Level;
  179. OS << ", iteration = " << *DA->getSplitIteration(*D, Level);
  180. OS << "!\n";
  181. }
  182. }
  183. }
  184. else
  185. OS << "none!\n";
  186. }
  187. }
  188. }
  189. }
  190. }
  191. void DependenceAnalysisWrapperPass::print(raw_ostream &OS,
  192. const Module *) const {
  193. dumpExampleDependence(OS, info.get());
  194. }
  195. PreservedAnalyses
  196. DependenceAnalysisPrinterPass::run(Function &F, FunctionAnalysisManager &FAM) {
  197. OS << "'Dependence Analysis' for function '" << F.getName() << "':\n";
  198. dumpExampleDependence(OS, &FAM.getResult<DependenceAnalysis>(F));
  199. return PreservedAnalyses::all();
  200. }
  201. //===----------------------------------------------------------------------===//
  202. // Dependence methods
  203. // Returns true if this is an input dependence.
  204. bool Dependence::isInput() const {
  205. return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
  206. }
  207. // Returns true if this is an output dependence.
  208. bool Dependence::isOutput() const {
  209. return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
  210. }
  211. // Returns true if this is an flow (aka true) dependence.
  212. bool Dependence::isFlow() const {
  213. return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
  214. }
  215. // Returns true if this is an anti dependence.
  216. bool Dependence::isAnti() const {
  217. return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
  218. }
  219. // Returns true if a particular level is scalar; that is,
  220. // if no subscript in the source or destination mention the induction
  221. // variable associated with the loop at this level.
  222. // Leave this out of line, so it will serve as a virtual method anchor
  223. bool Dependence::isScalar(unsigned level) const {
  224. return false;
  225. }
  226. //===----------------------------------------------------------------------===//
  227. // FullDependence methods
  228. FullDependence::FullDependence(Instruction *Source, Instruction *Destination,
  229. bool PossiblyLoopIndependent,
  230. unsigned CommonLevels)
  231. : Dependence(Source, Destination), Levels(CommonLevels),
  232. LoopIndependent(PossiblyLoopIndependent) {
  233. Consistent = true;
  234. if (CommonLevels)
  235. DV = std::make_unique<DVEntry[]>(CommonLevels);
  236. }
  237. // The rest are simple getters that hide the implementation.
  238. // getDirection - Returns the direction associated with a particular level.
  239. unsigned FullDependence::getDirection(unsigned Level) const {
  240. assert(0 < Level && Level <= Levels && "Level out of range");
  241. return DV[Level - 1].Direction;
  242. }
  243. // Returns the distance (or NULL) associated with a particular level.
  244. const SCEV *FullDependence::getDistance(unsigned Level) const {
  245. assert(0 < Level && Level <= Levels && "Level out of range");
  246. return DV[Level - 1].Distance;
  247. }
  248. // Returns true if a particular level is scalar; that is,
  249. // if no subscript in the source or destination mention the induction
  250. // variable associated with the loop at this level.
  251. bool FullDependence::isScalar(unsigned Level) const {
  252. assert(0 < Level && Level <= Levels && "Level out of range");
  253. return DV[Level - 1].Scalar;
  254. }
  255. // Returns true if peeling the first iteration from this loop
  256. // will break this dependence.
  257. bool FullDependence::isPeelFirst(unsigned Level) const {
  258. assert(0 < Level && Level <= Levels && "Level out of range");
  259. return DV[Level - 1].PeelFirst;
  260. }
  261. // Returns true if peeling the last iteration from this loop
  262. // will break this dependence.
  263. bool FullDependence::isPeelLast(unsigned Level) const {
  264. assert(0 < Level && Level <= Levels && "Level out of range");
  265. return DV[Level - 1].PeelLast;
  266. }
  267. // Returns true if splitting this loop will break the dependence.
  268. bool FullDependence::isSplitable(unsigned Level) const {
  269. assert(0 < Level && Level <= Levels && "Level out of range");
  270. return DV[Level - 1].Splitable;
  271. }
  272. //===----------------------------------------------------------------------===//
  273. // DependenceInfo::Constraint methods
  274. // If constraint is a point <X, Y>, returns X.
  275. // Otherwise assert.
  276. const SCEV *DependenceInfo::Constraint::getX() const {
  277. assert(Kind == Point && "Kind should be Point");
  278. return A;
  279. }
  280. // If constraint is a point <X, Y>, returns Y.
  281. // Otherwise assert.
  282. const SCEV *DependenceInfo::Constraint::getY() const {
  283. assert(Kind == Point && "Kind should be Point");
  284. return B;
  285. }
  286. // If constraint is a line AX + BY = C, returns A.
  287. // Otherwise assert.
  288. const SCEV *DependenceInfo::Constraint::getA() const {
  289. assert((Kind == Line || Kind == Distance) &&
  290. "Kind should be Line (or Distance)");
  291. return A;
  292. }
  293. // If constraint is a line AX + BY = C, returns B.
  294. // Otherwise assert.
  295. const SCEV *DependenceInfo::Constraint::getB() const {
  296. assert((Kind == Line || Kind == Distance) &&
  297. "Kind should be Line (or Distance)");
  298. return B;
  299. }
  300. // If constraint is a line AX + BY = C, returns C.
  301. // Otherwise assert.
  302. const SCEV *DependenceInfo::Constraint::getC() const {
  303. assert((Kind == Line || Kind == Distance) &&
  304. "Kind should be Line (or Distance)");
  305. return C;
  306. }
  307. // If constraint is a distance, returns D.
  308. // Otherwise assert.
  309. const SCEV *DependenceInfo::Constraint::getD() const {
  310. assert(Kind == Distance && "Kind should be Distance");
  311. return SE->getNegativeSCEV(C);
  312. }
  313. // Returns the loop associated with this constraint.
  314. const Loop *DependenceInfo::Constraint::getAssociatedLoop() const {
  315. assert((Kind == Distance || Kind == Line || Kind == Point) &&
  316. "Kind should be Distance, Line, or Point");
  317. return AssociatedLoop;
  318. }
  319. void DependenceInfo::Constraint::setPoint(const SCEV *X, const SCEV *Y,
  320. const Loop *CurLoop) {
  321. Kind = Point;
  322. A = X;
  323. B = Y;
  324. AssociatedLoop = CurLoop;
  325. }
  326. void DependenceInfo::Constraint::setLine(const SCEV *AA, const SCEV *BB,
  327. const SCEV *CC, const Loop *CurLoop) {
  328. Kind = Line;
  329. A = AA;
  330. B = BB;
  331. C = CC;
  332. AssociatedLoop = CurLoop;
  333. }
  334. void DependenceInfo::Constraint::setDistance(const SCEV *D,
  335. const Loop *CurLoop) {
  336. Kind = Distance;
  337. A = SE->getOne(D->getType());
  338. B = SE->getNegativeSCEV(A);
  339. C = SE->getNegativeSCEV(D);
  340. AssociatedLoop = CurLoop;
  341. }
  342. void DependenceInfo::Constraint::setEmpty() { Kind = Empty; }
  343. void DependenceInfo::Constraint::setAny(ScalarEvolution *NewSE) {
  344. SE = NewSE;
  345. Kind = Any;
  346. }
  347. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  348. // For debugging purposes. Dumps the constraint out to OS.
  349. LLVM_DUMP_METHOD void DependenceInfo::Constraint::dump(raw_ostream &OS) const {
  350. if (isEmpty())
  351. OS << " Empty\n";
  352. else if (isAny())
  353. OS << " Any\n";
  354. else if (isPoint())
  355. OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
  356. else if (isDistance())
  357. OS << " Distance is " << *getD() <<
  358. " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
  359. else if (isLine())
  360. OS << " Line is " << *getA() << "*X + " <<
  361. *getB() << "*Y = " << *getC() << "\n";
  362. else
  363. llvm_unreachable("unknown constraint type in Constraint::dump");
  364. }
  365. #endif
  366. // Updates X with the intersection
  367. // of the Constraints X and Y. Returns true if X has changed.
  368. // Corresponds to Figure 4 from the paper
  369. //
  370. // Practical Dependence Testing
  371. // Goff, Kennedy, Tseng
  372. // PLDI 1991
  373. bool DependenceInfo::intersectConstraints(Constraint *X, const Constraint *Y) {
  374. ++DeltaApplications;
  375. LLVM_DEBUG(dbgs() << "\tintersect constraints\n");
  376. LLVM_DEBUG(dbgs() << "\t X ="; X->dump(dbgs()));
  377. LLVM_DEBUG(dbgs() << "\t Y ="; Y->dump(dbgs()));
  378. assert(!Y->isPoint() && "Y must not be a Point");
  379. if (X->isAny()) {
  380. if (Y->isAny())
  381. return false;
  382. *X = *Y;
  383. return true;
  384. }
  385. if (X->isEmpty())
  386. return false;
  387. if (Y->isEmpty()) {
  388. X->setEmpty();
  389. return true;
  390. }
  391. if (X->isDistance() && Y->isDistance()) {
  392. LLVM_DEBUG(dbgs() << "\t intersect 2 distances\n");
  393. if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
  394. return false;
  395. if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
  396. X->setEmpty();
  397. ++DeltaSuccesses;
  398. return true;
  399. }
  400. // Hmmm, interesting situation.
  401. // I guess if either is constant, keep it and ignore the other.
  402. if (isa<SCEVConstant>(Y->getD())) {
  403. *X = *Y;
  404. return true;
  405. }
  406. return false;
  407. }
  408. // At this point, the pseudo-code in Figure 4 of the paper
  409. // checks if (X->isPoint() && Y->isPoint()).
  410. // This case can't occur in our implementation,
  411. // since a Point can only arise as the result of intersecting
  412. // two Line constraints, and the right-hand value, Y, is never
  413. // the result of an intersection.
  414. assert(!(X->isPoint() && Y->isPoint()) &&
  415. "We shouldn't ever see X->isPoint() && Y->isPoint()");
  416. if (X->isLine() && Y->isLine()) {
  417. LLVM_DEBUG(dbgs() << "\t intersect 2 lines\n");
  418. const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
  419. const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
  420. if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
  421. // slopes are equal, so lines are parallel
  422. LLVM_DEBUG(dbgs() << "\t\tsame slope\n");
  423. Prod1 = SE->getMulExpr(X->getC(), Y->getB());
  424. Prod2 = SE->getMulExpr(X->getB(), Y->getC());
  425. if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
  426. return false;
  427. if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
  428. X->setEmpty();
  429. ++DeltaSuccesses;
  430. return true;
  431. }
  432. return false;
  433. }
  434. if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
  435. // slopes differ, so lines intersect
  436. LLVM_DEBUG(dbgs() << "\t\tdifferent slopes\n");
  437. const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
  438. const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
  439. const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
  440. const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
  441. const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
  442. const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
  443. const SCEVConstant *C1A2_C2A1 =
  444. dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
  445. const SCEVConstant *C1B2_C2B1 =
  446. dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
  447. const SCEVConstant *A1B2_A2B1 =
  448. dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
  449. const SCEVConstant *A2B1_A1B2 =
  450. dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
  451. if (!C1B2_C2B1 || !C1A2_C2A1 ||
  452. !A1B2_A2B1 || !A2B1_A1B2)
  453. return false;
  454. APInt Xtop = C1B2_C2B1->getAPInt();
  455. APInt Xbot = A1B2_A2B1->getAPInt();
  456. APInt Ytop = C1A2_C2A1->getAPInt();
  457. APInt Ybot = A2B1_A1B2->getAPInt();
  458. LLVM_DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
  459. LLVM_DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
  460. LLVM_DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
  461. LLVM_DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
  462. APInt Xq = Xtop; // these need to be initialized, even
  463. APInt Xr = Xtop; // though they're just going to be overwritten
  464. APInt::sdivrem(Xtop, Xbot, Xq, Xr);
  465. APInt Yq = Ytop;
  466. APInt Yr = Ytop;
  467. APInt::sdivrem(Ytop, Ybot, Yq, Yr);
  468. if (Xr != 0 || Yr != 0) {
  469. X->setEmpty();
  470. ++DeltaSuccesses;
  471. return true;
  472. }
  473. LLVM_DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
  474. if (Xq.slt(0) || Yq.slt(0)) {
  475. X->setEmpty();
  476. ++DeltaSuccesses;
  477. return true;
  478. }
  479. if (const SCEVConstant *CUB =
  480. collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
  481. const APInt &UpperBound = CUB->getAPInt();
  482. LLVM_DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
  483. if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
  484. X->setEmpty();
  485. ++DeltaSuccesses;
  486. return true;
  487. }
  488. }
  489. X->setPoint(SE->getConstant(Xq),
  490. SE->getConstant(Yq),
  491. X->getAssociatedLoop());
  492. ++DeltaSuccesses;
  493. return true;
  494. }
  495. return false;
  496. }
  497. // if (X->isLine() && Y->isPoint()) This case can't occur.
  498. assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
  499. if (X->isPoint() && Y->isLine()) {
  500. LLVM_DEBUG(dbgs() << "\t intersect Point and Line\n");
  501. const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
  502. const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
  503. const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
  504. if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
  505. return false;
  506. if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
  507. X->setEmpty();
  508. ++DeltaSuccesses;
  509. return true;
  510. }
  511. return false;
  512. }
  513. llvm_unreachable("shouldn't reach the end of Constraint intersection");
  514. return false;
  515. }
  516. //===----------------------------------------------------------------------===//
  517. // DependenceInfo methods
  518. // For debugging purposes. Dumps a dependence to OS.
  519. void Dependence::dump(raw_ostream &OS) const {
  520. bool Splitable = false;
  521. if (isConfused())
  522. OS << "confused";
  523. else {
  524. if (isConsistent())
  525. OS << "consistent ";
  526. if (isFlow())
  527. OS << "flow";
  528. else if (isOutput())
  529. OS << "output";
  530. else if (isAnti())
  531. OS << "anti";
  532. else if (isInput())
  533. OS << "input";
  534. unsigned Levels = getLevels();
  535. OS << " [";
  536. for (unsigned II = 1; II <= Levels; ++II) {
  537. if (isSplitable(II))
  538. Splitable = true;
  539. if (isPeelFirst(II))
  540. OS << 'p';
  541. const SCEV *Distance = getDistance(II);
  542. if (Distance)
  543. OS << *Distance;
  544. else if (isScalar(II))
  545. OS << "S";
  546. else {
  547. unsigned Direction = getDirection(II);
  548. if (Direction == DVEntry::ALL)
  549. OS << "*";
  550. else {
  551. if (Direction & DVEntry::LT)
  552. OS << "<";
  553. if (Direction & DVEntry::EQ)
  554. OS << "=";
  555. if (Direction & DVEntry::GT)
  556. OS << ">";
  557. }
  558. }
  559. if (isPeelLast(II))
  560. OS << 'p';
  561. if (II < Levels)
  562. OS << " ";
  563. }
  564. if (isLoopIndependent())
  565. OS << "|<";
  566. OS << "]";
  567. if (Splitable)
  568. OS << " splitable";
  569. }
  570. OS << "!\n";
  571. }
  572. // Returns NoAlias/MayAliass/MustAlias for two memory locations based upon their
  573. // underlaying objects. If LocA and LocB are known to not alias (for any reason:
  574. // tbaa, non-overlapping regions etc), then it is known there is no dependecy.
  575. // Otherwise the underlying objects are checked to see if they point to
  576. // different identifiable objects.
  577. static AliasResult underlyingObjectsAlias(AAResults *AA,
  578. const DataLayout &DL,
  579. const MemoryLocation &LocA,
  580. const MemoryLocation &LocB) {
  581. // Check the original locations (minus size) for noalias, which can happen for
  582. // tbaa, incompatible underlying object locations, etc.
  583. MemoryLocation LocAS =
  584. MemoryLocation::getBeforeOrAfter(LocA.Ptr, LocA.AATags);
  585. MemoryLocation LocBS =
  586. MemoryLocation::getBeforeOrAfter(LocB.Ptr, LocB.AATags);
  587. if (AA->isNoAlias(LocAS, LocBS))
  588. return AliasResult::NoAlias;
  589. // Check the underlying objects are the same
  590. const Value *AObj = getUnderlyingObject(LocA.Ptr);
  591. const Value *BObj = getUnderlyingObject(LocB.Ptr);
  592. // If the underlying objects are the same, they must alias
  593. if (AObj == BObj)
  594. return AliasResult::MustAlias;
  595. // We may have hit the recursion limit for underlying objects, or have
  596. // underlying objects where we don't know they will alias.
  597. if (!isIdentifiedObject(AObj) || !isIdentifiedObject(BObj))
  598. return AliasResult::MayAlias;
  599. // Otherwise we know the objects are different and both identified objects so
  600. // must not alias.
  601. return AliasResult::NoAlias;
  602. }
  603. // Returns true if the load or store can be analyzed. Atomic and volatile
  604. // operations have properties which this analysis does not understand.
  605. static
  606. bool isLoadOrStore(const Instruction *I) {
  607. if (const LoadInst *LI = dyn_cast<LoadInst>(I))
  608. return LI->isUnordered();
  609. else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
  610. return SI->isUnordered();
  611. return false;
  612. }
  613. // Examines the loop nesting of the Src and Dst
  614. // instructions and establishes their shared loops. Sets the variables
  615. // CommonLevels, SrcLevels, and MaxLevels.
  616. // The source and destination instructions needn't be contained in the same
  617. // loop. The routine establishNestingLevels finds the level of most deeply
  618. // nested loop that contains them both, CommonLevels. An instruction that's
  619. // not contained in a loop is at level = 0. MaxLevels is equal to the level
  620. // of the source plus the level of the destination, minus CommonLevels.
  621. // This lets us allocate vectors MaxLevels in length, with room for every
  622. // distinct loop referenced in both the source and destination subscripts.
  623. // The variable SrcLevels is the nesting depth of the source instruction.
  624. // It's used to help calculate distinct loops referenced by the destination.
  625. // Here's the map from loops to levels:
  626. // 0 - unused
  627. // 1 - outermost common loop
  628. // ... - other common loops
  629. // CommonLevels - innermost common loop
  630. // ... - loops containing Src but not Dst
  631. // SrcLevels - innermost loop containing Src but not Dst
  632. // ... - loops containing Dst but not Src
  633. // MaxLevels - innermost loops containing Dst but not Src
  634. // Consider the follow code fragment:
  635. // for (a = ...) {
  636. // for (b = ...) {
  637. // for (c = ...) {
  638. // for (d = ...) {
  639. // A[] = ...;
  640. // }
  641. // }
  642. // for (e = ...) {
  643. // for (f = ...) {
  644. // for (g = ...) {
  645. // ... = A[];
  646. // }
  647. // }
  648. // }
  649. // }
  650. // }
  651. // If we're looking at the possibility of a dependence between the store
  652. // to A (the Src) and the load from A (the Dst), we'll note that they
  653. // have 2 loops in common, so CommonLevels will equal 2 and the direction
  654. // vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
  655. // A map from loop names to loop numbers would look like
  656. // a - 1
  657. // b - 2 = CommonLevels
  658. // c - 3
  659. // d - 4 = SrcLevels
  660. // e - 5
  661. // f - 6
  662. // g - 7 = MaxLevels
  663. void DependenceInfo::establishNestingLevels(const Instruction *Src,
  664. const Instruction *Dst) {
  665. const BasicBlock *SrcBlock = Src->getParent();
  666. const BasicBlock *DstBlock = Dst->getParent();
  667. unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
  668. unsigned DstLevel = LI->getLoopDepth(DstBlock);
  669. const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
  670. const Loop *DstLoop = LI->getLoopFor(DstBlock);
  671. SrcLevels = SrcLevel;
  672. MaxLevels = SrcLevel + DstLevel;
  673. while (SrcLevel > DstLevel) {
  674. SrcLoop = SrcLoop->getParentLoop();
  675. SrcLevel--;
  676. }
  677. while (DstLevel > SrcLevel) {
  678. DstLoop = DstLoop->getParentLoop();
  679. DstLevel--;
  680. }
  681. while (SrcLoop != DstLoop) {
  682. SrcLoop = SrcLoop->getParentLoop();
  683. DstLoop = DstLoop->getParentLoop();
  684. SrcLevel--;
  685. }
  686. CommonLevels = SrcLevel;
  687. MaxLevels -= CommonLevels;
  688. }
  689. // Given one of the loops containing the source, return
  690. // its level index in our numbering scheme.
  691. unsigned DependenceInfo::mapSrcLoop(const Loop *SrcLoop) const {
  692. return SrcLoop->getLoopDepth();
  693. }
  694. // Given one of the loops containing the destination,
  695. // return its level index in our numbering scheme.
  696. unsigned DependenceInfo::mapDstLoop(const Loop *DstLoop) const {
  697. unsigned D = DstLoop->getLoopDepth();
  698. if (D > CommonLevels)
  699. return D - CommonLevels + SrcLevels;
  700. else
  701. return D;
  702. }
  703. // Returns true if Expression is loop invariant in LoopNest.
  704. bool DependenceInfo::isLoopInvariant(const SCEV *Expression,
  705. const Loop *LoopNest) const {
  706. if (!LoopNest)
  707. return true;
  708. return SE->isLoopInvariant(Expression, LoopNest) &&
  709. isLoopInvariant(Expression, LoopNest->getParentLoop());
  710. }
  711. // Finds the set of loops from the LoopNest that
  712. // have a level <= CommonLevels and are referred to by the SCEV Expression.
  713. void DependenceInfo::collectCommonLoops(const SCEV *Expression,
  714. const Loop *LoopNest,
  715. SmallBitVector &Loops) const {
  716. while (LoopNest) {
  717. unsigned Level = LoopNest->getLoopDepth();
  718. if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
  719. Loops.set(Level);
  720. LoopNest = LoopNest->getParentLoop();
  721. }
  722. }
  723. void DependenceInfo::unifySubscriptType(ArrayRef<Subscript *> Pairs) {
  724. unsigned widestWidthSeen = 0;
  725. Type *widestType;
  726. // Go through each pair and find the widest bit to which we need
  727. // to extend all of them.
  728. for (Subscript *Pair : Pairs) {
  729. const SCEV *Src = Pair->Src;
  730. const SCEV *Dst = Pair->Dst;
  731. IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
  732. IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
  733. if (SrcTy == nullptr || DstTy == nullptr) {
  734. assert(SrcTy == DstTy && "This function only unify integer types and "
  735. "expect Src and Dst share the same type "
  736. "otherwise.");
  737. continue;
  738. }
  739. if (SrcTy->getBitWidth() > widestWidthSeen) {
  740. widestWidthSeen = SrcTy->getBitWidth();
  741. widestType = SrcTy;
  742. }
  743. if (DstTy->getBitWidth() > widestWidthSeen) {
  744. widestWidthSeen = DstTy->getBitWidth();
  745. widestType = DstTy;
  746. }
  747. }
  748. assert(widestWidthSeen > 0);
  749. // Now extend each pair to the widest seen.
  750. for (Subscript *Pair : Pairs) {
  751. const SCEV *Src = Pair->Src;
  752. const SCEV *Dst = Pair->Dst;
  753. IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
  754. IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
  755. if (SrcTy == nullptr || DstTy == nullptr) {
  756. assert(SrcTy == DstTy && "This function only unify integer types and "
  757. "expect Src and Dst share the same type "
  758. "otherwise.");
  759. continue;
  760. }
  761. if (SrcTy->getBitWidth() < widestWidthSeen)
  762. // Sign-extend Src to widestType
  763. Pair->Src = SE->getSignExtendExpr(Src, widestType);
  764. if (DstTy->getBitWidth() < widestWidthSeen) {
  765. // Sign-extend Dst to widestType
  766. Pair->Dst = SE->getSignExtendExpr(Dst, widestType);
  767. }
  768. }
  769. }
  770. // removeMatchingExtensions - Examines a subscript pair.
  771. // If the source and destination are identically sign (or zero)
  772. // extended, it strips off the extension in an effect to simplify
  773. // the actual analysis.
  774. void DependenceInfo::removeMatchingExtensions(Subscript *Pair) {
  775. const SCEV *Src = Pair->Src;
  776. const SCEV *Dst = Pair->Dst;
  777. if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
  778. (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
  779. const SCEVIntegralCastExpr *SrcCast = cast<SCEVIntegralCastExpr>(Src);
  780. const SCEVIntegralCastExpr *DstCast = cast<SCEVIntegralCastExpr>(Dst);
  781. const SCEV *SrcCastOp = SrcCast->getOperand();
  782. const SCEV *DstCastOp = DstCast->getOperand();
  783. if (SrcCastOp->getType() == DstCastOp->getType()) {
  784. Pair->Src = SrcCastOp;
  785. Pair->Dst = DstCastOp;
  786. }
  787. }
  788. }
  789. // Examine the scev and return true iff it's linear.
  790. // Collect any loops mentioned in the set of "Loops".
  791. bool DependenceInfo::checkSubscript(const SCEV *Expr, const Loop *LoopNest,
  792. SmallBitVector &Loops, bool IsSrc) {
  793. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
  794. if (!AddRec)
  795. return isLoopInvariant(Expr, LoopNest);
  796. const SCEV *Start = AddRec->getStart();
  797. const SCEV *Step = AddRec->getStepRecurrence(*SE);
  798. const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
  799. if (!isa<SCEVCouldNotCompute>(UB)) {
  800. if (SE->getTypeSizeInBits(Start->getType()) <
  801. SE->getTypeSizeInBits(UB->getType())) {
  802. if (!AddRec->getNoWrapFlags())
  803. return false;
  804. }
  805. }
  806. if (!isLoopInvariant(Step, LoopNest))
  807. return false;
  808. if (IsSrc)
  809. Loops.set(mapSrcLoop(AddRec->getLoop()));
  810. else
  811. Loops.set(mapDstLoop(AddRec->getLoop()));
  812. return checkSubscript(Start, LoopNest, Loops, IsSrc);
  813. }
  814. // Examine the scev and return true iff it's linear.
  815. // Collect any loops mentioned in the set of "Loops".
  816. bool DependenceInfo::checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
  817. SmallBitVector &Loops) {
  818. return checkSubscript(Src, LoopNest, Loops, true);
  819. }
  820. // Examine the scev and return true iff it's linear.
  821. // Collect any loops mentioned in the set of "Loops".
  822. bool DependenceInfo::checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
  823. SmallBitVector &Loops) {
  824. return checkSubscript(Dst, LoopNest, Loops, false);
  825. }
  826. // Examines the subscript pair (the Src and Dst SCEVs)
  827. // and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
  828. // Collects the associated loops in a set.
  829. DependenceInfo::Subscript::ClassificationKind
  830. DependenceInfo::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
  831. const SCEV *Dst, const Loop *DstLoopNest,
  832. SmallBitVector &Loops) {
  833. SmallBitVector SrcLoops(MaxLevels + 1);
  834. SmallBitVector DstLoops(MaxLevels + 1);
  835. if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
  836. return Subscript::NonLinear;
  837. if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
  838. return Subscript::NonLinear;
  839. Loops = SrcLoops;
  840. Loops |= DstLoops;
  841. unsigned N = Loops.count();
  842. if (N == 0)
  843. return Subscript::ZIV;
  844. if (N == 1)
  845. return Subscript::SIV;
  846. if (N == 2 && (SrcLoops.count() == 0 ||
  847. DstLoops.count() == 0 ||
  848. (SrcLoops.count() == 1 && DstLoops.count() == 1)))
  849. return Subscript::RDIV;
  850. return Subscript::MIV;
  851. }
  852. // A wrapper around SCEV::isKnownPredicate.
  853. // Looks for cases where we're interested in comparing for equality.
  854. // If both X and Y have been identically sign or zero extended,
  855. // it strips off the (confusing) extensions before invoking
  856. // SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
  857. // will be similarly updated.
  858. //
  859. // If SCEV::isKnownPredicate can't prove the predicate,
  860. // we try simple subtraction, which seems to help in some cases
  861. // involving symbolics.
  862. bool DependenceInfo::isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *X,
  863. const SCEV *Y) const {
  864. if (Pred == CmpInst::ICMP_EQ ||
  865. Pred == CmpInst::ICMP_NE) {
  866. if ((isa<SCEVSignExtendExpr>(X) &&
  867. isa<SCEVSignExtendExpr>(Y)) ||
  868. (isa<SCEVZeroExtendExpr>(X) &&
  869. isa<SCEVZeroExtendExpr>(Y))) {
  870. const SCEVIntegralCastExpr *CX = cast<SCEVIntegralCastExpr>(X);
  871. const SCEVIntegralCastExpr *CY = cast<SCEVIntegralCastExpr>(Y);
  872. const SCEV *Xop = CX->getOperand();
  873. const SCEV *Yop = CY->getOperand();
  874. if (Xop->getType() == Yop->getType()) {
  875. X = Xop;
  876. Y = Yop;
  877. }
  878. }
  879. }
  880. if (SE->isKnownPredicate(Pred, X, Y))
  881. return true;
  882. // If SE->isKnownPredicate can't prove the condition,
  883. // we try the brute-force approach of subtracting
  884. // and testing the difference.
  885. // By testing with SE->isKnownPredicate first, we avoid
  886. // the possibility of overflow when the arguments are constants.
  887. const SCEV *Delta = SE->getMinusSCEV(X, Y);
  888. switch (Pred) {
  889. case CmpInst::ICMP_EQ:
  890. return Delta->isZero();
  891. case CmpInst::ICMP_NE:
  892. return SE->isKnownNonZero(Delta);
  893. case CmpInst::ICMP_SGE:
  894. return SE->isKnownNonNegative(Delta);
  895. case CmpInst::ICMP_SLE:
  896. return SE->isKnownNonPositive(Delta);
  897. case CmpInst::ICMP_SGT:
  898. return SE->isKnownPositive(Delta);
  899. case CmpInst::ICMP_SLT:
  900. return SE->isKnownNegative(Delta);
  901. default:
  902. llvm_unreachable("unexpected predicate in isKnownPredicate");
  903. }
  904. }
  905. /// Compare to see if S is less than Size, using isKnownNegative(S - max(Size, 1))
  906. /// with some extra checking if S is an AddRec and we can prove less-than using
  907. /// the loop bounds.
  908. bool DependenceInfo::isKnownLessThan(const SCEV *S, const SCEV *Size) const {
  909. // First unify to the same type
  910. auto *SType = dyn_cast<IntegerType>(S->getType());
  911. auto *SizeType = dyn_cast<IntegerType>(Size->getType());
  912. if (!SType || !SizeType)
  913. return false;
  914. Type *MaxType =
  915. (SType->getBitWidth() >= SizeType->getBitWidth()) ? SType : SizeType;
  916. S = SE->getTruncateOrZeroExtend(S, MaxType);
  917. Size = SE->getTruncateOrZeroExtend(Size, MaxType);
  918. // Special check for addrecs using BE taken count
  919. const SCEV *Bound = SE->getMinusSCEV(S, Size);
  920. if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Bound)) {
  921. if (AddRec->isAffine()) {
  922. const SCEV *BECount = SE->getBackedgeTakenCount(AddRec->getLoop());
  923. if (!isa<SCEVCouldNotCompute>(BECount)) {
  924. const SCEV *Limit = AddRec->evaluateAtIteration(BECount, *SE);
  925. if (SE->isKnownNegative(Limit))
  926. return true;
  927. }
  928. }
  929. }
  930. // Check using normal isKnownNegative
  931. const SCEV *LimitedBound =
  932. SE->getMinusSCEV(S, SE->getSMaxExpr(Size, SE->getOne(Size->getType())));
  933. return SE->isKnownNegative(LimitedBound);
  934. }
  935. bool DependenceInfo::isKnownNonNegative(const SCEV *S, const Value *Ptr) const {
  936. bool Inbounds = false;
  937. if (auto *SrcGEP = dyn_cast<GetElementPtrInst>(Ptr))
  938. Inbounds = SrcGEP->isInBounds();
  939. if (Inbounds) {
  940. if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
  941. if (AddRec->isAffine()) {
  942. // We know S is for Ptr, the operand on a load/store, so doesn't wrap.
  943. // If both parts are NonNegative, the end result will be NonNegative
  944. if (SE->isKnownNonNegative(AddRec->getStart()) &&
  945. SE->isKnownNonNegative(AddRec->getOperand(1)))
  946. return true;
  947. }
  948. }
  949. }
  950. return SE->isKnownNonNegative(S);
  951. }
  952. // All subscripts are all the same type.
  953. // Loop bound may be smaller (e.g., a char).
  954. // Should zero extend loop bound, since it's always >= 0.
  955. // This routine collects upper bound and extends or truncates if needed.
  956. // Truncating is safe when subscripts are known not to wrap. Cases without
  957. // nowrap flags should have been rejected earlier.
  958. // Return null if no bound available.
  959. const SCEV *DependenceInfo::collectUpperBound(const Loop *L, Type *T) const {
  960. if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
  961. const SCEV *UB = SE->getBackedgeTakenCount(L);
  962. return SE->getTruncateOrZeroExtend(UB, T);
  963. }
  964. return nullptr;
  965. }
  966. // Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
  967. // If the cast fails, returns NULL.
  968. const SCEVConstant *DependenceInfo::collectConstantUpperBound(const Loop *L,
  969. Type *T) const {
  970. if (const SCEV *UB = collectUpperBound(L, T))
  971. return dyn_cast<SCEVConstant>(UB);
  972. return nullptr;
  973. }
  974. // testZIV -
  975. // When we have a pair of subscripts of the form [c1] and [c2],
  976. // where c1 and c2 are both loop invariant, we attack it using
  977. // the ZIV test. Basically, we test by comparing the two values,
  978. // but there are actually three possible results:
  979. // 1) the values are equal, so there's a dependence
  980. // 2) the values are different, so there's no dependence
  981. // 3) the values might be equal, so we have to assume a dependence.
  982. //
  983. // Return true if dependence disproved.
  984. bool DependenceInfo::testZIV(const SCEV *Src, const SCEV *Dst,
  985. FullDependence &Result) const {
  986. LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
  987. LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
  988. ++ZIVapplications;
  989. if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
  990. LLVM_DEBUG(dbgs() << " provably dependent\n");
  991. return false; // provably dependent
  992. }
  993. if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
  994. LLVM_DEBUG(dbgs() << " provably independent\n");
  995. ++ZIVindependence;
  996. return true; // provably independent
  997. }
  998. LLVM_DEBUG(dbgs() << " possibly dependent\n");
  999. Result.Consistent = false;
  1000. return false; // possibly dependent
  1001. }
  1002. // strongSIVtest -
  1003. // From the paper, Practical Dependence Testing, Section 4.2.1
  1004. //
  1005. // When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
  1006. // where i is an induction variable, c1 and c2 are loop invariant,
  1007. // and a is a constant, we can solve it exactly using the Strong SIV test.
  1008. //
  1009. // Can prove independence. Failing that, can compute distance (and direction).
  1010. // In the presence of symbolic terms, we can sometimes make progress.
  1011. //
  1012. // If there's a dependence,
  1013. //
  1014. // c1 + a*i = c2 + a*i'
  1015. //
  1016. // The dependence distance is
  1017. //
  1018. // d = i' - i = (c1 - c2)/a
  1019. //
  1020. // A dependence only exists if d is an integer and abs(d) <= U, where U is the
  1021. // loop's upper bound. If a dependence exists, the dependence direction is
  1022. // defined as
  1023. //
  1024. // { < if d > 0
  1025. // direction = { = if d = 0
  1026. // { > if d < 0
  1027. //
  1028. // Return true if dependence disproved.
  1029. bool DependenceInfo::strongSIVtest(const SCEV *Coeff, const SCEV *SrcConst,
  1030. const SCEV *DstConst, const Loop *CurLoop,
  1031. unsigned Level, FullDependence &Result,
  1032. Constraint &NewConstraint) const {
  1033. LLVM_DEBUG(dbgs() << "\tStrong SIV test\n");
  1034. LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff);
  1035. LLVM_DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
  1036. LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
  1037. LLVM_DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
  1038. LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst);
  1039. LLVM_DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
  1040. ++StrongSIVapplications;
  1041. assert(0 < Level && Level <= CommonLevels && "level out of range");
  1042. Level--;
  1043. const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
  1044. LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta);
  1045. LLVM_DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
  1046. // check that |Delta| < iteration count
  1047. if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
  1048. LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound);
  1049. LLVM_DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
  1050. const SCEV *AbsDelta =
  1051. SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
  1052. const SCEV *AbsCoeff =
  1053. SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
  1054. const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
  1055. if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
  1056. // Distance greater than trip count - no dependence
  1057. ++StrongSIVindependence;
  1058. ++StrongSIVsuccesses;
  1059. return true;
  1060. }
  1061. }
  1062. // Can we compute distance?
  1063. if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
  1064. APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
  1065. APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
  1066. APInt Distance = ConstDelta; // these need to be initialized
  1067. APInt Remainder = ConstDelta;
  1068. APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
  1069. LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
  1070. LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
  1071. // Make sure Coeff divides Delta exactly
  1072. if (Remainder != 0) {
  1073. // Coeff doesn't divide Distance, no dependence
  1074. ++StrongSIVindependence;
  1075. ++StrongSIVsuccesses;
  1076. return true;
  1077. }
  1078. Result.DV[Level].Distance = SE->getConstant(Distance);
  1079. NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
  1080. if (Distance.sgt(0))
  1081. Result.DV[Level].Direction &= Dependence::DVEntry::LT;
  1082. else if (Distance.slt(0))
  1083. Result.DV[Level].Direction &= Dependence::DVEntry::GT;
  1084. else
  1085. Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
  1086. ++StrongSIVsuccesses;
  1087. }
  1088. else if (Delta->isZero()) {
  1089. // since 0/X == 0
  1090. Result.DV[Level].Distance = Delta;
  1091. NewConstraint.setDistance(Delta, CurLoop);
  1092. Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
  1093. ++StrongSIVsuccesses;
  1094. }
  1095. else {
  1096. if (Coeff->isOne()) {
  1097. LLVM_DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
  1098. Result.DV[Level].Distance = Delta; // since X/1 == X
  1099. NewConstraint.setDistance(Delta, CurLoop);
  1100. }
  1101. else {
  1102. Result.Consistent = false;
  1103. NewConstraint.setLine(Coeff,
  1104. SE->getNegativeSCEV(Coeff),
  1105. SE->getNegativeSCEV(Delta), CurLoop);
  1106. }
  1107. // maybe we can get a useful direction
  1108. bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
  1109. bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
  1110. bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
  1111. bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
  1112. bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
  1113. // The double negatives above are confusing.
  1114. // It helps to read !SE->isKnownNonZero(Delta)
  1115. // as "Delta might be Zero"
  1116. unsigned NewDirection = Dependence::DVEntry::NONE;
  1117. if ((DeltaMaybePositive && CoeffMaybePositive) ||
  1118. (DeltaMaybeNegative && CoeffMaybeNegative))
  1119. NewDirection = Dependence::DVEntry::LT;
  1120. if (DeltaMaybeZero)
  1121. NewDirection |= Dependence::DVEntry::EQ;
  1122. if ((DeltaMaybeNegative && CoeffMaybePositive) ||
  1123. (DeltaMaybePositive && CoeffMaybeNegative))
  1124. NewDirection |= Dependence::DVEntry::GT;
  1125. if (NewDirection < Result.DV[Level].Direction)
  1126. ++StrongSIVsuccesses;
  1127. Result.DV[Level].Direction &= NewDirection;
  1128. }
  1129. return false;
  1130. }
  1131. // weakCrossingSIVtest -
  1132. // From the paper, Practical Dependence Testing, Section 4.2.2
  1133. //
  1134. // When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
  1135. // where i is an induction variable, c1 and c2 are loop invariant,
  1136. // and a is a constant, we can solve it exactly using the
  1137. // Weak-Crossing SIV test.
  1138. //
  1139. // Given c1 + a*i = c2 - a*i', we can look for the intersection of
  1140. // the two lines, where i = i', yielding
  1141. //
  1142. // c1 + a*i = c2 - a*i
  1143. // 2a*i = c2 - c1
  1144. // i = (c2 - c1)/2a
  1145. //
  1146. // If i < 0, there is no dependence.
  1147. // If i > upperbound, there is no dependence.
  1148. // If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
  1149. // If i = upperbound, there's a dependence with distance = 0.
  1150. // If i is integral, there's a dependence (all directions).
  1151. // If the non-integer part = 1/2, there's a dependence (<> directions).
  1152. // Otherwise, there's no dependence.
  1153. //
  1154. // Can prove independence. Failing that,
  1155. // can sometimes refine the directions.
  1156. // Can determine iteration for splitting.
  1157. //
  1158. // Return true if dependence disproved.
  1159. bool DependenceInfo::weakCrossingSIVtest(
  1160. const SCEV *Coeff, const SCEV *SrcConst, const SCEV *DstConst,
  1161. const Loop *CurLoop, unsigned Level, FullDependence &Result,
  1162. Constraint &NewConstraint, const SCEV *&SplitIter) const {
  1163. LLVM_DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
  1164. LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
  1165. LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
  1166. LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
  1167. ++WeakCrossingSIVapplications;
  1168. assert(0 < Level && Level <= CommonLevels && "Level out of range");
  1169. Level--;
  1170. Result.Consistent = false;
  1171. const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
  1172. LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
  1173. NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
  1174. if (Delta->isZero()) {
  1175. Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
  1176. Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
  1177. ++WeakCrossingSIVsuccesses;
  1178. if (!Result.DV[Level].Direction) {
  1179. ++WeakCrossingSIVindependence;
  1180. return true;
  1181. }
  1182. Result.DV[Level].Distance = Delta; // = 0
  1183. return false;
  1184. }
  1185. const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
  1186. if (!ConstCoeff)
  1187. return false;
  1188. Result.DV[Level].Splitable = true;
  1189. if (SE->isKnownNegative(ConstCoeff)) {
  1190. ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
  1191. assert(ConstCoeff &&
  1192. "dynamic cast of negative of ConstCoeff should yield constant");
  1193. Delta = SE->getNegativeSCEV(Delta);
  1194. }
  1195. assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
  1196. // compute SplitIter for use by DependenceInfo::getSplitIteration()
  1197. SplitIter = SE->getUDivExpr(
  1198. SE->getSMaxExpr(SE->getZero(Delta->getType()), Delta),
  1199. SE->getMulExpr(SE->getConstant(Delta->getType(), 2), ConstCoeff));
  1200. LLVM_DEBUG(dbgs() << "\t Split iter = " << *SplitIter << "\n");
  1201. const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
  1202. if (!ConstDelta)
  1203. return false;
  1204. // We're certain that ConstCoeff > 0; therefore,
  1205. // if Delta < 0, then no dependence.
  1206. LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
  1207. LLVM_DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n");
  1208. if (SE->isKnownNegative(Delta)) {
  1209. // No dependence, Delta < 0
  1210. ++WeakCrossingSIVindependence;
  1211. ++WeakCrossingSIVsuccesses;
  1212. return true;
  1213. }
  1214. // We're certain that Delta > 0 and ConstCoeff > 0.
  1215. // Check Delta/(2*ConstCoeff) against upper loop bound
  1216. if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
  1217. LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
  1218. const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
  1219. const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
  1220. ConstantTwo);
  1221. LLVM_DEBUG(dbgs() << "\t ML = " << *ML << "\n");
  1222. if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
  1223. // Delta too big, no dependence
  1224. ++WeakCrossingSIVindependence;
  1225. ++WeakCrossingSIVsuccesses;
  1226. return true;
  1227. }
  1228. if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
  1229. // i = i' = UB
  1230. Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
  1231. Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
  1232. ++WeakCrossingSIVsuccesses;
  1233. if (!Result.DV[Level].Direction) {
  1234. ++WeakCrossingSIVindependence;
  1235. return true;
  1236. }
  1237. Result.DV[Level].Splitable = false;
  1238. Result.DV[Level].Distance = SE->getZero(Delta->getType());
  1239. return false;
  1240. }
  1241. }
  1242. // check that Coeff divides Delta
  1243. APInt APDelta = ConstDelta->getAPInt();
  1244. APInt APCoeff = ConstCoeff->getAPInt();
  1245. APInt Distance = APDelta; // these need to be initialzed
  1246. APInt Remainder = APDelta;
  1247. APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
  1248. LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
  1249. if (Remainder != 0) {
  1250. // Coeff doesn't divide Delta, no dependence
  1251. ++WeakCrossingSIVindependence;
  1252. ++WeakCrossingSIVsuccesses;
  1253. return true;
  1254. }
  1255. LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
  1256. // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
  1257. APInt Two = APInt(Distance.getBitWidth(), 2, true);
  1258. Remainder = Distance.srem(Two);
  1259. LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
  1260. if (Remainder != 0) {
  1261. // Equal direction isn't possible
  1262. Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
  1263. ++WeakCrossingSIVsuccesses;
  1264. }
  1265. return false;
  1266. }
  1267. // Kirch's algorithm, from
  1268. //
  1269. // Optimizing Supercompilers for Supercomputers
  1270. // Michael Wolfe
  1271. // MIT Press, 1989
  1272. //
  1273. // Program 2.1, page 29.
  1274. // Computes the GCD of AM and BM.
  1275. // Also finds a solution to the equation ax - by = gcd(a, b).
  1276. // Returns true if dependence disproved; i.e., gcd does not divide Delta.
  1277. static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM,
  1278. const APInt &Delta, APInt &G, APInt &X, APInt &Y) {
  1279. APInt A0(Bits, 1, true), A1(Bits, 0, true);
  1280. APInt B0(Bits, 0, true), B1(Bits, 1, true);
  1281. APInt G0 = AM.abs();
  1282. APInt G1 = BM.abs();
  1283. APInt Q = G0; // these need to be initialized
  1284. APInt R = G0;
  1285. APInt::sdivrem(G0, G1, Q, R);
  1286. while (R != 0) {
  1287. APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
  1288. APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
  1289. G0 = G1; G1 = R;
  1290. APInt::sdivrem(G0, G1, Q, R);
  1291. }
  1292. G = G1;
  1293. LLVM_DEBUG(dbgs() << "\t GCD = " << G << "\n");
  1294. X = AM.slt(0) ? -A1 : A1;
  1295. Y = BM.slt(0) ? B1 : -B1;
  1296. // make sure gcd divides Delta
  1297. R = Delta.srem(G);
  1298. if (R != 0)
  1299. return true; // gcd doesn't divide Delta, no dependence
  1300. Q = Delta.sdiv(G);
  1301. return false;
  1302. }
  1303. static APInt floorOfQuotient(const APInt &A, const APInt &B) {
  1304. APInt Q = A; // these need to be initialized
  1305. APInt R = A;
  1306. APInt::sdivrem(A, B, Q, R);
  1307. if (R == 0)
  1308. return Q;
  1309. if ((A.sgt(0) && B.sgt(0)) ||
  1310. (A.slt(0) && B.slt(0)))
  1311. return Q;
  1312. else
  1313. return Q - 1;
  1314. }
  1315. static APInt ceilingOfQuotient(const APInt &A, const APInt &B) {
  1316. APInt Q = A; // these need to be initialized
  1317. APInt R = A;
  1318. APInt::sdivrem(A, B, Q, R);
  1319. if (R == 0)
  1320. return Q;
  1321. if ((A.sgt(0) && B.sgt(0)) ||
  1322. (A.slt(0) && B.slt(0)))
  1323. return Q + 1;
  1324. else
  1325. return Q;
  1326. }
  1327. // exactSIVtest -
  1328. // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
  1329. // where i is an induction variable, c1 and c2 are loop invariant, and a1
  1330. // and a2 are constant, we can solve it exactly using an algorithm developed
  1331. // by Banerjee and Wolfe. See Algorithm 6.2.1 (case 2.5) in:
  1332. //
  1333. // Dependence Analysis for Supercomputing
  1334. // Utpal Banerjee
  1335. // Kluwer Academic Publishers, 1988
  1336. //
  1337. // It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
  1338. // so use them if possible. They're also a bit better with symbolics and,
  1339. // in the case of the strong SIV test, can compute Distances.
  1340. //
  1341. // Return true if dependence disproved.
  1342. //
  1343. // This is a modified version of the original Banerjee algorithm. The original
  1344. // only tested whether Dst depends on Src. This algorithm extends that and
  1345. // returns all the dependencies that exist between Dst and Src.
  1346. bool DependenceInfo::exactSIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
  1347. const SCEV *SrcConst, const SCEV *DstConst,
  1348. const Loop *CurLoop, unsigned Level,
  1349. FullDependence &Result,
  1350. Constraint &NewConstraint) const {
  1351. LLVM_DEBUG(dbgs() << "\tExact SIV test\n");
  1352. LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
  1353. LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
  1354. LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
  1355. LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
  1356. ++ExactSIVapplications;
  1357. assert(0 < Level && Level <= CommonLevels && "Level out of range");
  1358. Level--;
  1359. Result.Consistent = false;
  1360. const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
  1361. LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
  1362. NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff), Delta,
  1363. CurLoop);
  1364. const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
  1365. const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
  1366. const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
  1367. if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
  1368. return false;
  1369. // find gcd
  1370. APInt G, X, Y;
  1371. APInt AM = ConstSrcCoeff->getAPInt();
  1372. APInt BM = ConstDstCoeff->getAPInt();
  1373. APInt CM = ConstDelta->getAPInt();
  1374. unsigned Bits = AM.getBitWidth();
  1375. if (findGCD(Bits, AM, BM, CM, G, X, Y)) {
  1376. // gcd doesn't divide Delta, no dependence
  1377. ++ExactSIVindependence;
  1378. ++ExactSIVsuccesses;
  1379. return true;
  1380. }
  1381. LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
  1382. // since SCEV construction normalizes, LM = 0
  1383. APInt UM(Bits, 1, true);
  1384. bool UMValid = false;
  1385. // UM is perhaps unavailable, let's check
  1386. if (const SCEVConstant *CUB =
  1387. collectConstantUpperBound(CurLoop, Delta->getType())) {
  1388. UM = CUB->getAPInt();
  1389. LLVM_DEBUG(dbgs() << "\t UM = " << UM << "\n");
  1390. UMValid = true;
  1391. }
  1392. APInt TU(APInt::getSignedMaxValue(Bits));
  1393. APInt TL(APInt::getSignedMinValue(Bits));
  1394. APInt TC = CM.sdiv(G);
  1395. APInt TX = X * TC;
  1396. APInt TY = Y * TC;
  1397. LLVM_DEBUG(dbgs() << "\t TC = " << TC << "\n");
  1398. LLVM_DEBUG(dbgs() << "\t TX = " << TX << "\n");
  1399. LLVM_DEBUG(dbgs() << "\t TY = " << TY << "\n");
  1400. SmallVector<APInt, 2> TLVec, TUVec;
  1401. APInt TB = BM.sdiv(G);
  1402. if (TB.sgt(0)) {
  1403. TLVec.push_back(ceilingOfQuotient(-TX, TB));
  1404. LLVM_DEBUG(dbgs() << "\t Possible TL = " << TLVec.back() << "\n");
  1405. // New bound check - modification to Banerjee's e3 check
  1406. if (UMValid) {
  1407. TUVec.push_back(floorOfQuotient(UM - TX, TB));
  1408. LLVM_DEBUG(dbgs() << "\t Possible TU = " << TUVec.back() << "\n");
  1409. }
  1410. } else {
  1411. TUVec.push_back(floorOfQuotient(-TX, TB));
  1412. LLVM_DEBUG(dbgs() << "\t Possible TU = " << TUVec.back() << "\n");
  1413. // New bound check - modification to Banerjee's e3 check
  1414. if (UMValid) {
  1415. TLVec.push_back(ceilingOfQuotient(UM - TX, TB));
  1416. LLVM_DEBUG(dbgs() << "\t Possible TL = " << TLVec.back() << "\n");
  1417. }
  1418. }
  1419. APInt TA = AM.sdiv(G);
  1420. if (TA.sgt(0)) {
  1421. if (UMValid) {
  1422. TUVec.push_back(floorOfQuotient(UM - TY, TA));
  1423. LLVM_DEBUG(dbgs() << "\t Possible TU = " << TUVec.back() << "\n");
  1424. }
  1425. // New bound check - modification to Banerjee's e3 check
  1426. TLVec.push_back(ceilingOfQuotient(-TY, TA));
  1427. LLVM_DEBUG(dbgs() << "\t Possible TL = " << TLVec.back() << "\n");
  1428. } else {
  1429. if (UMValid) {
  1430. TLVec.push_back(ceilingOfQuotient(UM - TY, TA));
  1431. LLVM_DEBUG(dbgs() << "\t Possible TL = " << TLVec.back() << "\n");
  1432. }
  1433. // New bound check - modification to Banerjee's e3 check
  1434. TUVec.push_back(floorOfQuotient(-TY, TA));
  1435. LLVM_DEBUG(dbgs() << "\t Possible TU = " << TUVec.back() << "\n");
  1436. }
  1437. LLVM_DEBUG(dbgs() << "\t TA = " << TA << "\n");
  1438. LLVM_DEBUG(dbgs() << "\t TB = " << TB << "\n");
  1439. if (TLVec.empty() || TUVec.empty())
  1440. return false;
  1441. TL = APIntOps::smax(TLVec.front(), TLVec.back());
  1442. TU = APIntOps::smin(TUVec.front(), TUVec.back());
  1443. LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
  1444. LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
  1445. if (TL.sgt(TU)) {
  1446. ++ExactSIVindependence;
  1447. ++ExactSIVsuccesses;
  1448. return true;
  1449. }
  1450. // explore directions
  1451. unsigned NewDirection = Dependence::DVEntry::NONE;
  1452. APInt LowerDistance, UpperDistance;
  1453. if (TA.sgt(TB)) {
  1454. LowerDistance = (TY - TX) + (TA - TB) * TL;
  1455. UpperDistance = (TY - TX) + (TA - TB) * TU;
  1456. } else {
  1457. LowerDistance = (TY - TX) + (TA - TB) * TU;
  1458. UpperDistance = (TY - TX) + (TA - TB) * TL;
  1459. }
  1460. LLVM_DEBUG(dbgs() << "\t LowerDistance = " << LowerDistance << "\n");
  1461. LLVM_DEBUG(dbgs() << "\t UpperDistance = " << UpperDistance << "\n");
  1462. APInt Zero(Bits, 0, true);
  1463. if (LowerDistance.sle(Zero) && UpperDistance.sge(Zero)) {
  1464. NewDirection |= Dependence::DVEntry::EQ;
  1465. ++ExactSIVsuccesses;
  1466. }
  1467. if (LowerDistance.slt(0)) {
  1468. NewDirection |= Dependence::DVEntry::GT;
  1469. ++ExactSIVsuccesses;
  1470. }
  1471. if (UpperDistance.sgt(0)) {
  1472. NewDirection |= Dependence::DVEntry::LT;
  1473. ++ExactSIVsuccesses;
  1474. }
  1475. // finished
  1476. Result.DV[Level].Direction &= NewDirection;
  1477. if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
  1478. ++ExactSIVindependence;
  1479. LLVM_DEBUG(dbgs() << "\t Result = ");
  1480. LLVM_DEBUG(Result.dump(dbgs()));
  1481. return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
  1482. }
  1483. // Return true if the divisor evenly divides the dividend.
  1484. static
  1485. bool isRemainderZero(const SCEVConstant *Dividend,
  1486. const SCEVConstant *Divisor) {
  1487. const APInt &ConstDividend = Dividend->getAPInt();
  1488. const APInt &ConstDivisor = Divisor->getAPInt();
  1489. return ConstDividend.srem(ConstDivisor) == 0;
  1490. }
  1491. // weakZeroSrcSIVtest -
  1492. // From the paper, Practical Dependence Testing, Section 4.2.2
  1493. //
  1494. // When we have a pair of subscripts of the form [c1] and [c2 + a*i],
  1495. // where i is an induction variable, c1 and c2 are loop invariant,
  1496. // and a is a constant, we can solve it exactly using the
  1497. // Weak-Zero SIV test.
  1498. //
  1499. // Given
  1500. //
  1501. // c1 = c2 + a*i
  1502. //
  1503. // we get
  1504. //
  1505. // (c1 - c2)/a = i
  1506. //
  1507. // If i is not an integer, there's no dependence.
  1508. // If i < 0 or > UB, there's no dependence.
  1509. // If i = 0, the direction is >= and peeling the
  1510. // 1st iteration will break the dependence.
  1511. // If i = UB, the direction is <= and peeling the
  1512. // last iteration will break the dependence.
  1513. // Otherwise, the direction is *.
  1514. //
  1515. // Can prove independence. Failing that, we can sometimes refine
  1516. // the directions. Can sometimes show that first or last
  1517. // iteration carries all the dependences (so worth peeling).
  1518. //
  1519. // (see also weakZeroDstSIVtest)
  1520. //
  1521. // Return true if dependence disproved.
  1522. bool DependenceInfo::weakZeroSrcSIVtest(const SCEV *DstCoeff,
  1523. const SCEV *SrcConst,
  1524. const SCEV *DstConst,
  1525. const Loop *CurLoop, unsigned Level,
  1526. FullDependence &Result,
  1527. Constraint &NewConstraint) const {
  1528. // For the WeakSIV test, it's possible the loop isn't common to
  1529. // the Src and Dst loops. If it isn't, then there's no need to
  1530. // record a direction.
  1531. LLVM_DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
  1532. LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
  1533. LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
  1534. LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
  1535. ++WeakZeroSIVapplications;
  1536. assert(0 < Level && Level <= MaxLevels && "Level out of range");
  1537. Level--;
  1538. Result.Consistent = false;
  1539. const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
  1540. NewConstraint.setLine(SE->getZero(Delta->getType()), DstCoeff, Delta,
  1541. CurLoop);
  1542. LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
  1543. if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
  1544. if (Level < CommonLevels) {
  1545. Result.DV[Level].Direction &= Dependence::DVEntry::GE;
  1546. Result.DV[Level].PeelFirst = true;
  1547. ++WeakZeroSIVsuccesses;
  1548. }
  1549. return false; // dependences caused by first iteration
  1550. }
  1551. const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
  1552. if (!ConstCoeff)
  1553. return false;
  1554. const SCEV *AbsCoeff =
  1555. SE->isKnownNegative(ConstCoeff) ?
  1556. SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
  1557. const SCEV *NewDelta =
  1558. SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
  1559. // check that Delta/SrcCoeff < iteration count
  1560. // really check NewDelta < count*AbsCoeff
  1561. if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
  1562. LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
  1563. const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
  1564. if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
  1565. ++WeakZeroSIVindependence;
  1566. ++WeakZeroSIVsuccesses;
  1567. return true;
  1568. }
  1569. if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
  1570. // dependences caused by last iteration
  1571. if (Level < CommonLevels) {
  1572. Result.DV[Level].Direction &= Dependence::DVEntry::LE;
  1573. Result.DV[Level].PeelLast = true;
  1574. ++WeakZeroSIVsuccesses;
  1575. }
  1576. return false;
  1577. }
  1578. }
  1579. // check that Delta/SrcCoeff >= 0
  1580. // really check that NewDelta >= 0
  1581. if (SE->isKnownNegative(NewDelta)) {
  1582. // No dependence, newDelta < 0
  1583. ++WeakZeroSIVindependence;
  1584. ++WeakZeroSIVsuccesses;
  1585. return true;
  1586. }
  1587. // if SrcCoeff doesn't divide Delta, then no dependence
  1588. if (isa<SCEVConstant>(Delta) &&
  1589. !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
  1590. ++WeakZeroSIVindependence;
  1591. ++WeakZeroSIVsuccesses;
  1592. return true;
  1593. }
  1594. return false;
  1595. }
  1596. // weakZeroDstSIVtest -
  1597. // From the paper, Practical Dependence Testing, Section 4.2.2
  1598. //
  1599. // When we have a pair of subscripts of the form [c1 + a*i] and [c2],
  1600. // where i is an induction variable, c1 and c2 are loop invariant,
  1601. // and a is a constant, we can solve it exactly using the
  1602. // Weak-Zero SIV test.
  1603. //
  1604. // Given
  1605. //
  1606. // c1 + a*i = c2
  1607. //
  1608. // we get
  1609. //
  1610. // i = (c2 - c1)/a
  1611. //
  1612. // If i is not an integer, there's no dependence.
  1613. // If i < 0 or > UB, there's no dependence.
  1614. // If i = 0, the direction is <= and peeling the
  1615. // 1st iteration will break the dependence.
  1616. // If i = UB, the direction is >= and peeling the
  1617. // last iteration will break the dependence.
  1618. // Otherwise, the direction is *.
  1619. //
  1620. // Can prove independence. Failing that, we can sometimes refine
  1621. // the directions. Can sometimes show that first or last
  1622. // iteration carries all the dependences (so worth peeling).
  1623. //
  1624. // (see also weakZeroSrcSIVtest)
  1625. //
  1626. // Return true if dependence disproved.
  1627. bool DependenceInfo::weakZeroDstSIVtest(const SCEV *SrcCoeff,
  1628. const SCEV *SrcConst,
  1629. const SCEV *DstConst,
  1630. const Loop *CurLoop, unsigned Level,
  1631. FullDependence &Result,
  1632. Constraint &NewConstraint) const {
  1633. // For the WeakSIV test, it's possible the loop isn't common to the
  1634. // Src and Dst loops. If it isn't, then there's no need to record a direction.
  1635. LLVM_DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
  1636. LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
  1637. LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
  1638. LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
  1639. ++WeakZeroSIVapplications;
  1640. assert(0 < Level && Level <= SrcLevels && "Level out of range");
  1641. Level--;
  1642. Result.Consistent = false;
  1643. const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
  1644. NewConstraint.setLine(SrcCoeff, SE->getZero(Delta->getType()), Delta,
  1645. CurLoop);
  1646. LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
  1647. if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
  1648. if (Level < CommonLevels) {
  1649. Result.DV[Level].Direction &= Dependence::DVEntry::LE;
  1650. Result.DV[Level].PeelFirst = true;
  1651. ++WeakZeroSIVsuccesses;
  1652. }
  1653. return false; // dependences caused by first iteration
  1654. }
  1655. const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
  1656. if (!ConstCoeff)
  1657. return false;
  1658. const SCEV *AbsCoeff =
  1659. SE->isKnownNegative(ConstCoeff) ?
  1660. SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
  1661. const SCEV *NewDelta =
  1662. SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
  1663. // check that Delta/SrcCoeff < iteration count
  1664. // really check NewDelta < count*AbsCoeff
  1665. if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
  1666. LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
  1667. const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
  1668. if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
  1669. ++WeakZeroSIVindependence;
  1670. ++WeakZeroSIVsuccesses;
  1671. return true;
  1672. }
  1673. if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
  1674. // dependences caused by last iteration
  1675. if (Level < CommonLevels) {
  1676. Result.DV[Level].Direction &= Dependence::DVEntry::GE;
  1677. Result.DV[Level].PeelLast = true;
  1678. ++WeakZeroSIVsuccesses;
  1679. }
  1680. return false;
  1681. }
  1682. }
  1683. // check that Delta/SrcCoeff >= 0
  1684. // really check that NewDelta >= 0
  1685. if (SE->isKnownNegative(NewDelta)) {
  1686. // No dependence, newDelta < 0
  1687. ++WeakZeroSIVindependence;
  1688. ++WeakZeroSIVsuccesses;
  1689. return true;
  1690. }
  1691. // if SrcCoeff doesn't divide Delta, then no dependence
  1692. if (isa<SCEVConstant>(Delta) &&
  1693. !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
  1694. ++WeakZeroSIVindependence;
  1695. ++WeakZeroSIVsuccesses;
  1696. return true;
  1697. }
  1698. return false;
  1699. }
  1700. // exactRDIVtest - Tests the RDIV subscript pair for dependence.
  1701. // Things of the form [c1 + a*i] and [c2 + b*j],
  1702. // where i and j are induction variable, c1 and c2 are loop invariant,
  1703. // and a and b are constants.
  1704. // Returns true if any possible dependence is disproved.
  1705. // Marks the result as inconsistent.
  1706. // Works in some cases that symbolicRDIVtest doesn't, and vice versa.
  1707. bool DependenceInfo::exactRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
  1708. const SCEV *SrcConst, const SCEV *DstConst,
  1709. const Loop *SrcLoop, const Loop *DstLoop,
  1710. FullDependence &Result) const {
  1711. LLVM_DEBUG(dbgs() << "\tExact RDIV test\n");
  1712. LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
  1713. LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
  1714. LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
  1715. LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
  1716. ++ExactRDIVapplications;
  1717. Result.Consistent = false;
  1718. const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
  1719. LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
  1720. const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
  1721. const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
  1722. const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
  1723. if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
  1724. return false;
  1725. // find gcd
  1726. APInt G, X, Y;
  1727. APInt AM = ConstSrcCoeff->getAPInt();
  1728. APInt BM = ConstDstCoeff->getAPInt();
  1729. APInt CM = ConstDelta->getAPInt();
  1730. unsigned Bits = AM.getBitWidth();
  1731. if (findGCD(Bits, AM, BM, CM, G, X, Y)) {
  1732. // gcd doesn't divide Delta, no dependence
  1733. ++ExactRDIVindependence;
  1734. return true;
  1735. }
  1736. LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
  1737. // since SCEV construction seems to normalize, LM = 0
  1738. APInt SrcUM(Bits, 1, true);
  1739. bool SrcUMvalid = false;
  1740. // SrcUM is perhaps unavailable, let's check
  1741. if (const SCEVConstant *UpperBound =
  1742. collectConstantUpperBound(SrcLoop, Delta->getType())) {
  1743. SrcUM = UpperBound->getAPInt();
  1744. LLVM_DEBUG(dbgs() << "\t SrcUM = " << SrcUM << "\n");
  1745. SrcUMvalid = true;
  1746. }
  1747. APInt DstUM(Bits, 1, true);
  1748. bool DstUMvalid = false;
  1749. // UM is perhaps unavailable, let's check
  1750. if (const SCEVConstant *UpperBound =
  1751. collectConstantUpperBound(DstLoop, Delta->getType())) {
  1752. DstUM = UpperBound->getAPInt();
  1753. LLVM_DEBUG(dbgs() << "\t DstUM = " << DstUM << "\n");
  1754. DstUMvalid = true;
  1755. }
  1756. APInt TU(APInt::getSignedMaxValue(Bits));
  1757. APInt TL(APInt::getSignedMinValue(Bits));
  1758. APInt TC = CM.sdiv(G);
  1759. APInt TX = X * TC;
  1760. APInt TY = Y * TC;
  1761. LLVM_DEBUG(dbgs() << "\t TC = " << TC << "\n");
  1762. LLVM_DEBUG(dbgs() << "\t TX = " << TX << "\n");
  1763. LLVM_DEBUG(dbgs() << "\t TY = " << TY << "\n");
  1764. SmallVector<APInt, 2> TLVec, TUVec;
  1765. APInt TB = BM.sdiv(G);
  1766. if (TB.sgt(0)) {
  1767. TLVec.push_back(ceilingOfQuotient(-TX, TB));
  1768. LLVM_DEBUG(dbgs() << "\t Possible TL = " << TLVec.back() << "\n");
  1769. if (SrcUMvalid) {
  1770. TUVec.push_back(floorOfQuotient(SrcUM - TX, TB));
  1771. LLVM_DEBUG(dbgs() << "\t Possible TU = " << TUVec.back() << "\n");
  1772. }
  1773. } else {
  1774. TUVec.push_back(floorOfQuotient(-TX, TB));
  1775. LLVM_DEBUG(dbgs() << "\t Possible TU = " << TUVec.back() << "\n");
  1776. if (SrcUMvalid) {
  1777. TLVec.push_back(ceilingOfQuotient(SrcUM - TX, TB));
  1778. LLVM_DEBUG(dbgs() << "\t Possible TL = " << TLVec.back() << "\n");
  1779. }
  1780. }
  1781. APInt TA = AM.sdiv(G);
  1782. if (TA.sgt(0)) {
  1783. TLVec.push_back(ceilingOfQuotient(-TY, TA));
  1784. LLVM_DEBUG(dbgs() << "\t Possible TL = " << TLVec.back() << "\n");
  1785. if (DstUMvalid) {
  1786. TUVec.push_back(floorOfQuotient(DstUM - TY, TA));
  1787. LLVM_DEBUG(dbgs() << "\t Possible TU = " << TUVec.back() << "\n");
  1788. }
  1789. } else {
  1790. TUVec.push_back(floorOfQuotient(-TY, TA));
  1791. LLVM_DEBUG(dbgs() << "\t Possible TU = " << TUVec.back() << "\n");
  1792. if (DstUMvalid) {
  1793. TLVec.push_back(ceilingOfQuotient(DstUM - TY, TA));
  1794. LLVM_DEBUG(dbgs() << "\t Possible TL = " << TLVec.back() << "\n");
  1795. }
  1796. }
  1797. if (TLVec.empty() || TUVec.empty())
  1798. return false;
  1799. LLVM_DEBUG(dbgs() << "\t TA = " << TA << "\n");
  1800. LLVM_DEBUG(dbgs() << "\t TB = " << TB << "\n");
  1801. TL = APIntOps::smax(TLVec.front(), TLVec.back());
  1802. TU = APIntOps::smin(TUVec.front(), TUVec.back());
  1803. LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
  1804. LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
  1805. if (TL.sgt(TU))
  1806. ++ExactRDIVindependence;
  1807. return TL.sgt(TU);
  1808. }
  1809. // symbolicRDIVtest -
  1810. // In Section 4.5 of the Practical Dependence Testing paper,the authors
  1811. // introduce a special case of Banerjee's Inequalities (also called the
  1812. // Extreme-Value Test) that can handle some of the SIV and RDIV cases,
  1813. // particularly cases with symbolics. Since it's only able to disprove
  1814. // dependence (not compute distances or directions), we'll use it as a
  1815. // fall back for the other tests.
  1816. //
  1817. // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
  1818. // where i and j are induction variables and c1 and c2 are loop invariants,
  1819. // we can use the symbolic tests to disprove some dependences, serving as a
  1820. // backup for the RDIV test. Note that i and j can be the same variable,
  1821. // letting this test serve as a backup for the various SIV tests.
  1822. //
  1823. // For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
  1824. // 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
  1825. // loop bounds for the i and j loops, respectively. So, ...
  1826. //
  1827. // c1 + a1*i = c2 + a2*j
  1828. // a1*i - a2*j = c2 - c1
  1829. //
  1830. // To test for a dependence, we compute c2 - c1 and make sure it's in the
  1831. // range of the maximum and minimum possible values of a1*i - a2*j.
  1832. // Considering the signs of a1 and a2, we have 4 possible cases:
  1833. //
  1834. // 1) If a1 >= 0 and a2 >= 0, then
  1835. // a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
  1836. // -a2*N2 <= c2 - c1 <= a1*N1
  1837. //
  1838. // 2) If a1 >= 0 and a2 <= 0, then
  1839. // a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
  1840. // 0 <= c2 - c1 <= a1*N1 - a2*N2
  1841. //
  1842. // 3) If a1 <= 0 and a2 >= 0, then
  1843. // a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
  1844. // a1*N1 - a2*N2 <= c2 - c1 <= 0
  1845. //
  1846. // 4) If a1 <= 0 and a2 <= 0, then
  1847. // a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2
  1848. // a1*N1 <= c2 - c1 <= -a2*N2
  1849. //
  1850. // return true if dependence disproved
  1851. bool DependenceInfo::symbolicRDIVtest(const SCEV *A1, const SCEV *A2,
  1852. const SCEV *C1, const SCEV *C2,
  1853. const Loop *Loop1,
  1854. const Loop *Loop2) const {
  1855. ++SymbolicRDIVapplications;
  1856. LLVM_DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
  1857. LLVM_DEBUG(dbgs() << "\t A1 = " << *A1);
  1858. LLVM_DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
  1859. LLVM_DEBUG(dbgs() << "\t A2 = " << *A2 << "\n");
  1860. LLVM_DEBUG(dbgs() << "\t C1 = " << *C1 << "\n");
  1861. LLVM_DEBUG(dbgs() << "\t C2 = " << *C2 << "\n");
  1862. const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
  1863. const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
  1864. LLVM_DEBUG(if (N1) dbgs() << "\t N1 = " << *N1 << "\n");
  1865. LLVM_DEBUG(if (N2) dbgs() << "\t N2 = " << *N2 << "\n");
  1866. const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
  1867. const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
  1868. LLVM_DEBUG(dbgs() << "\t C2 - C1 = " << *C2_C1 << "\n");
  1869. LLVM_DEBUG(dbgs() << "\t C1 - C2 = " << *C1_C2 << "\n");
  1870. if (SE->isKnownNonNegative(A1)) {
  1871. if (SE->isKnownNonNegative(A2)) {
  1872. // A1 >= 0 && A2 >= 0
  1873. if (N1) {
  1874. // make sure that c2 - c1 <= a1*N1
  1875. const SCEV *A1N1 = SE->getMulExpr(A1, N1);
  1876. LLVM_DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
  1877. if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
  1878. ++SymbolicRDIVindependence;
  1879. return true;
  1880. }
  1881. }
  1882. if (N2) {
  1883. // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
  1884. const SCEV *A2N2 = SE->getMulExpr(A2, N2);
  1885. LLVM_DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
  1886. if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
  1887. ++SymbolicRDIVindependence;
  1888. return true;
  1889. }
  1890. }
  1891. }
  1892. else if (SE->isKnownNonPositive(A2)) {
  1893. // a1 >= 0 && a2 <= 0
  1894. if (N1 && N2) {
  1895. // make sure that c2 - c1 <= a1*N1 - a2*N2
  1896. const SCEV *A1N1 = SE->getMulExpr(A1, N1);
  1897. const SCEV *A2N2 = SE->getMulExpr(A2, N2);
  1898. const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
  1899. LLVM_DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
  1900. if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
  1901. ++SymbolicRDIVindependence;
  1902. return true;
  1903. }
  1904. }
  1905. // make sure that 0 <= c2 - c1
  1906. if (SE->isKnownNegative(C2_C1)) {
  1907. ++SymbolicRDIVindependence;
  1908. return true;
  1909. }
  1910. }
  1911. }
  1912. else if (SE->isKnownNonPositive(A1)) {
  1913. if (SE->isKnownNonNegative(A2)) {
  1914. // a1 <= 0 && a2 >= 0
  1915. if (N1 && N2) {
  1916. // make sure that a1*N1 - a2*N2 <= c2 - c1
  1917. const SCEV *A1N1 = SE->getMulExpr(A1, N1);
  1918. const SCEV *A2N2 = SE->getMulExpr(A2, N2);
  1919. const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
  1920. LLVM_DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
  1921. if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
  1922. ++SymbolicRDIVindependence;
  1923. return true;
  1924. }
  1925. }
  1926. // make sure that c2 - c1 <= 0
  1927. if (SE->isKnownPositive(C2_C1)) {
  1928. ++SymbolicRDIVindependence;
  1929. return true;
  1930. }
  1931. }
  1932. else if (SE->isKnownNonPositive(A2)) {
  1933. // a1 <= 0 && a2 <= 0
  1934. if (N1) {
  1935. // make sure that a1*N1 <= c2 - c1
  1936. const SCEV *A1N1 = SE->getMulExpr(A1, N1);
  1937. LLVM_DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
  1938. if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
  1939. ++SymbolicRDIVindependence;
  1940. return true;
  1941. }
  1942. }
  1943. if (N2) {
  1944. // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
  1945. const SCEV *A2N2 = SE->getMulExpr(A2, N2);
  1946. LLVM_DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
  1947. if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
  1948. ++SymbolicRDIVindependence;
  1949. return true;
  1950. }
  1951. }
  1952. }
  1953. }
  1954. return false;
  1955. }
  1956. // testSIV -
  1957. // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
  1958. // where i is an induction variable, c1 and c2 are loop invariant, and a1 and
  1959. // a2 are constant, we attack it with an SIV test. While they can all be
  1960. // solved with the Exact SIV test, it's worthwhile to use simpler tests when
  1961. // they apply; they're cheaper and sometimes more precise.
  1962. //
  1963. // Return true if dependence disproved.
  1964. bool DependenceInfo::testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
  1965. FullDependence &Result, Constraint &NewConstraint,
  1966. const SCEV *&SplitIter) const {
  1967. LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
  1968. LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
  1969. const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
  1970. const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
  1971. if (SrcAddRec && DstAddRec) {
  1972. const SCEV *SrcConst = SrcAddRec->getStart();
  1973. const SCEV *DstConst = DstAddRec->getStart();
  1974. const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
  1975. const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
  1976. const Loop *CurLoop = SrcAddRec->getLoop();
  1977. assert(CurLoop == DstAddRec->getLoop() &&
  1978. "both loops in SIV should be same");
  1979. Level = mapSrcLoop(CurLoop);
  1980. bool disproven;
  1981. if (SrcCoeff == DstCoeff)
  1982. disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
  1983. Level, Result, NewConstraint);
  1984. else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
  1985. disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
  1986. Level, Result, NewConstraint, SplitIter);
  1987. else
  1988. disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
  1989. Level, Result, NewConstraint);
  1990. return disproven ||
  1991. gcdMIVtest(Src, Dst, Result) ||
  1992. symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
  1993. }
  1994. if (SrcAddRec) {
  1995. const SCEV *SrcConst = SrcAddRec->getStart();
  1996. const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
  1997. const SCEV *DstConst = Dst;
  1998. const Loop *CurLoop = SrcAddRec->getLoop();
  1999. Level = mapSrcLoop(CurLoop);
  2000. return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
  2001. Level, Result, NewConstraint) ||
  2002. gcdMIVtest(Src, Dst, Result);
  2003. }
  2004. if (DstAddRec) {
  2005. const SCEV *DstConst = DstAddRec->getStart();
  2006. const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
  2007. const SCEV *SrcConst = Src;
  2008. const Loop *CurLoop = DstAddRec->getLoop();
  2009. Level = mapDstLoop(CurLoop);
  2010. return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
  2011. CurLoop, Level, Result, NewConstraint) ||
  2012. gcdMIVtest(Src, Dst, Result);
  2013. }
  2014. llvm_unreachable("SIV test expected at least one AddRec");
  2015. return false;
  2016. }
  2017. // testRDIV -
  2018. // When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
  2019. // where i and j are induction variables, c1 and c2 are loop invariant,
  2020. // and a1 and a2 are constant, we can solve it exactly with an easy adaptation
  2021. // of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
  2022. // It doesn't make sense to talk about distance or direction in this case,
  2023. // so there's no point in making special versions of the Strong SIV test or
  2024. // the Weak-crossing SIV test.
  2025. //
  2026. // With minor algebra, this test can also be used for things like
  2027. // [c1 + a1*i + a2*j][c2].
  2028. //
  2029. // Return true if dependence disproved.
  2030. bool DependenceInfo::testRDIV(const SCEV *Src, const SCEV *Dst,
  2031. FullDependence &Result) const {
  2032. // we have 3 possible situations here:
  2033. // 1) [a*i + b] and [c*j + d]
  2034. // 2) [a*i + c*j + b] and [d]
  2035. // 3) [b] and [a*i + c*j + d]
  2036. // We need to find what we've got and get organized
  2037. const SCEV *SrcConst, *DstConst;
  2038. const SCEV *SrcCoeff, *DstCoeff;
  2039. const Loop *SrcLoop, *DstLoop;
  2040. LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
  2041. LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
  2042. const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
  2043. const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
  2044. if (SrcAddRec && DstAddRec) {
  2045. SrcConst = SrcAddRec->getStart();
  2046. SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
  2047. SrcLoop = SrcAddRec->getLoop();
  2048. DstConst = DstAddRec->getStart();
  2049. DstCoeff = DstAddRec->getStepRecurrence(*SE);
  2050. DstLoop = DstAddRec->getLoop();
  2051. }
  2052. else if (SrcAddRec) {
  2053. if (const SCEVAddRecExpr *tmpAddRec =
  2054. dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
  2055. SrcConst = tmpAddRec->getStart();
  2056. SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
  2057. SrcLoop = tmpAddRec->getLoop();
  2058. DstConst = Dst;
  2059. DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
  2060. DstLoop = SrcAddRec->getLoop();
  2061. }
  2062. else
  2063. llvm_unreachable("RDIV reached by surprising SCEVs");
  2064. }
  2065. else if (DstAddRec) {
  2066. if (const SCEVAddRecExpr *tmpAddRec =
  2067. dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
  2068. DstConst = tmpAddRec->getStart();
  2069. DstCoeff = tmpAddRec->getStepRecurrence(*SE);
  2070. DstLoop = tmpAddRec->getLoop();
  2071. SrcConst = Src;
  2072. SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
  2073. SrcLoop = DstAddRec->getLoop();
  2074. }
  2075. else
  2076. llvm_unreachable("RDIV reached by surprising SCEVs");
  2077. }
  2078. else
  2079. llvm_unreachable("RDIV expected at least one AddRec");
  2080. return exactRDIVtest(SrcCoeff, DstCoeff,
  2081. SrcConst, DstConst,
  2082. SrcLoop, DstLoop,
  2083. Result) ||
  2084. gcdMIVtest(Src, Dst, Result) ||
  2085. symbolicRDIVtest(SrcCoeff, DstCoeff,
  2086. SrcConst, DstConst,
  2087. SrcLoop, DstLoop);
  2088. }
  2089. // Tests the single-subscript MIV pair (Src and Dst) for dependence.
  2090. // Return true if dependence disproved.
  2091. // Can sometimes refine direction vectors.
  2092. bool DependenceInfo::testMIV(const SCEV *Src, const SCEV *Dst,
  2093. const SmallBitVector &Loops,
  2094. FullDependence &Result) const {
  2095. LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
  2096. LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
  2097. Result.Consistent = false;
  2098. return gcdMIVtest(Src, Dst, Result) ||
  2099. banerjeeMIVtest(Src, Dst, Loops, Result);
  2100. }
  2101. // Given a product, e.g., 10*X*Y, returns the first constant operand,
  2102. // in this case 10. If there is no constant part, returns NULL.
  2103. static
  2104. const SCEVConstant *getConstantPart(const SCEV *Expr) {
  2105. if (const auto *Constant = dyn_cast<SCEVConstant>(Expr))
  2106. return Constant;
  2107. else if (const auto *Product = dyn_cast<SCEVMulExpr>(Expr))
  2108. if (const auto *Constant = dyn_cast<SCEVConstant>(Product->getOperand(0)))
  2109. return Constant;
  2110. return nullptr;
  2111. }
  2112. //===----------------------------------------------------------------------===//
  2113. // gcdMIVtest -
  2114. // Tests an MIV subscript pair for dependence.
  2115. // Returns true if any possible dependence is disproved.
  2116. // Marks the result as inconsistent.
  2117. // Can sometimes disprove the equal direction for 1 or more loops,
  2118. // as discussed in Michael Wolfe's book,
  2119. // High Performance Compilers for Parallel Computing, page 235.
  2120. //
  2121. // We spend some effort (code!) to handle cases like
  2122. // [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
  2123. // but M and N are just loop-invariant variables.
  2124. // This should help us handle linearized subscripts;
  2125. // also makes this test a useful backup to the various SIV tests.
  2126. //
  2127. // It occurs to me that the presence of loop-invariant variables
  2128. // changes the nature of the test from "greatest common divisor"
  2129. // to "a common divisor".
  2130. bool DependenceInfo::gcdMIVtest(const SCEV *Src, const SCEV *Dst,
  2131. FullDependence &Result) const {
  2132. LLVM_DEBUG(dbgs() << "starting gcd\n");
  2133. ++GCDapplications;
  2134. unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
  2135. APInt RunningGCD = APInt::getZero(BitWidth);
  2136. // Examine Src coefficients.
  2137. // Compute running GCD and record source constant.
  2138. // Because we're looking for the constant at the end of the chain,
  2139. // we can't quit the loop just because the GCD == 1.
  2140. const SCEV *Coefficients = Src;
  2141. while (const SCEVAddRecExpr *AddRec =
  2142. dyn_cast<SCEVAddRecExpr>(Coefficients)) {
  2143. const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
  2144. // If the coefficient is the product of a constant and other stuff,
  2145. // we can use the constant in the GCD computation.
  2146. const auto *Constant = getConstantPart(Coeff);
  2147. if (!Constant)
  2148. return false;
  2149. APInt ConstCoeff = Constant->getAPInt();
  2150. RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
  2151. Coefficients = AddRec->getStart();
  2152. }
  2153. const SCEV *SrcConst = Coefficients;
  2154. // Examine Dst coefficients.
  2155. // Compute running GCD and record destination constant.
  2156. // Because we're looking for the constant at the end of the chain,
  2157. // we can't quit the loop just because the GCD == 1.
  2158. Coefficients = Dst;
  2159. while (const SCEVAddRecExpr *AddRec =
  2160. dyn_cast<SCEVAddRecExpr>(Coefficients)) {
  2161. const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
  2162. // If the coefficient is the product of a constant and other stuff,
  2163. // we can use the constant in the GCD computation.
  2164. const auto *Constant = getConstantPart(Coeff);
  2165. if (!Constant)
  2166. return false;
  2167. APInt ConstCoeff = Constant->getAPInt();
  2168. RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
  2169. Coefficients = AddRec->getStart();
  2170. }
  2171. const SCEV *DstConst = Coefficients;
  2172. APInt ExtraGCD = APInt::getZero(BitWidth);
  2173. const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
  2174. LLVM_DEBUG(dbgs() << " Delta = " << *Delta << "\n");
  2175. const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
  2176. if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
  2177. // If Delta is a sum of products, we may be able to make further progress.
  2178. for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
  2179. const SCEV *Operand = Sum->getOperand(Op);
  2180. if (isa<SCEVConstant>(Operand)) {
  2181. assert(!Constant && "Surprised to find multiple constants");
  2182. Constant = cast<SCEVConstant>(Operand);
  2183. }
  2184. else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) {
  2185. // Search for constant operand to participate in GCD;
  2186. // If none found; return false.
  2187. const SCEVConstant *ConstOp = getConstantPart(Product);
  2188. if (!ConstOp)
  2189. return false;
  2190. APInt ConstOpValue = ConstOp->getAPInt();
  2191. ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
  2192. ConstOpValue.abs());
  2193. }
  2194. else
  2195. return false;
  2196. }
  2197. }
  2198. if (!Constant)
  2199. return false;
  2200. APInt ConstDelta = cast<SCEVConstant>(Constant)->getAPInt();
  2201. LLVM_DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
  2202. if (ConstDelta == 0)
  2203. return false;
  2204. RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
  2205. LLVM_DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
  2206. APInt Remainder = ConstDelta.srem(RunningGCD);
  2207. if (Remainder != 0) {
  2208. ++GCDindependence;
  2209. return true;
  2210. }
  2211. // Try to disprove equal directions.
  2212. // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
  2213. // the code above can't disprove the dependence because the GCD = 1.
  2214. // So we consider what happen if i = i' and what happens if j = j'.
  2215. // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
  2216. // which is infeasible, so we can disallow the = direction for the i level.
  2217. // Setting j = j' doesn't help matters, so we end up with a direction vector
  2218. // of [<>, *]
  2219. //
  2220. // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
  2221. // we need to remember that the constant part is 5 and the RunningGCD should
  2222. // be initialized to ExtraGCD = 30.
  2223. LLVM_DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n');
  2224. bool Improved = false;
  2225. Coefficients = Src;
  2226. while (const SCEVAddRecExpr *AddRec =
  2227. dyn_cast<SCEVAddRecExpr>(Coefficients)) {
  2228. Coefficients = AddRec->getStart();
  2229. const Loop *CurLoop = AddRec->getLoop();
  2230. RunningGCD = ExtraGCD;
  2231. const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
  2232. const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
  2233. const SCEV *Inner = Src;
  2234. while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
  2235. AddRec = cast<SCEVAddRecExpr>(Inner);
  2236. const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
  2237. if (CurLoop == AddRec->getLoop())
  2238. ; // SrcCoeff == Coeff
  2239. else {
  2240. // If the coefficient is the product of a constant and other stuff,
  2241. // we can use the constant in the GCD computation.
  2242. Constant = getConstantPart(Coeff);
  2243. if (!Constant)
  2244. return false;
  2245. APInt ConstCoeff = Constant->getAPInt();
  2246. RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
  2247. }
  2248. Inner = AddRec->getStart();
  2249. }
  2250. Inner = Dst;
  2251. while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
  2252. AddRec = cast<SCEVAddRecExpr>(Inner);
  2253. const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
  2254. if (CurLoop == AddRec->getLoop())
  2255. DstCoeff = Coeff;
  2256. else {
  2257. // If the coefficient is the product of a constant and other stuff,
  2258. // we can use the constant in the GCD computation.
  2259. Constant = getConstantPart(Coeff);
  2260. if (!Constant)
  2261. return false;
  2262. APInt ConstCoeff = Constant->getAPInt();
  2263. RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
  2264. }
  2265. Inner = AddRec->getStart();
  2266. }
  2267. Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
  2268. // If the coefficient is the product of a constant and other stuff,
  2269. // we can use the constant in the GCD computation.
  2270. Constant = getConstantPart(Delta);
  2271. if (!Constant)
  2272. // The difference of the two coefficients might not be a product
  2273. // or constant, in which case we give up on this direction.
  2274. continue;
  2275. APInt ConstCoeff = Constant->getAPInt();
  2276. RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
  2277. LLVM_DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
  2278. if (RunningGCD != 0) {
  2279. Remainder = ConstDelta.srem(RunningGCD);
  2280. LLVM_DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
  2281. if (Remainder != 0) {
  2282. unsigned Level = mapSrcLoop(CurLoop);
  2283. Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
  2284. Improved = true;
  2285. }
  2286. }
  2287. }
  2288. if (Improved)
  2289. ++GCDsuccesses;
  2290. LLVM_DEBUG(dbgs() << "all done\n");
  2291. return false;
  2292. }
  2293. //===----------------------------------------------------------------------===//
  2294. // banerjeeMIVtest -
  2295. // Use Banerjee's Inequalities to test an MIV subscript pair.
  2296. // (Wolfe, in the race-car book, calls this the Extreme Value Test.)
  2297. // Generally follows the discussion in Section 2.5.2 of
  2298. //
  2299. // Optimizing Supercompilers for Supercomputers
  2300. // Michael Wolfe
  2301. //
  2302. // The inequalities given on page 25 are simplified in that loops are
  2303. // normalized so that the lower bound is always 0 and the stride is always 1.
  2304. // For example, Wolfe gives
  2305. //
  2306. // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
  2307. //
  2308. // where A_k is the coefficient of the kth index in the source subscript,
  2309. // B_k is the coefficient of the kth index in the destination subscript,
  2310. // U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
  2311. // index, and N_k is the stride of the kth index. Since all loops are normalized
  2312. // by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
  2313. // equation to
  2314. //
  2315. // LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
  2316. // = (A^-_k - B_k)^- (U_k - 1) - B_k
  2317. //
  2318. // Similar simplifications are possible for the other equations.
  2319. //
  2320. // When we can't determine the number of iterations for a loop,
  2321. // we use NULL as an indicator for the worst case, infinity.
  2322. // When computing the upper bound, NULL denotes +inf;
  2323. // for the lower bound, NULL denotes -inf.
  2324. //
  2325. // Return true if dependence disproved.
  2326. bool DependenceInfo::banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
  2327. const SmallBitVector &Loops,
  2328. FullDependence &Result) const {
  2329. LLVM_DEBUG(dbgs() << "starting Banerjee\n");
  2330. ++BanerjeeApplications;
  2331. LLVM_DEBUG(dbgs() << " Src = " << *Src << '\n');
  2332. const SCEV *A0;
  2333. CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
  2334. LLVM_DEBUG(dbgs() << " Dst = " << *Dst << '\n');
  2335. const SCEV *B0;
  2336. CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
  2337. BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
  2338. const SCEV *Delta = SE->getMinusSCEV(B0, A0);
  2339. LLVM_DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
  2340. // Compute bounds for all the * directions.
  2341. LLVM_DEBUG(dbgs() << "\tBounds[*]\n");
  2342. for (unsigned K = 1; K <= MaxLevels; ++K) {
  2343. Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
  2344. Bound[K].Direction = Dependence::DVEntry::ALL;
  2345. Bound[K].DirSet = Dependence::DVEntry::NONE;
  2346. findBoundsALL(A, B, Bound, K);
  2347. #ifndef NDEBUG
  2348. LLVM_DEBUG(dbgs() << "\t " << K << '\t');
  2349. if (Bound[K].Lower[Dependence::DVEntry::ALL])
  2350. LLVM_DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
  2351. else
  2352. LLVM_DEBUG(dbgs() << "-inf\t");
  2353. if (Bound[K].Upper[Dependence::DVEntry::ALL])
  2354. LLVM_DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
  2355. else
  2356. LLVM_DEBUG(dbgs() << "+inf\n");
  2357. #endif
  2358. }
  2359. // Test the *, *, *, ... case.
  2360. bool Disproved = false;
  2361. if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
  2362. // Explore the direction vector hierarchy.
  2363. unsigned DepthExpanded = 0;
  2364. unsigned NewDeps = exploreDirections(1, A, B, Bound,
  2365. Loops, DepthExpanded, Delta);
  2366. if (NewDeps > 0) {
  2367. bool Improved = false;
  2368. for (unsigned K = 1; K <= CommonLevels; ++K) {
  2369. if (Loops[K]) {
  2370. unsigned Old = Result.DV[K - 1].Direction;
  2371. Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
  2372. Improved |= Old != Result.DV[K - 1].Direction;
  2373. if (!Result.DV[K - 1].Direction) {
  2374. Improved = false;
  2375. Disproved = true;
  2376. break;
  2377. }
  2378. }
  2379. }
  2380. if (Improved)
  2381. ++BanerjeeSuccesses;
  2382. }
  2383. else {
  2384. ++BanerjeeIndependence;
  2385. Disproved = true;
  2386. }
  2387. }
  2388. else {
  2389. ++BanerjeeIndependence;
  2390. Disproved = true;
  2391. }
  2392. delete [] Bound;
  2393. delete [] A;
  2394. delete [] B;
  2395. return Disproved;
  2396. }
  2397. // Hierarchically expands the direction vector
  2398. // search space, combining the directions of discovered dependences
  2399. // in the DirSet field of Bound. Returns the number of distinct
  2400. // dependences discovered. If the dependence is disproved,
  2401. // it will return 0.
  2402. unsigned DependenceInfo::exploreDirections(unsigned Level, CoefficientInfo *A,
  2403. CoefficientInfo *B, BoundInfo *Bound,
  2404. const SmallBitVector &Loops,
  2405. unsigned &DepthExpanded,
  2406. const SCEV *Delta) const {
  2407. // This algorithm has worst case complexity of O(3^n), where 'n' is the number
  2408. // of common loop levels. To avoid excessive compile-time, pessimize all the
  2409. // results and immediately return when the number of common levels is beyond
  2410. // the given threshold.
  2411. if (CommonLevels > MIVMaxLevelThreshold) {
  2412. LLVM_DEBUG(dbgs() << "Number of common levels exceeded the threshold. MIV "
  2413. "direction exploration is terminated.\n");
  2414. for (unsigned K = 1; K <= CommonLevels; ++K)
  2415. if (Loops[K])
  2416. Bound[K].DirSet = Dependence::DVEntry::ALL;
  2417. return 1;
  2418. }
  2419. if (Level > CommonLevels) {
  2420. // record result
  2421. LLVM_DEBUG(dbgs() << "\t[");
  2422. for (unsigned K = 1; K <= CommonLevels; ++K) {
  2423. if (Loops[K]) {
  2424. Bound[K].DirSet |= Bound[K].Direction;
  2425. #ifndef NDEBUG
  2426. switch (Bound[K].Direction) {
  2427. case Dependence::DVEntry::LT:
  2428. LLVM_DEBUG(dbgs() << " <");
  2429. break;
  2430. case Dependence::DVEntry::EQ:
  2431. LLVM_DEBUG(dbgs() << " =");
  2432. break;
  2433. case Dependence::DVEntry::GT:
  2434. LLVM_DEBUG(dbgs() << " >");
  2435. break;
  2436. case Dependence::DVEntry::ALL:
  2437. LLVM_DEBUG(dbgs() << " *");
  2438. break;
  2439. default:
  2440. llvm_unreachable("unexpected Bound[K].Direction");
  2441. }
  2442. #endif
  2443. }
  2444. }
  2445. LLVM_DEBUG(dbgs() << " ]\n");
  2446. return 1;
  2447. }
  2448. if (Loops[Level]) {
  2449. if (Level > DepthExpanded) {
  2450. DepthExpanded = Level;
  2451. // compute bounds for <, =, > at current level
  2452. findBoundsLT(A, B, Bound, Level);
  2453. findBoundsGT(A, B, Bound, Level);
  2454. findBoundsEQ(A, B, Bound, Level);
  2455. #ifndef NDEBUG
  2456. LLVM_DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
  2457. LLVM_DEBUG(dbgs() << "\t <\t");
  2458. if (Bound[Level].Lower[Dependence::DVEntry::LT])
  2459. LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT]
  2460. << '\t');
  2461. else
  2462. LLVM_DEBUG(dbgs() << "-inf\t");
  2463. if (Bound[Level].Upper[Dependence::DVEntry::LT])
  2464. LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT]
  2465. << '\n');
  2466. else
  2467. LLVM_DEBUG(dbgs() << "+inf\n");
  2468. LLVM_DEBUG(dbgs() << "\t =\t");
  2469. if (Bound[Level].Lower[Dependence::DVEntry::EQ])
  2470. LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ]
  2471. << '\t');
  2472. else
  2473. LLVM_DEBUG(dbgs() << "-inf\t");
  2474. if (Bound[Level].Upper[Dependence::DVEntry::EQ])
  2475. LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ]
  2476. << '\n');
  2477. else
  2478. LLVM_DEBUG(dbgs() << "+inf\n");
  2479. LLVM_DEBUG(dbgs() << "\t >\t");
  2480. if (Bound[Level].Lower[Dependence::DVEntry::GT])
  2481. LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT]
  2482. << '\t');
  2483. else
  2484. LLVM_DEBUG(dbgs() << "-inf\t");
  2485. if (Bound[Level].Upper[Dependence::DVEntry::GT])
  2486. LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT]
  2487. << '\n');
  2488. else
  2489. LLVM_DEBUG(dbgs() << "+inf\n");
  2490. #endif
  2491. }
  2492. unsigned NewDeps = 0;
  2493. // test bounds for <, *, *, ...
  2494. if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
  2495. NewDeps += exploreDirections(Level + 1, A, B, Bound,
  2496. Loops, DepthExpanded, Delta);
  2497. // Test bounds for =, *, *, ...
  2498. if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
  2499. NewDeps += exploreDirections(Level + 1, A, B, Bound,
  2500. Loops, DepthExpanded, Delta);
  2501. // test bounds for >, *, *, ...
  2502. if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
  2503. NewDeps += exploreDirections(Level + 1, A, B, Bound,
  2504. Loops, DepthExpanded, Delta);
  2505. Bound[Level].Direction = Dependence::DVEntry::ALL;
  2506. return NewDeps;
  2507. }
  2508. else
  2509. return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
  2510. }
  2511. // Returns true iff the current bounds are plausible.
  2512. bool DependenceInfo::testBounds(unsigned char DirKind, unsigned Level,
  2513. BoundInfo *Bound, const SCEV *Delta) const {
  2514. Bound[Level].Direction = DirKind;
  2515. if (const SCEV *LowerBound = getLowerBound(Bound))
  2516. if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
  2517. return false;
  2518. if (const SCEV *UpperBound = getUpperBound(Bound))
  2519. if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
  2520. return false;
  2521. return true;
  2522. }
  2523. // Computes the upper and lower bounds for level K
  2524. // using the * direction. Records them in Bound.
  2525. // Wolfe gives the equations
  2526. //
  2527. // LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
  2528. // UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
  2529. //
  2530. // Since we normalize loops, we can simplify these equations to
  2531. //
  2532. // LB^*_k = (A^-_k - B^+_k)U_k
  2533. // UB^*_k = (A^+_k - B^-_k)U_k
  2534. //
  2535. // We must be careful to handle the case where the upper bound is unknown.
  2536. // Note that the lower bound is always <= 0
  2537. // and the upper bound is always >= 0.
  2538. void DependenceInfo::findBoundsALL(CoefficientInfo *A, CoefficientInfo *B,
  2539. BoundInfo *Bound, unsigned K) const {
  2540. Bound[K].Lower[Dependence::DVEntry::ALL] = nullptr; // Default value = -infinity.
  2541. Bound[K].Upper[Dependence::DVEntry::ALL] = nullptr; // Default value = +infinity.
  2542. if (Bound[K].Iterations) {
  2543. Bound[K].Lower[Dependence::DVEntry::ALL] =
  2544. SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
  2545. Bound[K].Iterations);
  2546. Bound[K].Upper[Dependence::DVEntry::ALL] =
  2547. SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
  2548. Bound[K].Iterations);
  2549. }
  2550. else {
  2551. // If the difference is 0, we won't need to know the number of iterations.
  2552. if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
  2553. Bound[K].Lower[Dependence::DVEntry::ALL] =
  2554. SE->getZero(A[K].Coeff->getType());
  2555. if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
  2556. Bound[K].Upper[Dependence::DVEntry::ALL] =
  2557. SE->getZero(A[K].Coeff->getType());
  2558. }
  2559. }
  2560. // Computes the upper and lower bounds for level K
  2561. // using the = direction. Records them in Bound.
  2562. // Wolfe gives the equations
  2563. //
  2564. // LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
  2565. // UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
  2566. //
  2567. // Since we normalize loops, we can simplify these equations to
  2568. //
  2569. // LB^=_k = (A_k - B_k)^- U_k
  2570. // UB^=_k = (A_k - B_k)^+ U_k
  2571. //
  2572. // We must be careful to handle the case where the upper bound is unknown.
  2573. // Note that the lower bound is always <= 0
  2574. // and the upper bound is always >= 0.
  2575. void DependenceInfo::findBoundsEQ(CoefficientInfo *A, CoefficientInfo *B,
  2576. BoundInfo *Bound, unsigned K) const {
  2577. Bound[K].Lower[Dependence::DVEntry::EQ] = nullptr; // Default value = -infinity.
  2578. Bound[K].Upper[Dependence::DVEntry::EQ] = nullptr; // Default value = +infinity.
  2579. if (Bound[K].Iterations) {
  2580. const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
  2581. const SCEV *NegativePart = getNegativePart(Delta);
  2582. Bound[K].Lower[Dependence::DVEntry::EQ] =
  2583. SE->getMulExpr(NegativePart, Bound[K].Iterations);
  2584. const SCEV *PositivePart = getPositivePart(Delta);
  2585. Bound[K].Upper[Dependence::DVEntry::EQ] =
  2586. SE->getMulExpr(PositivePart, Bound[K].Iterations);
  2587. }
  2588. else {
  2589. // If the positive/negative part of the difference is 0,
  2590. // we won't need to know the number of iterations.
  2591. const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
  2592. const SCEV *NegativePart = getNegativePart(Delta);
  2593. if (NegativePart->isZero())
  2594. Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
  2595. const SCEV *PositivePart = getPositivePart(Delta);
  2596. if (PositivePart->isZero())
  2597. Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
  2598. }
  2599. }
  2600. // Computes the upper and lower bounds for level K
  2601. // using the < direction. Records them in Bound.
  2602. // Wolfe gives the equations
  2603. //
  2604. // LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
  2605. // UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
  2606. //
  2607. // Since we normalize loops, we can simplify these equations to
  2608. //
  2609. // LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
  2610. // UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
  2611. //
  2612. // We must be careful to handle the case where the upper bound is unknown.
  2613. void DependenceInfo::findBoundsLT(CoefficientInfo *A, CoefficientInfo *B,
  2614. BoundInfo *Bound, unsigned K) const {
  2615. Bound[K].Lower[Dependence::DVEntry::LT] = nullptr; // Default value = -infinity.
  2616. Bound[K].Upper[Dependence::DVEntry::LT] = nullptr; // Default value = +infinity.
  2617. if (Bound[K].Iterations) {
  2618. const SCEV *Iter_1 = SE->getMinusSCEV(
  2619. Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
  2620. const SCEV *NegPart =
  2621. getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
  2622. Bound[K].Lower[Dependence::DVEntry::LT] =
  2623. SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
  2624. const SCEV *PosPart =
  2625. getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
  2626. Bound[K].Upper[Dependence::DVEntry::LT] =
  2627. SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
  2628. }
  2629. else {
  2630. // If the positive/negative part of the difference is 0,
  2631. // we won't need to know the number of iterations.
  2632. const SCEV *NegPart =
  2633. getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
  2634. if (NegPart->isZero())
  2635. Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
  2636. const SCEV *PosPart =
  2637. getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
  2638. if (PosPart->isZero())
  2639. Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
  2640. }
  2641. }
  2642. // Computes the upper and lower bounds for level K
  2643. // using the > direction. Records them in Bound.
  2644. // Wolfe gives the equations
  2645. //
  2646. // LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
  2647. // UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
  2648. //
  2649. // Since we normalize loops, we can simplify these equations to
  2650. //
  2651. // LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
  2652. // UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
  2653. //
  2654. // We must be careful to handle the case where the upper bound is unknown.
  2655. void DependenceInfo::findBoundsGT(CoefficientInfo *A, CoefficientInfo *B,
  2656. BoundInfo *Bound, unsigned K) const {
  2657. Bound[K].Lower[Dependence::DVEntry::GT] = nullptr; // Default value = -infinity.
  2658. Bound[K].Upper[Dependence::DVEntry::GT] = nullptr; // Default value = +infinity.
  2659. if (Bound[K].Iterations) {
  2660. const SCEV *Iter_1 = SE->getMinusSCEV(
  2661. Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
  2662. const SCEV *NegPart =
  2663. getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
  2664. Bound[K].Lower[Dependence::DVEntry::GT] =
  2665. SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
  2666. const SCEV *PosPart =
  2667. getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
  2668. Bound[K].Upper[Dependence::DVEntry::GT] =
  2669. SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
  2670. }
  2671. else {
  2672. // If the positive/negative part of the difference is 0,
  2673. // we won't need to know the number of iterations.
  2674. const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
  2675. if (NegPart->isZero())
  2676. Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
  2677. const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
  2678. if (PosPart->isZero())
  2679. Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
  2680. }
  2681. }
  2682. // X^+ = max(X, 0)
  2683. const SCEV *DependenceInfo::getPositivePart(const SCEV *X) const {
  2684. return SE->getSMaxExpr(X, SE->getZero(X->getType()));
  2685. }
  2686. // X^- = min(X, 0)
  2687. const SCEV *DependenceInfo::getNegativePart(const SCEV *X) const {
  2688. return SE->getSMinExpr(X, SE->getZero(X->getType()));
  2689. }
  2690. // Walks through the subscript,
  2691. // collecting each coefficient, the associated loop bounds,
  2692. // and recording its positive and negative parts for later use.
  2693. DependenceInfo::CoefficientInfo *
  2694. DependenceInfo::collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
  2695. const SCEV *&Constant) const {
  2696. const SCEV *Zero = SE->getZero(Subscript->getType());
  2697. CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
  2698. for (unsigned K = 1; K <= MaxLevels; ++K) {
  2699. CI[K].Coeff = Zero;
  2700. CI[K].PosPart = Zero;
  2701. CI[K].NegPart = Zero;
  2702. CI[K].Iterations = nullptr;
  2703. }
  2704. while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
  2705. const Loop *L = AddRec->getLoop();
  2706. unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
  2707. CI[K].Coeff = AddRec->getStepRecurrence(*SE);
  2708. CI[K].PosPart = getPositivePart(CI[K].Coeff);
  2709. CI[K].NegPart = getNegativePart(CI[K].Coeff);
  2710. CI[K].Iterations = collectUpperBound(L, Subscript->getType());
  2711. Subscript = AddRec->getStart();
  2712. }
  2713. Constant = Subscript;
  2714. #ifndef NDEBUG
  2715. LLVM_DEBUG(dbgs() << "\tCoefficient Info\n");
  2716. for (unsigned K = 1; K <= MaxLevels; ++K) {
  2717. LLVM_DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff);
  2718. LLVM_DEBUG(dbgs() << "\tPos Part = ");
  2719. LLVM_DEBUG(dbgs() << *CI[K].PosPart);
  2720. LLVM_DEBUG(dbgs() << "\tNeg Part = ");
  2721. LLVM_DEBUG(dbgs() << *CI[K].NegPart);
  2722. LLVM_DEBUG(dbgs() << "\tUpper Bound = ");
  2723. if (CI[K].Iterations)
  2724. LLVM_DEBUG(dbgs() << *CI[K].Iterations);
  2725. else
  2726. LLVM_DEBUG(dbgs() << "+inf");
  2727. LLVM_DEBUG(dbgs() << '\n');
  2728. }
  2729. LLVM_DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n');
  2730. #endif
  2731. return CI;
  2732. }
  2733. // Looks through all the bounds info and
  2734. // computes the lower bound given the current direction settings
  2735. // at each level. If the lower bound for any level is -inf,
  2736. // the result is -inf.
  2737. const SCEV *DependenceInfo::getLowerBound(BoundInfo *Bound) const {
  2738. const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
  2739. for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
  2740. if (Bound[K].Lower[Bound[K].Direction])
  2741. Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
  2742. else
  2743. Sum = nullptr;
  2744. }
  2745. return Sum;
  2746. }
  2747. // Looks through all the bounds info and
  2748. // computes the upper bound given the current direction settings
  2749. // at each level. If the upper bound at any level is +inf,
  2750. // the result is +inf.
  2751. const SCEV *DependenceInfo::getUpperBound(BoundInfo *Bound) const {
  2752. const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
  2753. for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
  2754. if (Bound[K].Upper[Bound[K].Direction])
  2755. Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
  2756. else
  2757. Sum = nullptr;
  2758. }
  2759. return Sum;
  2760. }
  2761. //===----------------------------------------------------------------------===//
  2762. // Constraint manipulation for Delta test.
  2763. // Given a linear SCEV,
  2764. // return the coefficient (the step)
  2765. // corresponding to the specified loop.
  2766. // If there isn't one, return 0.
  2767. // For example, given a*i + b*j + c*k, finding the coefficient
  2768. // corresponding to the j loop would yield b.
  2769. const SCEV *DependenceInfo::findCoefficient(const SCEV *Expr,
  2770. const Loop *TargetLoop) const {
  2771. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
  2772. if (!AddRec)
  2773. return SE->getZero(Expr->getType());
  2774. if (AddRec->getLoop() == TargetLoop)
  2775. return AddRec->getStepRecurrence(*SE);
  2776. return findCoefficient(AddRec->getStart(), TargetLoop);
  2777. }
  2778. // Given a linear SCEV,
  2779. // return the SCEV given by zeroing out the coefficient
  2780. // corresponding to the specified loop.
  2781. // For example, given a*i + b*j + c*k, zeroing the coefficient
  2782. // corresponding to the j loop would yield a*i + c*k.
  2783. const SCEV *DependenceInfo::zeroCoefficient(const SCEV *Expr,
  2784. const Loop *TargetLoop) const {
  2785. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
  2786. if (!AddRec)
  2787. return Expr; // ignore
  2788. if (AddRec->getLoop() == TargetLoop)
  2789. return AddRec->getStart();
  2790. return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
  2791. AddRec->getStepRecurrence(*SE),
  2792. AddRec->getLoop(),
  2793. AddRec->getNoWrapFlags());
  2794. }
  2795. // Given a linear SCEV Expr,
  2796. // return the SCEV given by adding some Value to the
  2797. // coefficient corresponding to the specified TargetLoop.
  2798. // For example, given a*i + b*j + c*k, adding 1 to the coefficient
  2799. // corresponding to the j loop would yield a*i + (b+1)*j + c*k.
  2800. const SCEV *DependenceInfo::addToCoefficient(const SCEV *Expr,
  2801. const Loop *TargetLoop,
  2802. const SCEV *Value) const {
  2803. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
  2804. if (!AddRec) // create a new addRec
  2805. return SE->getAddRecExpr(Expr,
  2806. Value,
  2807. TargetLoop,
  2808. SCEV::FlagAnyWrap); // Worst case, with no info.
  2809. if (AddRec->getLoop() == TargetLoop) {
  2810. const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
  2811. if (Sum->isZero())
  2812. return AddRec->getStart();
  2813. return SE->getAddRecExpr(AddRec->getStart(),
  2814. Sum,
  2815. AddRec->getLoop(),
  2816. AddRec->getNoWrapFlags());
  2817. }
  2818. if (SE->isLoopInvariant(AddRec, TargetLoop))
  2819. return SE->getAddRecExpr(AddRec, Value, TargetLoop, SCEV::FlagAnyWrap);
  2820. return SE->getAddRecExpr(
  2821. addToCoefficient(AddRec->getStart(), TargetLoop, Value),
  2822. AddRec->getStepRecurrence(*SE), AddRec->getLoop(),
  2823. AddRec->getNoWrapFlags());
  2824. }
  2825. // Review the constraints, looking for opportunities
  2826. // to simplify a subscript pair (Src and Dst).
  2827. // Return true if some simplification occurs.
  2828. // If the simplification isn't exact (that is, if it is conservative
  2829. // in terms of dependence), set consistent to false.
  2830. // Corresponds to Figure 5 from the paper
  2831. //
  2832. // Practical Dependence Testing
  2833. // Goff, Kennedy, Tseng
  2834. // PLDI 1991
  2835. bool DependenceInfo::propagate(const SCEV *&Src, const SCEV *&Dst,
  2836. SmallBitVector &Loops,
  2837. SmallVectorImpl<Constraint> &Constraints,
  2838. bool &Consistent) {
  2839. bool Result = false;
  2840. for (unsigned LI : Loops.set_bits()) {
  2841. LLVM_DEBUG(dbgs() << "\t Constraint[" << LI << "] is");
  2842. LLVM_DEBUG(Constraints[LI].dump(dbgs()));
  2843. if (Constraints[LI].isDistance())
  2844. Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
  2845. else if (Constraints[LI].isLine())
  2846. Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
  2847. else if (Constraints[LI].isPoint())
  2848. Result |= propagatePoint(Src, Dst, Constraints[LI]);
  2849. }
  2850. return Result;
  2851. }
  2852. // Attempt to propagate a distance
  2853. // constraint into a subscript pair (Src and Dst).
  2854. // Return true if some simplification occurs.
  2855. // If the simplification isn't exact (that is, if it is conservative
  2856. // in terms of dependence), set consistent to false.
  2857. bool DependenceInfo::propagateDistance(const SCEV *&Src, const SCEV *&Dst,
  2858. Constraint &CurConstraint,
  2859. bool &Consistent) {
  2860. const Loop *CurLoop = CurConstraint.getAssociatedLoop();
  2861. LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
  2862. const SCEV *A_K = findCoefficient(Src, CurLoop);
  2863. if (A_K->isZero())
  2864. return false;
  2865. const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
  2866. Src = SE->getMinusSCEV(Src, DA_K);
  2867. Src = zeroCoefficient(Src, CurLoop);
  2868. LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
  2869. LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
  2870. Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
  2871. LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
  2872. if (!findCoefficient(Dst, CurLoop)->isZero())
  2873. Consistent = false;
  2874. return true;
  2875. }
  2876. // Attempt to propagate a line
  2877. // constraint into a subscript pair (Src and Dst).
  2878. // Return true if some simplification occurs.
  2879. // If the simplification isn't exact (that is, if it is conservative
  2880. // in terms of dependence), set consistent to false.
  2881. bool DependenceInfo::propagateLine(const SCEV *&Src, const SCEV *&Dst,
  2882. Constraint &CurConstraint,
  2883. bool &Consistent) {
  2884. const Loop *CurLoop = CurConstraint.getAssociatedLoop();
  2885. const SCEV *A = CurConstraint.getA();
  2886. const SCEV *B = CurConstraint.getB();
  2887. const SCEV *C = CurConstraint.getC();
  2888. LLVM_DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C
  2889. << "\n");
  2890. LLVM_DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
  2891. LLVM_DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
  2892. if (A->isZero()) {
  2893. const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
  2894. const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
  2895. if (!Bconst || !Cconst) return false;
  2896. APInt Beta = Bconst->getAPInt();
  2897. APInt Charlie = Cconst->getAPInt();
  2898. APInt CdivB = Charlie.sdiv(Beta);
  2899. assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
  2900. const SCEV *AP_K = findCoefficient(Dst, CurLoop);
  2901. // Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
  2902. Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
  2903. Dst = zeroCoefficient(Dst, CurLoop);
  2904. if (!findCoefficient(Src, CurLoop)->isZero())
  2905. Consistent = false;
  2906. }
  2907. else if (B->isZero()) {
  2908. const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
  2909. const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
  2910. if (!Aconst || !Cconst) return false;
  2911. APInt Alpha = Aconst->getAPInt();
  2912. APInt Charlie = Cconst->getAPInt();
  2913. APInt CdivA = Charlie.sdiv(Alpha);
  2914. assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
  2915. const SCEV *A_K = findCoefficient(Src, CurLoop);
  2916. Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
  2917. Src = zeroCoefficient(Src, CurLoop);
  2918. if (!findCoefficient(Dst, CurLoop)->isZero())
  2919. Consistent = false;
  2920. }
  2921. else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
  2922. const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
  2923. const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
  2924. if (!Aconst || !Cconst) return false;
  2925. APInt Alpha = Aconst->getAPInt();
  2926. APInt Charlie = Cconst->getAPInt();
  2927. APInt CdivA = Charlie.sdiv(Alpha);
  2928. assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
  2929. const SCEV *A_K = findCoefficient(Src, CurLoop);
  2930. Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
  2931. Src = zeroCoefficient(Src, CurLoop);
  2932. Dst = addToCoefficient(Dst, CurLoop, A_K);
  2933. if (!findCoefficient(Dst, CurLoop)->isZero())
  2934. Consistent = false;
  2935. }
  2936. else {
  2937. // paper is incorrect here, or perhaps just misleading
  2938. const SCEV *A_K = findCoefficient(Src, CurLoop);
  2939. Src = SE->getMulExpr(Src, A);
  2940. Dst = SE->getMulExpr(Dst, A);
  2941. Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
  2942. Src = zeroCoefficient(Src, CurLoop);
  2943. Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
  2944. if (!findCoefficient(Dst, CurLoop)->isZero())
  2945. Consistent = false;
  2946. }
  2947. LLVM_DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
  2948. LLVM_DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
  2949. return true;
  2950. }
  2951. // Attempt to propagate a point
  2952. // constraint into a subscript pair (Src and Dst).
  2953. // Return true if some simplification occurs.
  2954. bool DependenceInfo::propagatePoint(const SCEV *&Src, const SCEV *&Dst,
  2955. Constraint &CurConstraint) {
  2956. const Loop *CurLoop = CurConstraint.getAssociatedLoop();
  2957. const SCEV *A_K = findCoefficient(Src, CurLoop);
  2958. const SCEV *AP_K = findCoefficient(Dst, CurLoop);
  2959. const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
  2960. const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
  2961. LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
  2962. Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
  2963. Src = zeroCoefficient(Src, CurLoop);
  2964. LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
  2965. LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
  2966. Dst = zeroCoefficient(Dst, CurLoop);
  2967. LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
  2968. return true;
  2969. }
  2970. // Update direction vector entry based on the current constraint.
  2971. void DependenceInfo::updateDirection(Dependence::DVEntry &Level,
  2972. const Constraint &CurConstraint) const {
  2973. LLVM_DEBUG(dbgs() << "\tUpdate direction, constraint =");
  2974. LLVM_DEBUG(CurConstraint.dump(dbgs()));
  2975. if (CurConstraint.isAny())
  2976. ; // use defaults
  2977. else if (CurConstraint.isDistance()) {
  2978. // this one is consistent, the others aren't
  2979. Level.Scalar = false;
  2980. Level.Distance = CurConstraint.getD();
  2981. unsigned NewDirection = Dependence::DVEntry::NONE;
  2982. if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
  2983. NewDirection = Dependence::DVEntry::EQ;
  2984. if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
  2985. NewDirection |= Dependence::DVEntry::LT;
  2986. if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
  2987. NewDirection |= Dependence::DVEntry::GT;
  2988. Level.Direction &= NewDirection;
  2989. }
  2990. else if (CurConstraint.isLine()) {
  2991. Level.Scalar = false;
  2992. Level.Distance = nullptr;
  2993. // direction should be accurate
  2994. }
  2995. else if (CurConstraint.isPoint()) {
  2996. Level.Scalar = false;
  2997. Level.Distance = nullptr;
  2998. unsigned NewDirection = Dependence::DVEntry::NONE;
  2999. if (!isKnownPredicate(CmpInst::ICMP_NE,
  3000. CurConstraint.getY(),
  3001. CurConstraint.getX()))
  3002. // if X may be = Y
  3003. NewDirection |= Dependence::DVEntry::EQ;
  3004. if (!isKnownPredicate(CmpInst::ICMP_SLE,
  3005. CurConstraint.getY(),
  3006. CurConstraint.getX()))
  3007. // if Y may be > X
  3008. NewDirection |= Dependence::DVEntry::LT;
  3009. if (!isKnownPredicate(CmpInst::ICMP_SGE,
  3010. CurConstraint.getY(),
  3011. CurConstraint.getX()))
  3012. // if Y may be < X
  3013. NewDirection |= Dependence::DVEntry::GT;
  3014. Level.Direction &= NewDirection;
  3015. }
  3016. else
  3017. llvm_unreachable("constraint has unexpected kind");
  3018. }
  3019. /// Check if we can delinearize the subscripts. If the SCEVs representing the
  3020. /// source and destination array references are recurrences on a nested loop,
  3021. /// this function flattens the nested recurrences into separate recurrences
  3022. /// for each loop level.
  3023. bool DependenceInfo::tryDelinearize(Instruction *Src, Instruction *Dst,
  3024. SmallVectorImpl<Subscript> &Pair) {
  3025. assert(isLoadOrStore(Src) && "instruction is not load or store");
  3026. assert(isLoadOrStore(Dst) && "instruction is not load or store");
  3027. Value *SrcPtr = getLoadStorePointerOperand(Src);
  3028. Value *DstPtr = getLoadStorePointerOperand(Dst);
  3029. Loop *SrcLoop = LI->getLoopFor(Src->getParent());
  3030. Loop *DstLoop = LI->getLoopFor(Dst->getParent());
  3031. const SCEV *SrcAccessFn = SE->getSCEVAtScope(SrcPtr, SrcLoop);
  3032. const SCEV *DstAccessFn = SE->getSCEVAtScope(DstPtr, DstLoop);
  3033. const SCEVUnknown *SrcBase =
  3034. dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
  3035. const SCEVUnknown *DstBase =
  3036. dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
  3037. if (!SrcBase || !DstBase || SrcBase != DstBase)
  3038. return false;
  3039. SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
  3040. if (!tryDelinearizeFixedSize(Src, Dst, SrcAccessFn, DstAccessFn,
  3041. SrcSubscripts, DstSubscripts) &&
  3042. !tryDelinearizeParametricSize(Src, Dst, SrcAccessFn, DstAccessFn,
  3043. SrcSubscripts, DstSubscripts))
  3044. return false;
  3045. int Size = SrcSubscripts.size();
  3046. LLVM_DEBUG({
  3047. dbgs() << "\nSrcSubscripts: ";
  3048. for (int I = 0; I < Size; I++)
  3049. dbgs() << *SrcSubscripts[I];
  3050. dbgs() << "\nDstSubscripts: ";
  3051. for (int I = 0; I < Size; I++)
  3052. dbgs() << *DstSubscripts[I];
  3053. });
  3054. // The delinearization transforms a single-subscript MIV dependence test into
  3055. // a multi-subscript SIV dependence test that is easier to compute. So we
  3056. // resize Pair to contain as many pairs of subscripts as the delinearization
  3057. // has found, and then initialize the pairs following the delinearization.
  3058. Pair.resize(Size);
  3059. for (int I = 0; I < Size; ++I) {
  3060. Pair[I].Src = SrcSubscripts[I];
  3061. Pair[I].Dst = DstSubscripts[I];
  3062. unifySubscriptType(&Pair[I]);
  3063. }
  3064. return true;
  3065. }
  3066. bool DependenceInfo::tryDelinearizeFixedSize(
  3067. Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
  3068. const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
  3069. SmallVectorImpl<const SCEV *> &DstSubscripts) {
  3070. Value *SrcPtr = getLoadStorePointerOperand(Src);
  3071. Value *DstPtr = getLoadStorePointerOperand(Dst);
  3072. const SCEVUnknown *SrcBase =
  3073. dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
  3074. const SCEVUnknown *DstBase =
  3075. dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
  3076. assert(SrcBase && DstBase && SrcBase == DstBase &&
  3077. "expected src and dst scev unknowns to be equal");
  3078. // Check the simple case where the array dimensions are fixed size.
  3079. auto *SrcGEP = dyn_cast<GetElementPtrInst>(SrcPtr);
  3080. auto *DstGEP = dyn_cast<GetElementPtrInst>(DstPtr);
  3081. if (!SrcGEP || !DstGEP)
  3082. return false;
  3083. SmallVector<int, 4> SrcSizes, DstSizes;
  3084. getIndexExpressionsFromGEP(*SE, SrcGEP, SrcSubscripts, SrcSizes);
  3085. getIndexExpressionsFromGEP(*SE, DstGEP, DstSubscripts, DstSizes);
  3086. // Check that the two size arrays are non-empty and equal in length and
  3087. // value.
  3088. if (SrcSizes.empty() || SrcSubscripts.size() <= 1 ||
  3089. SrcSizes.size() != DstSizes.size() ||
  3090. !std::equal(SrcSizes.begin(), SrcSizes.end(), DstSizes.begin())) {
  3091. SrcSubscripts.clear();
  3092. DstSubscripts.clear();
  3093. return false;
  3094. }
  3095. Value *SrcBasePtr = SrcGEP->getOperand(0);
  3096. Value *DstBasePtr = DstGEP->getOperand(0);
  3097. while (auto *PCast = dyn_cast<BitCastInst>(SrcBasePtr))
  3098. SrcBasePtr = PCast->getOperand(0);
  3099. while (auto *PCast = dyn_cast<BitCastInst>(DstBasePtr))
  3100. DstBasePtr = PCast->getOperand(0);
  3101. // Check that for identical base pointers we do not miss index offsets
  3102. // that have been added before this GEP is applied.
  3103. if (SrcBasePtr != SrcBase->getValue() || DstBasePtr != DstBase->getValue()) {
  3104. SrcSubscripts.clear();
  3105. DstSubscripts.clear();
  3106. return false;
  3107. }
  3108. assert(SrcSubscripts.size() == DstSubscripts.size() &&
  3109. SrcSubscripts.size() == SrcSizes.size() + 1 &&
  3110. "Expected equal number of entries in the list of sizes and "
  3111. "subscripts.");
  3112. // In general we cannot safely assume that the subscripts recovered from GEPs
  3113. // are in the range of values defined for their corresponding array
  3114. // dimensions. For example some C language usage/interpretation make it
  3115. // impossible to verify this at compile-time. As such we can only delinearize
  3116. // iff the subscripts are positive and are less than the range of the
  3117. // dimension.
  3118. if (!DisableDelinearizationChecks) {
  3119. auto AllIndiciesInRange = [&](SmallVector<int, 4> &DimensionSizes,
  3120. SmallVectorImpl<const SCEV *> &Subscripts,
  3121. Value *Ptr) {
  3122. size_t SSize = Subscripts.size();
  3123. for (size_t I = 1; I < SSize; ++I) {
  3124. const SCEV *S = Subscripts[I];
  3125. if (!isKnownNonNegative(S, Ptr))
  3126. return false;
  3127. if (auto *SType = dyn_cast<IntegerType>(S->getType())) {
  3128. const SCEV *Range = SE->getConstant(
  3129. ConstantInt::get(SType, DimensionSizes[I - 1], false));
  3130. if (!isKnownLessThan(S, Range))
  3131. return false;
  3132. }
  3133. }
  3134. return true;
  3135. };
  3136. if (!AllIndiciesInRange(SrcSizes, SrcSubscripts, SrcPtr) ||
  3137. !AllIndiciesInRange(DstSizes, DstSubscripts, DstPtr)) {
  3138. SrcSubscripts.clear();
  3139. DstSubscripts.clear();
  3140. return false;
  3141. }
  3142. }
  3143. LLVM_DEBUG({
  3144. dbgs() << "Delinearized subscripts of fixed-size array\n"
  3145. << "SrcGEP:" << *SrcGEP << "\n"
  3146. << "DstGEP:" << *DstGEP << "\n";
  3147. });
  3148. return true;
  3149. }
  3150. bool DependenceInfo::tryDelinearizeParametricSize(
  3151. Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
  3152. const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
  3153. SmallVectorImpl<const SCEV *> &DstSubscripts) {
  3154. Value *SrcPtr = getLoadStorePointerOperand(Src);
  3155. Value *DstPtr = getLoadStorePointerOperand(Dst);
  3156. const SCEVUnknown *SrcBase =
  3157. dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
  3158. const SCEVUnknown *DstBase =
  3159. dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
  3160. assert(SrcBase && DstBase && SrcBase == DstBase &&
  3161. "expected src and dst scev unknowns to be equal");
  3162. const SCEV *ElementSize = SE->getElementSize(Src);
  3163. if (ElementSize != SE->getElementSize(Dst))
  3164. return false;
  3165. const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
  3166. const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
  3167. const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
  3168. const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
  3169. if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
  3170. return false;
  3171. // First step: collect parametric terms in both array references.
  3172. SmallVector<const SCEV *, 4> Terms;
  3173. collectParametricTerms(*SE, SrcAR, Terms);
  3174. collectParametricTerms(*SE, DstAR, Terms);
  3175. // Second step: find subscript sizes.
  3176. SmallVector<const SCEV *, 4> Sizes;
  3177. findArrayDimensions(*SE, Terms, Sizes, ElementSize);
  3178. // Third step: compute the access functions for each subscript.
  3179. computeAccessFunctions(*SE, SrcAR, SrcSubscripts, Sizes);
  3180. computeAccessFunctions(*SE, DstAR, DstSubscripts, Sizes);
  3181. // Fail when there is only a subscript: that's a linearized access function.
  3182. if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
  3183. SrcSubscripts.size() != DstSubscripts.size())
  3184. return false;
  3185. size_t Size = SrcSubscripts.size();
  3186. // Statically check that the array bounds are in-range. The first subscript we
  3187. // don't have a size for and it cannot overflow into another subscript, so is
  3188. // always safe. The others need to be 0 <= subscript[i] < bound, for both src
  3189. // and dst.
  3190. // FIXME: It may be better to record these sizes and add them as constraints
  3191. // to the dependency checks.
  3192. if (!DisableDelinearizationChecks)
  3193. for (size_t I = 1; I < Size; ++I) {
  3194. if (!isKnownNonNegative(SrcSubscripts[I], SrcPtr))
  3195. return false;
  3196. if (!isKnownLessThan(SrcSubscripts[I], Sizes[I - 1]))
  3197. return false;
  3198. if (!isKnownNonNegative(DstSubscripts[I], DstPtr))
  3199. return false;
  3200. if (!isKnownLessThan(DstSubscripts[I], Sizes[I - 1]))
  3201. return false;
  3202. }
  3203. return true;
  3204. }
  3205. //===----------------------------------------------------------------------===//
  3206. #ifndef NDEBUG
  3207. // For debugging purposes, dump a small bit vector to dbgs().
  3208. static void dumpSmallBitVector(SmallBitVector &BV) {
  3209. dbgs() << "{";
  3210. for (unsigned VI : BV.set_bits()) {
  3211. dbgs() << VI;
  3212. if (BV.find_next(VI) >= 0)
  3213. dbgs() << ' ';
  3214. }
  3215. dbgs() << "}\n";
  3216. }
  3217. #endif
  3218. bool DependenceInfo::invalidate(Function &F, const PreservedAnalyses &PA,
  3219. FunctionAnalysisManager::Invalidator &Inv) {
  3220. // Check if the analysis itself has been invalidated.
  3221. auto PAC = PA.getChecker<DependenceAnalysis>();
  3222. if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
  3223. return true;
  3224. // Check transitive dependencies.
  3225. return Inv.invalidate<AAManager>(F, PA) ||
  3226. Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
  3227. Inv.invalidate<LoopAnalysis>(F, PA);
  3228. }
  3229. // depends -
  3230. // Returns NULL if there is no dependence.
  3231. // Otherwise, return a Dependence with as many details as possible.
  3232. // Corresponds to Section 3.1 in the paper
  3233. //
  3234. // Practical Dependence Testing
  3235. // Goff, Kennedy, Tseng
  3236. // PLDI 1991
  3237. //
  3238. // Care is required to keep the routine below, getSplitIteration(),
  3239. // up to date with respect to this routine.
  3240. std::unique_ptr<Dependence>
  3241. DependenceInfo::depends(Instruction *Src, Instruction *Dst,
  3242. bool PossiblyLoopIndependent) {
  3243. if (Src == Dst)
  3244. PossiblyLoopIndependent = false;
  3245. if (!(Src->mayReadOrWriteMemory() && Dst->mayReadOrWriteMemory()))
  3246. // if both instructions don't reference memory, there's no dependence
  3247. return nullptr;
  3248. if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
  3249. // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
  3250. LLVM_DEBUG(dbgs() << "can only handle simple loads and stores\n");
  3251. return std::make_unique<Dependence>(Src, Dst);
  3252. }
  3253. assert(isLoadOrStore(Src) && "instruction is not load or store");
  3254. assert(isLoadOrStore(Dst) && "instruction is not load or store");
  3255. Value *SrcPtr = getLoadStorePointerOperand(Src);
  3256. Value *DstPtr = getLoadStorePointerOperand(Dst);
  3257. switch (underlyingObjectsAlias(AA, F->getParent()->getDataLayout(),
  3258. MemoryLocation::get(Dst),
  3259. MemoryLocation::get(Src))) {
  3260. case AliasResult::MayAlias:
  3261. case AliasResult::PartialAlias:
  3262. // cannot analyse objects if we don't understand their aliasing.
  3263. LLVM_DEBUG(dbgs() << "can't analyze may or partial alias\n");
  3264. return std::make_unique<Dependence>(Src, Dst);
  3265. case AliasResult::NoAlias:
  3266. // If the objects noalias, they are distinct, accesses are independent.
  3267. LLVM_DEBUG(dbgs() << "no alias\n");
  3268. return nullptr;
  3269. case AliasResult::MustAlias:
  3270. break; // The underlying objects alias; test accesses for dependence.
  3271. }
  3272. // establish loop nesting levels
  3273. establishNestingLevels(Src, Dst);
  3274. LLVM_DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n");
  3275. LLVM_DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n");
  3276. FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels);
  3277. ++TotalArrayPairs;
  3278. unsigned Pairs = 1;
  3279. SmallVector<Subscript, 2> Pair(Pairs);
  3280. const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
  3281. const SCEV *DstSCEV = SE->getSCEV(DstPtr);
  3282. LLVM_DEBUG(dbgs() << " SrcSCEV = " << *SrcSCEV << "\n");
  3283. LLVM_DEBUG(dbgs() << " DstSCEV = " << *DstSCEV << "\n");
  3284. if (SE->getPointerBase(SrcSCEV) != SE->getPointerBase(DstSCEV)) {
  3285. // If two pointers have different bases, trying to analyze indexes won't
  3286. // work; we can't compare them to each other. This can happen, for example,
  3287. // if one is produced by an LCSSA PHI node.
  3288. //
  3289. // We check this upfront so we don't crash in cases where getMinusSCEV()
  3290. // returns a SCEVCouldNotCompute.
  3291. LLVM_DEBUG(dbgs() << "can't analyze SCEV with different pointer base\n");
  3292. return std::make_unique<Dependence>(Src, Dst);
  3293. }
  3294. Pair[0].Src = SrcSCEV;
  3295. Pair[0].Dst = DstSCEV;
  3296. if (Delinearize) {
  3297. if (tryDelinearize(Src, Dst, Pair)) {
  3298. LLVM_DEBUG(dbgs() << " delinearized\n");
  3299. Pairs = Pair.size();
  3300. }
  3301. }
  3302. for (unsigned P = 0; P < Pairs; ++P) {
  3303. Pair[P].Loops.resize(MaxLevels + 1);
  3304. Pair[P].GroupLoops.resize(MaxLevels + 1);
  3305. Pair[P].Group.resize(Pairs);
  3306. removeMatchingExtensions(&Pair[P]);
  3307. Pair[P].Classification =
  3308. classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
  3309. Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
  3310. Pair[P].Loops);
  3311. Pair[P].GroupLoops = Pair[P].Loops;
  3312. Pair[P].Group.set(P);
  3313. LLVM_DEBUG(dbgs() << " subscript " << P << "\n");
  3314. LLVM_DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
  3315. LLVM_DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
  3316. LLVM_DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
  3317. LLVM_DEBUG(dbgs() << "\tloops = ");
  3318. LLVM_DEBUG(dumpSmallBitVector(Pair[P].Loops));
  3319. }
  3320. SmallBitVector Separable(Pairs);
  3321. SmallBitVector Coupled(Pairs);
  3322. // Partition subscripts into separable and minimally-coupled groups
  3323. // Algorithm in paper is algorithmically better;
  3324. // this may be faster in practice. Check someday.
  3325. //
  3326. // Here's an example of how it works. Consider this code:
  3327. //
  3328. // for (i = ...) {
  3329. // for (j = ...) {
  3330. // for (k = ...) {
  3331. // for (l = ...) {
  3332. // for (m = ...) {
  3333. // A[i][j][k][m] = ...;
  3334. // ... = A[0][j][l][i + j];
  3335. // }
  3336. // }
  3337. // }
  3338. // }
  3339. // }
  3340. //
  3341. // There are 4 subscripts here:
  3342. // 0 [i] and [0]
  3343. // 1 [j] and [j]
  3344. // 2 [k] and [l]
  3345. // 3 [m] and [i + j]
  3346. //
  3347. // We've already classified each subscript pair as ZIV, SIV, etc.,
  3348. // and collected all the loops mentioned by pair P in Pair[P].Loops.
  3349. // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops
  3350. // and set Pair[P].Group = {P}.
  3351. //
  3352. // Src Dst Classification Loops GroupLoops Group
  3353. // 0 [i] [0] SIV {1} {1} {0}
  3354. // 1 [j] [j] SIV {2} {2} {1}
  3355. // 2 [k] [l] RDIV {3,4} {3,4} {2}
  3356. // 3 [m] [i + j] MIV {1,2,5} {1,2,5} {3}
  3357. //
  3358. // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ.
  3359. // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc.
  3360. //
  3361. // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty.
  3362. // Next, 0 and 2. Again, the intersection of their GroupLoops is empty.
  3363. // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty,
  3364. // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added
  3365. // to either Separable or Coupled).
  3366. //
  3367. // Next, we consider 1 and 2. The intersection of the GroupLoops is empty.
  3368. // Next, 1 and 3. The intersection of their GroupLoops = {2}, not empty,
  3369. // so Pair[3].Group = {0, 1, 3} and Done = false.
  3370. //
  3371. // Next, we compare 2 against 3. The intersection of the GroupLoops is empty.
  3372. // Since Done remains true, we add 2 to the set of Separable pairs.
  3373. //
  3374. // Finally, we consider 3. There's nothing to compare it with,
  3375. // so Done remains true and we add it to the Coupled set.
  3376. // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}.
  3377. //
  3378. // In the end, we've got 1 separable subscript and 1 coupled group.
  3379. for (unsigned SI = 0; SI < Pairs; ++SI) {
  3380. if (Pair[SI].Classification == Subscript::NonLinear) {
  3381. // ignore these, but collect loops for later
  3382. ++NonlinearSubscriptPairs;
  3383. collectCommonLoops(Pair[SI].Src,
  3384. LI->getLoopFor(Src->getParent()),
  3385. Pair[SI].Loops);
  3386. collectCommonLoops(Pair[SI].Dst,
  3387. LI->getLoopFor(Dst->getParent()),
  3388. Pair[SI].Loops);
  3389. Result.Consistent = false;
  3390. } else if (Pair[SI].Classification == Subscript::ZIV) {
  3391. // always separable
  3392. Separable.set(SI);
  3393. }
  3394. else {
  3395. // SIV, RDIV, or MIV, so check for coupled group
  3396. bool Done = true;
  3397. for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
  3398. SmallBitVector Intersection = Pair[SI].GroupLoops;
  3399. Intersection &= Pair[SJ].GroupLoops;
  3400. if (Intersection.any()) {
  3401. // accumulate set of all the loops in group
  3402. Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
  3403. // accumulate set of all subscripts in group
  3404. Pair[SJ].Group |= Pair[SI].Group;
  3405. Done = false;
  3406. }
  3407. }
  3408. if (Done) {
  3409. if (Pair[SI].Group.count() == 1) {
  3410. Separable.set(SI);
  3411. ++SeparableSubscriptPairs;
  3412. }
  3413. else {
  3414. Coupled.set(SI);
  3415. ++CoupledSubscriptPairs;
  3416. }
  3417. }
  3418. }
  3419. }
  3420. LLVM_DEBUG(dbgs() << " Separable = ");
  3421. LLVM_DEBUG(dumpSmallBitVector(Separable));
  3422. LLVM_DEBUG(dbgs() << " Coupled = ");
  3423. LLVM_DEBUG(dumpSmallBitVector(Coupled));
  3424. Constraint NewConstraint;
  3425. NewConstraint.setAny(SE);
  3426. // test separable subscripts
  3427. for (unsigned SI : Separable.set_bits()) {
  3428. LLVM_DEBUG(dbgs() << "testing subscript " << SI);
  3429. switch (Pair[SI].Classification) {
  3430. case Subscript::ZIV:
  3431. LLVM_DEBUG(dbgs() << ", ZIV\n");
  3432. if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
  3433. return nullptr;
  3434. break;
  3435. case Subscript::SIV: {
  3436. LLVM_DEBUG(dbgs() << ", SIV\n");
  3437. unsigned Level;
  3438. const SCEV *SplitIter = nullptr;
  3439. if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result, NewConstraint,
  3440. SplitIter))
  3441. return nullptr;
  3442. break;
  3443. }
  3444. case Subscript::RDIV:
  3445. LLVM_DEBUG(dbgs() << ", RDIV\n");
  3446. if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
  3447. return nullptr;
  3448. break;
  3449. case Subscript::MIV:
  3450. LLVM_DEBUG(dbgs() << ", MIV\n");
  3451. if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
  3452. return nullptr;
  3453. break;
  3454. default:
  3455. llvm_unreachable("subscript has unexpected classification");
  3456. }
  3457. }
  3458. if (Coupled.count()) {
  3459. // test coupled subscript groups
  3460. LLVM_DEBUG(dbgs() << "starting on coupled subscripts\n");
  3461. LLVM_DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n");
  3462. SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
  3463. for (unsigned II = 0; II <= MaxLevels; ++II)
  3464. Constraints[II].setAny(SE);
  3465. for (unsigned SI : Coupled.set_bits()) {
  3466. LLVM_DEBUG(dbgs() << "testing subscript group " << SI << " { ");
  3467. SmallBitVector Group(Pair[SI].Group);
  3468. SmallBitVector Sivs(Pairs);
  3469. SmallBitVector Mivs(Pairs);
  3470. SmallBitVector ConstrainedLevels(MaxLevels + 1);
  3471. SmallVector<Subscript *, 4> PairsInGroup;
  3472. for (unsigned SJ : Group.set_bits()) {
  3473. LLVM_DEBUG(dbgs() << SJ << " ");
  3474. if (Pair[SJ].Classification == Subscript::SIV)
  3475. Sivs.set(SJ);
  3476. else
  3477. Mivs.set(SJ);
  3478. PairsInGroup.push_back(&Pair[SJ]);
  3479. }
  3480. unifySubscriptType(PairsInGroup);
  3481. LLVM_DEBUG(dbgs() << "}\n");
  3482. while (Sivs.any()) {
  3483. bool Changed = false;
  3484. for (unsigned SJ : Sivs.set_bits()) {
  3485. LLVM_DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
  3486. // SJ is an SIV subscript that's part of the current coupled group
  3487. unsigned Level;
  3488. const SCEV *SplitIter = nullptr;
  3489. LLVM_DEBUG(dbgs() << "SIV\n");
  3490. if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level, Result, NewConstraint,
  3491. SplitIter))
  3492. return nullptr;
  3493. ConstrainedLevels.set(Level);
  3494. if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
  3495. if (Constraints[Level].isEmpty()) {
  3496. ++DeltaIndependence;
  3497. return nullptr;
  3498. }
  3499. Changed = true;
  3500. }
  3501. Sivs.reset(SJ);
  3502. }
  3503. if (Changed) {
  3504. // propagate, possibly creating new SIVs and ZIVs
  3505. LLVM_DEBUG(dbgs() << " propagating\n");
  3506. LLVM_DEBUG(dbgs() << "\tMivs = ");
  3507. LLVM_DEBUG(dumpSmallBitVector(Mivs));
  3508. for (unsigned SJ : Mivs.set_bits()) {
  3509. // SJ is an MIV subscript that's part of the current coupled group
  3510. LLVM_DEBUG(dbgs() << "\tSJ = " << SJ << "\n");
  3511. if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops,
  3512. Constraints, Result.Consistent)) {
  3513. LLVM_DEBUG(dbgs() << "\t Changed\n");
  3514. ++DeltaPropagations;
  3515. Pair[SJ].Classification =
  3516. classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
  3517. Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
  3518. Pair[SJ].Loops);
  3519. switch (Pair[SJ].Classification) {
  3520. case Subscript::ZIV:
  3521. LLVM_DEBUG(dbgs() << "ZIV\n");
  3522. if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
  3523. return nullptr;
  3524. Mivs.reset(SJ);
  3525. break;
  3526. case Subscript::SIV:
  3527. Sivs.set(SJ);
  3528. Mivs.reset(SJ);
  3529. break;
  3530. case Subscript::RDIV:
  3531. case Subscript::MIV:
  3532. break;
  3533. default:
  3534. llvm_unreachable("bad subscript classification");
  3535. }
  3536. }
  3537. }
  3538. }
  3539. }
  3540. // test & propagate remaining RDIVs
  3541. for (unsigned SJ : Mivs.set_bits()) {
  3542. if (Pair[SJ].Classification == Subscript::RDIV) {
  3543. LLVM_DEBUG(dbgs() << "RDIV test\n");
  3544. if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
  3545. return nullptr;
  3546. // I don't yet understand how to propagate RDIV results
  3547. Mivs.reset(SJ);
  3548. }
  3549. }
  3550. // test remaining MIVs
  3551. // This code is temporary.
  3552. // Better to somehow test all remaining subscripts simultaneously.
  3553. for (unsigned SJ : Mivs.set_bits()) {
  3554. if (Pair[SJ].Classification == Subscript::MIV) {
  3555. LLVM_DEBUG(dbgs() << "MIV test\n");
  3556. if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
  3557. return nullptr;
  3558. }
  3559. else
  3560. llvm_unreachable("expected only MIV subscripts at this point");
  3561. }
  3562. // update Result.DV from constraint vector
  3563. LLVM_DEBUG(dbgs() << " updating\n");
  3564. for (unsigned SJ : ConstrainedLevels.set_bits()) {
  3565. if (SJ > CommonLevels)
  3566. break;
  3567. updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
  3568. if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
  3569. return nullptr;
  3570. }
  3571. }
  3572. }
  3573. // Make sure the Scalar flags are set correctly.
  3574. SmallBitVector CompleteLoops(MaxLevels + 1);
  3575. for (unsigned SI = 0; SI < Pairs; ++SI)
  3576. CompleteLoops |= Pair[SI].Loops;
  3577. for (unsigned II = 1; II <= CommonLevels; ++II)
  3578. if (CompleteLoops[II])
  3579. Result.DV[II - 1].Scalar = false;
  3580. if (PossiblyLoopIndependent) {
  3581. // Make sure the LoopIndependent flag is set correctly.
  3582. // All directions must include equal, otherwise no
  3583. // loop-independent dependence is possible.
  3584. for (unsigned II = 1; II <= CommonLevels; ++II) {
  3585. if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
  3586. Result.LoopIndependent = false;
  3587. break;
  3588. }
  3589. }
  3590. }
  3591. else {
  3592. // On the other hand, if all directions are equal and there's no
  3593. // loop-independent dependence possible, then no dependence exists.
  3594. bool AllEqual = true;
  3595. for (unsigned II = 1; II <= CommonLevels; ++II) {
  3596. if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
  3597. AllEqual = false;
  3598. break;
  3599. }
  3600. }
  3601. if (AllEqual)
  3602. return nullptr;
  3603. }
  3604. return std::make_unique<FullDependence>(std::move(Result));
  3605. }
  3606. //===----------------------------------------------------------------------===//
  3607. // getSplitIteration -
  3608. // Rather than spend rarely-used space recording the splitting iteration
  3609. // during the Weak-Crossing SIV test, we re-compute it on demand.
  3610. // The re-computation is basically a repeat of the entire dependence test,
  3611. // though simplified since we know that the dependence exists.
  3612. // It's tedious, since we must go through all propagations, etc.
  3613. //
  3614. // Care is required to keep this code up to date with respect to the routine
  3615. // above, depends().
  3616. //
  3617. // Generally, the dependence analyzer will be used to build
  3618. // a dependence graph for a function (basically a map from instructions
  3619. // to dependences). Looking for cycles in the graph shows us loops
  3620. // that cannot be trivially vectorized/parallelized.
  3621. //
  3622. // We can try to improve the situation by examining all the dependences
  3623. // that make up the cycle, looking for ones we can break.
  3624. // Sometimes, peeling the first or last iteration of a loop will break
  3625. // dependences, and we've got flags for those possibilities.
  3626. // Sometimes, splitting a loop at some other iteration will do the trick,
  3627. // and we've got a flag for that case. Rather than waste the space to
  3628. // record the exact iteration (since we rarely know), we provide
  3629. // a method that calculates the iteration. It's a drag that it must work
  3630. // from scratch, but wonderful in that it's possible.
  3631. //
  3632. // Here's an example:
  3633. //
  3634. // for (i = 0; i < 10; i++)
  3635. // A[i] = ...
  3636. // ... = A[11 - i]
  3637. //
  3638. // There's a loop-carried flow dependence from the store to the load,
  3639. // found by the weak-crossing SIV test. The dependence will have a flag,
  3640. // indicating that the dependence can be broken by splitting the loop.
  3641. // Calling getSplitIteration will return 5.
  3642. // Splitting the loop breaks the dependence, like so:
  3643. //
  3644. // for (i = 0; i <= 5; i++)
  3645. // A[i] = ...
  3646. // ... = A[11 - i]
  3647. // for (i = 6; i < 10; i++)
  3648. // A[i] = ...
  3649. // ... = A[11 - i]
  3650. //
  3651. // breaks the dependence and allows us to vectorize/parallelize
  3652. // both loops.
  3653. const SCEV *DependenceInfo::getSplitIteration(const Dependence &Dep,
  3654. unsigned SplitLevel) {
  3655. assert(Dep.isSplitable(SplitLevel) &&
  3656. "Dep should be splitable at SplitLevel");
  3657. Instruction *Src = Dep.getSrc();
  3658. Instruction *Dst = Dep.getDst();
  3659. assert(Src->mayReadFromMemory() || Src->mayWriteToMemory());
  3660. assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory());
  3661. assert(isLoadOrStore(Src));
  3662. assert(isLoadOrStore(Dst));
  3663. Value *SrcPtr = getLoadStorePointerOperand(Src);
  3664. Value *DstPtr = getLoadStorePointerOperand(Dst);
  3665. assert(underlyingObjectsAlias(
  3666. AA, F->getParent()->getDataLayout(), MemoryLocation::get(Dst),
  3667. MemoryLocation::get(Src)) == AliasResult::MustAlias);
  3668. // establish loop nesting levels
  3669. establishNestingLevels(Src, Dst);
  3670. FullDependence Result(Src, Dst, false, CommonLevels);
  3671. unsigned Pairs = 1;
  3672. SmallVector<Subscript, 2> Pair(Pairs);
  3673. const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
  3674. const SCEV *DstSCEV = SE->getSCEV(DstPtr);
  3675. Pair[0].Src = SrcSCEV;
  3676. Pair[0].Dst = DstSCEV;
  3677. if (Delinearize) {
  3678. if (tryDelinearize(Src, Dst, Pair)) {
  3679. LLVM_DEBUG(dbgs() << " delinearized\n");
  3680. Pairs = Pair.size();
  3681. }
  3682. }
  3683. for (unsigned P = 0; P < Pairs; ++P) {
  3684. Pair[P].Loops.resize(MaxLevels + 1);
  3685. Pair[P].GroupLoops.resize(MaxLevels + 1);
  3686. Pair[P].Group.resize(Pairs);
  3687. removeMatchingExtensions(&Pair[P]);
  3688. Pair[P].Classification =
  3689. classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
  3690. Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
  3691. Pair[P].Loops);
  3692. Pair[P].GroupLoops = Pair[P].Loops;
  3693. Pair[P].Group.set(P);
  3694. }
  3695. SmallBitVector Separable(Pairs);
  3696. SmallBitVector Coupled(Pairs);
  3697. // partition subscripts into separable and minimally-coupled groups
  3698. for (unsigned SI = 0; SI < Pairs; ++SI) {
  3699. if (Pair[SI].Classification == Subscript::NonLinear) {
  3700. // ignore these, but collect loops for later
  3701. collectCommonLoops(Pair[SI].Src,
  3702. LI->getLoopFor(Src->getParent()),
  3703. Pair[SI].Loops);
  3704. collectCommonLoops(Pair[SI].Dst,
  3705. LI->getLoopFor(Dst->getParent()),
  3706. Pair[SI].Loops);
  3707. Result.Consistent = false;
  3708. }
  3709. else if (Pair[SI].Classification == Subscript::ZIV)
  3710. Separable.set(SI);
  3711. else {
  3712. // SIV, RDIV, or MIV, so check for coupled group
  3713. bool Done = true;
  3714. for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
  3715. SmallBitVector Intersection = Pair[SI].GroupLoops;
  3716. Intersection &= Pair[SJ].GroupLoops;
  3717. if (Intersection.any()) {
  3718. // accumulate set of all the loops in group
  3719. Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
  3720. // accumulate set of all subscripts in group
  3721. Pair[SJ].Group |= Pair[SI].Group;
  3722. Done = false;
  3723. }
  3724. }
  3725. if (Done) {
  3726. if (Pair[SI].Group.count() == 1)
  3727. Separable.set(SI);
  3728. else
  3729. Coupled.set(SI);
  3730. }
  3731. }
  3732. }
  3733. Constraint NewConstraint;
  3734. NewConstraint.setAny(SE);
  3735. // test separable subscripts
  3736. for (unsigned SI : Separable.set_bits()) {
  3737. switch (Pair[SI].Classification) {
  3738. case Subscript::SIV: {
  3739. unsigned Level;
  3740. const SCEV *SplitIter = nullptr;
  3741. (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
  3742. Result, NewConstraint, SplitIter);
  3743. if (Level == SplitLevel) {
  3744. assert(SplitIter != nullptr);
  3745. return SplitIter;
  3746. }
  3747. break;
  3748. }
  3749. case Subscript::ZIV:
  3750. case Subscript::RDIV:
  3751. case Subscript::MIV:
  3752. break;
  3753. default:
  3754. llvm_unreachable("subscript has unexpected classification");
  3755. }
  3756. }
  3757. if (Coupled.count()) {
  3758. // test coupled subscript groups
  3759. SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
  3760. for (unsigned II = 0; II <= MaxLevels; ++II)
  3761. Constraints[II].setAny(SE);
  3762. for (unsigned SI : Coupled.set_bits()) {
  3763. SmallBitVector Group(Pair[SI].Group);
  3764. SmallBitVector Sivs(Pairs);
  3765. SmallBitVector Mivs(Pairs);
  3766. SmallBitVector ConstrainedLevels(MaxLevels + 1);
  3767. for (unsigned SJ : Group.set_bits()) {
  3768. if (Pair[SJ].Classification == Subscript::SIV)
  3769. Sivs.set(SJ);
  3770. else
  3771. Mivs.set(SJ);
  3772. }
  3773. while (Sivs.any()) {
  3774. bool Changed = false;
  3775. for (unsigned SJ : Sivs.set_bits()) {
  3776. // SJ is an SIV subscript that's part of the current coupled group
  3777. unsigned Level;
  3778. const SCEV *SplitIter = nullptr;
  3779. (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
  3780. Result, NewConstraint, SplitIter);
  3781. if (Level == SplitLevel && SplitIter)
  3782. return SplitIter;
  3783. ConstrainedLevels.set(Level);
  3784. if (intersectConstraints(&Constraints[Level], &NewConstraint))
  3785. Changed = true;
  3786. Sivs.reset(SJ);
  3787. }
  3788. if (Changed) {
  3789. // propagate, possibly creating new SIVs and ZIVs
  3790. for (unsigned SJ : Mivs.set_bits()) {
  3791. // SJ is an MIV subscript that's part of the current coupled group
  3792. if (propagate(Pair[SJ].Src, Pair[SJ].Dst,
  3793. Pair[SJ].Loops, Constraints, Result.Consistent)) {
  3794. Pair[SJ].Classification =
  3795. classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
  3796. Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
  3797. Pair[SJ].Loops);
  3798. switch (Pair[SJ].Classification) {
  3799. case Subscript::ZIV:
  3800. Mivs.reset(SJ);
  3801. break;
  3802. case Subscript::SIV:
  3803. Sivs.set(SJ);
  3804. Mivs.reset(SJ);
  3805. break;
  3806. case Subscript::RDIV:
  3807. case Subscript::MIV:
  3808. break;
  3809. default:
  3810. llvm_unreachable("bad subscript classification");
  3811. }
  3812. }
  3813. }
  3814. }
  3815. }
  3816. }
  3817. }
  3818. llvm_unreachable("somehow reached end of routine");
  3819. return nullptr;
  3820. }