2
0

DependenceAnalysis.cpp 148 KB

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