BBVectorize.cpp 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242
  1. //===- BBVectorize.cpp - A Basic-Block Vectorizer -------------------------===//
  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. // This file implements a basic-block vectorization pass. The algorithm was
  11. // inspired by that used by the Vienna MAP Vectorizor by Franchetti and Kral,
  12. // et al. It works by looking for chains of pairable operations and then
  13. // pairing them.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #define BBV_NAME "bb-vectorize"
  17. #include "llvm/Transforms/Vectorize.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/DenseSet.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/SmallSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/Analysis/AliasSetTracker.h"
  27. #include "llvm/Analysis/ScalarEvolution.h"
  28. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  29. #include "llvm/Analysis/TargetTransformInfo.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DataLayout.h"
  33. #include "llvm/IR/DerivedTypes.h"
  34. #include "llvm/IR/Dominators.h"
  35. #include "llvm/IR/Function.h"
  36. #include "llvm/IR/Instructions.h"
  37. #include "llvm/IR/IntrinsicInst.h"
  38. #include "llvm/IR/Intrinsics.h"
  39. #include "llvm/IR/LLVMContext.h"
  40. #include "llvm/IR/Metadata.h"
  41. #include "llvm/IR/Module.h"
  42. #include "llvm/IR/Type.h"
  43. #include "llvm/IR/ValueHandle.h"
  44. #include "llvm/Pass.h"
  45. #include "llvm/Support/CommandLine.h"
  46. #include "llvm/Support/Debug.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Transforms/Utils/Local.h"
  49. #include <algorithm>
  50. using namespace llvm;
  51. #define DEBUG_TYPE BBV_NAME
  52. static cl::opt<bool>
  53. IgnoreTargetInfo("bb-vectorize-ignore-target-info", cl::init(false),
  54. cl::Hidden, cl::desc("Ignore target information"));
  55. static cl::opt<unsigned>
  56. ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
  57. cl::desc("The required chain depth for vectorization"));
  58. static cl::opt<bool>
  59. UseChainDepthWithTI("bb-vectorize-use-chain-depth", cl::init(false),
  60. cl::Hidden, cl::desc("Use the chain depth requirement with"
  61. " target information"));
  62. static cl::opt<unsigned>
  63. SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
  64. cl::desc("The maximum search distance for instruction pairs"));
  65. static cl::opt<bool>
  66. SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
  67. cl::desc("Replicating one element to a pair breaks the chain"));
  68. static cl::opt<unsigned>
  69. VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
  70. cl::desc("The size of the native vector registers"));
  71. static cl::opt<unsigned>
  72. MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
  73. cl::desc("The maximum number of pairing iterations"));
  74. static cl::opt<bool>
  75. Pow2LenOnly("bb-vectorize-pow2-len-only", cl::init(false), cl::Hidden,
  76. cl::desc("Don't try to form non-2^n-length vectors"));
  77. static cl::opt<unsigned>
  78. MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
  79. cl::desc("The maximum number of pairable instructions per group"));
  80. static cl::opt<unsigned>
  81. MaxPairs("bb-vectorize-max-pairs-per-group", cl::init(3000), cl::Hidden,
  82. cl::desc("The maximum number of candidate instruction pairs per group"));
  83. static cl::opt<unsigned>
  84. MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
  85. cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
  86. " a full cycle check"));
  87. static cl::opt<bool>
  88. NoBools("bb-vectorize-no-bools", cl::init(false), cl::Hidden,
  89. cl::desc("Don't try to vectorize boolean (i1) values"));
  90. static cl::opt<bool>
  91. NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
  92. cl::desc("Don't try to vectorize integer values"));
  93. static cl::opt<bool>
  94. NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
  95. cl::desc("Don't try to vectorize floating-point values"));
  96. // FIXME: This should default to false once pointer vector support works.
  97. static cl::opt<bool>
  98. NoPointers("bb-vectorize-no-pointers", cl::init(/*false*/ true), cl::Hidden,
  99. cl::desc("Don't try to vectorize pointer values"));
  100. static cl::opt<bool>
  101. NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
  102. cl::desc("Don't try to vectorize casting (conversion) operations"));
  103. static cl::opt<bool>
  104. NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
  105. cl::desc("Don't try to vectorize floating-point math intrinsics"));
  106. static cl::opt<bool>
  107. NoBitManipulation("bb-vectorize-no-bitmanip", cl::init(false), cl::Hidden,
  108. cl::desc("Don't try to vectorize BitManipulation intrinsics"));
  109. static cl::opt<bool>
  110. NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
  111. cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
  112. static cl::opt<bool>
  113. NoSelect("bb-vectorize-no-select", cl::init(false), cl::Hidden,
  114. cl::desc("Don't try to vectorize select instructions"));
  115. static cl::opt<bool>
  116. NoCmp("bb-vectorize-no-cmp", cl::init(false), cl::Hidden,
  117. cl::desc("Don't try to vectorize comparison instructions"));
  118. static cl::opt<bool>
  119. NoGEP("bb-vectorize-no-gep", cl::init(false), cl::Hidden,
  120. cl::desc("Don't try to vectorize getelementptr instructions"));
  121. static cl::opt<bool>
  122. NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
  123. cl::desc("Don't try to vectorize loads and stores"));
  124. static cl::opt<bool>
  125. AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
  126. cl::desc("Only generate aligned loads and stores"));
  127. static cl::opt<bool>
  128. NoMemOpBoost("bb-vectorize-no-mem-op-boost",
  129. cl::init(false), cl::Hidden,
  130. cl::desc("Don't boost the chain-depth contribution of loads and stores"));
  131. static cl::opt<bool>
  132. FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
  133. cl::desc("Use a fast instruction dependency analysis"));
  134. #ifndef NDEBUG
  135. static cl::opt<bool>
  136. DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
  137. cl::init(false), cl::Hidden,
  138. cl::desc("When debugging is enabled, output information on the"
  139. " instruction-examination process"));
  140. static cl::opt<bool>
  141. DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
  142. cl::init(false), cl::Hidden,
  143. cl::desc("When debugging is enabled, output information on the"
  144. " candidate-selection process"));
  145. static cl::opt<bool>
  146. DebugPairSelection("bb-vectorize-debug-pair-selection",
  147. cl::init(false), cl::Hidden,
  148. cl::desc("When debugging is enabled, output information on the"
  149. " pair-selection process"));
  150. static cl::opt<bool>
  151. DebugCycleCheck("bb-vectorize-debug-cycle-check",
  152. cl::init(false), cl::Hidden,
  153. cl::desc("When debugging is enabled, output information on the"
  154. " cycle-checking process"));
  155. static cl::opt<bool>
  156. PrintAfterEveryPair("bb-vectorize-debug-print-after-every-pair",
  157. cl::init(false), cl::Hidden,
  158. cl::desc("When debugging is enabled, dump the basic block after"
  159. " every pair is fused"));
  160. #endif
  161. STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
  162. namespace {
  163. struct BBVectorize : public BasicBlockPass {
  164. static char ID; // Pass identification, replacement for typeid
  165. const VectorizeConfig Config;
  166. BBVectorize(const VectorizeConfig &C = VectorizeConfig())
  167. : BasicBlockPass(ID), Config(C) {
  168. initializeBBVectorizePass(*PassRegistry::getPassRegistry());
  169. }
  170. BBVectorize(Pass *P, Function &F, const VectorizeConfig &C)
  171. : BasicBlockPass(ID), Config(C) {
  172. AA = &P->getAnalysis<AliasAnalysis>();
  173. DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  174. SE = &P->getAnalysis<ScalarEvolution>();
  175. TTI = IgnoreTargetInfo
  176. ? nullptr
  177. : &P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  178. }
  179. typedef std::pair<Value *, Value *> ValuePair;
  180. typedef std::pair<ValuePair, int> ValuePairWithCost;
  181. typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
  182. typedef std::pair<ValuePair, ValuePair> VPPair; // A ValuePair pair
  183. typedef std::pair<VPPair, unsigned> VPPairWithType;
  184. AliasAnalysis *AA;
  185. DominatorTree *DT;
  186. ScalarEvolution *SE;
  187. const TargetTransformInfo *TTI;
  188. // FIXME: const correct?
  189. bool vectorizePairs(BasicBlock &BB, bool NonPow2Len = false);
  190. bool getCandidatePairs(BasicBlock &BB,
  191. BasicBlock::iterator &Start,
  192. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  193. DenseSet<ValuePair> &FixedOrderPairs,
  194. DenseMap<ValuePair, int> &CandidatePairCostSavings,
  195. std::vector<Value *> &PairableInsts, bool NonPow2Len);
  196. // FIXME: The current implementation does not account for pairs that
  197. // are connected in multiple ways. For example:
  198. // C1 = A1 / A2; C2 = A2 / A1 (which may be both direct and a swap)
  199. enum PairConnectionType {
  200. PairConnectionDirect,
  201. PairConnectionSwap,
  202. PairConnectionSplat
  203. };
  204. void computeConnectedPairs(
  205. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  206. DenseSet<ValuePair> &CandidatePairsSet,
  207. std::vector<Value *> &PairableInsts,
  208. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  209. DenseMap<VPPair, unsigned> &PairConnectionTypes);
  210. void buildDepMap(BasicBlock &BB,
  211. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  212. std::vector<Value *> &PairableInsts,
  213. DenseSet<ValuePair> &PairableInstUsers);
  214. void choosePairs(DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  215. DenseSet<ValuePair> &CandidatePairsSet,
  216. DenseMap<ValuePair, int> &CandidatePairCostSavings,
  217. std::vector<Value *> &PairableInsts,
  218. DenseSet<ValuePair> &FixedOrderPairs,
  219. DenseMap<VPPair, unsigned> &PairConnectionTypes,
  220. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  221. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
  222. DenseSet<ValuePair> &PairableInstUsers,
  223. DenseMap<Value *, Value *>& ChosenPairs);
  224. void fuseChosenPairs(BasicBlock &BB,
  225. std::vector<Value *> &PairableInsts,
  226. DenseMap<Value *, Value *>& ChosenPairs,
  227. DenseSet<ValuePair> &FixedOrderPairs,
  228. DenseMap<VPPair, unsigned> &PairConnectionTypes,
  229. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  230. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps);
  231. bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
  232. bool areInstsCompatible(Instruction *I, Instruction *J,
  233. bool IsSimpleLoadStore, bool NonPow2Len,
  234. int &CostSavings, int &FixedOrder);
  235. bool trackUsesOfI(DenseSet<Value *> &Users,
  236. AliasSetTracker &WriteSet, Instruction *I,
  237. Instruction *J, bool UpdateUsers = true,
  238. DenseSet<ValuePair> *LoadMoveSetPairs = nullptr);
  239. void computePairsConnectedTo(
  240. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  241. DenseSet<ValuePair> &CandidatePairsSet,
  242. std::vector<Value *> &PairableInsts,
  243. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  244. DenseMap<VPPair, unsigned> &PairConnectionTypes,
  245. ValuePair P);
  246. bool pairsConflict(ValuePair P, ValuePair Q,
  247. DenseSet<ValuePair> &PairableInstUsers,
  248. DenseMap<ValuePair, std::vector<ValuePair> >
  249. *PairableInstUserMap = nullptr,
  250. DenseSet<VPPair> *PairableInstUserPairSet = nullptr);
  251. bool pairWillFormCycle(ValuePair P,
  252. DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUsers,
  253. DenseSet<ValuePair> &CurrentPairs);
  254. void pruneDAGFor(
  255. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  256. std::vector<Value *> &PairableInsts,
  257. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  258. DenseSet<ValuePair> &PairableInstUsers,
  259. DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
  260. DenseSet<VPPair> &PairableInstUserPairSet,
  261. DenseMap<Value *, Value *> &ChosenPairs,
  262. DenseMap<ValuePair, size_t> &DAG,
  263. DenseSet<ValuePair> &PrunedDAG, ValuePair J,
  264. bool UseCycleCheck);
  265. void buildInitialDAGFor(
  266. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  267. DenseSet<ValuePair> &CandidatePairsSet,
  268. std::vector<Value *> &PairableInsts,
  269. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  270. DenseSet<ValuePair> &PairableInstUsers,
  271. DenseMap<Value *, Value *> &ChosenPairs,
  272. DenseMap<ValuePair, size_t> &DAG, ValuePair J);
  273. void findBestDAGFor(
  274. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  275. DenseSet<ValuePair> &CandidatePairsSet,
  276. DenseMap<ValuePair, int> &CandidatePairCostSavings,
  277. std::vector<Value *> &PairableInsts,
  278. DenseSet<ValuePair> &FixedOrderPairs,
  279. DenseMap<VPPair, unsigned> &PairConnectionTypes,
  280. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  281. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
  282. DenseSet<ValuePair> &PairableInstUsers,
  283. DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
  284. DenseSet<VPPair> &PairableInstUserPairSet,
  285. DenseMap<Value *, Value *> &ChosenPairs,
  286. DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
  287. int &BestEffSize, Value *II, std::vector<Value *>&JJ,
  288. bool UseCycleCheck);
  289. Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
  290. Instruction *J, unsigned o);
  291. void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
  292. unsigned MaskOffset, unsigned NumInElem,
  293. unsigned NumInElem1, unsigned IdxOffset,
  294. std::vector<Constant*> &Mask);
  295. Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
  296. Instruction *J);
  297. bool expandIEChain(LLVMContext& Context, Instruction *I, Instruction *J,
  298. unsigned o, Value *&LOp, unsigned numElemL,
  299. Type *ArgTypeL, Type *ArgTypeR, bool IBeforeJ,
  300. unsigned IdxOff = 0);
  301. Value *getReplacementInput(LLVMContext& Context, Instruction *I,
  302. Instruction *J, unsigned o, bool IBeforeJ);
  303. void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
  304. Instruction *J, SmallVectorImpl<Value *> &ReplacedOperands,
  305. bool IBeforeJ);
  306. void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
  307. Instruction *J, Instruction *K,
  308. Instruction *&InsertionPt, Instruction *&K1,
  309. Instruction *&K2);
  310. void collectPairLoadMoveSet(BasicBlock &BB,
  311. DenseMap<Value *, Value *> &ChosenPairs,
  312. DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
  313. DenseSet<ValuePair> &LoadMoveSetPairs,
  314. Instruction *I);
  315. void collectLoadMoveSet(BasicBlock &BB,
  316. std::vector<Value *> &PairableInsts,
  317. DenseMap<Value *, Value *> &ChosenPairs,
  318. DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
  319. DenseSet<ValuePair> &LoadMoveSetPairs);
  320. bool canMoveUsesOfIAfterJ(BasicBlock &BB,
  321. DenseSet<ValuePair> &LoadMoveSetPairs,
  322. Instruction *I, Instruction *J);
  323. void moveUsesOfIAfterJ(BasicBlock &BB,
  324. DenseSet<ValuePair> &LoadMoveSetPairs,
  325. Instruction *&InsertionPt,
  326. Instruction *I, Instruction *J);
  327. bool vectorizeBB(BasicBlock &BB) {
  328. if (skipOptnoneFunction(BB))
  329. return false;
  330. if (!DT->isReachableFromEntry(&BB)) {
  331. DEBUG(dbgs() << "BBV: skipping unreachable " << BB.getName() <<
  332. " in " << BB.getParent()->getName() << "\n");
  333. return false;
  334. }
  335. DEBUG(if (TTI) dbgs() << "BBV: using target information\n");
  336. bool changed = false;
  337. // Iterate a sufficient number of times to merge types of size 1 bit,
  338. // then 2 bits, then 4, etc. up to half of the target vector width of the
  339. // target vector register.
  340. unsigned n = 1;
  341. for (unsigned v = 2;
  342. (TTI || v <= Config.VectorBits) &&
  343. (!Config.MaxIter || n <= Config.MaxIter);
  344. v *= 2, ++n) {
  345. DEBUG(dbgs() << "BBV: fusing loop #" << n <<
  346. " for " << BB.getName() << " in " <<
  347. BB.getParent()->getName() << "...\n");
  348. if (vectorizePairs(BB))
  349. changed = true;
  350. else
  351. break;
  352. }
  353. if (changed && !Pow2LenOnly) {
  354. ++n;
  355. for (; !Config.MaxIter || n <= Config.MaxIter; ++n) {
  356. DEBUG(dbgs() << "BBV: fusing for non-2^n-length vectors loop #: " <<
  357. n << " for " << BB.getName() << " in " <<
  358. BB.getParent()->getName() << "...\n");
  359. if (!vectorizePairs(BB, true)) break;
  360. }
  361. }
  362. DEBUG(dbgs() << "BBV: done!\n");
  363. return changed;
  364. }
  365. bool runOnBasicBlock(BasicBlock &BB) override {
  366. // OptimizeNone check deferred to vectorizeBB().
  367. AA = &getAnalysis<AliasAnalysis>();
  368. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  369. SE = &getAnalysis<ScalarEvolution>();
  370. TTI = IgnoreTargetInfo
  371. ? nullptr
  372. : &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  373. *BB.getParent());
  374. return vectorizeBB(BB);
  375. }
  376. void getAnalysisUsage(AnalysisUsage &AU) const override {
  377. BasicBlockPass::getAnalysisUsage(AU);
  378. AU.addRequired<AliasAnalysis>();
  379. AU.addRequired<DominatorTreeWrapperPass>();
  380. AU.addRequired<ScalarEvolution>();
  381. AU.addRequired<TargetTransformInfoWrapperPass>();
  382. AU.addPreserved<AliasAnalysis>();
  383. AU.addPreserved<DominatorTreeWrapperPass>();
  384. AU.addPreserved<ScalarEvolution>();
  385. AU.setPreservesCFG();
  386. }
  387. static inline VectorType *getVecTypeForPair(Type *ElemTy, Type *Elem2Ty) {
  388. assert(ElemTy->getScalarType() == Elem2Ty->getScalarType() &&
  389. "Cannot form vector from incompatible scalar types");
  390. Type *STy = ElemTy->getScalarType();
  391. unsigned numElem;
  392. if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
  393. numElem = VTy->getNumElements();
  394. } else {
  395. numElem = 1;
  396. }
  397. if (VectorType *VTy = dyn_cast<VectorType>(Elem2Ty)) {
  398. numElem += VTy->getNumElements();
  399. } else {
  400. numElem += 1;
  401. }
  402. return VectorType::get(STy, numElem);
  403. }
  404. static inline void getInstructionTypes(Instruction *I,
  405. Type *&T1, Type *&T2) {
  406. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  407. // For stores, it is the value type, not the pointer type that matters
  408. // because the value is what will come from a vector register.
  409. Value *IVal = SI->getValueOperand();
  410. T1 = IVal->getType();
  411. } else {
  412. T1 = I->getType();
  413. }
  414. if (CastInst *CI = dyn_cast<CastInst>(I))
  415. T2 = CI->getSrcTy();
  416. else
  417. T2 = T1;
  418. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  419. T2 = SI->getCondition()->getType();
  420. } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
  421. T2 = SI->getOperand(0)->getType();
  422. } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
  423. T2 = CI->getOperand(0)->getType();
  424. }
  425. }
  426. // Returns the weight associated with the provided value. A chain of
  427. // candidate pairs has a length given by the sum of the weights of its
  428. // members (one weight per pair; the weight of each member of the pair
  429. // is assumed to be the same). This length is then compared to the
  430. // chain-length threshold to determine if a given chain is significant
  431. // enough to be vectorized. The length is also used in comparing
  432. // candidate chains where longer chains are considered to be better.
  433. // Note: when this function returns 0, the resulting instructions are
  434. // not actually fused.
  435. inline size_t getDepthFactor(Value *V) {
  436. // InsertElement and ExtractElement have a depth factor of zero. This is
  437. // for two reasons: First, they cannot be usefully fused. Second, because
  438. // the pass generates a lot of these, they can confuse the simple metric
  439. // used to compare the dags in the next iteration. Thus, giving them a
  440. // weight of zero allows the pass to essentially ignore them in
  441. // subsequent iterations when looking for vectorization opportunities
  442. // while still tracking dependency chains that flow through those
  443. // instructions.
  444. if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
  445. return 0;
  446. // Give a load or store half of the required depth so that load/store
  447. // pairs will vectorize.
  448. if (!Config.NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
  449. return Config.ReqChainDepth/2;
  450. return 1;
  451. }
  452. // Returns the cost of the provided instruction using TTI.
  453. // This does not handle loads and stores.
  454. unsigned getInstrCost(unsigned Opcode, Type *T1, Type *T2,
  455. TargetTransformInfo::OperandValueKind Op1VK =
  456. TargetTransformInfo::OK_AnyValue,
  457. TargetTransformInfo::OperandValueKind Op2VK =
  458. TargetTransformInfo::OK_AnyValue) {
  459. switch (Opcode) {
  460. default: break;
  461. case Instruction::GetElementPtr:
  462. // We mark this instruction as zero-cost because scalar GEPs are usually
  463. // lowered to the instruction addressing mode. At the moment we don't
  464. // generate vector GEPs.
  465. return 0;
  466. case Instruction::Br:
  467. return TTI->getCFInstrCost(Opcode);
  468. case Instruction::PHI:
  469. return 0;
  470. case Instruction::Add:
  471. case Instruction::FAdd:
  472. case Instruction::Sub:
  473. case Instruction::FSub:
  474. case Instruction::Mul:
  475. case Instruction::FMul:
  476. case Instruction::UDiv:
  477. case Instruction::SDiv:
  478. case Instruction::FDiv:
  479. case Instruction::URem:
  480. case Instruction::SRem:
  481. case Instruction::FRem:
  482. case Instruction::Shl:
  483. case Instruction::LShr:
  484. case Instruction::AShr:
  485. case Instruction::And:
  486. case Instruction::Or:
  487. case Instruction::Xor:
  488. return TTI->getArithmeticInstrCost(Opcode, T1, Op1VK, Op2VK);
  489. case Instruction::Select:
  490. case Instruction::ICmp:
  491. case Instruction::FCmp:
  492. return TTI->getCmpSelInstrCost(Opcode, T1, T2);
  493. case Instruction::ZExt:
  494. case Instruction::SExt:
  495. case Instruction::FPToUI:
  496. case Instruction::FPToSI:
  497. case Instruction::FPExt:
  498. case Instruction::PtrToInt:
  499. case Instruction::IntToPtr:
  500. case Instruction::SIToFP:
  501. case Instruction::UIToFP:
  502. case Instruction::Trunc:
  503. case Instruction::FPTrunc:
  504. case Instruction::BitCast:
  505. case Instruction::ShuffleVector:
  506. return TTI->getCastInstrCost(Opcode, T1, T2);
  507. }
  508. return 1;
  509. }
  510. // This determines the relative offset of two loads or stores, returning
  511. // true if the offset could be determined to be some constant value.
  512. // For example, if OffsetInElmts == 1, then J accesses the memory directly
  513. // after I; if OffsetInElmts == -1 then I accesses the memory
  514. // directly after J.
  515. bool getPairPtrInfo(Instruction *I, Instruction *J,
  516. Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
  517. unsigned &IAddressSpace, unsigned &JAddressSpace,
  518. int64_t &OffsetInElmts, bool ComputeOffset = true) {
  519. OffsetInElmts = 0;
  520. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  521. LoadInst *LJ = cast<LoadInst>(J);
  522. IPtr = LI->getPointerOperand();
  523. JPtr = LJ->getPointerOperand();
  524. IAlignment = LI->getAlignment();
  525. JAlignment = LJ->getAlignment();
  526. IAddressSpace = LI->getPointerAddressSpace();
  527. JAddressSpace = LJ->getPointerAddressSpace();
  528. } else {
  529. StoreInst *SI = cast<StoreInst>(I), *SJ = cast<StoreInst>(J);
  530. IPtr = SI->getPointerOperand();
  531. JPtr = SJ->getPointerOperand();
  532. IAlignment = SI->getAlignment();
  533. JAlignment = SJ->getAlignment();
  534. IAddressSpace = SI->getPointerAddressSpace();
  535. JAddressSpace = SJ->getPointerAddressSpace();
  536. }
  537. if (!ComputeOffset)
  538. return true;
  539. const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
  540. const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
  541. // If this is a trivial offset, then we'll get something like
  542. // 1*sizeof(type). With target data, which we need anyway, this will get
  543. // constant folded into a number.
  544. const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
  545. if (const SCEVConstant *ConstOffSCEV =
  546. dyn_cast<SCEVConstant>(OffsetSCEV)) {
  547. ConstantInt *IntOff = ConstOffSCEV->getValue();
  548. int64_t Offset = IntOff->getSExtValue();
  549. const DataLayout &DL = I->getModule()->getDataLayout();
  550. Type *VTy = IPtr->getType()->getPointerElementType();
  551. int64_t VTyTSS = (int64_t)DL.getTypeStoreSize(VTy);
  552. Type *VTy2 = JPtr->getType()->getPointerElementType();
  553. if (VTy != VTy2 && Offset < 0) {
  554. int64_t VTy2TSS = (int64_t)DL.getTypeStoreSize(VTy2);
  555. OffsetInElmts = Offset/VTy2TSS;
  556. return (std::abs(Offset) % VTy2TSS) == 0;
  557. }
  558. OffsetInElmts = Offset/VTyTSS;
  559. return (std::abs(Offset) % VTyTSS) == 0;
  560. }
  561. return false;
  562. }
  563. // Returns true if the provided CallInst represents an intrinsic that can
  564. // be vectorized.
  565. bool isVectorizableIntrinsic(CallInst* I) {
  566. Function *F = I->getCalledFunction();
  567. if (!F) return false;
  568. Intrinsic::ID IID = F->getIntrinsicID();
  569. if (!IID) return false;
  570. switch(IID) {
  571. default:
  572. return false;
  573. case Intrinsic::sqrt:
  574. case Intrinsic::powi:
  575. case Intrinsic::sin:
  576. case Intrinsic::cos:
  577. case Intrinsic::log:
  578. case Intrinsic::log2:
  579. case Intrinsic::log10:
  580. case Intrinsic::exp:
  581. case Intrinsic::exp2:
  582. case Intrinsic::pow:
  583. case Intrinsic::round:
  584. case Intrinsic::copysign:
  585. case Intrinsic::ceil:
  586. case Intrinsic::nearbyint:
  587. case Intrinsic::rint:
  588. case Intrinsic::trunc:
  589. case Intrinsic::floor:
  590. case Intrinsic::fabs:
  591. case Intrinsic::minnum:
  592. case Intrinsic::maxnum:
  593. return Config.VectorizeMath;
  594. case Intrinsic::bswap:
  595. case Intrinsic::ctpop:
  596. case Intrinsic::ctlz:
  597. case Intrinsic::cttz:
  598. return Config.VectorizeBitManipulations;
  599. case Intrinsic::fma:
  600. case Intrinsic::fmuladd:
  601. return Config.VectorizeFMA;
  602. }
  603. }
  604. bool isPureIEChain(InsertElementInst *IE) {
  605. InsertElementInst *IENext = IE;
  606. do {
  607. if (!isa<UndefValue>(IENext->getOperand(0)) &&
  608. !isa<InsertElementInst>(IENext->getOperand(0))) {
  609. return false;
  610. }
  611. } while ((IENext =
  612. dyn_cast<InsertElementInst>(IENext->getOperand(0))));
  613. return true;
  614. }
  615. };
  616. // This function implements one vectorization iteration on the provided
  617. // basic block. It returns true if the block is changed.
  618. bool BBVectorize::vectorizePairs(BasicBlock &BB, bool NonPow2Len) {
  619. bool ShouldContinue;
  620. BasicBlock::iterator Start = BB.getFirstInsertionPt();
  621. std::vector<Value *> AllPairableInsts;
  622. DenseMap<Value *, Value *> AllChosenPairs;
  623. DenseSet<ValuePair> AllFixedOrderPairs;
  624. DenseMap<VPPair, unsigned> AllPairConnectionTypes;
  625. DenseMap<ValuePair, std::vector<ValuePair> > AllConnectedPairs,
  626. AllConnectedPairDeps;
  627. do {
  628. std::vector<Value *> PairableInsts;
  629. DenseMap<Value *, std::vector<Value *> > CandidatePairs;
  630. DenseSet<ValuePair> FixedOrderPairs;
  631. DenseMap<ValuePair, int> CandidatePairCostSavings;
  632. ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
  633. FixedOrderPairs,
  634. CandidatePairCostSavings,
  635. PairableInsts, NonPow2Len);
  636. if (PairableInsts.empty()) continue;
  637. // Build the candidate pair set for faster lookups.
  638. DenseSet<ValuePair> CandidatePairsSet;
  639. for (DenseMap<Value *, std::vector<Value *> >::iterator I =
  640. CandidatePairs.begin(), E = CandidatePairs.end(); I != E; ++I)
  641. for (std::vector<Value *>::iterator J = I->second.begin(),
  642. JE = I->second.end(); J != JE; ++J)
  643. CandidatePairsSet.insert(ValuePair(I->first, *J));
  644. // Now we have a map of all of the pairable instructions and we need to
  645. // select the best possible pairing. A good pairing is one such that the
  646. // users of the pair are also paired. This defines a (directed) forest
  647. // over the pairs such that two pairs are connected iff the second pair
  648. // uses the first.
  649. // Note that it only matters that both members of the second pair use some
  650. // element of the first pair (to allow for splatting).
  651. DenseMap<ValuePair, std::vector<ValuePair> > ConnectedPairs,
  652. ConnectedPairDeps;
  653. DenseMap<VPPair, unsigned> PairConnectionTypes;
  654. computeConnectedPairs(CandidatePairs, CandidatePairsSet,
  655. PairableInsts, ConnectedPairs, PairConnectionTypes);
  656. if (ConnectedPairs.empty()) continue;
  657. for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
  658. I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
  659. I != IE; ++I)
  660. for (std::vector<ValuePair>::iterator J = I->second.begin(),
  661. JE = I->second.end(); J != JE; ++J)
  662. ConnectedPairDeps[*J].push_back(I->first);
  663. // Build the pairable-instruction dependency map
  664. DenseSet<ValuePair> PairableInstUsers;
  665. buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
  666. // There is now a graph of the connected pairs. For each variable, pick
  667. // the pairing with the largest dag meeting the depth requirement on at
  668. // least one branch. Then select all pairings that are part of that dag
  669. // and remove them from the list of available pairings and pairable
  670. // variables.
  671. DenseMap<Value *, Value *> ChosenPairs;
  672. choosePairs(CandidatePairs, CandidatePairsSet,
  673. CandidatePairCostSavings,
  674. PairableInsts, FixedOrderPairs, PairConnectionTypes,
  675. ConnectedPairs, ConnectedPairDeps,
  676. PairableInstUsers, ChosenPairs);
  677. if (ChosenPairs.empty()) continue;
  678. AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
  679. PairableInsts.end());
  680. AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
  681. // Only for the chosen pairs, propagate information on fixed-order pairs,
  682. // pair connections, and their types to the data structures used by the
  683. // pair fusion procedures.
  684. for (DenseMap<Value *, Value *>::iterator I = ChosenPairs.begin(),
  685. IE = ChosenPairs.end(); I != IE; ++I) {
  686. if (FixedOrderPairs.count(*I))
  687. AllFixedOrderPairs.insert(*I);
  688. else if (FixedOrderPairs.count(ValuePair(I->second, I->first)))
  689. AllFixedOrderPairs.insert(ValuePair(I->second, I->first));
  690. for (DenseMap<Value *, Value *>::iterator J = ChosenPairs.begin();
  691. J != IE; ++J) {
  692. DenseMap<VPPair, unsigned>::iterator K =
  693. PairConnectionTypes.find(VPPair(*I, *J));
  694. if (K != PairConnectionTypes.end()) {
  695. AllPairConnectionTypes.insert(*K);
  696. } else {
  697. K = PairConnectionTypes.find(VPPair(*J, *I));
  698. if (K != PairConnectionTypes.end())
  699. AllPairConnectionTypes.insert(*K);
  700. }
  701. }
  702. }
  703. for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator
  704. I = ConnectedPairs.begin(), IE = ConnectedPairs.end();
  705. I != IE; ++I)
  706. for (std::vector<ValuePair>::iterator J = I->second.begin(),
  707. JE = I->second.end(); J != JE; ++J)
  708. if (AllPairConnectionTypes.count(VPPair(I->first, *J))) {
  709. AllConnectedPairs[I->first].push_back(*J);
  710. AllConnectedPairDeps[*J].push_back(I->first);
  711. }
  712. } while (ShouldContinue);
  713. if (AllChosenPairs.empty()) return false;
  714. NumFusedOps += AllChosenPairs.size();
  715. // A set of pairs has now been selected. It is now necessary to replace the
  716. // paired instructions with vector instructions. For this procedure each
  717. // operand must be replaced with a vector operand. This vector is formed
  718. // by using build_vector on the old operands. The replaced values are then
  719. // replaced with a vector_extract on the result. Subsequent optimization
  720. // passes should coalesce the build/extract combinations.
  721. fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs, AllFixedOrderPairs,
  722. AllPairConnectionTypes,
  723. AllConnectedPairs, AllConnectedPairDeps);
  724. // It is important to cleanup here so that future iterations of this
  725. // function have less work to do.
  726. (void)SimplifyInstructionsInBlock(&BB, AA->getTargetLibraryInfo());
  727. return true;
  728. }
  729. // This function returns true if the provided instruction is capable of being
  730. // fused into a vector instruction. This determination is based only on the
  731. // type and other attributes of the instruction.
  732. bool BBVectorize::isInstVectorizable(Instruction *I,
  733. bool &IsSimpleLoadStore) {
  734. IsSimpleLoadStore = false;
  735. if (CallInst *C = dyn_cast<CallInst>(I)) {
  736. if (!isVectorizableIntrinsic(C))
  737. return false;
  738. } else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
  739. // Vectorize simple loads if possbile:
  740. IsSimpleLoadStore = L->isSimple();
  741. if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
  742. return false;
  743. } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
  744. // Vectorize simple stores if possbile:
  745. IsSimpleLoadStore = S->isSimple();
  746. if (!IsSimpleLoadStore || !Config.VectorizeMemOps)
  747. return false;
  748. } else if (CastInst *C = dyn_cast<CastInst>(I)) {
  749. // We can vectorize casts, but not casts of pointer types, etc.
  750. if (!Config.VectorizeCasts)
  751. return false;
  752. Type *SrcTy = C->getSrcTy();
  753. if (!SrcTy->isSingleValueType())
  754. return false;
  755. Type *DestTy = C->getDestTy();
  756. if (!DestTy->isSingleValueType())
  757. return false;
  758. } else if (isa<SelectInst>(I)) {
  759. if (!Config.VectorizeSelect)
  760. return false;
  761. } else if (isa<CmpInst>(I)) {
  762. if (!Config.VectorizeCmp)
  763. return false;
  764. } else if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(I)) {
  765. if (!Config.VectorizeGEP)
  766. return false;
  767. // Currently, vector GEPs exist only with one index.
  768. if (G->getNumIndices() != 1)
  769. return false;
  770. } else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
  771. isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
  772. return false;
  773. }
  774. Type *T1, *T2;
  775. getInstructionTypes(I, T1, T2);
  776. // Not every type can be vectorized...
  777. if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
  778. !(VectorType::isValidElementType(T2) || T2->isVectorTy()))
  779. return false;
  780. if (T1->getScalarSizeInBits() == 1) {
  781. if (!Config.VectorizeBools)
  782. return false;
  783. } else {
  784. if (!Config.VectorizeInts && T1->isIntOrIntVectorTy())
  785. return false;
  786. }
  787. if (T2->getScalarSizeInBits() == 1) {
  788. if (!Config.VectorizeBools)
  789. return false;
  790. } else {
  791. if (!Config.VectorizeInts && T2->isIntOrIntVectorTy())
  792. return false;
  793. }
  794. if (!Config.VectorizeFloats
  795. && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
  796. return false;
  797. // Don't vectorize target-specific types.
  798. if (T1->isX86_FP80Ty() || T1->isPPC_FP128Ty() || T1->isX86_MMXTy())
  799. return false;
  800. if (T2->isX86_FP80Ty() || T2->isPPC_FP128Ty() || T2->isX86_MMXTy())
  801. return false;
  802. if (!Config.VectorizePointers && (T1->getScalarType()->isPointerTy() ||
  803. T2->getScalarType()->isPointerTy()))
  804. return false;
  805. if (!TTI && (T1->getPrimitiveSizeInBits() >= Config.VectorBits ||
  806. T2->getPrimitiveSizeInBits() >= Config.VectorBits))
  807. return false;
  808. return true;
  809. }
  810. // This function returns true if the two provided instructions are compatible
  811. // (meaning that they can be fused into a vector instruction). This assumes
  812. // that I has already been determined to be vectorizable and that J is not
  813. // in the use dag of I.
  814. bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
  815. bool IsSimpleLoadStore, bool NonPow2Len,
  816. int &CostSavings, int &FixedOrder) {
  817. DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
  818. " <-> " << *J << "\n");
  819. CostSavings = 0;
  820. FixedOrder = 0;
  821. // Loads and stores can be merged if they have different alignments,
  822. // but are otherwise the same.
  823. if (!J->isSameOperationAs(I, Instruction::CompareIgnoringAlignment |
  824. (NonPow2Len ? Instruction::CompareUsingScalarTypes : 0)))
  825. return false;
  826. Type *IT1, *IT2, *JT1, *JT2;
  827. getInstructionTypes(I, IT1, IT2);
  828. getInstructionTypes(J, JT1, JT2);
  829. unsigned MaxTypeBits = std::max(
  830. IT1->getPrimitiveSizeInBits() + JT1->getPrimitiveSizeInBits(),
  831. IT2->getPrimitiveSizeInBits() + JT2->getPrimitiveSizeInBits());
  832. if (!TTI && MaxTypeBits > Config.VectorBits)
  833. return false;
  834. // FIXME: handle addsub-type operations!
  835. if (IsSimpleLoadStore) {
  836. Value *IPtr, *JPtr;
  837. unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
  838. int64_t OffsetInElmts = 0;
  839. if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
  840. IAddressSpace, JAddressSpace, OffsetInElmts) &&
  841. std::abs(OffsetInElmts) == 1) {
  842. FixedOrder = (int) OffsetInElmts;
  843. unsigned BottomAlignment = IAlignment;
  844. if (OffsetInElmts < 0) BottomAlignment = JAlignment;
  845. Type *aTypeI = isa<StoreInst>(I) ?
  846. cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
  847. Type *aTypeJ = isa<StoreInst>(J) ?
  848. cast<StoreInst>(J)->getValueOperand()->getType() : J->getType();
  849. Type *VType = getVecTypeForPair(aTypeI, aTypeJ);
  850. if (Config.AlignedOnly) {
  851. // An aligned load or store is possible only if the instruction
  852. // with the lower offset has an alignment suitable for the
  853. // vector type.
  854. const DataLayout &DL = I->getModule()->getDataLayout();
  855. unsigned VecAlignment = DL.getPrefTypeAlignment(VType);
  856. if (BottomAlignment < VecAlignment)
  857. return false;
  858. }
  859. if (TTI) {
  860. unsigned ICost = TTI->getMemoryOpCost(I->getOpcode(), aTypeI,
  861. IAlignment, IAddressSpace);
  862. unsigned JCost = TTI->getMemoryOpCost(J->getOpcode(), aTypeJ,
  863. JAlignment, JAddressSpace);
  864. unsigned VCost = TTI->getMemoryOpCost(I->getOpcode(), VType,
  865. BottomAlignment,
  866. IAddressSpace);
  867. ICost += TTI->getAddressComputationCost(aTypeI);
  868. JCost += TTI->getAddressComputationCost(aTypeJ);
  869. VCost += TTI->getAddressComputationCost(VType);
  870. if (VCost > ICost + JCost)
  871. return false;
  872. // We don't want to fuse to a type that will be split, even
  873. // if the two input types will also be split and there is no other
  874. // associated cost.
  875. unsigned VParts = TTI->getNumberOfParts(VType);
  876. if (VParts > 1)
  877. return false;
  878. else if (!VParts && VCost == ICost + JCost)
  879. return false;
  880. CostSavings = ICost + JCost - VCost;
  881. }
  882. } else {
  883. return false;
  884. }
  885. } else if (TTI) {
  886. unsigned ICost = getInstrCost(I->getOpcode(), IT1, IT2);
  887. unsigned JCost = getInstrCost(J->getOpcode(), JT1, JT2);
  888. Type *VT1 = getVecTypeForPair(IT1, JT1),
  889. *VT2 = getVecTypeForPair(IT2, JT2);
  890. TargetTransformInfo::OperandValueKind Op1VK =
  891. TargetTransformInfo::OK_AnyValue;
  892. TargetTransformInfo::OperandValueKind Op2VK =
  893. TargetTransformInfo::OK_AnyValue;
  894. // On some targets (example X86) the cost of a vector shift may vary
  895. // depending on whether the second operand is a Uniform or
  896. // NonUniform Constant.
  897. switch (I->getOpcode()) {
  898. default : break;
  899. case Instruction::Shl:
  900. case Instruction::LShr:
  901. case Instruction::AShr:
  902. // If both I and J are scalar shifts by constant, then the
  903. // merged vector shift count would be either a constant splat value
  904. // or a non-uniform vector of constants.
  905. if (ConstantInt *CII = dyn_cast<ConstantInt>(I->getOperand(1))) {
  906. if (ConstantInt *CIJ = dyn_cast<ConstantInt>(J->getOperand(1)))
  907. Op2VK = CII == CIJ ? TargetTransformInfo::OK_UniformConstantValue :
  908. TargetTransformInfo::OK_NonUniformConstantValue;
  909. } else {
  910. // Check for a splat of a constant or for a non uniform vector
  911. // of constants.
  912. Value *IOp = I->getOperand(1);
  913. Value *JOp = J->getOperand(1);
  914. if ((isa<ConstantVector>(IOp) || isa<ConstantDataVector>(IOp)) &&
  915. (isa<ConstantVector>(JOp) || isa<ConstantDataVector>(JOp))) {
  916. Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
  917. Constant *SplatValue = cast<Constant>(IOp)->getSplatValue();
  918. if (SplatValue != nullptr &&
  919. SplatValue == cast<Constant>(JOp)->getSplatValue())
  920. Op2VK = TargetTransformInfo::OK_UniformConstantValue;
  921. }
  922. }
  923. }
  924. // Note that this procedure is incorrect for insert and extract element
  925. // instructions (because combining these often results in a shuffle),
  926. // but this cost is ignored (because insert and extract element
  927. // instructions are assigned a zero depth factor and are not really
  928. // fused in general).
  929. unsigned VCost = getInstrCost(I->getOpcode(), VT1, VT2, Op1VK, Op2VK);
  930. if (VCost > ICost + JCost)
  931. return false;
  932. // We don't want to fuse to a type that will be split, even
  933. // if the two input types will also be split and there is no other
  934. // associated cost.
  935. unsigned VParts1 = TTI->getNumberOfParts(VT1),
  936. VParts2 = TTI->getNumberOfParts(VT2);
  937. if (VParts1 > 1 || VParts2 > 1)
  938. return false;
  939. else if ((!VParts1 || !VParts2) && VCost == ICost + JCost)
  940. return false;
  941. CostSavings = ICost + JCost - VCost;
  942. }
  943. // The powi,ctlz,cttz intrinsics are special because only the first
  944. // argument is vectorized, the second arguments must be equal.
  945. CallInst *CI = dyn_cast<CallInst>(I);
  946. Function *FI;
  947. if (CI && (FI = CI->getCalledFunction())) {
  948. Intrinsic::ID IID = FI->getIntrinsicID();
  949. if (IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
  950. IID == Intrinsic::cttz) {
  951. Value *A1I = CI->getArgOperand(1),
  952. *A1J = cast<CallInst>(J)->getArgOperand(1);
  953. const SCEV *A1ISCEV = SE->getSCEV(A1I),
  954. *A1JSCEV = SE->getSCEV(A1J);
  955. return (A1ISCEV == A1JSCEV);
  956. }
  957. if (IID && TTI) {
  958. SmallVector<Type*, 4> Tys;
  959. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
  960. Tys.push_back(CI->getArgOperand(i)->getType());
  961. unsigned ICost = TTI->getIntrinsicInstrCost(IID, IT1, Tys);
  962. Tys.clear();
  963. CallInst *CJ = cast<CallInst>(J);
  964. for (unsigned i = 0, ie = CJ->getNumArgOperands(); i != ie; ++i)
  965. Tys.push_back(CJ->getArgOperand(i)->getType());
  966. unsigned JCost = TTI->getIntrinsicInstrCost(IID, JT1, Tys);
  967. Tys.clear();
  968. assert(CI->getNumArgOperands() == CJ->getNumArgOperands() &&
  969. "Intrinsic argument counts differ");
  970. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
  971. if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
  972. IID == Intrinsic::cttz) && i == 1)
  973. Tys.push_back(CI->getArgOperand(i)->getType());
  974. else
  975. Tys.push_back(getVecTypeForPair(CI->getArgOperand(i)->getType(),
  976. CJ->getArgOperand(i)->getType()));
  977. }
  978. Type *RetTy = getVecTypeForPair(IT1, JT1);
  979. unsigned VCost = TTI->getIntrinsicInstrCost(IID, RetTy, Tys);
  980. if (VCost > ICost + JCost)
  981. return false;
  982. // We don't want to fuse to a type that will be split, even
  983. // if the two input types will also be split and there is no other
  984. // associated cost.
  985. unsigned RetParts = TTI->getNumberOfParts(RetTy);
  986. if (RetParts > 1)
  987. return false;
  988. else if (!RetParts && VCost == ICost + JCost)
  989. return false;
  990. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
  991. if (!Tys[i]->isVectorTy())
  992. continue;
  993. unsigned NumParts = TTI->getNumberOfParts(Tys[i]);
  994. if (NumParts > 1)
  995. return false;
  996. else if (!NumParts && VCost == ICost + JCost)
  997. return false;
  998. }
  999. CostSavings = ICost + JCost - VCost;
  1000. }
  1001. }
  1002. return true;
  1003. }
  1004. // Figure out whether or not J uses I and update the users and write-set
  1005. // structures associated with I. Specifically, Users represents the set of
  1006. // instructions that depend on I. WriteSet represents the set
  1007. // of memory locations that are dependent on I. If UpdateUsers is true,
  1008. // and J uses I, then Users is updated to contain J and WriteSet is updated
  1009. // to contain any memory locations to which J writes. The function returns
  1010. // true if J uses I. By default, alias analysis is used to determine
  1011. // whether J reads from memory that overlaps with a location in WriteSet.
  1012. // If LoadMoveSet is not null, then it is a previously-computed map
  1013. // where the key is the memory-based user instruction and the value is
  1014. // the instruction to be compared with I. So, if LoadMoveSet is provided,
  1015. // then the alias analysis is not used. This is necessary because this
  1016. // function is called during the process of moving instructions during
  1017. // vectorization and the results of the alias analysis are not stable during
  1018. // that process.
  1019. bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
  1020. AliasSetTracker &WriteSet, Instruction *I,
  1021. Instruction *J, bool UpdateUsers,
  1022. DenseSet<ValuePair> *LoadMoveSetPairs) {
  1023. bool UsesI = false;
  1024. // This instruction may already be marked as a user due, for example, to
  1025. // being a member of a selected pair.
  1026. if (Users.count(J))
  1027. UsesI = true;
  1028. if (!UsesI)
  1029. for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
  1030. JU != JE; ++JU) {
  1031. Value *V = *JU;
  1032. if (I == V || Users.count(V)) {
  1033. UsesI = true;
  1034. break;
  1035. }
  1036. }
  1037. if (!UsesI && J->mayReadFromMemory()) {
  1038. if (LoadMoveSetPairs) {
  1039. UsesI = LoadMoveSetPairs->count(ValuePair(J, I));
  1040. } else {
  1041. for (AliasSetTracker::iterator W = WriteSet.begin(),
  1042. WE = WriteSet.end(); W != WE; ++W) {
  1043. if (W->aliasesUnknownInst(J, *AA)) {
  1044. UsesI = true;
  1045. break;
  1046. }
  1047. }
  1048. }
  1049. }
  1050. if (UsesI && UpdateUsers) {
  1051. if (J->mayWriteToMemory()) WriteSet.add(J);
  1052. Users.insert(J);
  1053. }
  1054. return UsesI;
  1055. }
  1056. // This function iterates over all instruction pairs in the provided
  1057. // basic block and collects all candidate pairs for vectorization.
  1058. bool BBVectorize::getCandidatePairs(BasicBlock &BB,
  1059. BasicBlock::iterator &Start,
  1060. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  1061. DenseSet<ValuePair> &FixedOrderPairs,
  1062. DenseMap<ValuePair, int> &CandidatePairCostSavings,
  1063. std::vector<Value *> &PairableInsts, bool NonPow2Len) {
  1064. size_t TotalPairs = 0;
  1065. BasicBlock::iterator E = BB.end();
  1066. if (Start == E) return false;
  1067. bool ShouldContinue = false, IAfterStart = false;
  1068. for (BasicBlock::iterator I = Start++; I != E; ++I) {
  1069. if (I == Start) IAfterStart = true;
  1070. bool IsSimpleLoadStore;
  1071. if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
  1072. // Look for an instruction with which to pair instruction *I...
  1073. DenseSet<Value *> Users;
  1074. AliasSetTracker WriteSet(*AA);
  1075. if (I->mayWriteToMemory()) WriteSet.add(I);
  1076. bool JAfterStart = IAfterStart;
  1077. BasicBlock::iterator J = std::next(I);
  1078. for (unsigned ss = 0; J != E && ss <= Config.SearchLimit; ++J, ++ss) {
  1079. if (J == Start) JAfterStart = true;
  1080. // Determine if J uses I, if so, exit the loop.
  1081. bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !Config.FastDep);
  1082. if (Config.FastDep) {
  1083. // Note: For this heuristic to be effective, independent operations
  1084. // must tend to be intermixed. This is likely to be true from some
  1085. // kinds of grouped loop unrolling (but not the generic LLVM pass),
  1086. // but otherwise may require some kind of reordering pass.
  1087. // When using fast dependency analysis,
  1088. // stop searching after first use:
  1089. if (UsesI) break;
  1090. } else {
  1091. if (UsesI) continue;
  1092. }
  1093. // J does not use I, and comes before the first use of I, so it can be
  1094. // merged with I if the instructions are compatible.
  1095. int CostSavings, FixedOrder;
  1096. if (!areInstsCompatible(I, J, IsSimpleLoadStore, NonPow2Len,
  1097. CostSavings, FixedOrder)) continue;
  1098. // J is a candidate for merging with I.
  1099. if (PairableInsts.empty() ||
  1100. PairableInsts[PairableInsts.size()-1] != I) {
  1101. PairableInsts.push_back(I);
  1102. }
  1103. CandidatePairs[I].push_back(J);
  1104. ++TotalPairs;
  1105. if (TTI)
  1106. CandidatePairCostSavings.insert(ValuePairWithCost(ValuePair(I, J),
  1107. CostSavings));
  1108. if (FixedOrder == 1)
  1109. FixedOrderPairs.insert(ValuePair(I, J));
  1110. else if (FixedOrder == -1)
  1111. FixedOrderPairs.insert(ValuePair(J, I));
  1112. // The next call to this function must start after the last instruction
  1113. // selected during this invocation.
  1114. if (JAfterStart) {
  1115. Start = std::next(J);
  1116. IAfterStart = JAfterStart = false;
  1117. }
  1118. DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
  1119. << *I << " <-> " << *J << " (cost savings: " <<
  1120. CostSavings << ")\n");
  1121. // If we have already found too many pairs, break here and this function
  1122. // will be called again starting after the last instruction selected
  1123. // during this invocation.
  1124. if (PairableInsts.size() >= Config.MaxInsts ||
  1125. TotalPairs >= Config.MaxPairs) {
  1126. ShouldContinue = true;
  1127. break;
  1128. }
  1129. }
  1130. if (ShouldContinue)
  1131. break;
  1132. }
  1133. DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
  1134. << " instructions with candidate pairs\n");
  1135. return ShouldContinue;
  1136. }
  1137. // Finds candidate pairs connected to the pair P = <PI, PJ>. This means that
  1138. // it looks for pairs such that both members have an input which is an
  1139. // output of PI or PJ.
  1140. void BBVectorize::computePairsConnectedTo(
  1141. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  1142. DenseSet<ValuePair> &CandidatePairsSet,
  1143. std::vector<Value *> &PairableInsts,
  1144. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  1145. DenseMap<VPPair, unsigned> &PairConnectionTypes,
  1146. ValuePair P) {
  1147. StoreInst *SI, *SJ;
  1148. // For each possible pairing for this variable, look at the uses of
  1149. // the first value...
  1150. for (Value::user_iterator I = P.first->user_begin(),
  1151. E = P.first->user_end();
  1152. I != E; ++I) {
  1153. User *UI = *I;
  1154. if (isa<LoadInst>(UI)) {
  1155. // A pair cannot be connected to a load because the load only takes one
  1156. // operand (the address) and it is a scalar even after vectorization.
  1157. continue;
  1158. } else if ((SI = dyn_cast<StoreInst>(UI)) &&
  1159. P.first == SI->getPointerOperand()) {
  1160. // Similarly, a pair cannot be connected to a store through its
  1161. // pointer operand.
  1162. continue;
  1163. }
  1164. // For each use of the first variable, look for uses of the second
  1165. // variable...
  1166. for (User *UJ : P.second->users()) {
  1167. if ((SJ = dyn_cast<StoreInst>(UJ)) &&
  1168. P.second == SJ->getPointerOperand())
  1169. continue;
  1170. // Look for <I, J>:
  1171. if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
  1172. VPPair VP(P, ValuePair(UI, UJ));
  1173. ConnectedPairs[VP.first].push_back(VP.second);
  1174. PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionDirect));
  1175. }
  1176. // Look for <J, I>:
  1177. if (CandidatePairsSet.count(ValuePair(UJ, UI))) {
  1178. VPPair VP(P, ValuePair(UJ, UI));
  1179. ConnectedPairs[VP.first].push_back(VP.second);
  1180. PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSwap));
  1181. }
  1182. }
  1183. if (Config.SplatBreaksChain) continue;
  1184. // Look for cases where just the first value in the pair is used by
  1185. // both members of another pair (splatting).
  1186. for (Value::user_iterator J = P.first->user_begin(); J != E; ++J) {
  1187. User *UJ = *J;
  1188. if ((SJ = dyn_cast<StoreInst>(UJ)) &&
  1189. P.first == SJ->getPointerOperand())
  1190. continue;
  1191. if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
  1192. VPPair VP(P, ValuePair(UI, UJ));
  1193. ConnectedPairs[VP.first].push_back(VP.second);
  1194. PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
  1195. }
  1196. }
  1197. }
  1198. if (Config.SplatBreaksChain) return;
  1199. // Look for cases where just the second value in the pair is used by
  1200. // both members of another pair (splatting).
  1201. for (Value::user_iterator I = P.second->user_begin(),
  1202. E = P.second->user_end();
  1203. I != E; ++I) {
  1204. User *UI = *I;
  1205. if (isa<LoadInst>(UI))
  1206. continue;
  1207. else if ((SI = dyn_cast<StoreInst>(UI)) &&
  1208. P.second == SI->getPointerOperand())
  1209. continue;
  1210. for (Value::user_iterator J = P.second->user_begin(); J != E; ++J) {
  1211. User *UJ = *J;
  1212. if ((SJ = dyn_cast<StoreInst>(UJ)) &&
  1213. P.second == SJ->getPointerOperand())
  1214. continue;
  1215. if (CandidatePairsSet.count(ValuePair(UI, UJ))) {
  1216. VPPair VP(P, ValuePair(UI, UJ));
  1217. ConnectedPairs[VP.first].push_back(VP.second);
  1218. PairConnectionTypes.insert(VPPairWithType(VP, PairConnectionSplat));
  1219. }
  1220. }
  1221. }
  1222. }
  1223. // This function figures out which pairs are connected. Two pairs are
  1224. // connected if some output of the first pair forms an input to both members
  1225. // of the second pair.
  1226. void BBVectorize::computeConnectedPairs(
  1227. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  1228. DenseSet<ValuePair> &CandidatePairsSet,
  1229. std::vector<Value *> &PairableInsts,
  1230. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  1231. DenseMap<VPPair, unsigned> &PairConnectionTypes) {
  1232. for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
  1233. PE = PairableInsts.end(); PI != PE; ++PI) {
  1234. DenseMap<Value *, std::vector<Value *> >::iterator PP =
  1235. CandidatePairs.find(*PI);
  1236. if (PP == CandidatePairs.end())
  1237. continue;
  1238. for (std::vector<Value *>::iterator P = PP->second.begin(),
  1239. E = PP->second.end(); P != E; ++P)
  1240. computePairsConnectedTo(CandidatePairs, CandidatePairsSet,
  1241. PairableInsts, ConnectedPairs,
  1242. PairConnectionTypes, ValuePair(*PI, *P));
  1243. }
  1244. DEBUG(size_t TotalPairs = 0;
  1245. for (DenseMap<ValuePair, std::vector<ValuePair> >::iterator I =
  1246. ConnectedPairs.begin(), IE = ConnectedPairs.end(); I != IE; ++I)
  1247. TotalPairs += I->second.size();
  1248. dbgs() << "BBV: found " << TotalPairs
  1249. << " pair connections.\n");
  1250. }
  1251. // This function builds a set of use tuples such that <A, B> is in the set
  1252. // if B is in the use dag of A. If B is in the use dag of A, then B
  1253. // depends on the output of A.
  1254. void BBVectorize::buildDepMap(
  1255. BasicBlock &BB,
  1256. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  1257. std::vector<Value *> &PairableInsts,
  1258. DenseSet<ValuePair> &PairableInstUsers) {
  1259. DenseSet<Value *> IsInPair;
  1260. for (DenseMap<Value *, std::vector<Value *> >::iterator C =
  1261. CandidatePairs.begin(), E = CandidatePairs.end(); C != E; ++C) {
  1262. IsInPair.insert(C->first);
  1263. IsInPair.insert(C->second.begin(), C->second.end());
  1264. }
  1265. // Iterate through the basic block, recording all users of each
  1266. // pairable instruction.
  1267. BasicBlock::iterator E = BB.end(), EL =
  1268. BasicBlock::iterator(cast<Instruction>(PairableInsts.back()));
  1269. for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
  1270. if (IsInPair.find(I) == IsInPair.end()) continue;
  1271. DenseSet<Value *> Users;
  1272. AliasSetTracker WriteSet(*AA);
  1273. if (I->mayWriteToMemory()) WriteSet.add(I);
  1274. for (BasicBlock::iterator J = std::next(I); J != E; ++J) {
  1275. (void) trackUsesOfI(Users, WriteSet, I, J);
  1276. if (J == EL)
  1277. break;
  1278. }
  1279. for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
  1280. U != E; ++U) {
  1281. if (IsInPair.find(*U) == IsInPair.end()) continue;
  1282. PairableInstUsers.insert(ValuePair(I, *U));
  1283. }
  1284. if (I == EL)
  1285. break;
  1286. }
  1287. }
  1288. // Returns true if an input to pair P is an output of pair Q and also an
  1289. // input of pair Q is an output of pair P. If this is the case, then these
  1290. // two pairs cannot be simultaneously fused.
  1291. bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
  1292. DenseSet<ValuePair> &PairableInstUsers,
  1293. DenseMap<ValuePair, std::vector<ValuePair> > *PairableInstUserMap,
  1294. DenseSet<VPPair> *PairableInstUserPairSet) {
  1295. // Two pairs are in conflict if they are mutual Users of eachother.
  1296. bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
  1297. PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
  1298. PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
  1299. PairableInstUsers.count(ValuePair(P.second, Q.second));
  1300. bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
  1301. PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
  1302. PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
  1303. PairableInstUsers.count(ValuePair(Q.second, P.second));
  1304. if (PairableInstUserMap) {
  1305. // FIXME: The expensive part of the cycle check is not so much the cycle
  1306. // check itself but this edge insertion procedure. This needs some
  1307. // profiling and probably a different data structure.
  1308. if (PUsesQ) {
  1309. if (PairableInstUserPairSet->insert(VPPair(Q, P)).second)
  1310. (*PairableInstUserMap)[Q].push_back(P);
  1311. }
  1312. if (QUsesP) {
  1313. if (PairableInstUserPairSet->insert(VPPair(P, Q)).second)
  1314. (*PairableInstUserMap)[P].push_back(Q);
  1315. }
  1316. }
  1317. return (QUsesP && PUsesQ);
  1318. }
  1319. // This function walks the use graph of current pairs to see if, starting
  1320. // from P, the walk returns to P.
  1321. bool BBVectorize::pairWillFormCycle(ValuePair P,
  1322. DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
  1323. DenseSet<ValuePair> &CurrentPairs) {
  1324. DEBUG(if (DebugCycleCheck)
  1325. dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
  1326. << *P.second << "\n");
  1327. // A lookup table of visisted pairs is kept because the PairableInstUserMap
  1328. // contains non-direct associations.
  1329. DenseSet<ValuePair> Visited;
  1330. SmallVector<ValuePair, 32> Q;
  1331. // General depth-first post-order traversal:
  1332. Q.push_back(P);
  1333. do {
  1334. ValuePair QTop = Q.pop_back_val();
  1335. Visited.insert(QTop);
  1336. DEBUG(if (DebugCycleCheck)
  1337. dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
  1338. << *QTop.second << "\n");
  1339. DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
  1340. PairableInstUserMap.find(QTop);
  1341. if (QQ == PairableInstUserMap.end())
  1342. continue;
  1343. for (std::vector<ValuePair>::iterator C = QQ->second.begin(),
  1344. CE = QQ->second.end(); C != CE; ++C) {
  1345. if (*C == P) {
  1346. DEBUG(dbgs()
  1347. << "BBV: rejected to prevent non-trivial cycle formation: "
  1348. << QTop.first << " <-> " << C->second << "\n");
  1349. return true;
  1350. }
  1351. if (CurrentPairs.count(*C) && !Visited.count(*C))
  1352. Q.push_back(*C);
  1353. }
  1354. } while (!Q.empty());
  1355. return false;
  1356. }
  1357. // This function builds the initial dag of connected pairs with the
  1358. // pair J at the root.
  1359. void BBVectorize::buildInitialDAGFor(
  1360. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  1361. DenseSet<ValuePair> &CandidatePairsSet,
  1362. std::vector<Value *> &PairableInsts,
  1363. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  1364. DenseSet<ValuePair> &PairableInstUsers,
  1365. DenseMap<Value *, Value *> &ChosenPairs,
  1366. DenseMap<ValuePair, size_t> &DAG, ValuePair J) {
  1367. // Each of these pairs is viewed as the root node of a DAG. The DAG
  1368. // is then walked (depth-first). As this happens, we keep track of
  1369. // the pairs that compose the DAG and the maximum depth of the DAG.
  1370. SmallVector<ValuePairWithDepth, 32> Q;
  1371. // General depth-first post-order traversal:
  1372. Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
  1373. do {
  1374. ValuePairWithDepth QTop = Q.back();
  1375. // Push each child onto the queue:
  1376. bool MoreChildren = false;
  1377. size_t MaxChildDepth = QTop.second;
  1378. DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
  1379. ConnectedPairs.find(QTop.first);
  1380. if (QQ != ConnectedPairs.end())
  1381. for (std::vector<ValuePair>::iterator k = QQ->second.begin(),
  1382. ke = QQ->second.end(); k != ke; ++k) {
  1383. // Make sure that this child pair is still a candidate:
  1384. if (CandidatePairsSet.count(*k)) {
  1385. DenseMap<ValuePair, size_t>::iterator C = DAG.find(*k);
  1386. if (C == DAG.end()) {
  1387. size_t d = getDepthFactor(k->first);
  1388. Q.push_back(ValuePairWithDepth(*k, QTop.second+d));
  1389. MoreChildren = true;
  1390. } else {
  1391. MaxChildDepth = std::max(MaxChildDepth, C->second);
  1392. }
  1393. }
  1394. }
  1395. if (!MoreChildren) {
  1396. // Record the current pair as part of the DAG:
  1397. DAG.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
  1398. Q.pop_back();
  1399. }
  1400. } while (!Q.empty());
  1401. }
  1402. // Given some initial dag, prune it by removing conflicting pairs (pairs
  1403. // that cannot be simultaneously chosen for vectorization).
  1404. void BBVectorize::pruneDAGFor(
  1405. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  1406. std::vector<Value *> &PairableInsts,
  1407. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  1408. DenseSet<ValuePair> &PairableInstUsers,
  1409. DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
  1410. DenseSet<VPPair> &PairableInstUserPairSet,
  1411. DenseMap<Value *, Value *> &ChosenPairs,
  1412. DenseMap<ValuePair, size_t> &DAG,
  1413. DenseSet<ValuePair> &PrunedDAG, ValuePair J,
  1414. bool UseCycleCheck) {
  1415. SmallVector<ValuePairWithDepth, 32> Q;
  1416. // General depth-first post-order traversal:
  1417. Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
  1418. do {
  1419. ValuePairWithDepth QTop = Q.pop_back_val();
  1420. PrunedDAG.insert(QTop.first);
  1421. // Visit each child, pruning as necessary...
  1422. SmallVector<ValuePairWithDepth, 8> BestChildren;
  1423. DenseMap<ValuePair, std::vector<ValuePair> >::iterator QQ =
  1424. ConnectedPairs.find(QTop.first);
  1425. if (QQ == ConnectedPairs.end())
  1426. continue;
  1427. for (std::vector<ValuePair>::iterator K = QQ->second.begin(),
  1428. KE = QQ->second.end(); K != KE; ++K) {
  1429. DenseMap<ValuePair, size_t>::iterator C = DAG.find(*K);
  1430. if (C == DAG.end()) continue;
  1431. // This child is in the DAG, now we need to make sure it is the
  1432. // best of any conflicting children. There could be multiple
  1433. // conflicting children, so first, determine if we're keeping
  1434. // this child, then delete conflicting children as necessary.
  1435. // It is also necessary to guard against pairing-induced
  1436. // dependencies. Consider instructions a .. x .. y .. b
  1437. // such that (a,b) are to be fused and (x,y) are to be fused
  1438. // but a is an input to x and b is an output from y. This
  1439. // means that y cannot be moved after b but x must be moved
  1440. // after b for (a,b) to be fused. In other words, after
  1441. // fusing (a,b) we have y .. a/b .. x where y is an input
  1442. // to a/b and x is an output to a/b: x and y can no longer
  1443. // be legally fused. To prevent this condition, we must
  1444. // make sure that a child pair added to the DAG is not
  1445. // both an input and output of an already-selected pair.
  1446. // Pairing-induced dependencies can also form from more complicated
  1447. // cycles. The pair vs. pair conflicts are easy to check, and so
  1448. // that is done explicitly for "fast rejection", and because for
  1449. // child vs. child conflicts, we may prefer to keep the current
  1450. // pair in preference to the already-selected child.
  1451. DenseSet<ValuePair> CurrentPairs;
  1452. bool CanAdd = true;
  1453. for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
  1454. = BestChildren.begin(), E2 = BestChildren.end();
  1455. C2 != E2; ++C2) {
  1456. if (C2->first.first == C->first.first ||
  1457. C2->first.first == C->first.second ||
  1458. C2->first.second == C->first.first ||
  1459. C2->first.second == C->first.second ||
  1460. pairsConflict(C2->first, C->first, PairableInstUsers,
  1461. UseCycleCheck ? &PairableInstUserMap : nullptr,
  1462. UseCycleCheck ? &PairableInstUserPairSet
  1463. : nullptr)) {
  1464. if (C2->second >= C->second) {
  1465. CanAdd = false;
  1466. break;
  1467. }
  1468. CurrentPairs.insert(C2->first);
  1469. }
  1470. }
  1471. if (!CanAdd) continue;
  1472. // Even worse, this child could conflict with another node already
  1473. // selected for the DAG. If that is the case, ignore this child.
  1474. for (DenseSet<ValuePair>::iterator T = PrunedDAG.begin(),
  1475. E2 = PrunedDAG.end(); T != E2; ++T) {
  1476. if (T->first == C->first.first ||
  1477. T->first == C->first.second ||
  1478. T->second == C->first.first ||
  1479. T->second == C->first.second ||
  1480. pairsConflict(*T, C->first, PairableInstUsers,
  1481. UseCycleCheck ? &PairableInstUserMap : nullptr,
  1482. UseCycleCheck ? &PairableInstUserPairSet
  1483. : nullptr)) {
  1484. CanAdd = false;
  1485. break;
  1486. }
  1487. CurrentPairs.insert(*T);
  1488. }
  1489. if (!CanAdd) continue;
  1490. // And check the queue too...
  1491. for (SmallVectorImpl<ValuePairWithDepth>::iterator C2 = Q.begin(),
  1492. E2 = Q.end(); C2 != E2; ++C2) {
  1493. if (C2->first.first == C->first.first ||
  1494. C2->first.first == C->first.second ||
  1495. C2->first.second == C->first.first ||
  1496. C2->first.second == C->first.second ||
  1497. pairsConflict(C2->first, C->first, PairableInstUsers,
  1498. UseCycleCheck ? &PairableInstUserMap : nullptr,
  1499. UseCycleCheck ? &PairableInstUserPairSet
  1500. : nullptr)) {
  1501. CanAdd = false;
  1502. break;
  1503. }
  1504. CurrentPairs.insert(C2->first);
  1505. }
  1506. if (!CanAdd) continue;
  1507. // Last but not least, check for a conflict with any of the
  1508. // already-chosen pairs.
  1509. for (DenseMap<Value *, Value *>::iterator C2 =
  1510. ChosenPairs.begin(), E2 = ChosenPairs.end();
  1511. C2 != E2; ++C2) {
  1512. if (pairsConflict(*C2, C->first, PairableInstUsers,
  1513. UseCycleCheck ? &PairableInstUserMap : nullptr,
  1514. UseCycleCheck ? &PairableInstUserPairSet
  1515. : nullptr)) {
  1516. CanAdd = false;
  1517. break;
  1518. }
  1519. CurrentPairs.insert(*C2);
  1520. }
  1521. if (!CanAdd) continue;
  1522. // To check for non-trivial cycles formed by the addition of the
  1523. // current pair we've formed a list of all relevant pairs, now use a
  1524. // graph walk to check for a cycle. We start from the current pair and
  1525. // walk the use dag to see if we again reach the current pair. If we
  1526. // do, then the current pair is rejected.
  1527. // FIXME: It may be more efficient to use a topological-ordering
  1528. // algorithm to improve the cycle check. This should be investigated.
  1529. if (UseCycleCheck &&
  1530. pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
  1531. continue;
  1532. // This child can be added, but we may have chosen it in preference
  1533. // to an already-selected child. Check for this here, and if a
  1534. // conflict is found, then remove the previously-selected child
  1535. // before adding this one in its place.
  1536. for (SmallVectorImpl<ValuePairWithDepth>::iterator C2
  1537. = BestChildren.begin(); C2 != BestChildren.end();) {
  1538. if (C2->first.first == C->first.first ||
  1539. C2->first.first == C->first.second ||
  1540. C2->first.second == C->first.first ||
  1541. C2->first.second == C->first.second ||
  1542. pairsConflict(C2->first, C->first, PairableInstUsers))
  1543. C2 = BestChildren.erase(C2);
  1544. else
  1545. ++C2;
  1546. }
  1547. BestChildren.push_back(ValuePairWithDepth(C->first, C->second));
  1548. }
  1549. for (SmallVectorImpl<ValuePairWithDepth>::iterator C
  1550. = BestChildren.begin(), E2 = BestChildren.end();
  1551. C != E2; ++C) {
  1552. size_t DepthF = getDepthFactor(C->first.first);
  1553. Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
  1554. }
  1555. } while (!Q.empty());
  1556. }
  1557. // This function finds the best dag of mututally-compatible connected
  1558. // pairs, given the choice of root pairs as an iterator range.
  1559. void BBVectorize::findBestDAGFor(
  1560. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  1561. DenseSet<ValuePair> &CandidatePairsSet,
  1562. DenseMap<ValuePair, int> &CandidatePairCostSavings,
  1563. std::vector<Value *> &PairableInsts,
  1564. DenseSet<ValuePair> &FixedOrderPairs,
  1565. DenseMap<VPPair, unsigned> &PairConnectionTypes,
  1566. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  1567. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
  1568. DenseSet<ValuePair> &PairableInstUsers,
  1569. DenseMap<ValuePair, std::vector<ValuePair> > &PairableInstUserMap,
  1570. DenseSet<VPPair> &PairableInstUserPairSet,
  1571. DenseMap<Value *, Value *> &ChosenPairs,
  1572. DenseSet<ValuePair> &BestDAG, size_t &BestMaxDepth,
  1573. int &BestEffSize, Value *II, std::vector<Value *>&JJ,
  1574. bool UseCycleCheck) {
  1575. for (std::vector<Value *>::iterator J = JJ.begin(), JE = JJ.end();
  1576. J != JE; ++J) {
  1577. ValuePair IJ(II, *J);
  1578. if (!CandidatePairsSet.count(IJ))
  1579. continue;
  1580. // Before going any further, make sure that this pair does not
  1581. // conflict with any already-selected pairs (see comment below
  1582. // near the DAG pruning for more details).
  1583. DenseSet<ValuePair> ChosenPairSet;
  1584. bool DoesConflict = false;
  1585. for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
  1586. E = ChosenPairs.end(); C != E; ++C) {
  1587. if (pairsConflict(*C, IJ, PairableInstUsers,
  1588. UseCycleCheck ? &PairableInstUserMap : nullptr,
  1589. UseCycleCheck ? &PairableInstUserPairSet : nullptr)) {
  1590. DoesConflict = true;
  1591. break;
  1592. }
  1593. ChosenPairSet.insert(*C);
  1594. }
  1595. if (DoesConflict) continue;
  1596. if (UseCycleCheck &&
  1597. pairWillFormCycle(IJ, PairableInstUserMap, ChosenPairSet))
  1598. continue;
  1599. DenseMap<ValuePair, size_t> DAG;
  1600. buildInitialDAGFor(CandidatePairs, CandidatePairsSet,
  1601. PairableInsts, ConnectedPairs,
  1602. PairableInstUsers, ChosenPairs, DAG, IJ);
  1603. // Because we'll keep the child with the largest depth, the largest
  1604. // depth is still the same in the unpruned DAG.
  1605. size_t MaxDepth = DAG.lookup(IJ);
  1606. DEBUG(if (DebugPairSelection) dbgs() << "BBV: found DAG for pair {"
  1607. << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
  1608. MaxDepth << " and size " << DAG.size() << "\n");
  1609. // At this point the DAG has been constructed, but, may contain
  1610. // contradictory children (meaning that different children of
  1611. // some dag node may be attempting to fuse the same instruction).
  1612. // So now we walk the dag again, in the case of a conflict,
  1613. // keep only the child with the largest depth. To break a tie,
  1614. // favor the first child.
  1615. DenseSet<ValuePair> PrunedDAG;
  1616. pruneDAGFor(CandidatePairs, PairableInsts, ConnectedPairs,
  1617. PairableInstUsers, PairableInstUserMap,
  1618. PairableInstUserPairSet,
  1619. ChosenPairs, DAG, PrunedDAG, IJ, UseCycleCheck);
  1620. int EffSize = 0;
  1621. if (TTI) {
  1622. DenseSet<Value *> PrunedDAGInstrs;
  1623. for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
  1624. E = PrunedDAG.end(); S != E; ++S) {
  1625. PrunedDAGInstrs.insert(S->first);
  1626. PrunedDAGInstrs.insert(S->second);
  1627. }
  1628. // The set of pairs that have already contributed to the total cost.
  1629. DenseSet<ValuePair> IncomingPairs;
  1630. // If the cost model were perfect, this might not be necessary; but we
  1631. // need to make sure that we don't get stuck vectorizing our own
  1632. // shuffle chains.
  1633. bool HasNontrivialInsts = false;
  1634. // The node weights represent the cost savings associated with
  1635. // fusing the pair of instructions.
  1636. for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
  1637. E = PrunedDAG.end(); S != E; ++S) {
  1638. if (!isa<ShuffleVectorInst>(S->first) &&
  1639. !isa<InsertElementInst>(S->first) &&
  1640. !isa<ExtractElementInst>(S->first))
  1641. HasNontrivialInsts = true;
  1642. bool FlipOrder = false;
  1643. if (getDepthFactor(S->first)) {
  1644. int ESContrib = CandidatePairCostSavings.find(*S)->second;
  1645. DEBUG(if (DebugPairSelection) dbgs() << "\tweight {"
  1646. << *S->first << " <-> " << *S->second << "} = " <<
  1647. ESContrib << "\n");
  1648. EffSize += ESContrib;
  1649. }
  1650. // The edge weights contribute in a negative sense: they represent
  1651. // the cost of shuffles.
  1652. DenseMap<ValuePair, std::vector<ValuePair> >::iterator SS =
  1653. ConnectedPairDeps.find(*S);
  1654. if (SS != ConnectedPairDeps.end()) {
  1655. unsigned NumDepsDirect = 0, NumDepsSwap = 0;
  1656. for (std::vector<ValuePair>::iterator T = SS->second.begin(),
  1657. TE = SS->second.end(); T != TE; ++T) {
  1658. VPPair Q(*S, *T);
  1659. if (!PrunedDAG.count(Q.second))
  1660. continue;
  1661. DenseMap<VPPair, unsigned>::iterator R =
  1662. PairConnectionTypes.find(VPPair(Q.second, Q.first));
  1663. assert(R != PairConnectionTypes.end() &&
  1664. "Cannot find pair connection type");
  1665. if (R->second == PairConnectionDirect)
  1666. ++NumDepsDirect;
  1667. else if (R->second == PairConnectionSwap)
  1668. ++NumDepsSwap;
  1669. }
  1670. // If there are more swaps than direct connections, then
  1671. // the pair order will be flipped during fusion. So the real
  1672. // number of swaps is the minimum number.
  1673. FlipOrder = !FixedOrderPairs.count(*S) &&
  1674. ((NumDepsSwap > NumDepsDirect) ||
  1675. FixedOrderPairs.count(ValuePair(S->second, S->first)));
  1676. for (std::vector<ValuePair>::iterator T = SS->second.begin(),
  1677. TE = SS->second.end(); T != TE; ++T) {
  1678. VPPair Q(*S, *T);
  1679. if (!PrunedDAG.count(Q.second))
  1680. continue;
  1681. DenseMap<VPPair, unsigned>::iterator R =
  1682. PairConnectionTypes.find(VPPair(Q.second, Q.first));
  1683. assert(R != PairConnectionTypes.end() &&
  1684. "Cannot find pair connection type");
  1685. Type *Ty1 = Q.second.first->getType(),
  1686. *Ty2 = Q.second.second->getType();
  1687. Type *VTy = getVecTypeForPair(Ty1, Ty2);
  1688. if ((R->second == PairConnectionDirect && FlipOrder) ||
  1689. (R->second == PairConnectionSwap && !FlipOrder) ||
  1690. R->second == PairConnectionSplat) {
  1691. int ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
  1692. VTy, VTy);
  1693. if (VTy->getVectorNumElements() == 2) {
  1694. if (R->second == PairConnectionSplat)
  1695. ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
  1696. TargetTransformInfo::SK_Broadcast, VTy));
  1697. else
  1698. ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
  1699. TargetTransformInfo::SK_Reverse, VTy));
  1700. }
  1701. DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
  1702. *Q.second.first << " <-> " << *Q.second.second <<
  1703. "} -> {" <<
  1704. *S->first << " <-> " << *S->second << "} = " <<
  1705. ESContrib << "\n");
  1706. EffSize -= ESContrib;
  1707. }
  1708. }
  1709. }
  1710. // Compute the cost of outgoing edges. We assume that edges outgoing
  1711. // to shuffles, inserts or extracts can be merged, and so contribute
  1712. // no additional cost.
  1713. if (!S->first->getType()->isVoidTy()) {
  1714. Type *Ty1 = S->first->getType(),
  1715. *Ty2 = S->second->getType();
  1716. Type *VTy = getVecTypeForPair(Ty1, Ty2);
  1717. bool NeedsExtraction = false;
  1718. for (User *U : S->first->users()) {
  1719. if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
  1720. // Shuffle can be folded if it has no other input
  1721. if (isa<UndefValue>(SI->getOperand(1)))
  1722. continue;
  1723. }
  1724. if (isa<ExtractElementInst>(U))
  1725. continue;
  1726. if (PrunedDAGInstrs.count(U))
  1727. continue;
  1728. NeedsExtraction = true;
  1729. break;
  1730. }
  1731. if (NeedsExtraction) {
  1732. int ESContrib;
  1733. if (Ty1->isVectorTy()) {
  1734. ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
  1735. Ty1, VTy);
  1736. ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
  1737. TargetTransformInfo::SK_ExtractSubvector, VTy, 0, Ty1));
  1738. } else
  1739. ESContrib = (int) TTI->getVectorInstrCost(
  1740. Instruction::ExtractElement, VTy, 0);
  1741. DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
  1742. *S->first << "} = " << ESContrib << "\n");
  1743. EffSize -= ESContrib;
  1744. }
  1745. NeedsExtraction = false;
  1746. for (User *U : S->second->users()) {
  1747. if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(U)) {
  1748. // Shuffle can be folded if it has no other input
  1749. if (isa<UndefValue>(SI->getOperand(1)))
  1750. continue;
  1751. }
  1752. if (isa<ExtractElementInst>(U))
  1753. continue;
  1754. if (PrunedDAGInstrs.count(U))
  1755. continue;
  1756. NeedsExtraction = true;
  1757. break;
  1758. }
  1759. if (NeedsExtraction) {
  1760. int ESContrib;
  1761. if (Ty2->isVectorTy()) {
  1762. ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
  1763. Ty2, VTy);
  1764. ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
  1765. TargetTransformInfo::SK_ExtractSubvector, VTy,
  1766. Ty1->isVectorTy() ? Ty1->getVectorNumElements() : 1, Ty2));
  1767. } else
  1768. ESContrib = (int) TTI->getVectorInstrCost(
  1769. Instruction::ExtractElement, VTy, 1);
  1770. DEBUG(if (DebugPairSelection) dbgs() << "\tcost {" <<
  1771. *S->second << "} = " << ESContrib << "\n");
  1772. EffSize -= ESContrib;
  1773. }
  1774. }
  1775. // Compute the cost of incoming edges.
  1776. if (!isa<LoadInst>(S->first) && !isa<StoreInst>(S->first)) {
  1777. Instruction *S1 = cast<Instruction>(S->first),
  1778. *S2 = cast<Instruction>(S->second);
  1779. for (unsigned o = 0; o < S1->getNumOperands(); ++o) {
  1780. Value *O1 = S1->getOperand(o), *O2 = S2->getOperand(o);
  1781. // Combining constants into vector constants (or small vector
  1782. // constants into larger ones are assumed free).
  1783. if (isa<Constant>(O1) && isa<Constant>(O2))
  1784. continue;
  1785. if (FlipOrder)
  1786. std::swap(O1, O2);
  1787. ValuePair VP = ValuePair(O1, O2);
  1788. ValuePair VPR = ValuePair(O2, O1);
  1789. // Internal edges are not handled here.
  1790. if (PrunedDAG.count(VP) || PrunedDAG.count(VPR))
  1791. continue;
  1792. Type *Ty1 = O1->getType(),
  1793. *Ty2 = O2->getType();
  1794. Type *VTy = getVecTypeForPair(Ty1, Ty2);
  1795. // Combining vector operations of the same type is also assumed
  1796. // folded with other operations.
  1797. if (Ty1 == Ty2) {
  1798. // If both are insert elements, then both can be widened.
  1799. InsertElementInst *IEO1 = dyn_cast<InsertElementInst>(O1),
  1800. *IEO2 = dyn_cast<InsertElementInst>(O2);
  1801. if (IEO1 && IEO2 && isPureIEChain(IEO1) && isPureIEChain(IEO2))
  1802. continue;
  1803. // If both are extract elements, and both have the same input
  1804. // type, then they can be replaced with a shuffle
  1805. ExtractElementInst *EIO1 = dyn_cast<ExtractElementInst>(O1),
  1806. *EIO2 = dyn_cast<ExtractElementInst>(O2);
  1807. if (EIO1 && EIO2 &&
  1808. EIO1->getOperand(0)->getType() ==
  1809. EIO2->getOperand(0)->getType())
  1810. continue;
  1811. // If both are a shuffle with equal operand types and only two
  1812. // unqiue operands, then they can be replaced with a single
  1813. // shuffle
  1814. ShuffleVectorInst *SIO1 = dyn_cast<ShuffleVectorInst>(O1),
  1815. *SIO2 = dyn_cast<ShuffleVectorInst>(O2);
  1816. if (SIO1 && SIO2 &&
  1817. SIO1->getOperand(0)->getType() ==
  1818. SIO2->getOperand(0)->getType()) {
  1819. SmallSet<Value *, 4> SIOps;
  1820. SIOps.insert(SIO1->getOperand(0));
  1821. SIOps.insert(SIO1->getOperand(1));
  1822. SIOps.insert(SIO2->getOperand(0));
  1823. SIOps.insert(SIO2->getOperand(1));
  1824. if (SIOps.size() <= 2)
  1825. continue;
  1826. }
  1827. }
  1828. int ESContrib;
  1829. // This pair has already been formed.
  1830. if (IncomingPairs.count(VP)) {
  1831. continue;
  1832. } else if (IncomingPairs.count(VPR)) {
  1833. ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
  1834. VTy, VTy);
  1835. if (VTy->getVectorNumElements() == 2)
  1836. ESContrib = std::min(ESContrib, (int) TTI->getShuffleCost(
  1837. TargetTransformInfo::SK_Reverse, VTy));
  1838. } else if (!Ty1->isVectorTy() && !Ty2->isVectorTy()) {
  1839. ESContrib = (int) TTI->getVectorInstrCost(
  1840. Instruction::InsertElement, VTy, 0);
  1841. ESContrib += (int) TTI->getVectorInstrCost(
  1842. Instruction::InsertElement, VTy, 1);
  1843. } else if (!Ty1->isVectorTy()) {
  1844. // O1 needs to be inserted into a vector of size O2, and then
  1845. // both need to be shuffled together.
  1846. ESContrib = (int) TTI->getVectorInstrCost(
  1847. Instruction::InsertElement, Ty2, 0);
  1848. ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
  1849. VTy, Ty2);
  1850. } else if (!Ty2->isVectorTy()) {
  1851. // O2 needs to be inserted into a vector of size O1, and then
  1852. // both need to be shuffled together.
  1853. ESContrib = (int) TTI->getVectorInstrCost(
  1854. Instruction::InsertElement, Ty1, 0);
  1855. ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
  1856. VTy, Ty1);
  1857. } else {
  1858. Type *TyBig = Ty1, *TySmall = Ty2;
  1859. if (Ty2->getVectorNumElements() > Ty1->getVectorNumElements())
  1860. std::swap(TyBig, TySmall);
  1861. ESContrib = (int) getInstrCost(Instruction::ShuffleVector,
  1862. VTy, TyBig);
  1863. if (TyBig != TySmall)
  1864. ESContrib += (int) getInstrCost(Instruction::ShuffleVector,
  1865. TyBig, TySmall);
  1866. }
  1867. DEBUG(if (DebugPairSelection) dbgs() << "\tcost {"
  1868. << *O1 << " <-> " << *O2 << "} = " <<
  1869. ESContrib << "\n");
  1870. EffSize -= ESContrib;
  1871. IncomingPairs.insert(VP);
  1872. }
  1873. }
  1874. }
  1875. if (!HasNontrivialInsts) {
  1876. DEBUG(if (DebugPairSelection) dbgs() <<
  1877. "\tNo non-trivial instructions in DAG;"
  1878. " override to zero effective size\n");
  1879. EffSize = 0;
  1880. }
  1881. } else {
  1882. for (DenseSet<ValuePair>::iterator S = PrunedDAG.begin(),
  1883. E = PrunedDAG.end(); S != E; ++S)
  1884. EffSize += (int) getDepthFactor(S->first);
  1885. }
  1886. DEBUG(if (DebugPairSelection)
  1887. dbgs() << "BBV: found pruned DAG for pair {"
  1888. << *IJ.first << " <-> " << *IJ.second << "} of depth " <<
  1889. MaxDepth << " and size " << PrunedDAG.size() <<
  1890. " (effective size: " << EffSize << ")\n");
  1891. if (((TTI && !UseChainDepthWithTI) ||
  1892. MaxDepth >= Config.ReqChainDepth) &&
  1893. EffSize > 0 && EffSize > BestEffSize) {
  1894. BestMaxDepth = MaxDepth;
  1895. BestEffSize = EffSize;
  1896. BestDAG = PrunedDAG;
  1897. }
  1898. }
  1899. }
  1900. // Given the list of candidate pairs, this function selects those
  1901. // that will be fused into vector instructions.
  1902. void BBVectorize::choosePairs(
  1903. DenseMap<Value *, std::vector<Value *> > &CandidatePairs,
  1904. DenseSet<ValuePair> &CandidatePairsSet,
  1905. DenseMap<ValuePair, int> &CandidatePairCostSavings,
  1906. std::vector<Value *> &PairableInsts,
  1907. DenseSet<ValuePair> &FixedOrderPairs,
  1908. DenseMap<VPPair, unsigned> &PairConnectionTypes,
  1909. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  1910. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps,
  1911. DenseSet<ValuePair> &PairableInstUsers,
  1912. DenseMap<Value *, Value *>& ChosenPairs) {
  1913. bool UseCycleCheck =
  1914. CandidatePairsSet.size() <= Config.MaxCandPairsForCycleCheck;
  1915. DenseMap<Value *, std::vector<Value *> > CandidatePairs2;
  1916. for (DenseSet<ValuePair>::iterator I = CandidatePairsSet.begin(),
  1917. E = CandidatePairsSet.end(); I != E; ++I) {
  1918. std::vector<Value *> &JJ = CandidatePairs2[I->second];
  1919. if (JJ.empty()) JJ.reserve(32);
  1920. JJ.push_back(I->first);
  1921. }
  1922. DenseMap<ValuePair, std::vector<ValuePair> > PairableInstUserMap;
  1923. DenseSet<VPPair> PairableInstUserPairSet;
  1924. for (std::vector<Value *>::iterator I = PairableInsts.begin(),
  1925. E = PairableInsts.end(); I != E; ++I) {
  1926. // The number of possible pairings for this variable:
  1927. size_t NumChoices = CandidatePairs.lookup(*I).size();
  1928. if (!NumChoices) continue;
  1929. std::vector<Value *> &JJ = CandidatePairs[*I];
  1930. // The best pair to choose and its dag:
  1931. size_t BestMaxDepth = 0;
  1932. int BestEffSize = 0;
  1933. DenseSet<ValuePair> BestDAG;
  1934. findBestDAGFor(CandidatePairs, CandidatePairsSet,
  1935. CandidatePairCostSavings,
  1936. PairableInsts, FixedOrderPairs, PairConnectionTypes,
  1937. ConnectedPairs, ConnectedPairDeps,
  1938. PairableInstUsers, PairableInstUserMap,
  1939. PairableInstUserPairSet, ChosenPairs,
  1940. BestDAG, BestMaxDepth, BestEffSize, *I, JJ,
  1941. UseCycleCheck);
  1942. if (BestDAG.empty())
  1943. continue;
  1944. // A dag has been chosen (or not) at this point. If no dag was
  1945. // chosen, then this instruction, I, cannot be paired (and is no longer
  1946. // considered).
  1947. DEBUG(dbgs() << "BBV: selected pairs in the best DAG for: "
  1948. << *cast<Instruction>(*I) << "\n");
  1949. for (DenseSet<ValuePair>::iterator S = BestDAG.begin(),
  1950. SE2 = BestDAG.end(); S != SE2; ++S) {
  1951. // Insert the members of this dag into the list of chosen pairs.
  1952. ChosenPairs.insert(ValuePair(S->first, S->second));
  1953. DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
  1954. *S->second << "\n");
  1955. // Remove all candidate pairs that have values in the chosen dag.
  1956. std::vector<Value *> &KK = CandidatePairs[S->first];
  1957. for (std::vector<Value *>::iterator K = KK.begin(), KE = KK.end();
  1958. K != KE; ++K) {
  1959. if (*K == S->second)
  1960. continue;
  1961. CandidatePairsSet.erase(ValuePair(S->first, *K));
  1962. }
  1963. std::vector<Value *> &LL = CandidatePairs2[S->second];
  1964. for (std::vector<Value *>::iterator L = LL.begin(), LE = LL.end();
  1965. L != LE; ++L) {
  1966. if (*L == S->first)
  1967. continue;
  1968. CandidatePairsSet.erase(ValuePair(*L, S->second));
  1969. }
  1970. std::vector<Value *> &MM = CandidatePairs[S->second];
  1971. for (std::vector<Value *>::iterator M = MM.begin(), ME = MM.end();
  1972. M != ME; ++M) {
  1973. assert(*M != S->first && "Flipped pair in candidate list?");
  1974. CandidatePairsSet.erase(ValuePair(S->second, *M));
  1975. }
  1976. std::vector<Value *> &NN = CandidatePairs2[S->first];
  1977. for (std::vector<Value *>::iterator N = NN.begin(), NE = NN.end();
  1978. N != NE; ++N) {
  1979. assert(*N != S->second && "Flipped pair in candidate list?");
  1980. CandidatePairsSet.erase(ValuePair(*N, S->first));
  1981. }
  1982. }
  1983. }
  1984. DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
  1985. }
  1986. std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
  1987. unsigned n = 0) {
  1988. if (!I->hasName())
  1989. return "";
  1990. return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
  1991. (n > 0 ? "." + utostr(n) : "")).str();
  1992. }
  1993. // Returns the value that is to be used as the pointer input to the vector
  1994. // instruction that fuses I with J.
  1995. Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
  1996. Instruction *I, Instruction *J, unsigned o) {
  1997. Value *IPtr, *JPtr;
  1998. unsigned IAlignment, JAlignment, IAddressSpace, JAddressSpace;
  1999. int64_t OffsetInElmts;
  2000. // Note: the analysis might fail here, that is why the pair order has
  2001. // been precomputed (OffsetInElmts must be unused here).
  2002. (void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
  2003. IAddressSpace, JAddressSpace,
  2004. OffsetInElmts, false);
  2005. // The pointer value is taken to be the one with the lowest offset.
  2006. Value *VPtr = IPtr;
  2007. Type *ArgTypeI = IPtr->getType()->getPointerElementType();
  2008. Type *ArgTypeJ = JPtr->getType()->getPointerElementType();
  2009. Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
  2010. Type *VArgPtrType
  2011. = PointerType::get(VArgType,
  2012. IPtr->getType()->getPointerAddressSpace());
  2013. return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
  2014. /* insert before */ I);
  2015. }
  2016. void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
  2017. unsigned MaskOffset, unsigned NumInElem,
  2018. unsigned NumInElem1, unsigned IdxOffset,
  2019. std::vector<Constant*> &Mask) {
  2020. unsigned NumElem1 = J->getType()->getVectorNumElements();
  2021. for (unsigned v = 0; v < NumElem1; ++v) {
  2022. int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
  2023. if (m < 0) {
  2024. Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
  2025. } else {
  2026. unsigned mm = m + (int) IdxOffset;
  2027. if (m >= (int) NumInElem1)
  2028. mm += (int) NumInElem;
  2029. Mask[v+MaskOffset] =
  2030. ConstantInt::get(Type::getInt32Ty(Context), mm);
  2031. }
  2032. }
  2033. }
  2034. // Returns the value that is to be used as the vector-shuffle mask to the
  2035. // vector instruction that fuses I with J.
  2036. Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
  2037. Instruction *I, Instruction *J) {
  2038. // This is the shuffle mask. We need to append the second
  2039. // mask to the first, and the numbers need to be adjusted.
  2040. Type *ArgTypeI = I->getType();
  2041. Type *ArgTypeJ = J->getType();
  2042. Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
  2043. unsigned NumElemI = ArgTypeI->getVectorNumElements();
  2044. // Get the total number of elements in the fused vector type.
  2045. // By definition, this must equal the number of elements in
  2046. // the final mask.
  2047. unsigned NumElem = VArgType->getVectorNumElements();
  2048. std::vector<Constant*> Mask(NumElem);
  2049. Type *OpTypeI = I->getOperand(0)->getType();
  2050. unsigned NumInElemI = OpTypeI->getVectorNumElements();
  2051. Type *OpTypeJ = J->getOperand(0)->getType();
  2052. unsigned NumInElemJ = OpTypeJ->getVectorNumElements();
  2053. // The fused vector will be:
  2054. // -----------------------------------------------------
  2055. // | NumInElemI | NumInElemJ | NumInElemI | NumInElemJ |
  2056. // -----------------------------------------------------
  2057. // from which we'll extract NumElem total elements (where the first NumElemI
  2058. // of them come from the mask in I and the remainder come from the mask
  2059. // in J.
  2060. // For the mask from the first pair...
  2061. fillNewShuffleMask(Context, I, 0, NumInElemJ, NumInElemI,
  2062. 0, Mask);
  2063. // For the mask from the second pair...
  2064. fillNewShuffleMask(Context, J, NumElemI, NumInElemI, NumInElemJ,
  2065. NumInElemI, Mask);
  2066. return ConstantVector::get(Mask);
  2067. }
  2068. bool BBVectorize::expandIEChain(LLVMContext& Context, Instruction *I,
  2069. Instruction *J, unsigned o, Value *&LOp,
  2070. unsigned numElemL,
  2071. Type *ArgTypeL, Type *ArgTypeH,
  2072. bool IBeforeJ, unsigned IdxOff) {
  2073. bool ExpandedIEChain = false;
  2074. if (InsertElementInst *LIE = dyn_cast<InsertElementInst>(LOp)) {
  2075. // If we have a pure insertelement chain, then this can be rewritten
  2076. // into a chain that directly builds the larger type.
  2077. if (isPureIEChain(LIE)) {
  2078. SmallVector<Value *, 8> VectElemts(numElemL,
  2079. UndefValue::get(ArgTypeL->getScalarType()));
  2080. InsertElementInst *LIENext = LIE;
  2081. do {
  2082. unsigned Idx =
  2083. cast<ConstantInt>(LIENext->getOperand(2))->getSExtValue();
  2084. VectElemts[Idx] = LIENext->getOperand(1);
  2085. } while ((LIENext =
  2086. dyn_cast<InsertElementInst>(LIENext->getOperand(0))));
  2087. LIENext = nullptr;
  2088. Value *LIEPrev = UndefValue::get(ArgTypeH);
  2089. for (unsigned i = 0; i < numElemL; ++i) {
  2090. if (isa<UndefValue>(VectElemts[i])) continue;
  2091. LIENext = InsertElementInst::Create(LIEPrev, VectElemts[i],
  2092. ConstantInt::get(Type::getInt32Ty(Context),
  2093. i + IdxOff),
  2094. getReplacementName(IBeforeJ ? I : J,
  2095. true, o, i+1));
  2096. LIENext->insertBefore(IBeforeJ ? J : I);
  2097. LIEPrev = LIENext;
  2098. }
  2099. LOp = LIENext ? (Value*) LIENext : UndefValue::get(ArgTypeH);
  2100. ExpandedIEChain = true;
  2101. }
  2102. }
  2103. return ExpandedIEChain;
  2104. }
  2105. static unsigned getNumScalarElements(Type *Ty) {
  2106. if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
  2107. return VecTy->getNumElements();
  2108. return 1;
  2109. }
  2110. // Returns the value to be used as the specified operand of the vector
  2111. // instruction that fuses I with J.
  2112. Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
  2113. Instruction *J, unsigned o, bool IBeforeJ) {
  2114. Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
  2115. Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
  2116. // Compute the fused vector type for this operand
  2117. Type *ArgTypeI = I->getOperand(o)->getType();
  2118. Type *ArgTypeJ = J->getOperand(o)->getType();
  2119. VectorType *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
  2120. Instruction *L = I, *H = J;
  2121. Type *ArgTypeL = ArgTypeI, *ArgTypeH = ArgTypeJ;
  2122. unsigned numElemL = getNumScalarElements(ArgTypeL);
  2123. unsigned numElemH = getNumScalarElements(ArgTypeH);
  2124. Value *LOp = L->getOperand(o);
  2125. Value *HOp = H->getOperand(o);
  2126. unsigned numElem = VArgType->getNumElements();
  2127. // First, we check if we can reuse the "original" vector outputs (if these
  2128. // exist). We might need a shuffle.
  2129. ExtractElementInst *LEE = dyn_cast<ExtractElementInst>(LOp);
  2130. ExtractElementInst *HEE = dyn_cast<ExtractElementInst>(HOp);
  2131. ShuffleVectorInst *LSV = dyn_cast<ShuffleVectorInst>(LOp);
  2132. ShuffleVectorInst *HSV = dyn_cast<ShuffleVectorInst>(HOp);
  2133. // FIXME: If we're fusing shuffle instructions, then we can't apply this
  2134. // optimization. The input vectors to the shuffle might be a different
  2135. // length from the shuffle outputs. Unfortunately, the replacement
  2136. // shuffle mask has already been formed, and the mask entries are sensitive
  2137. // to the sizes of the inputs.
  2138. bool IsSizeChangeShuffle =
  2139. isa<ShuffleVectorInst>(L) &&
  2140. (LOp->getType() != L->getType() || HOp->getType() != H->getType());
  2141. if ((LEE || LSV) && (HEE || HSV) && !IsSizeChangeShuffle) {
  2142. // We can have at most two unique vector inputs.
  2143. bool CanUseInputs = true;
  2144. Value *I1, *I2 = nullptr;
  2145. if (LEE) {
  2146. I1 = LEE->getOperand(0);
  2147. } else {
  2148. I1 = LSV->getOperand(0);
  2149. I2 = LSV->getOperand(1);
  2150. if (I2 == I1 || isa<UndefValue>(I2))
  2151. I2 = nullptr;
  2152. }
  2153. if (HEE) {
  2154. Value *I3 = HEE->getOperand(0);
  2155. if (!I2 && I3 != I1)
  2156. I2 = I3;
  2157. else if (I3 != I1 && I3 != I2)
  2158. CanUseInputs = false;
  2159. } else {
  2160. Value *I3 = HSV->getOperand(0);
  2161. if (!I2 && I3 != I1)
  2162. I2 = I3;
  2163. else if (I3 != I1 && I3 != I2)
  2164. CanUseInputs = false;
  2165. if (CanUseInputs) {
  2166. Value *I4 = HSV->getOperand(1);
  2167. if (!isa<UndefValue>(I4)) {
  2168. if (!I2 && I4 != I1)
  2169. I2 = I4;
  2170. else if (I4 != I1 && I4 != I2)
  2171. CanUseInputs = false;
  2172. }
  2173. }
  2174. }
  2175. if (CanUseInputs) {
  2176. unsigned LOpElem =
  2177. cast<Instruction>(LOp)->getOperand(0)->getType()
  2178. ->getVectorNumElements();
  2179. unsigned HOpElem =
  2180. cast<Instruction>(HOp)->getOperand(0)->getType()
  2181. ->getVectorNumElements();
  2182. // We have one or two input vectors. We need to map each index of the
  2183. // operands to the index of the original vector.
  2184. SmallVector<std::pair<int, int>, 8> II(numElem);
  2185. for (unsigned i = 0; i < numElemL; ++i) {
  2186. int Idx, INum;
  2187. if (LEE) {
  2188. Idx =
  2189. cast<ConstantInt>(LEE->getOperand(1))->getSExtValue();
  2190. INum = LEE->getOperand(0) == I1 ? 0 : 1;
  2191. } else {
  2192. Idx = LSV->getMaskValue(i);
  2193. if (Idx < (int) LOpElem) {
  2194. INum = LSV->getOperand(0) == I1 ? 0 : 1;
  2195. } else {
  2196. Idx -= LOpElem;
  2197. INum = LSV->getOperand(1) == I1 ? 0 : 1;
  2198. }
  2199. }
  2200. II[i] = std::pair<int, int>(Idx, INum);
  2201. }
  2202. for (unsigned i = 0; i < numElemH; ++i) {
  2203. int Idx, INum;
  2204. if (HEE) {
  2205. Idx =
  2206. cast<ConstantInt>(HEE->getOperand(1))->getSExtValue();
  2207. INum = HEE->getOperand(0) == I1 ? 0 : 1;
  2208. } else {
  2209. Idx = HSV->getMaskValue(i);
  2210. if (Idx < (int) HOpElem) {
  2211. INum = HSV->getOperand(0) == I1 ? 0 : 1;
  2212. } else {
  2213. Idx -= HOpElem;
  2214. INum = HSV->getOperand(1) == I1 ? 0 : 1;
  2215. }
  2216. }
  2217. II[i + numElemL] = std::pair<int, int>(Idx, INum);
  2218. }
  2219. // We now have an array which tells us from which index of which
  2220. // input vector each element of the operand comes.
  2221. VectorType *I1T = cast<VectorType>(I1->getType());
  2222. unsigned I1Elem = I1T->getNumElements();
  2223. if (!I2) {
  2224. // In this case there is only one underlying vector input. Check for
  2225. // the trivial case where we can use the input directly.
  2226. if (I1Elem == numElem) {
  2227. bool ElemInOrder = true;
  2228. for (unsigned i = 0; i < numElem; ++i) {
  2229. if (II[i].first != (int) i && II[i].first != -1) {
  2230. ElemInOrder = false;
  2231. break;
  2232. }
  2233. }
  2234. if (ElemInOrder)
  2235. return I1;
  2236. }
  2237. // A shuffle is needed.
  2238. std::vector<Constant *> Mask(numElem);
  2239. for (unsigned i = 0; i < numElem; ++i) {
  2240. int Idx = II[i].first;
  2241. if (Idx == -1)
  2242. Mask[i] = UndefValue::get(Type::getInt32Ty(Context));
  2243. else
  2244. Mask[i] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
  2245. }
  2246. Instruction *S =
  2247. new ShuffleVectorInst(I1, UndefValue::get(I1T),
  2248. ConstantVector::get(Mask),
  2249. getReplacementName(IBeforeJ ? I : J,
  2250. true, o));
  2251. S->insertBefore(IBeforeJ ? J : I);
  2252. return S;
  2253. }
  2254. VectorType *I2T = cast<VectorType>(I2->getType());
  2255. unsigned I2Elem = I2T->getNumElements();
  2256. // This input comes from two distinct vectors. The first step is to
  2257. // make sure that both vectors are the same length. If not, the
  2258. // smaller one will need to grow before they can be shuffled together.
  2259. if (I1Elem < I2Elem) {
  2260. std::vector<Constant *> Mask(I2Elem);
  2261. unsigned v = 0;
  2262. for (; v < I1Elem; ++v)
  2263. Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
  2264. for (; v < I2Elem; ++v)
  2265. Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
  2266. Instruction *NewI1 =
  2267. new ShuffleVectorInst(I1, UndefValue::get(I1T),
  2268. ConstantVector::get(Mask),
  2269. getReplacementName(IBeforeJ ? I : J,
  2270. true, o, 1));
  2271. NewI1->insertBefore(IBeforeJ ? J : I);
  2272. I1 = NewI1;
  2273. I1Elem = I2Elem;
  2274. } else if (I1Elem > I2Elem) {
  2275. std::vector<Constant *> Mask(I1Elem);
  2276. unsigned v = 0;
  2277. for (; v < I2Elem; ++v)
  2278. Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
  2279. for (; v < I1Elem; ++v)
  2280. Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
  2281. Instruction *NewI2 =
  2282. new ShuffleVectorInst(I2, UndefValue::get(I2T),
  2283. ConstantVector::get(Mask),
  2284. getReplacementName(IBeforeJ ? I : J,
  2285. true, o, 1));
  2286. NewI2->insertBefore(IBeforeJ ? J : I);
  2287. I2 = NewI2;
  2288. }
  2289. // Now that both I1 and I2 are the same length we can shuffle them
  2290. // together (and use the result).
  2291. std::vector<Constant *> Mask(numElem);
  2292. for (unsigned v = 0; v < numElem; ++v) {
  2293. if (II[v].first == -1) {
  2294. Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
  2295. } else {
  2296. int Idx = II[v].first + II[v].second * I1Elem;
  2297. Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
  2298. }
  2299. }
  2300. Instruction *NewOp =
  2301. new ShuffleVectorInst(I1, I2, ConstantVector::get(Mask),
  2302. getReplacementName(IBeforeJ ? I : J, true, o));
  2303. NewOp->insertBefore(IBeforeJ ? J : I);
  2304. return NewOp;
  2305. }
  2306. }
  2307. Type *ArgType = ArgTypeL;
  2308. if (numElemL < numElemH) {
  2309. if (numElemL == 1 && expandIEChain(Context, I, J, o, HOp, numElemH,
  2310. ArgTypeL, VArgType, IBeforeJ, 1)) {
  2311. // This is another short-circuit case: we're combining a scalar into
  2312. // a vector that is formed by an IE chain. We've just expanded the IE
  2313. // chain, now insert the scalar and we're done.
  2314. Instruction *S = InsertElementInst::Create(HOp, LOp, CV0,
  2315. getReplacementName(IBeforeJ ? I : J, true, o));
  2316. S->insertBefore(IBeforeJ ? J : I);
  2317. return S;
  2318. } else if (!expandIEChain(Context, I, J, o, LOp, numElemL, ArgTypeL,
  2319. ArgTypeH, IBeforeJ)) {
  2320. // The two vector inputs to the shuffle must be the same length,
  2321. // so extend the smaller vector to be the same length as the larger one.
  2322. Instruction *NLOp;
  2323. if (numElemL > 1) {
  2324. std::vector<Constant *> Mask(numElemH);
  2325. unsigned v = 0;
  2326. for (; v < numElemL; ++v)
  2327. Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
  2328. for (; v < numElemH; ++v)
  2329. Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
  2330. NLOp = new ShuffleVectorInst(LOp, UndefValue::get(ArgTypeL),
  2331. ConstantVector::get(Mask),
  2332. getReplacementName(IBeforeJ ? I : J,
  2333. true, o, 1));
  2334. } else {
  2335. NLOp = InsertElementInst::Create(UndefValue::get(ArgTypeH), LOp, CV0,
  2336. getReplacementName(IBeforeJ ? I : J,
  2337. true, o, 1));
  2338. }
  2339. NLOp->insertBefore(IBeforeJ ? J : I);
  2340. LOp = NLOp;
  2341. }
  2342. ArgType = ArgTypeH;
  2343. } else if (numElemL > numElemH) {
  2344. if (numElemH == 1 && expandIEChain(Context, I, J, o, LOp, numElemL,
  2345. ArgTypeH, VArgType, IBeforeJ)) {
  2346. Instruction *S =
  2347. InsertElementInst::Create(LOp, HOp,
  2348. ConstantInt::get(Type::getInt32Ty(Context),
  2349. numElemL),
  2350. getReplacementName(IBeforeJ ? I : J,
  2351. true, o));
  2352. S->insertBefore(IBeforeJ ? J : I);
  2353. return S;
  2354. } else if (!expandIEChain(Context, I, J, o, HOp, numElemH, ArgTypeH,
  2355. ArgTypeL, IBeforeJ)) {
  2356. Instruction *NHOp;
  2357. if (numElemH > 1) {
  2358. std::vector<Constant *> Mask(numElemL);
  2359. unsigned v = 0;
  2360. for (; v < numElemH; ++v)
  2361. Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
  2362. for (; v < numElemL; ++v)
  2363. Mask[v] = UndefValue::get(Type::getInt32Ty(Context));
  2364. NHOp = new ShuffleVectorInst(HOp, UndefValue::get(ArgTypeH),
  2365. ConstantVector::get(Mask),
  2366. getReplacementName(IBeforeJ ? I : J,
  2367. true, o, 1));
  2368. } else {
  2369. NHOp = InsertElementInst::Create(UndefValue::get(ArgTypeL), HOp, CV0,
  2370. getReplacementName(IBeforeJ ? I : J,
  2371. true, o, 1));
  2372. }
  2373. NHOp->insertBefore(IBeforeJ ? J : I);
  2374. HOp = NHOp;
  2375. }
  2376. }
  2377. if (ArgType->isVectorTy()) {
  2378. unsigned numElem = VArgType->getVectorNumElements();
  2379. std::vector<Constant*> Mask(numElem);
  2380. for (unsigned v = 0; v < numElem; ++v) {
  2381. unsigned Idx = v;
  2382. // If the low vector was expanded, we need to skip the extra
  2383. // undefined entries.
  2384. if (v >= numElemL && numElemH > numElemL)
  2385. Idx += (numElemH - numElemL);
  2386. Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), Idx);
  2387. }
  2388. Instruction *BV = new ShuffleVectorInst(LOp, HOp,
  2389. ConstantVector::get(Mask),
  2390. getReplacementName(IBeforeJ ? I : J, true, o));
  2391. BV->insertBefore(IBeforeJ ? J : I);
  2392. return BV;
  2393. }
  2394. Instruction *BV1 = InsertElementInst::Create(
  2395. UndefValue::get(VArgType), LOp, CV0,
  2396. getReplacementName(IBeforeJ ? I : J,
  2397. true, o, 1));
  2398. BV1->insertBefore(IBeforeJ ? J : I);
  2399. Instruction *BV2 = InsertElementInst::Create(BV1, HOp, CV1,
  2400. getReplacementName(IBeforeJ ? I : J,
  2401. true, o, 2));
  2402. BV2->insertBefore(IBeforeJ ? J : I);
  2403. return BV2;
  2404. }
  2405. // This function creates an array of values that will be used as the inputs
  2406. // to the vector instruction that fuses I with J.
  2407. void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
  2408. Instruction *I, Instruction *J,
  2409. SmallVectorImpl<Value *> &ReplacedOperands,
  2410. bool IBeforeJ) {
  2411. unsigned NumOperands = I->getNumOperands();
  2412. for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
  2413. // Iterate backward so that we look at the store pointer
  2414. // first and know whether or not we need to flip the inputs.
  2415. if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
  2416. // This is the pointer for a load/store instruction.
  2417. ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o);
  2418. continue;
  2419. } else if (isa<CallInst>(I)) {
  2420. Function *F = cast<CallInst>(I)->getCalledFunction();
  2421. Intrinsic::ID IID = F->getIntrinsicID();
  2422. if (o == NumOperands-1) {
  2423. BasicBlock &BB = *I->getParent();
  2424. Module *M = BB.getParent()->getParent();
  2425. Type *ArgTypeI = I->getType();
  2426. Type *ArgTypeJ = J->getType();
  2427. Type *VArgType = getVecTypeForPair(ArgTypeI, ArgTypeJ);
  2428. ReplacedOperands[o] = Intrinsic::getDeclaration(M, IID, VArgType);
  2429. continue;
  2430. } else if ((IID == Intrinsic::powi || IID == Intrinsic::ctlz ||
  2431. IID == Intrinsic::cttz) && o == 1) {
  2432. // The second argument of powi/ctlz/cttz is a single integer/constant
  2433. // and we've already checked that both arguments are equal.
  2434. // As a result, we just keep I's second argument.
  2435. ReplacedOperands[o] = I->getOperand(o);
  2436. continue;
  2437. }
  2438. } else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
  2439. ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
  2440. continue;
  2441. }
  2442. ReplacedOperands[o] = getReplacementInput(Context, I, J, o, IBeforeJ);
  2443. }
  2444. }
  2445. // This function creates two values that represent the outputs of the
  2446. // original I and J instructions. These are generally vector shuffles
  2447. // or extracts. In many cases, these will end up being unused and, thus,
  2448. // eliminated by later passes.
  2449. void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
  2450. Instruction *J, Instruction *K,
  2451. Instruction *&InsertionPt,
  2452. Instruction *&K1, Instruction *&K2) {
  2453. if (isa<StoreInst>(I)) {
  2454. AA->replaceWithNewValue(I, K);
  2455. AA->replaceWithNewValue(J, K);
  2456. } else {
  2457. Type *IType = I->getType();
  2458. Type *JType = J->getType();
  2459. VectorType *VType = getVecTypeForPair(IType, JType);
  2460. unsigned numElem = VType->getNumElements();
  2461. unsigned numElemI = getNumScalarElements(IType);
  2462. unsigned numElemJ = getNumScalarElements(JType);
  2463. if (IType->isVectorTy()) {
  2464. std::vector<Constant*> Mask1(numElemI), Mask2(numElemI);
  2465. for (unsigned v = 0; v < numElemI; ++v) {
  2466. Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
  2467. Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemJ+v);
  2468. }
  2469. K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
  2470. ConstantVector::get( Mask1),
  2471. getReplacementName(K, false, 1));
  2472. } else {
  2473. Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
  2474. K1 = ExtractElementInst::Create(K, CV0,
  2475. getReplacementName(K, false, 1));
  2476. }
  2477. if (JType->isVectorTy()) {
  2478. std::vector<Constant*> Mask1(numElemJ), Mask2(numElemJ);
  2479. for (unsigned v = 0; v < numElemJ; ++v) {
  2480. Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
  2481. Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElemI+v);
  2482. }
  2483. K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
  2484. ConstantVector::get( Mask2),
  2485. getReplacementName(K, false, 2));
  2486. } else {
  2487. Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), numElem-1);
  2488. K2 = ExtractElementInst::Create(K, CV1,
  2489. getReplacementName(K, false, 2));
  2490. }
  2491. K1->insertAfter(K);
  2492. K2->insertAfter(K1);
  2493. InsertionPt = K2;
  2494. }
  2495. }
  2496. // Move all uses of the function I (including pairing-induced uses) after J.
  2497. bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
  2498. DenseSet<ValuePair> &LoadMoveSetPairs,
  2499. Instruction *I, Instruction *J) {
  2500. // Skip to the first instruction past I.
  2501. BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
  2502. DenseSet<Value *> Users;
  2503. AliasSetTracker WriteSet(*AA);
  2504. if (I->mayWriteToMemory()) WriteSet.add(I);
  2505. for (; cast<Instruction>(L) != J; ++L)
  2506. (void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs);
  2507. assert(cast<Instruction>(L) == J &&
  2508. "Tracking has not proceeded far enough to check for dependencies");
  2509. // If J is now in the use set of I, then trackUsesOfI will return true
  2510. // and we have a dependency cycle (and the fusing operation must abort).
  2511. return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSetPairs);
  2512. }
  2513. // Move all uses of the function I (including pairing-induced uses) after J.
  2514. void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
  2515. DenseSet<ValuePair> &LoadMoveSetPairs,
  2516. Instruction *&InsertionPt,
  2517. Instruction *I, Instruction *J) {
  2518. // Skip to the first instruction past I.
  2519. BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
  2520. DenseSet<Value *> Users;
  2521. AliasSetTracker WriteSet(*AA);
  2522. if (I->mayWriteToMemory()) WriteSet.add(I);
  2523. for (; cast<Instruction>(L) != J;) {
  2524. if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSetPairs)) {
  2525. // Move this instruction
  2526. Instruction *InstToMove = L; ++L;
  2527. DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
  2528. " to after " << *InsertionPt << "\n");
  2529. InstToMove->removeFromParent();
  2530. InstToMove->insertAfter(InsertionPt);
  2531. InsertionPt = InstToMove;
  2532. } else {
  2533. ++L;
  2534. }
  2535. }
  2536. }
  2537. // Collect all load instruction that are in the move set of a given first
  2538. // pair member. These loads depend on the first instruction, I, and so need
  2539. // to be moved after J (the second instruction) when the pair is fused.
  2540. void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
  2541. DenseMap<Value *, Value *> &ChosenPairs,
  2542. DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
  2543. DenseSet<ValuePair> &LoadMoveSetPairs,
  2544. Instruction *I) {
  2545. // Skip to the first instruction past I.
  2546. BasicBlock::iterator L = std::next(BasicBlock::iterator(I));
  2547. DenseSet<Value *> Users;
  2548. AliasSetTracker WriteSet(*AA);
  2549. if (I->mayWriteToMemory()) WriteSet.add(I);
  2550. // Note: We cannot end the loop when we reach J because J could be moved
  2551. // farther down the use chain by another instruction pairing. Also, J
  2552. // could be before I if this is an inverted input.
  2553. for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
  2554. if (trackUsesOfI(Users, WriteSet, I, L)) {
  2555. if (L->mayReadFromMemory()) {
  2556. LoadMoveSet[L].push_back(I);
  2557. LoadMoveSetPairs.insert(ValuePair(L, I));
  2558. }
  2559. }
  2560. }
  2561. }
  2562. // In cases where both load/stores and the computation of their pointers
  2563. // are chosen for vectorization, we can end up in a situation where the
  2564. // aliasing analysis starts returning different query results as the
  2565. // process of fusing instruction pairs continues. Because the algorithm
  2566. // relies on finding the same use dags here as were found earlier, we'll
  2567. // need to precompute the necessary aliasing information here and then
  2568. // manually update it during the fusion process.
  2569. void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
  2570. std::vector<Value *> &PairableInsts,
  2571. DenseMap<Value *, Value *> &ChosenPairs,
  2572. DenseMap<Value *, std::vector<Value *> > &LoadMoveSet,
  2573. DenseSet<ValuePair> &LoadMoveSetPairs) {
  2574. for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
  2575. PIE = PairableInsts.end(); PI != PIE; ++PI) {
  2576. DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
  2577. if (P == ChosenPairs.end()) continue;
  2578. Instruction *I = cast<Instruction>(P->first);
  2579. collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet,
  2580. LoadMoveSetPairs, I);
  2581. }
  2582. }
  2583. // This function fuses the chosen instruction pairs into vector instructions,
  2584. // taking care preserve any needed scalar outputs and, then, it reorders the
  2585. // remaining instructions as needed (users of the first member of the pair
  2586. // need to be moved to after the location of the second member of the pair
  2587. // because the vector instruction is inserted in the location of the pair's
  2588. // second member).
  2589. void BBVectorize::fuseChosenPairs(BasicBlock &BB,
  2590. std::vector<Value *> &PairableInsts,
  2591. DenseMap<Value *, Value *> &ChosenPairs,
  2592. DenseSet<ValuePair> &FixedOrderPairs,
  2593. DenseMap<VPPair, unsigned> &PairConnectionTypes,
  2594. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairs,
  2595. DenseMap<ValuePair, std::vector<ValuePair> > &ConnectedPairDeps) {
  2596. LLVMContext& Context = BB.getContext();
  2597. // During the vectorization process, the order of the pairs to be fused
  2598. // could be flipped. So we'll add each pair, flipped, into the ChosenPairs
  2599. // list. After a pair is fused, the flipped pair is removed from the list.
  2600. DenseSet<ValuePair> FlippedPairs;
  2601. for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
  2602. E = ChosenPairs.end(); P != E; ++P)
  2603. FlippedPairs.insert(ValuePair(P->second, P->first));
  2604. for (DenseSet<ValuePair>::iterator P = FlippedPairs.begin(),
  2605. E = FlippedPairs.end(); P != E; ++P)
  2606. ChosenPairs.insert(*P);
  2607. DenseMap<Value *, std::vector<Value *> > LoadMoveSet;
  2608. DenseSet<ValuePair> LoadMoveSetPairs;
  2609. collectLoadMoveSet(BB, PairableInsts, ChosenPairs,
  2610. LoadMoveSet, LoadMoveSetPairs);
  2611. DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
  2612. for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
  2613. DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
  2614. if (P == ChosenPairs.end()) {
  2615. ++PI;
  2616. continue;
  2617. }
  2618. if (getDepthFactor(P->first) == 0) {
  2619. // These instructions are not really fused, but are tracked as though
  2620. // they are. Any case in which it would be interesting to fuse them
  2621. // will be taken care of by InstCombine.
  2622. --NumFusedOps;
  2623. ++PI;
  2624. continue;
  2625. }
  2626. Instruction *I = cast<Instruction>(P->first),
  2627. *J = cast<Instruction>(P->second);
  2628. DEBUG(dbgs() << "BBV: fusing: " << *I <<
  2629. " <-> " << *J << "\n");
  2630. // Remove the pair and flipped pair from the list.
  2631. DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
  2632. assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
  2633. ChosenPairs.erase(FP);
  2634. ChosenPairs.erase(P);
  2635. if (!canMoveUsesOfIAfterJ(BB, LoadMoveSetPairs, I, J)) {
  2636. DEBUG(dbgs() << "BBV: fusion of: " << *I <<
  2637. " <-> " << *J <<
  2638. " aborted because of non-trivial dependency cycle\n");
  2639. --NumFusedOps;
  2640. ++PI;
  2641. continue;
  2642. }
  2643. // If the pair must have the other order, then flip it.
  2644. bool FlipPairOrder = FixedOrderPairs.count(ValuePair(J, I));
  2645. if (!FlipPairOrder && !FixedOrderPairs.count(ValuePair(I, J))) {
  2646. // This pair does not have a fixed order, and so we might want to
  2647. // flip it if that will yield fewer shuffles. We count the number
  2648. // of dependencies connected via swaps, and those directly connected,
  2649. // and flip the order if the number of swaps is greater.
  2650. bool OrigOrder = true;
  2651. DenseMap<ValuePair, std::vector<ValuePair> >::iterator IJ =
  2652. ConnectedPairDeps.find(ValuePair(I, J));
  2653. if (IJ == ConnectedPairDeps.end()) {
  2654. IJ = ConnectedPairDeps.find(ValuePair(J, I));
  2655. OrigOrder = false;
  2656. }
  2657. if (IJ != ConnectedPairDeps.end()) {
  2658. unsigned NumDepsDirect = 0, NumDepsSwap = 0;
  2659. for (std::vector<ValuePair>::iterator T = IJ->second.begin(),
  2660. TE = IJ->second.end(); T != TE; ++T) {
  2661. VPPair Q(IJ->first, *T);
  2662. DenseMap<VPPair, unsigned>::iterator R =
  2663. PairConnectionTypes.find(VPPair(Q.second, Q.first));
  2664. assert(R != PairConnectionTypes.end() &&
  2665. "Cannot find pair connection type");
  2666. if (R->second == PairConnectionDirect)
  2667. ++NumDepsDirect;
  2668. else if (R->second == PairConnectionSwap)
  2669. ++NumDepsSwap;
  2670. }
  2671. if (!OrigOrder)
  2672. std::swap(NumDepsDirect, NumDepsSwap);
  2673. if (NumDepsSwap > NumDepsDirect) {
  2674. FlipPairOrder = true;
  2675. DEBUG(dbgs() << "BBV: reordering pair: " << *I <<
  2676. " <-> " << *J << "\n");
  2677. }
  2678. }
  2679. }
  2680. Instruction *L = I, *H = J;
  2681. if (FlipPairOrder)
  2682. std::swap(H, L);
  2683. // If the pair being fused uses the opposite order from that in the pair
  2684. // connection map, then we need to flip the types.
  2685. DenseMap<ValuePair, std::vector<ValuePair> >::iterator HL =
  2686. ConnectedPairs.find(ValuePair(H, L));
  2687. if (HL != ConnectedPairs.end())
  2688. for (std::vector<ValuePair>::iterator T = HL->second.begin(),
  2689. TE = HL->second.end(); T != TE; ++T) {
  2690. VPPair Q(HL->first, *T);
  2691. DenseMap<VPPair, unsigned>::iterator R = PairConnectionTypes.find(Q);
  2692. assert(R != PairConnectionTypes.end() &&
  2693. "Cannot find pair connection type");
  2694. if (R->second == PairConnectionDirect)
  2695. R->second = PairConnectionSwap;
  2696. else if (R->second == PairConnectionSwap)
  2697. R->second = PairConnectionDirect;
  2698. }
  2699. bool LBeforeH = !FlipPairOrder;
  2700. unsigned NumOperands = I->getNumOperands();
  2701. SmallVector<Value *, 3> ReplacedOperands(NumOperands);
  2702. getReplacementInputsForPair(Context, L, H, ReplacedOperands,
  2703. LBeforeH);
  2704. // Make a copy of the original operation, change its type to the vector
  2705. // type and replace its operands with the vector operands.
  2706. Instruction *K = L->clone();
  2707. if (L->hasName())
  2708. K->takeName(L);
  2709. else if (H->hasName())
  2710. K->takeName(H);
  2711. if (auto CS = CallSite(K)) {
  2712. SmallVector<Type *, 3> Tys;
  2713. FunctionType *Old = CS.getFunctionType();
  2714. unsigned NumOld = Old->getNumParams();
  2715. assert(NumOld <= ReplacedOperands.size());
  2716. for (unsigned i = 0; i != NumOld; ++i)
  2717. Tys.push_back(ReplacedOperands[i]->getType());
  2718. CS.mutateFunctionType(
  2719. FunctionType::get(getVecTypeForPair(L->getType(), H->getType()),
  2720. Tys, Old->isVarArg()));
  2721. } else if (!isa<StoreInst>(K))
  2722. K->mutateType(getVecTypeForPair(L->getType(), H->getType()));
  2723. unsigned KnownIDs[] = {
  2724. LLVMContext::MD_tbaa,
  2725. LLVMContext::MD_alias_scope,
  2726. LLVMContext::MD_noalias,
  2727. LLVMContext::MD_fpmath
  2728. };
  2729. combineMetadata(K, H, KnownIDs);
  2730. K->intersectOptionalDataWith(H);
  2731. for (unsigned o = 0; o < NumOperands; ++o)
  2732. K->setOperand(o, ReplacedOperands[o]);
  2733. K->insertAfter(J);
  2734. // Instruction insertion point:
  2735. Instruction *InsertionPt = K;
  2736. Instruction *K1 = nullptr, *K2 = nullptr;
  2737. replaceOutputsOfPair(Context, L, H, K, InsertionPt, K1, K2);
  2738. // The use dag of the first original instruction must be moved to after
  2739. // the location of the second instruction. The entire use dag of the
  2740. // first instruction is disjoint from the input dag of the second
  2741. // (by definition), and so commutes with it.
  2742. moveUsesOfIAfterJ(BB, LoadMoveSetPairs, InsertionPt, I, J);
  2743. if (!isa<StoreInst>(I)) {
  2744. L->replaceAllUsesWith(K1);
  2745. H->replaceAllUsesWith(K2);
  2746. AA->replaceWithNewValue(L, K1);
  2747. AA->replaceWithNewValue(H, K2);
  2748. }
  2749. // Instructions that may read from memory may be in the load move set.
  2750. // Once an instruction is fused, we no longer need its move set, and so
  2751. // the values of the map never need to be updated. However, when a load
  2752. // is fused, we need to merge the entries from both instructions in the
  2753. // pair in case those instructions were in the move set of some other
  2754. // yet-to-be-fused pair. The loads in question are the keys of the map.
  2755. if (I->mayReadFromMemory()) {
  2756. std::vector<ValuePair> NewSetMembers;
  2757. DenseMap<Value *, std::vector<Value *> >::iterator II =
  2758. LoadMoveSet.find(I);
  2759. if (II != LoadMoveSet.end())
  2760. for (std::vector<Value *>::iterator N = II->second.begin(),
  2761. NE = II->second.end(); N != NE; ++N)
  2762. NewSetMembers.push_back(ValuePair(K, *N));
  2763. DenseMap<Value *, std::vector<Value *> >::iterator JJ =
  2764. LoadMoveSet.find(J);
  2765. if (JJ != LoadMoveSet.end())
  2766. for (std::vector<Value *>::iterator N = JJ->second.begin(),
  2767. NE = JJ->second.end(); N != NE; ++N)
  2768. NewSetMembers.push_back(ValuePair(K, *N));
  2769. for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
  2770. AE = NewSetMembers.end(); A != AE; ++A) {
  2771. LoadMoveSet[A->first].push_back(A->second);
  2772. LoadMoveSetPairs.insert(*A);
  2773. }
  2774. }
  2775. // Before removing I, set the iterator to the next instruction.
  2776. PI = std::next(BasicBlock::iterator(I));
  2777. if (cast<Instruction>(PI) == J)
  2778. ++PI;
  2779. SE->forgetValue(I);
  2780. SE->forgetValue(J);
  2781. I->eraseFromParent();
  2782. J->eraseFromParent();
  2783. DEBUG(if (PrintAfterEveryPair) dbgs() << "BBV: block is now: \n" <<
  2784. BB << "\n");
  2785. }
  2786. DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
  2787. }
  2788. }
  2789. char BBVectorize::ID = 0;
  2790. static const char bb_vectorize_name[] = "Basic-Block Vectorization";
  2791. INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
  2792. INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
  2793. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  2794. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  2795. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  2796. INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
  2797. BasicBlockPass *llvm::createBBVectorizePass(const VectorizeConfig &C) {
  2798. return new BBVectorize(C);
  2799. }
  2800. bool
  2801. llvm::vectorizeBasicBlock(Pass *P, BasicBlock &BB, const VectorizeConfig &C) {
  2802. BBVectorize BBVectorizer(P, *BB.getParent(), C);
  2803. return BBVectorizer.vectorizeBB(BB);
  2804. }
  2805. //===----------------------------------------------------------------------===//
  2806. VectorizeConfig::VectorizeConfig() {
  2807. VectorBits = ::VectorBits;
  2808. VectorizeBools = !::NoBools;
  2809. VectorizeInts = !::NoInts;
  2810. VectorizeFloats = !::NoFloats;
  2811. VectorizePointers = !::NoPointers;
  2812. VectorizeCasts = !::NoCasts;
  2813. VectorizeMath = !::NoMath;
  2814. VectorizeBitManipulations = !::NoBitManipulation;
  2815. VectorizeFMA = !::NoFMA;
  2816. VectorizeSelect = !::NoSelect;
  2817. VectorizeCmp = !::NoCmp;
  2818. VectorizeGEP = !::NoGEP;
  2819. VectorizeMemOps = !::NoMemOps;
  2820. AlignedOnly = ::AlignedOnly;
  2821. ReqChainDepth= ::ReqChainDepth;
  2822. SearchLimit = ::SearchLimit;
  2823. MaxCandPairsForCycleCheck = ::MaxCandPairsForCycleCheck;
  2824. SplatBreaksChain = ::SplatBreaksChain;
  2825. MaxInsts = ::MaxInsts;
  2826. MaxPairs = ::MaxPairs;
  2827. MaxIter = ::MaxIter;
  2828. Pow2LenOnly = ::Pow2LenOnly;
  2829. NoMemOpBoost = ::NoMemOpBoost;
  2830. FastDep = ::FastDep;
  2831. }