TargetLowering.h 209 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/TargetLowering.h - Target Lowering Info -----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file describes how to lower LLVM code to machine code. This has two
  16. /// main components:
  17. ///
  18. /// 1. Which ValueTypes are natively supported by the target.
  19. /// 2. Which operations are supported for supported ValueTypes.
  20. /// 3. Cost thresholds for alternative implementations of certain operations.
  21. ///
  22. /// In addition it has a few other components, like information about FP
  23. /// immediates.
  24. ///
  25. //===----------------------------------------------------------------------===//
  26. #ifndef LLVM_CODEGEN_TARGETLOWERING_H
  27. #define LLVM_CODEGEN_TARGETLOWERING_H
  28. #include "llvm/ADT/APInt.h"
  29. #include "llvm/ADT/ArrayRef.h"
  30. #include "llvm/ADT/DenseMap.h"
  31. #include "llvm/ADT/STLExtras.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. #include "llvm/ADT/StringRef.h"
  34. #include "llvm/CodeGen/DAGCombine.h"
  35. #include "llvm/CodeGen/ISDOpcodes.h"
  36. #include "llvm/CodeGen/LowLevelType.h"
  37. #include "llvm/CodeGen/RuntimeLibcalls.h"
  38. #include "llvm/CodeGen/SelectionDAG.h"
  39. #include "llvm/CodeGen/SelectionDAGNodes.h"
  40. #include "llvm/CodeGen/TargetCallingConv.h"
  41. #include "llvm/CodeGen/ValueTypes.h"
  42. #include "llvm/IR/Attributes.h"
  43. #include "llvm/IR/CallingConv.h"
  44. #include "llvm/IR/DataLayout.h"
  45. #include "llvm/IR/DerivedTypes.h"
  46. #include "llvm/IR/Function.h"
  47. #include "llvm/IR/InlineAsm.h"
  48. #include "llvm/IR/Instruction.h"
  49. #include "llvm/IR/Instructions.h"
  50. #include "llvm/IR/Type.h"
  51. #include "llvm/Support/Alignment.h"
  52. #include "llvm/Support/AtomicOrdering.h"
  53. #include "llvm/Support/Casting.h"
  54. #include "llvm/Support/ErrorHandling.h"
  55. #include "llvm/Support/InstructionCost.h"
  56. #include "llvm/Support/MachineValueType.h"
  57. #include <algorithm>
  58. #include <cassert>
  59. #include <climits>
  60. #include <cstdint>
  61. #include <iterator>
  62. #include <map>
  63. #include <string>
  64. #include <utility>
  65. #include <vector>
  66. namespace llvm {
  67. class CCState;
  68. class CCValAssign;
  69. class Constant;
  70. class FastISel;
  71. class FunctionLoweringInfo;
  72. class GlobalValue;
  73. class GISelKnownBits;
  74. class IntrinsicInst;
  75. class IRBuilderBase;
  76. struct KnownBits;
  77. class LegacyDivergenceAnalysis;
  78. class LLVMContext;
  79. class MachineBasicBlock;
  80. class MachineFunction;
  81. class MachineInstr;
  82. class MachineJumpTableInfo;
  83. class MachineLoop;
  84. class MachineRegisterInfo;
  85. class MCContext;
  86. class MCExpr;
  87. class Module;
  88. class ProfileSummaryInfo;
  89. class TargetLibraryInfo;
  90. class TargetMachine;
  91. class TargetRegisterClass;
  92. class TargetRegisterInfo;
  93. class TargetTransformInfo;
  94. class Value;
  95. namespace Sched {
  96. enum Preference {
  97. None, // No preference
  98. Source, // Follow source order.
  99. RegPressure, // Scheduling for lowest register pressure.
  100. Hybrid, // Scheduling for both latency and register pressure.
  101. ILP, // Scheduling for ILP in low register pressure mode.
  102. VLIW, // Scheduling for VLIW targets.
  103. Fast, // Fast suboptimal list scheduling
  104. Linearize // Linearize DAG, no scheduling
  105. };
  106. } // end namespace Sched
  107. // MemOp models a memory operation, either memset or memcpy/memmove.
  108. struct MemOp {
  109. private:
  110. // Shared
  111. uint64_t Size;
  112. bool DstAlignCanChange; // true if destination alignment can satisfy any
  113. // constraint.
  114. Align DstAlign; // Specified alignment of the memory operation.
  115. bool AllowOverlap;
  116. // memset only
  117. bool IsMemset; // If setthis memory operation is a memset.
  118. bool ZeroMemset; // If set clears out memory with zeros.
  119. // memcpy only
  120. bool MemcpyStrSrc; // Indicates whether the memcpy source is an in-register
  121. // constant so it does not need to be loaded.
  122. Align SrcAlign; // Inferred alignment of the source or default value if the
  123. // memory operation does not need to load the value.
  124. public:
  125. static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
  126. Align SrcAlign, bool IsVolatile,
  127. bool MemcpyStrSrc = false) {
  128. MemOp Op;
  129. Op.Size = Size;
  130. Op.DstAlignCanChange = DstAlignCanChange;
  131. Op.DstAlign = DstAlign;
  132. Op.AllowOverlap = !IsVolatile;
  133. Op.IsMemset = false;
  134. Op.ZeroMemset = false;
  135. Op.MemcpyStrSrc = MemcpyStrSrc;
  136. Op.SrcAlign = SrcAlign;
  137. return Op;
  138. }
  139. static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign,
  140. bool IsZeroMemset, bool IsVolatile) {
  141. MemOp Op;
  142. Op.Size = Size;
  143. Op.DstAlignCanChange = DstAlignCanChange;
  144. Op.DstAlign = DstAlign;
  145. Op.AllowOverlap = !IsVolatile;
  146. Op.IsMemset = true;
  147. Op.ZeroMemset = IsZeroMemset;
  148. Op.MemcpyStrSrc = false;
  149. return Op;
  150. }
  151. uint64_t size() const { return Size; }
  152. Align getDstAlign() const {
  153. assert(!DstAlignCanChange);
  154. return DstAlign;
  155. }
  156. bool isFixedDstAlign() const { return !DstAlignCanChange; }
  157. bool allowOverlap() const { return AllowOverlap; }
  158. bool isMemset() const { return IsMemset; }
  159. bool isMemcpy() const { return !IsMemset; }
  160. bool isMemcpyWithFixedDstAlign() const {
  161. return isMemcpy() && !DstAlignCanChange;
  162. }
  163. bool isZeroMemset() const { return isMemset() && ZeroMemset; }
  164. bool isMemcpyStrSrc() const {
  165. assert(isMemcpy() && "Must be a memcpy");
  166. return MemcpyStrSrc;
  167. }
  168. Align getSrcAlign() const {
  169. assert(isMemcpy() && "Must be a memcpy");
  170. return SrcAlign;
  171. }
  172. bool isSrcAligned(Align AlignCheck) const {
  173. return isMemset() || llvm::isAligned(AlignCheck, SrcAlign.value());
  174. }
  175. bool isDstAligned(Align AlignCheck) const {
  176. return DstAlignCanChange || llvm::isAligned(AlignCheck, DstAlign.value());
  177. }
  178. bool isAligned(Align AlignCheck) const {
  179. return isSrcAligned(AlignCheck) && isDstAligned(AlignCheck);
  180. }
  181. };
  182. /// This base class for TargetLowering contains the SelectionDAG-independent
  183. /// parts that can be used from the rest of CodeGen.
  184. class TargetLoweringBase {
  185. public:
  186. /// This enum indicates whether operations are valid for a target, and if not,
  187. /// what action should be used to make them valid.
  188. enum LegalizeAction : uint8_t {
  189. Legal, // The target natively supports this operation.
  190. Promote, // This operation should be executed in a larger type.
  191. Expand, // Try to expand this to other ops, otherwise use a libcall.
  192. LibCall, // Don't try to expand this to other ops, always use a libcall.
  193. Custom // Use the LowerOperation hook to implement custom lowering.
  194. };
  195. /// This enum indicates whether a types are legal for a target, and if not,
  196. /// what action should be used to make them valid.
  197. enum LegalizeTypeAction : uint8_t {
  198. TypeLegal, // The target natively supports this type.
  199. TypePromoteInteger, // Replace this integer with a larger one.
  200. TypeExpandInteger, // Split this integer into two of half the size.
  201. TypeSoftenFloat, // Convert this float to a same size integer type.
  202. TypeExpandFloat, // Split this float into two of half the size.
  203. TypeScalarizeVector, // Replace this one-element vector with its element.
  204. TypeSplitVector, // Split this vector into two of half the size.
  205. TypeWidenVector, // This vector should be widened into a larger vector.
  206. TypePromoteFloat, // Replace this float with a larger one.
  207. TypeSoftPromoteHalf, // Soften half to i16 and use float to do arithmetic.
  208. TypeScalarizeScalableVector, // This action is explicitly left unimplemented.
  209. // While it is theoretically possible to
  210. // legalize operations on scalable types with a
  211. // loop that handles the vscale * #lanes of the
  212. // vector, this is non-trivial at SelectionDAG
  213. // level and these types are better to be
  214. // widened or promoted.
  215. };
  216. /// LegalizeKind holds the legalization kind that needs to happen to EVT
  217. /// in order to type-legalize it.
  218. using LegalizeKind = std::pair<LegalizeTypeAction, EVT>;
  219. /// Enum that describes how the target represents true/false values.
  220. enum BooleanContent {
  221. UndefinedBooleanContent, // Only bit 0 counts, the rest can hold garbage.
  222. ZeroOrOneBooleanContent, // All bits zero except for bit 0.
  223. ZeroOrNegativeOneBooleanContent // All bits equal to bit 0.
  224. };
  225. /// Enum that describes what type of support for selects the target has.
  226. enum SelectSupportKind {
  227. ScalarValSelect, // The target supports scalar selects (ex: cmov).
  228. ScalarCondVectorVal, // The target supports selects with a scalar condition
  229. // and vector values (ex: cmov).
  230. VectorMaskSelect // The target supports vector selects with a vector
  231. // mask (ex: x86 blends).
  232. };
  233. /// Enum that specifies what an atomic load/AtomicRMWInst is expanded
  234. /// to, if at all. Exists because different targets have different levels of
  235. /// support for these atomic instructions, and also have different options
  236. /// w.r.t. what they should expand to.
  237. enum class AtomicExpansionKind {
  238. None, // Don't expand the instruction.
  239. LLSC, // Expand the instruction into loadlinked/storeconditional; used
  240. // by ARM/AArch64.
  241. LLOnly, // Expand the (load) instruction into just a load-linked, which has
  242. // greater atomic guarantees than a normal load.
  243. CmpXChg, // Expand the instruction into cmpxchg; used by at least X86.
  244. MaskedIntrinsic, // Use a target-specific intrinsic for the LL/SC loop.
  245. };
  246. /// Enum that specifies when a multiplication should be expanded.
  247. enum class MulExpansionKind {
  248. Always, // Always expand the instruction.
  249. OnlyLegalOrCustom, // Only expand when the resulting instructions are legal
  250. // or custom.
  251. };
  252. /// Enum that specifies when a float negation is beneficial.
  253. enum class NegatibleCost {
  254. Cheaper = 0, // Negated expression is cheaper.
  255. Neutral = 1, // Negated expression has the same cost.
  256. Expensive = 2 // Negated expression is more expensive.
  257. };
  258. class ArgListEntry {
  259. public:
  260. Value *Val = nullptr;
  261. SDValue Node = SDValue();
  262. Type *Ty = nullptr;
  263. bool IsSExt : 1;
  264. bool IsZExt : 1;
  265. bool IsInReg : 1;
  266. bool IsSRet : 1;
  267. bool IsNest : 1;
  268. bool IsByVal : 1;
  269. bool IsByRef : 1;
  270. bool IsInAlloca : 1;
  271. bool IsPreallocated : 1;
  272. bool IsReturned : 1;
  273. bool IsSwiftSelf : 1;
  274. bool IsSwiftAsync : 1;
  275. bool IsSwiftError : 1;
  276. bool IsCFGuardTarget : 1;
  277. MaybeAlign Alignment = None;
  278. Type *IndirectType = nullptr;
  279. ArgListEntry()
  280. : IsSExt(false), IsZExt(false), IsInReg(false), IsSRet(false),
  281. IsNest(false), IsByVal(false), IsByRef(false), IsInAlloca(false),
  282. IsPreallocated(false), IsReturned(false), IsSwiftSelf(false),
  283. IsSwiftAsync(false), IsSwiftError(false), IsCFGuardTarget(false) {}
  284. void setAttributes(const CallBase *Call, unsigned ArgIdx);
  285. };
  286. using ArgListTy = std::vector<ArgListEntry>;
  287. virtual void markLibCallAttributes(MachineFunction *MF, unsigned CC,
  288. ArgListTy &Args) const {};
  289. static ISD::NodeType getExtendForContent(BooleanContent Content) {
  290. switch (Content) {
  291. case UndefinedBooleanContent:
  292. // Extend by adding rubbish bits.
  293. return ISD::ANY_EXTEND;
  294. case ZeroOrOneBooleanContent:
  295. // Extend by adding zero bits.
  296. return ISD::ZERO_EXTEND;
  297. case ZeroOrNegativeOneBooleanContent:
  298. // Extend by copying the sign bit.
  299. return ISD::SIGN_EXTEND;
  300. }
  301. llvm_unreachable("Invalid content kind");
  302. }
  303. explicit TargetLoweringBase(const TargetMachine &TM);
  304. TargetLoweringBase(const TargetLoweringBase &) = delete;
  305. TargetLoweringBase &operator=(const TargetLoweringBase &) = delete;
  306. virtual ~TargetLoweringBase() = default;
  307. /// Return true if the target support strict float operation
  308. bool isStrictFPEnabled() const {
  309. return IsStrictFPEnabled;
  310. }
  311. protected:
  312. /// Initialize all of the actions to default values.
  313. void initActions();
  314. public:
  315. const TargetMachine &getTargetMachine() const { return TM; }
  316. virtual bool useSoftFloat() const { return false; }
  317. /// Return the pointer type for the given address space, defaults to
  318. /// the pointer type from the data layout.
  319. /// FIXME: The default needs to be removed once all the code is updated.
  320. virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS = 0) const {
  321. return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  322. }
  323. /// Return the in-memory pointer type for the given address space, defaults to
  324. /// the pointer type from the data layout. FIXME: The default needs to be
  325. /// removed once all the code is updated.
  326. virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS = 0) const {
  327. return MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  328. }
  329. /// Return the type for frame index, which is determined by
  330. /// the alloca address space specified through the data layout.
  331. MVT getFrameIndexTy(const DataLayout &DL) const {
  332. return getPointerTy(DL, DL.getAllocaAddrSpace());
  333. }
  334. /// Return the type for code pointers, which is determined by the program
  335. /// address space specified through the data layout.
  336. MVT getProgramPointerTy(const DataLayout &DL) const {
  337. return getPointerTy(DL, DL.getProgramAddressSpace());
  338. }
  339. /// Return the type for operands of fence.
  340. /// TODO: Let fence operands be of i32 type and remove this.
  341. virtual MVT getFenceOperandTy(const DataLayout &DL) const {
  342. return getPointerTy(DL);
  343. }
  344. /// Return the type to use for a scalar shift opcode, given the shifted amount
  345. /// type. Targets should return a legal type if the input type is legal.
  346. /// Targets can return a type that is too small if the input type is illegal.
  347. virtual MVT getScalarShiftAmountTy(const DataLayout &, EVT) const;
  348. /// Returns the type for the shift amount of a shift opcode. For vectors,
  349. /// returns the input type. For scalars, behavior depends on \p LegalTypes. If
  350. /// \p LegalTypes is true, calls getScalarShiftAmountTy, otherwise uses
  351. /// pointer type. If getScalarShiftAmountTy or pointer type cannot represent
  352. /// all possible shift amounts, returns MVT::i32. In general, \p LegalTypes
  353. /// should be set to true for calls during type legalization and after type
  354. /// legalization has been completed.
  355. EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL,
  356. bool LegalTypes = true) const;
  357. /// Return the preferred type to use for a shift opcode, given the shifted
  358. /// amount type is \p ShiftValueTy.
  359. LLVM_READONLY
  360. virtual LLT getPreferredShiftAmountTy(LLT ShiftValueTy) const {
  361. return ShiftValueTy;
  362. }
  363. /// Returns the type to be used for the index operand of:
  364. /// ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT,
  365. /// ISD::INSERT_SUBVECTOR, and ISD::EXTRACT_SUBVECTOR
  366. virtual MVT getVectorIdxTy(const DataLayout &DL) const {
  367. return getPointerTy(DL);
  368. }
  369. /// Returns the type to be used for the EVL/AVL operand of VP nodes:
  370. /// ISD::VP_ADD, ISD::VP_SUB, etc. It must be a legal scalar integer type,
  371. /// and must be at least as large as i32. The EVL is implicitly zero-extended
  372. /// to any larger type.
  373. virtual MVT getVPExplicitVectorLengthTy() const { return MVT::i32; }
  374. /// This callback is used to inspect load/store instructions and add
  375. /// target-specific MachineMemOperand flags to them. The default
  376. /// implementation does nothing.
  377. virtual MachineMemOperand::Flags getTargetMMOFlags(const Instruction &I) const {
  378. return MachineMemOperand::MONone;
  379. }
  380. MachineMemOperand::Flags getLoadMemOperandFlags(const LoadInst &LI,
  381. const DataLayout &DL) const;
  382. MachineMemOperand::Flags getStoreMemOperandFlags(const StoreInst &SI,
  383. const DataLayout &DL) const;
  384. MachineMemOperand::Flags getAtomicMemOperandFlags(const Instruction &AI,
  385. const DataLayout &DL) const;
  386. virtual bool isSelectSupported(SelectSupportKind /*kind*/) const {
  387. return true;
  388. }
  389. /// Return true if the @llvm.get.active.lane.mask intrinsic should be expanded
  390. /// using generic code in SelectionDAGBuilder.
  391. virtual bool shouldExpandGetActiveLaneMask(EVT VT, EVT OpVT) const {
  392. return true;
  393. }
  394. /// Return true if it is profitable to convert a select of FP constants into
  395. /// a constant pool load whose address depends on the select condition. The
  396. /// parameter may be used to differentiate a select with FP compare from
  397. /// integer compare.
  398. virtual bool reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
  399. return true;
  400. }
  401. /// Return true if multiple condition registers are available.
  402. bool hasMultipleConditionRegisters() const {
  403. return HasMultipleConditionRegisters;
  404. }
  405. /// Return true if the target has BitExtract instructions.
  406. bool hasExtractBitsInsn() const { return HasExtractBitsInsn; }
  407. /// Return the preferred vector type legalization action.
  408. virtual TargetLoweringBase::LegalizeTypeAction
  409. getPreferredVectorAction(MVT VT) const {
  410. // The default action for one element vectors is to scalarize
  411. if (VT.getVectorElementCount().isScalar())
  412. return TypeScalarizeVector;
  413. // The default action for an odd-width vector is to widen.
  414. if (!VT.isPow2VectorType())
  415. return TypeWidenVector;
  416. // The default action for other vectors is to promote
  417. return TypePromoteInteger;
  418. }
  419. // Return true if the half type should be passed around as i16, but promoted
  420. // to float around arithmetic. The default behavior is to pass around as
  421. // float and convert around loads/stores/bitcasts and other places where
  422. // the size matters.
  423. virtual bool softPromoteHalfType() const { return false; }
  424. // There are two general methods for expanding a BUILD_VECTOR node:
  425. // 1. Use SCALAR_TO_VECTOR on the defined scalar values and then shuffle
  426. // them together.
  427. // 2. Build the vector on the stack and then load it.
  428. // If this function returns true, then method (1) will be used, subject to
  429. // the constraint that all of the necessary shuffles are legal (as determined
  430. // by isShuffleMaskLegal). If this function returns false, then method (2) is
  431. // always used. The vector type, and the number of defined values, are
  432. // provided.
  433. virtual bool
  434. shouldExpandBuildVectorWithShuffles(EVT /* VT */,
  435. unsigned DefinedValues) const {
  436. return DefinedValues < 3;
  437. }
  438. /// Return true if integer divide is usually cheaper than a sequence of
  439. /// several shifts, adds, and multiplies for this target.
  440. /// The definition of "cheaper" may depend on whether we're optimizing
  441. /// for speed or for size.
  442. virtual bool isIntDivCheap(EVT VT, AttributeList Attr) const { return false; }
  443. /// Return true if the target can handle a standalone remainder operation.
  444. virtual bool hasStandaloneRem(EVT VT) const {
  445. return true;
  446. }
  447. /// Return true if SQRT(X) shouldn't be replaced with X*RSQRT(X).
  448. virtual bool isFsqrtCheap(SDValue X, SelectionDAG &DAG) const {
  449. // Default behavior is to replace SQRT(X) with X*RSQRT(X).
  450. return false;
  451. }
  452. /// Reciprocal estimate status values used by the functions below.
  453. enum ReciprocalEstimate : int {
  454. Unspecified = -1,
  455. Disabled = 0,
  456. Enabled = 1
  457. };
  458. /// Return a ReciprocalEstimate enum value for a square root of the given type
  459. /// based on the function's attributes. If the operation is not overridden by
  460. /// the function's attributes, "Unspecified" is returned and target defaults
  461. /// are expected to be used for instruction selection.
  462. int getRecipEstimateSqrtEnabled(EVT VT, MachineFunction &MF) const;
  463. /// Return a ReciprocalEstimate enum value for a division of the given type
  464. /// based on the function's attributes. If the operation is not overridden by
  465. /// the function's attributes, "Unspecified" is returned and target defaults
  466. /// are expected to be used for instruction selection.
  467. int getRecipEstimateDivEnabled(EVT VT, MachineFunction &MF) const;
  468. /// Return the refinement step count for a square root of the given type based
  469. /// on the function's attributes. If the operation is not overridden by
  470. /// the function's attributes, "Unspecified" is returned and target defaults
  471. /// are expected to be used for instruction selection.
  472. int getSqrtRefinementSteps(EVT VT, MachineFunction &MF) const;
  473. /// Return the refinement step count for a division of the given type based
  474. /// on the function's attributes. If the operation is not overridden by
  475. /// the function's attributes, "Unspecified" is returned and target defaults
  476. /// are expected to be used for instruction selection.
  477. int getDivRefinementSteps(EVT VT, MachineFunction &MF) const;
  478. /// Returns true if target has indicated at least one type should be bypassed.
  479. bool isSlowDivBypassed() const { return !BypassSlowDivWidths.empty(); }
  480. /// Returns map of slow types for division or remainder with corresponding
  481. /// fast types
  482. const DenseMap<unsigned int, unsigned int> &getBypassSlowDivWidths() const {
  483. return BypassSlowDivWidths;
  484. }
  485. /// Return true if Flow Control is an expensive operation that should be
  486. /// avoided.
  487. bool isJumpExpensive() const { return JumpIsExpensive; }
  488. /// Return true if selects are only cheaper than branches if the branch is
  489. /// unlikely to be predicted right.
  490. bool isPredictableSelectExpensive() const {
  491. return PredictableSelectIsExpensive;
  492. }
  493. virtual bool fallBackToDAGISel(const Instruction &Inst) const {
  494. return false;
  495. }
  496. /// Return true if the following transform is beneficial:
  497. /// fold (conv (load x)) -> (load (conv*)x)
  498. /// On architectures that don't natively support some vector loads
  499. /// efficiently, casting the load to a smaller vector of larger types and
  500. /// loading is more efficient, however, this can be undone by optimizations in
  501. /// dag combiner.
  502. virtual bool isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
  503. const SelectionDAG &DAG,
  504. const MachineMemOperand &MMO) const {
  505. // Don't do if we could do an indexed load on the original type, but not on
  506. // the new one.
  507. if (!LoadVT.isSimple() || !BitcastVT.isSimple())
  508. return true;
  509. MVT LoadMVT = LoadVT.getSimpleVT();
  510. // Don't bother doing this if it's just going to be promoted again later, as
  511. // doing so might interfere with other combines.
  512. if (getOperationAction(ISD::LOAD, LoadMVT) == Promote &&
  513. getTypeToPromoteTo(ISD::LOAD, LoadMVT) == BitcastVT.getSimpleVT())
  514. return false;
  515. bool Fast = false;
  516. return allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), BitcastVT,
  517. MMO, &Fast) && Fast;
  518. }
  519. /// Return true if the following transform is beneficial:
  520. /// (store (y (conv x)), y*)) -> (store x, (x*))
  521. virtual bool isStoreBitCastBeneficial(EVT StoreVT, EVT BitcastVT,
  522. const SelectionDAG &DAG,
  523. const MachineMemOperand &MMO) const {
  524. // Default to the same logic as loads.
  525. return isLoadBitCastBeneficial(StoreVT, BitcastVT, DAG, MMO);
  526. }
  527. /// Return true if it is expected to be cheaper to do a store of a non-zero
  528. /// vector constant with the given size and type for the address space than to
  529. /// store the individual scalar element constants.
  530. virtual bool storeOfVectorConstantIsCheap(EVT MemVT,
  531. unsigned NumElem,
  532. unsigned AddrSpace) const {
  533. return false;
  534. }
  535. /// Allow store merging for the specified type after legalization in addition
  536. /// to before legalization. This may transform stores that do not exist
  537. /// earlier (for example, stores created from intrinsics).
  538. virtual bool mergeStoresAfterLegalization(EVT MemVT) const {
  539. return true;
  540. }
  541. /// Returns if it's reasonable to merge stores to MemVT size.
  542. virtual bool canMergeStoresTo(unsigned AS, EVT MemVT,
  543. const MachineFunction &MF) const {
  544. return true;
  545. }
  546. /// Return true if it is cheap to speculate a call to intrinsic cttz.
  547. virtual bool isCheapToSpeculateCttz() const {
  548. return false;
  549. }
  550. /// Return true if it is cheap to speculate a call to intrinsic ctlz.
  551. virtual bool isCheapToSpeculateCtlz() const {
  552. return false;
  553. }
  554. /// Return true if ctlz instruction is fast.
  555. virtual bool isCtlzFast() const {
  556. return false;
  557. }
  558. /// Return the maximum number of "x & (x - 1)" operations that can be done
  559. /// instead of deferring to a custom CTPOP.
  560. virtual unsigned getCustomCtpopCost(EVT VT, ISD::CondCode Cond) const {
  561. return 1;
  562. }
  563. /// Return true if instruction generated for equality comparison is folded
  564. /// with instruction generated for signed comparison.
  565. virtual bool isEqualityCmpFoldedWithSignedCmp() const { return true; }
  566. /// Return true if the heuristic to prefer icmp eq zero should be used in code
  567. /// gen prepare.
  568. virtual bool preferZeroCompareBranch() const { return false; }
  569. /// Return true if it is safe to transform an integer-domain bitwise operation
  570. /// into the equivalent floating-point operation. This should be set to true
  571. /// if the target has IEEE-754-compliant fabs/fneg operations for the input
  572. /// type.
  573. virtual bool hasBitPreservingFPLogic(EVT VT) const {
  574. return false;
  575. }
  576. /// Return true if it is cheaper to split the store of a merged int val
  577. /// from a pair of smaller values into multiple stores.
  578. virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const {
  579. return false;
  580. }
  581. /// Return if the target supports combining a
  582. /// chain like:
  583. /// \code
  584. /// %andResult = and %val1, #mask
  585. /// %icmpResult = icmp %andResult, 0
  586. /// \endcode
  587. /// into a single machine instruction of a form like:
  588. /// \code
  589. /// cc = test %register, #mask
  590. /// \endcode
  591. virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
  592. return false;
  593. }
  594. /// Use bitwise logic to make pairs of compares more efficient. For example:
  595. /// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
  596. /// This should be true when it takes more than one instruction to lower
  597. /// setcc (cmp+set on x86 scalar), when bitwise ops are faster than logic on
  598. /// condition bits (crand on PowerPC), and/or when reducing cmp+br is a win.
  599. virtual bool convertSetCCLogicToBitwiseLogic(EVT VT) const {
  600. return false;
  601. }
  602. /// Return the preferred operand type if the target has a quick way to compare
  603. /// integer values of the given size. Assume that any legal integer type can
  604. /// be compared efficiently. Targets may override this to allow illegal wide
  605. /// types to return a vector type if there is support to compare that type.
  606. virtual MVT hasFastEqualityCompare(unsigned NumBits) const {
  607. MVT VT = MVT::getIntegerVT(NumBits);
  608. return isTypeLegal(VT) ? VT : MVT::INVALID_SIMPLE_VALUE_TYPE;
  609. }
  610. /// Return true if the target should transform:
  611. /// (X & Y) == Y ---> (~X & Y) == 0
  612. /// (X & Y) != Y ---> (~X & Y) != 0
  613. ///
  614. /// This may be profitable if the target has a bitwise and-not operation that
  615. /// sets comparison flags. A target may want to limit the transformation based
  616. /// on the type of Y or if Y is a constant.
  617. ///
  618. /// Note that the transform will not occur if Y is known to be a power-of-2
  619. /// because a mask and compare of a single bit can be handled by inverting the
  620. /// predicate, for example:
  621. /// (X & 8) == 8 ---> (X & 8) != 0
  622. virtual bool hasAndNotCompare(SDValue Y) const {
  623. return false;
  624. }
  625. /// Return true if the target has a bitwise and-not operation:
  626. /// X = ~A & B
  627. /// This can be used to simplify select or other instructions.
  628. virtual bool hasAndNot(SDValue X) const {
  629. // If the target has the more complex version of this operation, assume that
  630. // it has this operation too.
  631. return hasAndNotCompare(X);
  632. }
  633. /// Return true if the target has a bit-test instruction:
  634. /// (X & (1 << Y)) ==/!= 0
  635. /// This knowledge can be used to prevent breaking the pattern,
  636. /// or creating it if it could be recognized.
  637. virtual bool hasBitTest(SDValue X, SDValue Y) const { return false; }
  638. /// There are two ways to clear extreme bits (either low or high):
  639. /// Mask: x & (-1 << y) (the instcombine canonical form)
  640. /// Shifts: x >> y << y
  641. /// Return true if the variant with 2 variable shifts is preferred.
  642. /// Return false if there is no preference.
  643. virtual bool shouldFoldMaskToVariableShiftPair(SDValue X) const {
  644. // By default, let's assume that no one prefers shifts.
  645. return false;
  646. }
  647. /// Return true if it is profitable to fold a pair of shifts into a mask.
  648. /// This is usually true on most targets. But some targets, like Thumb1,
  649. /// have immediate shift instructions, but no immediate "and" instruction;
  650. /// this makes the fold unprofitable.
  651. virtual bool shouldFoldConstantShiftPairToMask(const SDNode *N,
  652. CombineLevel Level) const {
  653. return true;
  654. }
  655. /// Should we tranform the IR-optimal check for whether given truncation
  656. /// down into KeptBits would be truncating or not:
  657. /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
  658. /// Into it's more traditional form:
  659. /// ((%x << C) a>> C) dstcond %x
  660. /// Return true if we should transform.
  661. /// Return false if there is no preference.
  662. virtual bool shouldTransformSignedTruncationCheck(EVT XVT,
  663. unsigned KeptBits) const {
  664. // By default, let's assume that no one prefers shifts.
  665. return false;
  666. }
  667. /// Given the pattern
  668. /// (X & (C l>>/<< Y)) ==/!= 0
  669. /// return true if it should be transformed into:
  670. /// ((X <</l>> Y) & C) ==/!= 0
  671. /// WARNING: if 'X' is a constant, the fold may deadlock!
  672. /// FIXME: we could avoid passing XC, but we can't use isConstOrConstSplat()
  673. /// here because it can end up being not linked in.
  674. virtual bool shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
  675. SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
  676. unsigned OldShiftOpcode, unsigned NewShiftOpcode,
  677. SelectionDAG &DAG) const {
  678. if (hasBitTest(X, Y)) {
  679. // One interesting pattern that we'd want to form is 'bit test':
  680. // ((1 << Y) & C) ==/!= 0
  681. // But we also need to be careful not to try to reverse that fold.
  682. // Is this '1 << Y' ?
  683. if (OldShiftOpcode == ISD::SHL && CC->isOne())
  684. return false; // Keep the 'bit test' pattern.
  685. // Will it be '1 << Y' after the transform ?
  686. if (XC && NewShiftOpcode == ISD::SHL && XC->isOne())
  687. return true; // Do form the 'bit test' pattern.
  688. }
  689. // If 'X' is a constant, and we transform, then we will immediately
  690. // try to undo the fold, thus causing endless combine loop.
  691. // So by default, let's assume everyone prefers the fold
  692. // iff 'X' is not a constant.
  693. return !XC;
  694. }
  695. /// These two forms are equivalent:
  696. /// sub %y, (xor %x, -1)
  697. /// add (add %x, 1), %y
  698. /// The variant with two add's is IR-canonical.
  699. /// Some targets may prefer one to the other.
  700. virtual bool preferIncOfAddToSubOfNot(EVT VT) const {
  701. // By default, let's assume that everyone prefers the form with two add's.
  702. return true;
  703. }
  704. /// Return true if the target wants to use the optimization that
  705. /// turns ext(promotableInst1(...(promotableInstN(load)))) into
  706. /// promotedInst1(...(promotedInstN(ext(load)))).
  707. bool enableExtLdPromotion() const { return EnableExtLdPromotion; }
  708. /// Return true if the target can combine store(extractelement VectorTy,
  709. /// Idx).
  710. /// \p Cost[out] gives the cost of that transformation when this is true.
  711. virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
  712. unsigned &Cost) const {
  713. return false;
  714. }
  715. /// Return true if inserting a scalar into a variable element of an undef
  716. /// vector is more efficiently handled by splatting the scalar instead.
  717. virtual bool shouldSplatInsEltVarIndex(EVT) const {
  718. return false;
  719. }
  720. /// Return true if target always benefits from combining into FMA for a
  721. /// given value type. This must typically return false on targets where FMA
  722. /// takes more cycles to execute than FADD.
  723. virtual bool enableAggressiveFMAFusion(EVT VT) const { return false; }
  724. /// Return true if target always benefits from combining into FMA for a
  725. /// given value type. This must typically return false on targets where FMA
  726. /// takes more cycles to execute than FADD.
  727. virtual bool enableAggressiveFMAFusion(LLT Ty) const { return false; }
  728. /// Return the ValueType of the result of SETCC operations.
  729. virtual EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
  730. EVT VT) const;
  731. /// Return the ValueType for comparison libcalls. Comparions libcalls include
  732. /// floating point comparion calls, and Ordered/Unordered check calls on
  733. /// floating point numbers.
  734. virtual
  735. MVT::SimpleValueType getCmpLibcallReturnType() const;
  736. /// For targets without i1 registers, this gives the nature of the high-bits
  737. /// of boolean values held in types wider than i1.
  738. ///
  739. /// "Boolean values" are special true/false values produced by nodes like
  740. /// SETCC and consumed (as the condition) by nodes like SELECT and BRCOND.
  741. /// Not to be confused with general values promoted from i1. Some cpus
  742. /// distinguish between vectors of boolean and scalars; the isVec parameter
  743. /// selects between the two kinds. For example on X86 a scalar boolean should
  744. /// be zero extended from i1, while the elements of a vector of booleans
  745. /// should be sign extended from i1.
  746. ///
  747. /// Some cpus also treat floating point types the same way as they treat
  748. /// vectors instead of the way they treat scalars.
  749. BooleanContent getBooleanContents(bool isVec, bool isFloat) const {
  750. if (isVec)
  751. return BooleanVectorContents;
  752. return isFloat ? BooleanFloatContents : BooleanContents;
  753. }
  754. BooleanContent getBooleanContents(EVT Type) const {
  755. return getBooleanContents(Type.isVector(), Type.isFloatingPoint());
  756. }
  757. /// Promote the given target boolean to a target boolean of the given type.
  758. /// A target boolean is an integer value, not necessarily of type i1, the bits
  759. /// of which conform to getBooleanContents.
  760. ///
  761. /// ValVT is the type of values that produced the boolean.
  762. SDValue promoteTargetBoolean(SelectionDAG &DAG, SDValue Bool,
  763. EVT ValVT) const {
  764. SDLoc dl(Bool);
  765. EVT BoolVT =
  766. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ValVT);
  767. ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(ValVT));
  768. return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
  769. }
  770. /// Return target scheduling preference.
  771. Sched::Preference getSchedulingPreference() const {
  772. return SchedPreferenceInfo;
  773. }
  774. /// Some scheduler, e.g. hybrid, can switch to different scheduling heuristics
  775. /// for different nodes. This function returns the preference (or none) for
  776. /// the given node.
  777. virtual Sched::Preference getSchedulingPreference(SDNode *) const {
  778. return Sched::None;
  779. }
  780. /// Return the register class that should be used for the specified value
  781. /// type.
  782. virtual const TargetRegisterClass *getRegClassFor(MVT VT, bool isDivergent = false) const {
  783. (void)isDivergent;
  784. const TargetRegisterClass *RC = RegClassForVT[VT.SimpleTy];
  785. assert(RC && "This value type is not natively supported!");
  786. return RC;
  787. }
  788. /// Allows target to decide about the register class of the
  789. /// specific value that is live outside the defining block.
  790. /// Returns true if the value needs uniform register class.
  791. virtual bool requiresUniformRegister(MachineFunction &MF,
  792. const Value *) const {
  793. return false;
  794. }
  795. /// Return the 'representative' register class for the specified value
  796. /// type.
  797. ///
  798. /// The 'representative' register class is the largest legal super-reg
  799. /// register class for the register class of the value type. For example, on
  800. /// i386 the rep register class for i8, i16, and i32 are GR32; while the rep
  801. /// register class is GR64 on x86_64.
  802. virtual const TargetRegisterClass *getRepRegClassFor(MVT VT) const {
  803. const TargetRegisterClass *RC = RepRegClassForVT[VT.SimpleTy];
  804. return RC;
  805. }
  806. /// Return the cost of the 'representative' register class for the specified
  807. /// value type.
  808. virtual uint8_t getRepRegClassCostFor(MVT VT) const {
  809. return RepRegClassCostForVT[VT.SimpleTy];
  810. }
  811. /// Return true if SHIFT instructions should be expanded to SHIFT_PARTS
  812. /// instructions, and false if a library call is preferred (e.g for code-size
  813. /// reasons).
  814. virtual bool shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
  815. return true;
  816. }
  817. /// Return true if the target has native support for the specified value type.
  818. /// This means that it has a register that directly holds it without
  819. /// promotions or expansions.
  820. bool isTypeLegal(EVT VT) const {
  821. assert(!VT.isSimple() ||
  822. (unsigned)VT.getSimpleVT().SimpleTy < array_lengthof(RegClassForVT));
  823. return VT.isSimple() && RegClassForVT[VT.getSimpleVT().SimpleTy] != nullptr;
  824. }
  825. class ValueTypeActionImpl {
  826. /// ValueTypeActions - For each value type, keep a LegalizeTypeAction enum
  827. /// that indicates how instruction selection should deal with the type.
  828. LegalizeTypeAction ValueTypeActions[MVT::VALUETYPE_SIZE];
  829. public:
  830. ValueTypeActionImpl() {
  831. std::fill(std::begin(ValueTypeActions), std::end(ValueTypeActions),
  832. TypeLegal);
  833. }
  834. LegalizeTypeAction getTypeAction(MVT VT) const {
  835. return ValueTypeActions[VT.SimpleTy];
  836. }
  837. void setTypeAction(MVT VT, LegalizeTypeAction Action) {
  838. ValueTypeActions[VT.SimpleTy] = Action;
  839. }
  840. };
  841. const ValueTypeActionImpl &getValueTypeActions() const {
  842. return ValueTypeActions;
  843. }
  844. /// Return how we should legalize values of this type, either it is already
  845. /// legal (return 'Legal') or we need to promote it to a larger type (return
  846. /// 'Promote'), or we need to expand it into multiple registers of smaller
  847. /// integer type (return 'Expand'). 'Custom' is not an option.
  848. LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const {
  849. return getTypeConversion(Context, VT).first;
  850. }
  851. LegalizeTypeAction getTypeAction(MVT VT) const {
  852. return ValueTypeActions.getTypeAction(VT);
  853. }
  854. /// For types supported by the target, this is an identity function. For
  855. /// types that must be promoted to larger types, this returns the larger type
  856. /// to promote to. For integer types that are larger than the largest integer
  857. /// register, this contains one step in the expansion to get to the smaller
  858. /// register. For illegal floating point types, this returns the integer type
  859. /// to transform to.
  860. EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const {
  861. return getTypeConversion(Context, VT).second;
  862. }
  863. /// For types supported by the target, this is an identity function. For
  864. /// types that must be expanded (i.e. integer types that are larger than the
  865. /// largest integer register or illegal floating point types), this returns
  866. /// the largest legal type it will be expanded to.
  867. EVT getTypeToExpandTo(LLVMContext &Context, EVT VT) const {
  868. assert(!VT.isVector());
  869. while (true) {
  870. switch (getTypeAction(Context, VT)) {
  871. case TypeLegal:
  872. return VT;
  873. case TypeExpandInteger:
  874. VT = getTypeToTransformTo(Context, VT);
  875. break;
  876. default:
  877. llvm_unreachable("Type is not legal nor is it to be expanded!");
  878. }
  879. }
  880. }
  881. /// Vector types are broken down into some number of legal first class types.
  882. /// For example, EVT::v8f32 maps to 2 EVT::v4f32 with Altivec or SSE1, or 8
  883. /// promoted EVT::f64 values with the X86 FP stack. Similarly, EVT::v2i64
  884. /// turns into 4 EVT::i32 values with both PPC and X86.
  885. ///
  886. /// This method returns the number of registers needed, and the VT for each
  887. /// register. It also returns the VT and quantity of the intermediate values
  888. /// before they are promoted/expanded.
  889. unsigned getVectorTypeBreakdown(LLVMContext &Context, EVT VT,
  890. EVT &IntermediateVT,
  891. unsigned &NumIntermediates,
  892. MVT &RegisterVT) const;
  893. /// Certain targets such as MIPS require that some types such as vectors are
  894. /// always broken down into scalars in some contexts. This occurs even if the
  895. /// vector type is legal.
  896. virtual unsigned getVectorTypeBreakdownForCallingConv(
  897. LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
  898. unsigned &NumIntermediates, MVT &RegisterVT) const {
  899. return getVectorTypeBreakdown(Context, VT, IntermediateVT, NumIntermediates,
  900. RegisterVT);
  901. }
  902. struct IntrinsicInfo {
  903. unsigned opc = 0; // target opcode
  904. EVT memVT; // memory VT
  905. // value representing memory location
  906. PointerUnion<const Value *, const PseudoSourceValue *> ptrVal;
  907. int offset = 0; // offset off of ptrVal
  908. uint64_t size = 0; // the size of the memory location
  909. // (taken from memVT if zero)
  910. MaybeAlign align = Align(1); // alignment
  911. MachineMemOperand::Flags flags = MachineMemOperand::MONone;
  912. IntrinsicInfo() = default;
  913. };
  914. /// Given an intrinsic, checks if on the target the intrinsic will need to map
  915. /// to a MemIntrinsicNode (touches memory). If this is the case, it returns
  916. /// true and store the intrinsic information into the IntrinsicInfo that was
  917. /// passed to the function.
  918. virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &,
  919. MachineFunction &,
  920. unsigned /*Intrinsic*/) const {
  921. return false;
  922. }
  923. /// Returns true if the target can instruction select the specified FP
  924. /// immediate natively. If false, the legalizer will materialize the FP
  925. /// immediate as a load from a constant pool.
  926. virtual bool isFPImmLegal(const APFloat & /*Imm*/, EVT /*VT*/,
  927. bool ForCodeSize = false) const {
  928. return false;
  929. }
  930. /// Targets can use this to indicate that they only support *some*
  931. /// VECTOR_SHUFFLE operations, those with specific masks. By default, if a
  932. /// target supports the VECTOR_SHUFFLE node, all mask values are assumed to be
  933. /// legal.
  934. virtual bool isShuffleMaskLegal(ArrayRef<int> /*Mask*/, EVT /*VT*/) const {
  935. return true;
  936. }
  937. /// Returns true if the operation can trap for the value type.
  938. ///
  939. /// VT must be a legal type. By default, we optimistically assume most
  940. /// operations don't trap except for integer divide and remainder.
  941. virtual bool canOpTrap(unsigned Op, EVT VT) const;
  942. /// Similar to isShuffleMaskLegal. Targets can use this to indicate if there
  943. /// is a suitable VECTOR_SHUFFLE that can be used to replace a VAND with a
  944. /// constant pool entry.
  945. virtual bool isVectorClearMaskLegal(ArrayRef<int> /*Mask*/,
  946. EVT /*VT*/) const {
  947. return false;
  948. }
  949. /// Return how this operation should be treated: either it is legal, needs to
  950. /// be promoted to a larger size, needs to be expanded to some other code
  951. /// sequence, or the target has a custom expander for it.
  952. LegalizeAction getOperationAction(unsigned Op, EVT VT) const {
  953. if (VT.isExtended()) return Expand;
  954. // If a target-specific SDNode requires legalization, require the target
  955. // to provide custom legalization for it.
  956. if (Op >= array_lengthof(OpActions[0])) return Custom;
  957. return OpActions[(unsigned)VT.getSimpleVT().SimpleTy][Op];
  958. }
  959. /// Custom method defined by each target to indicate if an operation which
  960. /// may require a scale is supported natively by the target.
  961. /// If not, the operation is illegal.
  962. virtual bool isSupportedFixedPointOperation(unsigned Op, EVT VT,
  963. unsigned Scale) const {
  964. return false;
  965. }
  966. /// Some fixed point operations may be natively supported by the target but
  967. /// only for specific scales. This method allows for checking
  968. /// if the width is supported by the target for a given operation that may
  969. /// depend on scale.
  970. LegalizeAction getFixedPointOperationAction(unsigned Op, EVT VT,
  971. unsigned Scale) const {
  972. auto Action = getOperationAction(Op, VT);
  973. if (Action != Legal)
  974. return Action;
  975. // This operation is supported in this type but may only work on specific
  976. // scales.
  977. bool Supported;
  978. switch (Op) {
  979. default:
  980. llvm_unreachable("Unexpected fixed point operation.");
  981. case ISD::SMULFIX:
  982. case ISD::SMULFIXSAT:
  983. case ISD::UMULFIX:
  984. case ISD::UMULFIXSAT:
  985. case ISD::SDIVFIX:
  986. case ISD::SDIVFIXSAT:
  987. case ISD::UDIVFIX:
  988. case ISD::UDIVFIXSAT:
  989. Supported = isSupportedFixedPointOperation(Op, VT, Scale);
  990. break;
  991. }
  992. return Supported ? Action : Expand;
  993. }
  994. // If Op is a strict floating-point operation, return the result
  995. // of getOperationAction for the equivalent non-strict operation.
  996. LegalizeAction getStrictFPOperationAction(unsigned Op, EVT VT) const {
  997. unsigned EqOpc;
  998. switch (Op) {
  999. default: llvm_unreachable("Unexpected FP pseudo-opcode");
  1000. #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  1001. case ISD::STRICT_##DAGN: EqOpc = ISD::DAGN; break;
  1002. #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  1003. case ISD::STRICT_##DAGN: EqOpc = ISD::SETCC; break;
  1004. #include "llvm/IR/ConstrainedOps.def"
  1005. }
  1006. return getOperationAction(EqOpc, VT);
  1007. }
  1008. /// Return true if the specified operation is legal on this target or can be
  1009. /// made legal with custom lowering. This is used to help guide high-level
  1010. /// lowering decisions. LegalOnly is an optional convenience for code paths
  1011. /// traversed pre and post legalisation.
  1012. bool isOperationLegalOrCustom(unsigned Op, EVT VT,
  1013. bool LegalOnly = false) const {
  1014. if (LegalOnly)
  1015. return isOperationLegal(Op, VT);
  1016. return (VT == MVT::Other || isTypeLegal(VT)) &&
  1017. (getOperationAction(Op, VT) == Legal ||
  1018. getOperationAction(Op, VT) == Custom);
  1019. }
  1020. /// Return true if the specified operation is legal on this target or can be
  1021. /// made legal using promotion. This is used to help guide high-level lowering
  1022. /// decisions. LegalOnly is an optional convenience for code paths traversed
  1023. /// pre and post legalisation.
  1024. bool isOperationLegalOrPromote(unsigned Op, EVT VT,
  1025. bool LegalOnly = false) const {
  1026. if (LegalOnly)
  1027. return isOperationLegal(Op, VT);
  1028. return (VT == MVT::Other || isTypeLegal(VT)) &&
  1029. (getOperationAction(Op, VT) == Legal ||
  1030. getOperationAction(Op, VT) == Promote);
  1031. }
  1032. /// Return true if the specified operation is legal on this target or can be
  1033. /// made legal with custom lowering or using promotion. This is used to help
  1034. /// guide high-level lowering decisions. LegalOnly is an optional convenience
  1035. /// for code paths traversed pre and post legalisation.
  1036. bool isOperationLegalOrCustomOrPromote(unsigned Op, EVT VT,
  1037. bool LegalOnly = false) const {
  1038. if (LegalOnly)
  1039. return isOperationLegal(Op, VT);
  1040. return (VT == MVT::Other || isTypeLegal(VT)) &&
  1041. (getOperationAction(Op, VT) == Legal ||
  1042. getOperationAction(Op, VT) == Custom ||
  1043. getOperationAction(Op, VT) == Promote);
  1044. }
  1045. /// Return true if the operation uses custom lowering, regardless of whether
  1046. /// the type is legal or not.
  1047. bool isOperationCustom(unsigned Op, EVT VT) const {
  1048. return getOperationAction(Op, VT) == Custom;
  1049. }
  1050. /// Return true if lowering to a jump table is allowed.
  1051. virtual bool areJTsAllowed(const Function *Fn) const {
  1052. if (Fn->getFnAttribute("no-jump-tables").getValueAsBool())
  1053. return false;
  1054. return isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  1055. isOperationLegalOrCustom(ISD::BRIND, MVT::Other);
  1056. }
  1057. /// Check whether the range [Low,High] fits in a machine word.
  1058. bool rangeFitsInWord(const APInt &Low, const APInt &High,
  1059. const DataLayout &DL) const {
  1060. // FIXME: Using the pointer type doesn't seem ideal.
  1061. uint64_t BW = DL.getIndexSizeInBits(0u);
  1062. uint64_t Range = (High - Low).getLimitedValue(UINT64_MAX - 1) + 1;
  1063. return Range <= BW;
  1064. }
  1065. /// Return true if lowering to a jump table is suitable for a set of case
  1066. /// clusters which may contain \p NumCases cases, \p Range range of values.
  1067. virtual bool isSuitableForJumpTable(const SwitchInst *SI, uint64_t NumCases,
  1068. uint64_t Range, ProfileSummaryInfo *PSI,
  1069. BlockFrequencyInfo *BFI) const;
  1070. /// Return true if lowering to a bit test is suitable for a set of case
  1071. /// clusters which contains \p NumDests unique destinations, \p Low and
  1072. /// \p High as its lowest and highest case values, and expects \p NumCmps
  1073. /// case value comparisons. Check if the number of destinations, comparison
  1074. /// metric, and range are all suitable.
  1075. bool isSuitableForBitTests(unsigned NumDests, unsigned NumCmps,
  1076. const APInt &Low, const APInt &High,
  1077. const DataLayout &DL) const {
  1078. // FIXME: I don't think NumCmps is the correct metric: a single case and a
  1079. // range of cases both require only one branch to lower. Just looking at the
  1080. // number of clusters and destinations should be enough to decide whether to
  1081. // build bit tests.
  1082. // To lower a range with bit tests, the range must fit the bitwidth of a
  1083. // machine word.
  1084. if (!rangeFitsInWord(Low, High, DL))
  1085. return false;
  1086. // Decide whether it's profitable to lower this range with bit tests. Each
  1087. // destination requires a bit test and branch, and there is an overall range
  1088. // check branch. For a small number of clusters, separate comparisons might
  1089. // be cheaper, and for many destinations, splitting the range might be
  1090. // better.
  1091. return (NumDests == 1 && NumCmps >= 3) || (NumDests == 2 && NumCmps >= 5) ||
  1092. (NumDests == 3 && NumCmps >= 6);
  1093. }
  1094. /// Return true if the specified operation is illegal on this target or
  1095. /// unlikely to be made legal with custom lowering. This is used to help guide
  1096. /// high-level lowering decisions.
  1097. bool isOperationExpand(unsigned Op, EVT VT) const {
  1098. return (!isTypeLegal(VT) || getOperationAction(Op, VT) == Expand);
  1099. }
  1100. /// Return true if the specified operation is legal on this target.
  1101. bool isOperationLegal(unsigned Op, EVT VT) const {
  1102. return (VT == MVT::Other || isTypeLegal(VT)) &&
  1103. getOperationAction(Op, VT) == Legal;
  1104. }
  1105. /// Return how this load with extension should be treated: either it is legal,
  1106. /// needs to be promoted to a larger size, needs to be expanded to some other
  1107. /// code sequence, or the target has a custom expander for it.
  1108. LegalizeAction getLoadExtAction(unsigned ExtType, EVT ValVT,
  1109. EVT MemVT) const {
  1110. if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
  1111. unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
  1112. unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
  1113. assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValI < MVT::VALUETYPE_SIZE &&
  1114. MemI < MVT::VALUETYPE_SIZE && "Table isn't big enough!");
  1115. unsigned Shift = 4 * ExtType;
  1116. return (LegalizeAction)((LoadExtActions[ValI][MemI] >> Shift) & 0xf);
  1117. }
  1118. /// Return true if the specified load with extension is legal on this target.
  1119. bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const {
  1120. return getLoadExtAction(ExtType, ValVT, MemVT) == Legal;
  1121. }
  1122. /// Return true if the specified load with extension is legal or custom
  1123. /// on this target.
  1124. bool isLoadExtLegalOrCustom(unsigned ExtType, EVT ValVT, EVT MemVT) const {
  1125. return getLoadExtAction(ExtType, ValVT, MemVT) == Legal ||
  1126. getLoadExtAction(ExtType, ValVT, MemVT) == Custom;
  1127. }
  1128. /// Return how this store with truncation should be treated: either it is
  1129. /// legal, needs to be promoted to a larger size, needs to be expanded to some
  1130. /// other code sequence, or the target has a custom expander for it.
  1131. LegalizeAction getTruncStoreAction(EVT ValVT, EVT MemVT) const {
  1132. if (ValVT.isExtended() || MemVT.isExtended()) return Expand;
  1133. unsigned ValI = (unsigned) ValVT.getSimpleVT().SimpleTy;
  1134. unsigned MemI = (unsigned) MemVT.getSimpleVT().SimpleTy;
  1135. assert(ValI < MVT::VALUETYPE_SIZE && MemI < MVT::VALUETYPE_SIZE &&
  1136. "Table isn't big enough!");
  1137. return TruncStoreActions[ValI][MemI];
  1138. }
  1139. /// Return true if the specified store with truncation is legal on this
  1140. /// target.
  1141. bool isTruncStoreLegal(EVT ValVT, EVT MemVT) const {
  1142. return isTypeLegal(ValVT) && getTruncStoreAction(ValVT, MemVT) == Legal;
  1143. }
  1144. /// Return true if the specified store with truncation has solution on this
  1145. /// target.
  1146. bool isTruncStoreLegalOrCustom(EVT ValVT, EVT MemVT) const {
  1147. return isTypeLegal(ValVT) &&
  1148. (getTruncStoreAction(ValVT, MemVT) == Legal ||
  1149. getTruncStoreAction(ValVT, MemVT) == Custom);
  1150. }
  1151. virtual bool canCombineTruncStore(EVT ValVT, EVT MemVT,
  1152. bool LegalOnly) const {
  1153. if (LegalOnly)
  1154. return isTruncStoreLegal(ValVT, MemVT);
  1155. return isTruncStoreLegalOrCustom(ValVT, MemVT);
  1156. }
  1157. /// Return how the indexed load should be treated: either it is legal, needs
  1158. /// to be promoted to a larger size, needs to be expanded to some other code
  1159. /// sequence, or the target has a custom expander for it.
  1160. LegalizeAction getIndexedLoadAction(unsigned IdxMode, MVT VT) const {
  1161. return getIndexedModeAction(IdxMode, VT, IMAB_Load);
  1162. }
  1163. /// Return true if the specified indexed load is legal on this target.
  1164. bool isIndexedLoadLegal(unsigned IdxMode, EVT VT) const {
  1165. return VT.isSimple() &&
  1166. (getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
  1167. getIndexedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
  1168. }
  1169. /// Return how the indexed store should be treated: either it is legal, needs
  1170. /// to be promoted to a larger size, needs to be expanded to some other code
  1171. /// sequence, or the target has a custom expander for it.
  1172. LegalizeAction getIndexedStoreAction(unsigned IdxMode, MVT VT) const {
  1173. return getIndexedModeAction(IdxMode, VT, IMAB_Store);
  1174. }
  1175. /// Return true if the specified indexed load is legal on this target.
  1176. bool isIndexedStoreLegal(unsigned IdxMode, EVT VT) const {
  1177. return VT.isSimple() &&
  1178. (getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
  1179. getIndexedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
  1180. }
  1181. /// Return how the indexed load should be treated: either it is legal, needs
  1182. /// to be promoted to a larger size, needs to be expanded to some other code
  1183. /// sequence, or the target has a custom expander for it.
  1184. LegalizeAction getIndexedMaskedLoadAction(unsigned IdxMode, MVT VT) const {
  1185. return getIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad);
  1186. }
  1187. /// Return true if the specified indexed load is legal on this target.
  1188. bool isIndexedMaskedLoadLegal(unsigned IdxMode, EVT VT) const {
  1189. return VT.isSimple() &&
  1190. (getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Legal ||
  1191. getIndexedMaskedLoadAction(IdxMode, VT.getSimpleVT()) == Custom);
  1192. }
  1193. /// Return how the indexed store should be treated: either it is legal, needs
  1194. /// to be promoted to a larger size, needs to be expanded to some other code
  1195. /// sequence, or the target has a custom expander for it.
  1196. LegalizeAction getIndexedMaskedStoreAction(unsigned IdxMode, MVT VT) const {
  1197. return getIndexedModeAction(IdxMode, VT, IMAB_MaskedStore);
  1198. }
  1199. /// Return true if the specified indexed load is legal on this target.
  1200. bool isIndexedMaskedStoreLegal(unsigned IdxMode, EVT VT) const {
  1201. return VT.isSimple() &&
  1202. (getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Legal ||
  1203. getIndexedMaskedStoreAction(IdxMode, VT.getSimpleVT()) == Custom);
  1204. }
  1205. /// Returns true if the index type for a masked gather/scatter requires
  1206. /// extending
  1207. virtual bool shouldExtendGSIndex(EVT VT, EVT &EltTy) const { return false; }
  1208. // Returns true if VT is a legal index type for masked gathers/scatters
  1209. // on this target
  1210. virtual bool shouldRemoveExtendFromGSIndex(EVT VT) const { return false; }
  1211. /// Return how the condition code should be treated: either it is legal, needs
  1212. /// to be expanded to some other code sequence, or the target has a custom
  1213. /// expander for it.
  1214. LegalizeAction
  1215. getCondCodeAction(ISD::CondCode CC, MVT VT) const {
  1216. assert((unsigned)CC < array_lengthof(CondCodeActions) &&
  1217. ((unsigned)VT.SimpleTy >> 3) < array_lengthof(CondCodeActions[0]) &&
  1218. "Table isn't big enough!");
  1219. // See setCondCodeAction for how this is encoded.
  1220. uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
  1221. uint32_t Value = CondCodeActions[CC][VT.SimpleTy >> 3];
  1222. LegalizeAction Action = (LegalizeAction) ((Value >> Shift) & 0xF);
  1223. assert(Action != Promote && "Can't promote condition code!");
  1224. return Action;
  1225. }
  1226. /// Return true if the specified condition code is legal on this target.
  1227. bool isCondCodeLegal(ISD::CondCode CC, MVT VT) const {
  1228. return getCondCodeAction(CC, VT) == Legal;
  1229. }
  1230. /// Return true if the specified condition code is legal or custom on this
  1231. /// target.
  1232. bool isCondCodeLegalOrCustom(ISD::CondCode CC, MVT VT) const {
  1233. return getCondCodeAction(CC, VT) == Legal ||
  1234. getCondCodeAction(CC, VT) == Custom;
  1235. }
  1236. /// If the action for this operation is to promote, this method returns the
  1237. /// ValueType to promote to.
  1238. MVT getTypeToPromoteTo(unsigned Op, MVT VT) const {
  1239. assert(getOperationAction(Op, VT) == Promote &&
  1240. "This operation isn't promoted!");
  1241. // See if this has an explicit type specified.
  1242. std::map<std::pair<unsigned, MVT::SimpleValueType>,
  1243. MVT::SimpleValueType>::const_iterator PTTI =
  1244. PromoteToType.find(std::make_pair(Op, VT.SimpleTy));
  1245. if (PTTI != PromoteToType.end()) return PTTI->second;
  1246. assert((VT.isInteger() || VT.isFloatingPoint()) &&
  1247. "Cannot autopromote this type, add it with AddPromotedToType.");
  1248. MVT NVT = VT;
  1249. do {
  1250. NVT = (MVT::SimpleValueType)(NVT.SimpleTy+1);
  1251. assert(NVT.isInteger() == VT.isInteger() && NVT != MVT::isVoid &&
  1252. "Didn't find type to promote to!");
  1253. } while (!isTypeLegal(NVT) ||
  1254. getOperationAction(Op, NVT) == Promote);
  1255. return NVT;
  1256. }
  1257. virtual EVT getAsmOperandValueType(const DataLayout &DL, Type *Ty,
  1258. bool AllowUnknown = false) const {
  1259. return getValueType(DL, Ty, AllowUnknown);
  1260. }
  1261. /// Return the EVT corresponding to this LLVM type. This is fixed by the LLVM
  1262. /// operations except for the pointer size. If AllowUnknown is true, this
  1263. /// will return MVT::Other for types with no EVT counterpart (e.g. structs),
  1264. /// otherwise it will assert.
  1265. EVT getValueType(const DataLayout &DL, Type *Ty,
  1266. bool AllowUnknown = false) const {
  1267. // Lower scalar pointers to native pointer types.
  1268. if (auto *PTy = dyn_cast<PointerType>(Ty))
  1269. return getPointerTy(DL, PTy->getAddressSpace());
  1270. if (auto *VTy = dyn_cast<VectorType>(Ty)) {
  1271. Type *EltTy = VTy->getElementType();
  1272. // Lower vectors of pointers to native pointer types.
  1273. if (auto *PTy = dyn_cast<PointerType>(EltTy)) {
  1274. EVT PointerTy(getPointerTy(DL, PTy->getAddressSpace()));
  1275. EltTy = PointerTy.getTypeForEVT(Ty->getContext());
  1276. }
  1277. return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(EltTy, false),
  1278. VTy->getElementCount());
  1279. }
  1280. return EVT::getEVT(Ty, AllowUnknown);
  1281. }
  1282. EVT getMemValueType(const DataLayout &DL, Type *Ty,
  1283. bool AllowUnknown = false) const {
  1284. // Lower scalar pointers to native pointer types.
  1285. if (PointerType *PTy = dyn_cast<PointerType>(Ty))
  1286. return getPointerMemTy(DL, PTy->getAddressSpace());
  1287. else if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  1288. Type *Elm = VTy->getElementType();
  1289. if (PointerType *PT = dyn_cast<PointerType>(Elm)) {
  1290. EVT PointerTy(getPointerMemTy(DL, PT->getAddressSpace()));
  1291. Elm = PointerTy.getTypeForEVT(Ty->getContext());
  1292. }
  1293. return EVT::getVectorVT(Ty->getContext(), EVT::getEVT(Elm, false),
  1294. VTy->getElementCount());
  1295. }
  1296. return getValueType(DL, Ty, AllowUnknown);
  1297. }
  1298. /// Return the MVT corresponding to this LLVM type. See getValueType.
  1299. MVT getSimpleValueType(const DataLayout &DL, Type *Ty,
  1300. bool AllowUnknown = false) const {
  1301. return getValueType(DL, Ty, AllowUnknown).getSimpleVT();
  1302. }
  1303. /// Return the desired alignment for ByVal or InAlloca aggregate function
  1304. /// arguments in the caller parameter area. This is the actual alignment, not
  1305. /// its logarithm.
  1306. virtual uint64_t getByValTypeAlignment(Type *Ty, const DataLayout &DL) const;
  1307. /// Return the type of registers that this ValueType will eventually require.
  1308. MVT getRegisterType(MVT VT) const {
  1309. assert((unsigned)VT.SimpleTy < array_lengthof(RegisterTypeForVT));
  1310. return RegisterTypeForVT[VT.SimpleTy];
  1311. }
  1312. /// Return the type of registers that this ValueType will eventually require.
  1313. MVT getRegisterType(LLVMContext &Context, EVT VT) const {
  1314. if (VT.isSimple()) {
  1315. assert((unsigned)VT.getSimpleVT().SimpleTy <
  1316. array_lengthof(RegisterTypeForVT));
  1317. return RegisterTypeForVT[VT.getSimpleVT().SimpleTy];
  1318. }
  1319. if (VT.isVector()) {
  1320. EVT VT1;
  1321. MVT RegisterVT;
  1322. unsigned NumIntermediates;
  1323. (void)getVectorTypeBreakdown(Context, VT, VT1,
  1324. NumIntermediates, RegisterVT);
  1325. return RegisterVT;
  1326. }
  1327. if (VT.isInteger()) {
  1328. return getRegisterType(Context, getTypeToTransformTo(Context, VT));
  1329. }
  1330. llvm_unreachable("Unsupported extended type!");
  1331. }
  1332. /// Return the number of registers that this ValueType will eventually
  1333. /// require.
  1334. ///
  1335. /// This is one for any types promoted to live in larger registers, but may be
  1336. /// more than one for types (like i64) that are split into pieces. For types
  1337. /// like i140, which are first promoted then expanded, it is the number of
  1338. /// registers needed to hold all the bits of the original type. For an i140
  1339. /// on a 32 bit machine this means 5 registers.
  1340. ///
  1341. /// RegisterVT may be passed as a way to override the default settings, for
  1342. /// instance with i128 inline assembly operands on SystemZ.
  1343. virtual unsigned
  1344. getNumRegisters(LLVMContext &Context, EVT VT,
  1345. Optional<MVT> RegisterVT = None) const {
  1346. if (VT.isSimple()) {
  1347. assert((unsigned)VT.getSimpleVT().SimpleTy <
  1348. array_lengthof(NumRegistersForVT));
  1349. return NumRegistersForVT[VT.getSimpleVT().SimpleTy];
  1350. }
  1351. if (VT.isVector()) {
  1352. EVT VT1;
  1353. MVT VT2;
  1354. unsigned NumIntermediates;
  1355. return getVectorTypeBreakdown(Context, VT, VT1, NumIntermediates, VT2);
  1356. }
  1357. if (VT.isInteger()) {
  1358. unsigned BitWidth = VT.getSizeInBits();
  1359. unsigned RegWidth = getRegisterType(Context, VT).getSizeInBits();
  1360. return (BitWidth + RegWidth - 1) / RegWidth;
  1361. }
  1362. llvm_unreachable("Unsupported extended type!");
  1363. }
  1364. /// Certain combinations of ABIs, Targets and features require that types
  1365. /// are legal for some operations and not for other operations.
  1366. /// For MIPS all vector types must be passed through the integer register set.
  1367. virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context,
  1368. CallingConv::ID CC, EVT VT) const {
  1369. return getRegisterType(Context, VT);
  1370. }
  1371. /// Certain targets require unusual breakdowns of certain types. For MIPS,
  1372. /// this occurs when a vector type is used, as vector are passed through the
  1373. /// integer register set.
  1374. virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context,
  1375. CallingConv::ID CC,
  1376. EVT VT) const {
  1377. return getNumRegisters(Context, VT);
  1378. }
  1379. /// Certain targets have context sensitive alignment requirements, where one
  1380. /// type has the alignment requirement of another type.
  1381. virtual Align getABIAlignmentForCallingConv(Type *ArgTy,
  1382. const DataLayout &DL) const {
  1383. return DL.getABITypeAlign(ArgTy);
  1384. }
  1385. /// If true, then instruction selection should seek to shrink the FP constant
  1386. /// of the specified type to a smaller type in order to save space and / or
  1387. /// reduce runtime.
  1388. virtual bool ShouldShrinkFPConstant(EVT) const { return true; }
  1389. /// Return true if it is profitable to reduce a load to a smaller type.
  1390. /// Example: (i16 (trunc (i32 (load x))) -> i16 load x
  1391. virtual bool shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy,
  1392. EVT NewVT) const {
  1393. // By default, assume that it is cheaper to extract a subvector from a wide
  1394. // vector load rather than creating multiple narrow vector loads.
  1395. if (NewVT.isVector() && !Load->hasOneUse())
  1396. return false;
  1397. return true;
  1398. }
  1399. /// When splitting a value of the specified type into parts, does the Lo
  1400. /// or Hi part come first? This usually follows the endianness, except
  1401. /// for ppcf128, where the Hi part always comes first.
  1402. bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const {
  1403. return DL.isBigEndian() || VT == MVT::ppcf128;
  1404. }
  1405. /// If true, the target has custom DAG combine transformations that it can
  1406. /// perform for the specified node.
  1407. bool hasTargetDAGCombine(ISD::NodeType NT) const {
  1408. assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
  1409. return TargetDAGCombineArray[NT >> 3] & (1 << (NT&7));
  1410. }
  1411. unsigned getGatherAllAliasesMaxDepth() const {
  1412. return GatherAllAliasesMaxDepth;
  1413. }
  1414. /// Returns the size of the platform's va_list object.
  1415. virtual unsigned getVaListSizeInBits(const DataLayout &DL) const {
  1416. return getPointerTy(DL).getSizeInBits();
  1417. }
  1418. /// Get maximum # of store operations permitted for llvm.memset
  1419. ///
  1420. /// This function returns the maximum number of store operations permitted
  1421. /// to replace a call to llvm.memset. The value is set by the target at the
  1422. /// performance threshold for such a replacement. If OptSize is true,
  1423. /// return the limit for functions that have OptSize attribute.
  1424. unsigned getMaxStoresPerMemset(bool OptSize) const {
  1425. return OptSize ? MaxStoresPerMemsetOptSize : MaxStoresPerMemset;
  1426. }
  1427. /// Get maximum # of store operations permitted for llvm.memcpy
  1428. ///
  1429. /// This function returns the maximum number of store operations permitted
  1430. /// to replace a call to llvm.memcpy. The value is set by the target at the
  1431. /// performance threshold for such a replacement. If OptSize is true,
  1432. /// return the limit for functions that have OptSize attribute.
  1433. unsigned getMaxStoresPerMemcpy(bool OptSize) const {
  1434. return OptSize ? MaxStoresPerMemcpyOptSize : MaxStoresPerMemcpy;
  1435. }
  1436. /// \brief Get maximum # of store operations to be glued together
  1437. ///
  1438. /// This function returns the maximum number of store operations permitted
  1439. /// to glue together during lowering of llvm.memcpy. The value is set by
  1440. // the target at the performance threshold for such a replacement.
  1441. virtual unsigned getMaxGluedStoresPerMemcpy() const {
  1442. return MaxGluedStoresPerMemcpy;
  1443. }
  1444. /// Get maximum # of load operations permitted for memcmp
  1445. ///
  1446. /// This function returns the maximum number of load operations permitted
  1447. /// to replace a call to memcmp. The value is set by the target at the
  1448. /// performance threshold for such a replacement. If OptSize is true,
  1449. /// return the limit for functions that have OptSize attribute.
  1450. unsigned getMaxExpandSizeMemcmp(bool OptSize) const {
  1451. return OptSize ? MaxLoadsPerMemcmpOptSize : MaxLoadsPerMemcmp;
  1452. }
  1453. /// Get maximum # of store operations permitted for llvm.memmove
  1454. ///
  1455. /// This function returns the maximum number of store operations permitted
  1456. /// to replace a call to llvm.memmove. The value is set by the target at the
  1457. /// performance threshold for such a replacement. If OptSize is true,
  1458. /// return the limit for functions that have OptSize attribute.
  1459. unsigned getMaxStoresPerMemmove(bool OptSize) const {
  1460. return OptSize ? MaxStoresPerMemmoveOptSize : MaxStoresPerMemmove;
  1461. }
  1462. /// Determine if the target supports unaligned memory accesses.
  1463. ///
  1464. /// This function returns true if the target allows unaligned memory accesses
  1465. /// of the specified type in the given address space. If true, it also returns
  1466. /// whether the unaligned memory access is "fast" in the last argument by
  1467. /// reference. This is used, for example, in situations where an array
  1468. /// copy/move/set is converted to a sequence of store operations. Its use
  1469. /// helps to ensure that such replacements don't generate code that causes an
  1470. /// alignment error (trap) on the target machine.
  1471. virtual bool allowsMisalignedMemoryAccesses(
  1472. EVT, unsigned AddrSpace = 0, Align Alignment = Align(1),
  1473. MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
  1474. bool * /*Fast*/ = nullptr) const {
  1475. return false;
  1476. }
  1477. /// LLT handling variant.
  1478. virtual bool allowsMisalignedMemoryAccesses(
  1479. LLT, unsigned AddrSpace = 0, Align Alignment = Align(1),
  1480. MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
  1481. bool * /*Fast*/ = nullptr) const {
  1482. return false;
  1483. }
  1484. /// This function returns true if the memory access is aligned or if the
  1485. /// target allows this specific unaligned memory access. If the access is
  1486. /// allowed, the optional final parameter returns if the access is also fast
  1487. /// (as defined by the target).
  1488. bool allowsMemoryAccessForAlignment(
  1489. LLVMContext &Context, const DataLayout &DL, EVT VT,
  1490. unsigned AddrSpace = 0, Align Alignment = Align(1),
  1491. MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
  1492. bool *Fast = nullptr) const;
  1493. /// Return true if the memory access of this type is aligned or if the target
  1494. /// allows this specific unaligned access for the given MachineMemOperand.
  1495. /// If the access is allowed, the optional final parameter returns if the
  1496. /// access is also fast (as defined by the target).
  1497. bool allowsMemoryAccessForAlignment(LLVMContext &Context,
  1498. const DataLayout &DL, EVT VT,
  1499. const MachineMemOperand &MMO,
  1500. bool *Fast = nullptr) const;
  1501. /// Return true if the target supports a memory access of this type for the
  1502. /// given address space and alignment. If the access is allowed, the optional
  1503. /// final parameter returns if the access is also fast (as defined by the
  1504. /// target).
  1505. virtual bool
  1506. allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
  1507. unsigned AddrSpace = 0, Align Alignment = Align(1),
  1508. MachineMemOperand::Flags Flags = MachineMemOperand::MONone,
  1509. bool *Fast = nullptr) const;
  1510. /// Return true if the target supports a memory access of this type for the
  1511. /// given MachineMemOperand. If the access is allowed, the optional
  1512. /// final parameter returns if the access is also fast (as defined by the
  1513. /// target).
  1514. bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, EVT VT,
  1515. const MachineMemOperand &MMO,
  1516. bool *Fast = nullptr) const;
  1517. /// LLT handling variant.
  1518. bool allowsMemoryAccess(LLVMContext &Context, const DataLayout &DL, LLT Ty,
  1519. const MachineMemOperand &MMO,
  1520. bool *Fast = nullptr) const;
  1521. /// Returns the target specific optimal type for load and store operations as
  1522. /// a result of memset, memcpy, and memmove lowering.
  1523. /// It returns EVT::Other if the type should be determined using generic
  1524. /// target-independent logic.
  1525. virtual EVT
  1526. getOptimalMemOpType(const MemOp &Op,
  1527. const AttributeList & /*FuncAttributes*/) const {
  1528. return MVT::Other;
  1529. }
  1530. /// LLT returning variant.
  1531. virtual LLT
  1532. getOptimalMemOpLLT(const MemOp &Op,
  1533. const AttributeList & /*FuncAttributes*/) const {
  1534. return LLT();
  1535. }
  1536. /// Returns true if it's safe to use load / store of the specified type to
  1537. /// expand memcpy / memset inline.
  1538. ///
  1539. /// This is mostly true for all types except for some special cases. For
  1540. /// example, on X86 targets without SSE2 f64 load / store are done with fldl /
  1541. /// fstpl which also does type conversion. Note the specified type doesn't
  1542. /// have to be legal as the hook is used before type legalization.
  1543. virtual bool isSafeMemOpType(MVT /*VT*/) const { return true; }
  1544. /// Return lower limit for number of blocks in a jump table.
  1545. virtual unsigned getMinimumJumpTableEntries() const;
  1546. /// Return lower limit of the density in a jump table.
  1547. unsigned getMinimumJumpTableDensity(bool OptForSize) const;
  1548. /// Return upper limit for number of entries in a jump table.
  1549. /// Zero if no limit.
  1550. unsigned getMaximumJumpTableSize() const;
  1551. virtual bool isJumpTableRelative() const;
  1552. /// If a physical register, this specifies the register that
  1553. /// llvm.savestack/llvm.restorestack should save and restore.
  1554. Register getStackPointerRegisterToSaveRestore() const {
  1555. return StackPointerRegisterToSaveRestore;
  1556. }
  1557. /// If a physical register, this returns the register that receives the
  1558. /// exception address on entry to an EH pad.
  1559. virtual Register
  1560. getExceptionPointerRegister(const Constant *PersonalityFn) const {
  1561. return Register();
  1562. }
  1563. /// If a physical register, this returns the register that receives the
  1564. /// exception typeid on entry to a landing pad.
  1565. virtual Register
  1566. getExceptionSelectorRegister(const Constant *PersonalityFn) const {
  1567. return Register();
  1568. }
  1569. virtual bool needsFixedCatchObjects() const {
  1570. report_fatal_error("Funclet EH is not implemented for this target");
  1571. }
  1572. /// Return the minimum stack alignment of an argument.
  1573. Align getMinStackArgumentAlignment() const {
  1574. return MinStackArgumentAlignment;
  1575. }
  1576. /// Return the minimum function alignment.
  1577. Align getMinFunctionAlignment() const { return MinFunctionAlignment; }
  1578. /// Return the preferred function alignment.
  1579. Align getPrefFunctionAlignment() const { return PrefFunctionAlignment; }
  1580. /// Return the preferred loop alignment.
  1581. virtual Align getPrefLoopAlignment(MachineLoop *ML = nullptr) const;
  1582. /// Return the maximum amount of bytes allowed to be emitted when padding for
  1583. /// alignment
  1584. virtual unsigned
  1585. getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const;
  1586. /// Should loops be aligned even when the function is marked OptSize (but not
  1587. /// MinSize).
  1588. virtual bool alignLoopsWithOptSize() const { return false; }
  1589. /// If the target has a standard location for the stack protector guard,
  1590. /// returns the address of that location. Otherwise, returns nullptr.
  1591. /// DEPRECATED: please override useLoadStackGuardNode and customize
  1592. /// LOAD_STACK_GUARD, or customize \@llvm.stackguard().
  1593. virtual Value *getIRStackGuard(IRBuilderBase &IRB) const;
  1594. /// Inserts necessary declarations for SSP (stack protection) purpose.
  1595. /// Should be used only when getIRStackGuard returns nullptr.
  1596. virtual void insertSSPDeclarations(Module &M) const;
  1597. /// Return the variable that's previously inserted by insertSSPDeclarations,
  1598. /// if any, otherwise return nullptr. Should be used only when
  1599. /// getIRStackGuard returns nullptr.
  1600. virtual Value *getSDagStackGuard(const Module &M) const;
  1601. /// If this function returns true, stack protection checks should XOR the
  1602. /// frame pointer (or whichever pointer is used to address locals) into the
  1603. /// stack guard value before checking it. getIRStackGuard must return nullptr
  1604. /// if this returns true.
  1605. virtual bool useStackGuardXorFP() const { return false; }
  1606. /// If the target has a standard stack protection check function that
  1607. /// performs validation and error handling, returns the function. Otherwise,
  1608. /// returns nullptr. Must be previously inserted by insertSSPDeclarations.
  1609. /// Should be used only when getIRStackGuard returns nullptr.
  1610. virtual Function *getSSPStackGuardCheck(const Module &M) const;
  1611. /// \returns true if a constant G_UBFX is legal on the target.
  1612. virtual bool isConstantUnsignedBitfieldExtractLegal(unsigned Opc, LLT Ty1,
  1613. LLT Ty2) const {
  1614. return false;
  1615. }
  1616. protected:
  1617. Value *getDefaultSafeStackPointerLocation(IRBuilderBase &IRB,
  1618. bool UseTLS) const;
  1619. public:
  1620. /// Returns the target-specific address of the unsafe stack pointer.
  1621. virtual Value *getSafeStackPointerLocation(IRBuilderBase &IRB) const;
  1622. /// Returns the name of the symbol used to emit stack probes or the empty
  1623. /// string if not applicable.
  1624. virtual bool hasStackProbeSymbol(MachineFunction &MF) const { return false; }
  1625. virtual bool hasInlineStackProbe(MachineFunction &MF) const { return false; }
  1626. virtual StringRef getStackProbeSymbolName(MachineFunction &MF) const {
  1627. return "";
  1628. }
  1629. /// Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g. we
  1630. /// are happy to sink it into basic blocks. A cast may be free, but not
  1631. /// necessarily a no-op. e.g. a free truncate from a 64-bit to 32-bit pointer.
  1632. virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const;
  1633. /// Return true if the pointer arguments to CI should be aligned by aligning
  1634. /// the object whose address is being passed. If so then MinSize is set to the
  1635. /// minimum size the object must be to be aligned and PrefAlign is set to the
  1636. /// preferred alignment.
  1637. virtual bool shouldAlignPointerArgs(CallInst * /*CI*/, unsigned & /*MinSize*/,
  1638. unsigned & /*PrefAlign*/) const {
  1639. return false;
  1640. }
  1641. //===--------------------------------------------------------------------===//
  1642. /// \name Helpers for TargetTransformInfo implementations
  1643. /// @{
  1644. /// Get the ISD node that corresponds to the Instruction class opcode.
  1645. int InstructionOpcodeToISD(unsigned Opcode) const;
  1646. /// Estimate the cost of type-legalization and the legalized type.
  1647. std::pair<InstructionCost, MVT> getTypeLegalizationCost(const DataLayout &DL,
  1648. Type *Ty) const;
  1649. /// @}
  1650. //===--------------------------------------------------------------------===//
  1651. /// \name Helpers for atomic expansion.
  1652. /// @{
  1653. /// Returns the maximum atomic operation size (in bits) supported by
  1654. /// the backend. Atomic operations greater than this size (as well
  1655. /// as ones that are not naturally aligned), will be expanded by
  1656. /// AtomicExpandPass into an __atomic_* library call.
  1657. unsigned getMaxAtomicSizeInBitsSupported() const {
  1658. return MaxAtomicSizeInBitsSupported;
  1659. }
  1660. /// Returns the size of the smallest cmpxchg or ll/sc instruction
  1661. /// the backend supports. Any smaller operations are widened in
  1662. /// AtomicExpandPass.
  1663. ///
  1664. /// Note that *unlike* operations above the maximum size, atomic ops
  1665. /// are still natively supported below the minimum; they just
  1666. /// require a more complex expansion.
  1667. unsigned getMinCmpXchgSizeInBits() const { return MinCmpXchgSizeInBits; }
  1668. /// Whether the target supports unaligned atomic operations.
  1669. bool supportsUnalignedAtomics() const { return SupportsUnalignedAtomics; }
  1670. /// Whether AtomicExpandPass should automatically insert fences and reduce
  1671. /// ordering for this atomic. This should be true for most architectures with
  1672. /// weak memory ordering. Defaults to false.
  1673. virtual bool shouldInsertFencesForAtomic(const Instruction *I) const {
  1674. return false;
  1675. }
  1676. /// Perform a load-linked operation on Addr, returning a "Value *" with the
  1677. /// corresponding pointee type. This may entail some non-trivial operations to
  1678. /// truncate or reconstruct types that will be illegal in the backend. See
  1679. /// ARMISelLowering for an example implementation.
  1680. virtual Value *emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy,
  1681. Value *Addr, AtomicOrdering Ord) const {
  1682. llvm_unreachable("Load linked unimplemented on this target");
  1683. }
  1684. /// Perform a store-conditional operation to Addr. Return the status of the
  1685. /// store. This should be 0 if the store succeeded, non-zero otherwise.
  1686. virtual Value *emitStoreConditional(IRBuilderBase &Builder, Value *Val,
  1687. Value *Addr, AtomicOrdering Ord) const {
  1688. llvm_unreachable("Store conditional unimplemented on this target");
  1689. }
  1690. /// Perform a masked atomicrmw using a target-specific intrinsic. This
  1691. /// represents the core LL/SC loop which will be lowered at a late stage by
  1692. /// the backend.
  1693. virtual Value *emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder,
  1694. AtomicRMWInst *AI,
  1695. Value *AlignedAddr, Value *Incr,
  1696. Value *Mask, Value *ShiftAmt,
  1697. AtomicOrdering Ord) const {
  1698. llvm_unreachable("Masked atomicrmw expansion unimplemented on this target");
  1699. }
  1700. /// Perform a masked cmpxchg using a target-specific intrinsic. This
  1701. /// represents the core LL/SC loop which will be lowered at a late stage by
  1702. /// the backend.
  1703. virtual Value *emitMaskedAtomicCmpXchgIntrinsic(
  1704. IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
  1705. Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
  1706. llvm_unreachable("Masked cmpxchg expansion unimplemented on this target");
  1707. }
  1708. /// Inserts in the IR a target-specific intrinsic specifying a fence.
  1709. /// It is called by AtomicExpandPass before expanding an
  1710. /// AtomicRMW/AtomicCmpXchg/AtomicStore/AtomicLoad
  1711. /// if shouldInsertFencesForAtomic returns true.
  1712. ///
  1713. /// Inst is the original atomic instruction, prior to other expansions that
  1714. /// may be performed.
  1715. ///
  1716. /// This function should either return a nullptr, or a pointer to an IR-level
  1717. /// Instruction*. Even complex fence sequences can be represented by a
  1718. /// single Instruction* through an intrinsic to be lowered later.
  1719. /// Backends should override this method to produce target-specific intrinsic
  1720. /// for their fences.
  1721. /// FIXME: Please note that the default implementation here in terms of
  1722. /// IR-level fences exists for historical/compatibility reasons and is
  1723. /// *unsound* ! Fences cannot, in general, be used to restore sequential
  1724. /// consistency. For example, consider the following example:
  1725. /// atomic<int> x = y = 0;
  1726. /// int r1, r2, r3, r4;
  1727. /// Thread 0:
  1728. /// x.store(1);
  1729. /// Thread 1:
  1730. /// y.store(1);
  1731. /// Thread 2:
  1732. /// r1 = x.load();
  1733. /// r2 = y.load();
  1734. /// Thread 3:
  1735. /// r3 = y.load();
  1736. /// r4 = x.load();
  1737. /// r1 = r3 = 1 and r2 = r4 = 0 is impossible as long as the accesses are all
  1738. /// seq_cst. But if they are lowered to monotonic accesses, no amount of
  1739. /// IR-level fences can prevent it.
  1740. /// @{
  1741. virtual Instruction *emitLeadingFence(IRBuilderBase &Builder,
  1742. Instruction *Inst,
  1743. AtomicOrdering Ord) const;
  1744. virtual Instruction *emitTrailingFence(IRBuilderBase &Builder,
  1745. Instruction *Inst,
  1746. AtomicOrdering Ord) const;
  1747. /// @}
  1748. // Emits code that executes when the comparison result in the ll/sc
  1749. // expansion of a cmpxchg instruction is such that the store-conditional will
  1750. // not execute. This makes it possible to balance out the load-linked with
  1751. // a dedicated instruction, if desired.
  1752. // E.g., on ARM, if ldrex isn't followed by strex, the exclusive monitor would
  1753. // be unnecessarily held, except if clrex, inserted by this hook, is executed.
  1754. virtual void emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const {}
  1755. /// Returns true if the given (atomic) store should be expanded by the
  1756. /// IR-level AtomicExpand pass into an "atomic xchg" which ignores its input.
  1757. virtual bool shouldExpandAtomicStoreInIR(StoreInst *SI) const {
  1758. return false;
  1759. }
  1760. /// Returns true if arguments should be sign-extended in lib calls.
  1761. virtual bool shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
  1762. return IsSigned;
  1763. }
  1764. /// Returns true if arguments should be extended in lib calls.
  1765. virtual bool shouldExtendTypeInLibCall(EVT Type) const {
  1766. return true;
  1767. }
  1768. /// Returns how the given (atomic) load should be expanded by the
  1769. /// IR-level AtomicExpand pass.
  1770. virtual AtomicExpansionKind shouldExpandAtomicLoadInIR(LoadInst *LI) const {
  1771. return AtomicExpansionKind::None;
  1772. }
  1773. /// Returns how the given atomic cmpxchg should be expanded by the IR-level
  1774. /// AtomicExpand pass.
  1775. virtual AtomicExpansionKind
  1776. shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
  1777. return AtomicExpansionKind::None;
  1778. }
  1779. /// Returns how the IR-level AtomicExpand pass should expand the given
  1780. /// AtomicRMW, if at all. Default is to never expand.
  1781. virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
  1782. return RMW->isFloatingPointOperation() ?
  1783. AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None;
  1784. }
  1785. /// On some platforms, an AtomicRMW that never actually modifies the value
  1786. /// (such as fetch_add of 0) can be turned into a fence followed by an
  1787. /// atomic load. This may sound useless, but it makes it possible for the
  1788. /// processor to keep the cacheline shared, dramatically improving
  1789. /// performance. And such idempotent RMWs are useful for implementing some
  1790. /// kinds of locks, see for example (justification + benchmarks):
  1791. /// http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf
  1792. /// This method tries doing that transformation, returning the atomic load if
  1793. /// it succeeds, and nullptr otherwise.
  1794. /// If shouldExpandAtomicLoadInIR returns true on that load, it will undergo
  1795. /// another round of expansion.
  1796. virtual LoadInst *
  1797. lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *RMWI) const {
  1798. return nullptr;
  1799. }
  1800. /// Returns how the platform's atomic operations are extended (ZERO_EXTEND,
  1801. /// SIGN_EXTEND, or ANY_EXTEND).
  1802. virtual ISD::NodeType getExtendForAtomicOps() const {
  1803. return ISD::ZERO_EXTEND;
  1804. }
  1805. /// Returns how the platform's atomic compare and swap expects its comparison
  1806. /// value to be extended (ZERO_EXTEND, SIGN_EXTEND, or ANY_EXTEND). This is
  1807. /// separate from getExtendForAtomicOps, which is concerned with the
  1808. /// sign-extension of the instruction's output, whereas here we are concerned
  1809. /// with the sign-extension of the input. For targets with compare-and-swap
  1810. /// instructions (or sub-word comparisons in their LL/SC loop expansions),
  1811. /// the input can be ANY_EXTEND, but the output will still have a specific
  1812. /// extension.
  1813. virtual ISD::NodeType getExtendForAtomicCmpSwapArg() const {
  1814. return ISD::ANY_EXTEND;
  1815. }
  1816. /// @}
  1817. /// Returns true if we should normalize
  1818. /// select(N0&N1, X, Y) => select(N0, select(N1, X, Y), Y) and
  1819. /// select(N0|N1, X, Y) => select(N0, select(N1, X, Y, Y)) if it is likely
  1820. /// that it saves us from materializing N0 and N1 in an integer register.
  1821. /// Targets that are able to perform and/or on flags should return false here.
  1822. virtual bool shouldNormalizeToSelectSequence(LLVMContext &Context,
  1823. EVT VT) const {
  1824. // If a target has multiple condition registers, then it likely has logical
  1825. // operations on those registers.
  1826. if (hasMultipleConditionRegisters())
  1827. return false;
  1828. // Only do the transform if the value won't be split into multiple
  1829. // registers.
  1830. LegalizeTypeAction Action = getTypeAction(Context, VT);
  1831. return Action != TypeExpandInteger && Action != TypeExpandFloat &&
  1832. Action != TypeSplitVector;
  1833. }
  1834. virtual bool isProfitableToCombineMinNumMaxNum(EVT VT) const { return true; }
  1835. /// Return true if a select of constants (select Cond, C1, C2) should be
  1836. /// transformed into simple math ops with the condition value. For example:
  1837. /// select Cond, C1, C1-1 --> add (zext Cond), C1-1
  1838. virtual bool convertSelectOfConstantsToMath(EVT VT) const {
  1839. return false;
  1840. }
  1841. /// Return true if it is profitable to transform an integer
  1842. /// multiplication-by-constant into simpler operations like shifts and adds.
  1843. /// This may be true if the target does not directly support the
  1844. /// multiplication operation for the specified type or the sequence of simpler
  1845. /// ops is faster than the multiply.
  1846. virtual bool decomposeMulByConstant(LLVMContext &Context,
  1847. EVT VT, SDValue C) const {
  1848. return false;
  1849. }
  1850. /// Return true if it may be profitable to transform
  1851. /// (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
  1852. /// This may not be true if c1 and c2 can be represented as immediates but
  1853. /// c1*c2 cannot, for example.
  1854. /// The target should check if c1, c2 and c1*c2 can be represented as
  1855. /// immediates, or have to be materialized into registers. If it is not sure
  1856. /// about some cases, a default true can be returned to let the DAGCombiner
  1857. /// decide.
  1858. /// AddNode is (add x, c1), and ConstNode is c2.
  1859. virtual bool isMulAddWithConstProfitable(const SDValue &AddNode,
  1860. const SDValue &ConstNode) const {
  1861. return true;
  1862. }
  1863. /// Return true if it is more correct/profitable to use strict FP_TO_INT
  1864. /// conversion operations - canonicalizing the FP source value instead of
  1865. /// converting all cases and then selecting based on value.
  1866. /// This may be true if the target throws exceptions for out of bounds
  1867. /// conversions or has fast FP CMOV.
  1868. virtual bool shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
  1869. bool IsSigned) const {
  1870. return false;
  1871. }
  1872. //===--------------------------------------------------------------------===//
  1873. // TargetLowering Configuration Methods - These methods should be invoked by
  1874. // the derived class constructor to configure this object for the target.
  1875. //
  1876. protected:
  1877. /// Specify how the target extends the result of integer and floating point
  1878. /// boolean values from i1 to a wider type. See getBooleanContents.
  1879. void setBooleanContents(BooleanContent Ty) {
  1880. BooleanContents = Ty;
  1881. BooleanFloatContents = Ty;
  1882. }
  1883. /// Specify how the target extends the result of integer and floating point
  1884. /// boolean values from i1 to a wider type. See getBooleanContents.
  1885. void setBooleanContents(BooleanContent IntTy, BooleanContent FloatTy) {
  1886. BooleanContents = IntTy;
  1887. BooleanFloatContents = FloatTy;
  1888. }
  1889. /// Specify how the target extends the result of a vector boolean value from a
  1890. /// vector of i1 to a wider type. See getBooleanContents.
  1891. void setBooleanVectorContents(BooleanContent Ty) {
  1892. BooleanVectorContents = Ty;
  1893. }
  1894. /// Specify the target scheduling preference.
  1895. void setSchedulingPreference(Sched::Preference Pref) {
  1896. SchedPreferenceInfo = Pref;
  1897. }
  1898. /// Indicate the minimum number of blocks to generate jump tables.
  1899. void setMinimumJumpTableEntries(unsigned Val);
  1900. /// Indicate the maximum number of entries in jump tables.
  1901. /// Set to zero to generate unlimited jump tables.
  1902. void setMaximumJumpTableSize(unsigned);
  1903. /// If set to a physical register, this specifies the register that
  1904. /// llvm.savestack/llvm.restorestack should save and restore.
  1905. void setStackPointerRegisterToSaveRestore(Register R) {
  1906. StackPointerRegisterToSaveRestore = R;
  1907. }
  1908. /// Tells the code generator that the target has multiple (allocatable)
  1909. /// condition registers that can be used to store the results of comparisons
  1910. /// for use by selects and conditional branches. With multiple condition
  1911. /// registers, the code generator will not aggressively sink comparisons into
  1912. /// the blocks of their users.
  1913. void setHasMultipleConditionRegisters(bool hasManyRegs = true) {
  1914. HasMultipleConditionRegisters = hasManyRegs;
  1915. }
  1916. /// Tells the code generator that the target has BitExtract instructions.
  1917. /// The code generator will aggressively sink "shift"s into the blocks of
  1918. /// their users if the users will generate "and" instructions which can be
  1919. /// combined with "shift" to BitExtract instructions.
  1920. void setHasExtractBitsInsn(bool hasExtractInsn = true) {
  1921. HasExtractBitsInsn = hasExtractInsn;
  1922. }
  1923. /// Tells the code generator not to expand logic operations on comparison
  1924. /// predicates into separate sequences that increase the amount of flow
  1925. /// control.
  1926. void setJumpIsExpensive(bool isExpensive = true);
  1927. /// Tells the code generator which bitwidths to bypass.
  1928. void addBypassSlowDiv(unsigned int SlowBitWidth, unsigned int FastBitWidth) {
  1929. BypassSlowDivWidths[SlowBitWidth] = FastBitWidth;
  1930. }
  1931. /// Add the specified register class as an available regclass for the
  1932. /// specified value type. This indicates the selector can handle values of
  1933. /// that class natively.
  1934. void addRegisterClass(MVT VT, const TargetRegisterClass *RC) {
  1935. assert((unsigned)VT.SimpleTy < array_lengthof(RegClassForVT));
  1936. RegClassForVT[VT.SimpleTy] = RC;
  1937. }
  1938. /// Return the largest legal super-reg register class of the register class
  1939. /// for the specified type and its associated "cost".
  1940. virtual std::pair<const TargetRegisterClass *, uint8_t>
  1941. findRepresentativeClass(const TargetRegisterInfo *TRI, MVT VT) const;
  1942. /// Once all of the register classes are added, this allows us to compute
  1943. /// derived properties we expose.
  1944. void computeRegisterProperties(const TargetRegisterInfo *TRI);
  1945. /// Indicate that the specified operation does not work with the specified
  1946. /// type and indicate what to do about it. Note that VT may refer to either
  1947. /// the type of a result or that of an operand of Op.
  1948. void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action) {
  1949. assert(Op < array_lengthof(OpActions[0]) && "Table isn't big enough!");
  1950. OpActions[(unsigned)VT.SimpleTy][Op] = Action;
  1951. }
  1952. /// Indicate that the specified load with extension does not work with the
  1953. /// specified type and indicate what to do about it.
  1954. void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT,
  1955. LegalizeAction Action) {
  1956. assert(ExtType < ISD::LAST_LOADEXT_TYPE && ValVT.isValid() &&
  1957. MemVT.isValid() && "Table isn't big enough!");
  1958. assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
  1959. unsigned Shift = 4 * ExtType;
  1960. LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] &= ~((uint16_t)0xF << Shift);
  1961. LoadExtActions[ValVT.SimpleTy][MemVT.SimpleTy] |= (uint16_t)Action << Shift;
  1962. }
  1963. /// Indicate that the specified truncating store does not work with the
  1964. /// specified type and indicate what to do about it.
  1965. void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action) {
  1966. assert(ValVT.isValid() && MemVT.isValid() && "Table isn't big enough!");
  1967. TruncStoreActions[(unsigned)ValVT.SimpleTy][MemVT.SimpleTy] = Action;
  1968. }
  1969. /// Indicate that the specified indexed load does or does not work with the
  1970. /// specified type and indicate what to do abort it.
  1971. ///
  1972. /// NOTE: All indexed mode loads are initialized to Expand in
  1973. /// TargetLowering.cpp
  1974. void setIndexedLoadAction(unsigned IdxMode, MVT VT, LegalizeAction Action) {
  1975. setIndexedModeAction(IdxMode, VT, IMAB_Load, Action);
  1976. }
  1977. /// Indicate that the specified indexed store does or does not work with the
  1978. /// specified type and indicate what to do about it.
  1979. ///
  1980. /// NOTE: All indexed mode stores are initialized to Expand in
  1981. /// TargetLowering.cpp
  1982. void setIndexedStoreAction(unsigned IdxMode, MVT VT, LegalizeAction Action) {
  1983. setIndexedModeAction(IdxMode, VT, IMAB_Store, Action);
  1984. }
  1985. /// Indicate that the specified indexed masked load does or does not work with
  1986. /// the specified type and indicate what to do about it.
  1987. ///
  1988. /// NOTE: All indexed mode masked loads are initialized to Expand in
  1989. /// TargetLowering.cpp
  1990. void setIndexedMaskedLoadAction(unsigned IdxMode, MVT VT,
  1991. LegalizeAction Action) {
  1992. setIndexedModeAction(IdxMode, VT, IMAB_MaskedLoad, Action);
  1993. }
  1994. /// Indicate that the specified indexed masked store does or does not work
  1995. /// with the specified type and indicate what to do about it.
  1996. ///
  1997. /// NOTE: All indexed mode masked stores are initialized to Expand in
  1998. /// TargetLowering.cpp
  1999. void setIndexedMaskedStoreAction(unsigned IdxMode, MVT VT,
  2000. LegalizeAction Action) {
  2001. setIndexedModeAction(IdxMode, VT, IMAB_MaskedStore, Action);
  2002. }
  2003. /// Indicate that the specified condition code is or isn't supported on the
  2004. /// target and indicate what to do about it.
  2005. void setCondCodeAction(ISD::CondCode CC, MVT VT,
  2006. LegalizeAction Action) {
  2007. assert(VT.isValid() && (unsigned)CC < array_lengthof(CondCodeActions) &&
  2008. "Table isn't big enough!");
  2009. assert((unsigned)Action < 0x10 && "too many bits for bitfield array");
  2010. /// The lower 3 bits of the SimpleTy index into Nth 4bit set from the 32-bit
  2011. /// value and the upper 29 bits index into the second dimension of the array
  2012. /// to select what 32-bit value to use.
  2013. uint32_t Shift = 4 * (VT.SimpleTy & 0x7);
  2014. CondCodeActions[CC][VT.SimpleTy >> 3] &= ~((uint32_t)0xF << Shift);
  2015. CondCodeActions[CC][VT.SimpleTy >> 3] |= (uint32_t)Action << Shift;
  2016. }
  2017. /// If Opc/OrigVT is specified as being promoted, the promotion code defaults
  2018. /// to trying a larger integer/fp until it can find one that works. If that
  2019. /// default is insufficient, this method can be used by the target to override
  2020. /// the default.
  2021. void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
  2022. PromoteToType[std::make_pair(Opc, OrigVT.SimpleTy)] = DestVT.SimpleTy;
  2023. }
  2024. /// Convenience method to set an operation to Promote and specify the type
  2025. /// in a single call.
  2026. void setOperationPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT) {
  2027. setOperationAction(Opc, OrigVT, Promote);
  2028. AddPromotedToType(Opc, OrigVT, DestVT);
  2029. }
  2030. /// Targets should invoke this method for each target independent node that
  2031. /// they want to provide a custom DAG combiner for by implementing the
  2032. /// PerformDAGCombine virtual method.
  2033. void setTargetDAGCombine(ISD::NodeType NT) {
  2034. assert(unsigned(NT >> 3) < array_lengthof(TargetDAGCombineArray));
  2035. TargetDAGCombineArray[NT >> 3] |= 1 << (NT&7);
  2036. }
  2037. /// Set the target's minimum function alignment.
  2038. void setMinFunctionAlignment(Align Alignment) {
  2039. MinFunctionAlignment = Alignment;
  2040. }
  2041. /// Set the target's preferred function alignment. This should be set if
  2042. /// there is a performance benefit to higher-than-minimum alignment
  2043. void setPrefFunctionAlignment(Align Alignment) {
  2044. PrefFunctionAlignment = Alignment;
  2045. }
  2046. /// Set the target's preferred loop alignment. Default alignment is one, it
  2047. /// means the target does not care about loop alignment. The target may also
  2048. /// override getPrefLoopAlignment to provide per-loop values.
  2049. void setPrefLoopAlignment(Align Alignment) { PrefLoopAlignment = Alignment; }
  2050. void setMaxBytesForAlignment(unsigned MaxBytes) {
  2051. MaxBytesForAlignment = MaxBytes;
  2052. }
  2053. /// Set the minimum stack alignment of an argument.
  2054. void setMinStackArgumentAlignment(Align Alignment) {
  2055. MinStackArgumentAlignment = Alignment;
  2056. }
  2057. /// Set the maximum atomic operation size supported by the
  2058. /// backend. Atomic operations greater than this size (as well as
  2059. /// ones that are not naturally aligned), will be expanded by
  2060. /// AtomicExpandPass into an __atomic_* library call.
  2061. void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits) {
  2062. MaxAtomicSizeInBitsSupported = SizeInBits;
  2063. }
  2064. /// Sets the minimum cmpxchg or ll/sc size supported by the backend.
  2065. void setMinCmpXchgSizeInBits(unsigned SizeInBits) {
  2066. MinCmpXchgSizeInBits = SizeInBits;
  2067. }
  2068. /// Sets whether unaligned atomic operations are supported.
  2069. void setSupportsUnalignedAtomics(bool UnalignedSupported) {
  2070. SupportsUnalignedAtomics = UnalignedSupported;
  2071. }
  2072. public:
  2073. //===--------------------------------------------------------------------===//
  2074. // Addressing mode description hooks (used by LSR etc).
  2075. //
  2076. /// CodeGenPrepare sinks address calculations into the same BB as Load/Store
  2077. /// instructions reading the address. This allows as much computation as
  2078. /// possible to be done in the address mode for that operand. This hook lets
  2079. /// targets also pass back when this should be done on intrinsics which
  2080. /// load/store.
  2081. virtual bool getAddrModeArguments(IntrinsicInst * /*I*/,
  2082. SmallVectorImpl<Value*> &/*Ops*/,
  2083. Type *&/*AccessTy*/) const {
  2084. return false;
  2085. }
  2086. /// This represents an addressing mode of:
  2087. /// BaseGV + BaseOffs + BaseReg + Scale*ScaleReg
  2088. /// If BaseGV is null, there is no BaseGV.
  2089. /// If BaseOffs is zero, there is no base offset.
  2090. /// If HasBaseReg is false, there is no base register.
  2091. /// If Scale is zero, there is no ScaleReg. Scale of 1 indicates a reg with
  2092. /// no scale.
  2093. struct AddrMode {
  2094. GlobalValue *BaseGV = nullptr;
  2095. int64_t BaseOffs = 0;
  2096. bool HasBaseReg = false;
  2097. int64_t Scale = 0;
  2098. AddrMode() = default;
  2099. };
  2100. /// Return true if the addressing mode represented by AM is legal for this
  2101. /// target, for a load/store of the specified type.
  2102. ///
  2103. /// The type may be VoidTy, in which case only return true if the addressing
  2104. /// mode is legal for a load/store of any legal type. TODO: Handle
  2105. /// pre/postinc as well.
  2106. ///
  2107. /// If the address space cannot be determined, it will be -1.
  2108. ///
  2109. /// TODO: Remove default argument
  2110. virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
  2111. Type *Ty, unsigned AddrSpace,
  2112. Instruction *I = nullptr) const;
  2113. /// Return the cost of the scaling factor used in the addressing mode
  2114. /// represented by AM for this target, for a load/store of the specified type.
  2115. ///
  2116. /// If the AM is supported, the return value must be >= 0.
  2117. /// If the AM is not supported, it returns a negative value.
  2118. /// TODO: Handle pre/postinc as well.
  2119. /// TODO: Remove default argument
  2120. virtual InstructionCost getScalingFactorCost(const DataLayout &DL,
  2121. const AddrMode &AM, Type *Ty,
  2122. unsigned AS = 0) const {
  2123. // Default: assume that any scaling factor used in a legal AM is free.
  2124. if (isLegalAddressingMode(DL, AM, Ty, AS))
  2125. return 0;
  2126. return -1;
  2127. }
  2128. /// Return true if the specified immediate is legal icmp immediate, that is
  2129. /// the target has icmp instructions which can compare a register against the
  2130. /// immediate without having to materialize the immediate into a register.
  2131. virtual bool isLegalICmpImmediate(int64_t) const {
  2132. return true;
  2133. }
  2134. /// Return true if the specified immediate is legal add immediate, that is the
  2135. /// target has add instructions which can add a register with the immediate
  2136. /// without having to materialize the immediate into a register.
  2137. virtual bool isLegalAddImmediate(int64_t) const {
  2138. return true;
  2139. }
  2140. /// Return true if the specified immediate is legal for the value input of a
  2141. /// store instruction.
  2142. virtual bool isLegalStoreImmediate(int64_t Value) const {
  2143. // Default implementation assumes that at least 0 works since it is likely
  2144. // that a zero register exists or a zero immediate is allowed.
  2145. return Value == 0;
  2146. }
  2147. /// Return true if it's significantly cheaper to shift a vector by a uniform
  2148. /// scalar than by an amount which will vary across each lane. On x86 before
  2149. /// AVX2 for example, there is a "psllw" instruction for the former case, but
  2150. /// no simple instruction for a general "a << b" operation on vectors.
  2151. /// This should also apply to lowering for vector funnel shifts (rotates).
  2152. virtual bool isVectorShiftByScalarCheap(Type *Ty) const {
  2153. return false;
  2154. }
  2155. /// Given a shuffle vector SVI representing a vector splat, return a new
  2156. /// scalar type of size equal to SVI's scalar type if the new type is more
  2157. /// profitable. Returns nullptr otherwise. For example under MVE float splats
  2158. /// are converted to integer to prevent the need to move from SPR to GPR
  2159. /// registers.
  2160. virtual Type* shouldConvertSplatType(ShuffleVectorInst* SVI) const {
  2161. return nullptr;
  2162. }
  2163. /// Given a set in interconnected phis of type 'From' that are loaded/stored
  2164. /// or bitcast to type 'To', return true if the set should be converted to
  2165. /// 'To'.
  2166. virtual bool shouldConvertPhiType(Type *From, Type *To) const {
  2167. return (From->isIntegerTy() || From->isFloatingPointTy()) &&
  2168. (To->isIntegerTy() || To->isFloatingPointTy());
  2169. }
  2170. /// Returns true if the opcode is a commutative binary operation.
  2171. virtual bool isCommutativeBinOp(unsigned Opcode) const {
  2172. // FIXME: This should get its info from the td file.
  2173. switch (Opcode) {
  2174. case ISD::ADD:
  2175. case ISD::SMIN:
  2176. case ISD::SMAX:
  2177. case ISD::UMIN:
  2178. case ISD::UMAX:
  2179. case ISD::MUL:
  2180. case ISD::MULHU:
  2181. case ISD::MULHS:
  2182. case ISD::SMUL_LOHI:
  2183. case ISD::UMUL_LOHI:
  2184. case ISD::FADD:
  2185. case ISD::FMUL:
  2186. case ISD::AND:
  2187. case ISD::OR:
  2188. case ISD::XOR:
  2189. case ISD::SADDO:
  2190. case ISD::UADDO:
  2191. case ISD::ADDC:
  2192. case ISD::ADDE:
  2193. case ISD::SADDSAT:
  2194. case ISD::UADDSAT:
  2195. case ISD::FMINNUM:
  2196. case ISD::FMAXNUM:
  2197. case ISD::FMINNUM_IEEE:
  2198. case ISD::FMAXNUM_IEEE:
  2199. case ISD::FMINIMUM:
  2200. case ISD::FMAXIMUM:
  2201. return true;
  2202. default: return false;
  2203. }
  2204. }
  2205. /// Return true if the node is a math/logic binary operator.
  2206. virtual bool isBinOp(unsigned Opcode) const {
  2207. // A commutative binop must be a binop.
  2208. if (isCommutativeBinOp(Opcode))
  2209. return true;
  2210. // These are non-commutative binops.
  2211. switch (Opcode) {
  2212. case ISD::SUB:
  2213. case ISD::SHL:
  2214. case ISD::SRL:
  2215. case ISD::SRA:
  2216. case ISD::ROTL:
  2217. case ISD::ROTR:
  2218. case ISD::SDIV:
  2219. case ISD::UDIV:
  2220. case ISD::SREM:
  2221. case ISD::UREM:
  2222. case ISD::SSUBSAT:
  2223. case ISD::USUBSAT:
  2224. case ISD::FSUB:
  2225. case ISD::FDIV:
  2226. case ISD::FREM:
  2227. return true;
  2228. default:
  2229. return false;
  2230. }
  2231. }
  2232. /// Return true if it's free to truncate a value of type FromTy to type
  2233. /// ToTy. e.g. On x86 it's free to truncate a i32 value in register EAX to i16
  2234. /// by referencing its sub-register AX.
  2235. /// Targets must return false when FromTy <= ToTy.
  2236. virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const {
  2237. return false;
  2238. }
  2239. /// Return true if a truncation from FromTy to ToTy is permitted when deciding
  2240. /// whether a call is in tail position. Typically this means that both results
  2241. /// would be assigned to the same register or stack slot, but it could mean
  2242. /// the target performs adequate checks of its own before proceeding with the
  2243. /// tail call. Targets must return false when FromTy <= ToTy.
  2244. virtual bool allowTruncateForTailCall(Type *FromTy, Type *ToTy) const {
  2245. return false;
  2246. }
  2247. virtual bool isTruncateFree(EVT FromVT, EVT ToVT) const { return false; }
  2248. virtual bool isTruncateFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
  2249. LLVMContext &Ctx) const {
  2250. return isTruncateFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
  2251. getApproximateEVTForLLT(ToTy, DL, Ctx));
  2252. }
  2253. virtual bool isProfitableToHoist(Instruction *I) const { return true; }
  2254. /// Return true if the extension represented by \p I is free.
  2255. /// Unlikely the is[Z|FP]ExtFree family which is based on types,
  2256. /// this method can use the context provided by \p I to decide
  2257. /// whether or not \p I is free.
  2258. /// This method extends the behavior of the is[Z|FP]ExtFree family.
  2259. /// In other words, if is[Z|FP]Free returns true, then this method
  2260. /// returns true as well. The converse is not true.
  2261. /// The target can perform the adequate checks by overriding isExtFreeImpl.
  2262. /// \pre \p I must be a sign, zero, or fp extension.
  2263. bool isExtFree(const Instruction *I) const {
  2264. switch (I->getOpcode()) {
  2265. case Instruction::FPExt:
  2266. if (isFPExtFree(EVT::getEVT(I->getType()),
  2267. EVT::getEVT(I->getOperand(0)->getType())))
  2268. return true;
  2269. break;
  2270. case Instruction::ZExt:
  2271. if (isZExtFree(I->getOperand(0)->getType(), I->getType()))
  2272. return true;
  2273. break;
  2274. case Instruction::SExt:
  2275. break;
  2276. default:
  2277. llvm_unreachable("Instruction is not an extension");
  2278. }
  2279. return isExtFreeImpl(I);
  2280. }
  2281. /// Return true if \p Load and \p Ext can form an ExtLoad.
  2282. /// For example, in AArch64
  2283. /// %L = load i8, i8* %ptr
  2284. /// %E = zext i8 %L to i32
  2285. /// can be lowered into one load instruction
  2286. /// ldrb w0, [x0]
  2287. bool isExtLoad(const LoadInst *Load, const Instruction *Ext,
  2288. const DataLayout &DL) const {
  2289. EVT VT = getValueType(DL, Ext->getType());
  2290. EVT LoadVT = getValueType(DL, Load->getType());
  2291. // If the load has other users and the truncate is not free, the ext
  2292. // probably isn't free.
  2293. if (!Load->hasOneUse() && (isTypeLegal(LoadVT) || !isTypeLegal(VT)) &&
  2294. !isTruncateFree(Ext->getType(), Load->getType()))
  2295. return false;
  2296. // Check whether the target supports casts folded into loads.
  2297. unsigned LType;
  2298. if (isa<ZExtInst>(Ext))
  2299. LType = ISD::ZEXTLOAD;
  2300. else {
  2301. assert(isa<SExtInst>(Ext) && "Unexpected ext type!");
  2302. LType = ISD::SEXTLOAD;
  2303. }
  2304. return isLoadExtLegal(LType, VT, LoadVT);
  2305. }
  2306. /// Return true if any actual instruction that defines a value of type FromTy
  2307. /// implicitly zero-extends the value to ToTy in the result register.
  2308. ///
  2309. /// The function should return true when it is likely that the truncate can
  2310. /// be freely folded with an instruction defining a value of FromTy. If
  2311. /// the defining instruction is unknown (because you're looking at a
  2312. /// function argument, PHI, etc.) then the target may require an
  2313. /// explicit truncate, which is not necessarily free, but this function
  2314. /// does not deal with those cases.
  2315. /// Targets must return false when FromTy >= ToTy.
  2316. virtual bool isZExtFree(Type *FromTy, Type *ToTy) const {
  2317. return false;
  2318. }
  2319. virtual bool isZExtFree(EVT FromTy, EVT ToTy) const { return false; }
  2320. virtual bool isZExtFree(LLT FromTy, LLT ToTy, const DataLayout &DL,
  2321. LLVMContext &Ctx) const {
  2322. return isZExtFree(getApproximateEVTForLLT(FromTy, DL, Ctx),
  2323. getApproximateEVTForLLT(ToTy, DL, Ctx));
  2324. }
  2325. /// Return true if sign-extension from FromTy to ToTy is cheaper than
  2326. /// zero-extension.
  2327. virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const {
  2328. return false;
  2329. }
  2330. /// Return true if sinking I's operands to the same basic block as I is
  2331. /// profitable, e.g. because the operands can be folded into a target
  2332. /// instruction during instruction selection. After calling the function
  2333. /// \p Ops contains the Uses to sink ordered by dominance (dominating users
  2334. /// come first).
  2335. virtual bool shouldSinkOperands(Instruction *I,
  2336. SmallVectorImpl<Use *> &Ops) const {
  2337. return false;
  2338. }
  2339. /// Return true if the target supplies and combines to a paired load
  2340. /// two loaded values of type LoadedType next to each other in memory.
  2341. /// RequiredAlignment gives the minimal alignment constraints that must be met
  2342. /// to be able to select this paired load.
  2343. ///
  2344. /// This information is *not* used to generate actual paired loads, but it is
  2345. /// used to generate a sequence of loads that is easier to combine into a
  2346. /// paired load.
  2347. /// For instance, something like this:
  2348. /// a = load i64* addr
  2349. /// b = trunc i64 a to i32
  2350. /// c = lshr i64 a, 32
  2351. /// d = trunc i64 c to i32
  2352. /// will be optimized into:
  2353. /// b = load i32* addr1
  2354. /// d = load i32* addr2
  2355. /// Where addr1 = addr2 +/- sizeof(i32).
  2356. ///
  2357. /// In other words, unless the target performs a post-isel load combining,
  2358. /// this information should not be provided because it will generate more
  2359. /// loads.
  2360. virtual bool hasPairedLoad(EVT /*LoadedType*/,
  2361. Align & /*RequiredAlignment*/) const {
  2362. return false;
  2363. }
  2364. /// Return true if the target has a vector blend instruction.
  2365. virtual bool hasVectorBlend() const { return false; }
  2366. /// Get the maximum supported factor for interleaved memory accesses.
  2367. /// Default to be the minimum interleave factor: 2.
  2368. virtual unsigned getMaxSupportedInterleaveFactor() const { return 2; }
  2369. /// Lower an interleaved load to target specific intrinsics. Return
  2370. /// true on success.
  2371. ///
  2372. /// \p LI is the vector load instruction.
  2373. /// \p Shuffles is the shufflevector list to DE-interleave the loaded vector.
  2374. /// \p Indices is the corresponding indices for each shufflevector.
  2375. /// \p Factor is the interleave factor.
  2376. virtual bool lowerInterleavedLoad(LoadInst *LI,
  2377. ArrayRef<ShuffleVectorInst *> Shuffles,
  2378. ArrayRef<unsigned> Indices,
  2379. unsigned Factor) const {
  2380. return false;
  2381. }
  2382. /// Lower an interleaved store to target specific intrinsics. Return
  2383. /// true on success.
  2384. ///
  2385. /// \p SI is the vector store instruction.
  2386. /// \p SVI is the shufflevector to RE-interleave the stored vector.
  2387. /// \p Factor is the interleave factor.
  2388. virtual bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
  2389. unsigned Factor) const {
  2390. return false;
  2391. }
  2392. /// Return true if zero-extending the specific node Val to type VT2 is free
  2393. /// (either because it's implicitly zero-extended such as ARM ldrb / ldrh or
  2394. /// because it's folded such as X86 zero-extending loads).
  2395. virtual bool isZExtFree(SDValue Val, EVT VT2) const {
  2396. return isZExtFree(Val.getValueType(), VT2);
  2397. }
  2398. /// Return true if an fpext operation is free (for instance, because
  2399. /// single-precision floating-point numbers are implicitly extended to
  2400. /// double-precision).
  2401. virtual bool isFPExtFree(EVT DestVT, EVT SrcVT) const {
  2402. assert(SrcVT.isFloatingPoint() && DestVT.isFloatingPoint() &&
  2403. "invalid fpext types");
  2404. return false;
  2405. }
  2406. /// Return true if an fpext operation input to an \p Opcode operation is free
  2407. /// (for instance, because half-precision floating-point numbers are
  2408. /// implicitly extended to float-precision) for an FMA instruction.
  2409. virtual bool isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
  2410. LLT DestTy, LLT SrcTy) const {
  2411. return false;
  2412. }
  2413. /// Return true if an fpext operation input to an \p Opcode operation is free
  2414. /// (for instance, because half-precision floating-point numbers are
  2415. /// implicitly extended to float-precision) for an FMA instruction.
  2416. virtual bool isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
  2417. EVT DestVT, EVT SrcVT) const {
  2418. assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
  2419. "invalid fpext types");
  2420. return isFPExtFree(DestVT, SrcVT);
  2421. }
  2422. /// Return true if folding a vector load into ExtVal (a sign, zero, or any
  2423. /// extend node) is profitable.
  2424. virtual bool isVectorLoadExtDesirable(SDValue ExtVal) const { return false; }
  2425. /// Return true if an fneg operation is free to the point where it is never
  2426. /// worthwhile to replace it with a bitwise operation.
  2427. virtual bool isFNegFree(EVT VT) const {
  2428. assert(VT.isFloatingPoint());
  2429. return false;
  2430. }
  2431. /// Return true if an fabs operation is free to the point where it is never
  2432. /// worthwhile to replace it with a bitwise operation.
  2433. virtual bool isFAbsFree(EVT VT) const {
  2434. assert(VT.isFloatingPoint());
  2435. return false;
  2436. }
  2437. /// Return true if an FMA operation is faster than a pair of fmul and fadd
  2438. /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
  2439. /// returns true, otherwise fmuladd is expanded to fmul + fadd.
  2440. ///
  2441. /// NOTE: This may be called before legalization on types for which FMAs are
  2442. /// not legal, but should return true if those types will eventually legalize
  2443. /// to types that support FMAs. After legalization, it will only be called on
  2444. /// types that support FMAs (via Legal or Custom actions)
  2445. virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
  2446. EVT) const {
  2447. return false;
  2448. }
  2449. /// Return true if an FMA operation is faster than a pair of fmul and fadd
  2450. /// instructions. fmuladd intrinsics will be expanded to FMAs when this method
  2451. /// returns true, otherwise fmuladd is expanded to fmul + fadd.
  2452. ///
  2453. /// NOTE: This may be called before legalization on types for which FMAs are
  2454. /// not legal, but should return true if those types will eventually legalize
  2455. /// to types that support FMAs. After legalization, it will only be called on
  2456. /// types that support FMAs (via Legal or Custom actions)
  2457. virtual bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
  2458. LLT) const {
  2459. return false;
  2460. }
  2461. /// IR version
  2462. virtual bool isFMAFasterThanFMulAndFAdd(const Function &F, Type *) const {
  2463. return false;
  2464. }
  2465. /// Returns true if \p MI can be combined with another instruction to
  2466. /// form TargetOpcode::G_FMAD. \p N may be an TargetOpcode::G_FADD,
  2467. /// TargetOpcode::G_FSUB, or an TargetOpcode::G_FMUL which will be
  2468. /// distributed into an fadd/fsub.
  2469. virtual bool isFMADLegal(const MachineInstr &MI, LLT Ty) const {
  2470. assert((MI.getOpcode() == TargetOpcode::G_FADD ||
  2471. MI.getOpcode() == TargetOpcode::G_FSUB ||
  2472. MI.getOpcode() == TargetOpcode::G_FMUL) &&
  2473. "unexpected node in FMAD forming combine");
  2474. switch (Ty.getScalarSizeInBits()) {
  2475. case 16:
  2476. return isOperationLegal(TargetOpcode::G_FMAD, MVT::f16);
  2477. case 32:
  2478. return isOperationLegal(TargetOpcode::G_FMAD, MVT::f32);
  2479. case 64:
  2480. return isOperationLegal(TargetOpcode::G_FMAD, MVT::f64);
  2481. default:
  2482. break;
  2483. }
  2484. return false;
  2485. }
  2486. /// Returns true if be combined with to form an ISD::FMAD. \p N may be an
  2487. /// ISD::FADD, ISD::FSUB, or an ISD::FMUL which will be distributed into an
  2488. /// fadd/fsub.
  2489. virtual bool isFMADLegal(const SelectionDAG &DAG, const SDNode *N) const {
  2490. assert((N->getOpcode() == ISD::FADD || N->getOpcode() == ISD::FSUB ||
  2491. N->getOpcode() == ISD::FMUL) &&
  2492. "unexpected node in FMAD forming combine");
  2493. return isOperationLegal(ISD::FMAD, N->getValueType(0));
  2494. }
  2495. // Return true when the decision to generate FMA's (or FMS, FMLA etc) rather
  2496. // than FMUL and ADD is delegated to the machine combiner.
  2497. virtual bool generateFMAsInMachineCombiner(EVT VT,
  2498. CodeGenOpt::Level OptLevel) const {
  2499. return false;
  2500. }
  2501. /// Return true if it's profitable to narrow operations of type VT1 to
  2502. /// VT2. e.g. on x86, it's profitable to narrow from i32 to i8 but not from
  2503. /// i32 to i16.
  2504. virtual bool isNarrowingProfitable(EVT /*VT1*/, EVT /*VT2*/) const {
  2505. return false;
  2506. }
  2507. /// Return true if pulling a binary operation into a select with an identity
  2508. /// constant is profitable. This is the inverse of an IR transform.
  2509. /// Example: X + (Cond ? Y : 0) --> Cond ? (X + Y) : X
  2510. virtual bool shouldFoldSelectWithIdentityConstant(unsigned BinOpcode,
  2511. EVT VT) const {
  2512. return false;
  2513. }
  2514. /// Return true if it is beneficial to convert a load of a constant to
  2515. /// just the constant itself.
  2516. /// On some targets it might be more efficient to use a combination of
  2517. /// arithmetic instructions to materialize the constant instead of loading it
  2518. /// from a constant pool.
  2519. virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
  2520. Type *Ty) const {
  2521. return false;
  2522. }
  2523. /// Return true if EXTRACT_SUBVECTOR is cheap for extracting this result type
  2524. /// from this source type with this index. This is needed because
  2525. /// EXTRACT_SUBVECTOR usually has custom lowering that depends on the index of
  2526. /// the first element, and only the target knows which lowering is cheap.
  2527. virtual bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
  2528. unsigned Index) const {
  2529. return false;
  2530. }
  2531. /// Try to convert an extract element of a vector binary operation into an
  2532. /// extract element followed by a scalar operation.
  2533. virtual bool shouldScalarizeBinop(SDValue VecOp) const {
  2534. return false;
  2535. }
  2536. /// Return true if extraction of a scalar element from the given vector type
  2537. /// at the given index is cheap. For example, if scalar operations occur on
  2538. /// the same register file as vector operations, then an extract element may
  2539. /// be a sub-register rename rather than an actual instruction.
  2540. virtual bool isExtractVecEltCheap(EVT VT, unsigned Index) const {
  2541. return false;
  2542. }
  2543. /// Try to convert math with an overflow comparison into the corresponding DAG
  2544. /// node operation. Targets may want to override this independently of whether
  2545. /// the operation is legal/custom for the given type because it may obscure
  2546. /// matching of other patterns.
  2547. virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
  2548. bool MathUsed) const {
  2549. // TODO: The default logic is inherited from code in CodeGenPrepare.
  2550. // The opcode should not make a difference by default?
  2551. if (Opcode != ISD::UADDO)
  2552. return false;
  2553. // Allow the transform as long as we have an integer type that is not
  2554. // obviously illegal and unsupported and if the math result is used
  2555. // besides the overflow check. On some targets (e.g. SPARC), it is
  2556. // not profitable to form on overflow op if the math result has no
  2557. // concrete users.
  2558. if (VT.isVector())
  2559. return false;
  2560. return MathUsed && (VT.isSimple() || !isOperationExpand(Opcode, VT));
  2561. }
  2562. // Return true if it is profitable to use a scalar input to a BUILD_VECTOR
  2563. // even if the vector itself has multiple uses.
  2564. virtual bool aggressivelyPreferBuildVectorSources(EVT VecVT) const {
  2565. return false;
  2566. }
  2567. // Return true if CodeGenPrepare should consider splitting large offset of a
  2568. // GEP to make the GEP fit into the addressing mode and can be sunk into the
  2569. // same blocks of its users.
  2570. virtual bool shouldConsiderGEPOffsetSplit() const { return false; }
  2571. /// Return true if creating a shift of the type by the given
  2572. /// amount is not profitable.
  2573. virtual bool shouldAvoidTransformToShift(EVT VT, unsigned Amount) const {
  2574. return false;
  2575. }
  2576. /// Does this target require the clearing of high-order bits in a register
  2577. /// passed to the fp16 to fp conversion library function.
  2578. virtual bool shouldKeepZExtForFP16Conv() const { return false; }
  2579. /// Should we generate fp_to_si_sat and fp_to_ui_sat from type FPVT to type VT
  2580. /// from min(max(fptoi)) saturation patterns.
  2581. virtual bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const {
  2582. return isOperationLegalOrCustom(Op, VT);
  2583. }
  2584. //===--------------------------------------------------------------------===//
  2585. // Runtime Library hooks
  2586. //
  2587. /// Rename the default libcall routine name for the specified libcall.
  2588. void setLibcallName(RTLIB::Libcall Call, const char *Name) {
  2589. LibcallRoutineNames[Call] = Name;
  2590. }
  2591. /// Get the libcall routine name for the specified libcall.
  2592. const char *getLibcallName(RTLIB::Libcall Call) const {
  2593. return LibcallRoutineNames[Call];
  2594. }
  2595. /// Override the default CondCode to be used to test the result of the
  2596. /// comparison libcall against zero.
  2597. void setCmpLibcallCC(RTLIB::Libcall Call, ISD::CondCode CC) {
  2598. CmpLibcallCCs[Call] = CC;
  2599. }
  2600. /// Get the CondCode that's to be used to test the result of the comparison
  2601. /// libcall against zero.
  2602. ISD::CondCode getCmpLibcallCC(RTLIB::Libcall Call) const {
  2603. return CmpLibcallCCs[Call];
  2604. }
  2605. /// Set the CallingConv that should be used for the specified libcall.
  2606. void setLibcallCallingConv(RTLIB::Libcall Call, CallingConv::ID CC) {
  2607. LibcallCallingConvs[Call] = CC;
  2608. }
  2609. /// Get the CallingConv that should be used for the specified libcall.
  2610. CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const {
  2611. return LibcallCallingConvs[Call];
  2612. }
  2613. /// Execute target specific actions to finalize target lowering.
  2614. /// This is used to set extra flags in MachineFrameInformation and freezing
  2615. /// the set of reserved registers.
  2616. /// The default implementation just freezes the set of reserved registers.
  2617. virtual void finalizeLowering(MachineFunction &MF) const;
  2618. //===----------------------------------------------------------------------===//
  2619. // GlobalISel Hooks
  2620. //===----------------------------------------------------------------------===//
  2621. /// Check whether or not \p MI needs to be moved close to its uses.
  2622. virtual bool shouldLocalize(const MachineInstr &MI, const TargetTransformInfo *TTI) const;
  2623. private:
  2624. const TargetMachine &TM;
  2625. /// Tells the code generator that the target has multiple (allocatable)
  2626. /// condition registers that can be used to store the results of comparisons
  2627. /// for use by selects and conditional branches. With multiple condition
  2628. /// registers, the code generator will not aggressively sink comparisons into
  2629. /// the blocks of their users.
  2630. bool HasMultipleConditionRegisters;
  2631. /// Tells the code generator that the target has BitExtract instructions.
  2632. /// The code generator will aggressively sink "shift"s into the blocks of
  2633. /// their users if the users will generate "and" instructions which can be
  2634. /// combined with "shift" to BitExtract instructions.
  2635. bool HasExtractBitsInsn;
  2636. /// Tells the code generator to bypass slow divide or remainder
  2637. /// instructions. For example, BypassSlowDivWidths[32,8] tells the code
  2638. /// generator to bypass 32-bit integer div/rem with an 8-bit unsigned integer
  2639. /// div/rem when the operands are positive and less than 256.
  2640. DenseMap <unsigned int, unsigned int> BypassSlowDivWidths;
  2641. /// Tells the code generator that it shouldn't generate extra flow control
  2642. /// instructions and should attempt to combine flow control instructions via
  2643. /// predication.
  2644. bool JumpIsExpensive;
  2645. /// Information about the contents of the high-bits in boolean values held in
  2646. /// a type wider than i1. See getBooleanContents.
  2647. BooleanContent BooleanContents;
  2648. /// Information about the contents of the high-bits in boolean values held in
  2649. /// a type wider than i1. See getBooleanContents.
  2650. BooleanContent BooleanFloatContents;
  2651. /// Information about the contents of the high-bits in boolean vector values
  2652. /// when the element type is wider than i1. See getBooleanContents.
  2653. BooleanContent BooleanVectorContents;
  2654. /// The target scheduling preference: shortest possible total cycles or lowest
  2655. /// register usage.
  2656. Sched::Preference SchedPreferenceInfo;
  2657. /// The minimum alignment that any argument on the stack needs to have.
  2658. Align MinStackArgumentAlignment;
  2659. /// The minimum function alignment (used when optimizing for size, and to
  2660. /// prevent explicitly provided alignment from leading to incorrect code).
  2661. Align MinFunctionAlignment;
  2662. /// The preferred function alignment (used when alignment unspecified and
  2663. /// optimizing for speed).
  2664. Align PrefFunctionAlignment;
  2665. /// The preferred loop alignment (in log2 bot in bytes).
  2666. Align PrefLoopAlignment;
  2667. /// The maximum amount of bytes permitted to be emitted for alignment.
  2668. unsigned MaxBytesForAlignment;
  2669. /// Size in bits of the maximum atomics size the backend supports.
  2670. /// Accesses larger than this will be expanded by AtomicExpandPass.
  2671. unsigned MaxAtomicSizeInBitsSupported;
  2672. /// Size in bits of the minimum cmpxchg or ll/sc operation the
  2673. /// backend supports.
  2674. unsigned MinCmpXchgSizeInBits;
  2675. /// This indicates if the target supports unaligned atomic operations.
  2676. bool SupportsUnalignedAtomics;
  2677. /// If set to a physical register, this specifies the register that
  2678. /// llvm.savestack/llvm.restorestack should save and restore.
  2679. Register StackPointerRegisterToSaveRestore;
  2680. /// This indicates the default register class to use for each ValueType the
  2681. /// target supports natively.
  2682. const TargetRegisterClass *RegClassForVT[MVT::VALUETYPE_SIZE];
  2683. uint16_t NumRegistersForVT[MVT::VALUETYPE_SIZE];
  2684. MVT RegisterTypeForVT[MVT::VALUETYPE_SIZE];
  2685. /// This indicates the "representative" register class to use for each
  2686. /// ValueType the target supports natively. This information is used by the
  2687. /// scheduler to track register pressure. By default, the representative
  2688. /// register class is the largest legal super-reg register class of the
  2689. /// register class of the specified type. e.g. On x86, i8, i16, and i32's
  2690. /// representative class would be GR32.
  2691. const TargetRegisterClass *RepRegClassForVT[MVT::VALUETYPE_SIZE];
  2692. /// This indicates the "cost" of the "representative" register class for each
  2693. /// ValueType. The cost is used by the scheduler to approximate register
  2694. /// pressure.
  2695. uint8_t RepRegClassCostForVT[MVT::VALUETYPE_SIZE];
  2696. /// For any value types we are promoting or expanding, this contains the value
  2697. /// type that we are changing to. For Expanded types, this contains one step
  2698. /// of the expand (e.g. i64 -> i32), even if there are multiple steps required
  2699. /// (e.g. i64 -> i16). For types natively supported by the system, this holds
  2700. /// the same type (e.g. i32 -> i32).
  2701. MVT TransformToType[MVT::VALUETYPE_SIZE];
  2702. /// For each operation and each value type, keep a LegalizeAction that
  2703. /// indicates how instruction selection should deal with the operation. Most
  2704. /// operations are Legal (aka, supported natively by the target), but
  2705. /// operations that are not should be described. Note that operations on
  2706. /// non-legal value types are not described here.
  2707. LegalizeAction OpActions[MVT::VALUETYPE_SIZE][ISD::BUILTIN_OP_END];
  2708. /// For each load extension type and each value type, keep a LegalizeAction
  2709. /// that indicates how instruction selection should deal with a load of a
  2710. /// specific value type and extension type. Uses 4-bits to store the action
  2711. /// for each of the 4 load ext types.
  2712. uint16_t LoadExtActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
  2713. /// For each value type pair keep a LegalizeAction that indicates whether a
  2714. /// truncating store of a specific value type and truncating type is legal.
  2715. LegalizeAction TruncStoreActions[MVT::VALUETYPE_SIZE][MVT::VALUETYPE_SIZE];
  2716. /// For each indexed mode and each value type, keep a quad of LegalizeAction
  2717. /// that indicates how instruction selection should deal with the load /
  2718. /// store / maskedload / maskedstore.
  2719. ///
  2720. /// The first dimension is the value_type for the reference. The second
  2721. /// dimension represents the various modes for load store.
  2722. uint16_t IndexedModeActions[MVT::VALUETYPE_SIZE][ISD::LAST_INDEXED_MODE];
  2723. /// For each condition code (ISD::CondCode) keep a LegalizeAction that
  2724. /// indicates how instruction selection should deal with the condition code.
  2725. ///
  2726. /// Because each CC action takes up 4 bits, we need to have the array size be
  2727. /// large enough to fit all of the value types. This can be done by rounding
  2728. /// up the MVT::VALUETYPE_SIZE value to the next multiple of 8.
  2729. uint32_t CondCodeActions[ISD::SETCC_INVALID][(MVT::VALUETYPE_SIZE + 7) / 8];
  2730. ValueTypeActionImpl ValueTypeActions;
  2731. private:
  2732. LegalizeKind getTypeConversion(LLVMContext &Context, EVT VT) const;
  2733. /// Targets can specify ISD nodes that they would like PerformDAGCombine
  2734. /// callbacks for by calling setTargetDAGCombine(), which sets a bit in this
  2735. /// array.
  2736. unsigned char
  2737. TargetDAGCombineArray[(ISD::BUILTIN_OP_END+CHAR_BIT-1)/CHAR_BIT];
  2738. /// For operations that must be promoted to a specific type, this holds the
  2739. /// destination type. This map should be sparse, so don't hold it as an
  2740. /// array.
  2741. ///
  2742. /// Targets add entries to this map with AddPromotedToType(..), clients access
  2743. /// this with getTypeToPromoteTo(..).
  2744. std::map<std::pair<unsigned, MVT::SimpleValueType>, MVT::SimpleValueType>
  2745. PromoteToType;
  2746. /// Stores the name each libcall.
  2747. const char *LibcallRoutineNames[RTLIB::UNKNOWN_LIBCALL + 1];
  2748. /// The ISD::CondCode that should be used to test the result of each of the
  2749. /// comparison libcall against zero.
  2750. ISD::CondCode CmpLibcallCCs[RTLIB::UNKNOWN_LIBCALL];
  2751. /// Stores the CallingConv that should be used for each libcall.
  2752. CallingConv::ID LibcallCallingConvs[RTLIB::UNKNOWN_LIBCALL];
  2753. /// Set default libcall names and calling conventions.
  2754. void InitLibcalls(const Triple &TT);
  2755. /// The bits of IndexedModeActions used to store the legalisation actions
  2756. /// We store the data as | ML | MS | L | S | each taking 4 bits.
  2757. enum IndexedModeActionsBits {
  2758. IMAB_Store = 0,
  2759. IMAB_Load = 4,
  2760. IMAB_MaskedStore = 8,
  2761. IMAB_MaskedLoad = 12
  2762. };
  2763. void setIndexedModeAction(unsigned IdxMode, MVT VT, unsigned Shift,
  2764. LegalizeAction Action) {
  2765. assert(VT.isValid() && IdxMode < ISD::LAST_INDEXED_MODE &&
  2766. (unsigned)Action < 0xf && "Table isn't big enough!");
  2767. unsigned Ty = (unsigned)VT.SimpleTy;
  2768. IndexedModeActions[Ty][IdxMode] &= ~(0xf << Shift);
  2769. IndexedModeActions[Ty][IdxMode] |= ((uint16_t)Action) << Shift;
  2770. }
  2771. LegalizeAction getIndexedModeAction(unsigned IdxMode, MVT VT,
  2772. unsigned Shift) const {
  2773. assert(IdxMode < ISD::LAST_INDEXED_MODE && VT.isValid() &&
  2774. "Table isn't big enough!");
  2775. unsigned Ty = (unsigned)VT.SimpleTy;
  2776. return (LegalizeAction)((IndexedModeActions[Ty][IdxMode] >> Shift) & 0xf);
  2777. }
  2778. protected:
  2779. /// Return true if the extension represented by \p I is free.
  2780. /// \pre \p I is a sign, zero, or fp extension and
  2781. /// is[Z|FP]ExtFree of the related types is not true.
  2782. virtual bool isExtFreeImpl(const Instruction *I) const { return false; }
  2783. /// Depth that GatherAllAliases should should continue looking for chain
  2784. /// dependencies when trying to find a more preferable chain. As an
  2785. /// approximation, this should be more than the number of consecutive stores
  2786. /// expected to be merged.
  2787. unsigned GatherAllAliasesMaxDepth;
  2788. /// \brief Specify maximum number of store instructions per memset call.
  2789. ///
  2790. /// When lowering \@llvm.memset this field specifies the maximum number of
  2791. /// store operations that may be substituted for the call to memset. Targets
  2792. /// must set this value based on the cost threshold for that target. Targets
  2793. /// should assume that the memset will be done using as many of the largest
  2794. /// store operations first, followed by smaller ones, if necessary, per
  2795. /// alignment restrictions. For example, storing 9 bytes on a 32-bit machine
  2796. /// with 16-bit alignment would result in four 2-byte stores and one 1-byte
  2797. /// store. This only applies to setting a constant array of a constant size.
  2798. unsigned MaxStoresPerMemset;
  2799. /// Likewise for functions with the OptSize attribute.
  2800. unsigned MaxStoresPerMemsetOptSize;
  2801. /// \brief Specify maximum number of store instructions per memcpy call.
  2802. ///
  2803. /// When lowering \@llvm.memcpy this field specifies the maximum number of
  2804. /// store operations that may be substituted for a call to memcpy. Targets
  2805. /// must set this value based on the cost threshold for that target. Targets
  2806. /// should assume that the memcpy will be done using as many of the largest
  2807. /// store operations first, followed by smaller ones, if necessary, per
  2808. /// alignment restrictions. For example, storing 7 bytes on a 32-bit machine
  2809. /// with 32-bit alignment would result in one 4-byte store, a one 2-byte store
  2810. /// and one 1-byte store. This only applies to copying a constant array of
  2811. /// constant size.
  2812. unsigned MaxStoresPerMemcpy;
  2813. /// Likewise for functions with the OptSize attribute.
  2814. unsigned MaxStoresPerMemcpyOptSize;
  2815. /// \brief Specify max number of store instructions to glue in inlined memcpy.
  2816. ///
  2817. /// When memcpy is inlined based on MaxStoresPerMemcpy, specify maximum number
  2818. /// of store instructions to keep together. This helps in pairing and
  2819. // vectorization later on.
  2820. unsigned MaxGluedStoresPerMemcpy = 0;
  2821. /// \brief Specify maximum number of load instructions per memcmp call.
  2822. ///
  2823. /// When lowering \@llvm.memcmp this field specifies the maximum number of
  2824. /// pairs of load operations that may be substituted for a call to memcmp.
  2825. /// Targets must set this value based on the cost threshold for that target.
  2826. /// Targets should assume that the memcmp will be done using as many of the
  2827. /// largest load operations first, followed by smaller ones, if necessary, per
  2828. /// alignment restrictions. For example, loading 7 bytes on a 32-bit machine
  2829. /// with 32-bit alignment would result in one 4-byte load, a one 2-byte load
  2830. /// and one 1-byte load. This only applies to copying a constant array of
  2831. /// constant size.
  2832. unsigned MaxLoadsPerMemcmp;
  2833. /// Likewise for functions with the OptSize attribute.
  2834. unsigned MaxLoadsPerMemcmpOptSize;
  2835. /// \brief Specify maximum number of store instructions per memmove call.
  2836. ///
  2837. /// When lowering \@llvm.memmove this field specifies the maximum number of
  2838. /// store instructions that may be substituted for a call to memmove. Targets
  2839. /// must set this value based on the cost threshold for that target. Targets
  2840. /// should assume that the memmove will be done using as many of the largest
  2841. /// store operations first, followed by smaller ones, if necessary, per
  2842. /// alignment restrictions. For example, moving 9 bytes on a 32-bit machine
  2843. /// with 8-bit alignment would result in nine 1-byte stores. This only
  2844. /// applies to copying a constant array of constant size.
  2845. unsigned MaxStoresPerMemmove;
  2846. /// Likewise for functions with the OptSize attribute.
  2847. unsigned MaxStoresPerMemmoveOptSize;
  2848. /// Tells the code generator that select is more expensive than a branch if
  2849. /// the branch is usually predicted right.
  2850. bool PredictableSelectIsExpensive;
  2851. /// \see enableExtLdPromotion.
  2852. bool EnableExtLdPromotion;
  2853. /// Return true if the value types that can be represented by the specified
  2854. /// register class are all legal.
  2855. bool isLegalRC(const TargetRegisterInfo &TRI,
  2856. const TargetRegisterClass &RC) const;
  2857. /// Replace/modify any TargetFrameIndex operands with a targte-dependent
  2858. /// sequence of memory operands that is recognized by PrologEpilogInserter.
  2859. MachineBasicBlock *emitPatchPoint(MachineInstr &MI,
  2860. MachineBasicBlock *MBB) const;
  2861. bool IsStrictFPEnabled;
  2862. };
  2863. /// This class defines information used to lower LLVM code to legal SelectionDAG
  2864. /// operators that the target instruction selector can accept natively.
  2865. ///
  2866. /// This class also defines callbacks that targets must implement to lower
  2867. /// target-specific constructs to SelectionDAG operators.
  2868. class TargetLowering : public TargetLoweringBase {
  2869. public:
  2870. struct DAGCombinerInfo;
  2871. struct MakeLibCallOptions;
  2872. TargetLowering(const TargetLowering &) = delete;
  2873. TargetLowering &operator=(const TargetLowering &) = delete;
  2874. explicit TargetLowering(const TargetMachine &TM);
  2875. bool isPositionIndependent() const;
  2876. virtual bool isSDNodeSourceOfDivergence(const SDNode *N,
  2877. FunctionLoweringInfo *FLI,
  2878. LegacyDivergenceAnalysis *DA) const {
  2879. return false;
  2880. }
  2881. // Lets target to control the following reassociation of operands: (op (op x,
  2882. // c1), y) -> (op (op x, y), c1) where N0 is (op x, c1) and N1 is y. By
  2883. // default consider profitable any case where N0 has single use. This
  2884. // behavior reflects the condition replaced by this target hook call in the
  2885. // DAGCombiner. Any particular target can implement its own heuristic to
  2886. // restrict common combiner.
  2887. virtual bool isReassocProfitable(SelectionDAG &DAG, SDValue N0,
  2888. SDValue N1) const {
  2889. return N0.hasOneUse();
  2890. }
  2891. virtual bool isSDNodeAlwaysUniform(const SDNode * N) const {
  2892. return false;
  2893. }
  2894. /// Returns true by value, base pointer and offset pointer and addressing mode
  2895. /// by reference if the node's address can be legally represented as
  2896. /// pre-indexed load / store address.
  2897. virtual bool getPreIndexedAddressParts(SDNode * /*N*/, SDValue &/*Base*/,
  2898. SDValue &/*Offset*/,
  2899. ISD::MemIndexedMode &/*AM*/,
  2900. SelectionDAG &/*DAG*/) const {
  2901. return false;
  2902. }
  2903. /// Returns true by value, base pointer and offset pointer and addressing mode
  2904. /// by reference if this node can be combined with a load / store to form a
  2905. /// post-indexed load / store.
  2906. virtual bool getPostIndexedAddressParts(SDNode * /*N*/, SDNode * /*Op*/,
  2907. SDValue &/*Base*/,
  2908. SDValue &/*Offset*/,
  2909. ISD::MemIndexedMode &/*AM*/,
  2910. SelectionDAG &/*DAG*/) const {
  2911. return false;
  2912. }
  2913. /// Returns true if the specified base+offset is a legal indexed addressing
  2914. /// mode for this target. \p MI is the load or store instruction that is being
  2915. /// considered for transformation.
  2916. virtual bool isIndexingLegal(MachineInstr &MI, Register Base, Register Offset,
  2917. bool IsPre, MachineRegisterInfo &MRI) const {
  2918. return false;
  2919. }
  2920. /// Return the entry encoding for a jump table in the current function. The
  2921. /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
  2922. virtual unsigned getJumpTableEncoding() const;
  2923. virtual const MCExpr *
  2924. LowerCustomJumpTableEntry(const MachineJumpTableInfo * /*MJTI*/,
  2925. const MachineBasicBlock * /*MBB*/, unsigned /*uid*/,
  2926. MCContext &/*Ctx*/) const {
  2927. llvm_unreachable("Need to implement this hook if target has custom JTIs");
  2928. }
  2929. /// Returns relocation base for the given PIC jumptable.
  2930. virtual SDValue getPICJumpTableRelocBase(SDValue Table,
  2931. SelectionDAG &DAG) const;
  2932. /// This returns the relocation base for the given PIC jumptable, the same as
  2933. /// getPICJumpTableRelocBase, but as an MCExpr.
  2934. virtual const MCExpr *
  2935. getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
  2936. unsigned JTI, MCContext &Ctx) const;
  2937. /// Return true if folding a constant offset with the given GlobalAddress is
  2938. /// legal. It is frequently not legal in PIC relocation models.
  2939. virtual bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const;
  2940. bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
  2941. SDValue &Chain) const;
  2942. void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
  2943. SDValue &NewRHS, ISD::CondCode &CCCode,
  2944. const SDLoc &DL, const SDValue OldLHS,
  2945. const SDValue OldRHS) const;
  2946. void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS,
  2947. SDValue &NewRHS, ISD::CondCode &CCCode,
  2948. const SDLoc &DL, const SDValue OldLHS,
  2949. const SDValue OldRHS, SDValue &Chain,
  2950. bool IsSignaling = false) const;
  2951. /// Returns a pair of (return value, chain).
  2952. /// It is an error to pass RTLIB::UNKNOWN_LIBCALL as \p LC.
  2953. std::pair<SDValue, SDValue> makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC,
  2954. EVT RetVT, ArrayRef<SDValue> Ops,
  2955. MakeLibCallOptions CallOptions,
  2956. const SDLoc &dl,
  2957. SDValue Chain = SDValue()) const;
  2958. /// Check whether parameters to a call that are passed in callee saved
  2959. /// registers are the same as from the calling function. This needs to be
  2960. /// checked for tail call eligibility.
  2961. bool parametersInCSRMatch(const MachineRegisterInfo &MRI,
  2962. const uint32_t *CallerPreservedMask,
  2963. const SmallVectorImpl<CCValAssign> &ArgLocs,
  2964. const SmallVectorImpl<SDValue> &OutVals) const;
  2965. //===--------------------------------------------------------------------===//
  2966. // TargetLowering Optimization Methods
  2967. //
  2968. /// A convenience struct that encapsulates a DAG, and two SDValues for
  2969. /// returning information from TargetLowering to its clients that want to
  2970. /// combine.
  2971. struct TargetLoweringOpt {
  2972. SelectionDAG &DAG;
  2973. bool LegalTys;
  2974. bool LegalOps;
  2975. SDValue Old;
  2976. SDValue New;
  2977. explicit TargetLoweringOpt(SelectionDAG &InDAG,
  2978. bool LT, bool LO) :
  2979. DAG(InDAG), LegalTys(LT), LegalOps(LO) {}
  2980. bool LegalTypes() const { return LegalTys; }
  2981. bool LegalOperations() const { return LegalOps; }
  2982. bool CombineTo(SDValue O, SDValue N) {
  2983. Old = O;
  2984. New = N;
  2985. return true;
  2986. }
  2987. };
  2988. /// Determines the optimal series of memory ops to replace the memset / memcpy.
  2989. /// Return true if the number of memory ops is below the threshold (Limit).
  2990. /// It returns the types of the sequence of memory ops to perform
  2991. /// memset / memcpy by reference.
  2992. bool findOptimalMemOpLowering(std::vector<EVT> &MemOps, unsigned Limit,
  2993. const MemOp &Op, unsigned DstAS, unsigned SrcAS,
  2994. const AttributeList &FuncAttributes) const;
  2995. /// Check to see if the specified operand of the specified instruction is a
  2996. /// constant integer. If so, check to see if there are any bits set in the
  2997. /// constant that are not demanded. If so, shrink the constant and return
  2998. /// true.
  2999. bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
  3000. const APInt &DemandedElts,
  3001. TargetLoweringOpt &TLO) const;
  3002. /// Helper wrapper around ShrinkDemandedConstant, demanding all elements.
  3003. bool ShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
  3004. TargetLoweringOpt &TLO) const;
  3005. // Target hook to do target-specific const optimization, which is called by
  3006. // ShrinkDemandedConstant. This function should return true if the target
  3007. // doesn't want ShrinkDemandedConstant to further optimize the constant.
  3008. virtual bool targetShrinkDemandedConstant(SDValue Op,
  3009. const APInt &DemandedBits,
  3010. const APInt &DemandedElts,
  3011. TargetLoweringOpt &TLO) const {
  3012. return false;
  3013. }
  3014. /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. This
  3015. /// uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
  3016. /// generalized for targets with other types of implicit widening casts.
  3017. bool ShrinkDemandedOp(SDValue Op, unsigned BitWidth, const APInt &Demanded,
  3018. TargetLoweringOpt &TLO) const;
  3019. /// Look at Op. At this point, we know that only the DemandedBits bits of the
  3020. /// result of Op are ever used downstream. If we can use this information to
  3021. /// simplify Op, create a new simplified DAG node and return true, returning
  3022. /// the original and new nodes in Old and New. Otherwise, analyze the
  3023. /// expression and return a mask of KnownOne and KnownZero bits for the
  3024. /// expression (used to simplify the caller). The KnownZero/One bits may only
  3025. /// be accurate for those bits in the Demanded masks.
  3026. /// \p AssumeSingleUse When this parameter is true, this function will
  3027. /// attempt to simplify \p Op even if there are multiple uses.
  3028. /// Callers are responsible for correctly updating the DAG based on the
  3029. /// results of this function, because simply replacing replacing TLO.Old
  3030. /// with TLO.New will be incorrect when this parameter is true and TLO.Old
  3031. /// has multiple uses.
  3032. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  3033. const APInt &DemandedElts, KnownBits &Known,
  3034. TargetLoweringOpt &TLO, unsigned Depth = 0,
  3035. bool AssumeSingleUse = false) const;
  3036. /// Helper wrapper around SimplifyDemandedBits, demanding all elements.
  3037. /// Adds Op back to the worklist upon success.
  3038. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  3039. KnownBits &Known, TargetLoweringOpt &TLO,
  3040. unsigned Depth = 0,
  3041. bool AssumeSingleUse = false) const;
  3042. /// Helper wrapper around SimplifyDemandedBits.
  3043. /// Adds Op back to the worklist upon success.
  3044. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  3045. DAGCombinerInfo &DCI) const;
  3046. /// Helper wrapper around SimplifyDemandedBits.
  3047. /// Adds Op back to the worklist upon success.
  3048. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  3049. const APInt &DemandedElts,
  3050. DAGCombinerInfo &DCI) const;
  3051. /// More limited version of SimplifyDemandedBits that can be used to "look
  3052. /// through" ops that don't contribute to the DemandedBits/DemandedElts -
  3053. /// bitwise ops etc.
  3054. SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
  3055. const APInt &DemandedElts,
  3056. SelectionDAG &DAG,
  3057. unsigned Depth = 0) const;
  3058. /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
  3059. /// elements.
  3060. SDValue SimplifyMultipleUseDemandedBits(SDValue Op, const APInt &DemandedBits,
  3061. SelectionDAG &DAG,
  3062. unsigned Depth = 0) const;
  3063. /// Helper wrapper around SimplifyMultipleUseDemandedBits, demanding all
  3064. /// bits from only some vector elements.
  3065. SDValue SimplifyMultipleUseDemandedVectorElts(SDValue Op,
  3066. const APInt &DemandedElts,
  3067. SelectionDAG &DAG,
  3068. unsigned Depth = 0) const;
  3069. /// Look at Vector Op. At this point, we know that only the DemandedElts
  3070. /// elements of the result of Op are ever used downstream. If we can use
  3071. /// this information to simplify Op, create a new simplified DAG node and
  3072. /// return true, storing the original and new nodes in TLO.
  3073. /// Otherwise, analyze the expression and return a mask of KnownUndef and
  3074. /// KnownZero elements for the expression (used to simplify the caller).
  3075. /// The KnownUndef/Zero elements may only be accurate for those bits
  3076. /// in the DemandedMask.
  3077. /// \p AssumeSingleUse When this parameter is true, this function will
  3078. /// attempt to simplify \p Op even if there are multiple uses.
  3079. /// Callers are responsible for correctly updating the DAG based on the
  3080. /// results of this function, because simply replacing replacing TLO.Old
  3081. /// with TLO.New will be incorrect when this parameter is true and TLO.Old
  3082. /// has multiple uses.
  3083. bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedEltMask,
  3084. APInt &KnownUndef, APInt &KnownZero,
  3085. TargetLoweringOpt &TLO, unsigned Depth = 0,
  3086. bool AssumeSingleUse = false) const;
  3087. /// Helper wrapper around SimplifyDemandedVectorElts.
  3088. /// Adds Op back to the worklist upon success.
  3089. bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
  3090. APInt &KnownUndef, APInt &KnownZero,
  3091. DAGCombinerInfo &DCI) const;
  3092. /// Determine which of the bits specified in Mask are known to be either zero
  3093. /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
  3094. /// argument allows us to only collect the known bits that are shared by the
  3095. /// requested vector elements.
  3096. virtual void computeKnownBitsForTargetNode(const SDValue Op,
  3097. KnownBits &Known,
  3098. const APInt &DemandedElts,
  3099. const SelectionDAG &DAG,
  3100. unsigned Depth = 0) const;
  3101. /// Determine which of the bits specified in Mask are known to be either zero
  3102. /// or one and return them in the KnownZero/KnownOne bitsets. The DemandedElts
  3103. /// argument allows us to only collect the known bits that are shared by the
  3104. /// requested vector elements. This is for GISel.
  3105. virtual void computeKnownBitsForTargetInstr(GISelKnownBits &Analysis,
  3106. Register R, KnownBits &Known,
  3107. const APInt &DemandedElts,
  3108. const MachineRegisterInfo &MRI,
  3109. unsigned Depth = 0) const;
  3110. /// Determine the known alignment for the pointer value \p R. This is can
  3111. /// typically be inferred from the number of low known 0 bits. However, for a
  3112. /// pointer with a non-integral address space, the alignment value may be
  3113. /// independent from the known low bits.
  3114. virtual Align computeKnownAlignForTargetInstr(GISelKnownBits &Analysis,
  3115. Register R,
  3116. const MachineRegisterInfo &MRI,
  3117. unsigned Depth = 0) const;
  3118. /// Determine which of the bits of FrameIndex \p FIOp are known to be 0.
  3119. /// Default implementation computes low bits based on alignment
  3120. /// information. This should preserve known bits passed into it.
  3121. virtual void computeKnownBitsForFrameIndex(int FIOp,
  3122. KnownBits &Known,
  3123. const MachineFunction &MF) const;
  3124. /// This method can be implemented by targets that want to expose additional
  3125. /// information about sign bits to the DAG Combiner. The DemandedElts
  3126. /// argument allows us to only collect the minimum sign bits that are shared
  3127. /// by the requested vector elements.
  3128. virtual unsigned ComputeNumSignBitsForTargetNode(SDValue Op,
  3129. const APInt &DemandedElts,
  3130. const SelectionDAG &DAG,
  3131. unsigned Depth = 0) const;
  3132. /// This method can be implemented by targets that want to expose additional
  3133. /// information about sign bits to GlobalISel combiners. The DemandedElts
  3134. /// argument allows us to only collect the minimum sign bits that are shared
  3135. /// by the requested vector elements.
  3136. virtual unsigned computeNumSignBitsForTargetInstr(GISelKnownBits &Analysis,
  3137. Register R,
  3138. const APInt &DemandedElts,
  3139. const MachineRegisterInfo &MRI,
  3140. unsigned Depth = 0) const;
  3141. /// Attempt to simplify any target nodes based on the demanded vector
  3142. /// elements, returning true on success. Otherwise, analyze the expression and
  3143. /// return a mask of KnownUndef and KnownZero elements for the expression
  3144. /// (used to simplify the caller). The KnownUndef/Zero elements may only be
  3145. /// accurate for those bits in the DemandedMask.
  3146. virtual bool SimplifyDemandedVectorEltsForTargetNode(
  3147. SDValue Op, const APInt &DemandedElts, APInt &KnownUndef,
  3148. APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth = 0) const;
  3149. /// Attempt to simplify any target nodes based on the demanded bits/elts,
  3150. /// returning true on success. Otherwise, analyze the
  3151. /// expression and return a mask of KnownOne and KnownZero bits for the
  3152. /// expression (used to simplify the caller). The KnownZero/One bits may only
  3153. /// be accurate for those bits in the Demanded masks.
  3154. virtual bool SimplifyDemandedBitsForTargetNode(SDValue Op,
  3155. const APInt &DemandedBits,
  3156. const APInt &DemandedElts,
  3157. KnownBits &Known,
  3158. TargetLoweringOpt &TLO,
  3159. unsigned Depth = 0) const;
  3160. /// More limited version of SimplifyDemandedBits that can be used to "look
  3161. /// through" ops that don't contribute to the DemandedBits/DemandedElts -
  3162. /// bitwise ops etc.
  3163. virtual SDValue SimplifyMultipleUseDemandedBitsForTargetNode(
  3164. SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
  3165. SelectionDAG &DAG, unsigned Depth) const;
  3166. /// Return true if this function can prove that \p Op is never poison
  3167. /// and, if \p PoisonOnly is false, does not have undef bits. The DemandedElts
  3168. /// argument limits the check to the requested vector elements.
  3169. virtual bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(
  3170. SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
  3171. bool PoisonOnly, unsigned Depth) const;
  3172. /// Tries to build a legal vector shuffle using the provided parameters
  3173. /// or equivalent variations. The Mask argument maybe be modified as the
  3174. /// function tries different variations.
  3175. /// Returns an empty SDValue if the operation fails.
  3176. SDValue buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
  3177. SDValue N1, MutableArrayRef<int> Mask,
  3178. SelectionDAG &DAG) const;
  3179. /// This method returns the constant pool value that will be loaded by LD.
  3180. /// NOTE: You must check for implicit extensions of the constant by LD.
  3181. virtual const Constant *getTargetConstantFromLoad(LoadSDNode *LD) const;
  3182. /// If \p SNaN is false, \returns true if \p Op is known to never be any
  3183. /// NaN. If \p sNaN is true, returns if \p Op is known to never be a signaling
  3184. /// NaN.
  3185. virtual bool isKnownNeverNaNForTargetNode(SDValue Op,
  3186. const SelectionDAG &DAG,
  3187. bool SNaN = false,
  3188. unsigned Depth = 0) const;
  3189. /// Return true if vector \p Op has the same value across all \p DemandedElts,
  3190. /// indicating any elements which may be undef in the output \p UndefElts.
  3191. virtual bool isSplatValueForTargetNode(SDValue Op, const APInt &DemandedElts,
  3192. APInt &UndefElts,
  3193. unsigned Depth = 0) const;
  3194. struct DAGCombinerInfo {
  3195. void *DC; // The DAG Combiner object.
  3196. CombineLevel Level;
  3197. bool CalledByLegalizer;
  3198. public:
  3199. SelectionDAG &DAG;
  3200. DAGCombinerInfo(SelectionDAG &dag, CombineLevel level, bool cl, void *dc)
  3201. : DC(dc), Level(level), CalledByLegalizer(cl), DAG(dag) {}
  3202. bool isBeforeLegalize() const { return Level == BeforeLegalizeTypes; }
  3203. bool isBeforeLegalizeOps() const { return Level < AfterLegalizeVectorOps; }
  3204. bool isAfterLegalizeDAG() const { return Level >= AfterLegalizeDAG; }
  3205. CombineLevel getDAGCombineLevel() { return Level; }
  3206. bool isCalledByLegalizer() const { return CalledByLegalizer; }
  3207. void AddToWorklist(SDNode *N);
  3208. SDValue CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo = true);
  3209. SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true);
  3210. SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo = true);
  3211. bool recursivelyDeleteUnusedNodes(SDNode *N);
  3212. void CommitTargetLoweringOpt(const TargetLoweringOpt &TLO);
  3213. };
  3214. /// Return if the N is a constant or constant vector equal to the true value
  3215. /// from getBooleanContents().
  3216. bool isConstTrueVal(SDValue N) const;
  3217. /// Return if the N is a constant or constant vector equal to the false value
  3218. /// from getBooleanContents().
  3219. bool isConstFalseVal(SDValue N) const;
  3220. /// Return if \p N is a True value when extended to \p VT.
  3221. bool isExtendedTrueVal(const ConstantSDNode *N, EVT VT, bool SExt) const;
  3222. /// Try to simplify a setcc built with the specified operands and cc. If it is
  3223. /// unable to simplify it, return a null SDValue.
  3224. SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  3225. bool foldBooleans, DAGCombinerInfo &DCI,
  3226. const SDLoc &dl) const;
  3227. // For targets which wrap address, unwrap for analysis.
  3228. virtual SDValue unwrapAddress(SDValue N) const { return N; }
  3229. /// Returns true (and the GlobalValue and the offset) if the node is a
  3230. /// GlobalAddress + offset.
  3231. virtual bool
  3232. isGAPlusOffset(SDNode *N, const GlobalValue* &GA, int64_t &Offset) const;
  3233. /// This method will be invoked for all target nodes and for any
  3234. /// target-independent nodes that the target has registered with invoke it
  3235. /// for.
  3236. ///
  3237. /// The semantics are as follows:
  3238. /// Return Value:
  3239. /// SDValue.Val == 0 - No change was made
  3240. /// SDValue.Val == N - N was replaced, is dead, and is already handled.
  3241. /// otherwise - N should be replaced by the returned Operand.
  3242. ///
  3243. /// In addition, methods provided by DAGCombinerInfo may be used to perform
  3244. /// more complex transformations.
  3245. ///
  3246. virtual SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const;
  3247. /// Return true if it is profitable to move this shift by a constant amount
  3248. /// though its operand, adjusting any immediate operands as necessary to
  3249. /// preserve semantics. This transformation may not be desirable if it
  3250. /// disrupts a particularly auspicious target-specific tree (e.g. bitfield
  3251. /// extraction in AArch64). By default, it returns true.
  3252. ///
  3253. /// @param N the shift node
  3254. /// @param Level the current DAGCombine legalization level.
  3255. virtual bool isDesirableToCommuteWithShift(const SDNode *N,
  3256. CombineLevel Level) const {
  3257. return true;
  3258. }
  3259. /// Return true if the target has native support for the specified value type
  3260. /// and it is 'desirable' to use the type for the given node type. e.g. On x86
  3261. /// i16 is legal, but undesirable since i16 instruction encodings are longer
  3262. /// and some i16 instructions are slow.
  3263. virtual bool isTypeDesirableForOp(unsigned /*Opc*/, EVT VT) const {
  3264. // By default, assume all legal types are desirable.
  3265. return isTypeLegal(VT);
  3266. }
  3267. /// Return true if it is profitable for dag combiner to transform a floating
  3268. /// point op of specified opcode to a equivalent op of an integer
  3269. /// type. e.g. f32 load -> i32 load can be profitable on ARM.
  3270. virtual bool isDesirableToTransformToIntegerOp(unsigned /*Opc*/,
  3271. EVT /*VT*/) const {
  3272. return false;
  3273. }
  3274. /// This method query the target whether it is beneficial for dag combiner to
  3275. /// promote the specified node. If true, it should return the desired
  3276. /// promotion type by reference.
  3277. virtual bool IsDesirableToPromoteOp(SDValue /*Op*/, EVT &/*PVT*/) const {
  3278. return false;
  3279. }
  3280. /// Return true if the target supports swifterror attribute. It optimizes
  3281. /// loads and stores to reading and writing a specific register.
  3282. virtual bool supportSwiftError() const {
  3283. return false;
  3284. }
  3285. /// Return true if the target supports that a subset of CSRs for the given
  3286. /// machine function is handled explicitly via copies.
  3287. virtual bool supportSplitCSR(MachineFunction *MF) const {
  3288. return false;
  3289. }
  3290. /// Perform necessary initialization to handle a subset of CSRs explicitly
  3291. /// via copies. This function is called at the beginning of instruction
  3292. /// selection.
  3293. virtual void initializeSplitCSR(MachineBasicBlock *Entry) const {
  3294. llvm_unreachable("Not Implemented");
  3295. }
  3296. /// Insert explicit copies in entry and exit blocks. We copy a subset of
  3297. /// CSRs to virtual registers in the entry block, and copy them back to
  3298. /// physical registers in the exit blocks. This function is called at the end
  3299. /// of instruction selection.
  3300. virtual void insertCopiesSplitCSR(
  3301. MachineBasicBlock *Entry,
  3302. const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
  3303. llvm_unreachable("Not Implemented");
  3304. }
  3305. /// Return the newly negated expression if the cost is not expensive and
  3306. /// set the cost in \p Cost to indicate that if it is cheaper or neutral to
  3307. /// do the negation.
  3308. virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG,
  3309. bool LegalOps, bool OptForSize,
  3310. NegatibleCost &Cost,
  3311. unsigned Depth = 0) const;
  3312. /// This is the helper function to return the newly negated expression only
  3313. /// when the cost is cheaper.
  3314. SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG,
  3315. bool LegalOps, bool OptForSize,
  3316. unsigned Depth = 0) const {
  3317. NegatibleCost Cost = NegatibleCost::Expensive;
  3318. SDValue Neg =
  3319. getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
  3320. if (Neg && Cost == NegatibleCost::Cheaper)
  3321. return Neg;
  3322. // Remove the new created node to avoid the side effect to the DAG.
  3323. if (Neg && Neg.getNode()->use_empty())
  3324. DAG.RemoveDeadNode(Neg.getNode());
  3325. return SDValue();
  3326. }
  3327. /// This is the helper function to return the newly negated expression if
  3328. /// the cost is not expensive.
  3329. SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps,
  3330. bool OptForSize, unsigned Depth = 0) const {
  3331. NegatibleCost Cost = NegatibleCost::Expensive;
  3332. return getNegatedExpression(Op, DAG, LegalOps, OptForSize, Cost, Depth);
  3333. }
  3334. //===--------------------------------------------------------------------===//
  3335. // Lowering methods - These methods must be implemented by targets so that
  3336. // the SelectionDAGBuilder code knows how to lower these.
  3337. //
  3338. /// Target-specific splitting of values into parts that fit a register
  3339. /// storing a legal type
  3340. virtual bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL,
  3341. SDValue Val, SDValue *Parts,
  3342. unsigned NumParts, MVT PartVT,
  3343. Optional<CallingConv::ID> CC) const {
  3344. return false;
  3345. }
  3346. /// Target-specific combining of register parts into its original value
  3347. virtual SDValue
  3348. joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL,
  3349. const SDValue *Parts, unsigned NumParts,
  3350. MVT PartVT, EVT ValueVT,
  3351. Optional<CallingConv::ID> CC) const {
  3352. return SDValue();
  3353. }
  3354. /// This hook must be implemented to lower the incoming (formal) arguments,
  3355. /// described by the Ins array, into the specified DAG. The implementation
  3356. /// should fill in the InVals array with legal-type argument values, and
  3357. /// return the resulting token chain value.
  3358. virtual SDValue LowerFormalArguments(
  3359. SDValue /*Chain*/, CallingConv::ID /*CallConv*/, bool /*isVarArg*/,
  3360. const SmallVectorImpl<ISD::InputArg> & /*Ins*/, const SDLoc & /*dl*/,
  3361. SelectionDAG & /*DAG*/, SmallVectorImpl<SDValue> & /*InVals*/) const {
  3362. llvm_unreachable("Not Implemented");
  3363. }
  3364. /// This structure contains all information that is necessary for lowering
  3365. /// calls. It is passed to TLI::LowerCallTo when the SelectionDAG builder
  3366. /// needs to lower a call, and targets will see this struct in their LowerCall
  3367. /// implementation.
  3368. struct CallLoweringInfo {
  3369. SDValue Chain;
  3370. Type *RetTy = nullptr;
  3371. bool RetSExt : 1;
  3372. bool RetZExt : 1;
  3373. bool IsVarArg : 1;
  3374. bool IsInReg : 1;
  3375. bool DoesNotReturn : 1;
  3376. bool IsReturnValueUsed : 1;
  3377. bool IsConvergent : 1;
  3378. bool IsPatchPoint : 1;
  3379. bool IsPreallocated : 1;
  3380. bool NoMerge : 1;
  3381. // IsTailCall should be modified by implementations of
  3382. // TargetLowering::LowerCall that perform tail call conversions.
  3383. bool IsTailCall = false;
  3384. // Is Call lowering done post SelectionDAG type legalization.
  3385. bool IsPostTypeLegalization = false;
  3386. unsigned NumFixedArgs = -1;
  3387. CallingConv::ID CallConv = CallingConv::C;
  3388. SDValue Callee;
  3389. ArgListTy Args;
  3390. SelectionDAG &DAG;
  3391. SDLoc DL;
  3392. const CallBase *CB = nullptr;
  3393. SmallVector<ISD::OutputArg, 32> Outs;
  3394. SmallVector<SDValue, 32> OutVals;
  3395. SmallVector<ISD::InputArg, 32> Ins;
  3396. SmallVector<SDValue, 4> InVals;
  3397. CallLoweringInfo(SelectionDAG &DAG)
  3398. : RetSExt(false), RetZExt(false), IsVarArg(false), IsInReg(false),
  3399. DoesNotReturn(false), IsReturnValueUsed(true), IsConvergent(false),
  3400. IsPatchPoint(false), IsPreallocated(false), NoMerge(false),
  3401. DAG(DAG) {}
  3402. CallLoweringInfo &setDebugLoc(const SDLoc &dl) {
  3403. DL = dl;
  3404. return *this;
  3405. }
  3406. CallLoweringInfo &setChain(SDValue InChain) {
  3407. Chain = InChain;
  3408. return *this;
  3409. }
  3410. // setCallee with target/module-specific attributes
  3411. CallLoweringInfo &setLibCallee(CallingConv::ID CC, Type *ResultType,
  3412. SDValue Target, ArgListTy &&ArgsList) {
  3413. RetTy = ResultType;
  3414. Callee = Target;
  3415. CallConv = CC;
  3416. NumFixedArgs = ArgsList.size();
  3417. Args = std::move(ArgsList);
  3418. DAG.getTargetLoweringInfo().markLibCallAttributes(
  3419. &(DAG.getMachineFunction()), CC, Args);
  3420. return *this;
  3421. }
  3422. CallLoweringInfo &setCallee(CallingConv::ID CC, Type *ResultType,
  3423. SDValue Target, ArgListTy &&ArgsList) {
  3424. RetTy = ResultType;
  3425. Callee = Target;
  3426. CallConv = CC;
  3427. NumFixedArgs = ArgsList.size();
  3428. Args = std::move(ArgsList);
  3429. return *this;
  3430. }
  3431. CallLoweringInfo &setCallee(Type *ResultType, FunctionType *FTy,
  3432. SDValue Target, ArgListTy &&ArgsList,
  3433. const CallBase &Call) {
  3434. RetTy = ResultType;
  3435. IsInReg = Call.hasRetAttr(Attribute::InReg);
  3436. DoesNotReturn =
  3437. Call.doesNotReturn() ||
  3438. (!isa<InvokeInst>(Call) && isa<UnreachableInst>(Call.getNextNode()));
  3439. IsVarArg = FTy->isVarArg();
  3440. IsReturnValueUsed = !Call.use_empty();
  3441. RetSExt = Call.hasRetAttr(Attribute::SExt);
  3442. RetZExt = Call.hasRetAttr(Attribute::ZExt);
  3443. NoMerge = Call.hasFnAttr(Attribute::NoMerge);
  3444. Callee = Target;
  3445. CallConv = Call.getCallingConv();
  3446. NumFixedArgs = FTy->getNumParams();
  3447. Args = std::move(ArgsList);
  3448. CB = &Call;
  3449. return *this;
  3450. }
  3451. CallLoweringInfo &setInRegister(bool Value = true) {
  3452. IsInReg = Value;
  3453. return *this;
  3454. }
  3455. CallLoweringInfo &setNoReturn(bool Value = true) {
  3456. DoesNotReturn = Value;
  3457. return *this;
  3458. }
  3459. CallLoweringInfo &setVarArg(bool Value = true) {
  3460. IsVarArg = Value;
  3461. return *this;
  3462. }
  3463. CallLoweringInfo &setTailCall(bool Value = true) {
  3464. IsTailCall = Value;
  3465. return *this;
  3466. }
  3467. CallLoweringInfo &setDiscardResult(bool Value = true) {
  3468. IsReturnValueUsed = !Value;
  3469. return *this;
  3470. }
  3471. CallLoweringInfo &setConvergent(bool Value = true) {
  3472. IsConvergent = Value;
  3473. return *this;
  3474. }
  3475. CallLoweringInfo &setSExtResult(bool Value = true) {
  3476. RetSExt = Value;
  3477. return *this;
  3478. }
  3479. CallLoweringInfo &setZExtResult(bool Value = true) {
  3480. RetZExt = Value;
  3481. return *this;
  3482. }
  3483. CallLoweringInfo &setIsPatchPoint(bool Value = true) {
  3484. IsPatchPoint = Value;
  3485. return *this;
  3486. }
  3487. CallLoweringInfo &setIsPreallocated(bool Value = true) {
  3488. IsPreallocated = Value;
  3489. return *this;
  3490. }
  3491. CallLoweringInfo &setIsPostTypeLegalization(bool Value=true) {
  3492. IsPostTypeLegalization = Value;
  3493. return *this;
  3494. }
  3495. ArgListTy &getArgs() {
  3496. return Args;
  3497. }
  3498. };
  3499. /// This structure is used to pass arguments to makeLibCall function.
  3500. struct MakeLibCallOptions {
  3501. // By passing type list before soften to makeLibCall, the target hook
  3502. // shouldExtendTypeInLibCall can get the original type before soften.
  3503. ArrayRef<EVT> OpsVTBeforeSoften;
  3504. EVT RetVTBeforeSoften;
  3505. bool IsSExt : 1;
  3506. bool DoesNotReturn : 1;
  3507. bool IsReturnValueUsed : 1;
  3508. bool IsPostTypeLegalization : 1;
  3509. bool IsSoften : 1;
  3510. MakeLibCallOptions()
  3511. : IsSExt(false), DoesNotReturn(false), IsReturnValueUsed(true),
  3512. IsPostTypeLegalization(false), IsSoften(false) {}
  3513. MakeLibCallOptions &setSExt(bool Value = true) {
  3514. IsSExt = Value;
  3515. return *this;
  3516. }
  3517. MakeLibCallOptions &setNoReturn(bool Value = true) {
  3518. DoesNotReturn = Value;
  3519. return *this;
  3520. }
  3521. MakeLibCallOptions &setDiscardResult(bool Value = true) {
  3522. IsReturnValueUsed = !Value;
  3523. return *this;
  3524. }
  3525. MakeLibCallOptions &setIsPostTypeLegalization(bool Value = true) {
  3526. IsPostTypeLegalization = Value;
  3527. return *this;
  3528. }
  3529. MakeLibCallOptions &setTypeListBeforeSoften(ArrayRef<EVT> OpsVT, EVT RetVT,
  3530. bool Value = true) {
  3531. OpsVTBeforeSoften = OpsVT;
  3532. RetVTBeforeSoften = RetVT;
  3533. IsSoften = Value;
  3534. return *this;
  3535. }
  3536. };
  3537. /// This function lowers an abstract call to a function into an actual call.
  3538. /// This returns a pair of operands. The first element is the return value
  3539. /// for the function (if RetTy is not VoidTy). The second element is the
  3540. /// outgoing token chain. It calls LowerCall to do the actual lowering.
  3541. std::pair<SDValue, SDValue> LowerCallTo(CallLoweringInfo &CLI) const;
  3542. /// This hook must be implemented to lower calls into the specified
  3543. /// DAG. The outgoing arguments to the call are described by the Outs array,
  3544. /// and the values to be returned by the call are described by the Ins
  3545. /// array. The implementation should fill in the InVals array with legal-type
  3546. /// return values from the call, and return the resulting token chain value.
  3547. virtual SDValue
  3548. LowerCall(CallLoweringInfo &/*CLI*/,
  3549. SmallVectorImpl<SDValue> &/*InVals*/) const {
  3550. llvm_unreachable("Not Implemented");
  3551. }
  3552. /// Target-specific cleanup for formal ByVal parameters.
  3553. virtual void HandleByVal(CCState *, unsigned &, Align) const {}
  3554. /// This hook should be implemented to check whether the return values
  3555. /// described by the Outs array can fit into the return registers. If false
  3556. /// is returned, an sret-demotion is performed.
  3557. virtual bool CanLowerReturn(CallingConv::ID /*CallConv*/,
  3558. MachineFunction &/*MF*/, bool /*isVarArg*/,
  3559. const SmallVectorImpl<ISD::OutputArg> &/*Outs*/,
  3560. LLVMContext &/*Context*/) const
  3561. {
  3562. // Return true by default to get preexisting behavior.
  3563. return true;
  3564. }
  3565. /// This hook must be implemented to lower outgoing return values, described
  3566. /// by the Outs array, into the specified DAG. The implementation should
  3567. /// return the resulting token chain value.
  3568. virtual SDValue LowerReturn(SDValue /*Chain*/, CallingConv::ID /*CallConv*/,
  3569. bool /*isVarArg*/,
  3570. const SmallVectorImpl<ISD::OutputArg> & /*Outs*/,
  3571. const SmallVectorImpl<SDValue> & /*OutVals*/,
  3572. const SDLoc & /*dl*/,
  3573. SelectionDAG & /*DAG*/) const {
  3574. llvm_unreachable("Not Implemented");
  3575. }
  3576. /// Return true if result of the specified node is used by a return node
  3577. /// only. It also compute and return the input chain for the tail call.
  3578. ///
  3579. /// This is used to determine whether it is possible to codegen a libcall as
  3580. /// tail call at legalization time.
  3581. virtual bool isUsedByReturnOnly(SDNode *, SDValue &/*Chain*/) const {
  3582. return false;
  3583. }
  3584. /// Return true if the target may be able emit the call instruction as a tail
  3585. /// call. This is used by optimization passes to determine if it's profitable
  3586. /// to duplicate return instructions to enable tailcall optimization.
  3587. virtual bool mayBeEmittedAsTailCall(const CallInst *) const {
  3588. return false;
  3589. }
  3590. /// Return the builtin name for the __builtin___clear_cache intrinsic
  3591. /// Default is to invoke the clear cache library call
  3592. virtual const char * getClearCacheBuiltinName() const {
  3593. return "__clear_cache";
  3594. }
  3595. /// Return the register ID of the name passed in. Used by named register
  3596. /// global variables extension. There is no target-independent behaviour
  3597. /// so the default action is to bail.
  3598. virtual Register getRegisterByName(const char* RegName, LLT Ty,
  3599. const MachineFunction &MF) const {
  3600. report_fatal_error("Named registers not implemented for this target");
  3601. }
  3602. /// Return the type that should be used to zero or sign extend a
  3603. /// zeroext/signext integer return value. FIXME: Some C calling conventions
  3604. /// require the return type to be promoted, but this is not true all the time,
  3605. /// e.g. i1/i8/i16 on x86/x86_64. It is also not necessary for non-C calling
  3606. /// conventions. The frontend should handle this and include all of the
  3607. /// necessary information.
  3608. virtual EVT getTypeForExtReturn(LLVMContext &Context, EVT VT,
  3609. ISD::NodeType /*ExtendKind*/) const {
  3610. EVT MinVT = getRegisterType(Context, MVT::i32);
  3611. return VT.bitsLT(MinVT) ? MinVT : VT;
  3612. }
  3613. /// For some targets, an LLVM struct type must be broken down into multiple
  3614. /// simple types, but the calling convention specifies that the entire struct
  3615. /// must be passed in a block of consecutive registers.
  3616. virtual bool
  3617. functionArgumentNeedsConsecutiveRegisters(Type *Ty, CallingConv::ID CallConv,
  3618. bool isVarArg,
  3619. const DataLayout &DL) const {
  3620. return false;
  3621. }
  3622. /// For most targets, an LLVM type must be broken down into multiple
  3623. /// smaller types. Usually the halves are ordered according to the endianness
  3624. /// but for some platform that would break. So this method will default to
  3625. /// matching the endianness but can be overridden.
  3626. virtual bool
  3627. shouldSplitFunctionArgumentsAsLittleEndian(const DataLayout &DL) const {
  3628. return DL.isLittleEndian();
  3629. }
  3630. /// Returns a 0 terminated array of registers that can be safely used as
  3631. /// scratch registers.
  3632. virtual const MCPhysReg *getScratchRegisters(CallingConv::ID CC) const {
  3633. return nullptr;
  3634. }
  3635. /// This callback is used to prepare for a volatile or atomic load.
  3636. /// It takes a chain node as input and returns the chain for the load itself.
  3637. ///
  3638. /// Having a callback like this is necessary for targets like SystemZ,
  3639. /// which allows a CPU to reuse the result of a previous load indefinitely,
  3640. /// even if a cache-coherent store is performed by another CPU. The default
  3641. /// implementation does nothing.
  3642. virtual SDValue prepareVolatileOrAtomicLoad(SDValue Chain, const SDLoc &DL,
  3643. SelectionDAG &DAG) const {
  3644. return Chain;
  3645. }
  3646. /// Should SelectionDAG lower an atomic store of the given kind as a normal
  3647. /// StoreSDNode (as opposed to an AtomicSDNode)? NOTE: The intention is to
  3648. /// eventually migrate all targets to the using StoreSDNodes, but porting is
  3649. /// being done target at a time.
  3650. virtual bool lowerAtomicStoreAsStoreSDNode(const StoreInst &SI) const {
  3651. assert(SI.isAtomic() && "violated precondition");
  3652. return false;
  3653. }
  3654. /// Should SelectionDAG lower an atomic load of the given kind as a normal
  3655. /// LoadSDNode (as opposed to an AtomicSDNode)? NOTE: The intention is to
  3656. /// eventually migrate all targets to the using LoadSDNodes, but porting is
  3657. /// being done target at a time.
  3658. virtual bool lowerAtomicLoadAsLoadSDNode(const LoadInst &LI) const {
  3659. assert(LI.isAtomic() && "violated precondition");
  3660. return false;
  3661. }
  3662. /// This callback is invoked by the type legalizer to legalize nodes with an
  3663. /// illegal operand type but legal result types. It replaces the
  3664. /// LowerOperation callback in the type Legalizer. The reason we can not do
  3665. /// away with LowerOperation entirely is that LegalizeDAG isn't yet ready to
  3666. /// use this callback.
  3667. ///
  3668. /// TODO: Consider merging with ReplaceNodeResults.
  3669. ///
  3670. /// The target places new result values for the node in Results (their number
  3671. /// and types must exactly match those of the original return values of
  3672. /// the node), or leaves Results empty, which indicates that the node is not
  3673. /// to be custom lowered after all.
  3674. /// The default implementation calls LowerOperation.
  3675. virtual void LowerOperationWrapper(SDNode *N,
  3676. SmallVectorImpl<SDValue> &Results,
  3677. SelectionDAG &DAG) const;
  3678. /// This callback is invoked for operations that are unsupported by the
  3679. /// target, which are registered to use 'custom' lowering, and whose defined
  3680. /// values are all legal. If the target has no operations that require custom
  3681. /// lowering, it need not implement this. The default implementation of this
  3682. /// aborts.
  3683. virtual SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const;
  3684. /// This callback is invoked when a node result type is illegal for the
  3685. /// target, and the operation was registered to use 'custom' lowering for that
  3686. /// result type. The target places new result values for the node in Results
  3687. /// (their number and types must exactly match those of the original return
  3688. /// values of the node), or leaves Results empty, which indicates that the
  3689. /// node is not to be custom lowered after all.
  3690. ///
  3691. /// If the target has no operations that require custom lowering, it need not
  3692. /// implement this. The default implementation aborts.
  3693. virtual void ReplaceNodeResults(SDNode * /*N*/,
  3694. SmallVectorImpl<SDValue> &/*Results*/,
  3695. SelectionDAG &/*DAG*/) const {
  3696. llvm_unreachable("ReplaceNodeResults not implemented for this target!");
  3697. }
  3698. /// This method returns the name of a target specific DAG node.
  3699. virtual const char *getTargetNodeName(unsigned Opcode) const;
  3700. /// This method returns a target specific FastISel object, or null if the
  3701. /// target does not support "fast" ISel.
  3702. virtual FastISel *createFastISel(FunctionLoweringInfo &,
  3703. const TargetLibraryInfo *) const {
  3704. return nullptr;
  3705. }
  3706. bool verifyReturnAddressArgumentIsConstant(SDValue Op,
  3707. SelectionDAG &DAG) const;
  3708. //===--------------------------------------------------------------------===//
  3709. // Inline Asm Support hooks
  3710. //
  3711. /// This hook allows the target to expand an inline asm call to be explicit
  3712. /// llvm code if it wants to. This is useful for turning simple inline asms
  3713. /// into LLVM intrinsics, which gives the compiler more information about the
  3714. /// behavior of the code.
  3715. virtual bool ExpandInlineAsm(CallInst *) const {
  3716. return false;
  3717. }
  3718. enum ConstraintType {
  3719. C_Register, // Constraint represents specific register(s).
  3720. C_RegisterClass, // Constraint represents any of register(s) in class.
  3721. C_Memory, // Memory constraint.
  3722. C_Immediate, // Requires an immediate.
  3723. C_Other, // Something else.
  3724. C_Unknown // Unsupported constraint.
  3725. };
  3726. enum ConstraintWeight {
  3727. // Generic weights.
  3728. CW_Invalid = -1, // No match.
  3729. CW_Okay = 0, // Acceptable.
  3730. CW_Good = 1, // Good weight.
  3731. CW_Better = 2, // Better weight.
  3732. CW_Best = 3, // Best weight.
  3733. // Well-known weights.
  3734. CW_SpecificReg = CW_Okay, // Specific register operands.
  3735. CW_Register = CW_Good, // Register operands.
  3736. CW_Memory = CW_Better, // Memory operands.
  3737. CW_Constant = CW_Best, // Constant operand.
  3738. CW_Default = CW_Okay // Default or don't know type.
  3739. };
  3740. /// This contains information for each constraint that we are lowering.
  3741. struct AsmOperandInfo : public InlineAsm::ConstraintInfo {
  3742. /// This contains the actual string for the code, like "m". TargetLowering
  3743. /// picks the 'best' code from ConstraintInfo::Codes that most closely
  3744. /// matches the operand.
  3745. std::string ConstraintCode;
  3746. /// Information about the constraint code, e.g. Register, RegisterClass,
  3747. /// Memory, Other, Unknown.
  3748. TargetLowering::ConstraintType ConstraintType = TargetLowering::C_Unknown;
  3749. /// If this is the result output operand or a clobber, this is null,
  3750. /// otherwise it is the incoming operand to the CallInst. This gets
  3751. /// modified as the asm is processed.
  3752. Value *CallOperandVal = nullptr;
  3753. /// The ValueType for the operand value.
  3754. MVT ConstraintVT = MVT::Other;
  3755. /// Copy constructor for copying from a ConstraintInfo.
  3756. AsmOperandInfo(InlineAsm::ConstraintInfo Info)
  3757. : InlineAsm::ConstraintInfo(std::move(Info)) {}
  3758. /// Return true of this is an input operand that is a matching constraint
  3759. /// like "4".
  3760. bool isMatchingInputConstraint() const;
  3761. /// If this is an input matching constraint, this method returns the output
  3762. /// operand it matches.
  3763. unsigned getMatchedOperand() const;
  3764. };
  3765. using AsmOperandInfoVector = std::vector<AsmOperandInfo>;
  3766. /// Split up the constraint string from the inline assembly value into the
  3767. /// specific constraints and their prefixes, and also tie in the associated
  3768. /// operand values. If this returns an empty vector, and if the constraint
  3769. /// string itself isn't empty, there was an error parsing.
  3770. virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL,
  3771. const TargetRegisterInfo *TRI,
  3772. const CallBase &Call) const;
  3773. /// Examine constraint type and operand type and determine a weight value.
  3774. /// The operand object must already have been set up with the operand type.
  3775. virtual ConstraintWeight getMultipleConstraintMatchWeight(
  3776. AsmOperandInfo &info, int maIndex) const;
  3777. /// Examine constraint string and operand type and determine a weight value.
  3778. /// The operand object must already have been set up with the operand type.
  3779. virtual ConstraintWeight getSingleConstraintMatchWeight(
  3780. AsmOperandInfo &info, const char *constraint) const;
  3781. /// Determines the constraint code and constraint type to use for the specific
  3782. /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
  3783. /// If the actual operand being passed in is available, it can be passed in as
  3784. /// Op, otherwise an empty SDValue can be passed.
  3785. virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo,
  3786. SDValue Op,
  3787. SelectionDAG *DAG = nullptr) const;
  3788. /// Given a constraint, return the type of constraint it is for this target.
  3789. virtual ConstraintType getConstraintType(StringRef Constraint) const;
  3790. /// Given a physical register constraint (e.g. {edx}), return the register
  3791. /// number and the register class for the register.
  3792. ///
  3793. /// Given a register class constraint, like 'r', if this corresponds directly
  3794. /// to an LLVM register class, return a register of 0 and the register class
  3795. /// pointer.
  3796. ///
  3797. /// This should only be used for C_Register constraints. On error, this
  3798. /// returns a register number of 0 and a null register class pointer.
  3799. virtual std::pair<unsigned, const TargetRegisterClass *>
  3800. getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
  3801. StringRef Constraint, MVT VT) const;
  3802. virtual unsigned getInlineAsmMemConstraint(StringRef ConstraintCode) const {
  3803. if (ConstraintCode == "m")
  3804. return InlineAsm::Constraint_m;
  3805. if (ConstraintCode == "o")
  3806. return InlineAsm::Constraint_o;
  3807. if (ConstraintCode == "X")
  3808. return InlineAsm::Constraint_X;
  3809. return InlineAsm::Constraint_Unknown;
  3810. }
  3811. /// Try to replace an X constraint, which matches anything, with another that
  3812. /// has more specific requirements based on the type of the corresponding
  3813. /// operand. This returns null if there is no replacement to make.
  3814. virtual const char *LowerXConstraint(EVT ConstraintVT) const;
  3815. /// Lower the specified operand into the Ops vector. If it is invalid, don't
  3816. /// add anything to Ops.
  3817. virtual void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
  3818. std::vector<SDValue> &Ops,
  3819. SelectionDAG &DAG) const;
  3820. // Lower custom output constraints. If invalid, return SDValue().
  3821. virtual SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag,
  3822. const SDLoc &DL,
  3823. const AsmOperandInfo &OpInfo,
  3824. SelectionDAG &DAG) const;
  3825. //===--------------------------------------------------------------------===//
  3826. // Div utility functions
  3827. //
  3828. SDValue BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
  3829. SmallVectorImpl<SDNode *> &Created) const;
  3830. SDValue BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
  3831. SmallVectorImpl<SDNode *> &Created) const;
  3832. /// Targets may override this function to provide custom SDIV lowering for
  3833. /// power-of-2 denominators. If the target returns an empty SDValue, LLVM
  3834. /// assumes SDIV is expensive and replaces it with a series of other integer
  3835. /// operations.
  3836. virtual SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor,
  3837. SelectionDAG &DAG,
  3838. SmallVectorImpl<SDNode *> &Created) const;
  3839. /// Indicate whether this target prefers to combine FDIVs with the same
  3840. /// divisor. If the transform should never be done, return zero. If the
  3841. /// transform should be done, return the minimum number of divisor uses
  3842. /// that must exist.
  3843. virtual unsigned combineRepeatedFPDivisors() const {
  3844. return 0;
  3845. }
  3846. /// Hooks for building estimates in place of slower divisions and square
  3847. /// roots.
  3848. /// Return either a square root or its reciprocal estimate value for the input
  3849. /// operand.
  3850. /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
  3851. /// 'Enabled' as set by a potential default override attribute.
  3852. /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
  3853. /// refinement iterations required to generate a sufficient (though not
  3854. /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
  3855. /// The boolean UseOneConstNR output is used to select a Newton-Raphson
  3856. /// algorithm implementation that uses either one or two constants.
  3857. /// The boolean Reciprocal is used to select whether the estimate is for the
  3858. /// square root of the input operand or the reciprocal of its square root.
  3859. /// A target may choose to implement its own refinement within this function.
  3860. /// If that's true, then return '0' as the number of RefinementSteps to avoid
  3861. /// any further refinement of the estimate.
  3862. /// An empty SDValue return means no estimate sequence can be created.
  3863. virtual SDValue getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
  3864. int Enabled, int &RefinementSteps,
  3865. bool &UseOneConstNR, bool Reciprocal) const {
  3866. return SDValue();
  3867. }
  3868. /// Return a reciprocal estimate value for the input operand.
  3869. /// \p Enabled is a ReciprocalEstimate enum with value either 'Unspecified' or
  3870. /// 'Enabled' as set by a potential default override attribute.
  3871. /// If \p RefinementSteps is 'Unspecified', the number of Newton-Raphson
  3872. /// refinement iterations required to generate a sufficient (though not
  3873. /// necessarily IEEE-754 compliant) estimate is returned in that parameter.
  3874. /// A target may choose to implement its own refinement within this function.
  3875. /// If that's true, then return '0' as the number of RefinementSteps to avoid
  3876. /// any further refinement of the estimate.
  3877. /// An empty SDValue return means no estimate sequence can be created.
  3878. virtual SDValue getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
  3879. int Enabled, int &RefinementSteps) const {
  3880. return SDValue();
  3881. }
  3882. /// Return a target-dependent comparison result if the input operand is
  3883. /// suitable for use with a square root estimate calculation. For example, the
  3884. /// comparison may check if the operand is NAN, INF, zero, normal, etc. The
  3885. /// result should be used as the condition operand for a select or branch.
  3886. virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG,
  3887. const DenormalMode &Mode) const;
  3888. /// Return a target-dependent result if the input operand is not suitable for
  3889. /// use with a square root estimate calculation.
  3890. virtual SDValue getSqrtResultForDenormInput(SDValue Operand,
  3891. SelectionDAG &DAG) const {
  3892. return DAG.getConstantFP(0.0, SDLoc(Operand), Operand.getValueType());
  3893. }
  3894. //===--------------------------------------------------------------------===//
  3895. // Legalization utility functions
  3896. //
  3897. /// Expand a MUL or [US]MUL_LOHI of n-bit values into two or four nodes,
  3898. /// respectively, each computing an n/2-bit part of the result.
  3899. /// \param Result A vector that will be filled with the parts of the result
  3900. /// in little-endian order.
  3901. /// \param LL Low bits of the LHS of the MUL. You can use this parameter
  3902. /// if you want to control how low bits are extracted from the LHS.
  3903. /// \param LH High bits of the LHS of the MUL. See LL for meaning.
  3904. /// \param RL Low bits of the RHS of the MUL. See LL for meaning
  3905. /// \param RH High bits of the RHS of the MUL. See LL for meaning.
  3906. /// \returns true if the node has been expanded, false if it has not
  3907. bool expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl, SDValue LHS,
  3908. SDValue RHS, SmallVectorImpl<SDValue> &Result, EVT HiLoVT,
  3909. SelectionDAG &DAG, MulExpansionKind Kind,
  3910. SDValue LL = SDValue(), SDValue LH = SDValue(),
  3911. SDValue RL = SDValue(), SDValue RH = SDValue()) const;
  3912. /// Expand a MUL into two nodes. One that computes the high bits of
  3913. /// the result and one that computes the low bits.
  3914. /// \param HiLoVT The value type to use for the Lo and Hi nodes.
  3915. /// \param LL Low bits of the LHS of the MUL. You can use this parameter
  3916. /// if you want to control how low bits are extracted from the LHS.
  3917. /// \param LH High bits of the LHS of the MUL. See LL for meaning.
  3918. /// \param RL Low bits of the RHS of the MUL. See LL for meaning
  3919. /// \param RH High bits of the RHS of the MUL. See LL for meaning.
  3920. /// \returns true if the node has been expanded. false if it has not
  3921. bool expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
  3922. SelectionDAG &DAG, MulExpansionKind Kind,
  3923. SDValue LL = SDValue(), SDValue LH = SDValue(),
  3924. SDValue RL = SDValue(), SDValue RH = SDValue()) const;
  3925. /// Expand funnel shift.
  3926. /// \param N Node to expand
  3927. /// \returns The expansion if successful, SDValue() otherwise
  3928. SDValue expandFunnelShift(SDNode *N, SelectionDAG &DAG) const;
  3929. /// Expand rotations.
  3930. /// \param N Node to expand
  3931. /// \param AllowVectorOps expand vector rotate, this should only be performed
  3932. /// if the legalization is happening outside of LegalizeVectorOps
  3933. /// \returns The expansion if successful, SDValue() otherwise
  3934. SDValue expandROT(SDNode *N, bool AllowVectorOps, SelectionDAG &DAG) const;
  3935. /// Expand shift-by-parts.
  3936. /// \param N Node to expand
  3937. /// \param Lo lower-output-part after conversion
  3938. /// \param Hi upper-output-part after conversion
  3939. void expandShiftParts(SDNode *N, SDValue &Lo, SDValue &Hi,
  3940. SelectionDAG &DAG) const;
  3941. /// Expand float(f32) to SINT(i64) conversion
  3942. /// \param N Node to expand
  3943. /// \param Result output after conversion
  3944. /// \returns True, if the expansion was successful, false otherwise
  3945. bool expandFP_TO_SINT(SDNode *N, SDValue &Result, SelectionDAG &DAG) const;
  3946. /// Expand float to UINT conversion
  3947. /// \param N Node to expand
  3948. /// \param Result output after conversion
  3949. /// \param Chain output chain after conversion
  3950. /// \returns True, if the expansion was successful, false otherwise
  3951. bool expandFP_TO_UINT(SDNode *N, SDValue &Result, SDValue &Chain,
  3952. SelectionDAG &DAG) const;
  3953. /// Expand UINT(i64) to double(f64) conversion
  3954. /// \param N Node to expand
  3955. /// \param Result output after conversion
  3956. /// \param Chain output chain after conversion
  3957. /// \returns True, if the expansion was successful, false otherwise
  3958. bool expandUINT_TO_FP(SDNode *N, SDValue &Result, SDValue &Chain,
  3959. SelectionDAG &DAG) const;
  3960. /// Expand fminnum/fmaxnum into fminnum_ieee/fmaxnum_ieee with quieted inputs.
  3961. SDValue expandFMINNUM_FMAXNUM(SDNode *N, SelectionDAG &DAG) const;
  3962. /// Expand FP_TO_[US]INT_SAT into FP_TO_[US]INT and selects or min/max.
  3963. /// \param N Node to expand
  3964. /// \returns The expansion result
  3965. SDValue expandFP_TO_INT_SAT(SDNode *N, SelectionDAG &DAG) const;
  3966. /// Expand CTPOP nodes. Expands vector/scalar CTPOP nodes,
  3967. /// vector nodes can only succeed if all operations are legal/custom.
  3968. /// \param N Node to expand
  3969. /// \returns The expansion result or SDValue() if it fails.
  3970. SDValue expandCTPOP(SDNode *N, SelectionDAG &DAG) const;
  3971. /// Expand CTLZ/CTLZ_ZERO_UNDEF nodes. Expands vector/scalar CTLZ nodes,
  3972. /// vector nodes can only succeed if all operations are legal/custom.
  3973. /// \param N Node to expand
  3974. /// \returns The expansion result or SDValue() if it fails.
  3975. SDValue expandCTLZ(SDNode *N, SelectionDAG &DAG) const;
  3976. /// Expand CTTZ/CTTZ_ZERO_UNDEF nodes. Expands vector/scalar CTTZ nodes,
  3977. /// vector nodes can only succeed if all operations are legal/custom.
  3978. /// \param N Node to expand
  3979. /// \returns The expansion result or SDValue() if it fails.
  3980. SDValue expandCTTZ(SDNode *N, SelectionDAG &DAG) const;
  3981. /// Expand ABS nodes. Expands vector/scalar ABS nodes,
  3982. /// vector nodes can only succeed if all operations are legal/custom.
  3983. /// (ABS x) -> (XOR (ADD x, (SRA x, type_size)), (SRA x, type_size))
  3984. /// \param N Node to expand
  3985. /// \param IsNegative indicate negated abs
  3986. /// \returns The expansion result or SDValue() if it fails.
  3987. SDValue expandABS(SDNode *N, SelectionDAG &DAG,
  3988. bool IsNegative = false) const;
  3989. /// Expand BSWAP nodes. Expands scalar/vector BSWAP nodes with i16/i32/i64
  3990. /// scalar types. Returns SDValue() if expand fails.
  3991. /// \param N Node to expand
  3992. /// \returns The expansion result or SDValue() if it fails.
  3993. SDValue expandBSWAP(SDNode *N, SelectionDAG &DAG) const;
  3994. /// Expand BITREVERSE nodes. Expands scalar/vector BITREVERSE nodes.
  3995. /// Returns SDValue() if expand fails.
  3996. /// \param N Node to expand
  3997. /// \returns The expansion result or SDValue() if it fails.
  3998. SDValue expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const;
  3999. /// Turn load of vector type into a load of the individual elements.
  4000. /// \param LD load to expand
  4001. /// \returns BUILD_VECTOR and TokenFactor nodes.
  4002. std::pair<SDValue, SDValue> scalarizeVectorLoad(LoadSDNode *LD,
  4003. SelectionDAG &DAG) const;
  4004. // Turn a store of a vector type into stores of the individual elements.
  4005. /// \param ST Store with a vector value type
  4006. /// \returns TokenFactor of the individual store chains.
  4007. SDValue scalarizeVectorStore(StoreSDNode *ST, SelectionDAG &DAG) const;
  4008. /// Expands an unaligned load to 2 half-size loads for an integer, and
  4009. /// possibly more for vectors.
  4010. std::pair<SDValue, SDValue> expandUnalignedLoad(LoadSDNode *LD,
  4011. SelectionDAG &DAG) const;
  4012. /// Expands an unaligned store to 2 half-size stores for integer values, and
  4013. /// possibly more for vectors.
  4014. SDValue expandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG) const;
  4015. /// Increments memory address \p Addr according to the type of the value
  4016. /// \p DataVT that should be stored. If the data is stored in compressed
  4017. /// form, the memory address should be incremented according to the number of
  4018. /// the stored elements. This number is equal to the number of '1's bits
  4019. /// in the \p Mask.
  4020. /// \p DataVT is a vector type. \p Mask is a vector value.
  4021. /// \p DataVT and \p Mask have the same number of vector elements.
  4022. SDValue IncrementMemoryAddress(SDValue Addr, SDValue Mask, const SDLoc &DL,
  4023. EVT DataVT, SelectionDAG &DAG,
  4024. bool IsCompressedMemory) const;
  4025. /// Get a pointer to vector element \p Idx located in memory for a vector of
  4026. /// type \p VecVT starting at a base address of \p VecPtr. If \p Idx is out of
  4027. /// bounds the returned pointer is unspecified, but will be within the vector
  4028. /// bounds.
  4029. SDValue getVectorElementPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
  4030. SDValue Index) const;
  4031. /// Get a pointer to a sub-vector of type \p SubVecVT at index \p Idx located
  4032. /// in memory for a vector of type \p VecVT starting at a base address of
  4033. /// \p VecPtr. If \p Idx plus the size of \p SubVecVT is out of bounds the
  4034. /// returned pointer is unspecified, but the value returned will be such that
  4035. /// the entire subvector would be within the vector bounds.
  4036. SDValue getVectorSubVecPointer(SelectionDAG &DAG, SDValue VecPtr, EVT VecVT,
  4037. EVT SubVecVT, SDValue Index) const;
  4038. /// Method for building the DAG expansion of ISD::[US][MIN|MAX]. This
  4039. /// method accepts integers as its arguments.
  4040. SDValue expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const;
  4041. /// Method for building the DAG expansion of ISD::[US][ADD|SUB]SAT. This
  4042. /// method accepts integers as its arguments.
  4043. SDValue expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const;
  4044. /// Method for building the DAG expansion of ISD::[US]SHLSAT. This
  4045. /// method accepts integers as its arguments.
  4046. SDValue expandShlSat(SDNode *Node, SelectionDAG &DAG) const;
  4047. /// Method for building the DAG expansion of ISD::[U|S]MULFIX[SAT]. This
  4048. /// method accepts integers as its arguments.
  4049. SDValue expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const;
  4050. /// Method for building the DAG expansion of ISD::[US]DIVFIX[SAT]. This
  4051. /// method accepts integers as its arguments.
  4052. /// Note: This method may fail if the division could not be performed
  4053. /// within the type. Clients must retry with a wider type if this happens.
  4054. SDValue expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
  4055. SDValue LHS, SDValue RHS,
  4056. unsigned Scale, SelectionDAG &DAG) const;
  4057. /// Method for building the DAG expansion of ISD::U(ADD|SUB)O. Expansion
  4058. /// always suceeds and populates the Result and Overflow arguments.
  4059. void expandUADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
  4060. SelectionDAG &DAG) const;
  4061. /// Method for building the DAG expansion of ISD::S(ADD|SUB)O. Expansion
  4062. /// always suceeds and populates the Result and Overflow arguments.
  4063. void expandSADDSUBO(SDNode *Node, SDValue &Result, SDValue &Overflow,
  4064. SelectionDAG &DAG) const;
  4065. /// Method for building the DAG expansion of ISD::[US]MULO. Returns whether
  4066. /// expansion was successful and populates the Result and Overflow arguments.
  4067. bool expandMULO(SDNode *Node, SDValue &Result, SDValue &Overflow,
  4068. SelectionDAG &DAG) const;
  4069. /// Expand a VECREDUCE_* into an explicit calculation. If Count is specified,
  4070. /// only the first Count elements of the vector are used.
  4071. SDValue expandVecReduce(SDNode *Node, SelectionDAG &DAG) const;
  4072. /// Expand a VECREDUCE_SEQ_* into an explicit ordered calculation.
  4073. SDValue expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const;
  4074. /// Expand an SREM or UREM using SDIV/UDIV or SDIVREM/UDIVREM, if legal.
  4075. /// Returns true if the expansion was successful.
  4076. bool expandREM(SDNode *Node, SDValue &Result, SelectionDAG &DAG) const;
  4077. /// Method for building the DAG expansion of ISD::VECTOR_SPLICE. This
  4078. /// method accepts vectors as its arguments.
  4079. SDValue expandVectorSplice(SDNode *Node, SelectionDAG &DAG) const;
  4080. /// Legalize a SETCC with given LHS and RHS and condition code CC on the
  4081. /// current target.
  4082. ///
  4083. /// If the SETCC has been legalized using AND / OR, then the legalized node
  4084. /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
  4085. /// will be set to false.
  4086. ///
  4087. /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
  4088. /// then the values of LHS and RHS will be swapped, CC will be set to the
  4089. /// new condition, and NeedInvert will be set to false.
  4090. ///
  4091. /// If the SETCC has been legalized using the inverse condcode, then LHS and
  4092. /// RHS will be unchanged, CC will set to the inverted condcode, and
  4093. /// NeedInvert will be set to true. The caller must invert the result of the
  4094. /// SETCC with SelectionDAG::getLogicalNOT() or take equivalent action to swap
  4095. /// the effect of a true/false result.
  4096. ///
  4097. /// \returns true if the SetCC has been legalized, false if it hasn't.
  4098. bool LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT, SDValue &LHS,
  4099. SDValue &RHS, SDValue &CC, bool &NeedInvert,
  4100. const SDLoc &dl, SDValue &Chain,
  4101. bool IsSignaling = false) const;
  4102. //===--------------------------------------------------------------------===//
  4103. // Instruction Emitting Hooks
  4104. //
  4105. /// This method should be implemented by targets that mark instructions with
  4106. /// the 'usesCustomInserter' flag. These instructions are special in various
  4107. /// ways, which require special support to insert. The specified MachineInstr
  4108. /// is created but not inserted into any basic blocks, and this method is
  4109. /// called to expand it into a sequence of instructions, potentially also
  4110. /// creating new basic blocks and control flow.
  4111. /// As long as the returned basic block is different (i.e., we created a new
  4112. /// one), the custom inserter is free to modify the rest of \p MBB.
  4113. virtual MachineBasicBlock *
  4114. EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const;
  4115. /// This method should be implemented by targets that mark instructions with
  4116. /// the 'hasPostISelHook' flag. These instructions must be adjusted after
  4117. /// instruction selection by target hooks. e.g. To fill in optional defs for
  4118. /// ARM 's' setting instructions.
  4119. virtual void AdjustInstrPostInstrSelection(MachineInstr &MI,
  4120. SDNode *Node) const;
  4121. /// If this function returns true, SelectionDAGBuilder emits a
  4122. /// LOAD_STACK_GUARD node when it is lowering Intrinsic::stackprotector.
  4123. virtual bool useLoadStackGuardNode() const {
  4124. return false;
  4125. }
  4126. virtual SDValue emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
  4127. const SDLoc &DL) const {
  4128. llvm_unreachable("not implemented for this target");
  4129. }
  4130. /// Lower TLS global address SDNode for target independent emulated TLS model.
  4131. virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
  4132. SelectionDAG &DAG) const;
  4133. /// Expands target specific indirect branch for the case of JumpTable
  4134. /// expanasion.
  4135. virtual SDValue expandIndirectJTBranch(const SDLoc& dl, SDValue Value, SDValue Addr,
  4136. SelectionDAG &DAG) const {
  4137. return DAG.getNode(ISD::BRIND, dl, MVT::Other, Value, Addr);
  4138. }
  4139. // seteq(x, 0) -> truncate(srl(ctlz(zext(x)), log2(#bits)))
  4140. // If we're comparing for equality to zero and isCtlzFast is true, expose the
  4141. // fact that this can be implemented as a ctlz/srl pair, so that the dag
  4142. // combiner can fold the new nodes.
  4143. SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const;
  4144. /// Give targets the chance to reduce the number of distinct addresing modes.
  4145. ISD::MemIndexType getCanonicalIndexType(ISD::MemIndexType IndexType,
  4146. EVT MemVT, SDValue Offsets) const;
  4147. private:
  4148. SDValue foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  4149. const SDLoc &DL, DAGCombinerInfo &DCI) const;
  4150. SDValue foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  4151. const SDLoc &DL, DAGCombinerInfo &DCI) const;
  4152. SDValue optimizeSetCCOfSignedTruncationCheck(EVT SCCVT, SDValue N0,
  4153. SDValue N1, ISD::CondCode Cond,
  4154. DAGCombinerInfo &DCI,
  4155. const SDLoc &DL) const;
  4156. // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
  4157. SDValue optimizeSetCCByHoistingAndByConstFromLogicalShift(
  4158. EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
  4159. DAGCombinerInfo &DCI, const SDLoc &DL) const;
  4160. SDValue prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
  4161. SDValue CompTargetNode, ISD::CondCode Cond,
  4162. DAGCombinerInfo &DCI, const SDLoc &DL,
  4163. SmallVectorImpl<SDNode *> &Created) const;
  4164. SDValue buildUREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
  4165. ISD::CondCode Cond, DAGCombinerInfo &DCI,
  4166. const SDLoc &DL) const;
  4167. SDValue prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
  4168. SDValue CompTargetNode, ISD::CondCode Cond,
  4169. DAGCombinerInfo &DCI, const SDLoc &DL,
  4170. SmallVectorImpl<SDNode *> &Created) const;
  4171. SDValue buildSREMEqFold(EVT SETCCVT, SDValue REMNode, SDValue CompTargetNode,
  4172. ISD::CondCode Cond, DAGCombinerInfo &DCI,
  4173. const SDLoc &DL) const;
  4174. };
  4175. /// Given an LLVM IR type and return type attributes, compute the return value
  4176. /// EVTs and flags, and optionally also the offsets, if the return value is
  4177. /// being lowered to memory.
  4178. void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr,
  4179. SmallVectorImpl<ISD::OutputArg> &Outs,
  4180. const TargetLowering &TLI, const DataLayout &DL);
  4181. } // end namespace llvm
  4182. #endif // LLVM_CODEGEN_TARGETLOWERING_H
  4183. #ifdef __GNUC__
  4184. #pragma GCC diagnostic pop
  4185. #endif