SelectionDAGISel.cpp 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708
  1. //===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements the SelectionDAGISel class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/SelectionDAGISel.h"
  13. #include "ScheduleDAGSDNodes.h"
  14. #include "SelectionDAGBuilder.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/PostOrderIterator.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallSet.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/ADT/StringRef.h"
  25. #include "llvm/Analysis/AliasAnalysis.h"
  26. #include "llvm/Analysis/BranchProbabilityInfo.h"
  27. #include "llvm/Analysis/CFG.h"
  28. #include "llvm/Analysis/EHPersonalities.h"
  29. #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
  30. #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
  31. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  32. #include "llvm/Analysis/ProfileSummaryInfo.h"
  33. #include "llvm/Analysis/TargetLibraryInfo.h"
  34. #include "llvm/Analysis/TargetTransformInfo.h"
  35. #include "llvm/CodeGen/CodeGenCommonISel.h"
  36. #include "llvm/CodeGen/FastISel.h"
  37. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  38. #include "llvm/CodeGen/GCMetadata.h"
  39. #include "llvm/CodeGen/ISDOpcodes.h"
  40. #include "llvm/CodeGen/MachineBasicBlock.h"
  41. #include "llvm/CodeGen/MachineFrameInfo.h"
  42. #include "llvm/CodeGen/MachineFunction.h"
  43. #include "llvm/CodeGen/MachineFunctionPass.h"
  44. #include "llvm/CodeGen/MachineInstr.h"
  45. #include "llvm/CodeGen/MachineInstrBuilder.h"
  46. #include "llvm/CodeGen/MachineMemOperand.h"
  47. #include "llvm/CodeGen/MachineModuleInfo.h"
  48. #include "llvm/CodeGen/MachineOperand.h"
  49. #include "llvm/CodeGen/MachinePassRegistry.h"
  50. #include "llvm/CodeGen/MachineRegisterInfo.h"
  51. #include "llvm/CodeGen/SchedulerRegistry.h"
  52. #include "llvm/CodeGen/SelectionDAG.h"
  53. #include "llvm/CodeGen/SelectionDAGNodes.h"
  54. #include "llvm/CodeGen/StackProtector.h"
  55. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  56. #include "llvm/CodeGen/TargetInstrInfo.h"
  57. #include "llvm/CodeGen/TargetLowering.h"
  58. #include "llvm/CodeGen/TargetRegisterInfo.h"
  59. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  60. #include "llvm/CodeGen/ValueTypes.h"
  61. #include "llvm/IR/BasicBlock.h"
  62. #include "llvm/IR/Constants.h"
  63. #include "llvm/IR/DataLayout.h"
  64. #include "llvm/IR/DebugInfoMetadata.h"
  65. #include "llvm/IR/DebugLoc.h"
  66. #include "llvm/IR/DiagnosticInfo.h"
  67. #include "llvm/IR/Dominators.h"
  68. #include "llvm/IR/Function.h"
  69. #include "llvm/IR/InlineAsm.h"
  70. #include "llvm/IR/InstIterator.h"
  71. #include "llvm/IR/InstrTypes.h"
  72. #include "llvm/IR/Instruction.h"
  73. #include "llvm/IR/Instructions.h"
  74. #include "llvm/IR/IntrinsicInst.h"
  75. #include "llvm/IR/Intrinsics.h"
  76. #include "llvm/IR/IntrinsicsWebAssembly.h"
  77. #include "llvm/IR/Metadata.h"
  78. #include "llvm/IR/Statepoint.h"
  79. #include "llvm/IR/Type.h"
  80. #include "llvm/IR/User.h"
  81. #include "llvm/IR/Value.h"
  82. #include "llvm/InitializePasses.h"
  83. #include "llvm/MC/MCInstrDesc.h"
  84. #include "llvm/MC/MCRegisterInfo.h"
  85. #include "llvm/Pass.h"
  86. #include "llvm/Support/BranchProbability.h"
  87. #include "llvm/Support/Casting.h"
  88. #include "llvm/Support/CodeGen.h"
  89. #include "llvm/Support/CommandLine.h"
  90. #include "llvm/Support/Compiler.h"
  91. #include "llvm/Support/Debug.h"
  92. #include "llvm/Support/ErrorHandling.h"
  93. #include "llvm/Support/KnownBits.h"
  94. #include "llvm/Support/MachineValueType.h"
  95. #include "llvm/Support/Timer.h"
  96. #include "llvm/Support/raw_ostream.h"
  97. #include "llvm/Target/TargetIntrinsicInfo.h"
  98. #include "llvm/Target/TargetMachine.h"
  99. #include "llvm/Target/TargetOptions.h"
  100. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  101. #include <algorithm>
  102. #include <cassert>
  103. #include <cstdint>
  104. #include <iterator>
  105. #include <limits>
  106. #include <memory>
  107. #include <string>
  108. #include <utility>
  109. #include <vector>
  110. using namespace llvm;
  111. #define DEBUG_TYPE "isel"
  112. STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
  113. STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
  114. STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
  115. STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
  116. STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
  117. STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
  118. STATISTIC(NumFastIselFailLowerArguments,
  119. "Number of entry blocks where fast isel failed to lower arguments");
  120. static cl::opt<int> EnableFastISelAbort(
  121. "fast-isel-abort", cl::Hidden,
  122. cl::desc("Enable abort calls when \"fast\" instruction selection "
  123. "fails to lower an instruction: 0 disable the abort, 1 will "
  124. "abort but for args, calls and terminators, 2 will also "
  125. "abort for argument lowering, and 3 will never fallback "
  126. "to SelectionDAG."));
  127. static cl::opt<bool> EnableFastISelFallbackReport(
  128. "fast-isel-report-on-fallback", cl::Hidden,
  129. cl::desc("Emit a diagnostic when \"fast\" instruction selection "
  130. "falls back to SelectionDAG."));
  131. static cl::opt<bool>
  132. UseMBPI("use-mbpi",
  133. cl::desc("use Machine Branch Probability Info"),
  134. cl::init(true), cl::Hidden);
  135. #ifndef NDEBUG
  136. static cl::opt<std::string>
  137. FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
  138. cl::desc("Only display the basic block whose name "
  139. "matches this for all view-*-dags options"));
  140. static cl::opt<bool>
  141. ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
  142. cl::desc("Pop up a window to show dags before the first "
  143. "dag combine pass"));
  144. static cl::opt<bool>
  145. ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
  146. cl::desc("Pop up a window to show dags before legalize types"));
  147. static cl::opt<bool>
  148. ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
  149. cl::desc("Pop up a window to show dags before the post "
  150. "legalize types dag combine pass"));
  151. static cl::opt<bool>
  152. ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
  153. cl::desc("Pop up a window to show dags before legalize"));
  154. static cl::opt<bool>
  155. ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
  156. cl::desc("Pop up a window to show dags before the second "
  157. "dag combine pass"));
  158. static cl::opt<bool>
  159. ViewISelDAGs("view-isel-dags", cl::Hidden,
  160. cl::desc("Pop up a window to show isel dags as they are selected"));
  161. static cl::opt<bool>
  162. ViewSchedDAGs("view-sched-dags", cl::Hidden,
  163. cl::desc("Pop up a window to show sched dags as they are processed"));
  164. static cl::opt<bool>
  165. ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
  166. cl::desc("Pop up a window to show SUnit dags after they are processed"));
  167. #else
  168. static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
  169. ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
  170. ViewDAGCombine2 = false, ViewISelDAGs = false,
  171. ViewSchedDAGs = false, ViewSUnitDAGs = false;
  172. #endif
  173. //===---------------------------------------------------------------------===//
  174. ///
  175. /// RegisterScheduler class - Track the registration of instruction schedulers.
  176. ///
  177. //===---------------------------------------------------------------------===//
  178. MachinePassRegistry<RegisterScheduler::FunctionPassCtor>
  179. RegisterScheduler::Registry;
  180. //===---------------------------------------------------------------------===//
  181. ///
  182. /// ISHeuristic command line option for instruction schedulers.
  183. ///
  184. //===---------------------------------------------------------------------===//
  185. static cl::opt<RegisterScheduler::FunctionPassCtor, false,
  186. RegisterPassParser<RegisterScheduler>>
  187. ISHeuristic("pre-RA-sched",
  188. cl::init(&createDefaultScheduler), cl::Hidden,
  189. cl::desc("Instruction schedulers available (before register"
  190. " allocation):"));
  191. static RegisterScheduler
  192. defaultListDAGScheduler("default", "Best scheduler for the target",
  193. createDefaultScheduler);
  194. namespace llvm {
  195. //===--------------------------------------------------------------------===//
  196. /// This class is used by SelectionDAGISel to temporarily override
  197. /// the optimization level on a per-function basis.
  198. class OptLevelChanger {
  199. SelectionDAGISel &IS;
  200. CodeGenOpt::Level SavedOptLevel;
  201. bool SavedFastISel;
  202. public:
  203. OptLevelChanger(SelectionDAGISel &ISel,
  204. CodeGenOpt::Level NewOptLevel) : IS(ISel) {
  205. SavedOptLevel = IS.OptLevel;
  206. SavedFastISel = IS.TM.Options.EnableFastISel;
  207. if (NewOptLevel == SavedOptLevel)
  208. return;
  209. IS.OptLevel = NewOptLevel;
  210. IS.TM.setOptLevel(NewOptLevel);
  211. LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
  212. << IS.MF->getFunction().getName() << "\n");
  213. LLVM_DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel << " ; After: -O"
  214. << NewOptLevel << "\n");
  215. if (NewOptLevel == CodeGenOpt::None) {
  216. IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
  217. LLVM_DEBUG(
  218. dbgs() << "\tFastISel is "
  219. << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
  220. << "\n");
  221. }
  222. }
  223. ~OptLevelChanger() {
  224. if (IS.OptLevel == SavedOptLevel)
  225. return;
  226. LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
  227. << IS.MF->getFunction().getName() << "\n");
  228. LLVM_DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel << " ; After: -O"
  229. << SavedOptLevel << "\n");
  230. IS.OptLevel = SavedOptLevel;
  231. IS.TM.setOptLevel(SavedOptLevel);
  232. IS.TM.setFastISel(SavedFastISel);
  233. }
  234. };
  235. //===--------------------------------------------------------------------===//
  236. /// createDefaultScheduler - This creates an instruction scheduler appropriate
  237. /// for the target.
  238. ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
  239. CodeGenOpt::Level OptLevel) {
  240. const TargetLowering *TLI = IS->TLI;
  241. const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
  242. // Try first to see if the Target has its own way of selecting a scheduler
  243. if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
  244. return SchedulerCtor(IS, OptLevel);
  245. }
  246. if (OptLevel == CodeGenOpt::None ||
  247. (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
  248. TLI->getSchedulingPreference() == Sched::Source)
  249. return createSourceListDAGScheduler(IS, OptLevel);
  250. if (TLI->getSchedulingPreference() == Sched::RegPressure)
  251. return createBURRListDAGScheduler(IS, OptLevel);
  252. if (TLI->getSchedulingPreference() == Sched::Hybrid)
  253. return createHybridListDAGScheduler(IS, OptLevel);
  254. if (TLI->getSchedulingPreference() == Sched::VLIW)
  255. return createVLIWDAGScheduler(IS, OptLevel);
  256. if (TLI->getSchedulingPreference() == Sched::Fast)
  257. return createFastDAGScheduler(IS, OptLevel);
  258. if (TLI->getSchedulingPreference() == Sched::Linearize)
  259. return createDAGLinearizer(IS, OptLevel);
  260. assert(TLI->getSchedulingPreference() == Sched::ILP &&
  261. "Unknown sched type!");
  262. return createILPListDAGScheduler(IS, OptLevel);
  263. }
  264. } // end namespace llvm
  265. // EmitInstrWithCustomInserter - This method should be implemented by targets
  266. // that mark instructions with the 'usesCustomInserter' flag. These
  267. // instructions are special in various ways, which require special support to
  268. // insert. The specified MachineInstr is created but not inserted into any
  269. // basic blocks, and this method is called to expand it into a sequence of
  270. // instructions, potentially also creating new basic blocks and control flow.
  271. // When new basic blocks are inserted and the edges from MBB to its successors
  272. // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
  273. // DenseMap.
  274. MachineBasicBlock *
  275. TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
  276. MachineBasicBlock *MBB) const {
  277. #ifndef NDEBUG
  278. dbgs() << "If a target marks an instruction with "
  279. "'usesCustomInserter', it must implement "
  280. "TargetLowering::EmitInstrWithCustomInserter!\n";
  281. #endif
  282. llvm_unreachable(nullptr);
  283. }
  284. void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
  285. SDNode *Node) const {
  286. assert(!MI.hasPostISelHook() &&
  287. "If a target marks an instruction with 'hasPostISelHook', "
  288. "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
  289. }
  290. //===----------------------------------------------------------------------===//
  291. // SelectionDAGISel code
  292. //===----------------------------------------------------------------------===//
  293. SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL)
  294. : MachineFunctionPass(ID), TM(tm), FuncInfo(new FunctionLoweringInfo()),
  295. SwiftError(new SwiftErrorValueTracking()),
  296. CurDAG(new SelectionDAG(tm, OL)),
  297. SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError,
  298. OL)),
  299. OptLevel(OL) {
  300. initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
  301. initializeBranchProbabilityInfoWrapperPassPass(
  302. *PassRegistry::getPassRegistry());
  303. initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
  304. initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
  305. }
  306. SelectionDAGISel::~SelectionDAGISel() {
  307. delete CurDAG;
  308. delete SwiftError;
  309. }
  310. void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
  311. if (OptLevel != CodeGenOpt::None)
  312. AU.addRequired<AAResultsWrapperPass>();
  313. AU.addRequired<GCModuleInfo>();
  314. AU.addRequired<StackProtector>();
  315. AU.addPreserved<GCModuleInfo>();
  316. AU.addRequired<TargetLibraryInfoWrapperPass>();
  317. AU.addRequired<TargetTransformInfoWrapperPass>();
  318. if (UseMBPI && OptLevel != CodeGenOpt::None)
  319. AU.addRequired<BranchProbabilityInfoWrapperPass>();
  320. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  321. if (OptLevel != CodeGenOpt::None)
  322. LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
  323. MachineFunctionPass::getAnalysisUsage(AU);
  324. }
  325. /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
  326. /// may trap on it. In this case we have to split the edge so that the path
  327. /// through the predecessor block that doesn't go to the phi block doesn't
  328. /// execute the possibly trapping instruction. If available, we pass domtree
  329. /// and loop info to be updated when we split critical edges. This is because
  330. /// SelectionDAGISel preserves these analyses.
  331. /// This is required for correctness, so it must be done at -O0.
  332. ///
  333. static void SplitCriticalSideEffectEdges(Function &Fn, DominatorTree *DT,
  334. LoopInfo *LI) {
  335. // Loop for blocks with phi nodes.
  336. for (BasicBlock &BB : Fn) {
  337. PHINode *PN = dyn_cast<PHINode>(BB.begin());
  338. if (!PN) continue;
  339. ReprocessBlock:
  340. // For each block with a PHI node, check to see if any of the input values
  341. // are potentially trapping constant expressions. Constant expressions are
  342. // the only potentially trapping value that can occur as the argument to a
  343. // PHI.
  344. for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
  345. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  346. ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
  347. if (!CE || !CE->canTrap()) continue;
  348. // The only case we have to worry about is when the edge is critical.
  349. // Since this block has a PHI Node, we assume it has multiple input
  350. // edges: check to see if the pred has multiple successors.
  351. BasicBlock *Pred = PN->getIncomingBlock(i);
  352. if (Pred->getTerminator()->getNumSuccessors() == 1)
  353. continue;
  354. // Okay, we have to split this edge.
  355. SplitCriticalEdge(
  356. Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
  357. CriticalEdgeSplittingOptions(DT, LI).setMergeIdenticalEdges());
  358. goto ReprocessBlock;
  359. }
  360. }
  361. }
  362. static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F,
  363. MachineModuleInfo &MMI) {
  364. // Only needed for MSVC
  365. if (!TT.isWindowsMSVCEnvironment())
  366. return;
  367. // If it's already set, nothing to do.
  368. if (MMI.usesMSVCFloatingPoint())
  369. return;
  370. for (const Instruction &I : instructions(F)) {
  371. if (I.getType()->isFPOrFPVectorTy()) {
  372. MMI.setUsesMSVCFloatingPoint(true);
  373. return;
  374. }
  375. for (const auto &Op : I.operands()) {
  376. if (Op->getType()->isFPOrFPVectorTy()) {
  377. MMI.setUsesMSVCFloatingPoint(true);
  378. return;
  379. }
  380. }
  381. }
  382. }
  383. bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
  384. // If we already selected that function, we do not need to run SDISel.
  385. if (mf.getProperties().hasProperty(
  386. MachineFunctionProperties::Property::Selected))
  387. return false;
  388. // Do some sanity-checking on the command-line options.
  389. assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
  390. "-fast-isel-abort > 0 requires -fast-isel");
  391. const Function &Fn = mf.getFunction();
  392. MF = &mf;
  393. // Decide what flavour of variable location debug-info will be used, before
  394. // we change the optimisation level.
  395. UseInstrRefDebugInfo = mf.useDebugInstrRef();
  396. CurDAG->useInstrRefDebugInfo(UseInstrRefDebugInfo);
  397. // Reset the target options before resetting the optimization
  398. // level below.
  399. // FIXME: This is a horrible hack and should be processed via
  400. // codegen looking at the optimization level explicitly when
  401. // it wants to look at it.
  402. TM.resetTargetOptions(Fn);
  403. // Reset OptLevel to None for optnone functions.
  404. CodeGenOpt::Level NewOptLevel = OptLevel;
  405. if (OptLevel != CodeGenOpt::None && skipFunction(Fn))
  406. NewOptLevel = CodeGenOpt::None;
  407. OptLevelChanger OLC(*this, NewOptLevel);
  408. TII = MF->getSubtarget().getInstrInfo();
  409. TLI = MF->getSubtarget().getTargetLowering();
  410. RegInfo = &MF->getRegInfo();
  411. LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(Fn);
  412. GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
  413. ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
  414. auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  415. DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
  416. auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
  417. LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
  418. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  419. BlockFrequencyInfo *BFI = nullptr;
  420. if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOpt::None)
  421. BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
  422. LLVM_DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
  423. SplitCriticalSideEffectEdges(const_cast<Function &>(Fn), DT, LI);
  424. CurDAG->init(*MF, *ORE, this, LibInfo,
  425. getAnalysisIfAvailable<LegacyDivergenceAnalysis>(), PSI, BFI);
  426. FuncInfo->set(Fn, *MF, CurDAG);
  427. SwiftError->setFunction(*MF);
  428. // Now get the optional analyzes if we want to.
  429. // This is based on the possibly changed OptLevel (after optnone is taken
  430. // into account). That's unfortunate but OK because it just means we won't
  431. // ask for passes that have been required anyway.
  432. if (UseMBPI && OptLevel != CodeGenOpt::None)
  433. FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
  434. else
  435. FuncInfo->BPI = nullptr;
  436. if (OptLevel != CodeGenOpt::None)
  437. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  438. else
  439. AA = nullptr;
  440. SDB->init(GFI, AA, LibInfo);
  441. MF->setHasInlineAsm(false);
  442. FuncInfo->SplitCSR = false;
  443. // We split CSR if the target supports it for the given function
  444. // and the function has only return exits.
  445. if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) {
  446. FuncInfo->SplitCSR = true;
  447. // Collect all the return blocks.
  448. for (const BasicBlock &BB : Fn) {
  449. if (!succ_empty(&BB))
  450. continue;
  451. const Instruction *Term = BB.getTerminator();
  452. if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
  453. continue;
  454. // Bail out if the exit block is not Return nor Unreachable.
  455. FuncInfo->SplitCSR = false;
  456. break;
  457. }
  458. }
  459. MachineBasicBlock *EntryMBB = &MF->front();
  460. if (FuncInfo->SplitCSR)
  461. // This performs initialization so lowering for SplitCSR will be correct.
  462. TLI->initializeSplitCSR(EntryMBB);
  463. SelectAllBasicBlocks(Fn);
  464. if (FastISelFailed && EnableFastISelFallbackReport) {
  465. DiagnosticInfoISelFallback DiagFallback(Fn);
  466. Fn.getContext().diagnose(DiagFallback);
  467. }
  468. // Replace forward-declared registers with the registers containing
  469. // the desired value.
  470. // Note: it is important that this happens **before** the call to
  471. // EmitLiveInCopies, since implementations can skip copies of unused
  472. // registers. If we don't apply the reg fixups before, some registers may
  473. // appear as unused and will be skipped, resulting in bad MI.
  474. MachineRegisterInfo &MRI = MF->getRegInfo();
  475. for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(),
  476. E = FuncInfo->RegFixups.end();
  477. I != E; ++I) {
  478. Register From = I->first;
  479. Register To = I->second;
  480. // If To is also scheduled to be replaced, find what its ultimate
  481. // replacement is.
  482. while (true) {
  483. DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To);
  484. if (J == E)
  485. break;
  486. To = J->second;
  487. }
  488. // Make sure the new register has a sufficiently constrained register class.
  489. if (Register::isVirtualRegister(From) && Register::isVirtualRegister(To))
  490. MRI.constrainRegClass(To, MRI.getRegClass(From));
  491. // Replace it.
  492. // Replacing one register with another won't touch the kill flags.
  493. // We need to conservatively clear the kill flags as a kill on the old
  494. // register might dominate existing uses of the new register.
  495. if (!MRI.use_empty(To))
  496. MRI.clearKillFlags(From);
  497. MRI.replaceRegWith(From, To);
  498. }
  499. // If the first basic block in the function has live ins that need to be
  500. // copied into vregs, emit the copies into the top of the block before
  501. // emitting the code for the block.
  502. const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
  503. RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
  504. // Insert copies in the entry block and the return blocks.
  505. if (FuncInfo->SplitCSR) {
  506. SmallVector<MachineBasicBlock*, 4> Returns;
  507. // Collect all the return blocks.
  508. for (MachineBasicBlock &MBB : mf) {
  509. if (!MBB.succ_empty())
  510. continue;
  511. MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
  512. if (Term != MBB.end() && Term->isReturn()) {
  513. Returns.push_back(&MBB);
  514. continue;
  515. }
  516. }
  517. TLI->insertCopiesSplitCSR(EntryMBB, Returns);
  518. }
  519. DenseMap<unsigned, unsigned> LiveInMap;
  520. if (!FuncInfo->ArgDbgValues.empty())
  521. for (std::pair<unsigned, unsigned> LI : RegInfo->liveins())
  522. if (LI.second)
  523. LiveInMap.insert(LI);
  524. // Insert DBG_VALUE instructions for function arguments to the entry block.
  525. bool InstrRef = MF->useDebugInstrRef();
  526. for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
  527. MachineInstr *MI = FuncInfo->ArgDbgValues[e - i - 1];
  528. assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
  529. "Function parameters should not be described by DBG_VALUE_LIST.");
  530. bool hasFI = MI->getOperand(0).isFI();
  531. Register Reg =
  532. hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
  533. if (Register::isPhysicalRegister(Reg))
  534. EntryMBB->insert(EntryMBB->begin(), MI);
  535. else {
  536. MachineInstr *Def = RegInfo->getVRegDef(Reg);
  537. if (Def) {
  538. MachineBasicBlock::iterator InsertPos = Def;
  539. // FIXME: VR def may not be in entry block.
  540. Def->getParent()->insert(std::next(InsertPos), MI);
  541. } else
  542. LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
  543. << Register::virtReg2Index(Reg) << "\n");
  544. }
  545. // Don't try and extend through copies in instruction referencing mode.
  546. if (InstrRef)
  547. continue;
  548. // If Reg is live-in then update debug info to track its copy in a vreg.
  549. DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
  550. if (LDI != LiveInMap.end()) {
  551. assert(!hasFI && "There's no handling of frame pointer updating here yet "
  552. "- add if needed");
  553. MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
  554. MachineBasicBlock::iterator InsertPos = Def;
  555. const MDNode *Variable = MI->getDebugVariable();
  556. const MDNode *Expr = MI->getDebugExpression();
  557. DebugLoc DL = MI->getDebugLoc();
  558. bool IsIndirect = MI->isIndirectDebugValue();
  559. if (IsIndirect)
  560. assert(MI->getOperand(1).getImm() == 0 &&
  561. "DBG_VALUE with nonzero offset");
  562. assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
  563. "Expected inlined-at fields to agree");
  564. assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
  565. "Didn't expect to see a DBG_VALUE_LIST here");
  566. // Def is never a terminator here, so it is ok to increment InsertPos.
  567. BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
  568. IsIndirect, LDI->second, Variable, Expr);
  569. // If this vreg is directly copied into an exported register then
  570. // that COPY instructions also need DBG_VALUE, if it is the only
  571. // user of LDI->second.
  572. MachineInstr *CopyUseMI = nullptr;
  573. for (MachineRegisterInfo::use_instr_iterator
  574. UI = RegInfo->use_instr_begin(LDI->second),
  575. E = RegInfo->use_instr_end(); UI != E; ) {
  576. MachineInstr *UseMI = &*(UI++);
  577. if (UseMI->isDebugValue()) continue;
  578. if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
  579. CopyUseMI = UseMI; continue;
  580. }
  581. // Otherwise this is another use or second copy use.
  582. CopyUseMI = nullptr; break;
  583. }
  584. if (CopyUseMI &&
  585. TRI.getRegSizeInBits(LDI->second, MRI) ==
  586. TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
  587. // Use MI's debug location, which describes where Variable was
  588. // declared, rather than whatever is attached to CopyUseMI.
  589. MachineInstr *NewMI =
  590. BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  591. CopyUseMI->getOperand(0).getReg(), Variable, Expr);
  592. MachineBasicBlock::iterator Pos = CopyUseMI;
  593. EntryMBB->insertAfter(Pos, NewMI);
  594. }
  595. }
  596. }
  597. // For debug-info, in instruction referencing mode, we need to perform some
  598. // post-isel maintenence.
  599. if (UseInstrRefDebugInfo)
  600. MF->finalizeDebugInstrRefs();
  601. // Determine if there are any calls in this machine function.
  602. MachineFrameInfo &MFI = MF->getFrameInfo();
  603. for (const auto &MBB : *MF) {
  604. if (MFI.hasCalls() && MF->hasInlineAsm())
  605. break;
  606. for (const auto &MI : MBB) {
  607. const MCInstrDesc &MCID = TII->get(MI.getOpcode());
  608. if ((MCID.isCall() && !MCID.isReturn()) ||
  609. MI.isStackAligningInlineAsm()) {
  610. MFI.setHasCalls(true);
  611. }
  612. if (MI.isInlineAsm()) {
  613. MF->setHasInlineAsm(true);
  614. }
  615. }
  616. }
  617. // Determine if there is a call to setjmp in the machine function.
  618. MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
  619. // Determine if floating point is used for msvc
  620. computeUsesMSVCFloatingPoint(TM.getTargetTriple(), Fn, MF->getMMI());
  621. // Release function-specific state. SDB and CurDAG are already cleared
  622. // at this point.
  623. FuncInfo->clear();
  624. LLVM_DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
  625. LLVM_DEBUG(MF->print(dbgs()));
  626. return true;
  627. }
  628. static void reportFastISelFailure(MachineFunction &MF,
  629. OptimizationRemarkEmitter &ORE,
  630. OptimizationRemarkMissed &R,
  631. bool ShouldAbort) {
  632. // Print the function name explicitly if we don't have a debug location (which
  633. // makes the diagnostic less useful) or if we're going to emit a raw error.
  634. if (!R.getLocation().isValid() || ShouldAbort)
  635. R << (" (in function: " + MF.getName() + ")").str();
  636. if (ShouldAbort)
  637. report_fatal_error(Twine(R.getMsg()));
  638. ORE.emit(R);
  639. }
  640. void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
  641. BasicBlock::const_iterator End,
  642. bool &HadTailCall) {
  643. // Allow creating illegal types during DAG building for the basic block.
  644. CurDAG->NewNodesMustHaveLegalTypes = false;
  645. // Lower the instructions. If a call is emitted as a tail call, cease emitting
  646. // nodes for this block.
  647. for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
  648. if (!ElidedArgCopyInstrs.count(&*I))
  649. SDB->visit(*I);
  650. }
  651. // Make sure the root of the DAG is up-to-date.
  652. CurDAG->setRoot(SDB->getControlRoot());
  653. HadTailCall = SDB->HasTailCall;
  654. SDB->resolveOrClearDbgInfo();
  655. SDB->clear();
  656. // Final step, emit the lowered DAG as machine code.
  657. CodeGenAndEmitDAG();
  658. }
  659. void SelectionDAGISel::ComputeLiveOutVRegInfo() {
  660. SmallPtrSet<SDNode *, 16> Added;
  661. SmallVector<SDNode*, 128> Worklist;
  662. Worklist.push_back(CurDAG->getRoot().getNode());
  663. Added.insert(CurDAG->getRoot().getNode());
  664. KnownBits Known;
  665. do {
  666. SDNode *N = Worklist.pop_back_val();
  667. // Otherwise, add all chain operands to the worklist.
  668. for (const SDValue &Op : N->op_values())
  669. if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
  670. Worklist.push_back(Op.getNode());
  671. // If this is a CopyToReg with a vreg dest, process it.
  672. if (N->getOpcode() != ISD::CopyToReg)
  673. continue;
  674. unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
  675. if (!Register::isVirtualRegister(DestReg))
  676. continue;
  677. // Ignore non-integer values.
  678. SDValue Src = N->getOperand(2);
  679. EVT SrcVT = Src.getValueType();
  680. if (!SrcVT.isInteger())
  681. continue;
  682. unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
  683. Known = CurDAG->computeKnownBits(Src);
  684. FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
  685. } while (!Worklist.empty());
  686. }
  687. void SelectionDAGISel::CodeGenAndEmitDAG() {
  688. StringRef GroupName = "sdag";
  689. StringRef GroupDescription = "Instruction Selection and Scheduling";
  690. std::string BlockName;
  691. bool MatchFilterBB = false; (void)MatchFilterBB;
  692. #ifndef NDEBUG
  693. TargetTransformInfo &TTI =
  694. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*FuncInfo->Fn);
  695. #endif
  696. // Pre-type legalization allow creation of any node types.
  697. CurDAG->NewNodesMustHaveLegalTypes = false;
  698. #ifndef NDEBUG
  699. MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
  700. FilterDAGBasicBlockName ==
  701. FuncInfo->MBB->getBasicBlock()->getName());
  702. #endif
  703. #ifdef NDEBUG
  704. if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewDAGCombineLT ||
  705. ViewLegalizeDAGs || ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs ||
  706. ViewSUnitDAGs)
  707. #endif
  708. {
  709. BlockName =
  710. (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
  711. }
  712. LLVM_DEBUG(dbgs() << "Initial selection DAG: "
  713. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  714. << "'\n";
  715. CurDAG->dump());
  716. #ifndef NDEBUG
  717. if (TTI.hasBranchDivergence())
  718. CurDAG->VerifyDAGDivergence();
  719. #endif
  720. if (ViewDAGCombine1 && MatchFilterBB)
  721. CurDAG->viewGraph("dag-combine1 input for " + BlockName);
  722. // Run the DAG combiner in pre-legalize mode.
  723. {
  724. NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
  725. GroupDescription, TimePassesIsEnabled);
  726. CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel);
  727. }
  728. LLVM_DEBUG(dbgs() << "Optimized lowered selection DAG: "
  729. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  730. << "'\n";
  731. CurDAG->dump());
  732. #ifndef NDEBUG
  733. if (TTI.hasBranchDivergence())
  734. CurDAG->VerifyDAGDivergence();
  735. #endif
  736. // Second step, hack on the DAG until it only uses operations and types that
  737. // the target supports.
  738. if (ViewLegalizeTypesDAGs && MatchFilterBB)
  739. CurDAG->viewGraph("legalize-types input for " + BlockName);
  740. bool Changed;
  741. {
  742. NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
  743. GroupDescription, TimePassesIsEnabled);
  744. Changed = CurDAG->LegalizeTypes();
  745. }
  746. LLVM_DEBUG(dbgs() << "Type-legalized selection DAG: "
  747. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  748. << "'\n";
  749. CurDAG->dump());
  750. #ifndef NDEBUG
  751. if (TTI.hasBranchDivergence())
  752. CurDAG->VerifyDAGDivergence();
  753. #endif
  754. // Only allow creation of legal node types.
  755. CurDAG->NewNodesMustHaveLegalTypes = true;
  756. if (Changed) {
  757. if (ViewDAGCombineLT && MatchFilterBB)
  758. CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
  759. // Run the DAG combiner in post-type-legalize mode.
  760. {
  761. NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
  762. GroupName, GroupDescription, TimePassesIsEnabled);
  763. CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel);
  764. }
  765. LLVM_DEBUG(dbgs() << "Optimized type-legalized selection DAG: "
  766. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  767. << "'\n";
  768. CurDAG->dump());
  769. #ifndef NDEBUG
  770. if (TTI.hasBranchDivergence())
  771. CurDAG->VerifyDAGDivergence();
  772. #endif
  773. }
  774. {
  775. NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
  776. GroupDescription, TimePassesIsEnabled);
  777. Changed = CurDAG->LegalizeVectors();
  778. }
  779. if (Changed) {
  780. LLVM_DEBUG(dbgs() << "Vector-legalized selection DAG: "
  781. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  782. << "'\n";
  783. CurDAG->dump());
  784. #ifndef NDEBUG
  785. if (TTI.hasBranchDivergence())
  786. CurDAG->VerifyDAGDivergence();
  787. #endif
  788. {
  789. NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
  790. GroupDescription, TimePassesIsEnabled);
  791. CurDAG->LegalizeTypes();
  792. }
  793. LLVM_DEBUG(dbgs() << "Vector/type-legalized selection DAG: "
  794. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  795. << "'\n";
  796. CurDAG->dump());
  797. #ifndef NDEBUG
  798. if (TTI.hasBranchDivergence())
  799. CurDAG->VerifyDAGDivergence();
  800. #endif
  801. if (ViewDAGCombineLT && MatchFilterBB)
  802. CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
  803. // Run the DAG combiner in post-type-legalize mode.
  804. {
  805. NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
  806. GroupName, GroupDescription, TimePassesIsEnabled);
  807. CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel);
  808. }
  809. LLVM_DEBUG(dbgs() << "Optimized vector-legalized selection DAG: "
  810. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  811. << "'\n";
  812. CurDAG->dump());
  813. #ifndef NDEBUG
  814. if (TTI.hasBranchDivergence())
  815. CurDAG->VerifyDAGDivergence();
  816. #endif
  817. }
  818. if (ViewLegalizeDAGs && MatchFilterBB)
  819. CurDAG->viewGraph("legalize input for " + BlockName);
  820. {
  821. NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
  822. GroupDescription, TimePassesIsEnabled);
  823. CurDAG->Legalize();
  824. }
  825. LLVM_DEBUG(dbgs() << "Legalized selection DAG: "
  826. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  827. << "'\n";
  828. CurDAG->dump());
  829. #ifndef NDEBUG
  830. if (TTI.hasBranchDivergence())
  831. CurDAG->VerifyDAGDivergence();
  832. #endif
  833. if (ViewDAGCombine2 && MatchFilterBB)
  834. CurDAG->viewGraph("dag-combine2 input for " + BlockName);
  835. // Run the DAG combiner in post-legalize mode.
  836. {
  837. NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
  838. GroupDescription, TimePassesIsEnabled);
  839. CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel);
  840. }
  841. LLVM_DEBUG(dbgs() << "Optimized legalized selection DAG: "
  842. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  843. << "'\n";
  844. CurDAG->dump());
  845. #ifndef NDEBUG
  846. if (TTI.hasBranchDivergence())
  847. CurDAG->VerifyDAGDivergence();
  848. #endif
  849. if (OptLevel != CodeGenOpt::None)
  850. ComputeLiveOutVRegInfo();
  851. if (ViewISelDAGs && MatchFilterBB)
  852. CurDAG->viewGraph("isel input for " + BlockName);
  853. // Third, instruction select all of the operations to machine code, adding the
  854. // code to the MachineBasicBlock.
  855. {
  856. NamedRegionTimer T("isel", "Instruction Selection", GroupName,
  857. GroupDescription, TimePassesIsEnabled);
  858. DoInstructionSelection();
  859. }
  860. LLVM_DEBUG(dbgs() << "Selected selection DAG: "
  861. << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
  862. << "'\n";
  863. CurDAG->dump());
  864. if (ViewSchedDAGs && MatchFilterBB)
  865. CurDAG->viewGraph("scheduler input for " + BlockName);
  866. // Schedule machine code.
  867. ScheduleDAGSDNodes *Scheduler = CreateScheduler();
  868. {
  869. NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
  870. GroupDescription, TimePassesIsEnabled);
  871. Scheduler->Run(CurDAG, FuncInfo->MBB);
  872. }
  873. if (ViewSUnitDAGs && MatchFilterBB)
  874. Scheduler->viewGraph();
  875. // Emit machine code to BB. This can change 'BB' to the last block being
  876. // inserted into.
  877. MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
  878. {
  879. NamedRegionTimer T("emit", "Instruction Creation", GroupName,
  880. GroupDescription, TimePassesIsEnabled);
  881. // FuncInfo->InsertPt is passed by reference and set to the end of the
  882. // scheduled instructions.
  883. LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
  884. }
  885. // If the block was split, make sure we update any references that are used to
  886. // update PHI nodes later on.
  887. if (FirstMBB != LastMBB)
  888. SDB->UpdateSplitBlock(FirstMBB, LastMBB);
  889. // Free the scheduler state.
  890. {
  891. NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
  892. GroupDescription, TimePassesIsEnabled);
  893. delete Scheduler;
  894. }
  895. // Free the SelectionDAG state, now that we're finished with it.
  896. CurDAG->clear();
  897. }
  898. namespace {
  899. /// ISelUpdater - helper class to handle updates of the instruction selection
  900. /// graph.
  901. class ISelUpdater : public SelectionDAG::DAGUpdateListener {
  902. SelectionDAG::allnodes_iterator &ISelPosition;
  903. public:
  904. ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
  905. : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
  906. /// NodeDeleted - Handle nodes deleted from the graph. If the node being
  907. /// deleted is the current ISelPosition node, update ISelPosition.
  908. ///
  909. void NodeDeleted(SDNode *N, SDNode *E) override {
  910. if (ISelPosition == SelectionDAG::allnodes_iterator(N))
  911. ++ISelPosition;
  912. }
  913. };
  914. } // end anonymous namespace
  915. // This function is used to enforce the topological node id property
  916. // leveraged during instruction selection. Before the selection process all
  917. // nodes are given a non-negative id such that all nodes have a greater id than
  918. // their operands. As this holds transitively we can prune checks that a node N
  919. // is a predecessor of M another by not recursively checking through M's
  920. // operands if N's ID is larger than M's ID. This significantly improves
  921. // performance of various legality checks (e.g. IsLegalToFold / UpdateChains).
  922. // However, when we fuse multiple nodes into a single node during the
  923. // selection we may induce a predecessor relationship between inputs and
  924. // outputs of distinct nodes being merged, violating the topological property.
  925. // Should a fused node have a successor which has yet to be selected,
  926. // our legality checks would be incorrect. To avoid this we mark all unselected
  927. // successor nodes, i.e. id != -1, as invalid for pruning by bit-negating (x =>
  928. // (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
  929. // We use bit-negation to more clearly enforce that node id -1 can only be
  930. // achieved by selected nodes. As the conversion is reversable to the original
  931. // Id, topological pruning can still be leveraged when looking for unselected
  932. // nodes. This method is called internally in all ISel replacement related
  933. // functions.
  934. void SelectionDAGISel::EnforceNodeIdInvariant(SDNode *Node) {
  935. SmallVector<SDNode *, 4> Nodes;
  936. Nodes.push_back(Node);
  937. while (!Nodes.empty()) {
  938. SDNode *N = Nodes.pop_back_val();
  939. for (auto *U : N->uses()) {
  940. auto UId = U->getNodeId();
  941. if (UId > 0) {
  942. InvalidateNodeId(U);
  943. Nodes.push_back(U);
  944. }
  945. }
  946. }
  947. }
  948. // InvalidateNodeId - As explained in EnforceNodeIdInvariant, mark a
  949. // NodeId with the equivalent node id which is invalid for topological
  950. // pruning.
  951. void SelectionDAGISel::InvalidateNodeId(SDNode *N) {
  952. int InvalidId = -(N->getNodeId() + 1);
  953. N->setNodeId(InvalidId);
  954. }
  955. // getUninvalidatedNodeId - get original uninvalidated node id.
  956. int SelectionDAGISel::getUninvalidatedNodeId(SDNode *N) {
  957. int Id = N->getNodeId();
  958. if (Id < -1)
  959. return -(Id + 1);
  960. return Id;
  961. }
  962. void SelectionDAGISel::DoInstructionSelection() {
  963. LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
  964. << printMBBReference(*FuncInfo->MBB) << " '"
  965. << FuncInfo->MBB->getName() << "'\n");
  966. PreprocessISelDAG();
  967. // Select target instructions for the DAG.
  968. {
  969. // Number all nodes with a topological order and set DAGSize.
  970. DAGSize = CurDAG->AssignTopologicalOrder();
  971. // Create a dummy node (which is not added to allnodes), that adds
  972. // a reference to the root node, preventing it from being deleted,
  973. // and tracking any changes of the root.
  974. HandleSDNode Dummy(CurDAG->getRoot());
  975. SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
  976. ++ISelPosition;
  977. // Make sure that ISelPosition gets properly updated when nodes are deleted
  978. // in calls made from this function.
  979. ISelUpdater ISU(*CurDAG, ISelPosition);
  980. // The AllNodes list is now topological-sorted. Visit the
  981. // nodes by starting at the end of the list (the root of the
  982. // graph) and preceding back toward the beginning (the entry
  983. // node).
  984. while (ISelPosition != CurDAG->allnodes_begin()) {
  985. SDNode *Node = &*--ISelPosition;
  986. // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
  987. // but there are currently some corner cases that it misses. Also, this
  988. // makes it theoretically possible to disable the DAGCombiner.
  989. if (Node->use_empty())
  990. continue;
  991. #ifndef NDEBUG
  992. SmallVector<SDNode *, 4> Nodes;
  993. Nodes.push_back(Node);
  994. while (!Nodes.empty()) {
  995. auto N = Nodes.pop_back_val();
  996. if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
  997. continue;
  998. for (const SDValue &Op : N->op_values()) {
  999. if (Op->getOpcode() == ISD::TokenFactor)
  1000. Nodes.push_back(Op.getNode());
  1001. else {
  1002. // We rely on topological ordering of node ids for checking for
  1003. // cycles when fusing nodes during selection. All unselected nodes
  1004. // successors of an already selected node should have a negative id.
  1005. // This assertion will catch such cases. If this assertion triggers
  1006. // it is likely you using DAG-level Value/Node replacement functions
  1007. // (versus equivalent ISEL replacement) in backend-specific
  1008. // selections. See comment in EnforceNodeIdInvariant for more
  1009. // details.
  1010. assert(Op->getNodeId() != -1 &&
  1011. "Node has already selected predecessor node");
  1012. }
  1013. }
  1014. }
  1015. #endif
  1016. // When we are using non-default rounding modes or FP exception behavior
  1017. // FP operations are represented by StrictFP pseudo-operations. For
  1018. // targets that do not (yet) understand strict FP operations directly,
  1019. // we convert them to normal FP opcodes instead at this point. This
  1020. // will allow them to be handled by existing target-specific instruction
  1021. // selectors.
  1022. if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
  1023. // For some opcodes, we need to call TLI->getOperationAction using
  1024. // the first operand type instead of the result type. Note that this
  1025. // must match what SelectionDAGLegalize::LegalizeOp is doing.
  1026. EVT ActionVT;
  1027. switch (Node->getOpcode()) {
  1028. case ISD::STRICT_SINT_TO_FP:
  1029. case ISD::STRICT_UINT_TO_FP:
  1030. case ISD::STRICT_LRINT:
  1031. case ISD::STRICT_LLRINT:
  1032. case ISD::STRICT_LROUND:
  1033. case ISD::STRICT_LLROUND:
  1034. case ISD::STRICT_FSETCC:
  1035. case ISD::STRICT_FSETCCS:
  1036. ActionVT = Node->getOperand(1).getValueType();
  1037. break;
  1038. default:
  1039. ActionVT = Node->getValueType(0);
  1040. break;
  1041. }
  1042. if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
  1043. == TargetLowering::Expand)
  1044. Node = CurDAG->mutateStrictFPToFP(Node);
  1045. }
  1046. LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
  1047. Node->dump(CurDAG));
  1048. Select(Node);
  1049. }
  1050. CurDAG->setRoot(Dummy.getValue());
  1051. }
  1052. LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
  1053. PostprocessISelDAG();
  1054. }
  1055. static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
  1056. for (const User *U : CPI->users()) {
  1057. if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
  1058. Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
  1059. if (IID == Intrinsic::eh_exceptionpointer ||
  1060. IID == Intrinsic::eh_exceptioncode)
  1061. return true;
  1062. }
  1063. }
  1064. return false;
  1065. }
  1066. // wasm.landingpad.index intrinsic is for associating a landing pad index number
  1067. // with a catchpad instruction. Retrieve the landing pad index in the intrinsic
  1068. // and store the mapping in the function.
  1069. static void mapWasmLandingPadIndex(MachineBasicBlock *MBB,
  1070. const CatchPadInst *CPI) {
  1071. MachineFunction *MF = MBB->getParent();
  1072. // In case of single catch (...), we don't emit LSDA, so we don't need
  1073. // this information.
  1074. bool IsSingleCatchAllClause =
  1075. CPI->getNumArgOperands() == 1 &&
  1076. cast<Constant>(CPI->getArgOperand(0))->isNullValue();
  1077. // cathchpads for longjmp use an empty type list, e.g. catchpad within %0 []
  1078. // and they don't need LSDA info
  1079. bool IsCatchLongjmp = CPI->getNumArgOperands() == 0;
  1080. if (!IsSingleCatchAllClause && !IsCatchLongjmp) {
  1081. // Create a mapping from landing pad label to landing pad index.
  1082. bool IntrFound = false;
  1083. for (const User *U : CPI->users()) {
  1084. if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
  1085. Intrinsic::ID IID = Call->getIntrinsicID();
  1086. if (IID == Intrinsic::wasm_landingpad_index) {
  1087. Value *IndexArg = Call->getArgOperand(1);
  1088. int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
  1089. MF->setWasmLandingPadIndex(MBB, Index);
  1090. IntrFound = true;
  1091. break;
  1092. }
  1093. }
  1094. }
  1095. assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
  1096. (void)IntrFound;
  1097. }
  1098. }
  1099. /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
  1100. /// do other setup for EH landing-pad blocks.
  1101. bool SelectionDAGISel::PrepareEHLandingPad() {
  1102. MachineBasicBlock *MBB = FuncInfo->MBB;
  1103. const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
  1104. const BasicBlock *LLVMBB = MBB->getBasicBlock();
  1105. const TargetRegisterClass *PtrRC =
  1106. TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
  1107. auto Pers = classifyEHPersonality(PersonalityFn);
  1108. // Catchpads have one live-in register, which typically holds the exception
  1109. // pointer or code.
  1110. if (isFuncletEHPersonality(Pers)) {
  1111. if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
  1112. if (hasExceptionPointerOrCodeUser(CPI)) {
  1113. // Get or create the virtual register to hold the pointer or code. Mark
  1114. // the live in physreg and copy into the vreg.
  1115. MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
  1116. assert(EHPhysReg && "target lacks exception pointer register");
  1117. MBB->addLiveIn(EHPhysReg);
  1118. unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
  1119. BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
  1120. TII->get(TargetOpcode::COPY), VReg)
  1121. .addReg(EHPhysReg, RegState::Kill);
  1122. }
  1123. }
  1124. return true;
  1125. }
  1126. // Add a label to mark the beginning of the landing pad. Deletion of the
  1127. // landing pad can thus be detected via the MachineModuleInfo.
  1128. MCSymbol *Label = MF->addLandingPad(MBB);
  1129. const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
  1130. BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
  1131. .addSym(Label);
  1132. // If the unwinder does not preserve all registers, ensure that the
  1133. // function marks the clobbered registers as used.
  1134. const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
  1135. if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
  1136. MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
  1137. if (Pers == EHPersonality::Wasm_CXX) {
  1138. if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI()))
  1139. mapWasmLandingPadIndex(MBB, CPI);
  1140. } else {
  1141. // Assign the call site to the landing pad's begin label.
  1142. MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
  1143. // Mark exception register as live in.
  1144. if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
  1145. FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
  1146. // Mark exception selector register as live in.
  1147. if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
  1148. FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
  1149. }
  1150. return true;
  1151. }
  1152. /// isFoldedOrDeadInstruction - Return true if the specified instruction is
  1153. /// side-effect free and is either dead or folded into a generated instruction.
  1154. /// Return false if it needs to be emitted.
  1155. static bool isFoldedOrDeadInstruction(const Instruction *I,
  1156. const FunctionLoweringInfo &FuncInfo) {
  1157. return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
  1158. !I->isTerminator() && // Terminators aren't folded.
  1159. !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
  1160. !I->isEHPad() && // EH pad instructions aren't folded.
  1161. !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
  1162. }
  1163. /// Collect llvm.dbg.declare information. This is done after argument lowering
  1164. /// in case the declarations refer to arguments.
  1165. static void processDbgDeclares(FunctionLoweringInfo &FuncInfo) {
  1166. MachineFunction *MF = FuncInfo.MF;
  1167. const DataLayout &DL = MF->getDataLayout();
  1168. for (const BasicBlock &BB : *FuncInfo.Fn) {
  1169. for (const Instruction &I : BB) {
  1170. const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I);
  1171. if (!DI)
  1172. continue;
  1173. assert(DI->getVariable() && "Missing variable");
  1174. assert(DI->getDebugLoc() && "Missing location");
  1175. const Value *Address = DI->getAddress();
  1176. if (!Address) {
  1177. LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *DI
  1178. << " (bad address)\n");
  1179. continue;
  1180. }
  1181. // Look through casts and constant offset GEPs. These mostly come from
  1182. // inalloca.
  1183. APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0);
  1184. Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
  1185. // Check if the variable is a static alloca or a byval or inalloca
  1186. // argument passed in memory. If it is not, then we will ignore this
  1187. // intrinsic and handle this during isel like dbg.value.
  1188. int FI = std::numeric_limits<int>::max();
  1189. if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
  1190. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1191. if (SI != FuncInfo.StaticAllocaMap.end())
  1192. FI = SI->second;
  1193. } else if (const auto *Arg = dyn_cast<Argument>(Address))
  1194. FI = FuncInfo.getArgumentFrameIndex(Arg);
  1195. if (FI == std::numeric_limits<int>::max())
  1196. continue;
  1197. DIExpression *Expr = DI->getExpression();
  1198. if (Offset.getBoolValue())
  1199. Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset,
  1200. Offset.getZExtValue());
  1201. LLVM_DEBUG(dbgs() << "processDbgDeclares: setVariableDbgInfo FI=" << FI
  1202. << ", " << *DI << "\n");
  1203. MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc());
  1204. }
  1205. }
  1206. }
  1207. void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
  1208. FastISelFailed = false;
  1209. // Initialize the Fast-ISel state, if needed.
  1210. FastISel *FastIS = nullptr;
  1211. if (TM.Options.EnableFastISel) {
  1212. LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
  1213. FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
  1214. if (FastIS)
  1215. FastIS->useInstrRefDebugInfo(UseInstrRefDebugInfo);
  1216. }
  1217. ReversePostOrderTraversal<const Function*> RPOT(&Fn);
  1218. // Lower arguments up front. An RPO iteration always visits the entry block
  1219. // first.
  1220. assert(*RPOT.begin() == &Fn.getEntryBlock());
  1221. ++NumEntryBlocks;
  1222. // Set up FuncInfo for ISel. Entry blocks never have PHIs.
  1223. FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
  1224. FuncInfo->InsertPt = FuncInfo->MBB->begin();
  1225. CurDAG->setFunctionLoweringInfo(FuncInfo.get());
  1226. if (!FastIS) {
  1227. LowerArguments(Fn);
  1228. } else {
  1229. // See if fast isel can lower the arguments.
  1230. FastIS->startNewBlock();
  1231. if (!FastIS->lowerArguments()) {
  1232. FastISelFailed = true;
  1233. // Fast isel failed to lower these arguments
  1234. ++NumFastIselFailLowerArguments;
  1235. OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
  1236. Fn.getSubprogram(),
  1237. &Fn.getEntryBlock());
  1238. R << "FastISel didn't lower all arguments: "
  1239. << ore::NV("Prototype", Fn.getType());
  1240. reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1);
  1241. // Use SelectionDAG argument lowering
  1242. LowerArguments(Fn);
  1243. CurDAG->setRoot(SDB->getControlRoot());
  1244. SDB->clear();
  1245. CodeGenAndEmitDAG();
  1246. }
  1247. // If we inserted any instructions at the beginning, make a note of
  1248. // where they are, so we can be sure to emit subsequent instructions
  1249. // after them.
  1250. if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
  1251. FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
  1252. else
  1253. FastIS->setLastLocalValue(nullptr);
  1254. }
  1255. bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
  1256. if (FastIS && Inserted)
  1257. FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
  1258. processDbgDeclares(*FuncInfo);
  1259. // Iterate over all basic blocks in the function.
  1260. StackProtector &SP = getAnalysis<StackProtector>();
  1261. for (const BasicBlock *LLVMBB : RPOT) {
  1262. if (OptLevel != CodeGenOpt::None) {
  1263. bool AllPredsVisited = true;
  1264. for (const BasicBlock *Pred : predecessors(LLVMBB)) {
  1265. if (!FuncInfo->VisitedBBs.count(Pred)) {
  1266. AllPredsVisited = false;
  1267. break;
  1268. }
  1269. }
  1270. if (AllPredsVisited) {
  1271. for (const PHINode &PN : LLVMBB->phis())
  1272. FuncInfo->ComputePHILiveOutRegInfo(&PN);
  1273. } else {
  1274. for (const PHINode &PN : LLVMBB->phis())
  1275. FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
  1276. }
  1277. FuncInfo->VisitedBBs.insert(LLVMBB);
  1278. }
  1279. BasicBlock::const_iterator const Begin =
  1280. LLVMBB->getFirstNonPHI()->getIterator();
  1281. BasicBlock::const_iterator const End = LLVMBB->end();
  1282. BasicBlock::const_iterator BI = End;
  1283. FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
  1284. if (!FuncInfo->MBB)
  1285. continue; // Some blocks like catchpads have no code or MBB.
  1286. // Insert new instructions after any phi or argument setup code.
  1287. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1288. // Setup an EH landing-pad block.
  1289. FuncInfo->ExceptionPointerVirtReg = 0;
  1290. FuncInfo->ExceptionSelectorVirtReg = 0;
  1291. if (LLVMBB->isEHPad())
  1292. if (!PrepareEHLandingPad())
  1293. continue;
  1294. // Before doing SelectionDAG ISel, see if FastISel has been requested.
  1295. if (FastIS) {
  1296. if (LLVMBB != &Fn.getEntryBlock())
  1297. FastIS->startNewBlock();
  1298. unsigned NumFastIselRemaining = std::distance(Begin, End);
  1299. // Pre-assign swifterror vregs.
  1300. SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
  1301. // Do FastISel on as many instructions as possible.
  1302. for (; BI != Begin; --BI) {
  1303. const Instruction *Inst = &*std::prev(BI);
  1304. // If we no longer require this instruction, skip it.
  1305. if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
  1306. ElidedArgCopyInstrs.count(Inst)) {
  1307. --NumFastIselRemaining;
  1308. continue;
  1309. }
  1310. // Bottom-up: reset the insert pos at the top, after any local-value
  1311. // instructions.
  1312. FastIS->recomputeInsertPt();
  1313. // Try to select the instruction with FastISel.
  1314. if (FastIS->selectInstruction(Inst)) {
  1315. --NumFastIselRemaining;
  1316. ++NumFastIselSuccess;
  1317. // If fast isel succeeded, skip over all the folded instructions, and
  1318. // then see if there is a load right before the selected instructions.
  1319. // Try to fold the load if so.
  1320. const Instruction *BeforeInst = Inst;
  1321. while (BeforeInst != &*Begin) {
  1322. BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
  1323. if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
  1324. break;
  1325. }
  1326. if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
  1327. BeforeInst->hasOneUse() &&
  1328. FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
  1329. // If we succeeded, don't re-select the load.
  1330. BI = std::next(BasicBlock::const_iterator(BeforeInst));
  1331. --NumFastIselRemaining;
  1332. ++NumFastIselSuccess;
  1333. }
  1334. continue;
  1335. }
  1336. FastISelFailed = true;
  1337. // Then handle certain instructions as single-LLVM-Instruction blocks.
  1338. // We cannot separate out GCrelocates to their own blocks since we need
  1339. // to keep track of gc-relocates for a particular gc-statepoint. This is
  1340. // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
  1341. // visitGCRelocate.
  1342. if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
  1343. !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
  1344. OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
  1345. Inst->getDebugLoc(), LLVMBB);
  1346. R << "FastISel missed call";
  1347. if (R.isEnabled() || EnableFastISelAbort) {
  1348. std::string InstStrStorage;
  1349. raw_string_ostream InstStr(InstStrStorage);
  1350. InstStr << *Inst;
  1351. R << ": " << InstStr.str();
  1352. }
  1353. reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2);
  1354. if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
  1355. !Inst->use_empty()) {
  1356. Register &R = FuncInfo->ValueMap[Inst];
  1357. if (!R)
  1358. R = FuncInfo->CreateRegs(Inst);
  1359. }
  1360. bool HadTailCall = false;
  1361. MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
  1362. SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
  1363. // If the call was emitted as a tail call, we're done with the block.
  1364. // We also need to delete any previously emitted instructions.
  1365. if (HadTailCall) {
  1366. FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
  1367. --BI;
  1368. break;
  1369. }
  1370. // Recompute NumFastIselRemaining as Selection DAG instruction
  1371. // selection may have handled the call, input args, etc.
  1372. unsigned RemainingNow = std::distance(Begin, BI);
  1373. NumFastIselFailures += NumFastIselRemaining - RemainingNow;
  1374. NumFastIselRemaining = RemainingNow;
  1375. continue;
  1376. }
  1377. OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
  1378. Inst->getDebugLoc(), LLVMBB);
  1379. bool ShouldAbort = EnableFastISelAbort;
  1380. if (Inst->isTerminator()) {
  1381. // Use a different message for terminator misses.
  1382. R << "FastISel missed terminator";
  1383. // Don't abort for terminator unless the level is really high
  1384. ShouldAbort = (EnableFastISelAbort > 2);
  1385. } else {
  1386. R << "FastISel missed";
  1387. }
  1388. if (R.isEnabled() || EnableFastISelAbort) {
  1389. std::string InstStrStorage;
  1390. raw_string_ostream InstStr(InstStrStorage);
  1391. InstStr << *Inst;
  1392. R << ": " << InstStr.str();
  1393. }
  1394. reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
  1395. NumFastIselFailures += NumFastIselRemaining;
  1396. break;
  1397. }
  1398. FastIS->recomputeInsertPt();
  1399. }
  1400. if (SP.shouldEmitSDCheck(*LLVMBB)) {
  1401. bool FunctionBasedInstrumentation =
  1402. TLI->getSSPStackGuardCheck(*Fn.getParent());
  1403. SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
  1404. FunctionBasedInstrumentation);
  1405. }
  1406. if (Begin != BI)
  1407. ++NumDAGBlocks;
  1408. else
  1409. ++NumFastIselBlocks;
  1410. if (Begin != BI) {
  1411. // Run SelectionDAG instruction selection on the remainder of the block
  1412. // not handled by FastISel. If FastISel is not run, this is the entire
  1413. // block.
  1414. bool HadTailCall;
  1415. SelectBasicBlock(Begin, BI, HadTailCall);
  1416. // But if FastISel was run, we already selected some of the block.
  1417. // If we emitted a tail-call, we need to delete any previously emitted
  1418. // instruction that follows it.
  1419. if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
  1420. FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
  1421. }
  1422. if (FastIS)
  1423. FastIS->finishBasicBlock();
  1424. FinishBasicBlock();
  1425. FuncInfo->PHINodesToUpdate.clear();
  1426. ElidedArgCopyInstrs.clear();
  1427. }
  1428. SP.copyToMachineFrameInfo(MF->getFrameInfo());
  1429. SwiftError->propagateVRegs();
  1430. delete FastIS;
  1431. SDB->clearDanglingDebugInfo();
  1432. SDB->SPDescriptor.resetPerFunctionState();
  1433. }
  1434. void
  1435. SelectionDAGISel::FinishBasicBlock() {
  1436. LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
  1437. << FuncInfo->PHINodesToUpdate.size() << "\n";
  1438. for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
  1439. ++i) dbgs()
  1440. << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
  1441. << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
  1442. // Next, now that we know what the last MBB the LLVM BB expanded is, update
  1443. // PHI nodes in successors.
  1444. for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
  1445. MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
  1446. assert(PHI->isPHI() &&
  1447. "This is not a machine PHI node that we are updating!");
  1448. if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
  1449. continue;
  1450. PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
  1451. }
  1452. // Handle stack protector.
  1453. if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
  1454. // The target provides a guard check function. There is no need to
  1455. // generate error handling code or to split current basic block.
  1456. MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
  1457. // Add load and check to the basicblock.
  1458. FuncInfo->MBB = ParentMBB;
  1459. FuncInfo->InsertPt =
  1460. findSplitPointForStackProtector(ParentMBB, *TII);
  1461. SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
  1462. CurDAG->setRoot(SDB->getRoot());
  1463. SDB->clear();
  1464. CodeGenAndEmitDAG();
  1465. // Clear the Per-BB State.
  1466. SDB->SPDescriptor.resetPerBBState();
  1467. } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
  1468. MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
  1469. MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
  1470. // Find the split point to split the parent mbb. At the same time copy all
  1471. // physical registers used in the tail of parent mbb into virtual registers
  1472. // before the split point and back into physical registers after the split
  1473. // point. This prevents us needing to deal with Live-ins and many other
  1474. // register allocation issues caused by us splitting the parent mbb. The
  1475. // register allocator will clean up said virtual copies later on.
  1476. MachineBasicBlock::iterator SplitPoint =
  1477. findSplitPointForStackProtector(ParentMBB, *TII);
  1478. // Splice the terminator of ParentMBB into SuccessMBB.
  1479. SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
  1480. SplitPoint,
  1481. ParentMBB->end());
  1482. // Add compare/jump on neq/jump to the parent BB.
  1483. FuncInfo->MBB = ParentMBB;
  1484. FuncInfo->InsertPt = ParentMBB->end();
  1485. SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
  1486. CurDAG->setRoot(SDB->getRoot());
  1487. SDB->clear();
  1488. CodeGenAndEmitDAG();
  1489. // CodeGen Failure MBB if we have not codegened it yet.
  1490. MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
  1491. if (FailureMBB->empty()) {
  1492. FuncInfo->MBB = FailureMBB;
  1493. FuncInfo->InsertPt = FailureMBB->end();
  1494. SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
  1495. CurDAG->setRoot(SDB->getRoot());
  1496. SDB->clear();
  1497. CodeGenAndEmitDAG();
  1498. }
  1499. // Clear the Per-BB State.
  1500. SDB->SPDescriptor.resetPerBBState();
  1501. }
  1502. // Lower each BitTestBlock.
  1503. for (auto &BTB : SDB->SL->BitTestCases) {
  1504. // Lower header first, if it wasn't already lowered
  1505. if (!BTB.Emitted) {
  1506. // Set the current basic block to the mbb we wish to insert the code into
  1507. FuncInfo->MBB = BTB.Parent;
  1508. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1509. // Emit the code
  1510. SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
  1511. CurDAG->setRoot(SDB->getRoot());
  1512. SDB->clear();
  1513. CodeGenAndEmitDAG();
  1514. }
  1515. BranchProbability UnhandledProb = BTB.Prob;
  1516. for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
  1517. UnhandledProb -= BTB.Cases[j].ExtraProb;
  1518. // Set the current basic block to the mbb we wish to insert the code into
  1519. FuncInfo->MBB = BTB.Cases[j].ThisBB;
  1520. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1521. // Emit the code
  1522. // If all cases cover a contiguous range, it is not necessary to jump to
  1523. // the default block after the last bit test fails. This is because the
  1524. // range check during bit test header creation has guaranteed that every
  1525. // case here doesn't go outside the range. In this case, there is no need
  1526. // to perform the last bit test, as it will always be true. Instead, make
  1527. // the second-to-last bit-test fall through to the target of the last bit
  1528. // test, and delete the last bit test.
  1529. MachineBasicBlock *NextMBB;
  1530. if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
  1531. // Second-to-last bit-test with contiguous range or omitted range
  1532. // check: fall through to the target of the final bit test.
  1533. NextMBB = BTB.Cases[j + 1].TargetBB;
  1534. } else if (j + 1 == ej) {
  1535. // For the last bit test, fall through to Default.
  1536. NextMBB = BTB.Default;
  1537. } else {
  1538. // Otherwise, fall through to the next bit test.
  1539. NextMBB = BTB.Cases[j + 1].ThisBB;
  1540. }
  1541. SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
  1542. FuncInfo->MBB);
  1543. CurDAG->setRoot(SDB->getRoot());
  1544. SDB->clear();
  1545. CodeGenAndEmitDAG();
  1546. if ((BTB.ContiguousRange || BTB.FallthroughUnreachable) && j + 2 == ej) {
  1547. // Since we're not going to use the final bit test, remove it.
  1548. BTB.Cases.pop_back();
  1549. break;
  1550. }
  1551. }
  1552. // Update PHI Nodes
  1553. for (const std::pair<MachineInstr *, unsigned> &P :
  1554. FuncInfo->PHINodesToUpdate) {
  1555. MachineInstrBuilder PHI(*MF, P.first);
  1556. MachineBasicBlock *PHIBB = PHI->getParent();
  1557. assert(PHI->isPHI() &&
  1558. "This is not a machine PHI node that we are updating!");
  1559. // This is "default" BB. We have two jumps to it. From "header" BB and
  1560. // from last "case" BB, unless the latter was skipped.
  1561. if (PHIBB == BTB.Default) {
  1562. PHI.addReg(P.second).addMBB(BTB.Parent);
  1563. if (!BTB.ContiguousRange) {
  1564. PHI.addReg(P.second).addMBB(BTB.Cases.back().ThisBB);
  1565. }
  1566. }
  1567. // One of "cases" BB.
  1568. for (const SwitchCG::BitTestCase &BT : BTB.Cases) {
  1569. MachineBasicBlock* cBB = BT.ThisBB;
  1570. if (cBB->isSuccessor(PHIBB))
  1571. PHI.addReg(P.second).addMBB(cBB);
  1572. }
  1573. }
  1574. }
  1575. SDB->SL->BitTestCases.clear();
  1576. // If the JumpTable record is filled in, then we need to emit a jump table.
  1577. // Updating the PHI nodes is tricky in this case, since we need to determine
  1578. // whether the PHI is a successor of the range check MBB or the jump table MBB
  1579. for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
  1580. // Lower header first, if it wasn't already lowered
  1581. if (!SDB->SL->JTCases[i].first.Emitted) {
  1582. // Set the current basic block to the mbb we wish to insert the code into
  1583. FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
  1584. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1585. // Emit the code
  1586. SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
  1587. SDB->SL->JTCases[i].first, FuncInfo->MBB);
  1588. CurDAG->setRoot(SDB->getRoot());
  1589. SDB->clear();
  1590. CodeGenAndEmitDAG();
  1591. }
  1592. // Set the current basic block to the mbb we wish to insert the code into
  1593. FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
  1594. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1595. // Emit the code
  1596. SDB->visitJumpTable(SDB->SL->JTCases[i].second);
  1597. CurDAG->setRoot(SDB->getRoot());
  1598. SDB->clear();
  1599. CodeGenAndEmitDAG();
  1600. // Update PHI Nodes
  1601. for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
  1602. pi != pe; ++pi) {
  1603. MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
  1604. MachineBasicBlock *PHIBB = PHI->getParent();
  1605. assert(PHI->isPHI() &&
  1606. "This is not a machine PHI node that we are updating!");
  1607. // "default" BB. We can go there only from header BB.
  1608. if (PHIBB == SDB->SL->JTCases[i].second.Default)
  1609. PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
  1610. .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
  1611. // JT BB. Just iterate over successors here
  1612. if (FuncInfo->MBB->isSuccessor(PHIBB))
  1613. PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
  1614. }
  1615. }
  1616. SDB->SL->JTCases.clear();
  1617. // If we generated any switch lowering information, build and codegen any
  1618. // additional DAGs necessary.
  1619. for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
  1620. // Set the current basic block to the mbb we wish to insert the code into
  1621. FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
  1622. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1623. // Determine the unique successors.
  1624. SmallVector<MachineBasicBlock *, 2> Succs;
  1625. Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
  1626. if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
  1627. Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
  1628. // Emit the code. Note that this could result in FuncInfo->MBB being split.
  1629. SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
  1630. CurDAG->setRoot(SDB->getRoot());
  1631. SDB->clear();
  1632. CodeGenAndEmitDAG();
  1633. // Remember the last block, now that any splitting is done, for use in
  1634. // populating PHI nodes in successors.
  1635. MachineBasicBlock *ThisBB = FuncInfo->MBB;
  1636. // Handle any PHI nodes in successors of this chunk, as if we were coming
  1637. // from the original BB before switch expansion. Note that PHI nodes can
  1638. // occur multiple times in PHINodesToUpdate. We have to be very careful to
  1639. // handle them the right number of times.
  1640. for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
  1641. FuncInfo->MBB = Succs[i];
  1642. FuncInfo->InsertPt = FuncInfo->MBB->end();
  1643. // FuncInfo->MBB may have been removed from the CFG if a branch was
  1644. // constant folded.
  1645. if (ThisBB->isSuccessor(FuncInfo->MBB)) {
  1646. for (MachineBasicBlock::iterator
  1647. MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
  1648. MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
  1649. MachineInstrBuilder PHI(*MF, MBBI);
  1650. // This value for this PHI node is recorded in PHINodesToUpdate.
  1651. for (unsigned pn = 0; ; ++pn) {
  1652. assert(pn != FuncInfo->PHINodesToUpdate.size() &&
  1653. "Didn't find PHI entry!");
  1654. if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
  1655. PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
  1656. break;
  1657. }
  1658. }
  1659. }
  1660. }
  1661. }
  1662. }
  1663. SDB->SL->SwitchCases.clear();
  1664. }
  1665. /// Create the scheduler. If a specific scheduler was specified
  1666. /// via the SchedulerRegistry, use it, otherwise select the
  1667. /// one preferred by the target.
  1668. ///
  1669. ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
  1670. return ISHeuristic(this, OptLevel);
  1671. }
  1672. //===----------------------------------------------------------------------===//
  1673. // Helper functions used by the generated instruction selector.
  1674. //===----------------------------------------------------------------------===//
  1675. // Calls to these methods are generated by tblgen.
  1676. /// CheckAndMask - The isel is trying to match something like (and X, 255). If
  1677. /// the dag combiner simplified the 255, we still want to match. RHS is the
  1678. /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
  1679. /// specified in the .td file (e.g. 255).
  1680. bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
  1681. int64_t DesiredMaskS) const {
  1682. const APInt &ActualMask = RHS->getAPIntValue();
  1683. const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
  1684. // If the actual mask exactly matches, success!
  1685. if (ActualMask == DesiredMask)
  1686. return true;
  1687. // If the actual AND mask is allowing unallowed bits, this doesn't match.
  1688. if (!ActualMask.isSubsetOf(DesiredMask))
  1689. return false;
  1690. // Otherwise, the DAG Combiner may have proven that the value coming in is
  1691. // either already zero or is not demanded. Check for known zero input bits.
  1692. APInt NeededMask = DesiredMask & ~ActualMask;
  1693. if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
  1694. return true;
  1695. // TODO: check to see if missing bits are just not demanded.
  1696. // Otherwise, this pattern doesn't match.
  1697. return false;
  1698. }
  1699. /// CheckOrMask - The isel is trying to match something like (or X, 255). If
  1700. /// the dag combiner simplified the 255, we still want to match. RHS is the
  1701. /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
  1702. /// specified in the .td file (e.g. 255).
  1703. bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
  1704. int64_t DesiredMaskS) const {
  1705. const APInt &ActualMask = RHS->getAPIntValue();
  1706. const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
  1707. // If the actual mask exactly matches, success!
  1708. if (ActualMask == DesiredMask)
  1709. return true;
  1710. // If the actual AND mask is allowing unallowed bits, this doesn't match.
  1711. if (!ActualMask.isSubsetOf(DesiredMask))
  1712. return false;
  1713. // Otherwise, the DAG Combiner may have proven that the value coming in is
  1714. // either already zero or is not demanded. Check for known zero input bits.
  1715. APInt NeededMask = DesiredMask & ~ActualMask;
  1716. KnownBits Known = CurDAG->computeKnownBits(LHS);
  1717. // If all the missing bits in the or are already known to be set, match!
  1718. if (NeededMask.isSubsetOf(Known.One))
  1719. return true;
  1720. // TODO: check to see if missing bits are just not demanded.
  1721. // Otherwise, this pattern doesn't match.
  1722. return false;
  1723. }
  1724. /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
  1725. /// by tblgen. Others should not call it.
  1726. void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
  1727. const SDLoc &DL) {
  1728. std::vector<SDValue> InOps;
  1729. std::swap(InOps, Ops);
  1730. Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
  1731. Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
  1732. Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
  1733. Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
  1734. unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
  1735. if (InOps[e-1].getValueType() == MVT::Glue)
  1736. --e; // Don't process a glue operand if it is here.
  1737. while (i != e) {
  1738. unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
  1739. if (!InlineAsm::isMemKind(Flags)) {
  1740. // Just skip over this operand, copying the operands verbatim.
  1741. Ops.insert(Ops.end(), InOps.begin()+i,
  1742. InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
  1743. i += InlineAsm::getNumOperandRegisters(Flags) + 1;
  1744. } else {
  1745. assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
  1746. "Memory operand with multiple values?");
  1747. unsigned TiedToOperand;
  1748. if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
  1749. // We need the constraint ID from the operand this is tied to.
  1750. unsigned CurOp = InlineAsm::Op_FirstOperand;
  1751. Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
  1752. for (; TiedToOperand; --TiedToOperand) {
  1753. CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
  1754. Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
  1755. }
  1756. }
  1757. // Otherwise, this is a memory operand. Ask the target to select it.
  1758. std::vector<SDValue> SelOps;
  1759. unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags);
  1760. if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps))
  1761. report_fatal_error("Could not match memory address. Inline asm"
  1762. " failure!");
  1763. // Add this to the output node.
  1764. unsigned NewFlags =
  1765. InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
  1766. NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID);
  1767. Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
  1768. llvm::append_range(Ops, SelOps);
  1769. i += 2;
  1770. }
  1771. }
  1772. // Add the glue input back if present.
  1773. if (e != InOps.size())
  1774. Ops.push_back(InOps.back());
  1775. }
  1776. /// findGlueUse - Return use of MVT::Glue value produced by the specified
  1777. /// SDNode.
  1778. ///
  1779. static SDNode *findGlueUse(SDNode *N) {
  1780. unsigned FlagResNo = N->getNumValues()-1;
  1781. for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
  1782. SDUse &Use = I.getUse();
  1783. if (Use.getResNo() == FlagResNo)
  1784. return Use.getUser();
  1785. }
  1786. return nullptr;
  1787. }
  1788. /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
  1789. /// beyond "ImmedUse". We may ignore chains as they are checked separately.
  1790. static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
  1791. bool IgnoreChains) {
  1792. SmallPtrSet<const SDNode *, 16> Visited;
  1793. SmallVector<const SDNode *, 16> WorkList;
  1794. // Only check if we have non-immediate uses of Def.
  1795. if (ImmedUse->isOnlyUserOf(Def))
  1796. return false;
  1797. // We don't care about paths to Def that go through ImmedUse so mark it
  1798. // visited and mark non-def operands as used.
  1799. Visited.insert(ImmedUse);
  1800. for (const SDValue &Op : ImmedUse->op_values()) {
  1801. SDNode *N = Op.getNode();
  1802. // Ignore chain deps (they are validated by
  1803. // HandleMergeInputChains) and immediate uses
  1804. if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
  1805. continue;
  1806. if (!Visited.insert(N).second)
  1807. continue;
  1808. WorkList.push_back(N);
  1809. }
  1810. // Initialize worklist to operands of Root.
  1811. if (Root != ImmedUse) {
  1812. for (const SDValue &Op : Root->op_values()) {
  1813. SDNode *N = Op.getNode();
  1814. // Ignore chains (they are validated by HandleMergeInputChains)
  1815. if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
  1816. continue;
  1817. if (!Visited.insert(N).second)
  1818. continue;
  1819. WorkList.push_back(N);
  1820. }
  1821. }
  1822. return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
  1823. }
  1824. /// IsProfitableToFold - Returns true if it's profitable to fold the specific
  1825. /// operand node N of U during instruction selection that starts at Root.
  1826. bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
  1827. SDNode *Root) const {
  1828. if (OptLevel == CodeGenOpt::None) return false;
  1829. return N.hasOneUse();
  1830. }
  1831. /// IsLegalToFold - Returns true if the specific operand node N of
  1832. /// U can be folded during instruction selection that starts at Root.
  1833. bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
  1834. CodeGenOpt::Level OptLevel,
  1835. bool IgnoreChains) {
  1836. if (OptLevel == CodeGenOpt::None) return false;
  1837. // If Root use can somehow reach N through a path that that doesn't contain
  1838. // U then folding N would create a cycle. e.g. In the following
  1839. // diagram, Root can reach N through X. If N is folded into Root, then
  1840. // X is both a predecessor and a successor of U.
  1841. //
  1842. // [N*] //
  1843. // ^ ^ //
  1844. // / \ //
  1845. // [U*] [X]? //
  1846. // ^ ^ //
  1847. // \ / //
  1848. // \ / //
  1849. // [Root*] //
  1850. //
  1851. // * indicates nodes to be folded together.
  1852. //
  1853. // If Root produces glue, then it gets (even more) interesting. Since it
  1854. // will be "glued" together with its glue use in the scheduler, we need to
  1855. // check if it might reach N.
  1856. //
  1857. // [N*] //
  1858. // ^ ^ //
  1859. // / \ //
  1860. // [U*] [X]? //
  1861. // ^ ^ //
  1862. // \ \ //
  1863. // \ | //
  1864. // [Root*] | //
  1865. // ^ | //
  1866. // f | //
  1867. // | / //
  1868. // [Y] / //
  1869. // ^ / //
  1870. // f / //
  1871. // | / //
  1872. // [GU] //
  1873. //
  1874. // If GU (glue use) indirectly reaches N (the load), and Root folds N
  1875. // (call it Fold), then X is a predecessor of GU and a successor of
  1876. // Fold. But since Fold and GU are glued together, this will create
  1877. // a cycle in the scheduling graph.
  1878. // If the node has glue, walk down the graph to the "lowest" node in the
  1879. // glueged set.
  1880. EVT VT = Root->getValueType(Root->getNumValues()-1);
  1881. while (VT == MVT::Glue) {
  1882. SDNode *GU = findGlueUse(Root);
  1883. if (!GU)
  1884. break;
  1885. Root = GU;
  1886. VT = Root->getValueType(Root->getNumValues()-1);
  1887. // If our query node has a glue result with a use, we've walked up it. If
  1888. // the user (which has already been selected) has a chain or indirectly uses
  1889. // the chain, HandleMergeInputChains will not consider it. Because of
  1890. // this, we cannot ignore chains in this predicate.
  1891. IgnoreChains = false;
  1892. }
  1893. return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
  1894. }
  1895. void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
  1896. SDLoc DL(N);
  1897. std::vector<SDValue> Ops(N->op_begin(), N->op_end());
  1898. SelectInlineAsmMemoryOperands(Ops, DL);
  1899. const EVT VTs[] = {MVT::Other, MVT::Glue};
  1900. SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
  1901. New->setNodeId(-1);
  1902. ReplaceUses(N, New.getNode());
  1903. CurDAG->RemoveDeadNode(N);
  1904. }
  1905. void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
  1906. SDLoc dl(Op);
  1907. MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
  1908. const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
  1909. EVT VT = Op->getValueType(0);
  1910. LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
  1911. Register Reg =
  1912. TLI->getRegisterByName(RegStr->getString().data(), Ty,
  1913. CurDAG->getMachineFunction());
  1914. SDValue New = CurDAG->getCopyFromReg(
  1915. Op->getOperand(0), dl, Reg, Op->getValueType(0));
  1916. New->setNodeId(-1);
  1917. ReplaceUses(Op, New.getNode());
  1918. CurDAG->RemoveDeadNode(Op);
  1919. }
  1920. void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
  1921. SDLoc dl(Op);
  1922. MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
  1923. const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
  1924. EVT VT = Op->getOperand(2).getValueType();
  1925. LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
  1926. Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty,
  1927. CurDAG->getMachineFunction());
  1928. SDValue New = CurDAG->getCopyToReg(
  1929. Op->getOperand(0), dl, Reg, Op->getOperand(2));
  1930. New->setNodeId(-1);
  1931. ReplaceUses(Op, New.getNode());
  1932. CurDAG->RemoveDeadNode(Op);
  1933. }
  1934. void SelectionDAGISel::Select_UNDEF(SDNode *N) {
  1935. CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
  1936. }
  1937. void SelectionDAGISel::Select_FREEZE(SDNode *N) {
  1938. // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
  1939. // If FREEZE instruction is added later, the code below must be changed as
  1940. // well.
  1941. CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
  1942. N->getOperand(0));
  1943. }
  1944. void SelectionDAGISel::Select_ARITH_FENCE(SDNode *N) {
  1945. CurDAG->SelectNodeTo(N, TargetOpcode::ARITH_FENCE, N->getValueType(0),
  1946. N->getOperand(0));
  1947. }
  1948. /// GetVBR - decode a vbr encoding whose top bit is set.
  1949. LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
  1950. GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
  1951. assert(Val >= 128 && "Not a VBR");
  1952. Val &= 127; // Remove first vbr bit.
  1953. unsigned Shift = 7;
  1954. uint64_t NextBits;
  1955. do {
  1956. NextBits = MatcherTable[Idx++];
  1957. Val |= (NextBits&127) << Shift;
  1958. Shift += 7;
  1959. } while (NextBits & 128);
  1960. return Val;
  1961. }
  1962. /// When a match is complete, this method updates uses of interior chain results
  1963. /// to use the new results.
  1964. void SelectionDAGISel::UpdateChains(
  1965. SDNode *NodeToMatch, SDValue InputChain,
  1966. SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
  1967. SmallVector<SDNode*, 4> NowDeadNodes;
  1968. // Now that all the normal results are replaced, we replace the chain and
  1969. // glue results if present.
  1970. if (!ChainNodesMatched.empty()) {
  1971. assert(InputChain.getNode() &&
  1972. "Matched input chains but didn't produce a chain");
  1973. // Loop over all of the nodes we matched that produced a chain result.
  1974. // Replace all the chain results with the final chain we ended up with.
  1975. for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
  1976. SDNode *ChainNode = ChainNodesMatched[i];
  1977. // If ChainNode is null, it's because we replaced it on a previous
  1978. // iteration and we cleared it out of the map. Just skip it.
  1979. if (!ChainNode)
  1980. continue;
  1981. assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
  1982. "Deleted node left in chain");
  1983. // Don't replace the results of the root node if we're doing a
  1984. // MorphNodeTo.
  1985. if (ChainNode == NodeToMatch && isMorphNodeTo)
  1986. continue;
  1987. SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
  1988. if (ChainVal.getValueType() == MVT::Glue)
  1989. ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
  1990. assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
  1991. SelectionDAG::DAGNodeDeletedListener NDL(
  1992. *CurDAG, [&](SDNode *N, SDNode *E) {
  1993. std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
  1994. static_cast<SDNode *>(nullptr));
  1995. });
  1996. if (ChainNode->getOpcode() != ISD::TokenFactor)
  1997. ReplaceUses(ChainVal, InputChain);
  1998. // If the node became dead and we haven't already seen it, delete it.
  1999. if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
  2000. !llvm::is_contained(NowDeadNodes, ChainNode))
  2001. NowDeadNodes.push_back(ChainNode);
  2002. }
  2003. }
  2004. if (!NowDeadNodes.empty())
  2005. CurDAG->RemoveDeadNodes(NowDeadNodes);
  2006. LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
  2007. }
  2008. /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
  2009. /// operation for when the pattern matched at least one node with a chains. The
  2010. /// input vector contains a list of all of the chained nodes that we match. We
  2011. /// must determine if this is a valid thing to cover (i.e. matching it won't
  2012. /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
  2013. /// be used as the input node chain for the generated nodes.
  2014. static SDValue
  2015. HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
  2016. SelectionDAG *CurDAG) {
  2017. SmallPtrSet<const SDNode *, 16> Visited;
  2018. SmallVector<const SDNode *, 8> Worklist;
  2019. SmallVector<SDValue, 3> InputChains;
  2020. unsigned int Max = 8192;
  2021. // Quick exit on trivial merge.
  2022. if (ChainNodesMatched.size() == 1)
  2023. return ChainNodesMatched[0]->getOperand(0);
  2024. // Add chains that aren't already added (internal). Peek through
  2025. // token factors.
  2026. std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
  2027. if (V.getValueType() != MVT::Other)
  2028. return;
  2029. if (V->getOpcode() == ISD::EntryToken)
  2030. return;
  2031. if (!Visited.insert(V.getNode()).second)
  2032. return;
  2033. if (V->getOpcode() == ISD::TokenFactor) {
  2034. for (const SDValue &Op : V->op_values())
  2035. AddChains(Op);
  2036. } else
  2037. InputChains.push_back(V);
  2038. };
  2039. for (auto *N : ChainNodesMatched) {
  2040. Worklist.push_back(N);
  2041. Visited.insert(N);
  2042. }
  2043. while (!Worklist.empty())
  2044. AddChains(Worklist.pop_back_val()->getOperand(0));
  2045. // Skip the search if there are no chain dependencies.
  2046. if (InputChains.size() == 0)
  2047. return CurDAG->getEntryNode();
  2048. // If one of these chains is a successor of input, we must have a
  2049. // node that is both the predecessor and successor of the
  2050. // to-be-merged nodes. Fail.
  2051. Visited.clear();
  2052. for (SDValue V : InputChains)
  2053. Worklist.push_back(V.getNode());
  2054. for (auto *N : ChainNodesMatched)
  2055. if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
  2056. return SDValue();
  2057. // Return merged chain.
  2058. if (InputChains.size() == 1)
  2059. return InputChains[0];
  2060. return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
  2061. MVT::Other, InputChains);
  2062. }
  2063. /// MorphNode - Handle morphing a node in place for the selector.
  2064. SDNode *SelectionDAGISel::
  2065. MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
  2066. ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
  2067. // It is possible we're using MorphNodeTo to replace a node with no
  2068. // normal results with one that has a normal result (or we could be
  2069. // adding a chain) and the input could have glue and chains as well.
  2070. // In this case we need to shift the operands down.
  2071. // FIXME: This is a horrible hack and broken in obscure cases, no worse
  2072. // than the old isel though.
  2073. int OldGlueResultNo = -1, OldChainResultNo = -1;
  2074. unsigned NTMNumResults = Node->getNumValues();
  2075. if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
  2076. OldGlueResultNo = NTMNumResults-1;
  2077. if (NTMNumResults != 1 &&
  2078. Node->getValueType(NTMNumResults-2) == MVT::Other)
  2079. OldChainResultNo = NTMNumResults-2;
  2080. } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
  2081. OldChainResultNo = NTMNumResults-1;
  2082. // Call the underlying SelectionDAG routine to do the transmogrification. Note
  2083. // that this deletes operands of the old node that become dead.
  2084. SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
  2085. // MorphNodeTo can operate in two ways: if an existing node with the
  2086. // specified operands exists, it can just return it. Otherwise, it
  2087. // updates the node in place to have the requested operands.
  2088. if (Res == Node) {
  2089. // If we updated the node in place, reset the node ID. To the isel,
  2090. // this should be just like a newly allocated machine node.
  2091. Res->setNodeId(-1);
  2092. }
  2093. unsigned ResNumResults = Res->getNumValues();
  2094. // Move the glue if needed.
  2095. if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
  2096. (unsigned)OldGlueResultNo != ResNumResults-1)
  2097. ReplaceUses(SDValue(Node, OldGlueResultNo),
  2098. SDValue(Res, ResNumResults - 1));
  2099. if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
  2100. --ResNumResults;
  2101. // Move the chain reference if needed.
  2102. if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
  2103. (unsigned)OldChainResultNo != ResNumResults-1)
  2104. ReplaceUses(SDValue(Node, OldChainResultNo),
  2105. SDValue(Res, ResNumResults - 1));
  2106. // Otherwise, no replacement happened because the node already exists. Replace
  2107. // Uses of the old node with the new one.
  2108. if (Res != Node) {
  2109. ReplaceNode(Node, Res);
  2110. } else {
  2111. EnforceNodeIdInvariant(Res);
  2112. }
  2113. return Res;
  2114. }
  2115. /// CheckSame - Implements OP_CheckSame.
  2116. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2117. CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
  2118. const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
  2119. // Accept if it is exactly the same as a previously recorded node.
  2120. unsigned RecNo = MatcherTable[MatcherIndex++];
  2121. assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
  2122. return N == RecordedNodes[RecNo].first;
  2123. }
  2124. /// CheckChildSame - Implements OP_CheckChildXSame.
  2125. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool CheckChildSame(
  2126. const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
  2127. const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
  2128. unsigned ChildNo) {
  2129. if (ChildNo >= N.getNumOperands())
  2130. return false; // Match fails if out of range child #.
  2131. return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
  2132. RecordedNodes);
  2133. }
  2134. /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
  2135. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2136. CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2137. const SelectionDAGISel &SDISel) {
  2138. return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
  2139. }
  2140. /// CheckNodePredicate - Implements OP_CheckNodePredicate.
  2141. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2142. CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2143. const SelectionDAGISel &SDISel, SDNode *N) {
  2144. return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
  2145. }
  2146. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2147. CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2148. SDNode *N) {
  2149. uint16_t Opc = MatcherTable[MatcherIndex++];
  2150. Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
  2151. return N->getOpcode() == Opc;
  2152. }
  2153. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2154. CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
  2155. const TargetLowering *TLI, const DataLayout &DL) {
  2156. MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2157. if (N.getValueType() == VT) return true;
  2158. // Handle the case when VT is iPTR.
  2159. return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
  2160. }
  2161. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2162. CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2163. SDValue N, const TargetLowering *TLI, const DataLayout &DL,
  2164. unsigned ChildNo) {
  2165. if (ChildNo >= N.getNumOperands())
  2166. return false; // Match fails if out of range child #.
  2167. return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
  2168. DL);
  2169. }
  2170. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2171. CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2172. SDValue N) {
  2173. return cast<CondCodeSDNode>(N)->get() ==
  2174. (ISD::CondCode)MatcherTable[MatcherIndex++];
  2175. }
  2176. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2177. CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2178. SDValue N) {
  2179. if (2 >= N.getNumOperands())
  2180. return false;
  2181. return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
  2182. }
  2183. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2184. CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2185. SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
  2186. MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2187. if (cast<VTSDNode>(N)->getVT() == VT)
  2188. return true;
  2189. // Handle the case when VT is iPTR.
  2190. return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
  2191. }
  2192. // Bit 0 stores the sign of the immediate. The upper bits contain the magnitude
  2193. // shifted left by 1.
  2194. static uint64_t decodeSignRotatedValue(uint64_t V) {
  2195. if ((V & 1) == 0)
  2196. return V >> 1;
  2197. if (V != 1)
  2198. return -(V >> 1);
  2199. // There is no such thing as -0 with integers. "-0" really means MININT.
  2200. return 1ULL << 63;
  2201. }
  2202. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2203. CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2204. SDValue N) {
  2205. int64_t Val = MatcherTable[MatcherIndex++];
  2206. if (Val & 128)
  2207. Val = GetVBR(Val, MatcherTable, MatcherIndex);
  2208. Val = decodeSignRotatedValue(Val);
  2209. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
  2210. return C && C->getSExtValue() == Val;
  2211. }
  2212. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2213. CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2214. SDValue N, unsigned ChildNo) {
  2215. if (ChildNo >= N.getNumOperands())
  2216. return false; // Match fails if out of range child #.
  2217. return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
  2218. }
  2219. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2220. CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
  2221. SDValue N, const SelectionDAGISel &SDISel) {
  2222. int64_t Val = MatcherTable[MatcherIndex++];
  2223. if (Val & 128)
  2224. Val = GetVBR(Val, MatcherTable, MatcherIndex);
  2225. if (N->getOpcode() != ISD::AND) return false;
  2226. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  2227. return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
  2228. }
  2229. LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
  2230. CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
  2231. const SelectionDAGISel &SDISel) {
  2232. int64_t Val = MatcherTable[MatcherIndex++];
  2233. if (Val & 128)
  2234. Val = GetVBR(Val, MatcherTable, MatcherIndex);
  2235. if (N->getOpcode() != ISD::OR) return false;
  2236. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  2237. return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
  2238. }
  2239. /// IsPredicateKnownToFail - If we know how and can do so without pushing a
  2240. /// scope, evaluate the current node. If the current predicate is known to
  2241. /// fail, set Result=true and return anything. If the current predicate is
  2242. /// known to pass, set Result=false and return the MatcherIndex to continue
  2243. /// with. If the current predicate is unknown, set Result=false and return the
  2244. /// MatcherIndex to continue with.
  2245. static unsigned IsPredicateKnownToFail(const unsigned char *Table,
  2246. unsigned Index, SDValue N,
  2247. bool &Result,
  2248. const SelectionDAGISel &SDISel,
  2249. SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
  2250. switch (Table[Index++]) {
  2251. default:
  2252. Result = false;
  2253. return Index-1; // Could not evaluate this predicate.
  2254. case SelectionDAGISel::OPC_CheckSame:
  2255. Result = !::CheckSame(Table, Index, N, RecordedNodes);
  2256. return Index;
  2257. case SelectionDAGISel::OPC_CheckChild0Same:
  2258. case SelectionDAGISel::OPC_CheckChild1Same:
  2259. case SelectionDAGISel::OPC_CheckChild2Same:
  2260. case SelectionDAGISel::OPC_CheckChild3Same:
  2261. Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
  2262. Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
  2263. return Index;
  2264. case SelectionDAGISel::OPC_CheckPatternPredicate:
  2265. Result = !::CheckPatternPredicate(Table, Index, SDISel);
  2266. return Index;
  2267. case SelectionDAGISel::OPC_CheckPredicate:
  2268. Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
  2269. return Index;
  2270. case SelectionDAGISel::OPC_CheckOpcode:
  2271. Result = !::CheckOpcode(Table, Index, N.getNode());
  2272. return Index;
  2273. case SelectionDAGISel::OPC_CheckType:
  2274. Result = !::CheckType(Table, Index, N, SDISel.TLI,
  2275. SDISel.CurDAG->getDataLayout());
  2276. return Index;
  2277. case SelectionDAGISel::OPC_CheckTypeRes: {
  2278. unsigned Res = Table[Index++];
  2279. Result = !::CheckType(Table, Index, N.getValue(Res), SDISel.TLI,
  2280. SDISel.CurDAG->getDataLayout());
  2281. return Index;
  2282. }
  2283. case SelectionDAGISel::OPC_CheckChild0Type:
  2284. case SelectionDAGISel::OPC_CheckChild1Type:
  2285. case SelectionDAGISel::OPC_CheckChild2Type:
  2286. case SelectionDAGISel::OPC_CheckChild3Type:
  2287. case SelectionDAGISel::OPC_CheckChild4Type:
  2288. case SelectionDAGISel::OPC_CheckChild5Type:
  2289. case SelectionDAGISel::OPC_CheckChild6Type:
  2290. case SelectionDAGISel::OPC_CheckChild7Type:
  2291. Result = !::CheckChildType(
  2292. Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
  2293. Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type);
  2294. return Index;
  2295. case SelectionDAGISel::OPC_CheckCondCode:
  2296. Result = !::CheckCondCode(Table, Index, N);
  2297. return Index;
  2298. case SelectionDAGISel::OPC_CheckChild2CondCode:
  2299. Result = !::CheckChild2CondCode(Table, Index, N);
  2300. return Index;
  2301. case SelectionDAGISel::OPC_CheckValueType:
  2302. Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
  2303. SDISel.CurDAG->getDataLayout());
  2304. return Index;
  2305. case SelectionDAGISel::OPC_CheckInteger:
  2306. Result = !::CheckInteger(Table, Index, N);
  2307. return Index;
  2308. case SelectionDAGISel::OPC_CheckChild0Integer:
  2309. case SelectionDAGISel::OPC_CheckChild1Integer:
  2310. case SelectionDAGISel::OPC_CheckChild2Integer:
  2311. case SelectionDAGISel::OPC_CheckChild3Integer:
  2312. case SelectionDAGISel::OPC_CheckChild4Integer:
  2313. Result = !::CheckChildInteger(Table, Index, N,
  2314. Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
  2315. return Index;
  2316. case SelectionDAGISel::OPC_CheckAndImm:
  2317. Result = !::CheckAndImm(Table, Index, N, SDISel);
  2318. return Index;
  2319. case SelectionDAGISel::OPC_CheckOrImm:
  2320. Result = !::CheckOrImm(Table, Index, N, SDISel);
  2321. return Index;
  2322. }
  2323. }
  2324. namespace {
  2325. struct MatchScope {
  2326. /// FailIndex - If this match fails, this is the index to continue with.
  2327. unsigned FailIndex;
  2328. /// NodeStack - The node stack when the scope was formed.
  2329. SmallVector<SDValue, 4> NodeStack;
  2330. /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
  2331. unsigned NumRecordedNodes;
  2332. /// NumMatchedMemRefs - The number of matched memref entries.
  2333. unsigned NumMatchedMemRefs;
  2334. /// InputChain/InputGlue - The current chain/glue
  2335. SDValue InputChain, InputGlue;
  2336. /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
  2337. bool HasChainNodesMatched;
  2338. };
  2339. /// \A DAG update listener to keep the matching state
  2340. /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
  2341. /// change the DAG while matching. X86 addressing mode matcher is an example
  2342. /// for this.
  2343. class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
  2344. {
  2345. SDNode **NodeToMatch;
  2346. SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
  2347. SmallVectorImpl<MatchScope> &MatchScopes;
  2348. public:
  2349. MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
  2350. SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
  2351. SmallVectorImpl<MatchScope> &MS)
  2352. : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
  2353. RecordedNodes(RN), MatchScopes(MS) {}
  2354. void NodeDeleted(SDNode *N, SDNode *E) override {
  2355. // Some early-returns here to avoid the search if we deleted the node or
  2356. // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
  2357. // do, so it's unnecessary to update matching state at that point).
  2358. // Neither of these can occur currently because we only install this
  2359. // update listener during matching a complex patterns.
  2360. if (!E || E->isMachineOpcode())
  2361. return;
  2362. // Check if NodeToMatch was updated.
  2363. if (N == *NodeToMatch)
  2364. *NodeToMatch = E;
  2365. // Performing linear search here does not matter because we almost never
  2366. // run this code. You'd have to have a CSE during complex pattern
  2367. // matching.
  2368. for (auto &I : RecordedNodes)
  2369. if (I.first.getNode() == N)
  2370. I.first.setNode(E);
  2371. for (auto &I : MatchScopes)
  2372. for (auto &J : I.NodeStack)
  2373. if (J.getNode() == N)
  2374. J.setNode(E);
  2375. }
  2376. };
  2377. } // end anonymous namespace
  2378. void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch,
  2379. const unsigned char *MatcherTable,
  2380. unsigned TableSize) {
  2381. // FIXME: Should these even be selected? Handle these cases in the caller?
  2382. switch (NodeToMatch->getOpcode()) {
  2383. default:
  2384. break;
  2385. case ISD::EntryToken: // These nodes remain the same.
  2386. case ISD::BasicBlock:
  2387. case ISD::Register:
  2388. case ISD::RegisterMask:
  2389. case ISD::HANDLENODE:
  2390. case ISD::MDNODE_SDNODE:
  2391. case ISD::TargetConstant:
  2392. case ISD::TargetConstantFP:
  2393. case ISD::TargetConstantPool:
  2394. case ISD::TargetFrameIndex:
  2395. case ISD::TargetExternalSymbol:
  2396. case ISD::MCSymbol:
  2397. case ISD::TargetBlockAddress:
  2398. case ISD::TargetJumpTable:
  2399. case ISD::TargetGlobalTLSAddress:
  2400. case ISD::TargetGlobalAddress:
  2401. case ISD::TokenFactor:
  2402. case ISD::CopyFromReg:
  2403. case ISD::CopyToReg:
  2404. case ISD::EH_LABEL:
  2405. case ISD::ANNOTATION_LABEL:
  2406. case ISD::LIFETIME_START:
  2407. case ISD::LIFETIME_END:
  2408. case ISD::PSEUDO_PROBE:
  2409. NodeToMatch->setNodeId(-1); // Mark selected.
  2410. return;
  2411. case ISD::AssertSext:
  2412. case ISD::AssertZext:
  2413. case ISD::AssertAlign:
  2414. ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
  2415. CurDAG->RemoveDeadNode(NodeToMatch);
  2416. return;
  2417. case ISD::INLINEASM:
  2418. case ISD::INLINEASM_BR:
  2419. Select_INLINEASM(NodeToMatch);
  2420. return;
  2421. case ISD::READ_REGISTER:
  2422. Select_READ_REGISTER(NodeToMatch);
  2423. return;
  2424. case ISD::WRITE_REGISTER:
  2425. Select_WRITE_REGISTER(NodeToMatch);
  2426. return;
  2427. case ISD::UNDEF:
  2428. Select_UNDEF(NodeToMatch);
  2429. return;
  2430. case ISD::FREEZE:
  2431. Select_FREEZE(NodeToMatch);
  2432. return;
  2433. case ISD::ARITH_FENCE:
  2434. Select_ARITH_FENCE(NodeToMatch);
  2435. return;
  2436. }
  2437. assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
  2438. // Set up the node stack with NodeToMatch as the only node on the stack.
  2439. SmallVector<SDValue, 8> NodeStack;
  2440. SDValue N = SDValue(NodeToMatch, 0);
  2441. NodeStack.push_back(N);
  2442. // MatchScopes - Scopes used when matching, if a match failure happens, this
  2443. // indicates where to continue checking.
  2444. SmallVector<MatchScope, 8> MatchScopes;
  2445. // RecordedNodes - This is the set of nodes that have been recorded by the
  2446. // state machine. The second value is the parent of the node, or null if the
  2447. // root is recorded.
  2448. SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
  2449. // MatchedMemRefs - This is the set of MemRef's we've seen in the input
  2450. // pattern.
  2451. SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
  2452. // These are the current input chain and glue for use when generating nodes.
  2453. // Various Emit operations change these. For example, emitting a copytoreg
  2454. // uses and updates these.
  2455. SDValue InputChain, InputGlue;
  2456. // ChainNodesMatched - If a pattern matches nodes that have input/output
  2457. // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
  2458. // which ones they are. The result is captured into this list so that we can
  2459. // update the chain results when the pattern is complete.
  2460. SmallVector<SDNode*, 3> ChainNodesMatched;
  2461. LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
  2462. // Determine where to start the interpreter. Normally we start at opcode #0,
  2463. // but if the state machine starts with an OPC_SwitchOpcode, then we
  2464. // accelerate the first lookup (which is guaranteed to be hot) with the
  2465. // OpcodeOffset table.
  2466. unsigned MatcherIndex = 0;
  2467. if (!OpcodeOffset.empty()) {
  2468. // Already computed the OpcodeOffset table, just index into it.
  2469. if (N.getOpcode() < OpcodeOffset.size())
  2470. MatcherIndex = OpcodeOffset[N.getOpcode()];
  2471. LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
  2472. } else if (MatcherTable[0] == OPC_SwitchOpcode) {
  2473. // Otherwise, the table isn't computed, but the state machine does start
  2474. // with an OPC_SwitchOpcode instruction. Populate the table now, since this
  2475. // is the first time we're selecting an instruction.
  2476. unsigned Idx = 1;
  2477. while (true) {
  2478. // Get the size of this case.
  2479. unsigned CaseSize = MatcherTable[Idx++];
  2480. if (CaseSize & 128)
  2481. CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
  2482. if (CaseSize == 0) break;
  2483. // Get the opcode, add the index to the table.
  2484. uint16_t Opc = MatcherTable[Idx++];
  2485. Opc |= (unsigned short)MatcherTable[Idx++] << 8;
  2486. if (Opc >= OpcodeOffset.size())
  2487. OpcodeOffset.resize((Opc+1)*2);
  2488. OpcodeOffset[Opc] = Idx;
  2489. Idx += CaseSize;
  2490. }
  2491. // Okay, do the lookup for the first opcode.
  2492. if (N.getOpcode() < OpcodeOffset.size())
  2493. MatcherIndex = OpcodeOffset[N.getOpcode()];
  2494. }
  2495. while (true) {
  2496. assert(MatcherIndex < TableSize && "Invalid index");
  2497. #ifndef NDEBUG
  2498. unsigned CurrentOpcodeIndex = MatcherIndex;
  2499. #endif
  2500. BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
  2501. switch (Opcode) {
  2502. case OPC_Scope: {
  2503. // Okay, the semantics of this operation are that we should push a scope
  2504. // then evaluate the first child. However, pushing a scope only to have
  2505. // the first check fail (which then pops it) is inefficient. If we can
  2506. // determine immediately that the first check (or first several) will
  2507. // immediately fail, don't even bother pushing a scope for them.
  2508. unsigned FailIndex;
  2509. while (true) {
  2510. unsigned NumToSkip = MatcherTable[MatcherIndex++];
  2511. if (NumToSkip & 128)
  2512. NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
  2513. // Found the end of the scope with no match.
  2514. if (NumToSkip == 0) {
  2515. FailIndex = 0;
  2516. break;
  2517. }
  2518. FailIndex = MatcherIndex+NumToSkip;
  2519. unsigned MatcherIndexOfPredicate = MatcherIndex;
  2520. (void)MatcherIndexOfPredicate; // silence warning.
  2521. // If we can't evaluate this predicate without pushing a scope (e.g. if
  2522. // it is a 'MoveParent') or if the predicate succeeds on this node, we
  2523. // push the scope and evaluate the full predicate chain.
  2524. bool Result;
  2525. MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
  2526. Result, *this, RecordedNodes);
  2527. if (!Result)
  2528. break;
  2529. LLVM_DEBUG(
  2530. dbgs() << " Skipped scope entry (due to false predicate) at "
  2531. << "index " << MatcherIndexOfPredicate << ", continuing at "
  2532. << FailIndex << "\n");
  2533. ++NumDAGIselRetries;
  2534. // Otherwise, we know that this case of the Scope is guaranteed to fail,
  2535. // move to the next case.
  2536. MatcherIndex = FailIndex;
  2537. }
  2538. // If the whole scope failed to match, bail.
  2539. if (FailIndex == 0) break;
  2540. // Push a MatchScope which indicates where to go if the first child fails
  2541. // to match.
  2542. MatchScope NewEntry;
  2543. NewEntry.FailIndex = FailIndex;
  2544. NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
  2545. NewEntry.NumRecordedNodes = RecordedNodes.size();
  2546. NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
  2547. NewEntry.InputChain = InputChain;
  2548. NewEntry.InputGlue = InputGlue;
  2549. NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
  2550. MatchScopes.push_back(NewEntry);
  2551. continue;
  2552. }
  2553. case OPC_RecordNode: {
  2554. // Remember this node, it may end up being an operand in the pattern.
  2555. SDNode *Parent = nullptr;
  2556. if (NodeStack.size() > 1)
  2557. Parent = NodeStack[NodeStack.size()-2].getNode();
  2558. RecordedNodes.push_back(std::make_pair(N, Parent));
  2559. continue;
  2560. }
  2561. case OPC_RecordChild0: case OPC_RecordChild1:
  2562. case OPC_RecordChild2: case OPC_RecordChild3:
  2563. case OPC_RecordChild4: case OPC_RecordChild5:
  2564. case OPC_RecordChild6: case OPC_RecordChild7: {
  2565. unsigned ChildNo = Opcode-OPC_RecordChild0;
  2566. if (ChildNo >= N.getNumOperands())
  2567. break; // Match fails if out of range child #.
  2568. RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
  2569. N.getNode()));
  2570. continue;
  2571. }
  2572. case OPC_RecordMemRef:
  2573. if (auto *MN = dyn_cast<MemSDNode>(N))
  2574. MatchedMemRefs.push_back(MN->getMemOperand());
  2575. else {
  2576. LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
  2577. dbgs() << '\n');
  2578. }
  2579. continue;
  2580. case OPC_CaptureGlueInput:
  2581. // If the current node has an input glue, capture it in InputGlue.
  2582. if (N->getNumOperands() != 0 &&
  2583. N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
  2584. InputGlue = N->getOperand(N->getNumOperands()-1);
  2585. continue;
  2586. case OPC_MoveChild: {
  2587. unsigned ChildNo = MatcherTable[MatcherIndex++];
  2588. if (ChildNo >= N.getNumOperands())
  2589. break; // Match fails if out of range child #.
  2590. N = N.getOperand(ChildNo);
  2591. NodeStack.push_back(N);
  2592. continue;
  2593. }
  2594. case OPC_MoveChild0: case OPC_MoveChild1:
  2595. case OPC_MoveChild2: case OPC_MoveChild3:
  2596. case OPC_MoveChild4: case OPC_MoveChild5:
  2597. case OPC_MoveChild6: case OPC_MoveChild7: {
  2598. unsigned ChildNo = Opcode-OPC_MoveChild0;
  2599. if (ChildNo >= N.getNumOperands())
  2600. break; // Match fails if out of range child #.
  2601. N = N.getOperand(ChildNo);
  2602. NodeStack.push_back(N);
  2603. continue;
  2604. }
  2605. case OPC_MoveParent:
  2606. // Pop the current node off the NodeStack.
  2607. NodeStack.pop_back();
  2608. assert(!NodeStack.empty() && "Node stack imbalance!");
  2609. N = NodeStack.back();
  2610. continue;
  2611. case OPC_CheckSame:
  2612. if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
  2613. continue;
  2614. case OPC_CheckChild0Same: case OPC_CheckChild1Same:
  2615. case OPC_CheckChild2Same: case OPC_CheckChild3Same:
  2616. if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
  2617. Opcode-OPC_CheckChild0Same))
  2618. break;
  2619. continue;
  2620. case OPC_CheckPatternPredicate:
  2621. if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
  2622. continue;
  2623. case OPC_CheckPredicate:
  2624. if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
  2625. N.getNode()))
  2626. break;
  2627. continue;
  2628. case OPC_CheckPredicateWithOperands: {
  2629. unsigned OpNum = MatcherTable[MatcherIndex++];
  2630. SmallVector<SDValue, 8> Operands;
  2631. for (unsigned i = 0; i < OpNum; ++i)
  2632. Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
  2633. unsigned PredNo = MatcherTable[MatcherIndex++];
  2634. if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands))
  2635. break;
  2636. continue;
  2637. }
  2638. case OPC_CheckComplexPat: {
  2639. unsigned CPNum = MatcherTable[MatcherIndex++];
  2640. unsigned RecNo = MatcherTable[MatcherIndex++];
  2641. assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
  2642. // If target can modify DAG during matching, keep the matching state
  2643. // consistent.
  2644. std::unique_ptr<MatchStateUpdater> MSU;
  2645. if (ComplexPatternFuncMutatesDAG())
  2646. MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
  2647. MatchScopes));
  2648. if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
  2649. RecordedNodes[RecNo].first, CPNum,
  2650. RecordedNodes))
  2651. break;
  2652. continue;
  2653. }
  2654. case OPC_CheckOpcode:
  2655. if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
  2656. continue;
  2657. case OPC_CheckType:
  2658. if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
  2659. CurDAG->getDataLayout()))
  2660. break;
  2661. continue;
  2662. case OPC_CheckTypeRes: {
  2663. unsigned Res = MatcherTable[MatcherIndex++];
  2664. if (!::CheckType(MatcherTable, MatcherIndex, N.getValue(Res), TLI,
  2665. CurDAG->getDataLayout()))
  2666. break;
  2667. continue;
  2668. }
  2669. case OPC_SwitchOpcode: {
  2670. unsigned CurNodeOpcode = N.getOpcode();
  2671. unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
  2672. unsigned CaseSize;
  2673. while (true) {
  2674. // Get the size of this case.
  2675. CaseSize = MatcherTable[MatcherIndex++];
  2676. if (CaseSize & 128)
  2677. CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
  2678. if (CaseSize == 0) break;
  2679. uint16_t Opc = MatcherTable[MatcherIndex++];
  2680. Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
  2681. // If the opcode matches, then we will execute this case.
  2682. if (CurNodeOpcode == Opc)
  2683. break;
  2684. // Otherwise, skip over this case.
  2685. MatcherIndex += CaseSize;
  2686. }
  2687. // If no cases matched, bail out.
  2688. if (CaseSize == 0) break;
  2689. // Otherwise, execute the case we found.
  2690. LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to "
  2691. << MatcherIndex << "\n");
  2692. continue;
  2693. }
  2694. case OPC_SwitchType: {
  2695. MVT CurNodeVT = N.getSimpleValueType();
  2696. unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
  2697. unsigned CaseSize;
  2698. while (true) {
  2699. // Get the size of this case.
  2700. CaseSize = MatcherTable[MatcherIndex++];
  2701. if (CaseSize & 128)
  2702. CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
  2703. if (CaseSize == 0) break;
  2704. MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2705. if (CaseVT == MVT::iPTR)
  2706. CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
  2707. // If the VT matches, then we will execute this case.
  2708. if (CurNodeVT == CaseVT)
  2709. break;
  2710. // Otherwise, skip over this case.
  2711. MatcherIndex += CaseSize;
  2712. }
  2713. // If no cases matched, bail out.
  2714. if (CaseSize == 0) break;
  2715. // Otherwise, execute the case we found.
  2716. LLVM_DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
  2717. << "] from " << SwitchStart << " to " << MatcherIndex
  2718. << '\n');
  2719. continue;
  2720. }
  2721. case OPC_CheckChild0Type: case OPC_CheckChild1Type:
  2722. case OPC_CheckChild2Type: case OPC_CheckChild3Type:
  2723. case OPC_CheckChild4Type: case OPC_CheckChild5Type:
  2724. case OPC_CheckChild6Type: case OPC_CheckChild7Type:
  2725. if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
  2726. CurDAG->getDataLayout(),
  2727. Opcode - OPC_CheckChild0Type))
  2728. break;
  2729. continue;
  2730. case OPC_CheckCondCode:
  2731. if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
  2732. continue;
  2733. case OPC_CheckChild2CondCode:
  2734. if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
  2735. continue;
  2736. case OPC_CheckValueType:
  2737. if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
  2738. CurDAG->getDataLayout()))
  2739. break;
  2740. continue;
  2741. case OPC_CheckInteger:
  2742. if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
  2743. continue;
  2744. case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
  2745. case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
  2746. case OPC_CheckChild4Integer:
  2747. if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
  2748. Opcode-OPC_CheckChild0Integer)) break;
  2749. continue;
  2750. case OPC_CheckAndImm:
  2751. if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
  2752. continue;
  2753. case OPC_CheckOrImm:
  2754. if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
  2755. continue;
  2756. case OPC_CheckImmAllOnesV:
  2757. if (!ISD::isConstantSplatVectorAllOnes(N.getNode()))
  2758. break;
  2759. continue;
  2760. case OPC_CheckImmAllZerosV:
  2761. if (!ISD::isConstantSplatVectorAllZeros(N.getNode()))
  2762. break;
  2763. continue;
  2764. case OPC_CheckFoldableChainNode: {
  2765. assert(NodeStack.size() != 1 && "No parent node");
  2766. // Verify that all intermediate nodes between the root and this one have
  2767. // a single use (ignoring chains, which are handled in UpdateChains).
  2768. bool HasMultipleUses = false;
  2769. for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
  2770. unsigned NNonChainUses = 0;
  2771. SDNode *NS = NodeStack[i].getNode();
  2772. for (auto UI = NS->use_begin(), UE = NS->use_end(); UI != UE; ++UI)
  2773. if (UI.getUse().getValueType() != MVT::Other)
  2774. if (++NNonChainUses > 1) {
  2775. HasMultipleUses = true;
  2776. break;
  2777. }
  2778. if (HasMultipleUses) break;
  2779. }
  2780. if (HasMultipleUses) break;
  2781. // Check to see that the target thinks this is profitable to fold and that
  2782. // we can fold it without inducing cycles in the graph.
  2783. if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
  2784. NodeToMatch) ||
  2785. !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
  2786. NodeToMatch, OptLevel,
  2787. true/*We validate our own chains*/))
  2788. break;
  2789. continue;
  2790. }
  2791. case OPC_EmitInteger:
  2792. case OPC_EmitStringInteger: {
  2793. MVT::SimpleValueType VT =
  2794. (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2795. int64_t Val = MatcherTable[MatcherIndex++];
  2796. if (Val & 128)
  2797. Val = GetVBR(Val, MatcherTable, MatcherIndex);
  2798. if (Opcode == OPC_EmitInteger)
  2799. Val = decodeSignRotatedValue(Val);
  2800. RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
  2801. CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
  2802. VT), nullptr));
  2803. continue;
  2804. }
  2805. case OPC_EmitRegister: {
  2806. MVT::SimpleValueType VT =
  2807. (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2808. unsigned RegNo = MatcherTable[MatcherIndex++];
  2809. RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
  2810. CurDAG->getRegister(RegNo, VT), nullptr));
  2811. continue;
  2812. }
  2813. case OPC_EmitRegister2: {
  2814. // For targets w/ more than 256 register names, the register enum
  2815. // values are stored in two bytes in the matcher table (just like
  2816. // opcodes).
  2817. MVT::SimpleValueType VT =
  2818. (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2819. unsigned RegNo = MatcherTable[MatcherIndex++];
  2820. RegNo |= MatcherTable[MatcherIndex++] << 8;
  2821. RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
  2822. CurDAG->getRegister(RegNo, VT), nullptr));
  2823. continue;
  2824. }
  2825. case OPC_EmitConvertToTarget: {
  2826. // Convert from IMM/FPIMM to target version.
  2827. unsigned RecNo = MatcherTable[MatcherIndex++];
  2828. assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
  2829. SDValue Imm = RecordedNodes[RecNo].first;
  2830. if (Imm->getOpcode() == ISD::Constant) {
  2831. const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
  2832. Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
  2833. Imm.getValueType());
  2834. } else if (Imm->getOpcode() == ISD::ConstantFP) {
  2835. const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
  2836. Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
  2837. Imm.getValueType());
  2838. }
  2839. RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
  2840. continue;
  2841. }
  2842. case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
  2843. case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
  2844. case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
  2845. // These are space-optimized forms of OPC_EmitMergeInputChains.
  2846. assert(!InputChain.getNode() &&
  2847. "EmitMergeInputChains should be the first chain producing node");
  2848. assert(ChainNodesMatched.empty() &&
  2849. "Should only have one EmitMergeInputChains per match");
  2850. // Read all of the chained nodes.
  2851. unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
  2852. assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
  2853. ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
  2854. // FIXME: What if other value results of the node have uses not matched
  2855. // by this pattern?
  2856. if (ChainNodesMatched.back() != NodeToMatch &&
  2857. !RecordedNodes[RecNo].first.hasOneUse()) {
  2858. ChainNodesMatched.clear();
  2859. break;
  2860. }
  2861. // Merge the input chains if they are not intra-pattern references.
  2862. InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
  2863. if (!InputChain.getNode())
  2864. break; // Failed to merge.
  2865. continue;
  2866. }
  2867. case OPC_EmitMergeInputChains: {
  2868. assert(!InputChain.getNode() &&
  2869. "EmitMergeInputChains should be the first chain producing node");
  2870. // This node gets a list of nodes we matched in the input that have
  2871. // chains. We want to token factor all of the input chains to these nodes
  2872. // together. However, if any of the input chains is actually one of the
  2873. // nodes matched in this pattern, then we have an intra-match reference.
  2874. // Ignore these because the newly token factored chain should not refer to
  2875. // the old nodes.
  2876. unsigned NumChains = MatcherTable[MatcherIndex++];
  2877. assert(NumChains != 0 && "Can't TF zero chains");
  2878. assert(ChainNodesMatched.empty() &&
  2879. "Should only have one EmitMergeInputChains per match");
  2880. // Read all of the chained nodes.
  2881. for (unsigned i = 0; i != NumChains; ++i) {
  2882. unsigned RecNo = MatcherTable[MatcherIndex++];
  2883. assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
  2884. ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
  2885. // FIXME: What if other value results of the node have uses not matched
  2886. // by this pattern?
  2887. if (ChainNodesMatched.back() != NodeToMatch &&
  2888. !RecordedNodes[RecNo].first.hasOneUse()) {
  2889. ChainNodesMatched.clear();
  2890. break;
  2891. }
  2892. }
  2893. // If the inner loop broke out, the match fails.
  2894. if (ChainNodesMatched.empty())
  2895. break;
  2896. // Merge the input chains if they are not intra-pattern references.
  2897. InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
  2898. if (!InputChain.getNode())
  2899. break; // Failed to merge.
  2900. continue;
  2901. }
  2902. case OPC_EmitCopyToReg:
  2903. case OPC_EmitCopyToReg2: {
  2904. unsigned RecNo = MatcherTable[MatcherIndex++];
  2905. assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
  2906. unsigned DestPhysReg = MatcherTable[MatcherIndex++];
  2907. if (Opcode == OPC_EmitCopyToReg2)
  2908. DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
  2909. if (!InputChain.getNode())
  2910. InputChain = CurDAG->getEntryNode();
  2911. InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
  2912. DestPhysReg, RecordedNodes[RecNo].first,
  2913. InputGlue);
  2914. InputGlue = InputChain.getValue(1);
  2915. continue;
  2916. }
  2917. case OPC_EmitNodeXForm: {
  2918. unsigned XFormNo = MatcherTable[MatcherIndex++];
  2919. unsigned RecNo = MatcherTable[MatcherIndex++];
  2920. assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
  2921. SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
  2922. RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
  2923. continue;
  2924. }
  2925. case OPC_Coverage: {
  2926. // This is emitted right before MorphNode/EmitNode.
  2927. // So it should be safe to assume that this node has been selected
  2928. unsigned index = MatcherTable[MatcherIndex++];
  2929. index |= (MatcherTable[MatcherIndex++] << 8);
  2930. dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
  2931. dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
  2932. continue;
  2933. }
  2934. case OPC_EmitNode: case OPC_MorphNodeTo:
  2935. case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2:
  2936. case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: {
  2937. uint16_t TargetOpc = MatcherTable[MatcherIndex++];
  2938. TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
  2939. unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
  2940. // Get the result VT list.
  2941. unsigned NumVTs;
  2942. // If this is one of the compressed forms, get the number of VTs based
  2943. // on the Opcode. Otherwise read the next byte from the table.
  2944. if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
  2945. NumVTs = Opcode - OPC_MorphNodeTo0;
  2946. else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
  2947. NumVTs = Opcode - OPC_EmitNode0;
  2948. else
  2949. NumVTs = MatcherTable[MatcherIndex++];
  2950. SmallVector<EVT, 4> VTs;
  2951. for (unsigned i = 0; i != NumVTs; ++i) {
  2952. MVT::SimpleValueType VT =
  2953. (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
  2954. if (VT == MVT::iPTR)
  2955. VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
  2956. VTs.push_back(VT);
  2957. }
  2958. if (EmitNodeInfo & OPFL_Chain)
  2959. VTs.push_back(MVT::Other);
  2960. if (EmitNodeInfo & OPFL_GlueOutput)
  2961. VTs.push_back(MVT::Glue);
  2962. // This is hot code, so optimize the two most common cases of 1 and 2
  2963. // results.
  2964. SDVTList VTList;
  2965. if (VTs.size() == 1)
  2966. VTList = CurDAG->getVTList(VTs[0]);
  2967. else if (VTs.size() == 2)
  2968. VTList = CurDAG->getVTList(VTs[0], VTs[1]);
  2969. else
  2970. VTList = CurDAG->getVTList(VTs);
  2971. // Get the operand list.
  2972. unsigned NumOps = MatcherTable[MatcherIndex++];
  2973. SmallVector<SDValue, 8> Ops;
  2974. for (unsigned i = 0; i != NumOps; ++i) {
  2975. unsigned RecNo = MatcherTable[MatcherIndex++];
  2976. if (RecNo & 128)
  2977. RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
  2978. assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
  2979. Ops.push_back(RecordedNodes[RecNo].first);
  2980. }
  2981. // If there are variadic operands to add, handle them now.
  2982. if (EmitNodeInfo & OPFL_VariadicInfo) {
  2983. // Determine the start index to copy from.
  2984. unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
  2985. FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
  2986. assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
  2987. "Invalid variadic node");
  2988. // Copy all of the variadic operands, not including a potential glue
  2989. // input.
  2990. for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
  2991. i != e; ++i) {
  2992. SDValue V = NodeToMatch->getOperand(i);
  2993. if (V.getValueType() == MVT::Glue) break;
  2994. Ops.push_back(V);
  2995. }
  2996. }
  2997. // If this has chain/glue inputs, add them.
  2998. if (EmitNodeInfo & OPFL_Chain)
  2999. Ops.push_back(InputChain);
  3000. if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
  3001. Ops.push_back(InputGlue);
  3002. // Check whether any matched node could raise an FP exception. Since all
  3003. // such nodes must have a chain, it suffices to check ChainNodesMatched.
  3004. // We need to perform this check before potentially modifying one of the
  3005. // nodes via MorphNode.
  3006. bool MayRaiseFPException = false;
  3007. for (auto *N : ChainNodesMatched)
  3008. if (mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept()) {
  3009. MayRaiseFPException = true;
  3010. break;
  3011. }
  3012. // Create the node.
  3013. MachineSDNode *Res = nullptr;
  3014. bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo ||
  3015. (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2);
  3016. if (!IsMorphNodeTo) {
  3017. // If this is a normal EmitNode command, just create the new node and
  3018. // add the results to the RecordedNodes list.
  3019. Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
  3020. VTList, Ops);
  3021. // Add all the non-glue/non-chain results to the RecordedNodes list.
  3022. for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
  3023. if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
  3024. RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
  3025. nullptr));
  3026. }
  3027. } else {
  3028. assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
  3029. "NodeToMatch was removed partway through selection");
  3030. SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N,
  3031. SDNode *E) {
  3032. CurDAG->salvageDebugInfo(*N);
  3033. auto &Chain = ChainNodesMatched;
  3034. assert((!E || !is_contained(Chain, N)) &&
  3035. "Chain node replaced during MorphNode");
  3036. llvm::erase_value(Chain, N);
  3037. });
  3038. Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
  3039. Ops, EmitNodeInfo));
  3040. }
  3041. // Set the NoFPExcept flag when no original matched node could
  3042. // raise an FP exception, but the new node potentially might.
  3043. if (!MayRaiseFPException && mayRaiseFPException(Res)) {
  3044. SDNodeFlags Flags = Res->getFlags();
  3045. Flags.setNoFPExcept(true);
  3046. Res->setFlags(Flags);
  3047. }
  3048. // If the node had chain/glue results, update our notion of the current
  3049. // chain and glue.
  3050. if (EmitNodeInfo & OPFL_GlueOutput) {
  3051. InputGlue = SDValue(Res, VTs.size()-1);
  3052. if (EmitNodeInfo & OPFL_Chain)
  3053. InputChain = SDValue(Res, VTs.size()-2);
  3054. } else if (EmitNodeInfo & OPFL_Chain)
  3055. InputChain = SDValue(Res, VTs.size()-1);
  3056. // If the OPFL_MemRefs glue is set on this node, slap all of the
  3057. // accumulated memrefs onto it.
  3058. //
  3059. // FIXME: This is vastly incorrect for patterns with multiple outputs
  3060. // instructions that access memory and for ComplexPatterns that match
  3061. // loads.
  3062. if (EmitNodeInfo & OPFL_MemRefs) {
  3063. // Only attach load or store memory operands if the generated
  3064. // instruction may load or store.
  3065. const MCInstrDesc &MCID = TII->get(TargetOpc);
  3066. bool mayLoad = MCID.mayLoad();
  3067. bool mayStore = MCID.mayStore();
  3068. // We expect to have relatively few of these so just filter them into a
  3069. // temporary buffer so that we can easily add them to the instruction.
  3070. SmallVector<MachineMemOperand *, 4> FilteredMemRefs;
  3071. for (MachineMemOperand *MMO : MatchedMemRefs) {
  3072. if (MMO->isLoad()) {
  3073. if (mayLoad)
  3074. FilteredMemRefs.push_back(MMO);
  3075. } else if (MMO->isStore()) {
  3076. if (mayStore)
  3077. FilteredMemRefs.push_back(MMO);
  3078. } else {
  3079. FilteredMemRefs.push_back(MMO);
  3080. }
  3081. }
  3082. CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
  3083. }
  3084. LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs()
  3085. << " Dropping mem operands\n";
  3086. dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created")
  3087. << " node: ";
  3088. Res->dump(CurDAG););
  3089. // If this was a MorphNodeTo then we're completely done!
  3090. if (IsMorphNodeTo) {
  3091. // Update chain uses.
  3092. UpdateChains(Res, InputChain, ChainNodesMatched, true);
  3093. return;
  3094. }
  3095. continue;
  3096. }
  3097. case OPC_CompleteMatch: {
  3098. // The match has been completed, and any new nodes (if any) have been
  3099. // created. Patch up references to the matched dag to use the newly
  3100. // created nodes.
  3101. unsigned NumResults = MatcherTable[MatcherIndex++];
  3102. for (unsigned i = 0; i != NumResults; ++i) {
  3103. unsigned ResSlot = MatcherTable[MatcherIndex++];
  3104. if (ResSlot & 128)
  3105. ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
  3106. assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
  3107. SDValue Res = RecordedNodes[ResSlot].first;
  3108. assert(i < NodeToMatch->getNumValues() &&
  3109. NodeToMatch->getValueType(i) != MVT::Other &&
  3110. NodeToMatch->getValueType(i) != MVT::Glue &&
  3111. "Invalid number of results to complete!");
  3112. assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
  3113. NodeToMatch->getValueType(i) == MVT::iPTR ||
  3114. Res.getValueType() == MVT::iPTR ||
  3115. NodeToMatch->getValueType(i).getSizeInBits() ==
  3116. Res.getValueSizeInBits()) &&
  3117. "invalid replacement");
  3118. ReplaceUses(SDValue(NodeToMatch, i), Res);
  3119. }
  3120. // Update chain uses.
  3121. UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
  3122. // If the root node defines glue, we need to update it to the glue result.
  3123. // TODO: This never happens in our tests and I think it can be removed /
  3124. // replaced with an assert, but if we do it this the way the change is
  3125. // NFC.
  3126. if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
  3127. MVT::Glue &&
  3128. InputGlue.getNode())
  3129. ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
  3130. InputGlue);
  3131. assert(NodeToMatch->use_empty() &&
  3132. "Didn't replace all uses of the node?");
  3133. CurDAG->RemoveDeadNode(NodeToMatch);
  3134. return;
  3135. }
  3136. }
  3137. // If the code reached this point, then the match failed. See if there is
  3138. // another child to try in the current 'Scope', otherwise pop it until we
  3139. // find a case to check.
  3140. LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
  3141. << "\n");
  3142. ++NumDAGIselRetries;
  3143. while (true) {
  3144. if (MatchScopes.empty()) {
  3145. CannotYetSelect(NodeToMatch);
  3146. return;
  3147. }
  3148. // Restore the interpreter state back to the point where the scope was
  3149. // formed.
  3150. MatchScope &LastScope = MatchScopes.back();
  3151. RecordedNodes.resize(LastScope.NumRecordedNodes);
  3152. NodeStack.clear();
  3153. NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
  3154. N = NodeStack.back();
  3155. if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
  3156. MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
  3157. MatcherIndex = LastScope.FailIndex;
  3158. LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
  3159. InputChain = LastScope.InputChain;
  3160. InputGlue = LastScope.InputGlue;
  3161. if (!LastScope.HasChainNodesMatched)
  3162. ChainNodesMatched.clear();
  3163. // Check to see what the offset is at the new MatcherIndex. If it is zero
  3164. // we have reached the end of this scope, otherwise we have another child
  3165. // in the current scope to try.
  3166. unsigned NumToSkip = MatcherTable[MatcherIndex++];
  3167. if (NumToSkip & 128)
  3168. NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
  3169. // If we have another child in this scope to match, update FailIndex and
  3170. // try it.
  3171. if (NumToSkip != 0) {
  3172. LastScope.FailIndex = MatcherIndex+NumToSkip;
  3173. break;
  3174. }
  3175. // End of this scope, pop it and try the next child in the containing
  3176. // scope.
  3177. MatchScopes.pop_back();
  3178. }
  3179. }
  3180. }
  3181. /// Return whether the node may raise an FP exception.
  3182. bool SelectionDAGISel::mayRaiseFPException(SDNode *N) const {
  3183. // For machine opcodes, consult the MCID flag.
  3184. if (N->isMachineOpcode()) {
  3185. const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
  3186. return MCID.mayRaiseFPException();
  3187. }
  3188. // For ISD opcodes, only StrictFP opcodes may raise an FP
  3189. // exception.
  3190. if (N->isTargetOpcode())
  3191. return N->isTargetStrictFPOpcode();
  3192. return N->isStrictFPOpcode();
  3193. }
  3194. bool SelectionDAGISel::isOrEquivalentToAdd(const SDNode *N) const {
  3195. assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
  3196. auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  3197. if (!C)
  3198. return false;
  3199. // Detect when "or" is used to add an offset to a stack object.
  3200. if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
  3201. MachineFrameInfo &MFI = MF->getFrameInfo();
  3202. Align A = MFI.getObjectAlign(FN->getIndex());
  3203. int32_t Off = C->getSExtValue();
  3204. // If the alleged offset fits in the zero bits guaranteed by
  3205. // the alignment, then this or is really an add.
  3206. return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
  3207. }
  3208. return false;
  3209. }
  3210. void SelectionDAGISel::CannotYetSelect(SDNode *N) {
  3211. std::string msg;
  3212. raw_string_ostream Msg(msg);
  3213. Msg << "Cannot select: ";
  3214. if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
  3215. N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
  3216. N->getOpcode() != ISD::INTRINSIC_VOID) {
  3217. N->printrFull(Msg, CurDAG);
  3218. Msg << "\nIn function: " << MF->getName();
  3219. } else {
  3220. bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
  3221. unsigned iid =
  3222. cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
  3223. if (iid < Intrinsic::num_intrinsics)
  3224. Msg << "intrinsic %" << Intrinsic::getBaseName((Intrinsic::ID)iid);
  3225. else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
  3226. Msg << "target intrinsic %" << TII->getName(iid);
  3227. else
  3228. Msg << "unknown intrinsic #" << iid;
  3229. }
  3230. report_fatal_error(Twine(Msg.str()));
  3231. }
  3232. char SelectionDAGISel::ID = 0;