CGHLSLMS.cpp 216 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660
  1. //===----- CGHLSLMS.cpp - Interface to HLSL Runtime ----------------===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // CGHLSLMS.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This provides a class for HLSL code generation. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "CGHLSLRuntime.h"
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGRecordLayout.h"
  16. #include "dxc/HlslIntrinsicOp.h"
  17. #include "dxc/HLSL/HLMatrixType.h"
  18. #include "dxc/HLSL/HLModule.h"
  19. #include "dxc/DXIL/DxilUtil.h"
  20. #include "dxc/HLSL/HLOperations.h"
  21. #include "dxc/DXIL/DxilOperations.h"
  22. #include "dxc/DXIL/DxilTypeSystem.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/HlslTypes.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "clang/Lex/HLSLMacroExpander.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/StringSwitch.h"
  29. #include "llvm/ADT/StringSet.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/StringSet.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/IRBuilder.h"
  34. #include "llvm/IR/GetElementPtrTypeIterator.h"
  35. #include "llvm/Transforms/Utils/Cloning.h"
  36. #include "llvm/IR/InstIterator.h"
  37. #include <memory>
  38. #include <unordered_map>
  39. #include <unordered_set>
  40. #include <set>
  41. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  42. #include "dxc/DXIL/DxilCBuffer.h"
  43. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  44. #include "dxc/Support/WinIncludes.h" // stream support
  45. #include "dxc/dxcapi.h" // stream support
  46. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  47. #include "dxc/HLSL/DxilGenerationPass.h" // support pause/resume passes
  48. #include "dxc/HLSL/DxilExportMap.h"
  49. #include "dxc/DXIL/DxilResourceProperties.h"
  50. #include "CGHLSLMSHelper.h"
  51. using namespace clang;
  52. using namespace CodeGen;
  53. using namespace hlsl;
  54. using namespace llvm;
  55. using std::unique_ptr;
  56. using namespace CGHLSLMSHelper;
  57. static const bool KeepUndefinedTrue = true; // Keep interpolation mode undefined if not set explicitly.
  58. namespace {
  59. class CGMSHLSLRuntime : public CGHLSLRuntime {
  60. private:
  61. /// Convenience reference to LLVM Context
  62. llvm::LLVMContext &Context;
  63. /// Convenience reference to the current module
  64. llvm::Module &TheModule;
  65. HLModule *m_pHLModule;
  66. llvm::Type *CBufferType;
  67. uint32_t globalCBIndex;
  68. // TODO: make sure how minprec works
  69. llvm::DataLayout dataLayout;
  70. // decl map to constant id for program
  71. llvm::DenseMap<HLSLBufferDecl *, uint32_t> constantBufMap;
  72. // Map for resource type to resource metadata value.
  73. std::unordered_map<llvm::Type *, MDNode*> resMetadataMap;
  74. // Map from Constant to register bindings.
  75. llvm::DenseMap<llvm::Constant *,
  76. llvm::SmallVector<std::pair<DXIL::ResourceClass, unsigned>, 1>>
  77. constantRegBindingMap;
  78. // Map from value to resource properties.
  79. // This only collect object variables(global/local/parameter), not object fields inside struct.
  80. // Object fields inside struct is saved by TypeAnnotation.
  81. DenseMap<Value *, DxilResourceProperties> valToResPropertiesMap;
  82. bool m_bDebugInfo;
  83. bool m_bIsLib;
  84. // For library, m_ExportMap maps from internal name to zero or more renames
  85. dxilutil::ExportMap m_ExportMap;
  86. HLCBuffer &GetGlobalCBuffer() {
  87. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(globalCBIndex)));
  88. }
  89. void AddConstant(VarDecl *constDecl, HLCBuffer &CB);
  90. uint32_t AddSampler(VarDecl *samplerDecl);
  91. uint32_t AddUAVSRV(VarDecl *decl, hlsl::DxilResourceBase::Class resClass);
  92. bool SetUAVSRV(SourceLocation loc, hlsl::DxilResourceBase::Class resClass,
  93. DxilResource *hlslRes, QualType QualTy);
  94. uint32_t AddCBuffer(HLSLBufferDecl *D);
  95. hlsl::DxilResourceBase::Class TypeToClass(clang::QualType Ty);
  96. void CreateSubobject(DXIL::SubobjectKind kind, const StringRef name, clang::Expr **args,
  97. unsigned int argCount, DXIL::HitGroupType hgType = (DXIL::HitGroupType)(-1));
  98. bool GetAsConstantString(clang::Expr *expr, StringRef *value, bool failWhenEmpty = false);
  99. bool GetAsConstantUInt32(clang::Expr *expr, uint32_t *value);
  100. std::vector<StringRef> ParseSubobjectExportsAssociations(StringRef exports);
  101. EntryFunctionInfo Entry;
  102. StringMap<PatchConstantInfo> patchConstantFunctionMap;
  103. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  104. patchConstantFunctionPropsMap;
  105. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  106. HSEntryPatchConstantFuncAttr;
  107. // Map to save entry functions.
  108. StringMap<EntryFunctionInfo> entryFunctionMap;
  109. // Map to save static global init exp.
  110. std::unordered_map<Expr *, GlobalVariable *> staticConstGlobalInitMap;
  111. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  112. staticConstGlobalInitListMap;
  113. std::unordered_map<GlobalVariable *, Function *> staticConstGlobalCtorMap;
  114. // List for functions with clip plane.
  115. std::vector<Function *> clipPlaneFuncList;
  116. std::unordered_map<Value *, DebugLoc> debugInfoMap;
  117. DxilRootSignatureVersion rootSigVer;
  118. Value *EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr, QualType Ty);
  119. void EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val, Value *DestPtr,
  120. QualType Ty);
  121. // Flatten the val into scalar val and push into elts and eltTys.
  122. void FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  123. SmallVector<QualType, 4> &eltTys, QualType Ty,
  124. Value *val);
  125. // Push every value on InitListExpr into EltValList and EltTyList.
  126. void ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  127. SmallVector<Value *, 4> &EltValList,
  128. SmallVector<QualType, 4> &EltTyList);
  129. void FlattenAggregatePtrToGepList(CodeGenFunction &CGF, Value *Ptr,
  130. SmallVector<Value *, 4> &idxList,
  131. clang::QualType Type, llvm::Type *Ty,
  132. SmallVector<Value *, 4> &GepList,
  133. SmallVector<QualType, 4> &EltTyList);
  134. void LoadElements(CodeGenFunction &CGF,
  135. ArrayRef<Value *> Ptrs, ArrayRef<QualType> QualTys,
  136. SmallVector<Value *, 4> &Vals);
  137. void ConvertAndStoreElements(CodeGenFunction &CGF,
  138. ArrayRef<Value *> SrcVals, ArrayRef<QualType> SrcQualTys,
  139. ArrayRef<Value *> DstPtrs, ArrayRef<QualType> DstQualTys);
  140. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  141. llvm::Value *DestPtr,
  142. SmallVector<Value *, 4> &idxList,
  143. clang::QualType SrcType,
  144. clang::QualType DestType,
  145. llvm::Type *Ty);
  146. void EmitHLSLSplat(CodeGenFunction &CGF, Value *SrcVal,
  147. llvm::Value *DestPtr,
  148. SmallVector<Value *, 4> &idxList,
  149. QualType Type, QualType SrcType,
  150. llvm::Type *Ty);
  151. void EmitHLSLRootSignature(CodeGenFunction &CGF, HLSLRootSignatureAttr *RSA,
  152. llvm::Function *Fn) override;
  153. void CheckParameterAnnotation(SourceLocation SLoc,
  154. const DxilParameterAnnotation &paramInfo,
  155. bool isPatchConstantFunction);
  156. void CheckParameterAnnotation(SourceLocation SLoc,
  157. DxilParamInputQual paramQual,
  158. llvm::StringRef semFullName,
  159. bool isPatchConstantFunction);
  160. void RemapObsoleteSemantic(DxilParameterAnnotation &paramInfo,
  161. bool isPatchConstantFunction);
  162. SourceLocation SetSemantic(const NamedDecl *decl,
  163. DxilParameterAnnotation &paramInfo);
  164. hlsl::InterpolationMode GetInterpMode(const Decl *decl, CompType compType,
  165. bool bKeepUndefined);
  166. hlsl::CompType GetCompType(const BuiltinType *BT);
  167. // save intrinsic opcode
  168. std::vector<std::pair<Function *, unsigned>> m_IntrinsicMap;
  169. void AddHLSLIntrinsicOpcodeToFunction(Function *, unsigned opcode);
  170. // Type annotation related.
  171. unsigned ConstructStructAnnotation(DxilStructAnnotation *annotation,
  172. const RecordDecl *RD,
  173. DxilTypeSystem &dxilTypeSys);
  174. unsigned AddTypeAnnotation(QualType Ty, DxilTypeSystem &dxilTypeSys,
  175. unsigned &arrayEltSize);
  176. MDNode *GetOrAddResTypeMD(QualType resTy, bool bCreate);
  177. DxilResourceProperties BuildResourceProperty(QualType resTy);
  178. void ConstructFieldAttributedAnnotation(DxilFieldAnnotation &fieldAnnotation,
  179. QualType fieldTy,
  180. bool bDefaultRowMajor);
  181. std::unordered_map<Constant*, DxilFieldAnnotation> m_ConstVarAnnotationMap;
  182. StringSet<> m_PreciseOutputSet;
  183. public:
  184. CGMSHLSLRuntime(CodeGenModule &CGM);
  185. /// Add resouce to the program
  186. void addResource(Decl *D) override;
  187. void addSubobject(Decl *D) override;
  188. void FinishCodeGen() override;
  189. bool IsTrivalInitListExpr(CodeGenFunction &CGF, InitListExpr *E) override;
  190. Value *EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E, Value *DestPtr) override;
  191. Constant *EmitHLSLConstInitListExpr(CodeGenModule &CGM, InitListExpr *E) override;
  192. RValue EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF, const FunctionDecl *FD,
  193. const CallExpr *E,
  194. ReturnValueSlot ReturnValue) override;
  195. void EmitHLSLOutParamConversionInit(
  196. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  197. llvm::SmallVector<LValue, 8> &castArgList,
  198. llvm::SmallVector<const Stmt *, 8> &argList,
  199. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap)
  200. override;
  201. void EmitHLSLOutParamConversionCopyBack(
  202. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) override;
  203. Value *EmitHLSLMatrixOperationCall(CodeGenFunction &CGF, const clang::Expr *E,
  204. llvm::Type *RetType,
  205. ArrayRef<Value *> paramList) override;
  206. void EmitHLSLDiscard(CodeGenFunction &CGF) override;
  207. void EmitHLSLCondBreak(CodeGenFunction &CGF, llvm::Function *F, llvm::BasicBlock *DestBB, llvm::BasicBlock *AltBB) override;
  208. Value *EmitHLSLMatrixSubscript(CodeGenFunction &CGF, llvm::Type *RetType,
  209. Value *Ptr, Value *Idx, QualType Ty) override;
  210. Value *EmitHLSLMatrixElement(CodeGenFunction &CGF, llvm::Type *RetType,
  211. ArrayRef<Value *> paramList,
  212. QualType Ty) override;
  213. Value *EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  214. QualType Ty) override;
  215. void EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val, Value *DestPtr,
  216. QualType Ty) override;
  217. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  218. llvm::Value *DestPtr,
  219. clang::QualType Ty) override;
  220. void EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *Val,
  221. llvm::Value *DestPtr,
  222. clang::QualType Ty) override;
  223. void EmitHLSLFlatConversion(CodeGenFunction &CGF, Value *Val,
  224. Value *DestPtr,
  225. QualType Ty,
  226. QualType SrcTy) override;
  227. Value *EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src, QualType SrcType,
  228. QualType DstType) override;
  229. void EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  230. clang::QualType SrcTy,
  231. llvm::Value *DestPtr,
  232. clang::QualType DestTy) override;
  233. void AddHLSLFunctionInfo(llvm::Function *, const FunctionDecl *FD) override;
  234. void EmitHLSLFunctionProlog(llvm::Function *, const FunctionDecl *FD) override;
  235. void AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  236. llvm::TerminatorInst *TI,
  237. ArrayRef<const Attr *> Attrs) override;
  238. void MarkRetTemp(CodeGenFunction &CGF, llvm::Value *V,
  239. clang::QualType QaulTy) override;
  240. void FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) override;
  241. /// Get or add constant to the program
  242. HLCBuffer &GetOrCreateCBuffer(HLSLBufferDecl *D);
  243. };
  244. }
  245. //------------------------------------------------------------------------------
  246. //
  247. // CGMSHLSLRuntime methods.
  248. //
  249. CGMSHLSLRuntime::CGMSHLSLRuntime(CodeGenModule &CGM)
  250. : CGHLSLRuntime(CGM), Context(CGM.getLLVMContext()),
  251. TheModule(CGM.getModule()),
  252. CBufferType(
  253. llvm::StructType::create(TheModule.getContext(), "ConstantBuffer")),
  254. dataLayout(CGM.getLangOpts().UseMinPrecision
  255. ? hlsl::DXIL::kLegacyLayoutString
  256. : hlsl::DXIL::kNewLayoutString), Entry() {
  257. const hlsl::ShaderModel *SM =
  258. hlsl::ShaderModel::GetByName(CGM.getCodeGenOpts().HLSLProfile.c_str());
  259. // Only accept valid, 6.0 shader model.
  260. if (!SM->IsValid() || SM->GetMajor() != 6) {
  261. DiagnosticsEngine &Diags = CGM.getDiags();
  262. unsigned DiagID =
  263. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid profile %0");
  264. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLProfile;
  265. return;
  266. }
  267. if (CGM.getCodeGenOpts().HLSLValidatorMajorVer != 0) {
  268. // Check validator version against minimum for target profile:
  269. unsigned MinMajor, MinMinor;
  270. SM->GetMinValidatorVersion(MinMajor, MinMinor);
  271. if (DXIL::CompareVersions(CGM.getCodeGenOpts().HLSLValidatorMajorVer,
  272. CGM.getCodeGenOpts().HLSLValidatorMinorVer,
  273. MinMajor, MinMinor) < 0) {
  274. DiagnosticsEngine &Diags = CGM.getDiags();
  275. unsigned DiagID =
  276. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  277. "validator version %0,%1 does not support target profile.");
  278. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLValidatorMajorVer
  279. << CGM.getCodeGenOpts().HLSLValidatorMinorVer;
  280. return;
  281. }
  282. }
  283. m_bIsLib = SM->IsLib();
  284. // TODO: add AllResourceBound.
  285. if (CGM.getCodeGenOpts().HLSLAvoidControlFlow && !CGM.getCodeGenOpts().HLSLAllResourcesBound) {
  286. if (SM->IsSM51Plus()) {
  287. DiagnosticsEngine &Diags = CGM.getDiags();
  288. unsigned DiagID =
  289. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  290. "Gfa option cannot be used in SM_5_1+ unless "
  291. "all_resources_bound flag is specified");
  292. Diags.Report(DiagID);
  293. }
  294. }
  295. // Create HLModule.
  296. const bool skipInit = true;
  297. m_pHLModule = &TheModule.GetOrCreateHLModule(skipInit);
  298. // Precise Output.
  299. for (auto &preciseOutput : CGM.getCodeGenOpts().HLSLPreciseOutputs) {
  300. m_PreciseOutputSet.insert(StringRef(preciseOutput).lower());
  301. }
  302. // Set Option.
  303. HLOptions opts;
  304. opts.bIEEEStrict = CGM.getCodeGenOpts().UnsafeFPMath;
  305. opts.bDefaultRowMajor = CGM.getCodeGenOpts().HLSLDefaultRowMajor;
  306. opts.bDisableOptimizations = CGM.getCodeGenOpts().DisableLLVMOpts;
  307. opts.bLegacyCBufferLoad = !CGM.getCodeGenOpts().HLSLNotUseLegacyCBufLoad;
  308. opts.bAllResourcesBound = CGM.getCodeGenOpts().HLSLAllResourcesBound;
  309. opts.PackingStrategy = CGM.getCodeGenOpts().HLSLSignaturePackingStrategy;
  310. opts.bLegacyResourceReservation = CGM.getCodeGenOpts().HLSLLegacyResourceReservation;
  311. opts.bUseMinPrecision = CGM.getLangOpts().UseMinPrecision;
  312. opts.bDX9CompatMode = CGM.getLangOpts().EnableDX9CompatMode;
  313. opts.bFXCCompatMode = CGM.getLangOpts().EnableFXCCompatMode;
  314. m_pHLModule->SetHLOptions(opts);
  315. m_pHLModule->GetOP()->SetMinPrecision(opts.bUseMinPrecision);
  316. m_pHLModule->GetTypeSystem().SetMinPrecision(opts.bUseMinPrecision);
  317. m_pHLModule->SetAutoBindingSpace(CGM.getCodeGenOpts().HLSLDefaultSpace);
  318. m_pHLModule->SetValidatorVersion(CGM.getCodeGenOpts().HLSLValidatorMajorVer, CGM.getCodeGenOpts().HLSLValidatorMinorVer);
  319. m_bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
  320. // set profile
  321. m_pHLModule->SetShaderModel(SM);
  322. // set entry name
  323. if (!SM->IsLib())
  324. m_pHLModule->SetEntryFunctionName(CGM.getCodeGenOpts().HLSLEntryFunction);
  325. // set root signature version.
  326. if (CGM.getLangOpts().RootSigMinor == 0) {
  327. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  328. }
  329. else {
  330. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  331. "else CGMSHLSLRuntime Constructor needs to be updated");
  332. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  333. }
  334. DXASSERT(CGM.getLangOpts().RootSigMajor == 1,
  335. "else CGMSHLSLRuntime Constructor needs to be updated");
  336. // add globalCB
  337. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  338. std::string globalCBName = "$Globals";
  339. CB->SetGlobalSymbol(nullptr);
  340. CB->SetGlobalName(globalCBName);
  341. globalCBIndex = m_pHLModule->GetCBuffers().size();
  342. CB->SetID(globalCBIndex);
  343. CB->SetRangeSize(1);
  344. CB->SetLowerBound(UINT_MAX);
  345. DXVERIFY_NOMSG(globalCBIndex == m_pHLModule->AddCBuffer(std::move(CB)));
  346. // set Float Denorm Mode
  347. m_pHLModule->SetFloat32DenormMode(CGM.getCodeGenOpts().HLSLFloat32DenormMode);
  348. // set DefaultLinkage
  349. m_pHLModule->SetDefaultLinkage(CGM.getCodeGenOpts().DefaultLinkage);
  350. // Fill in m_ExportMap, which maps from internal name to zero or more renames
  351. m_ExportMap.clear();
  352. std::string errors;
  353. llvm::raw_string_ostream os(errors);
  354. if (!m_ExportMap.ParseExports(CGM.getCodeGenOpts().HLSLLibraryExports, os)) {
  355. DiagnosticsEngine &Diags = CGM.getDiags();
  356. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "Error parsing -exports options: %0");
  357. Diags.Report(DiagID) << os.str();
  358. }
  359. }
  360. void CGMSHLSLRuntime::AddHLSLIntrinsicOpcodeToFunction(Function *F,
  361. unsigned opcode) {
  362. m_IntrinsicMap.emplace_back(F,opcode);
  363. }
  364. void CGMSHLSLRuntime::CheckParameterAnnotation(
  365. SourceLocation SLoc, const DxilParameterAnnotation &paramInfo,
  366. bool isPatchConstantFunction) {
  367. if (!paramInfo.HasSemanticString()) {
  368. return;
  369. }
  370. llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
  371. DxilParamInputQual paramQual = paramInfo.GetParamInputQual();
  372. if (paramQual == DxilParamInputQual::Inout) {
  373. CheckParameterAnnotation(SLoc, DxilParamInputQual::In, semFullName, isPatchConstantFunction);
  374. CheckParameterAnnotation(SLoc, DxilParamInputQual::Out, semFullName, isPatchConstantFunction);
  375. return;
  376. }
  377. CheckParameterAnnotation(SLoc, paramQual, semFullName, isPatchConstantFunction);
  378. }
  379. void CGMSHLSLRuntime::CheckParameterAnnotation(
  380. SourceLocation SLoc, DxilParamInputQual paramQual, llvm::StringRef semFullName,
  381. bool isPatchConstantFunction) {
  382. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  383. DXIL::SigPointKind sigPoint = SigPointFromInputQual(
  384. paramQual, SM->GetKind(), isPatchConstantFunction);
  385. llvm::StringRef semName;
  386. unsigned semIndex;
  387. Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
  388. const Semantic *pSemantic =
  389. Semantic::GetByName(semName, sigPoint, SM->GetMajor(), SM->GetMinor());
  390. if (pSemantic->IsInvalid()) {
  391. DiagnosticsEngine &Diags = CGM.getDiags();
  392. unsigned DiagID =
  393. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid semantic '%0' for %1 %2.%3");
  394. Diags.Report(SLoc, DiagID) << semName << SM->GetKindName() << SM->GetMajor() << SM->GetMinor();
  395. }
  396. }
  397. SourceLocation
  398. CGMSHLSLRuntime::SetSemantic(const NamedDecl *decl,
  399. DxilParameterAnnotation &paramInfo) {
  400. for (const hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  401. if (it->getKind() == hlsl::UnusualAnnotation::UA_SemanticDecl) {
  402. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  403. paramInfo.SetSemanticString(sd->SemanticName);
  404. if (m_PreciseOutputSet.count(StringRef(sd->SemanticName).lower()))
  405. paramInfo.SetPrecise();
  406. return it->Loc;
  407. }
  408. }
  409. return SourceLocation();
  410. }
  411. static DXIL::TessellatorDomain StringToDomain(StringRef domain) {
  412. if (domain == "isoline")
  413. return DXIL::TessellatorDomain::IsoLine;
  414. if (domain == "tri")
  415. return DXIL::TessellatorDomain::Tri;
  416. if (domain == "quad")
  417. return DXIL::TessellatorDomain::Quad;
  418. return DXIL::TessellatorDomain::Undefined;
  419. }
  420. static DXIL::TessellatorPartitioning StringToPartitioning(StringRef partition) {
  421. if (partition == "integer")
  422. return DXIL::TessellatorPartitioning::Integer;
  423. if (partition == "pow2")
  424. return DXIL::TessellatorPartitioning::Pow2;
  425. if (partition == "fractional_even")
  426. return DXIL::TessellatorPartitioning::FractionalEven;
  427. if (partition == "fractional_odd")
  428. return DXIL::TessellatorPartitioning::FractionalOdd;
  429. return DXIL::TessellatorPartitioning::Undefined;
  430. }
  431. static DXIL::TessellatorOutputPrimitive
  432. StringToTessOutputPrimitive(StringRef primitive) {
  433. if (primitive == "point")
  434. return DXIL::TessellatorOutputPrimitive::Point;
  435. if (primitive == "line")
  436. return DXIL::TessellatorOutputPrimitive::Line;
  437. if (primitive == "triangle_cw")
  438. return DXIL::TessellatorOutputPrimitive::TriangleCW;
  439. if (primitive == "triangle_ccw")
  440. return DXIL::TessellatorOutputPrimitive::TriangleCCW;
  441. return DXIL::TessellatorOutputPrimitive::Undefined;
  442. }
  443. static DXIL::MeshOutputTopology
  444. StringToMeshOutputTopology(StringRef topology) {
  445. if (topology == "line")
  446. return DXIL::MeshOutputTopology::Line;
  447. if (topology == "triangle")
  448. return DXIL::MeshOutputTopology::Triangle;
  449. return DXIL::MeshOutputTopology::Undefined;
  450. }
  451. static unsigned GetMatrixSizeInCB(QualType Ty, bool defaultRowMajor,
  452. bool b64Bit) {
  453. bool bRowMajor;
  454. if (!hlsl::HasHLSLMatOrientation(Ty, &bRowMajor))
  455. bRowMajor = defaultRowMajor;
  456. unsigned row, col;
  457. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  458. unsigned EltSize = b64Bit ? 8 : 4;
  459. // Align to 4 * 4bytes.
  460. unsigned alignment = 4 * 4;
  461. if (bRowMajor) {
  462. unsigned rowSize = EltSize * col;
  463. // 3x64bit or 4x64bit align to 32 bytes.
  464. if (rowSize > alignment)
  465. alignment <<= 1;
  466. return alignment * (row - 1) + col * EltSize;
  467. } else {
  468. unsigned rowSize = EltSize * row;
  469. // 3x64bit or 4x64bit align to 32 bytes.
  470. if (rowSize > alignment)
  471. alignment <<= 1;
  472. return alignment * (col - 1) + row * EltSize;
  473. }
  474. }
  475. static CompType::Kind BuiltinTyToCompTy(const BuiltinType *BTy, bool bSNorm,
  476. bool bUNorm) {
  477. CompType::Kind kind = CompType::Kind::Invalid;
  478. switch (BTy->getKind()) {
  479. case BuiltinType::UInt:
  480. kind = CompType::Kind::U32;
  481. break;
  482. case BuiltinType::Min16UInt: // HLSL Change
  483. case BuiltinType::UShort:
  484. kind = CompType::Kind::U16;
  485. break;
  486. case BuiltinType::ULongLong:
  487. kind = CompType::Kind::U64;
  488. break;
  489. case BuiltinType::Int:
  490. kind = CompType::Kind::I32;
  491. break;
  492. // HLSL Changes begin
  493. case BuiltinType::Min12Int:
  494. case BuiltinType::Min16Int:
  495. // HLSL Changes end
  496. case BuiltinType::Short:
  497. kind = CompType::Kind::I16;
  498. break;
  499. case BuiltinType::LongLong:
  500. kind = CompType::Kind::I64;
  501. break;
  502. // HLSL Changes begin
  503. case BuiltinType::Min10Float:
  504. case BuiltinType::Min16Float:
  505. // HLSL Changes end
  506. case BuiltinType::Half:
  507. if (bSNorm)
  508. kind = CompType::Kind::SNormF16;
  509. else if (bUNorm)
  510. kind = CompType::Kind::UNormF16;
  511. else
  512. kind = CompType::Kind::F16;
  513. break;
  514. case BuiltinType::HalfFloat: // HLSL Change
  515. case BuiltinType::Float:
  516. if (bSNorm)
  517. kind = CompType::Kind::SNormF32;
  518. else if (bUNorm)
  519. kind = CompType::Kind::UNormF32;
  520. else
  521. kind = CompType::Kind::F32;
  522. break;
  523. case BuiltinType::Double:
  524. if (bSNorm)
  525. kind = CompType::Kind::SNormF64;
  526. else if (bUNorm)
  527. kind = CompType::Kind::UNormF64;
  528. else
  529. kind = CompType::Kind::F64;
  530. break;
  531. case BuiltinType::Bool:
  532. kind = CompType::Kind::I1;
  533. break;
  534. default:
  535. // Other types not used by HLSL.
  536. break;
  537. }
  538. return kind;
  539. }
  540. static DxilSampler::SamplerKind KeywordToSamplerKind(llvm::StringRef keyword) {
  541. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  542. // compare)
  543. return llvm::StringSwitch<DxilSampler::SamplerKind>(keyword)
  544. .Case("SamplerState", DxilSampler::SamplerKind::Default)
  545. .Case("SamplerComparisonState", DxilSampler::SamplerKind::Comparison)
  546. .Default(DxilSampler::SamplerKind::Invalid);
  547. }
  548. MDNode *CGMSHLSLRuntime::GetOrAddResTypeMD(QualType resTy, bool bCreate) {
  549. const RecordType *RT = resTy->getAs<RecordType>();
  550. if (!RT)
  551. return nullptr;
  552. RecordDecl *RD = RT->getDecl();
  553. SourceLocation loc = RD->getLocation();
  554. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  555. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  556. auto it = resMetadataMap.find(Ty);
  557. if (!bCreate && it != resMetadataMap.end())
  558. return it->second;
  559. // Save resource type metadata.
  560. switch (resClass) {
  561. case DXIL::ResourceClass::UAV: {
  562. DxilResource UAV;
  563. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  564. SetUAVSRV(loc, resClass, &UAV, resTy);
  565. // Set global symbol to save type.
  566. UAV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  567. MDNode *MD = m_pHLModule->DxilUAVToMDNode(UAV);
  568. resMetadataMap[Ty] = MD;
  569. return MD;
  570. } break;
  571. case DXIL::ResourceClass::SRV: {
  572. DxilResource SRV;
  573. SetUAVSRV(loc, resClass, &SRV, resTy);
  574. // Set global symbol to save type.
  575. SRV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  576. MDNode *MD = m_pHLModule->DxilSRVToMDNode(SRV);
  577. resMetadataMap[Ty] = MD;
  578. return MD;
  579. } break;
  580. case DXIL::ResourceClass::Sampler: {
  581. DxilSampler S;
  582. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  583. S.SetSamplerKind(kind);
  584. // Set global symbol to save type.
  585. S.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  586. MDNode *MD = m_pHLModule->DxilSamplerToMDNode(S);
  587. resMetadataMap[Ty] = MD;
  588. return MD;
  589. }
  590. default:
  591. // Skip OutputStream for GS.
  592. return nullptr;
  593. }
  594. }
  595. namespace {
  596. MatrixOrientation GetMatrixMajor(QualType Ty, bool bDefaultRowMajor) {
  597. DXASSERT(hlsl::IsHLSLMatType(Ty), "");
  598. bool bIsRowMajor = bDefaultRowMajor;
  599. HasHLSLMatOrientation(Ty, &bIsRowMajor);
  600. return bIsRowMajor ? MatrixOrientation::RowMajor
  601. : MatrixOrientation::ColumnMajor;
  602. }
  603. QualType GetArrayEltType(ASTContext &Context, QualType Ty) {
  604. while (const clang::ArrayType *ArrayTy = Context.getAsArrayType(Ty))
  605. Ty = ArrayTy->getElementType();
  606. return Ty;
  607. }
  608. } // namespace
  609. DxilResourceProperties CGMSHLSLRuntime::BuildResourceProperty(QualType resTy) {
  610. resTy = GetArrayEltType(CGM.getContext(), resTy);
  611. const RecordType *RT = resTy->getAs<RecordType>();
  612. DxilResourceProperties RP;
  613. if (!RT) {
  614. RP.Class = DXIL::ResourceClass::Invalid;
  615. return RP;
  616. }
  617. RecordDecl *RD = RT->getDecl();
  618. SourceLocation loc = RD->getLocation();
  619. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  620. RP.Class = resClass;
  621. if (resClass == DXIL::ResourceClass::Invalid)
  622. return RP;
  623. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  624. switch (resClass) {
  625. case DXIL::ResourceClass::UAV: {
  626. DxilResource UAV;
  627. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  628. SetUAVSRV(loc, resClass, &UAV, resTy);
  629. UAV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  630. RP = resource_helper::loadFromResourceBase(&UAV);
  631. } break;
  632. case DXIL::ResourceClass::SRV: {
  633. DxilResource SRV;
  634. SetUAVSRV(loc, resClass, &SRV, resTy);
  635. SRV.SetGlobalSymbol(UndefValue::get(Ty->getPointerTo()));
  636. RP = resource_helper::loadFromResourceBase(&SRV);
  637. } break;
  638. case DXIL::ResourceClass::Sampler: {
  639. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  640. DxilSampler Sampler;
  641. Sampler.SetSamplerKind(kind);
  642. RP = resource_helper::loadFromResourceBase(&Sampler);
  643. }
  644. default:
  645. break;
  646. }
  647. return RP;
  648. }
  649. void CGMSHLSLRuntime::ConstructFieldAttributedAnnotation(
  650. DxilFieldAnnotation &fieldAnnotation, QualType fieldTy,
  651. bool bDefaultRowMajor) {
  652. QualType Ty = fieldTy;
  653. if (Ty->isReferenceType())
  654. Ty = Ty.getNonReferenceType();
  655. // Get element type.
  656. Ty = GetArrayEltType(CGM.getContext(), Ty);
  657. QualType EltTy = Ty;
  658. if (hlsl::IsHLSLMatType(Ty)) {
  659. DxilMatrixAnnotation Matrix;
  660. Matrix.Orientation = GetMatrixMajor(Ty, bDefaultRowMajor);
  661. hlsl::GetHLSLMatRowColCount(Ty, Matrix.Rows, Matrix.Cols);
  662. fieldAnnotation.SetMatrixAnnotation(Matrix);
  663. EltTy = hlsl::GetHLSLMatElementType(Ty);
  664. }
  665. if (hlsl::IsHLSLVecType(Ty))
  666. EltTy = hlsl::GetHLSLVecElementType(Ty);
  667. if (IsHLSLResourceType(Ty)) {
  668. // Always create for llvm::Type could be same for different QualType.
  669. // TODO: change to DxilProperties.
  670. MDNode *MD = GetOrAddResTypeMD(Ty, /*bCreate*/ true);
  671. fieldAnnotation.SetResourceAttribute(MD);
  672. }
  673. bool bSNorm = false;
  674. bool bUNorm = false;
  675. if (HasHLSLUNormSNorm(Ty, &bSNorm) && !bSNorm)
  676. bUNorm = true;
  677. if (EltTy->isBuiltinType()) {
  678. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  679. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  680. fieldAnnotation.SetCompType(kind);
  681. } else if (EltTy->isEnumeralType()) {
  682. const EnumType *ETy = EltTy->getAs<EnumType>();
  683. QualType type = ETy->getDecl()->getIntegerType();
  684. if (const BuiltinType *BTy =
  685. dyn_cast<BuiltinType>(type->getCanonicalTypeInternal()))
  686. fieldAnnotation.SetCompType(BuiltinTyToCompTy(BTy, bSNorm, bUNorm));
  687. } else {
  688. DXASSERT(!bSNorm && !bUNorm,
  689. "snorm/unorm on invalid type, validate at handleHLSLTypeAttr");
  690. }
  691. }
  692. static void ConstructFieldInterpolation(DxilFieldAnnotation &fieldAnnotation,
  693. FieldDecl *fieldDecl) {
  694. // Keep undefined for interpMode here.
  695. InterpolationMode InterpMode = {fieldDecl->hasAttr<HLSLNoInterpolationAttr>(),
  696. fieldDecl->hasAttr<HLSLLinearAttr>(),
  697. fieldDecl->hasAttr<HLSLNoPerspectiveAttr>(),
  698. fieldDecl->hasAttr<HLSLCentroidAttr>(),
  699. fieldDecl->hasAttr<HLSLSampleAttr>()};
  700. if (InterpMode.GetKind() != InterpolationMode::Kind::Undefined)
  701. fieldAnnotation.SetInterpolationMode(InterpMode);
  702. }
  703. static unsigned AlignBaseOffset(unsigned baseOffset, unsigned size, QualType Ty,
  704. bool bDefaultRowMajor) {
  705. bool needNewAlign = Ty->isArrayType();
  706. if (IsHLSLMatType(Ty)) {
  707. bool bRowMajor = false;
  708. if (!hlsl::HasHLSLMatOrientation(Ty, &bRowMajor))
  709. bRowMajor = bDefaultRowMajor;
  710. unsigned row, col;
  711. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  712. needNewAlign |= !bRowMajor && col > 1;
  713. needNewAlign |= bRowMajor && row > 1;
  714. } else if (Ty->isStructureOrClassType() && !hlsl::IsHLSLVecType(Ty)) {
  715. needNewAlign = true;
  716. }
  717. unsigned scalarSizeInBytes = 4;
  718. const clang::BuiltinType *BT = Ty->getAs<clang::BuiltinType>();
  719. if (hlsl::IsHLSLVecMatType(Ty)) {
  720. BT = hlsl::GetElementTypeOrType(Ty)->getAs<clang::BuiltinType>();
  721. }
  722. if (BT) {
  723. if (BT->getKind() == clang::BuiltinType::Kind::Double ||
  724. BT->getKind() == clang::BuiltinType::Kind::LongLong)
  725. scalarSizeInBytes = 8;
  726. else if (BT->getKind() == clang::BuiltinType::Kind::Half ||
  727. BT->getKind() == clang::BuiltinType::Kind::Short ||
  728. BT->getKind() == clang::BuiltinType::Kind::UShort)
  729. scalarSizeInBytes = 2;
  730. }
  731. return AlignBufferOffsetInLegacy(baseOffset, size, scalarSizeInBytes,
  732. needNewAlign);
  733. }
  734. static unsigned AlignBaseOffset(QualType Ty, unsigned baseOffset,
  735. bool bDefaultRowMajor,
  736. CodeGen::CodeGenModule &CGM,
  737. llvm::DataLayout &layout) {
  738. QualType paramTy = Ty.getCanonicalType();
  739. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  740. paramTy = RefType->getPointeeType();
  741. // Get size.
  742. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  743. unsigned size = layout.getTypeAllocSize(Type);
  744. return AlignBaseOffset(baseOffset, size, paramTy, bDefaultRowMajor);
  745. }
  746. unsigned CGMSHLSLRuntime::ConstructStructAnnotation(DxilStructAnnotation *annotation,
  747. const RecordDecl *RD,
  748. DxilTypeSystem &dxilTypeSys) {
  749. unsigned fieldIdx = 0;
  750. unsigned offset = 0;
  751. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  752. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  753. // If template, save template args
  754. if (const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  755. dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) {
  756. const clang::TemplateArgumentList &args = templateSpecializationDecl->getTemplateInstantiationArgs();
  757. for (unsigned i = 0; i < args.size(); ++i) {
  758. DxilTemplateArgAnnotation &argAnnotation = annotation->GetTemplateArgAnnotation(i);
  759. const clang::TemplateArgument &arg = args[i];
  760. switch (arg.getKind()) {
  761. case clang::TemplateArgument::ArgKind::Type:
  762. argAnnotation.SetType(CGM.getTypes().ConvertType(arg.getAsType()));
  763. break;
  764. case clang::TemplateArgument::ArgKind::Integral:
  765. argAnnotation.SetIntegral(arg.getAsIntegral().getExtValue());
  766. break;
  767. default:
  768. break;
  769. }
  770. }
  771. }
  772. if (CXXRD->getNumBases()) {
  773. // Add base as field.
  774. for (const auto &I : CXXRD->bases()) {
  775. const CXXRecordDecl *BaseDecl =
  776. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  777. std::string fieldSemName = "";
  778. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  779. // Align offset.
  780. offset = AlignBaseOffset(parentTy, offset, bDefaultRowMajor, CGM,
  781. dataLayout);
  782. unsigned CBufferOffset = offset;
  783. unsigned arrayEltSize = 0;
  784. // Process field to make sure the size of field is ready.
  785. unsigned size =
  786. AddTypeAnnotation(parentTy, dxilTypeSys, arrayEltSize);
  787. // Update offset.
  788. offset += size;
  789. if (size > 0) {
  790. DxilFieldAnnotation &fieldAnnotation =
  791. annotation->GetFieldAnnotation(fieldIdx++);
  792. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  793. fieldAnnotation.SetFieldName(BaseDecl->getNameAsString());
  794. }
  795. }
  796. }
  797. }
  798. for (auto fieldDecl : RD->fields()) {
  799. std::string fieldSemName = "";
  800. QualType fieldTy = fieldDecl->getType();
  801. DXASSERT(!fieldDecl->isBitField(), "We should have already ensured we have no bitfields.");
  802. // Align offset.
  803. offset = AlignBaseOffset(fieldTy, offset, bDefaultRowMajor, CGM, dataLayout);
  804. unsigned CBufferOffset = offset;
  805. // Try to get info from fieldDecl.
  806. for (const hlsl::UnusualAnnotation *it :
  807. fieldDecl->getUnusualAnnotations()) {
  808. switch (it->getKind()) {
  809. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  810. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  811. fieldSemName = sd->SemanticName;
  812. } break;
  813. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  814. const hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  815. CBufferOffset = cp->Subcomponent << 2;
  816. CBufferOffset += cp->ComponentOffset;
  817. // Change to byte.
  818. CBufferOffset <<= 2;
  819. } break;
  820. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  821. // register assignment only works on global constant.
  822. DiagnosticsEngine &Diags = CGM.getDiags();
  823. unsigned DiagID = Diags.getCustomDiagID(
  824. DiagnosticsEngine::Error,
  825. "location semantics cannot be specified on members.");
  826. Diags.Report(it->Loc, DiagID);
  827. return 0;
  828. } break;
  829. default:
  830. llvm_unreachable("only semantic for input/output");
  831. break;
  832. }
  833. }
  834. unsigned arrayEltSize = 0;
  835. // Process field to make sure the size of field is ready.
  836. unsigned size = AddTypeAnnotation(fieldDecl->getType(), dxilTypeSys, arrayEltSize);
  837. // Update offset.
  838. offset += size;
  839. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(fieldIdx++);
  840. ConstructFieldAttributedAnnotation(fieldAnnotation, fieldTy, bDefaultRowMajor);
  841. ConstructFieldInterpolation(fieldAnnotation, fieldDecl);
  842. if (fieldDecl->hasAttr<HLSLPreciseAttr>())
  843. fieldAnnotation.SetPrecise();
  844. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  845. fieldAnnotation.SetFieldName(fieldDecl->getName());
  846. if (!fieldSemName.empty()) {
  847. fieldAnnotation.SetSemanticString(fieldSemName);
  848. if (m_PreciseOutputSet.count(StringRef(fieldSemName).lower()))
  849. fieldAnnotation.SetPrecise();
  850. }
  851. }
  852. annotation->SetCBufferSize(offset);
  853. if (offset == 0) {
  854. annotation->MarkEmptyStruct();
  855. }
  856. return offset;
  857. }
  858. static bool IsElementInputOutputType(QualType Ty) {
  859. return Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty) || Ty->isEnumeralType();
  860. }
  861. static unsigned GetNumTemplateArgsForRecordDecl(const RecordDecl *RD) {
  862. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  863. if (const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  864. dyn_cast<ClassTemplateSpecializationDecl>(CXXRD)) {
  865. const clang::TemplateArgumentList &args = templateSpecializationDecl->getTemplateInstantiationArgs();
  866. return args.size();
  867. }
  868. }
  869. return 0;
  870. }
  871. // Return the size for constant buffer of each decl.
  872. unsigned CGMSHLSLRuntime::AddTypeAnnotation(QualType Ty,
  873. DxilTypeSystem &dxilTypeSys,
  874. unsigned &arrayEltSize) {
  875. QualType paramTy = Ty.getCanonicalType();
  876. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  877. paramTy = RefType->getPointeeType();
  878. // Get size.
  879. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  880. unsigned size = dataLayout.getTypeAllocSize(Type);
  881. if (IsHLSLMatType(Ty)) {
  882. llvm::Type *EltTy = HLMatrixType::cast(Type).getElementTypeForReg();
  883. bool b64Bit = dataLayout.getTypeAllocSize(EltTy) == 8;
  884. size = GetMatrixSizeInCB(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor,
  885. b64Bit);
  886. }
  887. // Skip element types.
  888. if (IsElementInputOutputType(paramTy))
  889. return size;
  890. else if (IsHLSLStreamOutputType(Ty)) {
  891. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  892. arrayEltSize);
  893. } else if (IsHLSLInputPatchType(Ty))
  894. return AddTypeAnnotation(GetHLSLInputPatchElementType(Ty), dxilTypeSys,
  895. arrayEltSize);
  896. else if (IsHLSLOutputPatchType(Ty))
  897. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  898. arrayEltSize);
  899. else if (const RecordType *RT = paramTy->getAsStructureType()) {
  900. RecordDecl *RD = RT->getDecl();
  901. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  902. // Skip if already created.
  903. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  904. unsigned structSize = annotation->GetCBufferSize();
  905. return structSize;
  906. }
  907. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST,
  908. GetNumTemplateArgsForRecordDecl(RT->getDecl()));
  909. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  910. } else if (const RecordType *RT = dyn_cast<RecordType>(paramTy)) {
  911. // For this pointer.
  912. RecordDecl *RD = RT->getDecl();
  913. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  914. // Skip if already created.
  915. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  916. unsigned structSize = annotation->GetCBufferSize();
  917. return structSize;
  918. }
  919. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST,
  920. GetNumTemplateArgsForRecordDecl(RT->getDecl()));
  921. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  922. } else if (IsHLSLResourceType(Ty)) {
  923. // Save result type info.
  924. AddTypeAnnotation(GetHLSLResourceResultType(Ty), dxilTypeSys, arrayEltSize);
  925. // Resource don't count for cbuffer size.
  926. return 0;
  927. } else if (IsStringType(Ty)) {
  928. // string won't be included in cbuffer
  929. return 0;
  930. } else {
  931. unsigned arraySize = 0;
  932. QualType arrayElementTy = Ty;
  933. if (Ty->isConstantArrayType()) {
  934. const ConstantArrayType *arrayTy =
  935. CGM.getContext().getAsConstantArrayType(Ty);
  936. DXASSERT(arrayTy != nullptr, "Must array type here");
  937. arraySize = arrayTy->getSize().getLimitedValue();
  938. arrayElementTy = arrayTy->getElementType();
  939. }
  940. else if (Ty->isIncompleteArrayType()) {
  941. const IncompleteArrayType *arrayTy = CGM.getContext().getAsIncompleteArrayType(Ty);
  942. arrayElementTy = arrayTy->getElementType();
  943. } else {
  944. DXASSERT(0, "Must array type here");
  945. }
  946. unsigned elementSize = AddTypeAnnotation(arrayElementTy, dxilTypeSys, arrayEltSize);
  947. // Only set arrayEltSize once.
  948. if (arrayEltSize == 0)
  949. arrayEltSize = elementSize;
  950. // Align to 4 * 4bytes.
  951. unsigned alignedSize = (elementSize + 15) & 0xfffffff0;
  952. return alignedSize * (arraySize - 1) + elementSize;
  953. }
  954. }
  955. static DxilResource::Kind KeywordToKind(StringRef keyword) {
  956. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  957. // compare)
  958. if (keyword == "Texture1D" || keyword == "RWTexture1D" || keyword == "RasterizerOrderedTexture1D")
  959. return DxilResource::Kind::Texture1D;
  960. if (keyword == "Texture2D" || keyword == "RWTexture2D" || keyword == "RasterizerOrderedTexture2D")
  961. return DxilResource::Kind::Texture2D;
  962. if (keyword == "Texture2DMS" || keyword == "RWTexture2DMS")
  963. return DxilResource::Kind::Texture2DMS;
  964. if (keyword == "FeedbackTexture2D")
  965. return DxilResource::Kind::FeedbackTexture2D;
  966. if (keyword == "Texture3D" || keyword == "RWTexture3D" || keyword == "RasterizerOrderedTexture3D")
  967. return DxilResource::Kind::Texture3D;
  968. if (keyword == "TextureCube" || keyword == "RWTextureCube")
  969. return DxilResource::Kind::TextureCube;
  970. if (keyword == "Texture1DArray" || keyword == "RWTexture1DArray" || keyword == "RasterizerOrderedTexture1DArray")
  971. return DxilResource::Kind::Texture1DArray;
  972. if (keyword == "Texture2DArray" || keyword == "RWTexture2DArray" || keyword == "RasterizerOrderedTexture2DArray")
  973. return DxilResource::Kind::Texture2DArray;
  974. if (keyword == "FeedbackTexture2DArray")
  975. return DxilResource::Kind::FeedbackTexture2DArray;
  976. if (keyword == "Texture2DMSArray" || keyword == "RWTexture2DMSArray")
  977. return DxilResource::Kind::Texture2DMSArray;
  978. if (keyword == "TextureCubeArray" || keyword == "RWTextureCubeArray")
  979. return DxilResource::Kind::TextureCubeArray;
  980. if (keyword == "ByteAddressBuffer" || keyword == "RWByteAddressBuffer" || keyword == "RasterizerOrderedByteAddressBuffer")
  981. return DxilResource::Kind::RawBuffer;
  982. if (keyword == "StructuredBuffer" || keyword == "RWStructuredBuffer" || keyword == "RasterizerOrderedStructuredBuffer")
  983. return DxilResource::Kind::StructuredBuffer;
  984. if (keyword == "AppendStructuredBuffer" || keyword == "ConsumeStructuredBuffer")
  985. return DxilResource::Kind::StructuredBuffer;
  986. // TODO: this is not efficient.
  987. bool isBuffer = keyword == "Buffer";
  988. isBuffer |= keyword == "RWBuffer";
  989. isBuffer |= keyword == "RasterizerOrderedBuffer";
  990. if (isBuffer)
  991. return DxilResource::Kind::TypedBuffer;
  992. if (keyword == "RaytracingAccelerationStructure")
  993. return DxilResource::Kind::RTAccelerationStructure;
  994. return DxilResource::Kind::Invalid;
  995. }
  996. void CGMSHLSLRuntime::AddHLSLFunctionInfo(Function *F, const FunctionDecl *FD) {
  997. // Add hlsl intrinsic attr
  998. unsigned intrinsicOpcode;
  999. StringRef intrinsicGroup;
  1000. if (hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup)) {
  1001. AddHLSLIntrinsicOpcodeToFunction(F, intrinsicOpcode);
  1002. F->addFnAttr(hlsl::HLPrefix, intrinsicGroup);
  1003. StringRef lower;
  1004. if (hlsl::GetIntrinsicLowering(FD, lower))
  1005. hlsl::SetHLLowerStrategy(F, lower);
  1006. if (FD->hasAttr<HLSLWaveSensitiveAttr>())
  1007. hlsl::SetHLWaveSensitive(F);
  1008. // Don't need to add FunctionQual for intrinsic function.
  1009. return;
  1010. }
  1011. if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::FTZ) {
  1012. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueFtzString);
  1013. }
  1014. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Preserve) {
  1015. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValuePreserveString);
  1016. }
  1017. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Any) {
  1018. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueAnyString);
  1019. }
  1020. // Set entry function
  1021. const std::string &entryName = m_pHLModule->GetEntryFunctionName();
  1022. bool isEntry = FD->getNameAsString() == entryName;
  1023. if (isEntry) {
  1024. Entry.Func = F;
  1025. Entry.SL = FD->getLocation();
  1026. }
  1027. DiagnosticsEngine &Diags = CGM.getDiags();
  1028. std::unique_ptr<DxilFunctionProps> funcProps =
  1029. llvm::make_unique<DxilFunctionProps>();
  1030. funcProps->shaderKind = DXIL::ShaderKind::Invalid;
  1031. bool isCS = false;
  1032. bool isGS = false;
  1033. bool isHS = false;
  1034. bool isDS = false;
  1035. bool isVS = false;
  1036. bool isPS = false;
  1037. bool isRay = false;
  1038. bool isMS = false;
  1039. bool isAS = false;
  1040. if (const HLSLShaderAttr *Attr = FD->getAttr<HLSLShaderAttr>()) {
  1041. // Stage is already validate in HandleDeclAttributeForHLSL.
  1042. // Here just check first letter (or two).
  1043. switch (Attr->getStage()[0]) {
  1044. case 'c':
  1045. switch (Attr->getStage()[1]) {
  1046. case 'o':
  1047. isCS = true;
  1048. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1049. break;
  1050. case 'l':
  1051. isRay = true;
  1052. funcProps->shaderKind = DXIL::ShaderKind::ClosestHit;
  1053. break;
  1054. case 'a':
  1055. isRay = true;
  1056. funcProps->shaderKind = DXIL::ShaderKind::Callable;
  1057. break;
  1058. default:
  1059. break;
  1060. }
  1061. break;
  1062. case 'v':
  1063. isVS = true;
  1064. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1065. break;
  1066. case 'h':
  1067. isHS = true;
  1068. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1069. break;
  1070. case 'd':
  1071. isDS = true;
  1072. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1073. break;
  1074. case 'g':
  1075. isGS = true;
  1076. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1077. break;
  1078. case 'p':
  1079. isPS = true;
  1080. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1081. break;
  1082. case 'r':
  1083. isRay = true;
  1084. funcProps->shaderKind = DXIL::ShaderKind::RayGeneration;
  1085. break;
  1086. case 'i':
  1087. isRay = true;
  1088. funcProps->shaderKind = DXIL::ShaderKind::Intersection;
  1089. break;
  1090. case 'a':
  1091. switch (Attr->getStage()[1]) {
  1092. case 'm':
  1093. isAS = true;
  1094. funcProps->shaderKind = DXIL::ShaderKind::Amplification;
  1095. break;
  1096. case 'n':
  1097. isRay = true;
  1098. funcProps->shaderKind = DXIL::ShaderKind::AnyHit;
  1099. break;
  1100. default:
  1101. break;
  1102. }
  1103. break;
  1104. case 'm':
  1105. switch (Attr->getStage()[1]) {
  1106. case 'e':
  1107. isMS = true;
  1108. funcProps->shaderKind = DXIL::ShaderKind::Mesh;
  1109. break;
  1110. case 'i':
  1111. isRay = true;
  1112. funcProps->shaderKind = DXIL::ShaderKind::Miss;
  1113. break;
  1114. default:
  1115. break;
  1116. }
  1117. break;
  1118. default:
  1119. break;
  1120. }
  1121. if (funcProps->shaderKind == DXIL::ShaderKind::Invalid) {
  1122. unsigned DiagID = Diags.getCustomDiagID(
  1123. DiagnosticsEngine::Error, "Invalid profile for shader attribute");
  1124. Diags.Report(Attr->getLocation(), DiagID);
  1125. }
  1126. if (isEntry && isRay) {
  1127. unsigned DiagID = Diags.getCustomDiagID(
  1128. DiagnosticsEngine::Error, "Ray function cannot be used as a global entry point");
  1129. Diags.Report(Attr->getLocation(), DiagID);
  1130. }
  1131. }
  1132. // Save patch constant function to patchConstantFunctionMap.
  1133. bool isPatchConstantFunction = false;
  1134. if (!isEntry && CGM.getContext().IsPatchConstantFunctionDecl(FD)) {
  1135. isPatchConstantFunction = true;
  1136. auto &PCI = patchConstantFunctionMap[FD->getName()];
  1137. PCI.SL = FD->getLocation();
  1138. PCI.Func = F;
  1139. ++PCI.NumOverloads;
  1140. for (ParmVarDecl *parmDecl : FD->parameters()) {
  1141. QualType Ty = parmDecl->getType();
  1142. if (IsHLSLOutputPatchType(Ty)) {
  1143. funcProps->ShaderProps.HS.outputControlPoints =
  1144. GetHLSLOutputPatchCount(parmDecl->getType());
  1145. } else if (IsHLSLInputPatchType(Ty)) {
  1146. funcProps->ShaderProps.HS.inputControlPoints =
  1147. GetHLSLInputPatchCount(parmDecl->getType());
  1148. }
  1149. }
  1150. // Mark patch constant functions that cannot be linked as exports
  1151. // InternalLinkage. Patch constant functions that are actually used
  1152. // will be set back to ExternalLinkage in FinishCodeGen.
  1153. if (funcProps->ShaderProps.HS.outputControlPoints ||
  1154. funcProps->ShaderProps.HS.inputControlPoints) {
  1155. PCI.Func->setLinkage(GlobalValue::InternalLinkage);
  1156. }
  1157. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1158. }
  1159. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1160. if (isEntry) {
  1161. funcProps->shaderKind = SM->GetKind();
  1162. if (funcProps->shaderKind == DXIL::ShaderKind::Mesh) {
  1163. isMS = true;
  1164. }
  1165. else if (funcProps->shaderKind == DXIL::ShaderKind::Amplification) {
  1166. isAS = true;
  1167. }
  1168. }
  1169. // Geometry shader.
  1170. if (const HLSLMaxVertexCountAttr *Attr =
  1171. FD->getAttr<HLSLMaxVertexCountAttr>()) {
  1172. isGS = true;
  1173. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1174. funcProps->ShaderProps.GS.maxVertexCount = Attr->getCount();
  1175. funcProps->ShaderProps.GS.inputPrimitive = DXIL::InputPrimitive::Undefined;
  1176. if (isEntry && !SM->IsGS()) {
  1177. unsigned DiagID =
  1178. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1179. "attribute maxvertexcount only valid for GS.");
  1180. Diags.Report(Attr->getLocation(), DiagID);
  1181. return;
  1182. }
  1183. }
  1184. if (const HLSLInstanceAttr *Attr = FD->getAttr<HLSLInstanceAttr>()) {
  1185. unsigned instanceCount = Attr->getCount();
  1186. funcProps->ShaderProps.GS.instanceCount = instanceCount;
  1187. if (isEntry && !SM->IsGS()) {
  1188. unsigned DiagID =
  1189. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1190. "attribute maxvertexcount only valid for GS.");
  1191. Diags.Report(Attr->getLocation(), DiagID);
  1192. return;
  1193. }
  1194. } else {
  1195. // Set default instance count.
  1196. if (isGS)
  1197. funcProps->ShaderProps.GS.instanceCount = 1;
  1198. }
  1199. // Compute shader
  1200. if (const HLSLNumThreadsAttr *Attr = FD->getAttr<HLSLNumThreadsAttr>()) {
  1201. if (isMS) {
  1202. funcProps->ShaderProps.MS.numThreads[0] = Attr->getX();
  1203. funcProps->ShaderProps.MS.numThreads[1] = Attr->getY();
  1204. funcProps->ShaderProps.MS.numThreads[2] = Attr->getZ();
  1205. } else if (isAS) {
  1206. funcProps->ShaderProps.AS.numThreads[0] = Attr->getX();
  1207. funcProps->ShaderProps.AS.numThreads[1] = Attr->getY();
  1208. funcProps->ShaderProps.AS.numThreads[2] = Attr->getZ();
  1209. } else {
  1210. isCS = true;
  1211. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1212. funcProps->ShaderProps.CS.numThreads[0] = Attr->getX();
  1213. funcProps->ShaderProps.CS.numThreads[1] = Attr->getY();
  1214. funcProps->ShaderProps.CS.numThreads[2] = Attr->getZ();
  1215. }
  1216. if (isEntry && !SM->IsCS() && !SM->IsMS() && !SM->IsAS()) {
  1217. unsigned DiagID = Diags.getCustomDiagID(
  1218. DiagnosticsEngine::Error, "attribute numthreads only valid for CS/MS/AS.");
  1219. Diags.Report(Attr->getLocation(), DiagID);
  1220. return;
  1221. }
  1222. }
  1223. // Hull shader.
  1224. if (const HLSLPatchConstantFuncAttr *Attr =
  1225. FD->getAttr<HLSLPatchConstantFuncAttr>()) {
  1226. if (isEntry && !SM->IsHS()) {
  1227. unsigned DiagID = Diags.getCustomDiagID(
  1228. DiagnosticsEngine::Error,
  1229. "attribute patchconstantfunc only valid for HS.");
  1230. Diags.Report(Attr->getLocation(), DiagID);
  1231. return;
  1232. }
  1233. isHS = true;
  1234. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1235. HSEntryPatchConstantFuncAttr[F] = Attr;
  1236. } else {
  1237. // TODO: This is a duplicate check. We also have this check in
  1238. // hlsl::DiagnoseTranslationUnit(clang::Sema*).
  1239. if (isEntry && SM->IsHS()) {
  1240. unsigned DiagID = Diags.getCustomDiagID(
  1241. DiagnosticsEngine::Error,
  1242. "HS entry point must have the patchconstantfunc attribute");
  1243. Diags.Report(FD->getLocation(), DiagID);
  1244. return;
  1245. }
  1246. }
  1247. if (const HLSLOutputControlPointsAttr *Attr =
  1248. FD->getAttr<HLSLOutputControlPointsAttr>()) {
  1249. if (isHS) {
  1250. funcProps->ShaderProps.HS.outputControlPoints = Attr->getCount();
  1251. } else if (isEntry && !SM->IsHS()) {
  1252. unsigned DiagID = Diags.getCustomDiagID(
  1253. DiagnosticsEngine::Error,
  1254. "attribute outputcontrolpoints only valid for HS.");
  1255. Diags.Report(Attr->getLocation(), DiagID);
  1256. return;
  1257. }
  1258. }
  1259. if (const HLSLPartitioningAttr *Attr = FD->getAttr<HLSLPartitioningAttr>()) {
  1260. if (isHS) {
  1261. DXIL::TessellatorPartitioning partition =
  1262. StringToPartitioning(Attr->getScheme());
  1263. funcProps->ShaderProps.HS.partition = partition;
  1264. } else if (isEntry && !SM->IsHS()) {
  1265. unsigned DiagID =
  1266. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1267. "attribute partitioning only valid for HS.");
  1268. Diags.Report(Attr->getLocation(), DiagID);
  1269. }
  1270. }
  1271. if (const HLSLOutputTopologyAttr *Attr =
  1272. FD->getAttr<HLSLOutputTopologyAttr>()) {
  1273. if (isHS) {
  1274. DXIL::TessellatorOutputPrimitive primitive =
  1275. StringToTessOutputPrimitive(Attr->getTopology());
  1276. funcProps->ShaderProps.HS.outputPrimitive = primitive;
  1277. }
  1278. else if (isMS) {
  1279. DXIL::MeshOutputTopology topology =
  1280. StringToMeshOutputTopology(Attr->getTopology());
  1281. funcProps->ShaderProps.MS.outputTopology = topology;
  1282. }
  1283. else if (isEntry && !SM->IsHS() && !SM->IsMS()) {
  1284. unsigned DiagID =
  1285. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1286. "attribute outputtopology only valid for HS and MS.");
  1287. Diags.Report(Attr->getLocation(), DiagID);
  1288. }
  1289. }
  1290. if (isHS) {
  1291. funcProps->ShaderProps.HS.maxTessFactor = DXIL::kHSMaxTessFactorUpperBound;
  1292. funcProps->ShaderProps.HS.inputControlPoints = DXIL::kHSDefaultInputControlPointCount;
  1293. }
  1294. if (const HLSLMaxTessFactorAttr *Attr =
  1295. FD->getAttr<HLSLMaxTessFactorAttr>()) {
  1296. if (isHS) {
  1297. // TODO: change getFactor to return float.
  1298. llvm::APInt intV(32, Attr->getFactor());
  1299. funcProps->ShaderProps.HS.maxTessFactor = intV.bitsToFloat();
  1300. } else if (isEntry && !SM->IsHS()) {
  1301. unsigned DiagID =
  1302. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1303. "attribute maxtessfactor only valid for HS.");
  1304. Diags.Report(Attr->getLocation(), DiagID);
  1305. return;
  1306. }
  1307. }
  1308. // Hull or domain shader.
  1309. if (const HLSLDomainAttr *Attr = FD->getAttr<HLSLDomainAttr>()) {
  1310. if (isEntry && !SM->IsHS() && !SM->IsDS()) {
  1311. unsigned DiagID =
  1312. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1313. "attribute domain only valid for HS or DS.");
  1314. Diags.Report(Attr->getLocation(), DiagID);
  1315. return;
  1316. }
  1317. isDS = !isHS;
  1318. if (isDS)
  1319. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1320. DXIL::TessellatorDomain domain = StringToDomain(Attr->getDomainType());
  1321. if (isHS)
  1322. funcProps->ShaderProps.HS.domain = domain;
  1323. else
  1324. funcProps->ShaderProps.DS.domain = domain;
  1325. }
  1326. // Vertex shader.
  1327. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1328. if (isEntry && !SM->IsVS()) {
  1329. unsigned DiagID = Diags.getCustomDiagID(
  1330. DiagnosticsEngine::Error, "attribute clipplane only valid for VS.");
  1331. Diags.Report(Attr->getLocation(), DiagID);
  1332. return;
  1333. }
  1334. isVS = true;
  1335. // The real job is done at EmitHLSLFunctionProlog where debug info is
  1336. // available. Only set shader kind here.
  1337. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1338. }
  1339. // Pixel shader.
  1340. if (const HLSLEarlyDepthStencilAttr *Attr =
  1341. FD->getAttr<HLSLEarlyDepthStencilAttr>()) {
  1342. if (isEntry && !SM->IsPS()) {
  1343. unsigned DiagID = Diags.getCustomDiagID(
  1344. DiagnosticsEngine::Error,
  1345. "attribute earlydepthstencil only valid for PS.");
  1346. Diags.Report(Attr->getLocation(), DiagID);
  1347. return;
  1348. }
  1349. isPS = true;
  1350. funcProps->ShaderProps.PS.EarlyDepthStencil = true;
  1351. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1352. }
  1353. const unsigned profileAttributes = isCS + isHS + isDS + isGS + isVS + isPS + isRay + isMS + isAS;
  1354. // TODO: check this in front-end and report error.
  1355. DXASSERT(profileAttributes < 2, "profile attributes are mutual exclusive");
  1356. if (isEntry) {
  1357. switch (funcProps->shaderKind) {
  1358. case ShaderModel::Kind::Compute:
  1359. case ShaderModel::Kind::Hull:
  1360. case ShaderModel::Kind::Domain:
  1361. case ShaderModel::Kind::Geometry:
  1362. case ShaderModel::Kind::Vertex:
  1363. case ShaderModel::Kind::Pixel:
  1364. case ShaderModel::Kind::Mesh:
  1365. case ShaderModel::Kind::Amplification:
  1366. DXASSERT(funcProps->shaderKind == SM->GetKind(),
  1367. "attribute profile not match entry function profile");
  1368. break;
  1369. case ShaderModel::Kind::Library:
  1370. case ShaderModel::Kind::Invalid:
  1371. // Non-shader stage shadermodels don't have entry points.
  1372. break;
  1373. }
  1374. }
  1375. DxilFunctionAnnotation *FuncAnnotation =
  1376. m_pHLModule->AddFunctionAnnotation(F);
  1377. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  1378. // Param Info
  1379. unsigned streamIndex = 0;
  1380. unsigned inputPatchCount = 0;
  1381. unsigned outputPatchCount = 0;
  1382. unsigned ArgNo = 0;
  1383. unsigned ParmIdx = 0;
  1384. auto ArgIt = F->arg_begin();
  1385. if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FD)) {
  1386. if (MethodDecl->isInstance()) {
  1387. QualType ThisTy = MethodDecl->getThisType(FD->getASTContext());
  1388. DxilParameterAnnotation &paramAnnotation =
  1389. FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1390. ++ArgIt;
  1391. // Construct annoation for this pointer.
  1392. ConstructFieldAttributedAnnotation(paramAnnotation, ThisTy,
  1393. bDefaultRowMajor);
  1394. if (MethodDecl->isConst()) {
  1395. paramAnnotation.SetParamInputQual(DxilParamInputQual::In);
  1396. } else {
  1397. paramAnnotation.SetParamInputQual(DxilParamInputQual::Inout);
  1398. }
  1399. }
  1400. }
  1401. // Ret Info
  1402. QualType retTy = FD->getReturnType();
  1403. DxilParameterAnnotation *pRetTyAnnotation = nullptr;
  1404. if (F->getReturnType()->isVoidTy() && !retTy->isVoidType()) {
  1405. // SRet.
  1406. pRetTyAnnotation = &FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1407. // Save resource properties for parameters.
  1408. DxilResourceProperties RP = BuildResourceProperty(retTy);
  1409. if (RP.Class != DXIL::ResourceClass::Invalid)
  1410. valToResPropertiesMap[ArgIt] = RP;
  1411. ++ArgIt;
  1412. } else {
  1413. pRetTyAnnotation = &FuncAnnotation->GetRetTypeAnnotation();
  1414. }
  1415. DxilParameterAnnotation &retTyAnnotation = *pRetTyAnnotation;
  1416. // keep Undefined here, we cannot decide for struct
  1417. retTyAnnotation.SetInterpolationMode(
  1418. GetInterpMode(FD, CompType::Kind::Invalid, /*bKeepUndefined*/ true)
  1419. .GetKind());
  1420. SourceLocation retTySemanticLoc = SetSemantic(FD, retTyAnnotation);
  1421. retTyAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  1422. if (isEntry) {
  1423. if (CGM.getLangOpts().EnableDX9CompatMode && retTyAnnotation.HasSemanticString()) {
  1424. RemapObsoleteSemantic(retTyAnnotation, /*isPatchConstantFunction*/ false);
  1425. }
  1426. CheckParameterAnnotation(retTySemanticLoc, retTyAnnotation,
  1427. /*isPatchConstantFunction*/ false);
  1428. }
  1429. if (isRay && !retTy->isVoidType()) {
  1430. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1431. DiagnosticsEngine::Error, "return type for ray tracing shaders must be void"));
  1432. }
  1433. ConstructFieldAttributedAnnotation(retTyAnnotation, retTy, bDefaultRowMajor);
  1434. if (FD->hasAttr<HLSLPreciseAttr>())
  1435. retTyAnnotation.SetPrecise();
  1436. if (isRay) {
  1437. funcProps->ShaderProps.Ray.payloadSizeInBytes = 0;
  1438. funcProps->ShaderProps.Ray.attributeSizeInBytes = 0;
  1439. }
  1440. bool hasOutIndices = false;
  1441. bool hasOutVertices = false;
  1442. bool hasOutPrimitives = false;
  1443. bool hasInPayload = false;
  1444. for (; ArgNo < F->arg_size(); ++ArgNo, ++ParmIdx, ++ArgIt) {
  1445. DxilParameterAnnotation &paramAnnotation =
  1446. FuncAnnotation->GetParameterAnnotation(ArgNo);
  1447. const ParmVarDecl *parmDecl = FD->getParamDecl(ParmIdx);
  1448. QualType fieldTy = parmDecl->getType();
  1449. // Save resource properties for parameters.
  1450. DxilResourceProperties RP = BuildResourceProperty(fieldTy);
  1451. if (RP.Class != DXIL::ResourceClass::Invalid)
  1452. valToResPropertiesMap[ArgIt] = RP;
  1453. // if parameter type is a typedef, try to desugar it first.
  1454. if (isa<TypedefType>(fieldTy.getTypePtr()))
  1455. fieldTy = fieldTy.getDesugaredType(FD->getASTContext());
  1456. ConstructFieldAttributedAnnotation(paramAnnotation, fieldTy,
  1457. bDefaultRowMajor);
  1458. if (parmDecl->hasAttr<HLSLPreciseAttr>())
  1459. paramAnnotation.SetPrecise();
  1460. // keep Undefined here, we cannot decide for struct
  1461. InterpolationMode paramIM =
  1462. GetInterpMode(parmDecl, CompType::Kind::Invalid, KeepUndefinedTrue);
  1463. paramAnnotation.SetInterpolationMode(paramIM);
  1464. SourceLocation paramSemanticLoc = SetSemantic(parmDecl, paramAnnotation);
  1465. DxilParamInputQual dxilInputQ = DxilParamInputQual::In;
  1466. if (parmDecl->hasAttr<HLSLInOutAttr>())
  1467. dxilInputQ = DxilParamInputQual::Inout;
  1468. else if (parmDecl->hasAttr<HLSLOutAttr>())
  1469. dxilInputQ = DxilParamInputQual::Out;
  1470. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLInAttr>())
  1471. dxilInputQ = DxilParamInputQual::Inout;
  1472. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLIndicesAttr>()) {
  1473. if (hasOutIndices) {
  1474. unsigned DiagID = Diags.getCustomDiagID(
  1475. DiagnosticsEngine::Error,
  1476. "multiple out indices parameters not allowed");
  1477. Diags.Report(parmDecl->getLocation(), DiagID);
  1478. continue;
  1479. }
  1480. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1481. if (CAT == nullptr) {
  1482. unsigned DiagID = Diags.getCustomDiagID(
  1483. DiagnosticsEngine::Error,
  1484. "indices output is not an constant-length array");
  1485. Diags.Report(parmDecl->getLocation(), DiagID);
  1486. continue;
  1487. }
  1488. unsigned count = CAT->getSize().getZExtValue();
  1489. if (count > DXIL::kMaxMSOutputPrimitiveCount) {
  1490. unsigned DiagID = Diags.getCustomDiagID(
  1491. DiagnosticsEngine::Error,
  1492. "max primitive count should not exceed %0");
  1493. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputPrimitiveCount;
  1494. continue;
  1495. }
  1496. if (funcProps->ShaderProps.MS.maxPrimitiveCount != 0 &&
  1497. funcProps->ShaderProps.MS.maxPrimitiveCount != count) {
  1498. unsigned DiagID = Diags.getCustomDiagID(
  1499. DiagnosticsEngine::Error,
  1500. "max primitive count mismatch");
  1501. Diags.Report(parmDecl->getLocation(), DiagID);
  1502. continue;
  1503. }
  1504. // Get element type.
  1505. QualType arrayEleTy = CAT->getElementType();
  1506. if (hlsl::IsHLSLVecType(arrayEleTy)) {
  1507. QualType vecEltTy = hlsl::GetHLSLVecElementType(arrayEleTy);
  1508. if (!vecEltTy->isUnsignedIntegerType() || CGM.getContext().getTypeSize(vecEltTy) != 32) {
  1509. unsigned DiagID = Diags.getCustomDiagID(
  1510. DiagnosticsEngine::Error,
  1511. "the element of out_indices array must be uint2 for line output or uint3 for triangle output");
  1512. Diags.Report(parmDecl->getLocation(), DiagID);
  1513. continue;
  1514. }
  1515. unsigned vecEltCount = hlsl::GetHLSLVecSize(arrayEleTy);
  1516. if (funcProps->ShaderProps.MS.outputTopology == DXIL::MeshOutputTopology::Line && vecEltCount != 2) {
  1517. unsigned DiagID = Diags.getCustomDiagID(
  1518. DiagnosticsEngine::Error,
  1519. "the element of out_indices array in a mesh shader whose output topology is line must be uint2");
  1520. Diags.Report(parmDecl->getLocation(), DiagID);
  1521. continue;
  1522. }
  1523. if (funcProps->ShaderProps.MS.outputTopology == DXIL::MeshOutputTopology::Triangle && vecEltCount != 3) {
  1524. unsigned DiagID = Diags.getCustomDiagID(
  1525. DiagnosticsEngine::Error,
  1526. "the element of out_indices array in a mesh shader whose output topology is triangle must be uint3");
  1527. Diags.Report(parmDecl->getLocation(), DiagID);
  1528. continue;
  1529. }
  1530. } else {
  1531. unsigned DiagID = Diags.getCustomDiagID(
  1532. DiagnosticsEngine::Error,
  1533. "the element of out_indices array must be uint2 for line output or uint3 for triangle output");
  1534. Diags.Report(parmDecl->getLocation(), DiagID);
  1535. continue;
  1536. }
  1537. dxilInputQ = DxilParamInputQual::OutIndices;
  1538. funcProps->ShaderProps.MS.maxPrimitiveCount = count;
  1539. hasOutIndices = true;
  1540. }
  1541. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLVerticesAttr>()) {
  1542. if (hasOutVertices) {
  1543. unsigned DiagID = Diags.getCustomDiagID(
  1544. DiagnosticsEngine::Error,
  1545. "multiple out vertices parameters not allowed");
  1546. Diags.Report(parmDecl->getLocation(), DiagID);
  1547. continue;
  1548. }
  1549. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1550. if (CAT == nullptr) {
  1551. unsigned DiagID = Diags.getCustomDiagID(
  1552. DiagnosticsEngine::Error,
  1553. "vertices output is not an constant-length array");
  1554. Diags.Report(parmDecl->getLocation(), DiagID);
  1555. continue;
  1556. }
  1557. unsigned count = CAT->getSize().getZExtValue();
  1558. if (count > DXIL::kMaxMSOutputVertexCount) {
  1559. unsigned DiagID = Diags.getCustomDiagID(
  1560. DiagnosticsEngine::Error,
  1561. "max vertex count should not exceed %0");
  1562. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputVertexCount;
  1563. continue;
  1564. }
  1565. dxilInputQ = DxilParamInputQual::OutVertices;
  1566. funcProps->ShaderProps.MS.maxVertexCount = count;
  1567. hasOutVertices = true;
  1568. }
  1569. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLPrimitivesAttr>()) {
  1570. if (hasOutPrimitives) {
  1571. unsigned DiagID = Diags.getCustomDiagID(
  1572. DiagnosticsEngine::Error,
  1573. "multiple out primitives parameters not allowed");
  1574. Diags.Report(parmDecl->getLocation(), DiagID);
  1575. continue;
  1576. }
  1577. const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(fieldTy.getCanonicalType());
  1578. if (CAT == nullptr) {
  1579. unsigned DiagID = Diags.getCustomDiagID(
  1580. DiagnosticsEngine::Error,
  1581. "primitives output is not an constant-length array");
  1582. Diags.Report(parmDecl->getLocation(), DiagID);
  1583. continue;
  1584. }
  1585. unsigned count = CAT->getSize().getZExtValue();
  1586. if (count > DXIL::kMaxMSOutputPrimitiveCount) {
  1587. unsigned DiagID = Diags.getCustomDiagID(
  1588. DiagnosticsEngine::Error,
  1589. "max primitive count should not exceed %0");
  1590. Diags.Report(parmDecl->getLocation(), DiagID) << DXIL::kMaxMSOutputPrimitiveCount;
  1591. continue;
  1592. }
  1593. if (funcProps->ShaderProps.MS.maxPrimitiveCount != 0 &&
  1594. funcProps->ShaderProps.MS.maxPrimitiveCount != count) {
  1595. unsigned DiagID = Diags.getCustomDiagID(
  1596. DiagnosticsEngine::Error,
  1597. "max primitive count mismatch");
  1598. Diags.Report(parmDecl->getLocation(), DiagID);
  1599. continue;
  1600. }
  1601. dxilInputQ = DxilParamInputQual::OutPrimitives;
  1602. funcProps->ShaderProps.MS.maxPrimitiveCount = count;
  1603. hasOutPrimitives = true;
  1604. }
  1605. if (parmDecl->hasAttr<HLSLInAttr>() && parmDecl->hasAttr<HLSLPayloadAttr>()) {
  1606. if (hasInPayload) {
  1607. unsigned DiagID = Diags.getCustomDiagID(
  1608. DiagnosticsEngine::Error,
  1609. "multiple in payload parameters not allowed");
  1610. Diags.Report(parmDecl->getLocation(), DiagID);
  1611. continue;
  1612. }
  1613. dxilInputQ = DxilParamInputQual::InPayload;
  1614. DataLayout DL(&this->TheModule);
  1615. funcProps->ShaderProps.MS.payloadSizeInBytes = DL.getTypeAllocSize(
  1616. F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1617. hasInPayload = true;
  1618. }
  1619. DXIL::InputPrimitive inputPrimitive = DXIL::InputPrimitive::Undefined;
  1620. if (IsHLSLOutputPatchType(parmDecl->getType())) {
  1621. outputPatchCount++;
  1622. if (dxilInputQ != DxilParamInputQual::In) {
  1623. unsigned DiagID = Diags.getCustomDiagID(
  1624. DiagnosticsEngine::Error,
  1625. "OutputPatch should not be out/inout parameter");
  1626. Diags.Report(parmDecl->getLocation(), DiagID);
  1627. continue;
  1628. }
  1629. dxilInputQ = DxilParamInputQual::OutputPatch;
  1630. if (isDS)
  1631. funcProps->ShaderProps.DS.inputControlPoints =
  1632. GetHLSLOutputPatchCount(parmDecl->getType());
  1633. } else if (IsHLSLInputPatchType(parmDecl->getType())) {
  1634. inputPatchCount++;
  1635. if (dxilInputQ != DxilParamInputQual::In) {
  1636. unsigned DiagID = Diags.getCustomDiagID(
  1637. DiagnosticsEngine::Error,
  1638. "InputPatch should not be out/inout parameter");
  1639. Diags.Report(parmDecl->getLocation(), DiagID);
  1640. continue;
  1641. }
  1642. dxilInputQ = DxilParamInputQual::InputPatch;
  1643. if (isHS) {
  1644. funcProps->ShaderProps.HS.inputControlPoints =
  1645. GetHLSLInputPatchCount(parmDecl->getType());
  1646. } else if (isGS) {
  1647. inputPrimitive = (DXIL::InputPrimitive)(
  1648. (unsigned)DXIL::InputPrimitive::ControlPointPatch1 +
  1649. GetHLSLInputPatchCount(parmDecl->getType()) - 1);
  1650. }
  1651. } else if (IsHLSLStreamOutputType(parmDecl->getType())) {
  1652. // TODO: validation this at ASTContext::getFunctionType in
  1653. // AST/ASTContext.cpp
  1654. DXASSERT(dxilInputQ == DxilParamInputQual::Inout,
  1655. "stream output parameter must be inout");
  1656. switch (streamIndex) {
  1657. case 0:
  1658. dxilInputQ = DxilParamInputQual::OutStream0;
  1659. break;
  1660. case 1:
  1661. dxilInputQ = DxilParamInputQual::OutStream1;
  1662. break;
  1663. case 2:
  1664. dxilInputQ = DxilParamInputQual::OutStream2;
  1665. break;
  1666. case 3:
  1667. default:
  1668. // TODO: validation this at ASTContext::getFunctionType in
  1669. // AST/ASTContext.cpp
  1670. DXASSERT(streamIndex == 3, "stream number out of bound");
  1671. dxilInputQ = DxilParamInputQual::OutStream3;
  1672. break;
  1673. }
  1674. DXIL::PrimitiveTopology &streamTopology =
  1675. funcProps->ShaderProps.GS.streamPrimitiveTopologies[streamIndex];
  1676. if (IsHLSLPointStreamType(parmDecl->getType()))
  1677. streamTopology = DXIL::PrimitiveTopology::PointList;
  1678. else if (IsHLSLLineStreamType(parmDecl->getType()))
  1679. streamTopology = DXIL::PrimitiveTopology::LineStrip;
  1680. else {
  1681. DXASSERT(IsHLSLTriangleStreamType(parmDecl->getType()),
  1682. "invalid StreamType");
  1683. streamTopology = DXIL::PrimitiveTopology::TriangleStrip;
  1684. }
  1685. if (streamIndex > 0) {
  1686. bool bAllPoint =
  1687. streamTopology == DXIL::PrimitiveTopology::PointList &&
  1688. funcProps->ShaderProps.GS.streamPrimitiveTopologies[0] ==
  1689. DXIL::PrimitiveTopology::PointList;
  1690. if (!bAllPoint) {
  1691. unsigned DiagID = Diags.getCustomDiagID(
  1692. DiagnosticsEngine::Error, "when multiple GS output streams are "
  1693. "used they must be pointlists.");
  1694. Diags.Report(FD->getLocation(), DiagID);
  1695. }
  1696. }
  1697. streamIndex++;
  1698. }
  1699. unsigned GsInputArrayDim = 0;
  1700. if (parmDecl->hasAttr<HLSLTriangleAttr>()) {
  1701. inputPrimitive = DXIL::InputPrimitive::Triangle;
  1702. GsInputArrayDim = 3;
  1703. } else if (parmDecl->hasAttr<HLSLTriangleAdjAttr>()) {
  1704. inputPrimitive = DXIL::InputPrimitive::TriangleWithAdjacency;
  1705. GsInputArrayDim = 6;
  1706. } else if (parmDecl->hasAttr<HLSLPointAttr>()) {
  1707. inputPrimitive = DXIL::InputPrimitive::Point;
  1708. GsInputArrayDim = 1;
  1709. } else if (parmDecl->hasAttr<HLSLLineAdjAttr>()) {
  1710. inputPrimitive = DXIL::InputPrimitive::LineWithAdjacency;
  1711. GsInputArrayDim = 4;
  1712. } else if (parmDecl->hasAttr<HLSLLineAttr>()) {
  1713. inputPrimitive = DXIL::InputPrimitive::Line;
  1714. GsInputArrayDim = 2;
  1715. }
  1716. if (inputPrimitive != DXIL::InputPrimitive::Undefined) {
  1717. // Set to InputPrimitive for GS.
  1718. dxilInputQ = DxilParamInputQual::InputPrimitive;
  1719. if (funcProps->ShaderProps.GS.inputPrimitive ==
  1720. DXIL::InputPrimitive::Undefined) {
  1721. funcProps->ShaderProps.GS.inputPrimitive = inputPrimitive;
  1722. } else if (funcProps->ShaderProps.GS.inputPrimitive != inputPrimitive) {
  1723. unsigned DiagID = Diags.getCustomDiagID(
  1724. DiagnosticsEngine::Error, "input parameter conflicts with geometry "
  1725. "specifier of previous input parameters");
  1726. Diags.Report(parmDecl->getLocation(), DiagID);
  1727. }
  1728. }
  1729. if (GsInputArrayDim != 0) {
  1730. QualType Ty = parmDecl->getType();
  1731. if (!Ty->isConstantArrayType()) {
  1732. unsigned DiagID = Diags.getCustomDiagID(
  1733. DiagnosticsEngine::Error,
  1734. "input types for geometry shader must be constant size arrays");
  1735. Diags.Report(parmDecl->getLocation(), DiagID);
  1736. } else {
  1737. const ConstantArrayType *CAT = cast<ConstantArrayType>(Ty);
  1738. if (CAT->getSize().getLimitedValue() != GsInputArrayDim) {
  1739. StringRef primtiveNames[] = {
  1740. "invalid", // 0
  1741. "point", // 1
  1742. "line", // 2
  1743. "triangle", // 3
  1744. "lineadj", // 4
  1745. "invalid", // 5
  1746. "triangleadj", // 6
  1747. };
  1748. DXASSERT(GsInputArrayDim < llvm::array_lengthof(primtiveNames),
  1749. "Invalid array dim");
  1750. unsigned DiagID = Diags.getCustomDiagID(
  1751. DiagnosticsEngine::Error, "array dimension for %0 must be %1");
  1752. Diags.Report(parmDecl->getLocation(), DiagID)
  1753. << primtiveNames[GsInputArrayDim] << GsInputArrayDim;
  1754. }
  1755. }
  1756. }
  1757. // Validate Ray Tracing function parameter (some validation may be pushed into front end)
  1758. if (isRay) {
  1759. switch (funcProps->shaderKind) {
  1760. case DXIL::ShaderKind::RayGeneration:
  1761. case DXIL::ShaderKind::Intersection:
  1762. // RayGeneration and Intersection shaders are not allowed to have any input parameters
  1763. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1764. DiagnosticsEngine::Error, "parameters are not allowed for %0 shader"))
  1765. << (funcProps->shaderKind == DXIL::ShaderKind::RayGeneration ?
  1766. "raygeneration" : "intersection");
  1767. break;
  1768. case DXIL::ShaderKind::AnyHit:
  1769. case DXIL::ShaderKind::ClosestHit:
  1770. if (0 == ArgNo && dxilInputQ != DxilParamInputQual::Inout) {
  1771. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1772. DiagnosticsEngine::Error,
  1773. "ray payload parameter must be inout"));
  1774. } else if (1 == ArgNo && dxilInputQ != DxilParamInputQual::In) {
  1775. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1776. DiagnosticsEngine::Error,
  1777. "intersection attributes parameter must be in"));
  1778. } else if (ArgNo > 1) {
  1779. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1780. DiagnosticsEngine::Error,
  1781. "too many parameters, expected payload and attributes parameters only."));
  1782. }
  1783. if (ArgNo < 2) {
  1784. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1785. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1786. DiagnosticsEngine::Error,
  1787. "payload and attribute structures must be user defined types with only numeric contents."));
  1788. } else {
  1789. DataLayout DL(&this->TheModule);
  1790. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1791. if (0 == ArgNo)
  1792. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1793. else
  1794. funcProps->ShaderProps.Ray.attributeSizeInBytes = size;
  1795. }
  1796. }
  1797. break;
  1798. case DXIL::ShaderKind::Miss:
  1799. if (ArgNo > 0) {
  1800. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1801. DiagnosticsEngine::Error,
  1802. "only one parameter (ray payload) allowed for miss shader"));
  1803. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1804. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1805. DiagnosticsEngine::Error,
  1806. "ray payload parameter must be declared inout"));
  1807. }
  1808. if (ArgNo < 1) {
  1809. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1810. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1811. DiagnosticsEngine::Error,
  1812. "ray payload parameter must be a user defined type with only numeric contents."));
  1813. } else {
  1814. DataLayout DL(&this->TheModule);
  1815. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1816. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1817. }
  1818. }
  1819. break;
  1820. case DXIL::ShaderKind::Callable:
  1821. if (ArgNo > 0) {
  1822. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1823. DiagnosticsEngine::Error,
  1824. "only one parameter allowed for callable shader"));
  1825. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1826. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1827. DiagnosticsEngine::Error,
  1828. "callable parameter must be declared inout"));
  1829. }
  1830. if (ArgNo < 1) {
  1831. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1832. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1833. DiagnosticsEngine::Error,
  1834. "callable parameter must be a user defined type with only numeric contents."));
  1835. } else {
  1836. DataLayout DL(&this->TheModule);
  1837. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1838. funcProps->ShaderProps.Ray.paramSizeInBytes = size;
  1839. }
  1840. }
  1841. break;
  1842. }
  1843. }
  1844. paramAnnotation.SetParamInputQual(dxilInputQ);
  1845. if (isEntry) {
  1846. if (CGM.getLangOpts().EnableDX9CompatMode && paramAnnotation.HasSemanticString()) {
  1847. RemapObsoleteSemantic(paramAnnotation, /*isPatchConstantFunction*/ false);
  1848. }
  1849. CheckParameterAnnotation(paramSemanticLoc, paramAnnotation,
  1850. /*isPatchConstantFunction*/ false);
  1851. }
  1852. }
  1853. if (inputPatchCount > 1) {
  1854. unsigned DiagID = Diags.getCustomDiagID(
  1855. DiagnosticsEngine::Error, "may only have one InputPatch parameter");
  1856. Diags.Report(FD->getLocation(), DiagID);
  1857. }
  1858. if (outputPatchCount > 1) {
  1859. unsigned DiagID = Diags.getCustomDiagID(
  1860. DiagnosticsEngine::Error, "may only have one OutputPatch parameter");
  1861. Diags.Report(FD->getLocation(), DiagID);
  1862. }
  1863. // If Shader is a ray shader that requires parameters, make sure size is non-zero
  1864. if (isRay) {
  1865. bool bNeedsAttributes = false;
  1866. bool bNeedsPayload = false;
  1867. switch (funcProps->shaderKind) {
  1868. case DXIL::ShaderKind::AnyHit:
  1869. case DXIL::ShaderKind::ClosestHit:
  1870. bNeedsAttributes = true;
  1871. case DXIL::ShaderKind::Miss:
  1872. bNeedsPayload = true;
  1873. case DXIL::ShaderKind::Callable:
  1874. if (0 == funcProps->ShaderProps.Ray.payloadSizeInBytes) {
  1875. unsigned DiagID = bNeedsPayload ?
  1876. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1877. "shader must include inout payload structure parameter.") :
  1878. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1879. "shader must include inout parameter structure.");
  1880. Diags.Report(FD->getLocation(), DiagID);
  1881. }
  1882. }
  1883. if (bNeedsAttributes &&
  1884. 0 == funcProps->ShaderProps.Ray.attributeSizeInBytes) {
  1885. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1886. DiagnosticsEngine::Error,
  1887. "shader must include attributes structure parameter."));
  1888. }
  1889. }
  1890. // Type annotation for parameters and return type.
  1891. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  1892. unsigned arrayEltSize = 0;
  1893. AddTypeAnnotation(FD->getReturnType(), dxilTypeSys, arrayEltSize);
  1894. // Type annotation for this pointer.
  1895. if (const CXXMethodDecl *MFD = dyn_cast<CXXMethodDecl>(FD)) {
  1896. const CXXRecordDecl *RD = MFD->getParent();
  1897. QualType Ty = CGM.getContext().getTypeDeclType(RD);
  1898. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1899. }
  1900. for (const ValueDecl *param : FD->params()) {
  1901. QualType Ty = param->getType();
  1902. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1903. }
  1904. // clear isExportedEntry if not exporting entry
  1905. bool isExportedEntry = profileAttributes != 0;
  1906. if (isExportedEntry) {
  1907. // use unmangled or mangled name depending on which is used for final entry function
  1908. StringRef name = isRay ? F->getName() : FD->getName();
  1909. if (!m_ExportMap.IsExported(name)) {
  1910. isExportedEntry = false;
  1911. }
  1912. }
  1913. // Only add functionProps when exist.
  1914. if (isExportedEntry || isEntry)
  1915. m_pHLModule->AddDxilFunctionProps(F, funcProps);
  1916. if (isPatchConstantFunction)
  1917. patchConstantFunctionPropsMap[F] = std::move(funcProps);
  1918. // Save F to entry map.
  1919. if (isExportedEntry) {
  1920. if (entryFunctionMap.count(FD->getName())) {
  1921. DiagnosticsEngine &Diags = CGM.getDiags();
  1922. unsigned DiagID = Diags.getCustomDiagID(
  1923. DiagnosticsEngine::Error,
  1924. "redefinition of %0");
  1925. Diags.Report(FD->getLocStart(), DiagID) << FD->getName();
  1926. }
  1927. auto &Entry = entryFunctionMap[FD->getNameAsString()];
  1928. Entry.SL = FD->getLocation();
  1929. Entry.Func= F;
  1930. }
  1931. // Add target-dependent experimental function attributes
  1932. for (const auto &Attr : FD->specific_attrs<HLSLExperimentalAttr>()) {
  1933. F->addFnAttr(Twine("exp-", Attr->getName()).str(), Attr->getValue());
  1934. }
  1935. }
  1936. void CGMSHLSLRuntime::RemapObsoleteSemantic(DxilParameterAnnotation &paramInfo, bool isPatchConstantFunction) {
  1937. DXASSERT(CGM.getLangOpts().EnableDX9CompatMode, "should be used only in back-compat mode");
  1938. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1939. DXIL::SigPointKind sigPointKind = SigPointFromInputQual(paramInfo.GetParamInputQual(), SM->GetKind(), isPatchConstantFunction);
  1940. hlsl::RemapObsoleteSemantic(paramInfo, sigPointKind, CGM.getLLVMContext());
  1941. }
  1942. void CGMSHLSLRuntime::EmitHLSLFunctionProlog(Function *F, const FunctionDecl *FD) {
  1943. // Support clip plane need debug info which not available when create function attribute.
  1944. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1945. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  1946. // Initialize to null.
  1947. memset(funcProps.ShaderProps.VS.clipPlanes, 0, sizeof(funcProps.ShaderProps.VS.clipPlanes));
  1948. // Create global for each clip plane, and use the clip plane val as init val.
  1949. auto AddClipPlane = [&](Expr *clipPlane, unsigned idx) {
  1950. if (DeclRefExpr *decl = dyn_cast<DeclRefExpr>(clipPlane)) {
  1951. const VarDecl *VD = cast<VarDecl>(decl->getDecl());
  1952. Constant *clipPlaneVal = CGM.GetAddrOfGlobalVar(VD);
  1953. funcProps.ShaderProps.VS.clipPlanes[idx] = clipPlaneVal;
  1954. if (m_bDebugInfo) {
  1955. CodeGenFunction CGF(CGM);
  1956. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1957. debugInfoMap[clipPlaneVal] = CGF.Builder.getCurrentDebugLocation();
  1958. }
  1959. } else {
  1960. // Must be a MemberExpr.
  1961. const MemberExpr *ME = cast<MemberExpr>(clipPlane);
  1962. CodeGenFunction CGF(CGM);
  1963. CodeGen::LValue LV = CGF.EmitMemberExpr(ME);
  1964. Value *addr = LV.getAddress();
  1965. funcProps.ShaderProps.VS.clipPlanes[idx] = cast<Constant>(addr);
  1966. if (m_bDebugInfo) {
  1967. CodeGenFunction CGF(CGM);
  1968. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1969. debugInfoMap[addr] = CGF.Builder.getCurrentDebugLocation();
  1970. }
  1971. }
  1972. };
  1973. if (Expr *clipPlane = Attr->getClipPlane1())
  1974. AddClipPlane(clipPlane, 0);
  1975. if (Expr *clipPlane = Attr->getClipPlane2())
  1976. AddClipPlane(clipPlane, 1);
  1977. if (Expr *clipPlane = Attr->getClipPlane3())
  1978. AddClipPlane(clipPlane, 2);
  1979. if (Expr *clipPlane = Attr->getClipPlane4())
  1980. AddClipPlane(clipPlane, 3);
  1981. if (Expr *clipPlane = Attr->getClipPlane5())
  1982. AddClipPlane(clipPlane, 4);
  1983. if (Expr *clipPlane = Attr->getClipPlane6())
  1984. AddClipPlane(clipPlane, 5);
  1985. clipPlaneFuncList.emplace_back(F);
  1986. }
  1987. // Update function linkage based on DefaultLinkage
  1988. // We will take care of patch constant functions later, once identified for certain.
  1989. if (!m_pHLModule->HasDxilFunctionProps(F)) {
  1990. if (F->getLinkage() == GlobalValue::LinkageTypes::ExternalLinkage) {
  1991. if (!FD->hasAttr<HLSLExportAttr>()) {
  1992. switch (CGM.getCodeGenOpts().DefaultLinkage) {
  1993. case DXIL::DefaultLinkage::Default:
  1994. if (m_pHLModule->GetShaderModel()->GetMinor() != ShaderModel::kOfflineMinor)
  1995. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  1996. break;
  1997. case DXIL::DefaultLinkage::Internal:
  1998. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  1999. break;
  2000. }
  2001. }
  2002. }
  2003. }
  2004. }
  2005. void CGMSHLSLRuntime::AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  2006. llvm::TerminatorInst *TI,
  2007. ArrayRef<const Attr *> Attrs) {
  2008. // Build hints.
  2009. bool bNoBranchFlatten = true;
  2010. bool bBranch = false;
  2011. bool bFlatten = false;
  2012. std::vector<DXIL::ControlFlowHint> hints;
  2013. for (const auto *Attr : Attrs) {
  2014. if (isa<HLSLBranchAttr>(Attr)) {
  2015. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  2016. bNoBranchFlatten = false;
  2017. bBranch = true;
  2018. }
  2019. else if (isa<HLSLFlattenAttr>(Attr)) {
  2020. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  2021. bNoBranchFlatten = false;
  2022. bFlatten = true;
  2023. } else if (isa<HLSLForceCaseAttr>(Attr)) {
  2024. if (isa<SwitchStmt>(&S)) {
  2025. hints.emplace_back(DXIL::ControlFlowHint::ForceCase);
  2026. }
  2027. }
  2028. // Ignore fastopt, allow_uav_condition and call for now.
  2029. }
  2030. if (bNoBranchFlatten) {
  2031. // CHECK control flow option.
  2032. if (CGF.CGM.getCodeGenOpts().HLSLPreferControlFlow)
  2033. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  2034. else if (CGF.CGM.getCodeGenOpts().HLSLAvoidControlFlow)
  2035. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  2036. }
  2037. if (bFlatten && bBranch) {
  2038. DiagnosticsEngine &Diags = CGM.getDiags();
  2039. unsigned DiagID = Diags.getCustomDiagID(
  2040. DiagnosticsEngine::Error,
  2041. "can't use branch and flatten attributes together");
  2042. Diags.Report(S.getLocStart(), DiagID);
  2043. }
  2044. if (hints.size()) {
  2045. // Add meta data to the instruction.
  2046. MDNode *hintsNode = DxilMDHelper::EmitControlFlowHints(Context, hints);
  2047. TI->setMetadata(DxilMDHelper::kDxilControlFlowHintMDName, hintsNode);
  2048. }
  2049. }
  2050. void CGMSHLSLRuntime::MarkRetTemp(CodeGenFunction &CGF, Value *V,
  2051. QualType QualTy) {
  2052. // Save resource properties for ret temp.
  2053. DxilResourceProperties RP = BuildResourceProperty(QualTy);
  2054. if (RP.Class != DXIL::ResourceClass::Invalid)
  2055. valToResPropertiesMap[V] = RP;
  2056. }
  2057. void CGMSHLSLRuntime::FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D,
  2058. llvm::Value *V) {
  2059. if (D.hasAttr<HLSLPreciseAttr>()) {
  2060. AllocaInst *AI = cast<AllocaInst>(V);
  2061. HLModule::MarkPreciseAttributeWithMetadata(AI);
  2062. }
  2063. // Add type annotation for local variable.
  2064. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  2065. unsigned arrayEltSize = 0;
  2066. AddTypeAnnotation(D.getType(), typeSys, arrayEltSize);
  2067. // Save resource properties for local variables.
  2068. DxilResourceProperties RP = BuildResourceProperty(D.getType());
  2069. if (RP.Class != DXIL::ResourceClass::Invalid)
  2070. valToResPropertiesMap[V] = RP;
  2071. }
  2072. hlsl::InterpolationMode CGMSHLSLRuntime::GetInterpMode(const Decl *decl,
  2073. CompType compType,
  2074. bool bKeepUndefined) {
  2075. InterpolationMode Interp(
  2076. decl->hasAttr<HLSLNoInterpolationAttr>(), decl->hasAttr<HLSLLinearAttr>(),
  2077. decl->hasAttr<HLSLNoPerspectiveAttr>(), decl->hasAttr<HLSLCentroidAttr>(),
  2078. decl->hasAttr<HLSLSampleAttr>());
  2079. DXASSERT(Interp.IsValid(), "otherwise front-end missing validation");
  2080. if (Interp.IsUndefined() && !bKeepUndefined) {
  2081. // Type-based default: linear for floats, constant for others.
  2082. if (compType.IsFloatTy())
  2083. Interp = InterpolationMode::Kind::Linear;
  2084. else
  2085. Interp = InterpolationMode::Kind::Constant;
  2086. }
  2087. return Interp;
  2088. }
  2089. hlsl::CompType CGMSHLSLRuntime::GetCompType(const BuiltinType *BT) {
  2090. hlsl::CompType ElementType = hlsl::CompType::getInvalid();
  2091. switch (BT->getKind()) {
  2092. case BuiltinType::Bool:
  2093. ElementType = hlsl::CompType::getI1();
  2094. break;
  2095. case BuiltinType::Double:
  2096. ElementType = hlsl::CompType::getF64();
  2097. break;
  2098. case BuiltinType::HalfFloat: // HLSL Change
  2099. case BuiltinType::Float:
  2100. ElementType = hlsl::CompType::getF32();
  2101. break;
  2102. // HLSL Changes begin
  2103. case BuiltinType::Min10Float:
  2104. case BuiltinType::Min16Float:
  2105. // HLSL Changes end
  2106. case BuiltinType::Half:
  2107. ElementType = hlsl::CompType::getF16();
  2108. break;
  2109. case BuiltinType::Int:
  2110. ElementType = hlsl::CompType::getI32();
  2111. break;
  2112. case BuiltinType::LongLong:
  2113. ElementType = hlsl::CompType::getI64();
  2114. break;
  2115. // HLSL Changes begin
  2116. case BuiltinType::Min12Int:
  2117. case BuiltinType::Min16Int:
  2118. // HLSL Changes end
  2119. case BuiltinType::Short:
  2120. ElementType = hlsl::CompType::getI16();
  2121. break;
  2122. case BuiltinType::UInt:
  2123. ElementType = hlsl::CompType::getU32();
  2124. break;
  2125. case BuiltinType::ULongLong:
  2126. ElementType = hlsl::CompType::getU64();
  2127. break;
  2128. case BuiltinType::Min16UInt: // HLSL Change
  2129. case BuiltinType::UShort:
  2130. ElementType = hlsl::CompType::getU16();
  2131. break;
  2132. default:
  2133. llvm_unreachable("unsupported type");
  2134. break;
  2135. }
  2136. return ElementType;
  2137. }
  2138. /// Add resource to the program
  2139. void CGMSHLSLRuntime::addResource(Decl *D) {
  2140. if (HLSLBufferDecl *BD = dyn_cast<HLSLBufferDecl>(D))
  2141. GetOrCreateCBuffer(BD);
  2142. else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2143. hlsl::DxilResourceBase::Class resClass = TypeToClass(VD->getType());
  2144. // Save resource properties for global variables.
  2145. if (resClass != DXIL::ResourceClass::Invalid) {
  2146. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2147. DxilResourceProperties RP = BuildResourceProperty(VD->getType());
  2148. if (RP.Class != DXIL::ResourceClass::Invalid)
  2149. valToResPropertiesMap[GV] = RP;
  2150. }
  2151. // skip decl has init which is resource.
  2152. if (VD->hasInit() && resClass != DXIL::ResourceClass::Invalid)
  2153. return;
  2154. // skip static global.
  2155. if (!VD->hasExternalFormalLinkage()) {
  2156. if (VD->hasInit() && VD->getType().isConstQualified()) {
  2157. Expr* InitExp = VD->getInit();
  2158. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2159. // Only save const static global of struct type.
  2160. if (GV->getType()->getElementType()->isStructTy()) {
  2161. staticConstGlobalInitMap[InitExp] = GV;
  2162. }
  2163. }
  2164. // Add type annotation for static global variable.
  2165. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  2166. unsigned arrayEltSize = 0;
  2167. AddTypeAnnotation(VD->getType(), typeSys, arrayEltSize);
  2168. return;
  2169. }
  2170. if (D->hasAttr<HLSLGroupSharedAttr>()) {
  2171. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  2172. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2173. unsigned arraySize = 0;
  2174. AddTypeAnnotation(VD->getType(), dxilTypeSys, arraySize);
  2175. m_pHLModule->AddGroupSharedVariable(GV);
  2176. return;
  2177. }
  2178. switch (resClass) {
  2179. case hlsl::DxilResourceBase::Class::Sampler:
  2180. AddSampler(VD);
  2181. break;
  2182. case hlsl::DxilResourceBase::Class::UAV:
  2183. case hlsl::DxilResourceBase::Class::SRV:
  2184. AddUAVSRV(VD, resClass);
  2185. break;
  2186. case hlsl::DxilResourceBase::Class::Invalid: {
  2187. // normal global constant, add to global CB
  2188. HLCBuffer &globalCB = GetGlobalCBuffer();
  2189. AddConstant(VD, globalCB);
  2190. break;
  2191. }
  2192. case DXIL::ResourceClass::CBuffer:
  2193. DXASSERT(0, "cbuffer should not be here");
  2194. break;
  2195. }
  2196. }
  2197. }
  2198. /// Add subobject to the module
  2199. void CGMSHLSLRuntime::addSubobject(Decl *D) {
  2200. VarDecl *VD = dyn_cast<VarDecl>(D);
  2201. DXASSERT(VD != nullptr, "must be a global variable");
  2202. DXIL::SubobjectKind subobjKind;
  2203. DXIL::HitGroupType hgType;
  2204. if (!hlsl::GetHLSLSubobjectKind(VD->getType(), subobjKind, hgType)) {
  2205. DXASSERT(false, "not a valid subobject declaration");
  2206. return;
  2207. }
  2208. Expr *initExpr = const_cast<Expr*>(VD->getAnyInitializer());
  2209. if (!initExpr) {
  2210. DiagnosticsEngine &Diags = CGM.getDiags();
  2211. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "subobject needs to be initialized");
  2212. Diags.Report(D->getLocStart(), DiagID);
  2213. return;
  2214. }
  2215. if (InitListExpr *initListExpr = dyn_cast<InitListExpr>(initExpr)) {
  2216. try {
  2217. CreateSubobject(subobjKind, VD->getName(), initListExpr->getInits(), initListExpr->getNumInits(), hgType);
  2218. } catch (hlsl::Exception&) {
  2219. DiagnosticsEngine &Diags = CGM.getDiags();
  2220. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "internal error creating subobject");
  2221. Diags.Report(initExpr->getLocStart(), DiagID);
  2222. return;
  2223. }
  2224. }
  2225. else {
  2226. DiagnosticsEngine &Diags = CGM.getDiags();
  2227. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "expected initialization list");
  2228. Diags.Report(initExpr->getLocStart(), DiagID);
  2229. return;
  2230. }
  2231. }
  2232. // TODO: collect such helper utility functions in one place.
  2233. static DxilResourceBase::Class KeywordToClass(const std::string &keyword) {
  2234. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  2235. // compare)
  2236. if (keyword == "SamplerState")
  2237. return DxilResourceBase::Class::Sampler;
  2238. if (keyword == "SamplerComparisonState")
  2239. return DxilResourceBase::Class::Sampler;
  2240. if (keyword == "ConstantBuffer")
  2241. return DxilResourceBase::Class::CBuffer;
  2242. if (keyword == "TextureBuffer")
  2243. return DxilResourceBase::Class::SRV;
  2244. bool isSRV = keyword == "Buffer";
  2245. isSRV |= keyword == "ByteAddressBuffer";
  2246. isSRV |= keyword == "RaytracingAccelerationStructure";
  2247. isSRV |= keyword == "StructuredBuffer";
  2248. isSRV |= keyword == "Texture1D";
  2249. isSRV |= keyword == "Texture1DArray";
  2250. isSRV |= keyword == "Texture2D";
  2251. isSRV |= keyword == "Texture2DArray";
  2252. isSRV |= keyword == "Texture3D";
  2253. isSRV |= keyword == "TextureCube";
  2254. isSRV |= keyword == "TextureCubeArray";
  2255. isSRV |= keyword == "Texture2DMS";
  2256. isSRV |= keyword == "Texture2DMSArray";
  2257. if (isSRV)
  2258. return DxilResourceBase::Class::SRV;
  2259. bool isUAV = keyword == "RWBuffer";
  2260. isUAV |= keyword == "RWByteAddressBuffer";
  2261. isUAV |= keyword == "RWStructuredBuffer";
  2262. isUAV |= keyword == "RWTexture1D";
  2263. isUAV |= keyword == "RWTexture1DArray";
  2264. isUAV |= keyword == "RWTexture2D";
  2265. isUAV |= keyword == "RWTexture2DArray";
  2266. isUAV |= keyword == "RWTexture3D";
  2267. isUAV |= keyword == "RWTextureCube";
  2268. isUAV |= keyword == "RWTextureCubeArray";
  2269. isUAV |= keyword == "RWTexture2DMS";
  2270. isUAV |= keyword == "RWTexture2DMSArray";
  2271. isUAV |= keyword == "AppendStructuredBuffer";
  2272. isUAV |= keyword == "ConsumeStructuredBuffer";
  2273. isUAV |= keyword == "RasterizerOrderedBuffer";
  2274. isUAV |= keyword == "RasterizerOrderedByteAddressBuffer";
  2275. isUAV |= keyword == "RasterizerOrderedStructuredBuffer";
  2276. isUAV |= keyword == "RasterizerOrderedTexture1D";
  2277. isUAV |= keyword == "RasterizerOrderedTexture1DArray";
  2278. isUAV |= keyword == "RasterizerOrderedTexture2D";
  2279. isUAV |= keyword == "RasterizerOrderedTexture2DArray";
  2280. isUAV |= keyword == "RasterizerOrderedTexture3D";
  2281. isUAV |= keyword == "FeedbackTexture2D";
  2282. isUAV |= keyword == "FeedbackTexture2DArray";
  2283. if (isUAV)
  2284. return DxilResourceBase::Class::UAV;
  2285. return DxilResourceBase::Class::Invalid;
  2286. }
  2287. // This should probably be refactored to ASTContextHLSL, and follow types
  2288. // rather than do string comparisons.
  2289. DXIL::ResourceClass
  2290. hlsl::GetResourceClassForType(const clang::ASTContext &context,
  2291. clang::QualType Ty) {
  2292. Ty = Ty.getCanonicalType();
  2293. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2294. return GetResourceClassForType(context, arrayType->getElementType());
  2295. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2296. return KeywordToClass(RT->getDecl()->getName());
  2297. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2298. if (const ClassTemplateSpecializationDecl *templateDecl =
  2299. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2300. return KeywordToClass(templateDecl->getName());
  2301. }
  2302. }
  2303. return hlsl::DxilResourceBase::Class::Invalid;
  2304. }
  2305. hlsl::DxilResourceBase::Class CGMSHLSLRuntime::TypeToClass(clang::QualType Ty) {
  2306. return hlsl::GetResourceClassForType(CGM.getContext(), Ty);
  2307. }
  2308. namespace {
  2309. void GetResourceDeclElemTypeAndRangeSize(CodeGenModule &CGM, HLModule &HL, VarDecl &VD,
  2310. QualType &ElemType, unsigned& rangeSize) {
  2311. // We can't canonicalize nor desugar the type without losing the 'snorm' in Buffer<snorm float>
  2312. ElemType = VD.getType();
  2313. rangeSize = 1;
  2314. while (const clang::ArrayType *arrayType = CGM.getContext().getAsArrayType(ElemType)) {
  2315. if (rangeSize != UINT_MAX) {
  2316. if (arrayType->isConstantArrayType()) {
  2317. rangeSize *= cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2318. }
  2319. else {
  2320. if (HL.GetHLOptions().bLegacyResourceReservation) {
  2321. DiagnosticsEngine &Diags = CGM.getDiags();
  2322. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2323. "unbounded resources are not supported with -flegacy-resource-reservation");
  2324. Diags.Report(VD.getLocation(), DiagID);
  2325. }
  2326. rangeSize = UINT_MAX;
  2327. }
  2328. }
  2329. ElemType = arrayType->getElementType();
  2330. }
  2331. }
  2332. }
  2333. static void InitFromUnusualAnnotations(DxilResourceBase &Resource, NamedDecl &Decl) {
  2334. for (hlsl::UnusualAnnotation* It : Decl.getUnusualAnnotations()) {
  2335. switch (It->getKind()) {
  2336. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2337. hlsl::RegisterAssignment* RegAssign = cast<hlsl::RegisterAssignment>(It);
  2338. if (RegAssign->RegisterType) {
  2339. Resource.SetLowerBound(RegAssign->RegisterNumber);
  2340. // For backcompat, don't auto-assign the register space if there's an
  2341. // explicit register type.
  2342. Resource.SetSpaceID(RegAssign->RegisterSpace.getValueOr(0));
  2343. }
  2344. else {
  2345. Resource.SetSpaceID(RegAssign->RegisterSpace.getValueOr(UINT_MAX));
  2346. }
  2347. break;
  2348. }
  2349. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2350. // Ignore Semantics
  2351. break;
  2352. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2353. // Should be handled by front-end
  2354. llvm_unreachable("packoffset on resource");
  2355. break;
  2356. default:
  2357. llvm_unreachable("unknown UnusualAnnotation on resource");
  2358. break;
  2359. }
  2360. }
  2361. }
  2362. uint32_t CGMSHLSLRuntime::AddSampler(VarDecl *samplerDecl) {
  2363. llvm::GlobalVariable *val =
  2364. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(samplerDecl));
  2365. unique_ptr<DxilSampler> hlslRes(new DxilSampler);
  2366. hlslRes->SetLowerBound(UINT_MAX);
  2367. hlslRes->SetSpaceID(UINT_MAX);
  2368. hlslRes->SetGlobalSymbol(val);
  2369. hlslRes->SetGlobalName(samplerDecl->getName());
  2370. QualType VarTy;
  2371. unsigned rangeSize;
  2372. GetResourceDeclElemTypeAndRangeSize(CGM, *m_pHLModule, *samplerDecl,
  2373. VarTy, rangeSize);
  2374. hlslRes->SetRangeSize(rangeSize);
  2375. const RecordType *RT = VarTy->getAs<RecordType>();
  2376. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RT->getDecl()->getName());
  2377. hlslRes->SetSamplerKind(kind);
  2378. InitFromUnusualAnnotations(*hlslRes, *samplerDecl);
  2379. hlslRes->SetID(m_pHLModule->GetSamplers().size());
  2380. return m_pHLModule->AddSampler(std::move(hlslRes));
  2381. }
  2382. bool CGMSHLSLRuntime::GetAsConstantUInt32(clang::Expr *expr, uint32_t *value) {
  2383. APSInt result;
  2384. if (!expr->EvaluateAsInt(result, CGM.getContext())) {
  2385. DiagnosticsEngine &Diags = CGM.getDiags();
  2386. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2387. "cannot convert to constant unsigned int");
  2388. Diags.Report(expr->getLocStart(), DiagID);
  2389. return false;
  2390. }
  2391. *value = result.getLimitedValue(UINT32_MAX);
  2392. return true;
  2393. }
  2394. bool CGMSHLSLRuntime::GetAsConstantString(clang::Expr *expr, StringRef *value, bool failWhenEmpty /*=false*/) {
  2395. Expr::EvalResult result;
  2396. DiagnosticsEngine &Diags = CGM.getDiags();
  2397. unsigned DiagID = 0;
  2398. if (expr->EvaluateAsRValue(result, CGM.getContext())) {
  2399. if (result.Val.isLValue()) {
  2400. DXASSERT_NOMSG(result.Val.getLValueOffset().isZero());
  2401. DXASSERT_NOMSG(result.Val.getLValueCallIndex() == 0);
  2402. const Expr *evExpr = result.Val.getLValueBase().get<const Expr *>();
  2403. if (const StringLiteral *strLit = dyn_cast<const StringLiteral>(evExpr)) {
  2404. *value = strLit->getBytes();
  2405. if (!failWhenEmpty || !(*value).empty()) {
  2406. return true;
  2407. }
  2408. DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "empty string not expected here");
  2409. }
  2410. }
  2411. }
  2412. if (!DiagID)
  2413. DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot convert to constant string");
  2414. Diags.Report(expr->getLocStart(), DiagID);
  2415. return false;
  2416. }
  2417. std::vector<StringRef> CGMSHLSLRuntime::ParseSubobjectExportsAssociations(StringRef exports) {
  2418. std::vector<StringRef> parsedExports;
  2419. const char *pData = exports.data();
  2420. const char *pEnd = pData + exports.size();
  2421. const char *pLast = pData;
  2422. while (pData < pEnd) {
  2423. if (*pData == ';') {
  2424. if (pLast < pData) {
  2425. parsedExports.emplace_back(StringRef(pLast, pData - pLast));
  2426. }
  2427. pLast = pData + 1;
  2428. }
  2429. pData++;
  2430. }
  2431. if (pLast < pData) {
  2432. parsedExports.emplace_back(StringRef(pLast, pData - pLast));
  2433. }
  2434. return std::move(parsedExports);
  2435. }
  2436. void CGMSHLSLRuntime::CreateSubobject(DXIL::SubobjectKind kind, const StringRef name,
  2437. clang::Expr **args, unsigned int argCount,
  2438. DXIL::HitGroupType hgType /*= (DXIL::HitGroupType)(-1)*/) {
  2439. DxilSubobjects *subobjects = m_pHLModule->GetSubobjects();
  2440. if (!subobjects) {
  2441. subobjects = new DxilSubobjects();
  2442. m_pHLModule->ResetSubobjects(subobjects);
  2443. }
  2444. DxilRootSignatureCompilationFlags flags = DxilRootSignatureCompilationFlags::GlobalRootSignature;
  2445. switch (kind) {
  2446. case DXIL::SubobjectKind::StateObjectConfig: {
  2447. uint32_t flags;
  2448. DXASSERT_NOMSG(argCount == 1);
  2449. if (GetAsConstantUInt32(args[0], &flags)) {
  2450. subobjects->CreateStateObjectConfig(name, flags);
  2451. }
  2452. break;
  2453. }
  2454. case DXIL::SubobjectKind::LocalRootSignature:
  2455. flags = DxilRootSignatureCompilationFlags::LocalRootSignature;
  2456. __fallthrough;
  2457. case DXIL::SubobjectKind::GlobalRootSignature: {
  2458. DXASSERT_NOMSG(argCount == 1);
  2459. StringRef signature;
  2460. if (!GetAsConstantString(args[0], &signature, true))
  2461. return;
  2462. RootSignatureHandle RootSigHandle;
  2463. CompileRootSignature(signature, CGM.getDiags(), args[0]->getLocStart(), rootSigVer, flags, &RootSigHandle);
  2464. if (!RootSigHandle.IsEmpty()) {
  2465. RootSigHandle.EnsureSerializedAvailable();
  2466. subobjects->CreateRootSignature(name, kind == DXIL::SubobjectKind::LocalRootSignature,
  2467. RootSigHandle.GetSerializedBytes(), RootSigHandle.GetSerializedSize(), &signature);
  2468. }
  2469. break;
  2470. }
  2471. case DXIL::SubobjectKind::SubobjectToExportsAssociation: {
  2472. DXASSERT_NOMSG(argCount == 2);
  2473. StringRef subObjName, exports;
  2474. if (!GetAsConstantString(args[0], &subObjName, true) ||
  2475. !GetAsConstantString(args[1], &exports, false))
  2476. return;
  2477. std::vector<StringRef> exportList = ParseSubobjectExportsAssociations(exports);
  2478. subobjects->CreateSubobjectToExportsAssociation(name, subObjName, exportList.data(), exportList.size());
  2479. break;
  2480. }
  2481. case DXIL::SubobjectKind::RaytracingShaderConfig: {
  2482. DXASSERT_NOMSG(argCount == 2);
  2483. uint32_t maxPayloadSize;
  2484. uint32_t MaxAttributeSize;
  2485. if (!GetAsConstantUInt32(args[0], &maxPayloadSize) ||
  2486. !GetAsConstantUInt32(args[1], &MaxAttributeSize))
  2487. return;
  2488. subobjects->CreateRaytracingShaderConfig(name, maxPayloadSize, MaxAttributeSize);
  2489. break;
  2490. }
  2491. case DXIL::SubobjectKind::RaytracingPipelineConfig: {
  2492. DXASSERT_NOMSG(argCount == 1);
  2493. uint32_t maxTraceRecursionDepth;
  2494. if (!GetAsConstantUInt32(args[0], &maxTraceRecursionDepth))
  2495. return;
  2496. subobjects->CreateRaytracingPipelineConfig(name, maxTraceRecursionDepth);
  2497. break;
  2498. }
  2499. case DXIL::SubobjectKind::HitGroup: {
  2500. switch (hgType) {
  2501. case DXIL::HitGroupType::Triangle: {
  2502. DXASSERT_NOMSG(argCount == 2);
  2503. StringRef anyhit, closesthit;
  2504. if (!GetAsConstantString(args[0], &anyhit) ||
  2505. !GetAsConstantString(args[1], &closesthit))
  2506. return;
  2507. subobjects->CreateHitGroup(name, DXIL::HitGroupType::Triangle, anyhit, closesthit, llvm::StringRef(""));
  2508. break;
  2509. }
  2510. case DXIL::HitGroupType::ProceduralPrimitive: {
  2511. DXASSERT_NOMSG(argCount == 3);
  2512. StringRef anyhit, closesthit, intersection;
  2513. if (!GetAsConstantString(args[0], &anyhit) ||
  2514. !GetAsConstantString(args[1], &closesthit) ||
  2515. !GetAsConstantString(args[2], &intersection, true))
  2516. return;
  2517. subobjects->CreateHitGroup(name, DXIL::HitGroupType::ProceduralPrimitive, anyhit, closesthit, intersection);
  2518. break;
  2519. }
  2520. default:
  2521. llvm_unreachable("unknown HitGroupType");
  2522. }
  2523. break;
  2524. }
  2525. case DXIL::SubobjectKind::RaytracingPipelineConfig1: {
  2526. DXASSERT_NOMSG(argCount == 2);
  2527. uint32_t maxTraceRecursionDepth;
  2528. uint32_t raytracingPipelineFlags;
  2529. if (!GetAsConstantUInt32(args[0], &maxTraceRecursionDepth))
  2530. return;
  2531. if (!GetAsConstantUInt32(args[1], &raytracingPipelineFlags))
  2532. return;
  2533. subobjects->CreateRaytracingPipelineConfig1(name, maxTraceRecursionDepth, raytracingPipelineFlags);
  2534. break;
  2535. }
  2536. default:
  2537. llvm_unreachable("unknown SubobjectKind");
  2538. break;
  2539. }
  2540. }
  2541. static void CollectScalarTypes(std::vector<QualType> &ScalarTys, QualType Ty) {
  2542. if (Ty->isRecordType()) {
  2543. if (hlsl::IsHLSLMatType(Ty)) {
  2544. QualType EltTy = hlsl::GetHLSLMatElementType(Ty);
  2545. unsigned row = 0;
  2546. unsigned col = 0;
  2547. hlsl::GetRowsAndCols(Ty, row, col);
  2548. unsigned size = col*row;
  2549. for (unsigned i = 0; i < size; i++) {
  2550. CollectScalarTypes(ScalarTys, EltTy);
  2551. }
  2552. } else if (hlsl::IsHLSLVecType(Ty)) {
  2553. QualType EltTy = hlsl::GetHLSLVecElementType(Ty);
  2554. unsigned row = 0;
  2555. unsigned col = 0;
  2556. hlsl::GetRowsAndColsForAny(Ty, row, col);
  2557. unsigned size = col;
  2558. for (unsigned i = 0; i < size; i++) {
  2559. CollectScalarTypes(ScalarTys, EltTy);
  2560. }
  2561. } else {
  2562. const RecordType *RT = Ty->getAsStructureType();
  2563. // For CXXRecord.
  2564. if (!RT)
  2565. RT = Ty->getAs<RecordType>();
  2566. RecordDecl *RD = RT->getDecl();
  2567. for (FieldDecl *field : RD->fields())
  2568. CollectScalarTypes(ScalarTys, field->getType());
  2569. }
  2570. } else if (Ty->isArrayType()) {
  2571. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  2572. QualType EltTy = AT->getElementType();
  2573. // Set it to 5 for unsized array.
  2574. unsigned size = 5;
  2575. if (AT->isConstantArrayType()) {
  2576. size = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  2577. }
  2578. for (unsigned i=0;i<size;i++) {
  2579. CollectScalarTypes(ScalarTys, EltTy);
  2580. }
  2581. } else {
  2582. ScalarTys.emplace_back(Ty);
  2583. }
  2584. }
  2585. bool CGMSHLSLRuntime::SetUAVSRV(SourceLocation loc,
  2586. hlsl::DxilResourceBase::Class resClass,
  2587. DxilResource *hlslRes, QualType QualTy) {
  2588. RecordDecl *RD = QualTy->getAs<RecordType>()->getDecl();
  2589. hlsl::DxilResource::Kind kind = KeywordToKind(RD->getName());
  2590. DXASSERT_NOMSG(kind != hlsl::DxilResource::Kind::Invalid);
  2591. hlslRes->SetKind(kind);
  2592. // Type annotation for result type of resource.
  2593. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2594. unsigned arrayEltSize = 0;
  2595. AddTypeAnnotation(QualType(RD->getTypeForDecl(),0), dxilTypeSys, arrayEltSize);
  2596. if (kind == hlsl::DxilResource::Kind::Texture2DMS ||
  2597. kind == hlsl::DxilResource::Kind::Texture2DMSArray) {
  2598. const ClassTemplateSpecializationDecl *templateDecl =
  2599. cast<ClassTemplateSpecializationDecl>(RD);
  2600. const clang::TemplateArgument &sampleCountArg =
  2601. templateDecl->getTemplateArgs()[1];
  2602. uint32_t sampleCount = sampleCountArg.getAsIntegral().getLimitedValue();
  2603. hlslRes->SetSampleCount(sampleCount);
  2604. }
  2605. if (hlsl::DxilResource::IsAnyTexture(kind)) {
  2606. const ClassTemplateSpecializationDecl *templateDecl = cast<ClassTemplateSpecializationDecl>(RD);
  2607. const clang::TemplateArgument &texelTyArg = templateDecl->getTemplateArgs()[0];
  2608. llvm::Type *texelTy = CGM.getTypes().ConvertType(texelTyArg.getAsType());
  2609. if (!texelTy->isFloatingPointTy() && !texelTy->isIntegerTy()
  2610. && !hlsl::IsHLSLVecType(texelTyArg.getAsType())) {
  2611. DiagnosticsEngine &Diags = CGM.getDiags();
  2612. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2613. "texture resource texel type must be scalar or vector");
  2614. Diags.Report(loc, DiagID);
  2615. return false;
  2616. }
  2617. }
  2618. QualType resultTy = hlsl::GetHLSLResourceResultType(QualTy);
  2619. if (kind != hlsl::DxilResource::Kind::StructuredBuffer && !resultTy.isNull()) {
  2620. QualType Ty = resultTy;
  2621. QualType EltTy = Ty;
  2622. if (hlsl::IsHLSLVecType(Ty)) {
  2623. EltTy = hlsl::GetHLSLVecElementType(Ty);
  2624. } else if (hlsl::IsHLSLMatType(Ty)) {
  2625. EltTy = hlsl::GetHLSLMatElementType(Ty);
  2626. } else if (hlsl::IsHLSLAggregateType(resultTy)) {
  2627. // Struct or array in a none-struct resource.
  2628. std::vector<QualType> ScalarTys;
  2629. CollectScalarTypes(ScalarTys, resultTy);
  2630. unsigned size = ScalarTys.size();
  2631. if (size == 0) {
  2632. DiagnosticsEngine &Diags = CGM.getDiags();
  2633. unsigned DiagID = Diags.getCustomDiagID(
  2634. DiagnosticsEngine::Error,
  2635. "object's templated type must have at least one element");
  2636. Diags.Report(loc, DiagID);
  2637. return false;
  2638. }
  2639. if (size > 4) {
  2640. DiagnosticsEngine &Diags = CGM.getDiags();
  2641. unsigned DiagID = Diags.getCustomDiagID(
  2642. DiagnosticsEngine::Error, "elements of typed buffers and textures "
  2643. "must fit in four 32-bit quantities");
  2644. Diags.Report(loc, DiagID);
  2645. return false;
  2646. }
  2647. EltTy = ScalarTys[0];
  2648. for (QualType ScalarTy : ScalarTys) {
  2649. if (ScalarTy != EltTy) {
  2650. DiagnosticsEngine &Diags = CGM.getDiags();
  2651. unsigned DiagID = Diags.getCustomDiagID(
  2652. DiagnosticsEngine::Error,
  2653. "all template type components must have the same type");
  2654. Diags.Report(loc, DiagID);
  2655. return false;
  2656. }
  2657. }
  2658. }
  2659. bool bSNorm = false;
  2660. bool bHasNormAttribute = hlsl::HasHLSLUNormSNorm(Ty, &bSNorm);
  2661. if (const BuiltinType *BTy = EltTy->getAs<BuiltinType>()) {
  2662. CompType::Kind kind = BuiltinTyToCompTy(BTy, bHasNormAttribute && bSNorm, bHasNormAttribute && !bSNorm);
  2663. // 64bits types are implemented with u32.
  2664. if (kind == CompType::Kind::U64 || kind == CompType::Kind::I64 ||
  2665. kind == CompType::Kind::SNormF64 ||
  2666. kind == CompType::Kind::UNormF64 || kind == CompType::Kind::F64) {
  2667. kind = CompType::Kind::U32;
  2668. }
  2669. hlslRes->SetCompType(kind);
  2670. } else {
  2671. DXASSERT(!bHasNormAttribute, "snorm/unorm on invalid type");
  2672. }
  2673. }
  2674. if (hlslRes->IsFeedbackTexture()) {
  2675. hlslRes->SetSamplerFeedbackType(
  2676. static_cast<DXIL::SamplerFeedbackType>(hlsl::GetHLSLResourceTemplateUInt(QualTy)));
  2677. }
  2678. hlslRes->SetROV(RD->getName().startswith("RasterizerOrdered"));
  2679. if (kind == hlsl::DxilResource::Kind::TypedBuffer ||
  2680. kind == hlsl::DxilResource::Kind::StructuredBuffer) {
  2681. const ClassTemplateSpecializationDecl *templateDecl =
  2682. cast<ClassTemplateSpecializationDecl>(RD);
  2683. const clang::TemplateArgument &retTyArg =
  2684. templateDecl->getTemplateArgs()[0];
  2685. llvm::Type *retTy = CGM.getTypes().ConvertType(retTyArg.getAsType());
  2686. uint32_t strideInBytes = dataLayout.getTypeAllocSize(retTy);
  2687. hlslRes->SetElementStride(strideInBytes);
  2688. }
  2689. if (HasHLSLGloballyCoherent(QualTy)) {
  2690. hlslRes->SetGloballyCoherent(true);
  2691. }
  2692. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2693. if (hlslRes->IsGloballyCoherent()) {
  2694. DiagnosticsEngine &Diags = CGM.getDiags();
  2695. unsigned DiagID = Diags.getCustomDiagID(
  2696. DiagnosticsEngine::Error, "globallycoherent can only be used with "
  2697. "Unordered Access View buffers.");
  2698. Diags.Report(loc, DiagID);
  2699. return false;
  2700. }
  2701. hlslRes->SetRW(false);
  2702. hlslRes->SetID(m_pHLModule->GetSRVs().size());
  2703. } else {
  2704. hlslRes->SetRW(true);
  2705. hlslRes->SetID(m_pHLModule->GetUAVs().size());
  2706. }
  2707. return true;
  2708. }
  2709. uint32_t CGMSHLSLRuntime::AddUAVSRV(VarDecl *decl,
  2710. hlsl::DxilResourceBase::Class resClass) {
  2711. llvm::GlobalVariable *val =
  2712. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(decl));
  2713. unique_ptr<HLResource> hlslRes(new HLResource);
  2714. hlslRes->SetLowerBound(UINT_MAX);
  2715. hlslRes->SetSpaceID(UINT_MAX);
  2716. hlslRes->SetGlobalSymbol(val);
  2717. hlslRes->SetGlobalName(decl->getName());
  2718. QualType VarTy;
  2719. unsigned rangeSize;
  2720. GetResourceDeclElemTypeAndRangeSize(CGM, *m_pHLModule, *decl,
  2721. VarTy, rangeSize);
  2722. hlslRes->SetRangeSize(rangeSize);
  2723. InitFromUnusualAnnotations(*hlslRes, *decl);
  2724. if (decl->hasAttr<HLSLGloballyCoherentAttr>()) {
  2725. hlslRes->SetGloballyCoherent(true);
  2726. }
  2727. if (!SetUAVSRV(decl->getLocation(), resClass, hlslRes.get(), VarTy))
  2728. return 0;
  2729. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2730. return m_pHLModule->AddSRV(std::move(hlslRes));
  2731. } else {
  2732. return m_pHLModule->AddUAV(std::move(hlslRes));
  2733. }
  2734. }
  2735. static bool IsResourceInType(const clang::ASTContext &context,
  2736. clang::QualType Ty) {
  2737. Ty = Ty.getCanonicalType();
  2738. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2739. return IsResourceInType(context, arrayType->getElementType());
  2740. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2741. if (KeywordToClass(RT->getDecl()->getName()) != DxilResourceBase::Class::Invalid)
  2742. return true;
  2743. const CXXRecordDecl* typeRecordDecl = RT->getAsCXXRecordDecl();
  2744. if (typeRecordDecl && !typeRecordDecl->isImplicit()) {
  2745. for (auto field : typeRecordDecl->fields()) {
  2746. if (IsResourceInType(context, field->getType()))
  2747. return true;
  2748. }
  2749. }
  2750. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2751. if (const ClassTemplateSpecializationDecl *templateDecl =
  2752. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2753. if (KeywordToClass(templateDecl->getName()) != DxilResourceBase::Class::Invalid)
  2754. return true;
  2755. }
  2756. }
  2757. return false; // no resources found
  2758. }
  2759. void CGMSHLSLRuntime::AddConstant(VarDecl *constDecl, HLCBuffer &CB) {
  2760. if (constDecl->getStorageClass() == SC_Static) {
  2761. // For static inside cbuffer, take as global static.
  2762. // Don't add to cbuffer.
  2763. CGM.EmitGlobal(constDecl);
  2764. // Add type annotation for static global types.
  2765. // May need it when cast from cbuf.
  2766. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2767. unsigned arraySize = 0;
  2768. AddTypeAnnotation(constDecl->getType(), dxilTypeSys, arraySize);
  2769. return;
  2770. }
  2771. // Search defined structure for resource objects and fail
  2772. if (CB.GetRangeSize() > 1 &&
  2773. IsResourceInType(CGM.getContext(), constDecl->getType())) {
  2774. DiagnosticsEngine &Diags = CGM.getDiags();
  2775. unsigned DiagID = Diags.getCustomDiagID(
  2776. DiagnosticsEngine::Error,
  2777. "object types not supported in cbuffer/tbuffer view arrays.");
  2778. Diags.Report(constDecl->getLocation(), DiagID);
  2779. return;
  2780. }
  2781. llvm::Constant *constVal = CGM.GetAddrOfGlobalVar(constDecl);
  2782. auto &regBindings = constantRegBindingMap[constVal];
  2783. // Save resource properties for cbuffer variables.
  2784. DxilResourceProperties RP = BuildResourceProperty(constDecl->getType());
  2785. if (RP.Class != DXIL::ResourceClass::Invalid)
  2786. valToResPropertiesMap[constVal] = RP;
  2787. bool isGlobalCB = CB.GetID() == globalCBIndex;
  2788. uint32_t offset = 0;
  2789. bool userOffset = false;
  2790. for (hlsl::UnusualAnnotation *it : constDecl->getUnusualAnnotations()) {
  2791. switch (it->getKind()) {
  2792. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  2793. if (!isGlobalCB) {
  2794. // TODO: check cannot mix packoffset elements with nonpackoffset
  2795. // elements in a cbuffer.
  2796. hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  2797. offset = cp->Subcomponent << 2;
  2798. offset += cp->ComponentOffset;
  2799. // Change to byte.
  2800. offset <<= 2;
  2801. userOffset = true;
  2802. } else {
  2803. DiagnosticsEngine &Diags = CGM.getDiags();
  2804. unsigned DiagID = Diags.getCustomDiagID(
  2805. DiagnosticsEngine::Error,
  2806. "packoffset is only allowed in a constant buffer.");
  2807. Diags.Report(it->Loc, DiagID);
  2808. }
  2809. break;
  2810. }
  2811. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2812. RegisterAssignment *ra = cast<RegisterAssignment>(it);
  2813. if (isGlobalCB) {
  2814. if (ra->RegisterSpace.hasValue()) {
  2815. DiagnosticsEngine& Diags = CGM.getDiags();
  2816. unsigned DiagID = Diags.getCustomDiagID(
  2817. DiagnosticsEngine::Error,
  2818. "register space cannot be specified on global constants.");
  2819. Diags.Report(it->Loc, DiagID);
  2820. }
  2821. offset = ra->RegisterNumber << 2;
  2822. // Change to byte.
  2823. offset <<= 2;
  2824. userOffset = true;
  2825. }
  2826. switch (ra->RegisterType) {
  2827. default:
  2828. break;
  2829. case 't':
  2830. regBindings.emplace_back(
  2831. std::make_pair(DXIL::ResourceClass::SRV, ra->RegisterNumber));
  2832. break;
  2833. case 'u':
  2834. regBindings.emplace_back(
  2835. std::make_pair(DXIL::ResourceClass::UAV, ra->RegisterNumber));
  2836. break;
  2837. case 's':
  2838. regBindings.emplace_back(
  2839. std::make_pair(DXIL::ResourceClass::Sampler, ra->RegisterNumber));
  2840. break;
  2841. }
  2842. break;
  2843. }
  2844. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2845. // skip semantic on constant
  2846. break;
  2847. }
  2848. }
  2849. std::unique_ptr<DxilResourceBase> pHlslConst = llvm::make_unique<DxilResourceBase>(DXIL::ResourceClass::Invalid);
  2850. pHlslConst->SetLowerBound(UINT_MAX);
  2851. pHlslConst->SetSpaceID(0);
  2852. pHlslConst->SetGlobalSymbol(cast<llvm::GlobalVariable>(constVal));
  2853. pHlslConst->SetGlobalName(constDecl->getName());
  2854. if (userOffset) {
  2855. pHlslConst->SetLowerBound(offset);
  2856. }
  2857. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2858. // Just add type annotation here.
  2859. // Offset will be allocated later.
  2860. QualType Ty = constDecl->getType();
  2861. if (CB.GetRangeSize() != 1) {
  2862. while (Ty->isArrayType()) {
  2863. Ty = Ty->getAsArrayTypeUnsafe()->getElementType();
  2864. }
  2865. }
  2866. unsigned arrayEltSize = 0;
  2867. unsigned size = AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2868. pHlslConst->SetRangeSize(size);
  2869. CB.AddConst(pHlslConst);
  2870. // Save fieldAnnotation for the const var.
  2871. DxilFieldAnnotation fieldAnnotation;
  2872. if (userOffset)
  2873. fieldAnnotation.SetCBufferOffset(offset);
  2874. // Get the nested element type.
  2875. if (Ty->isArrayType()) {
  2876. while (const ConstantArrayType *arrayTy =
  2877. CGM.getContext().getAsConstantArrayType(Ty)) {
  2878. Ty = arrayTy->getElementType();
  2879. }
  2880. }
  2881. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  2882. ConstructFieldAttributedAnnotation(fieldAnnotation, Ty, bDefaultRowMajor);
  2883. m_ConstVarAnnotationMap[constVal] = fieldAnnotation;
  2884. }
  2885. uint32_t CGMSHLSLRuntime::AddCBuffer(HLSLBufferDecl *D) {
  2886. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  2887. // setup the CB
  2888. CB->SetGlobalSymbol(nullptr);
  2889. CB->SetGlobalName(D->getNameAsString());
  2890. CB->SetSpaceID(UINT_MAX);
  2891. CB->SetLowerBound(UINT_MAX);
  2892. if (!D->isCBuffer()) {
  2893. CB->SetKind(DXIL::ResourceKind::TBuffer);
  2894. }
  2895. // the global variable will only used once by the createHandle?
  2896. // SetHandle(llvm::Value *pHandle);
  2897. InitFromUnusualAnnotations(*CB, *D);
  2898. // Add constant
  2899. if (D->isConstantBufferView()) {
  2900. VarDecl *constDecl = cast<VarDecl>(*D->decls_begin());
  2901. CB->SetRangeSize(1);
  2902. QualType Ty = constDecl->getType();
  2903. if (Ty->isArrayType()) {
  2904. if (!Ty->isIncompleteArrayType()) {
  2905. unsigned arraySize = 1;
  2906. while (Ty->isArrayType()) {
  2907. Ty = Ty->getCanonicalTypeUnqualified();
  2908. const ConstantArrayType *AT = cast<ConstantArrayType>(Ty);
  2909. arraySize *= AT->getSize().getLimitedValue();
  2910. Ty = AT->getElementType();
  2911. }
  2912. CB->SetRangeSize(arraySize);
  2913. } else {
  2914. CB->SetRangeSize(UINT_MAX);
  2915. }
  2916. }
  2917. AddConstant(constDecl, *CB.get());
  2918. } else {
  2919. auto declsEnds = D->decls_end();
  2920. CB->SetRangeSize(1);
  2921. for (auto it = D->decls_begin(); it != declsEnds; it++) {
  2922. if (VarDecl *constDecl = dyn_cast<VarDecl>(*it)) {
  2923. AddConstant(constDecl, *CB.get());
  2924. } else if (isa<EmptyDecl>(*it)) {
  2925. // Nothing to do for this declaration.
  2926. } else if (isa<CXXRecordDecl>(*it)) {
  2927. // Nothing to do for this declaration.
  2928. } else if (isa<FunctionDecl>(*it)) {
  2929. // A function within an cbuffer is effectively a top-level function,
  2930. // as it only refers to globally scoped declarations.
  2931. this->CGM.EmitTopLevelDecl(*it);
  2932. } else {
  2933. HLSLBufferDecl *inner = cast<HLSLBufferDecl>(*it);
  2934. GetOrCreateCBuffer(inner);
  2935. }
  2936. }
  2937. }
  2938. CB->SetID(m_pHLModule->GetCBuffers().size());
  2939. return m_pHLModule->AddCBuffer(std::move(CB));
  2940. }
  2941. HLCBuffer &CGMSHLSLRuntime::GetOrCreateCBuffer(HLSLBufferDecl *D) {
  2942. if (constantBufMap.count(D) != 0) {
  2943. uint32_t cbIndex = constantBufMap[D];
  2944. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbIndex)));
  2945. }
  2946. uint32_t cbID = AddCBuffer(D);
  2947. constantBufMap[D] = cbID;
  2948. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbID)));
  2949. }
  2950. void CGMSHLSLRuntime::FinishCodeGen() {
  2951. HLModule &HLM = *m_pHLModule;
  2952. llvm::Module &M = TheModule;
  2953. // Do this before CloneShaderEntry and TranslateRayQueryConstructor to avoid
  2954. // update valToResPropertiesMap for cloned inst.
  2955. FinishIntrinsics(HLM, m_IntrinsicMap, valToResPropertiesMap);
  2956. FinishEntries(HLM, Entry, CGM, entryFunctionMap, HSEntryPatchConstantFuncAttr,
  2957. patchConstantFunctionMap, patchConstantFunctionPropsMap);
  2958. ReplaceConstStaticGlobals(staticConstGlobalInitListMap,
  2959. staticConstGlobalCtorMap);
  2960. // Create copy for clip plane.
  2961. if (!clipPlaneFuncList.empty()) {
  2962. FinishClipPlane(HLM, clipPlaneFuncList, debugInfoMap, CGM);
  2963. }
  2964. // Add Reg bindings for resource in cb.
  2965. AddRegBindingsForResourceInConstantBuffer(HLM, constantRegBindingMap);
  2966. // Allocate constant buffers.
  2967. // Create Global variable and type annotation for each CBuffer.
  2968. FinishCBuffer(HLM, CBufferType, m_ConstVarAnnotationMap);
  2969. // Translate calls to RayQuery constructor into hl Allocate calls
  2970. TranslateRayQueryConstructor(HLM);
  2971. bool bIsLib = HLM.GetShaderModel()->IsLib();
  2972. if (!bIsLib) {
  2973. // need this for "llvm.global_dtors"?
  2974. ProcessCtorFunctions(M, "llvm.global_ctors",
  2975. Entry.Func->getEntryBlock().getFirstInsertionPt());
  2976. }
  2977. UpdateLinkage(HLM, CGM, m_ExportMap, entryFunctionMap,
  2978. patchConstantFunctionMap);
  2979. // Do simple transform to make later lower pass easier.
  2980. SimpleTransformForHLDXIR(&M);
  2981. // Add dx.break function and make appropriate breaks conditional on it.
  2982. AddDxBreak(M, m_DxBreaks);
  2983. // Handle lang extensions if provided.
  2984. if (CGM.getCodeGenOpts().HLSLExtensionsCodegen) {
  2985. ExtensionCodeGen(HLM, CGM);
  2986. }
  2987. // At this point, we have a high-level DXIL module - record this.
  2988. SetPauseResumePasses(*m_pHLModule->GetModule(), "hlsl-hlemit",
  2989. "hlsl-hlensure");
  2990. }
  2991. RValue CGMSHLSLRuntime::EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF,
  2992. const FunctionDecl *FD,
  2993. const CallExpr *E,
  2994. ReturnValueSlot ReturnValue) {
  2995. const Decl *TargetDecl = E->getCalleeDecl();
  2996. llvm::Value *Callee = CGF.EmitScalarExpr(E->getCallee());
  2997. RValue RV = CGF.EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  2998. TargetDecl);
  2999. if (RV.isScalar() && RV.getScalarVal() != nullptr) {
  3000. if (CallInst *CI = dyn_cast<CallInst>(RV.getScalarVal())) {
  3001. Function *F = CI->getCalledFunction();
  3002. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  3003. if (group == HLOpcodeGroup::HLIntrinsic) {
  3004. bool allOperandImm = true;
  3005. for (auto &operand : CI->arg_operands()) {
  3006. bool isImm = isa<ConstantInt>(operand) || isa<ConstantFP>(operand) ||
  3007. isa<ConstantAggregateZero>(operand) || isa<ConstantDataVector>(operand);
  3008. if (!isImm) {
  3009. allOperandImm = false;
  3010. break;
  3011. } else if (operand->getType()->isHalfTy()) {
  3012. // Not support half Eval yet.
  3013. allOperandImm = false;
  3014. break;
  3015. }
  3016. }
  3017. if (allOperandImm) {
  3018. unsigned intrinsicOpcode;
  3019. StringRef intrinsicGroup;
  3020. hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup);
  3021. IntrinsicOp opcode = static_cast<IntrinsicOp>(intrinsicOpcode);
  3022. if (Value *Result = TryEvalIntrinsic(CI, opcode)) {
  3023. RV = RValue::get(Result);
  3024. }
  3025. }
  3026. }
  3027. }
  3028. }
  3029. return RV;
  3030. }
  3031. static HLOpcodeGroup GetHLOpcodeGroup(const clang::Stmt::StmtClass stmtClass) {
  3032. switch (stmtClass) {
  3033. case Stmt::CStyleCastExprClass:
  3034. case Stmt::ImplicitCastExprClass:
  3035. case Stmt::CXXFunctionalCastExprClass:
  3036. return HLOpcodeGroup::HLCast;
  3037. case Stmt::InitListExprClass:
  3038. return HLOpcodeGroup::HLInit;
  3039. case Stmt::BinaryOperatorClass:
  3040. case Stmt::CompoundAssignOperatorClass:
  3041. return HLOpcodeGroup::HLBinOp;
  3042. case Stmt::UnaryOperatorClass:
  3043. return HLOpcodeGroup::HLUnOp;
  3044. case Stmt::ExtMatrixElementExprClass:
  3045. return HLOpcodeGroup::HLSubscript;
  3046. case Stmt::CallExprClass:
  3047. return HLOpcodeGroup::HLIntrinsic;
  3048. case Stmt::ConditionalOperatorClass:
  3049. return HLOpcodeGroup::HLSelect;
  3050. default:
  3051. llvm_unreachable("not support operation");
  3052. }
  3053. }
  3054. // NOTE: This table must match BinaryOperator::Opcode
  3055. static const HLBinaryOpcode BinaryOperatorKindMap[] = {
  3056. HLBinaryOpcode::Invalid, // PtrMemD
  3057. HLBinaryOpcode::Invalid, // PtrMemI
  3058. HLBinaryOpcode::Mul, HLBinaryOpcode::Div, HLBinaryOpcode::Rem,
  3059. HLBinaryOpcode::Add, HLBinaryOpcode::Sub, HLBinaryOpcode::Shl,
  3060. HLBinaryOpcode::Shr, HLBinaryOpcode::LT, HLBinaryOpcode::GT,
  3061. HLBinaryOpcode::LE, HLBinaryOpcode::GE, HLBinaryOpcode::EQ,
  3062. HLBinaryOpcode::NE, HLBinaryOpcode::And, HLBinaryOpcode::Xor,
  3063. HLBinaryOpcode::Or, HLBinaryOpcode::LAnd, HLBinaryOpcode::LOr,
  3064. HLBinaryOpcode::Invalid, // Assign,
  3065. // The assign part is done by matrix store
  3066. HLBinaryOpcode::Mul, // MulAssign
  3067. HLBinaryOpcode::Div, // DivAssign
  3068. HLBinaryOpcode::Rem, // RemAssign
  3069. HLBinaryOpcode::Add, // AddAssign
  3070. HLBinaryOpcode::Sub, // SubAssign
  3071. HLBinaryOpcode::Shl, // ShlAssign
  3072. HLBinaryOpcode::Shr, // ShrAssign
  3073. HLBinaryOpcode::And, // AndAssign
  3074. HLBinaryOpcode::Xor, // XorAssign
  3075. HLBinaryOpcode::Or, // OrAssign
  3076. HLBinaryOpcode::Invalid, // Comma
  3077. };
  3078. // NOTE: This table must match UnaryOperator::Opcode
  3079. static const HLUnaryOpcode UnaryOperatorKindMap[] = {
  3080. HLUnaryOpcode::PostInc, HLUnaryOpcode::PostDec,
  3081. HLUnaryOpcode::PreInc, HLUnaryOpcode::PreDec,
  3082. HLUnaryOpcode::Invalid, // AddrOf,
  3083. HLUnaryOpcode::Invalid, // Deref,
  3084. HLUnaryOpcode::Plus, HLUnaryOpcode::Minus,
  3085. HLUnaryOpcode::Not, HLUnaryOpcode::LNot,
  3086. HLUnaryOpcode::Invalid, // Real,
  3087. HLUnaryOpcode::Invalid, // Imag,
  3088. HLUnaryOpcode::Invalid, // Extension
  3089. };
  3090. static unsigned GetHLOpcode(const Expr *E) {
  3091. switch (E->getStmtClass()) {
  3092. case Stmt::CompoundAssignOperatorClass:
  3093. case Stmt::BinaryOperatorClass: {
  3094. const clang::BinaryOperator *binOp = cast<clang::BinaryOperator>(E);
  3095. HLBinaryOpcode binOpcode = BinaryOperatorKindMap[binOp->getOpcode()];
  3096. if (HasUnsignedOpcode(binOpcode)) {
  3097. if (hlsl::IsHLSLUnsigned(binOp->getLHS()->getType())) {
  3098. binOpcode = GetUnsignedOpcode(binOpcode);
  3099. }
  3100. }
  3101. return static_cast<unsigned>(binOpcode);
  3102. }
  3103. case Stmt::UnaryOperatorClass: {
  3104. const UnaryOperator *unOp = cast<clang::UnaryOperator>(E);
  3105. HLUnaryOpcode unOpcode = UnaryOperatorKindMap[unOp->getOpcode()];
  3106. return static_cast<unsigned>(unOpcode);
  3107. }
  3108. case Stmt::ImplicitCastExprClass:
  3109. case Stmt::CStyleCastExprClass: {
  3110. const CastExpr *CE = cast<CastExpr>(E);
  3111. bool toUnsigned = hlsl::IsHLSLUnsigned(E->getType());
  3112. bool fromUnsigned = hlsl::IsHLSLUnsigned(CE->getSubExpr()->getType());
  3113. if (toUnsigned && fromUnsigned)
  3114. return static_cast<unsigned>(HLCastOpcode::UnsignedUnsignedCast);
  3115. else if (toUnsigned)
  3116. return static_cast<unsigned>(HLCastOpcode::ToUnsignedCast);
  3117. else if (fromUnsigned)
  3118. return static_cast<unsigned>(HLCastOpcode::FromUnsignedCast);
  3119. else
  3120. return static_cast<unsigned>(HLCastOpcode::DefaultCast);
  3121. }
  3122. default:
  3123. return 0;
  3124. }
  3125. }
  3126. static Value *
  3127. EmitHLSLMatrixOperationCallImp(CGBuilderTy &Builder, HLOpcodeGroup group,
  3128. unsigned opcode, llvm::Type *RetType,
  3129. ArrayRef<Value *> paramList, llvm::Module &M) {
  3130. SmallVector<llvm::Type *, 4> paramTyList;
  3131. // Add the opcode param
  3132. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  3133. paramTyList.emplace_back(opcodeTy);
  3134. for (Value *param : paramList) {
  3135. paramTyList.emplace_back(param->getType());
  3136. }
  3137. llvm::FunctionType *funcTy =
  3138. llvm::FunctionType::get(RetType, paramTyList, false);
  3139. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  3140. SmallVector<Value *, 4> opcodeParamList;
  3141. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  3142. opcodeParamList.emplace_back(opcodeConst);
  3143. opcodeParamList.append(paramList.begin(), paramList.end());
  3144. return Builder.CreateCall(opFunc, opcodeParamList);
  3145. }
  3146. static Value *EmitHLSLArrayInit(CGBuilderTy &Builder, HLOpcodeGroup group,
  3147. unsigned opcode, llvm::Type *RetType,
  3148. ArrayRef<Value *> paramList, llvm::Module &M) {
  3149. // It's a matrix init.
  3150. if (!RetType->isVoidTy())
  3151. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  3152. paramList, M);
  3153. Value *arrayPtr = paramList[0];
  3154. llvm::ArrayType *AT =
  3155. cast<llvm::ArrayType>(arrayPtr->getType()->getPointerElementType());
  3156. // Avoid the arrayPtr.
  3157. unsigned paramSize = paramList.size() - 1;
  3158. // Support simple case here.
  3159. if (paramSize == AT->getArrayNumElements()) {
  3160. bool typeMatch = true;
  3161. llvm::Type *EltTy = AT->getArrayElementType();
  3162. if (EltTy->isAggregateType()) {
  3163. // Aggregate Type use pointer in initList.
  3164. EltTy = llvm::PointerType::get(EltTy, 0);
  3165. }
  3166. for (unsigned i = 1; i < paramList.size(); i++) {
  3167. if (paramList[i]->getType() != EltTy) {
  3168. typeMatch = false;
  3169. break;
  3170. }
  3171. }
  3172. // Both size and type match.
  3173. if (typeMatch) {
  3174. bool isPtr = EltTy->isPointerTy();
  3175. llvm::Type *i32Ty = llvm::Type::getInt32Ty(EltTy->getContext());
  3176. Constant *zero = ConstantInt::get(i32Ty, 0);
  3177. for (unsigned i = 1; i < paramList.size(); i++) {
  3178. Constant *idx = ConstantInt::get(i32Ty, i - 1);
  3179. Value *GEP = Builder.CreateInBoundsGEP(arrayPtr, {zero, idx});
  3180. Value *Elt = paramList[i];
  3181. if (isPtr) {
  3182. Elt = Builder.CreateLoad(Elt);
  3183. }
  3184. Builder.CreateStore(Elt, GEP);
  3185. }
  3186. // The return value will not be used.
  3187. return nullptr;
  3188. }
  3189. }
  3190. // Other case will be lowered in later pass.
  3191. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  3192. paramList, M);
  3193. }
  3194. void CGMSHLSLRuntime::FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  3195. SmallVector<QualType, 4> &eltTys,
  3196. QualType Ty, Value *val) {
  3197. CGBuilderTy &Builder = CGF.Builder;
  3198. llvm::Type *valTy = val->getType();
  3199. if (valTy->isPointerTy()) {
  3200. llvm::Type *valEltTy = valTy->getPointerElementType();
  3201. if (valEltTy->isVectorTy() ||
  3202. valEltTy->isSingleValueType()) {
  3203. Value *ldVal = Builder.CreateLoad(val);
  3204. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  3205. } else if (HLMatrixType::isa(valEltTy)) {
  3206. Value *ldVal = EmitHLSLMatrixLoad(Builder, val, Ty);
  3207. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  3208. } else {
  3209. llvm::Type *i32Ty = llvm::Type::getInt32Ty(valTy->getContext());
  3210. Value *zero = ConstantInt::get(i32Ty, 0);
  3211. if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(valEltTy)) {
  3212. QualType EltTy = Ty->getAsArrayTypeUnsafe()->getElementType();
  3213. for (unsigned i = 0; i < AT->getArrayNumElements(); i++) {
  3214. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3215. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3216. FlattenValToInitList(CGF, elts, eltTys, EltTy,EltPtr);
  3217. }
  3218. } else {
  3219. // Struct.
  3220. StructType *ST = cast<StructType>(valEltTy);
  3221. if (dxilutil::IsHLSLObjectType(ST)) {
  3222. // Save object directly like basic type.
  3223. elts.emplace_back(Builder.CreateLoad(val));
  3224. eltTys.emplace_back(Ty);
  3225. } else {
  3226. RecordDecl *RD = Ty->getAsStructureType()->getDecl();
  3227. const CGRecordLayout& RL = CGF.getTypes().getCGRecordLayout(RD);
  3228. // Take care base.
  3229. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3230. if (CXXRD->getNumBases()) {
  3231. for (const auto &I : CXXRD->bases()) {
  3232. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3233. I.getType()->castAs<RecordType>()->getDecl());
  3234. if (BaseDecl->field_empty())
  3235. continue;
  3236. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3237. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3238. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3239. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3240. FlattenValToInitList(CGF, elts, eltTys, parentTy, EltPtr);
  3241. }
  3242. }
  3243. }
  3244. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  3245. fieldIter != fieldEnd; ++fieldIter) {
  3246. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  3247. Value *gepIdx = ConstantInt::get(i32Ty, i);
  3248. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  3249. FlattenValToInitList(CGF, elts, eltTys, fieldIter->getType(), EltPtr);
  3250. }
  3251. }
  3252. }
  3253. }
  3254. } else {
  3255. if (HLMatrixType MatTy = HLMatrixType::dyn_cast(valTy)) {
  3256. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  3257. // All matrix Value should be row major.
  3258. // Init list is row major in scalar.
  3259. // So the order is match here, just cast to vector.
  3260. unsigned matSize = MatTy.getNumElements();
  3261. bool isRowMajor = hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  3262. HLCastOpcode opcode = isRowMajor ? HLCastOpcode::RowMatrixToVecCast
  3263. : HLCastOpcode::ColMatrixToVecCast;
  3264. // Cast to vector.
  3265. val = EmitHLSLMatrixOperationCallImp(
  3266. Builder, HLOpcodeGroup::HLCast,
  3267. static_cast<unsigned>(opcode),
  3268. llvm::VectorType::get(EltTy, matSize), {val}, TheModule);
  3269. valTy = val->getType();
  3270. }
  3271. if (valTy->isVectorTy()) {
  3272. QualType EltTy = hlsl::GetElementTypeOrType(Ty);
  3273. unsigned vecSize = valTy->getVectorNumElements();
  3274. for (unsigned i = 0; i < vecSize; i++) {
  3275. Value *Elt = Builder.CreateExtractElement(val, i);
  3276. elts.emplace_back(Elt);
  3277. eltTys.emplace_back(EltTy);
  3278. }
  3279. } else {
  3280. DXASSERT(valTy->isSingleValueType(), "must be single value type here");
  3281. elts.emplace_back(val);
  3282. eltTys.emplace_back(Ty);
  3283. }
  3284. }
  3285. }
  3286. static Value* ConvertScalarOrVector(CGBuilderTy& Builder, CodeGenTypes &Types,
  3287. Value *Val, QualType SrcQualTy, QualType DstQualTy) {
  3288. llvm::Type *SrcTy = Val->getType();
  3289. llvm::Type *DstTy = Types.ConvertType(DstQualTy);
  3290. DXASSERT(Val->getType() == Types.ConvertType(SrcQualTy), "QualType/Value mismatch!");
  3291. DXASSERT((SrcTy->isIntOrIntVectorTy() || SrcTy->isFPOrFPVectorTy())
  3292. && (DstTy->isIntOrIntVectorTy() || DstTy->isFPOrFPVectorTy()),
  3293. "EmitNumericConversion can only be used with int/float scalars/vectors.");
  3294. if (SrcTy == DstTy) return Val; // Valid no-op, including uint to int / int to uint
  3295. DXASSERT(SrcTy->isVectorTy()
  3296. ? (DstTy->isVectorTy() && SrcTy->getVectorNumElements() == DstTy->getVectorNumElements())
  3297. : !DstTy->isVectorTy(),
  3298. "EmitNumericConversion can only cast between scalars or vectors of matching sizes");
  3299. // Conversions to bools are comparisons
  3300. if (DstTy->getScalarSizeInBits() == 1) {
  3301. // fcmp une is what regular clang uses in C++ for (bool)f;
  3302. return SrcTy->isIntOrIntVectorTy()
  3303. ? Builder.CreateICmpNE(Val, llvm::Constant::getNullValue(SrcTy), "tobool")
  3304. : Builder.CreateFCmpUNE(Val, llvm::Constant::getNullValue(SrcTy), "tobool");
  3305. }
  3306. // Cast necessary
  3307. auto CastOp = static_cast<Instruction::CastOps>(HLModule::GetNumericCastOp(
  3308. SrcTy, hlsl::IsHLSLUnsigned(SrcQualTy), DstTy, hlsl::IsHLSLUnsigned(DstQualTy)));
  3309. return Builder.CreateCast(CastOp, Val, DstTy);
  3310. }
  3311. static Value* ConvertScalarOrVector(CodeGenFunction &CGF,
  3312. Value *Val, QualType SrcQualTy, QualType DstQualTy) {
  3313. return ConvertScalarOrVector(CGF.Builder, CGF.getTypes(), Val, SrcQualTy, DstQualTy);
  3314. }
  3315. // Cast elements in initlist if not match the target type.
  3316. // idx is current element index in initlist, Ty is target type.
  3317. // TODO: Stop handling missing cast here. Handle the casting of non-scalar values
  3318. // to their destination type in init list expressions at AST level.
  3319. static void AddMissingCastOpsInInitList(SmallVector<Value *, 4> &elts, SmallVector<QualType, 4> &eltTys, unsigned &idx, QualType Ty, CodeGenFunction &CGF) {
  3320. if (Ty->isArrayType()) {
  3321. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  3322. // Must be ConstantArrayType here.
  3323. unsigned arraySize = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  3324. QualType EltTy = AT->getElementType();
  3325. for (unsigned i = 0; i < arraySize; i++)
  3326. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3327. } else if (IsHLSLVecType(Ty)) {
  3328. QualType EltTy = GetHLSLVecElementType(Ty);
  3329. unsigned vecSize = GetHLSLVecSize(Ty);
  3330. for (unsigned i=0;i< vecSize;i++)
  3331. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3332. } else if (IsHLSLMatType(Ty)) {
  3333. QualType EltTy = GetHLSLMatElementType(Ty);
  3334. unsigned row, col;
  3335. GetHLSLMatRowColCount(Ty, row, col);
  3336. unsigned matSize = row*col;
  3337. for (unsigned i = 0; i < matSize; i++)
  3338. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  3339. } else if (Ty->isRecordType()) {
  3340. if (dxilutil::IsHLSLObjectType(CGF.ConvertType(Ty))) {
  3341. // Skip hlsl object.
  3342. idx++;
  3343. } else {
  3344. const RecordType *RT = Ty->getAsStructureType();
  3345. // For CXXRecord.
  3346. if (!RT)
  3347. RT = Ty->getAs<RecordType>();
  3348. RecordDecl *RD = RT->getDecl();
  3349. // Take care base.
  3350. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3351. if (CXXRD->getNumBases()) {
  3352. for (const auto &I : CXXRD->bases()) {
  3353. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3354. I.getType()->castAs<RecordType>()->getDecl());
  3355. if (BaseDecl->field_empty())
  3356. continue;
  3357. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3358. AddMissingCastOpsInInitList(elts, eltTys, idx, parentTy, CGF);
  3359. }
  3360. }
  3361. }
  3362. for (FieldDecl *field : RD->fields())
  3363. AddMissingCastOpsInInitList(elts, eltTys, idx, field->getType(), CGF);
  3364. }
  3365. }
  3366. else {
  3367. // Basic type.
  3368. elts[idx] = ConvertScalarOrVector(CGF, elts[idx], eltTys[idx], Ty);
  3369. idx++;
  3370. }
  3371. }
  3372. static void StoreInitListToDestPtr(Value *DestPtr,
  3373. SmallVector<Value *, 4> &elts, unsigned &idx,
  3374. QualType Type, bool bDefaultRowMajor,
  3375. CodeGenFunction &CGF, llvm::Module &M) {
  3376. CodeGenTypes &Types = CGF.getTypes();
  3377. CGBuilderTy &Builder = CGF.Builder;
  3378. llvm::Type *Ty = DestPtr->getType()->getPointerElementType();
  3379. if (Ty->isVectorTy()) {
  3380. llvm::Type *RegTy = CGF.ConvertType(Type);
  3381. Value *Result = UndefValue::get(RegTy);
  3382. for (unsigned i = 0; i < RegTy->getVectorNumElements(); i++)
  3383. Result = Builder.CreateInsertElement(Result, elts[idx + i], i);
  3384. Result = CGF.EmitToMemory(Result, Type);
  3385. Builder.CreateStore(Result, DestPtr);
  3386. idx += Ty->getVectorNumElements();
  3387. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  3388. bool isRowMajor = hlsl::IsHLSLMatRowMajor(Type, bDefaultRowMajor);
  3389. std::vector<Value *> matInitList(MatTy.getNumElements());
  3390. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  3391. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  3392. unsigned matIdx = c * MatTy.getNumRows() + r;
  3393. matInitList[matIdx] = elts[idx + matIdx];
  3394. }
  3395. }
  3396. idx += MatTy.getNumElements();
  3397. Value *matVal =
  3398. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLInit,
  3399. /*opcode*/ 0, Ty, matInitList, M);
  3400. // matVal return from HLInit is row major.
  3401. // If DestPtr is row major, just store it directly.
  3402. if (!isRowMajor) {
  3403. // ColMatStore need a col major value.
  3404. // Cast row major matrix into col major.
  3405. // Then store it.
  3406. Value *colMatVal = EmitHLSLMatrixOperationCallImp(
  3407. Builder, HLOpcodeGroup::HLCast,
  3408. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix), Ty,
  3409. {matVal}, M);
  3410. EmitHLSLMatrixOperationCallImp(
  3411. Builder, HLOpcodeGroup::HLMatLoadStore,
  3412. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore), Ty,
  3413. {DestPtr, colMatVal}, M);
  3414. } else {
  3415. EmitHLSLMatrixOperationCallImp(
  3416. Builder, HLOpcodeGroup::HLMatLoadStore,
  3417. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore), Ty,
  3418. {DestPtr, matVal}, M);
  3419. }
  3420. } else if (Ty->isStructTy()) {
  3421. if (dxilutil::IsHLSLObjectType(Ty)) {
  3422. Builder.CreateStore(elts[idx], DestPtr);
  3423. idx++;
  3424. } else {
  3425. Constant *zero = Builder.getInt32(0);
  3426. const RecordType *RT = Type->getAsStructureType();
  3427. // For CXXRecord.
  3428. if (!RT)
  3429. RT = Type->getAs<RecordType>();
  3430. RecordDecl *RD = RT->getDecl();
  3431. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  3432. // Take care base.
  3433. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  3434. if (CXXRD->getNumBases()) {
  3435. for (const auto &I : CXXRD->bases()) {
  3436. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  3437. I.getType()->castAs<RecordType>()->getDecl());
  3438. if (BaseDecl->field_empty())
  3439. continue;
  3440. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3441. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3442. Constant *gepIdx = Builder.getInt32(i);
  3443. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3444. StoreInitListToDestPtr(GEP, elts, idx, parentTy,
  3445. bDefaultRowMajor, CGF, M);
  3446. }
  3447. }
  3448. }
  3449. for (FieldDecl *field : RD->fields()) {
  3450. unsigned i = RL.getLLVMFieldNo(field);
  3451. Constant *gepIdx = Builder.getInt32(i);
  3452. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3453. StoreInitListToDestPtr(GEP, elts, idx, field->getType(),
  3454. bDefaultRowMajor, CGF, M);
  3455. }
  3456. }
  3457. } else if (Ty->isArrayTy()) {
  3458. Constant *zero = Builder.getInt32(0);
  3459. QualType EltType = Type->getAsArrayTypeUnsafe()->getElementType();
  3460. for (unsigned i = 0; i < Ty->getArrayNumElements(); i++) {
  3461. Constant *gepIdx = Builder.getInt32(i);
  3462. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  3463. StoreInitListToDestPtr(GEP, elts, idx, EltType, bDefaultRowMajor,
  3464. CGF, M);
  3465. }
  3466. } else {
  3467. DXASSERT(Ty->isSingleValueType(), "invalid type");
  3468. llvm::Type *i1Ty = Builder.getInt1Ty();
  3469. Value *V = elts[idx];
  3470. if (V->getType() == i1Ty &&
  3471. DestPtr->getType()->getPointerElementType() != i1Ty) {
  3472. V = Builder.CreateZExt(V, DestPtr->getType()->getPointerElementType());
  3473. }
  3474. Builder.CreateStore(V, DestPtr);
  3475. idx++;
  3476. }
  3477. }
  3478. void CGMSHLSLRuntime::ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  3479. SmallVector<Value *, 4> &EltValList,
  3480. SmallVector<QualType, 4> &EltTyList) {
  3481. unsigned NumInitElements = E->getNumInits();
  3482. for (unsigned i = 0; i != NumInitElements; ++i) {
  3483. Expr *init = E->getInit(i);
  3484. QualType iType = init->getType();
  3485. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  3486. ScanInitList(CGF, initList, EltValList, EltTyList);
  3487. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  3488. llvm::Value *initVal = CGF.EmitScalarExpr(init);
  3489. FlattenValToInitList(CGF, EltValList, EltTyList, iType, initVal);
  3490. } else {
  3491. AggValueSlot Slot =
  3492. CGF.CreateAggTemp(init->getType(), "Agg.InitList.tmp");
  3493. CGF.EmitAggExpr(init, Slot);
  3494. llvm::Value *aggPtr = Slot.getAddr();
  3495. FlattenValToInitList(CGF, EltValList, EltTyList, iType, aggPtr);
  3496. }
  3497. }
  3498. }
  3499. // Is Type of E match Ty.
  3500. static bool ExpTypeMatch(Expr *E, QualType Ty, ASTContext &Ctx, CodeGenTypes &Types) {
  3501. if (InitListExpr *initList = dyn_cast<InitListExpr>(E)) {
  3502. unsigned NumInitElements = initList->getNumInits();
  3503. // Skip vector and matrix type.
  3504. if (Ty->isVectorType())
  3505. return false;
  3506. if (hlsl::IsHLSLVecMatType(Ty))
  3507. return false;
  3508. if (Ty->isStructureOrClassType()) {
  3509. RecordDecl *record = Ty->castAs<RecordType>()->getDecl();
  3510. bool bMatch = true;
  3511. unsigned i = 0;
  3512. for (auto it = record->field_begin(), end = record->field_end();
  3513. it != end; it++) {
  3514. if (i == NumInitElements) {
  3515. bMatch = false;
  3516. break;
  3517. }
  3518. Expr *init = initList->getInit(i++);
  3519. QualType EltTy = it->getType();
  3520. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  3521. if (!bMatch)
  3522. break;
  3523. }
  3524. bMatch &= i == NumInitElements;
  3525. if (bMatch && initList->getType()->isVoidType()) {
  3526. initList->setType(Ty);
  3527. }
  3528. return bMatch;
  3529. } else if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) {
  3530. const ConstantArrayType *AT = Ctx.getAsConstantArrayType(Ty);
  3531. QualType EltTy = AT->getElementType();
  3532. unsigned size = AT->getSize().getZExtValue();
  3533. if (size != NumInitElements)
  3534. return false;
  3535. bool bMatch = true;
  3536. for (unsigned i = 0; i != NumInitElements; ++i) {
  3537. Expr *init = initList->getInit(i);
  3538. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  3539. if (!bMatch)
  3540. break;
  3541. }
  3542. if (bMatch && initList->getType()->isVoidType()) {
  3543. initList->setType(Ty);
  3544. }
  3545. return bMatch;
  3546. } else {
  3547. return false;
  3548. }
  3549. } else {
  3550. llvm::Type *ExpTy = Types.ConvertType(E->getType());
  3551. llvm::Type *TargetTy = Types.ConvertType(Ty);
  3552. return ExpTy == TargetTy;
  3553. }
  3554. }
  3555. bool CGMSHLSLRuntime::IsTrivalInitListExpr(CodeGenFunction &CGF,
  3556. InitListExpr *E) {
  3557. QualType Ty = E->getType();
  3558. bool result = ExpTypeMatch(E, Ty, CGF.getContext(), CGF.getTypes());
  3559. if (result) {
  3560. auto iter = staticConstGlobalInitMap.find(E);
  3561. if (iter != staticConstGlobalInitMap.end()) {
  3562. GlobalVariable * GV = iter->second;
  3563. auto &InitConstants = staticConstGlobalInitListMap[GV];
  3564. // Add Constant to InitList.
  3565. for (unsigned i=0;i<E->getNumInits();i++) {
  3566. Expr *Expr = E->getInit(i);
  3567. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Expr)) {
  3568. if (Cast->getCastKind() == CK_LValueToRValue) {
  3569. Expr = Cast->getSubExpr();
  3570. }
  3571. }
  3572. // Only do this on lvalue, if not lvalue, it will not be constant
  3573. // anyway.
  3574. if (Expr->isLValue()) {
  3575. LValue LV = CGF.EmitLValue(Expr);
  3576. if (LV.isSimple()) {
  3577. Constant *SrcPtr = dyn_cast<Constant>(LV.getAddress());
  3578. if (SrcPtr && !isa<UndefValue>(SrcPtr)) {
  3579. InitConstants.emplace_back(SrcPtr);
  3580. continue;
  3581. }
  3582. }
  3583. }
  3584. // Only support simple LV and Constant Ptr case.
  3585. // Other case just go normal path.
  3586. InitConstants.clear();
  3587. break;
  3588. }
  3589. if (InitConstants.empty())
  3590. staticConstGlobalInitListMap.erase(GV);
  3591. else
  3592. staticConstGlobalCtorMap[GV] = CGF.CurFn;
  3593. }
  3594. }
  3595. return result;
  3596. }
  3597. Value *CGMSHLSLRuntime::EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E,
  3598. // The destPtr when emiting aggregate init, for normal case, it will be null.
  3599. Value *DestPtr) {
  3600. if (DestPtr && E->getNumInits() == 1) {
  3601. llvm::Type *ExpTy = CGF.ConvertType(E->getType());
  3602. llvm::Type *TargetTy = CGF.ConvertType(E->getInit(0)->getType());
  3603. if (ExpTy == TargetTy) {
  3604. Expr *Expr = E->getInit(0);
  3605. LValue LV = CGF.EmitLValue(Expr);
  3606. if (LV.isSimple()) {
  3607. Value *SrcPtr = LV.getAddress();
  3608. SmallVector<Value *, 4> idxList;
  3609. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Expr->getType(),
  3610. E->getType(), SrcPtr->getType());
  3611. return nullptr;
  3612. }
  3613. }
  3614. }
  3615. SmallVector<Value *, 4> EltValList;
  3616. SmallVector<QualType, 4> EltTyList;
  3617. ScanInitList(CGF, E, EltValList, EltTyList);
  3618. QualType ResultTy = E->getType();
  3619. unsigned idx = 0;
  3620. // Create cast if need.
  3621. AddMissingCastOpsInInitList(EltValList, EltTyList, idx, ResultTy, CGF);
  3622. DXASSERT(idx == EltValList.size(), "size must match");
  3623. llvm::Type *RetTy = CGF.ConvertType(ResultTy);
  3624. if (DestPtr) {
  3625. SmallVector<Value *, 4> ParamList;
  3626. DXASSERT_NOMSG(RetTy->isAggregateType());
  3627. ParamList.emplace_back(DestPtr);
  3628. ParamList.append(EltValList.begin(), EltValList.end());
  3629. idx = 0;
  3630. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  3631. StoreInitListToDestPtr(DestPtr, EltValList, idx, ResultTy,
  3632. bDefaultRowMajor, CGF, TheModule);
  3633. return nullptr;
  3634. }
  3635. if (IsHLSLVecType(ResultTy)) {
  3636. Value *Result = UndefValue::get(RetTy);
  3637. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++)
  3638. Result = CGF.Builder.CreateInsertElement(Result, EltValList[i], i);
  3639. return Result;
  3640. } else {
  3641. // Must be matrix here.
  3642. DXASSERT(IsHLSLMatType(ResultTy), "must be matrix type here.");
  3643. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLInit,
  3644. /*opcode*/ 0, RetTy, EltValList,
  3645. TheModule);
  3646. }
  3647. }
  3648. static void FlatConstToList(CodeGenTypes &Types, bool bDefaultRowMajor,
  3649. Constant *C, QualType QualTy,
  3650. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys) {
  3651. llvm::Type *Ty = C->getType();
  3652. DXASSERT(Types.ConvertTypeForMem(QualTy) == Ty, "QualType/Type mismatch!");
  3653. if (llvm::VectorType *VecTy = dyn_cast<llvm::VectorType>(Ty)) {
  3654. DXASSERT(hlsl::IsHLSLVecType(QualTy), "QualType/Type mismatch!");
  3655. QualType VecElemQualTy = hlsl::GetHLSLVecElementType(QualTy);
  3656. for (unsigned i = 0; i < VecTy->getNumElements(); i++) {
  3657. EltVals.emplace_back(C->getAggregateElement(i));
  3658. EltQualTys.emplace_back(VecElemQualTy);
  3659. }
  3660. } else if (HLMatrixType::isa(Ty)) {
  3661. DXASSERT(hlsl::IsHLSLMatType(QualTy), "QualType/Type mismatch!");
  3662. // matrix type is struct { [rowcount x <colcount x T>] };
  3663. // Strip the struct level here.
  3664. Constant *RowArrayVal = C->getAggregateElement((unsigned)0);
  3665. QualType MatEltQualTy = hlsl::GetHLSLMatElementType(QualTy);
  3666. unsigned RowCount, ColCount;
  3667. hlsl::GetHLSLMatRowColCount(QualTy, RowCount, ColCount);
  3668. // Get all the elements from the array of row vectors.
  3669. // Matrices are never in memory representation so convert as needed.
  3670. SmallVector<Constant *, 16> MatElts;
  3671. for (unsigned r = 0; r < RowCount; ++r) {
  3672. Constant *RowVec = RowArrayVal->getAggregateElement(r);
  3673. for (unsigned c = 0; c < ColCount; ++c) {
  3674. Constant *MatElt = RowVec->getAggregateElement(c);
  3675. if (MatEltQualTy->isBooleanType()) {
  3676. DXASSERT(MatElt->getType()->isIntegerTy(1),
  3677. "Matrix elements should be in their register representation.");
  3678. MatElt = llvm::ConstantExpr::getZExt(MatElt, Types.ConvertTypeForMem(MatEltQualTy));
  3679. }
  3680. MatElts.emplace_back(MatElt);
  3681. }
  3682. }
  3683. // Return the elements in the order respecting the orientation.
  3684. // Constant initializers are used as the initial value for static variables,
  3685. // which live in memory. This is why they have to respect memory packing order.
  3686. bool IsRowMajor = hlsl::IsHLSLMatRowMajor(QualTy, bDefaultRowMajor);
  3687. for (unsigned r = 0; r < RowCount; ++r) {
  3688. for (unsigned c = 0; c < ColCount; ++c) {
  3689. unsigned Idx = IsRowMajor ? (r * ColCount + c) : (c * RowCount + r);
  3690. EltVals.emplace_back(MatElts[Idx]);
  3691. EltQualTys.emplace_back(MatEltQualTy);
  3692. }
  3693. }
  3694. }
  3695. else if (const clang::ConstantArrayType *ClangArrayTy = Types.getContext().getAsConstantArrayType(QualTy)) {
  3696. QualType ArrayEltQualTy = ClangArrayTy->getElementType();
  3697. uint64_t ArraySize = ClangArrayTy->getSize().getLimitedValue();
  3698. DXASSERT(cast<llvm::ArrayType>(Ty)->getArrayNumElements() == ArraySize, "QualType/Type mismatch!");
  3699. for (unsigned i = 0; i < ArraySize; i++) {
  3700. FlatConstToList(Types, bDefaultRowMajor, C->getAggregateElement(i), ArrayEltQualTy,
  3701. EltVals, EltQualTys);
  3702. }
  3703. }
  3704. else if (const clang::RecordType* RecordTy = QualTy->getAs<clang::RecordType>()) {
  3705. DXASSERT(dyn_cast<llvm::StructType>(Ty) != nullptr, "QualType/Type mismatch!");
  3706. RecordDecl *RecordDecl = RecordTy->getDecl();
  3707. const CGRecordLayout &RL = Types.getCGRecordLayout(RecordDecl);
  3708. // Take care base.
  3709. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RecordDecl)) {
  3710. if (CXXRD->getNumBases()) {
  3711. for (const auto &I : CXXRD->bases()) {
  3712. const CXXRecordDecl *BaseDecl =
  3713. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  3714. if (BaseDecl->field_empty())
  3715. continue;
  3716. QualType BaseQualTy = QualType(BaseDecl->getTypeForDecl(), 0);
  3717. unsigned BaseFieldIdx = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  3718. FlatConstToList(Types, bDefaultRowMajor,
  3719. C->getAggregateElement(BaseFieldIdx), BaseQualTy, EltVals, EltQualTys);
  3720. }
  3721. }
  3722. }
  3723. for (auto FieldIt = RecordDecl->field_begin(), fieldEnd = RecordDecl->field_end();
  3724. FieldIt != fieldEnd; ++FieldIt) {
  3725. unsigned FieldIndex = RL.getLLVMFieldNo(*FieldIt);
  3726. FlatConstToList(Types, bDefaultRowMajor,
  3727. C->getAggregateElement(FieldIndex), FieldIt->getType(), EltVals, EltQualTys);
  3728. }
  3729. }
  3730. else {
  3731. // At this point, we should have scalars in their memory representation
  3732. DXASSERT_NOMSG(QualTy->isBuiltinType());
  3733. EltVals.emplace_back(C);
  3734. EltQualTys.emplace_back(QualTy);
  3735. }
  3736. }
  3737. static bool ScanConstInitList(CodeGenModule &CGM, bool bDefaultRowMajor,
  3738. InitListExpr *InitList,
  3739. SmallVectorImpl<Constant *> &EltVals,
  3740. SmallVectorImpl<QualType> &EltQualTys) {
  3741. unsigned NumInitElements = InitList->getNumInits();
  3742. for (unsigned i = 0; i != NumInitElements; ++i) {
  3743. Expr *InitExpr = InitList->getInit(i);
  3744. QualType InitQualTy = InitExpr->getType();
  3745. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(InitExpr)) {
  3746. if (!ScanConstInitList(CGM, bDefaultRowMajor, SubInitList, EltVals, EltQualTys))
  3747. return false;
  3748. } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(InitExpr)) {
  3749. if (VarDecl *Var = dyn_cast<VarDecl>(DeclRef->getDecl())) {
  3750. if (!Var->hasInit())
  3751. return false;
  3752. if (Constant *InitVal = CGM.EmitConstantInit(*Var)) {
  3753. FlatConstToList(CGM.getTypes(), bDefaultRowMajor,
  3754. InitVal, InitQualTy, EltVals, EltQualTys);
  3755. } else {
  3756. return false;
  3757. }
  3758. } else {
  3759. return false;
  3760. }
  3761. } else if (hlsl::IsHLSLMatType(InitQualTy)) {
  3762. return false;
  3763. } else if (CodeGenFunction::hasScalarEvaluationKind(InitQualTy)) {
  3764. if (Constant *InitVal = CGM.EmitConstantExpr(InitExpr, InitQualTy)) {
  3765. FlatConstToList(CGM.getTypes(), bDefaultRowMajor, InitVal, InitQualTy, EltVals, EltQualTys);
  3766. } else {
  3767. return false;
  3768. }
  3769. } else {
  3770. return false;
  3771. }
  3772. }
  3773. return true;
  3774. }
  3775. static Constant *BuildConstInitializer(CodeGenTypes &Types, bool bDefaultRowMajor,
  3776. QualType QualTy, bool MemRepr,
  3777. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx);
  3778. static Constant *BuildConstMatrix(CodeGenTypes &Types, bool bDefaultRowMajor, QualType QualTy,
  3779. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  3780. QualType MatEltTy = hlsl::GetHLSLMatElementType(QualTy);
  3781. unsigned RowCount, ColCount;
  3782. hlsl::GetHLSLMatRowColCount(QualTy, RowCount, ColCount);
  3783. bool IsRowMajor = hlsl::IsHLSLMatRowMajor(QualTy, bDefaultRowMajor);
  3784. // Save initializer elements first.
  3785. // Matrix initializer is row major.
  3786. SmallVector<Constant *, 16> RowMajorMatElts;
  3787. for (unsigned i = 0; i < RowCount * ColCount; i++) {
  3788. // Matrix elements are never in their memory representation,
  3789. // to preserve type information for later lowering.
  3790. bool MemRepr = false;
  3791. RowMajorMatElts.emplace_back(BuildConstInitializer(
  3792. Types, bDefaultRowMajor, MatEltTy, MemRepr,
  3793. EltVals, EltQualTys, EltIdx));
  3794. }
  3795. SmallVector<Constant *, 16> FinalMatElts;
  3796. if (IsRowMajor) {
  3797. FinalMatElts = RowMajorMatElts;
  3798. }
  3799. else {
  3800. // Cast row major to col major.
  3801. for (unsigned c = 0; c < ColCount; c++) {
  3802. for (unsigned r = 0; r < RowCount; r++) {
  3803. FinalMatElts.emplace_back(RowMajorMatElts[r * ColCount + c]);
  3804. }
  3805. }
  3806. }
  3807. // The type is vector<element, col>[row].
  3808. SmallVector<Constant *, 4> Rows;
  3809. unsigned idx = 0;
  3810. for (unsigned r = 0; r < RowCount; r++) {
  3811. SmallVector<Constant *, 4> RowElts;
  3812. for (unsigned c = 0; c < ColCount; c++) {
  3813. RowElts.emplace_back(FinalMatElts[idx++]);
  3814. }
  3815. Rows.emplace_back(llvm::ConstantVector::get(RowElts));
  3816. }
  3817. Constant *RowArray = llvm::ConstantArray::get(
  3818. llvm::ArrayType::get(Rows[0]->getType(), Rows.size()), Rows);
  3819. return llvm::ConstantStruct::get(cast<llvm::StructType>(Types.ConvertType(QualTy)), RowArray);
  3820. }
  3821. static Constant *BuildConstStruct(CodeGenTypes &Types, bool bDefaultRowMajor, QualType QualTy,
  3822. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  3823. const RecordDecl *Record = QualTy->castAs<RecordType>()->getDecl();
  3824. bool MemRepr = true; // Structs are always in their memory representation
  3825. SmallVector<Constant *, 4> FieldVals;
  3826. if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  3827. if (CXXRecord->getNumBases()) {
  3828. // Add base as field.
  3829. for (const auto &BaseSpec : CXXRecord->bases()) {
  3830. const CXXRecordDecl *BaseDecl =
  3831. cast<CXXRecordDecl>(BaseSpec.getType()->castAs<RecordType>()->getDecl());
  3832. // Skip empty struct.
  3833. if (BaseDecl->field_empty())
  3834. continue;
  3835. // Add base as a whole constant. Not as element.
  3836. FieldVals.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  3837. BaseSpec.getType(), MemRepr, EltVals, EltQualTys, EltIdx));
  3838. }
  3839. }
  3840. }
  3841. for (auto FieldIt = Record->field_begin(), FieldEnd = Record->field_end();
  3842. FieldIt != FieldEnd; ++FieldIt) {
  3843. FieldVals.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  3844. FieldIt->getType(), MemRepr, EltVals, EltQualTys, EltIdx));
  3845. }
  3846. return llvm::ConstantStruct::get(cast<llvm::StructType>(Types.ConvertTypeForMem(QualTy)), FieldVals);
  3847. }
  3848. static Constant *BuildConstInitializer(CodeGenTypes &Types, bool bDefaultRowMajor,
  3849. QualType QualTy, bool MemRepr,
  3850. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  3851. if (hlsl::IsHLSLVecType(QualTy)) {
  3852. QualType VecEltQualTy = hlsl::GetHLSLVecElementType(QualTy);
  3853. unsigned VecSize = hlsl::GetHLSLVecSize(QualTy);
  3854. SmallVector<Constant *, 4> VecElts;
  3855. for (unsigned i = 0; i < VecSize; i++) {
  3856. VecElts.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  3857. VecEltQualTy, MemRepr,
  3858. EltVals, EltQualTys, EltIdx));
  3859. }
  3860. return llvm::ConstantVector::get(VecElts);
  3861. }
  3862. else if (const clang::ConstantArrayType *ArrayTy = Types.getContext().getAsConstantArrayType(QualTy)) {
  3863. QualType ArrayEltQualTy = QualType(ArrayTy->getArrayElementTypeNoTypeQual(), 0);
  3864. uint64_t ArraySize = ArrayTy->getSize().getLimitedValue();
  3865. SmallVector<Constant *, 4> ArrayElts;
  3866. for (unsigned i = 0; i < ArraySize; i++) {
  3867. ArrayElts.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  3868. ArrayEltQualTy, true, // Array elements must be in their memory representation
  3869. EltVals, EltQualTys, EltIdx));
  3870. }
  3871. return llvm::ConstantArray::get(
  3872. cast<llvm::ArrayType>(Types.ConvertTypeForMem(QualTy)), ArrayElts);
  3873. }
  3874. else if (hlsl::IsHLSLMatType(QualTy)) {
  3875. return BuildConstMatrix(Types, bDefaultRowMajor, QualTy,
  3876. EltVals, EltQualTys, EltIdx);
  3877. }
  3878. else if (QualTy->getAs<clang::RecordType>() != nullptr) {
  3879. return BuildConstStruct(Types, bDefaultRowMajor, QualTy,
  3880. EltVals, EltQualTys, EltIdx);
  3881. } else {
  3882. DXASSERT_NOMSG(QualTy->isBuiltinType());
  3883. Constant *EltVal = EltVals[EltIdx];
  3884. QualType EltQualTy = EltQualTys[EltIdx];
  3885. EltIdx++;
  3886. // Initializer constants are in their memory representation.
  3887. if (EltQualTy == QualTy && MemRepr) return EltVal;
  3888. CGBuilderTy Builder(EltVal->getContext());
  3889. if (EltQualTy->isBooleanType()) {
  3890. // Convert to register representation
  3891. // We don't have access to CodeGenFunction::EmitFromMemory here
  3892. DXASSERT_NOMSG(!EltVal->getType()->isIntegerTy(1));
  3893. EltVal = cast<Constant>(Builder.CreateICmpNE(EltVal, Constant::getNullValue(EltVal->getType())));
  3894. }
  3895. Constant *Result = cast<Constant>(ConvertScalarOrVector(Builder, Types, EltVal, EltQualTy, QualTy));
  3896. if (QualTy->isBooleanType() && MemRepr) {
  3897. // Convert back to the memory representation
  3898. // We don't have access to CodeGenFunction::EmitToMemory here
  3899. DXASSERT_NOMSG(Result->getType()->isIntegerTy(1));
  3900. Result = cast<Constant>(Builder.CreateZExt(Result, Types.ConvertTypeForMem(QualTy)));
  3901. }
  3902. return Result;
  3903. }
  3904. }
  3905. Constant *CGMSHLSLRuntime::EmitHLSLConstInitListExpr(CodeGenModule &CGM,
  3906. InitListExpr *E) {
  3907. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  3908. SmallVector<Constant *, 4> EltVals;
  3909. SmallVector<QualType, 4> EltQualTys;
  3910. if (!ScanConstInitList(CGM, bDefaultRowMajor, E, EltVals, EltQualTys))
  3911. return nullptr;
  3912. QualType QualTy = E->getType();
  3913. unsigned EltIdx = 0;
  3914. bool MemRepr = true;
  3915. return BuildConstInitializer(CGM.getTypes(), bDefaultRowMajor,
  3916. QualTy, MemRepr, EltVals, EltQualTys, EltIdx);
  3917. }
  3918. Value *CGMSHLSLRuntime::EmitHLSLMatrixOperationCall(
  3919. CodeGenFunction &CGF, const clang::Expr *E, llvm::Type *RetType,
  3920. ArrayRef<Value *> paramList) {
  3921. HLOpcodeGroup group = GetHLOpcodeGroup(E->getStmtClass());
  3922. unsigned opcode = GetHLOpcode(E);
  3923. if (group == HLOpcodeGroup::HLInit)
  3924. return EmitHLSLArrayInit(CGF.Builder, group, opcode, RetType, paramList,
  3925. TheModule);
  3926. else
  3927. return EmitHLSLMatrixOperationCallImp(CGF.Builder, group, opcode, RetType,
  3928. paramList, TheModule);
  3929. }
  3930. void CGMSHLSLRuntime::EmitHLSLDiscard(CodeGenFunction &CGF) {
  3931. EmitHLSLMatrixOperationCallImp(
  3932. CGF.Builder, HLOpcodeGroup::HLIntrinsic,
  3933. static_cast<unsigned>(IntrinsicOp::IOP_clip),
  3934. llvm::Type::getVoidTy(CGF.getLLVMContext()),
  3935. {ConstantFP::get(llvm::Type::getFloatTy(CGF.getLLVMContext()), -1.0f)},
  3936. TheModule);
  3937. }
  3938. // Emit an artificially conditionalized branch for a break operation when in a potentially wave-enabled stage
  3939. // This allows the block containing what would have been an unconditional break to be included in the loop
  3940. // If the block uses values that are wave-sensitive, it needs to stay in the loop to prevent optimizations
  3941. // that might produce incorrect results by ignoring the volatile aspect of wave operation results.
  3942. void CGMSHLSLRuntime::EmitHLSLCondBreak(CodeGenFunction &CGF, Function *F, BasicBlock *DestBB, BasicBlock *AltBB) {
  3943. // If not a wave-enabled stage, we can keep everything unconditional as before
  3944. if (!m_pHLModule->GetShaderModel()->IsPS() && !m_pHLModule->GetShaderModel()->IsCS() &&
  3945. !m_pHLModule->GetShaderModel()->IsLib()) {
  3946. CGF.Builder.CreateBr(DestBB);
  3947. return;
  3948. }
  3949. // Create a branch that is temporarily conditional on a constant
  3950. // FinalizeCodeGen will turn this into a function, DxilFinalize will turn it into a global var
  3951. llvm::Type *boolTy = llvm::Type::getInt1Ty(Context);
  3952. BranchInst *BI = CGF.Builder.CreateCondBr(llvm::ConstantInt::get(boolTy,1), DestBB, AltBB);
  3953. m_DxBreaks.emplace_back(BI);
  3954. }
  3955. static llvm::Type *MergeIntType(llvm::IntegerType *T0, llvm::IntegerType *T1) {
  3956. if (T0->getBitWidth() > T1->getBitWidth())
  3957. return T0;
  3958. else
  3959. return T1;
  3960. }
  3961. static Value *CreateExt(CGBuilderTy &Builder, Value *Src, llvm::Type *DstTy,
  3962. bool bSigned) {
  3963. if (bSigned)
  3964. return Builder.CreateSExt(Src, DstTy);
  3965. else
  3966. return Builder.CreateZExt(Src, DstTy);
  3967. }
  3968. // For integer literal, try to get lowest precision.
  3969. static Value *CalcHLSLLiteralToLowestPrecision(CGBuilderTy &Builder, Value *Src,
  3970. bool bSigned) {
  3971. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  3972. APInt v = CI->getValue();
  3973. switch (v.getActiveWords()) {
  3974. case 4:
  3975. return Builder.getInt32(v.getLimitedValue());
  3976. case 8:
  3977. return Builder.getInt64(v.getLimitedValue());
  3978. case 2:
  3979. // TODO: use low precision type when support it in dxil.
  3980. // return Builder.getInt16(v.getLimitedValue());
  3981. return Builder.getInt32(v.getLimitedValue());
  3982. case 1:
  3983. // TODO: use precision type when support it in dxil.
  3984. // return Builder.getInt8(v.getLimitedValue());
  3985. return Builder.getInt32(v.getLimitedValue());
  3986. default:
  3987. return nullptr;
  3988. }
  3989. } else if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  3990. if (SI->getType()->isIntegerTy()) {
  3991. Value *T = SI->getTrueValue();
  3992. Value *F = SI->getFalseValue();
  3993. Value *lowT = CalcHLSLLiteralToLowestPrecision(Builder, T, bSigned);
  3994. Value *lowF = CalcHLSLLiteralToLowestPrecision(Builder, F, bSigned);
  3995. if (lowT && lowF && lowT != T && lowF != F) {
  3996. llvm::IntegerType *TTy = cast<llvm::IntegerType>(lowT->getType());
  3997. llvm::IntegerType *FTy = cast<llvm::IntegerType>(lowF->getType());
  3998. llvm::Type *Ty = MergeIntType(TTy, FTy);
  3999. if (TTy != Ty) {
  4000. lowT = CreateExt(Builder, lowT, Ty, bSigned);
  4001. }
  4002. if (FTy != Ty) {
  4003. lowF = CreateExt(Builder, lowF, Ty, bSigned);
  4004. }
  4005. Value *Cond = SI->getCondition();
  4006. return Builder.CreateSelect(Cond, lowT, lowF);
  4007. }
  4008. }
  4009. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(Src)) {
  4010. Value *Src0 = BO->getOperand(0);
  4011. Value *Src1 = BO->getOperand(1);
  4012. Value *CastSrc0 = CalcHLSLLiteralToLowestPrecision(Builder, Src0, bSigned);
  4013. Value *CastSrc1 = CalcHLSLLiteralToLowestPrecision(Builder, Src1, bSigned);
  4014. if (Src0 != CastSrc0 && Src1 != CastSrc1 && CastSrc0 && CastSrc1 &&
  4015. CastSrc0->getType() == CastSrc1->getType()) {
  4016. llvm::IntegerType *Ty0 = cast<llvm::IntegerType>(CastSrc0->getType());
  4017. llvm::IntegerType *Ty1 = cast<llvm::IntegerType>(CastSrc0->getType());
  4018. llvm::Type *Ty = MergeIntType(Ty0, Ty1);
  4019. if (Ty0 != Ty) {
  4020. CastSrc0 = CreateExt(Builder, CastSrc0, Ty, bSigned);
  4021. }
  4022. if (Ty1 != Ty) {
  4023. CastSrc1 = CreateExt(Builder, CastSrc1, Ty, bSigned);
  4024. }
  4025. return Builder.CreateBinOp(BO->getOpcode(), CastSrc0, CastSrc1);
  4026. }
  4027. }
  4028. return nullptr;
  4029. }
  4030. Value *CGMSHLSLRuntime::EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src,
  4031. QualType SrcType,
  4032. QualType DstType) {
  4033. auto &Builder = CGF.Builder;
  4034. llvm::Type *DstTy = CGF.ConvertType(DstType);
  4035. bool bSrcSigned = SrcType->isSignedIntegerType();
  4036. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  4037. APInt v = CI->getValue();
  4038. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  4039. v = v.trunc(IT->getBitWidth());
  4040. switch (IT->getBitWidth()) {
  4041. case 32:
  4042. return Builder.getInt32(v.getLimitedValue());
  4043. case 64:
  4044. return Builder.getInt64(v.getLimitedValue());
  4045. case 16:
  4046. return Builder.getInt16(v.getLimitedValue());
  4047. case 8:
  4048. return Builder.getInt8(v.getLimitedValue());
  4049. default:
  4050. return nullptr;
  4051. }
  4052. } else {
  4053. DXASSERT_NOMSG(DstTy->isFloatingPointTy());
  4054. int64_t val = v.getLimitedValue();
  4055. if (v.isNegative())
  4056. val = 0-v.abs().getLimitedValue();
  4057. if (DstTy->isDoubleTy())
  4058. return ConstantFP::get(DstTy, (double)val);
  4059. else if (DstTy->isFloatTy())
  4060. return ConstantFP::get(DstTy, (float)val);
  4061. else {
  4062. if (bSrcSigned)
  4063. return Builder.CreateSIToFP(Src, DstTy);
  4064. else
  4065. return Builder.CreateUIToFP(Src, DstTy);
  4066. }
  4067. }
  4068. } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Src)) {
  4069. APFloat v = CF->getValueAPF();
  4070. double dv = v.convertToDouble();
  4071. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  4072. switch (IT->getBitWidth()) {
  4073. case 32:
  4074. return Builder.getInt32(dv);
  4075. case 64:
  4076. return Builder.getInt64(dv);
  4077. case 16:
  4078. return Builder.getInt16(dv);
  4079. case 8:
  4080. return Builder.getInt8(dv);
  4081. default:
  4082. return nullptr;
  4083. }
  4084. } else {
  4085. if (DstTy->isFloatTy()) {
  4086. float fv = dv;
  4087. return ConstantFP::get(DstTy->getContext(), APFloat(fv));
  4088. } else {
  4089. return Builder.CreateFPTrunc(Src, DstTy);
  4090. }
  4091. }
  4092. } else if (dyn_cast<UndefValue>(Src)) {
  4093. return UndefValue::get(DstTy);
  4094. } else {
  4095. Instruction *I = cast<Instruction>(Src);
  4096. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  4097. Value *T = SI->getTrueValue();
  4098. Value *F = SI->getFalseValue();
  4099. Value *Cond = SI->getCondition();
  4100. if (isa<llvm::ConstantInt>(T) && isa<llvm::ConstantInt>(F)) {
  4101. llvm::APInt lhs = cast<llvm::ConstantInt>(T)->getValue();
  4102. llvm::APInt rhs = cast<llvm::ConstantInt>(F)->getValue();
  4103. if (DstTy == Builder.getInt32Ty()) {
  4104. T = Builder.getInt32(lhs.getLimitedValue());
  4105. F = Builder.getInt32(rhs.getLimitedValue());
  4106. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4107. return Sel;
  4108. } else if (DstTy->isFloatingPointTy()) {
  4109. T = ConstantFP::get(DstTy, int64_t(lhs.getLimitedValue()));
  4110. F = ConstantFP::get(DstTy, int64_t(rhs.getLimitedValue()));
  4111. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4112. return Sel;
  4113. }
  4114. } else if (isa<llvm::ConstantFP>(T) && isa<llvm::ConstantFP>(F)) {
  4115. llvm::APFloat lhs = cast<llvm::ConstantFP>(T)->getValueAPF();
  4116. llvm::APFloat rhs = cast<llvm::ConstantFP>(F)->getValueAPF();
  4117. double ld = lhs.convertToDouble();
  4118. double rd = rhs.convertToDouble();
  4119. if (DstTy->isFloatTy()) {
  4120. float lf = ld;
  4121. float rf = rd;
  4122. T = ConstantFP::get(DstTy->getContext(), APFloat(lf));
  4123. F = ConstantFP::get(DstTy->getContext(), APFloat(rf));
  4124. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4125. return Sel;
  4126. } else if (DstTy == Builder.getInt32Ty()) {
  4127. T = Builder.getInt32(ld);
  4128. F = Builder.getInt32(rd);
  4129. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4130. return Sel;
  4131. } else if (DstTy == Builder.getInt64Ty()) {
  4132. T = Builder.getInt64(ld);
  4133. F = Builder.getInt64(rd);
  4134. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  4135. return Sel;
  4136. }
  4137. }
  4138. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(I)) {
  4139. // For integer binary operator, do the calc on lowest precision, then cast
  4140. // to dstTy.
  4141. if (I->getType()->isIntegerTy()) {
  4142. bool bSigned = DstType->isSignedIntegerType();
  4143. Value *CastResult =
  4144. CalcHLSLLiteralToLowestPrecision(Builder, BO, bSigned);
  4145. if (!CastResult)
  4146. return nullptr;
  4147. if (dyn_cast<llvm::IntegerType>(DstTy)) {
  4148. if (DstTy == CastResult->getType()) {
  4149. return CastResult;
  4150. } else {
  4151. if (bSigned)
  4152. return Builder.CreateSExtOrTrunc(CastResult, DstTy);
  4153. else
  4154. return Builder.CreateZExtOrTrunc(CastResult, DstTy);
  4155. }
  4156. } else {
  4157. if (bSrcSigned)
  4158. return Builder.CreateSIToFP(CastResult, DstTy);
  4159. else
  4160. return Builder.CreateUIToFP(CastResult, DstTy);
  4161. }
  4162. }
  4163. }
  4164. // TODO: support other opcode if need.
  4165. return nullptr;
  4166. }
  4167. }
  4168. // For case like ((float3xfloat3)mat4x4).m21 or ((float3xfloat3)mat4x4)[1], just
  4169. // treat it like mat4x4.m21 or mat4x4[1].
  4170. static Value *GetOriginMatrixOperandAndUpdateMatSize(Value *Ptr, unsigned &row,
  4171. unsigned &col) {
  4172. if (CallInst *Mat = dyn_cast<CallInst>(Ptr)) {
  4173. HLOpcodeGroup OpcodeGroup =
  4174. GetHLOpcodeGroupByName(Mat->getCalledFunction());
  4175. if (OpcodeGroup == HLOpcodeGroup::HLCast) {
  4176. HLCastOpcode castOpcode = static_cast<HLCastOpcode>(GetHLOpcode(Mat));
  4177. if (castOpcode == HLCastOpcode::DefaultCast) {
  4178. Ptr = Mat->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  4179. // Remove the cast which is useless now.
  4180. Mat->eraseFromParent();
  4181. // Update row and col.
  4182. HLMatrixType matTy =
  4183. HLMatrixType::cast(Ptr->getType()->getPointerElementType());
  4184. row = matTy.getNumRows();
  4185. col = matTy.getNumColumns();
  4186. // Don't update RetTy and DxilGeneration pass will do the right thing.
  4187. return Ptr;
  4188. }
  4189. }
  4190. }
  4191. return nullptr;
  4192. }
  4193. Value *CGMSHLSLRuntime::EmitHLSLMatrixSubscript(CodeGenFunction &CGF,
  4194. llvm::Type *RetType,
  4195. llvm::Value *Ptr,
  4196. llvm::Value *Idx,
  4197. clang::QualType Ty) {
  4198. bool isRowMajor =
  4199. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4200. unsigned opcode =
  4201. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatSubscript)
  4202. : static_cast<unsigned>(HLSubscriptOpcode::ColMatSubscript);
  4203. Value *matBase = Ptr;
  4204. DXASSERT(matBase->getType()->isPointerTy(),
  4205. "matrix subscript should return pointer");
  4206. RetType =
  4207. llvm::PointerType::get(RetType->getPointerElementType(),
  4208. matBase->getType()->getPointerAddressSpace());
  4209. unsigned row, col;
  4210. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  4211. unsigned resultCol = col;
  4212. if (Value *OriginPtr = GetOriginMatrixOperandAndUpdateMatSize(Ptr, row, col)) {
  4213. Ptr = OriginPtr;
  4214. // Update col to result col to get correct result size.
  4215. col = resultCol;
  4216. }
  4217. // Lower mat[Idx] into real idx.
  4218. SmallVector<Value *, 8> args;
  4219. args.emplace_back(Ptr);
  4220. if (isRowMajor) {
  4221. Value *cCol = ConstantInt::get(Idx->getType(), col);
  4222. Value *Base = CGF.Builder.CreateMul(cCol, Idx);
  4223. for (unsigned i = 0; i < col; i++) {
  4224. Value *c = ConstantInt::get(Idx->getType(), i);
  4225. // r * col + c
  4226. Value *matIdx = CGF.Builder.CreateAdd(Base, c);
  4227. args.emplace_back(matIdx);
  4228. }
  4229. } else {
  4230. for (unsigned i = 0; i < col; i++) {
  4231. Value *cMulRow = ConstantInt::get(Idx->getType(), i * row);
  4232. // c * row + r
  4233. Value *matIdx = CGF.Builder.CreateAdd(cMulRow, Idx);
  4234. args.emplace_back(matIdx);
  4235. }
  4236. }
  4237. Value *matSub =
  4238. EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  4239. opcode, RetType, args, TheModule);
  4240. return matSub;
  4241. }
  4242. Value *CGMSHLSLRuntime::EmitHLSLMatrixElement(CodeGenFunction &CGF,
  4243. llvm::Type *RetType,
  4244. ArrayRef<Value *> paramList,
  4245. QualType Ty) {
  4246. bool isRowMajor =
  4247. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4248. unsigned opcode =
  4249. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatElement)
  4250. : static_cast<unsigned>(HLSubscriptOpcode::ColMatElement);
  4251. Value *matBase = paramList[0];
  4252. DXASSERT(matBase->getType()->isPointerTy(),
  4253. "matrix element should return pointer");
  4254. RetType =
  4255. llvm::PointerType::get(RetType->getPointerElementType(),
  4256. matBase->getType()->getPointerAddressSpace());
  4257. Value *idx = paramList[HLOperandIndex::kMatSubscriptSubOpIdx-1];
  4258. // Lower _m00 into real idx.
  4259. // -1 to avoid opcode param which is added in EmitHLSLMatrixOperationCallImp.
  4260. Value *args[] = {paramList[HLOperandIndex::kMatSubscriptMatOpIdx - 1],
  4261. paramList[HLOperandIndex::kMatSubscriptSubOpIdx - 1]};
  4262. unsigned row, col;
  4263. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  4264. Value *Ptr = paramList[0];
  4265. if (Value *OriginPtr = GetOriginMatrixOperandAndUpdateMatSize(Ptr, row, col)) {
  4266. args[0] = OriginPtr;
  4267. }
  4268. // For all zero idx. Still all zero idx.
  4269. if (ConstantAggregateZero *zeros = dyn_cast<ConstantAggregateZero>(idx)) {
  4270. Constant *zero = zeros->getAggregateElement((unsigned)0);
  4271. std::vector<Constant *> elts(zeros->getNumElements() >> 1, zero);
  4272. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(elts);
  4273. } else {
  4274. ConstantDataSequential *elts = cast<ConstantDataSequential>(idx);
  4275. unsigned count = elts->getNumElements();
  4276. std::vector<Constant *> idxs(count >> 1);
  4277. for (unsigned i = 0; i < count; i += 2) {
  4278. unsigned rowIdx = elts->getElementAsInteger(i);
  4279. unsigned colIdx = elts->getElementAsInteger(i + 1);
  4280. unsigned matIdx = 0;
  4281. if (isRowMajor) {
  4282. matIdx = rowIdx * col + colIdx;
  4283. } else {
  4284. matIdx = colIdx * row + rowIdx;
  4285. }
  4286. idxs[i >> 1] = CGF.Builder.getInt32(matIdx);
  4287. }
  4288. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(idxs);
  4289. }
  4290. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  4291. opcode, RetType, args, TheModule);
  4292. }
  4293. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr,
  4294. QualType Ty) {
  4295. bool isRowMajor =
  4296. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4297. unsigned opcode =
  4298. isRowMajor
  4299. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad)
  4300. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad);
  4301. Value *matVal = EmitHLSLMatrixOperationCallImp(
  4302. Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  4303. Ptr->getType()->getPointerElementType(), {Ptr}, TheModule);
  4304. if (!isRowMajor) {
  4305. // ColMatLoad will return a col major matrix.
  4306. // All matrix Value should be row major.
  4307. // Cast it to row major.
  4308. matVal = EmitHLSLMatrixOperationCallImp(
  4309. Builder, HLOpcodeGroup::HLCast,
  4310. static_cast<unsigned>(HLCastOpcode::ColMatrixToRowMatrix),
  4311. matVal->getType(), {matVal}, TheModule);
  4312. }
  4313. return matVal;
  4314. }
  4315. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val,
  4316. Value *DestPtr, QualType Ty) {
  4317. bool isRowMajor =
  4318. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4319. unsigned opcode =
  4320. isRowMajor
  4321. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore)
  4322. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore);
  4323. if (!isRowMajor) {
  4324. Value *ColVal = nullptr;
  4325. // If Val is casted from col major. Just use the original col major val.
  4326. if (CallInst *CI = dyn_cast<CallInst>(Val)) {
  4327. hlsl::HLOpcodeGroup group =
  4328. hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  4329. if (group == HLOpcodeGroup::HLCast) {
  4330. HLCastOpcode castOp = static_cast<HLCastOpcode>(hlsl::GetHLOpcode(CI));
  4331. if (castOp == HLCastOpcode::ColMatrixToRowMatrix) {
  4332. ColVal = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  4333. }
  4334. }
  4335. }
  4336. if (ColVal) {
  4337. Val = ColVal;
  4338. } else {
  4339. // All matrix Value should be row major.
  4340. // ColMatStore need a col major value.
  4341. // Cast it to row major.
  4342. Val = EmitHLSLMatrixOperationCallImp(
  4343. Builder, HLOpcodeGroup::HLCast,
  4344. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  4345. Val->getType(), {Val}, TheModule);
  4346. }
  4347. }
  4348. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  4349. Val->getType(), {DestPtr, Val}, TheModule);
  4350. }
  4351. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  4352. QualType Ty) {
  4353. return EmitHLSLMatrixLoad(CGF.Builder, Ptr, Ty);
  4354. }
  4355. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val,
  4356. Value *DestPtr, QualType Ty) {
  4357. EmitHLSLMatrixStore(CGF.Builder, Val, DestPtr, Ty);
  4358. }
  4359. // Copy data from srcPtr to destPtr.
  4360. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  4361. ArrayRef<Value *> idxList, CGBuilderTy &Builder) {
  4362. if (idxList.size() > 1) {
  4363. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  4364. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  4365. }
  4366. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  4367. Builder.CreateStore(ld, DestPtr);
  4368. }
  4369. // Get Element val from SrvVal with extract value.
  4370. static Value *GetEltVal(Value *SrcVal, ArrayRef<Value*> idxList,
  4371. CGBuilderTy &Builder) {
  4372. Value *Val = SrcVal;
  4373. // Skip beginning pointer type.
  4374. for (unsigned i = 1; i < idxList.size(); i++) {
  4375. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  4376. llvm::Type *Ty = Val->getType();
  4377. if (Ty->isAggregateType()) {
  4378. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  4379. }
  4380. }
  4381. return Val;
  4382. }
  4383. // Copy srcVal to destPtr.
  4384. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  4385. ArrayRef<Value*> idxList,
  4386. CGBuilderTy &Builder) {
  4387. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  4388. Value *Val = GetEltVal(SrcVal, idxList, Builder);
  4389. Builder.CreateStore(Val, DestGEP);
  4390. }
  4391. static void SimpleCopy(Value *Dest, Value *Src,
  4392. ArrayRef<Value *> idxList,
  4393. CGBuilderTy &Builder) {
  4394. if (Src->getType()->isPointerTy())
  4395. SimplePtrCopy(Dest, Src, idxList, Builder);
  4396. else
  4397. SimpleValCopy(Dest, Src, idxList, Builder);
  4398. }
  4399. void CGMSHLSLRuntime::FlattenAggregatePtrToGepList(
  4400. CodeGenFunction &CGF, Value *Ptr, SmallVector<Value *, 4> &idxList,
  4401. clang::QualType Type, llvm::Type *Ty, SmallVector<Value *, 4> &GepList,
  4402. SmallVector<QualType, 4> &EltTyList) {
  4403. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  4404. Constant *idx = Constant::getIntegerValue(
  4405. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  4406. idxList.emplace_back(idx);
  4407. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, Type, PT->getElementType(),
  4408. GepList, EltTyList);
  4409. idxList.pop_back();
  4410. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  4411. // Use matLd/St for matrix.
  4412. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  4413. llvm::PointerType *EltPtrTy =
  4414. llvm::PointerType::get(EltTy, Ptr->getType()->getPointerAddressSpace());
  4415. QualType EltQualTy = hlsl::GetHLSLMatElementType(Type);
  4416. Value *matPtr = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4417. // Flatten matrix to elements.
  4418. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  4419. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  4420. ConstantInt *cRow = CGF.Builder.getInt32(r);
  4421. ConstantInt *cCol = CGF.Builder.getInt32(c);
  4422. Constant *CV = llvm::ConstantVector::get({cRow, cCol});
  4423. GepList.push_back(
  4424. EmitHLSLMatrixElement(CGF, EltPtrTy, {matPtr, CV}, Type));
  4425. EltTyList.push_back(EltQualTy);
  4426. }
  4427. }
  4428. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4429. if (dxilutil::IsHLSLObjectType(ST)) {
  4430. // Avoid split HLSL object.
  4431. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4432. GepList.push_back(GEP);
  4433. EltTyList.push_back(Type);
  4434. return;
  4435. }
  4436. const clang::RecordType *RT = Type->getAsStructureType();
  4437. RecordDecl *RD = RT->getDecl();
  4438. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  4439. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4440. if (CXXRD->getNumBases()) {
  4441. // Add base as field.
  4442. for (const auto &I : CXXRD->bases()) {
  4443. const CXXRecordDecl *BaseDecl =
  4444. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4445. // Skip empty struct.
  4446. if (BaseDecl->field_empty())
  4447. continue;
  4448. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4449. llvm::Type *parentType = CGF.ConvertType(parentTy);
  4450. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4451. Constant *idx = llvm::Constant::getIntegerValue(
  4452. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4453. idxList.emplace_back(idx);
  4454. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, parentTy, parentType,
  4455. GepList, EltTyList);
  4456. idxList.pop_back();
  4457. }
  4458. }
  4459. }
  4460. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4461. fieldIter != fieldEnd; ++fieldIter) {
  4462. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4463. llvm::Type *ET = ST->getElementType(i);
  4464. Constant *idx = llvm::Constant::getIntegerValue(
  4465. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4466. idxList.emplace_back(idx);
  4467. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, fieldIter->getType(), ET,
  4468. GepList, EltTyList);
  4469. idxList.pop_back();
  4470. }
  4471. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4472. llvm::Type *ET = AT->getElementType();
  4473. QualType EltType = CGF.getContext().getBaseElementType(Type);
  4474. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  4475. Constant *idx = Constant::getIntegerValue(
  4476. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4477. idxList.emplace_back(idx);
  4478. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, EltType, ET, GepList,
  4479. EltTyList);
  4480. idxList.pop_back();
  4481. }
  4482. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  4483. // Flatten vector too.
  4484. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  4485. for (uint32_t i = 0; i < VT->getNumElements(); i++) {
  4486. Constant *idx = CGF.Builder.getInt32(i);
  4487. idxList.emplace_back(idx);
  4488. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4489. GepList.push_back(GEP);
  4490. EltTyList.push_back(EltTy);
  4491. idxList.pop_back();
  4492. }
  4493. } else {
  4494. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  4495. GepList.push_back(GEP);
  4496. EltTyList.push_back(Type);
  4497. }
  4498. }
  4499. void CGMSHLSLRuntime::LoadElements(CodeGenFunction &CGF,
  4500. ArrayRef<Value *> Ptrs, ArrayRef<QualType> QualTys,
  4501. SmallVector<Value *, 4> &Vals) {
  4502. for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
  4503. Value *Ptr = Ptrs[i];
  4504. llvm::Type *Ty = Ptr->getType()->getPointerElementType();
  4505. DXASSERT_LOCALVAR(Ty, Ty->isIntegerTy() || Ty->isFloatingPointTy(), "Expected only element types.");
  4506. Value *Val = CGF.Builder.CreateLoad(Ptr);
  4507. Val = CGF.EmitFromMemory(Val, QualTys[i]);
  4508. Vals.push_back(Val);
  4509. }
  4510. }
  4511. void CGMSHLSLRuntime::ConvertAndStoreElements(CodeGenFunction &CGF,
  4512. ArrayRef<Value *> SrcVals, ArrayRef<QualType> SrcQualTys,
  4513. ArrayRef<Value *> DstPtrs, ArrayRef<QualType> DstQualTys) {
  4514. for (size_t i = 0, e = DstPtrs.size(); i < e; i++) {
  4515. Value *DstPtr = DstPtrs[i];
  4516. QualType DstQualTy = DstQualTys[i];
  4517. Value *SrcVal = SrcVals[i];
  4518. QualType SrcQualTy = SrcQualTys[i];
  4519. DXASSERT(SrcVal->getType()->isIntegerTy() || SrcVal->getType()->isFloatingPointTy(),
  4520. "Expected only element types.");
  4521. llvm::Value *Result = ConvertScalarOrVector(CGF, SrcVal, SrcQualTy, DstQualTy);
  4522. Result = CGF.EmitToMemory(Result, DstQualTy);
  4523. CGF.Builder.CreateStore(Result, DstPtr);
  4524. }
  4525. }
  4526. static bool AreMatrixArrayOrientationMatching(ASTContext& Context,
  4527. HLModule &Module, QualType LhsTy, QualType RhsTy) {
  4528. while (const clang::ArrayType *LhsArrayTy = Context.getAsArrayType(LhsTy)) {
  4529. LhsTy = LhsArrayTy->getElementType();
  4530. RhsTy = Context.getAsArrayType(RhsTy)->getElementType();
  4531. }
  4532. bool LhsRowMajor, RhsRowMajor;
  4533. LhsRowMajor = RhsRowMajor = Module.GetHLOptions().bDefaultRowMajor;
  4534. HasHLSLMatOrientation(LhsTy, &LhsRowMajor);
  4535. HasHLSLMatOrientation(RhsTy, &RhsRowMajor);
  4536. return LhsRowMajor == RhsRowMajor;
  4537. }
  4538. static llvm::Value *CreateInBoundsGEPIfNeeded(llvm::Value *Ptr, ArrayRef<Value*> IdxList, CGBuilderTy &Builder) {
  4539. DXASSERT(IdxList.size() > 0, "Invalid empty GEP index list");
  4540. // If the GEP list is a single zero, it's a no-op, so save us the trouble.
  4541. if (IdxList.size() == 1) {
  4542. if (ConstantInt *FirstIdx = dyn_cast<ConstantInt>(IdxList[0])) {
  4543. if (FirstIdx->isZero()) return Ptr;
  4544. }
  4545. }
  4546. return Builder.CreateInBoundsGEP(Ptr, IdxList);
  4547. }
  4548. // Copy data from SrcPtr to DestPtr.
  4549. // For matrix, use MatLoad/MatStore.
  4550. // For matrix array, EmitHLSLAggregateCopy on each element.
  4551. // For struct or array, use memcpy.
  4552. // Other just load/store.
  4553. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(
  4554. CodeGenFunction &CGF, llvm::Value *SrcPtr, llvm::Value *DestPtr,
  4555. SmallVector<Value *, 4> &idxList, clang::QualType SrcType,
  4556. clang::QualType DestType, llvm::Type *Ty) {
  4557. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  4558. Constant *idx = Constant::getIntegerValue(
  4559. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  4560. idxList.emplace_back(idx);
  4561. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, SrcType, DestType,
  4562. PT->getElementType());
  4563. idxList.pop_back();
  4564. } else if (HLMatrixType::isa(Ty)) {
  4565. // Use matLd/St for matrix.
  4566. Value *SrcMatPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4567. Value *DestMatPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4568. Value *ldMat = EmitHLSLMatrixLoad(CGF, SrcMatPtr, SrcType);
  4569. EmitHLSLMatrixStore(CGF, ldMat, DestMatPtr, DestType);
  4570. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4571. if (dxilutil::IsHLSLObjectType(ST)) {
  4572. // Avoid split HLSL object.
  4573. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  4574. return;
  4575. }
  4576. Value *SrcStructPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4577. Value *DestStructPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4578. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(ST);
  4579. // Memcpy struct.
  4580. CGF.Builder.CreateMemCpy(DestStructPtr, SrcStructPtr, size, 1);
  4581. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4582. if (!HLMatrixType::isMatrixArray(Ty)
  4583. || AreMatrixArrayOrientationMatching(CGF.getContext(), *m_pHLModule, SrcType, DestType)) {
  4584. Value *SrcArrayPtr = CreateInBoundsGEPIfNeeded(SrcPtr, idxList, CGF.Builder);
  4585. Value *DestArrayPtr = CreateInBoundsGEPIfNeeded(DestPtr, idxList, CGF.Builder);
  4586. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(AT);
  4587. // Memcpy non-matrix array.
  4588. CGF.Builder.CreateMemCpy(DestArrayPtr, SrcArrayPtr, size, 1);
  4589. } else {
  4590. // Copy matrix arrays elementwise if orientation changes are needed.
  4591. llvm::Type *ET = AT->getElementType();
  4592. QualType EltDestType = CGF.getContext().getBaseElementType(DestType);
  4593. QualType EltSrcType = CGF.getContext().getBaseElementType(SrcType);
  4594. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  4595. Constant *idx = Constant::getIntegerValue(
  4596. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4597. idxList.emplace_back(idx);
  4598. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, EltSrcType,
  4599. EltDestType, ET);
  4600. idxList.pop_back();
  4601. }
  4602. }
  4603. } else {
  4604. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  4605. }
  4606. }
  4607. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  4608. llvm::Value *DestPtr,
  4609. clang::QualType Ty) {
  4610. SmallVector<Value *, 4> idxList;
  4611. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Ty, Ty, SrcPtr->getType());
  4612. }
  4613. // Make sure all element type of struct is same type.
  4614. static bool IsStructWithSameElementType(llvm::StructType *ST, llvm::Type *Ty) {
  4615. for (llvm::Type *EltTy : ST->elements()) {
  4616. if (StructType *EltSt = dyn_cast<StructType>(EltTy)) {
  4617. if (!IsStructWithSameElementType(EltSt, Ty))
  4618. return false;
  4619. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(EltTy)) {
  4620. llvm::Type *ArrayEltTy = dxilutil::GetArrayEltTy(AT);
  4621. if (ArrayEltTy == Ty) {
  4622. continue;
  4623. } else if (StructType *EltSt = dyn_cast<StructType>(EltTy)) {
  4624. if (!IsStructWithSameElementType(EltSt, Ty))
  4625. return false;
  4626. } else {
  4627. return false;
  4628. }
  4629. } else if (EltTy != Ty)
  4630. return false;
  4631. }
  4632. return true;
  4633. }
  4634. // To memcpy, need element type match.
  4635. // For struct type, the layout should match in cbuffer layout.
  4636. // struct { float2 x; float3 y; } will not match struct { float3 x; float2 y; }.
  4637. // struct { float2 x; float3 y; } will not match array of float.
  4638. static bool IsTypeMatchForMemcpy(llvm::Type *SrcTy, llvm::Type *DestTy) {
  4639. llvm::Type *SrcEltTy = dxilutil::GetArrayEltTy(SrcTy);
  4640. llvm::Type *DestEltTy = dxilutil::GetArrayEltTy(DestTy);
  4641. if (SrcEltTy == DestEltTy)
  4642. return true;
  4643. llvm::StructType *SrcST = dyn_cast<llvm::StructType>(SrcEltTy);
  4644. llvm::StructType *DestST = dyn_cast<llvm::StructType>(DestEltTy);
  4645. if (SrcST && DestST) {
  4646. // Only allow identical struct.
  4647. return SrcST->isLayoutIdentical(DestST);
  4648. } else if (!SrcST && !DestST) {
  4649. // For basic type, if one is array, one is not array, layout is different.
  4650. // If both array, type mismatch. If both basic, copy should be fine.
  4651. // So all return false.
  4652. return false;
  4653. } else {
  4654. // One struct, one basic type.
  4655. // Make sure all struct element match the basic type and basic type is
  4656. // vector4.
  4657. llvm::StructType *ST = SrcST ? SrcST : DestST;
  4658. llvm::Type *Ty = SrcST ? DestEltTy : SrcEltTy;
  4659. if (!Ty->isVectorTy())
  4660. return false;
  4661. if (Ty->getVectorNumElements() != 4)
  4662. return false;
  4663. return IsStructWithSameElementType(ST, Ty);
  4664. }
  4665. }
  4666. void CGMSHLSLRuntime::EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  4667. clang::QualType SrcTy,
  4668. llvm::Value *DestPtr,
  4669. clang::QualType DestTy) {
  4670. llvm::Type *SrcPtrTy = SrcPtr->getType()->getPointerElementType();
  4671. llvm::Type *DestPtrTy = DestPtr->getType()->getPointerElementType();
  4672. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  4673. if (SrcPtrTy == DestPtrTy) {
  4674. bool bMatArrayRotate = false;
  4675. if (HLMatrixType::isMatrixArrayPtr(SrcPtr->getType())) {
  4676. QualType SrcEltTy = GetArrayEltType(CGM.getContext(), SrcTy);
  4677. QualType DestEltTy = GetArrayEltType(CGM.getContext(), DestTy);
  4678. if (GetMatrixMajor(SrcEltTy, bDefaultRowMajor) !=
  4679. GetMatrixMajor(DestEltTy, bDefaultRowMajor)) {
  4680. bMatArrayRotate = true;
  4681. }
  4682. }
  4683. if (!bMatArrayRotate) {
  4684. // Memcpy if type is match.
  4685. unsigned size = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  4686. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, size, 1);
  4687. return;
  4688. }
  4689. } else if (dxilutil::IsHLSLResourceDescType(SrcPtrTy) &&
  4690. dxilutil::IsHLSLResourceType(DestPtrTy)) {
  4691. // Cast resource desc to resource.
  4692. Value *CastPtr = CGF.Builder.CreatePointerCast(SrcPtr, DestPtr->getType());
  4693. // Load resource.
  4694. Value *V = CGF.Builder.CreateLoad(CastPtr);
  4695. // Store to resource ptr.
  4696. CGF.Builder.CreateStore(V, DestPtr);
  4697. return;
  4698. } else if (dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(SrcPtrTy)) &&
  4699. dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(DestPtrTy))) {
  4700. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  4701. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  4702. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::max(sizeSrc, sizeDest), 1);
  4703. return;
  4704. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(DestPtr)) {
  4705. if (GV->isInternalLinkage(GV->getLinkage()) &&
  4706. IsTypeMatchForMemcpy(SrcPtrTy, DestPtrTy)) {
  4707. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  4708. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  4709. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::min(sizeSrc, sizeDest), 1);
  4710. return;
  4711. }
  4712. }
  4713. // It is possible to implement EmitHLSLAggregateCopy, EmitHLSLAggregateStore
  4714. // the same way. But split value to scalar will generate many instruction when
  4715. // src type is same as dest type.
  4716. SmallVector<Value *, 4> GEPIdxStack;
  4717. SmallVector<Value *, 4> SrcPtrs;
  4718. SmallVector<QualType, 4> SrcQualTys;
  4719. FlattenAggregatePtrToGepList(CGF, SrcPtr, GEPIdxStack, SrcTy, SrcPtr->getType(),
  4720. SrcPtrs, SrcQualTys);
  4721. SmallVector<Value *, 4> SrcVals;
  4722. LoadElements(CGF, SrcPtrs, SrcQualTys, SrcVals);
  4723. GEPIdxStack.clear();
  4724. SmallVector<Value *, 4> DstPtrs;
  4725. SmallVector<QualType, 4> DstQualTys;
  4726. FlattenAggregatePtrToGepList(CGF, DestPtr, GEPIdxStack, DestTy,
  4727. DestPtr->getType(), DstPtrs, DstQualTys);
  4728. ConvertAndStoreElements(CGF, SrcVals, SrcQualTys, DstPtrs, DstQualTys);
  4729. }
  4730. void CGMSHLSLRuntime::EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *SrcVal,
  4731. llvm::Value *DestPtr,
  4732. clang::QualType Ty) {
  4733. DXASSERT(0, "aggregate return type will use SRet, no aggregate store should exist");
  4734. }
  4735. // Either copies a scalar to a scalar, a scalar to a vector, or splats a scalar to a vector
  4736. static void SimpleFlatValCopy(CodeGenFunction &CGF,
  4737. Value *SrcVal, QualType SrcQualTy, Value *DstPtr, QualType DstQualTy) {
  4738. DXASSERT(SrcVal->getType() == CGF.ConvertType(SrcQualTy), "QualType/Type mismatch!");
  4739. llvm::Type *DstTy = DstPtr->getType()->getPointerElementType();
  4740. DXASSERT(DstTy == CGF.ConvertTypeForMem(DstQualTy), "QualType/Type mismatch!");
  4741. llvm::VectorType *DstVecTy = dyn_cast<llvm::VectorType>(DstTy);
  4742. QualType DstScalarQualTy = DstQualTy;
  4743. if (DstVecTy) {
  4744. DstScalarQualTy = hlsl::GetHLSLVecElementType(DstQualTy);
  4745. }
  4746. Value *ResultScalar = ConvertScalarOrVector(CGF, SrcVal, SrcQualTy, DstScalarQualTy);
  4747. ResultScalar = CGF.EmitToMemory(ResultScalar, DstScalarQualTy);
  4748. if (DstVecTy) {
  4749. llvm::VectorType *DstScalarVecTy = llvm::VectorType::get(ResultScalar->getType(), 1);
  4750. Value *ResultScalarVec = CGF.Builder.CreateInsertElement(
  4751. UndefValue::get(DstScalarVecTy), ResultScalar, (uint64_t)0);
  4752. std::vector<int> ShufIdx(DstVecTy->getNumElements(), 0);
  4753. Value *ResultVec = CGF.Builder.CreateShuffleVector(ResultScalarVec, ResultScalarVec, ShufIdx);
  4754. CGF.Builder.CreateStore(ResultVec, DstPtr);
  4755. } else
  4756. CGF.Builder.CreateStore(ResultScalar, DstPtr);
  4757. }
  4758. void CGMSHLSLRuntime::EmitHLSLSplat(
  4759. CodeGenFunction &CGF, Value *SrcVal, llvm::Value *DestPtr,
  4760. SmallVector<Value *, 4> &idxList, QualType Type, QualType SrcType,
  4761. llvm::Type *Ty) {
  4762. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  4763. idxList.emplace_back(CGF.Builder.getInt32(0));
  4764. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, Type,
  4765. SrcType, PT->getElementType());
  4766. idxList.pop_back();
  4767. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  4768. // Use matLd/St for matrix.
  4769. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  4770. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  4771. llvm::VectorType *VT1 = llvm::VectorType::get(EltTy, 1);
  4772. SrcVal = ConvertScalarOrVector(CGF, SrcVal, SrcType, hlsl::GetHLSLMatElementType(Type));
  4773. // Splat the value
  4774. Value *V1 = CGF.Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal,
  4775. (uint64_t)0);
  4776. std::vector<int> shufIdx(MatTy.getNumElements(), 0);
  4777. Value *VecMat = CGF.Builder.CreateShuffleVector(V1, V1, shufIdx);
  4778. Value *MatInit = EmitHLSLMatrixOperationCallImp(
  4779. CGF.Builder, HLOpcodeGroup::HLInit, 0, Ty, {VecMat}, TheModule);
  4780. EmitHLSLMatrixStore(CGF, MatInit, dstGEP, Type);
  4781. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4782. DXASSERT(!dxilutil::IsHLSLObjectType(ST), "cannot cast to hlsl object, Sema should reject");
  4783. const clang::RecordType *RT = Type->getAsStructureType();
  4784. RecordDecl *RD = RT->getDecl();
  4785. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  4786. // Take care base.
  4787. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4788. if (CXXRD->getNumBases()) {
  4789. for (const auto &I : CXXRD->bases()) {
  4790. const CXXRecordDecl *BaseDecl =
  4791. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4792. if (BaseDecl->field_empty())
  4793. continue;
  4794. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4795. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4796. llvm::Type *ET = ST->getElementType(i);
  4797. Constant *idx = llvm::Constant::getIntegerValue(
  4798. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4799. idxList.emplace_back(idx);
  4800. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, parentTy, SrcType, ET);
  4801. idxList.pop_back();
  4802. }
  4803. }
  4804. }
  4805. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4806. fieldIter != fieldEnd; ++fieldIter) {
  4807. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4808. llvm::Type *ET = ST->getElementType(i);
  4809. Constant *idx = llvm::Constant::getIntegerValue(
  4810. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4811. idxList.emplace_back(idx);
  4812. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, fieldIter->getType(), SrcType, ET);
  4813. idxList.pop_back();
  4814. }
  4815. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  4816. llvm::Type *ET = AT->getElementType();
  4817. QualType EltType = CGF.getContext().getBaseElementType(Type);
  4818. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  4819. Constant *idx = Constant::getIntegerValue(
  4820. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  4821. idxList.emplace_back(idx);
  4822. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, EltType, SrcType, ET);
  4823. idxList.pop_back();
  4824. }
  4825. } else {
  4826. DestPtr = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  4827. SimpleFlatValCopy(CGF, SrcVal, SrcType, DestPtr, Type);
  4828. }
  4829. }
  4830. void CGMSHLSLRuntime::EmitHLSLFlatConversion(CodeGenFunction &CGF,
  4831. Value *Val,
  4832. Value *DestPtr,
  4833. QualType Ty,
  4834. QualType SrcTy) {
  4835. SmallVector<Value *, 4> SrcVals;
  4836. SmallVector<QualType, 4> SrcQualTys;
  4837. FlattenValToInitList(CGF, SrcVals, SrcQualTys, SrcTy, Val);
  4838. if (SrcVals.size() == 1) {
  4839. // Perform a splat
  4840. SmallVector<Value *, 4> GEPIdxStack;
  4841. GEPIdxStack.emplace_back(CGF.Builder.getInt32(0)); // Add first 0 for DestPtr.
  4842. EmitHLSLSplat(
  4843. CGF, SrcVals[0], DestPtr, GEPIdxStack, Ty, SrcQualTys[0],
  4844. DestPtr->getType()->getPointerElementType());
  4845. }
  4846. else {
  4847. SmallVector<Value *, 4> GEPIdxStack;
  4848. SmallVector<Value *, 4> DstPtrs;
  4849. SmallVector<QualType, 4> DstQualTys;
  4850. FlattenAggregatePtrToGepList(CGF, DestPtr, GEPIdxStack, Ty, DestPtr->getType(), DstPtrs, DstQualTys);
  4851. ConvertAndStoreElements(CGF, SrcVals, SrcQualTys, DstPtrs, DstQualTys);
  4852. }
  4853. }
  4854. void CGMSHLSLRuntime::EmitHLSLRootSignature(CodeGenFunction &CGF,
  4855. HLSLRootSignatureAttr *RSA,
  4856. Function *Fn) {
  4857. // Only parse root signature for entry function.
  4858. if (Fn != Entry.Func)
  4859. return;
  4860. StringRef StrRef = RSA->getSignatureName();
  4861. DiagnosticsEngine &Diags = CGF.getContext().getDiagnostics();
  4862. SourceLocation SLoc = RSA->getLocation();
  4863. RootSignatureHandle RootSigHandle;
  4864. clang::CompileRootSignature(StrRef, Diags, SLoc, rootSigVer, DxilRootSignatureCompilationFlags::GlobalRootSignature, &RootSigHandle);
  4865. if (!RootSigHandle.IsEmpty()) {
  4866. RootSigHandle.EnsureSerializedAvailable();
  4867. m_pHLModule->SetSerializedRootSignature(RootSigHandle.GetSerializedBytes(),
  4868. RootSigHandle.GetSerializedSize());
  4869. }
  4870. }
  4871. void CGMSHLSLRuntime::EmitHLSLOutParamConversionInit(
  4872. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  4873. llvm::SmallVector<LValue, 8> &castArgList,
  4874. llvm::SmallVector<const Stmt *, 8> &argList,
  4875. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap) {
  4876. // Special case: skip first argument of CXXOperatorCall (it is "this").
  4877. unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(E) ? 1 : 0;
  4878. for (uint32_t i = 0; i < FD->getNumParams(); i++) {
  4879. const ParmVarDecl *Param = FD->getParamDecl(i);
  4880. const Expr *Arg = E->getArg(i+ArgsToSkip);
  4881. QualType ParamTy = Param->getType().getNonReferenceType();
  4882. bool isObject = dxilutil::IsHLSLObjectType(CGF.ConvertTypeForMem(ParamTy));
  4883. bool isAggregateType = !isObject &&
  4884. (ParamTy->isArrayType() || ParamTy->isRecordType()) &&
  4885. !hlsl::IsHLSLVecMatType(ParamTy);
  4886. bool EmitRValueAgg = false;
  4887. bool RValOnRef = false;
  4888. if (!Param->isModifierOut()) {
  4889. if (!isAggregateType && !isObject) {
  4890. if (Arg->isRValue() && Param->getType()->isReferenceType()) {
  4891. // RValue on a reference type.
  4892. if (const CStyleCastExpr *cCast = dyn_cast<CStyleCastExpr>(Arg)) {
  4893. // TODO: Evolving this to warn then fail in future language versions.
  4894. // Allow special case like cast uint to uint for back-compat.
  4895. if (cCast->getCastKind() == CastKind::CK_NoOp) {
  4896. if (const ImplicitCastExpr *cast =
  4897. dyn_cast<ImplicitCastExpr>(cCast->getSubExpr())) {
  4898. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  4899. // update the arg
  4900. argList[i] = cast->getSubExpr();
  4901. continue;
  4902. }
  4903. }
  4904. }
  4905. }
  4906. // EmitLValue will report error.
  4907. // Mark RValOnRef to create tmpArg for it.
  4908. RValOnRef = true;
  4909. } else {
  4910. continue;
  4911. }
  4912. } else if (isAggregateType) {
  4913. // aggregate in-only - emit RValue, unless LValueToRValue cast
  4914. EmitRValueAgg = true;
  4915. if (const ImplicitCastExpr *cast =
  4916. dyn_cast<ImplicitCastExpr>(Arg)) {
  4917. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  4918. EmitRValueAgg = false;
  4919. }
  4920. }
  4921. } else {
  4922. // Must be object
  4923. DXASSERT(isObject, "otherwise, flow condition changed, breaking assumption");
  4924. // in-only objects should be skipped to preserve previous behavior.
  4925. continue;
  4926. }
  4927. }
  4928. // Skip unbounded array, since we cannot preserve copy-in copy-out
  4929. // semantics for these.
  4930. if (ParamTy->isIncompleteArrayType()) {
  4931. continue;
  4932. }
  4933. if (!Param->isModifierOut() && !RValOnRef) {
  4934. // No need to copy arg to in-only param for hlsl intrinsic.
  4935. if (const FunctionDecl *Callee = E->getDirectCallee()) {
  4936. if (Callee->hasAttr<HLSLIntrinsicAttr>())
  4937. continue;
  4938. }
  4939. }
  4940. // get original arg
  4941. // FIXME: This will not emit in correct argument order with the other
  4942. // arguments. This should be integrated into
  4943. // CodeGenFunction::EmitCallArg if possible.
  4944. RValue argRV; // emit this if aggregate arg on in-only param
  4945. LValue argLV; // otherwise, we may emit this
  4946. llvm::Value *argAddr = nullptr;
  4947. QualType argType = Arg->getType();
  4948. CharUnits argAlignment;
  4949. if (EmitRValueAgg) {
  4950. argRV = CGF.EmitAnyExprToTemp(Arg);
  4951. argAddr = argRV.getAggregateAddr(); // must be alloca
  4952. argAlignment = CharUnits::fromQuantity(cast<AllocaInst>(argAddr)->getAlignment());
  4953. argLV = LValue::MakeAddr(argAddr, ParamTy, argAlignment, CGF.getContext());
  4954. } else {
  4955. argLV = CGF.EmitLValue(Arg);
  4956. if (argLV.isSimple())
  4957. argAddr = argLV.getAddress();
  4958. // TODO: enable avoid copy for lib profile.
  4959. if (!m_bIsLib) {
  4960. // When there's argument need to lower like buffer/cbuffer load, need to
  4961. // copy to let the lower not happen on argument when calle is noinline
  4962. // or extern functions. Will do it in HLLegalizeParameter after known
  4963. // which functions are extern but before inline.
  4964. bool bConstGlobal = false;
  4965. Value *Ptr = argAddr;
  4966. while (GEPOperator *GEP = dyn_cast_or_null<GEPOperator>(Ptr)) {
  4967. Ptr = GEP->getPointerOperand();
  4968. }
  4969. if (GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(Ptr)) {
  4970. bConstGlobal = m_ConstVarAnnotationMap.count(GV) | GV->isConstant();
  4971. }
  4972. // Skip copy-in copy-out when safe.
  4973. // The unsafe case will be global variable alias with parameter.
  4974. // Then global variable is updated in the function, the parameter will
  4975. // be updated silently. For non global variable or constant global
  4976. // variable, it should be safe.
  4977. if (argAddr &&
  4978. (isa<AllocaInst>(Ptr) || isa<Argument>(Ptr) || bConstGlobal)) {
  4979. llvm::Type *ToTy = CGF.ConvertType(ParamTy.getNonReferenceType());
  4980. if (argAddr->getType()->getPointerElementType() == ToTy &&
  4981. // Check clang Type for case like int cast to unsigned.
  4982. ParamTy.getNonReferenceType().getCanonicalType().getTypePtr() ==
  4983. Arg->getType().getCanonicalType().getTypePtr())
  4984. continue;
  4985. }
  4986. }
  4987. argType = argLV.getType(); // TBD: Can this be different than Arg->getType()?
  4988. argAlignment = argLV.getAlignment();
  4989. }
  4990. // After emit Arg, we must update the argList[i],
  4991. // otherwise we get double emit of the expression.
  4992. // create temp Var
  4993. VarDecl *tmpArg =
  4994. VarDecl::Create(CGF.getContext(), const_cast<FunctionDecl *>(FD),
  4995. SourceLocation(), SourceLocation(),
  4996. /*IdentifierInfo*/ nullptr, ParamTy,
  4997. CGF.getContext().getTrivialTypeSourceInfo(ParamTy),
  4998. StorageClass::SC_Auto);
  4999. // Aggregate type will be indirect param convert to pointer type.
  5000. // So don't update to ReferenceType, use RValue for it.
  5001. const DeclRefExpr *tmpRef = DeclRefExpr::Create(
  5002. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), tmpArg,
  5003. /*enclosing*/ false, tmpArg->getLocation(), ParamTy,
  5004. (isAggregateType || isObject) ? VK_RValue : VK_LValue);
  5005. // must update the arg, since we did emit Arg, else we get double emit.
  5006. argList[i] = tmpRef;
  5007. // create alloc for the tmp arg
  5008. Value *tmpArgAddr = nullptr;
  5009. BasicBlock *InsertBlock = CGF.Builder.GetInsertBlock();
  5010. Function *F = InsertBlock->getParent();
  5011. // Make sure the alloca is in entry block to stop inline create stacksave.
  5012. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  5013. tmpArgAddr = AllocaBuilder.CreateAlloca(CGF.ConvertTypeForMem(ParamTy));
  5014. // add it to local decl map
  5015. TmpArgMap(tmpArg, tmpArgAddr);
  5016. LValue tmpLV = LValue::MakeAddr(tmpArgAddr, ParamTy, argAlignment,
  5017. CGF.getContext());
  5018. // save for cast after call
  5019. if (Param->isModifierOut()) {
  5020. castArgList.emplace_back(tmpLV);
  5021. castArgList.emplace_back(argLV);
  5022. }
  5023. // cast before the call
  5024. if (Param->isModifierIn() &&
  5025. // Don't copy object
  5026. !isObject) {
  5027. QualType ArgTy = Arg->getType();
  5028. Value *outVal = nullptr;
  5029. if (!isAggregateType) {
  5030. if (!IsHLSLMatType(ParamTy)) {
  5031. RValue outRVal = CGF.EmitLoadOfLValue(argLV, SourceLocation());
  5032. outVal = outRVal.getScalarVal();
  5033. } else {
  5034. DXASSERT(argAddr, "should be RV or simple LV");
  5035. outVal = EmitHLSLMatrixLoad(CGF, argAddr, ArgTy);
  5036. }
  5037. llvm::Type *ToTy = tmpArgAddr->getType()->getPointerElementType();
  5038. if (HLMatrixType::isa(ToTy)) {
  5039. Value *castVal = CGF.Builder.CreateBitCast(outVal, ToTy);
  5040. EmitHLSLMatrixStore(CGF, castVal, tmpArgAddr, ParamTy);
  5041. }
  5042. else {
  5043. Value *castVal = ConvertScalarOrVector(CGF, outVal, argType, ParamTy);
  5044. castVal = CGF.EmitToMemory(castVal, ParamTy);
  5045. CGF.Builder.CreateStore(castVal, tmpArgAddr);
  5046. }
  5047. } else {
  5048. DXASSERT(argAddr, "should be RV or simple LV");
  5049. SmallVector<Value *, 4> idxList;
  5050. EmitHLSLAggregateCopy(CGF, argAddr, tmpArgAddr,
  5051. idxList, ArgTy, ParamTy,
  5052. argAddr->getType());
  5053. }
  5054. }
  5055. }
  5056. }
  5057. void CGMSHLSLRuntime::EmitHLSLOutParamConversionCopyBack(
  5058. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) {
  5059. for (uint32_t i = 0; i < castArgList.size(); i += 2) {
  5060. // cast after the call
  5061. LValue tmpLV = castArgList[i];
  5062. LValue argLV = castArgList[i + 1];
  5063. QualType ArgTy = argLV.getType().getNonReferenceType();
  5064. QualType ParamTy = tmpLV.getType().getNonReferenceType();
  5065. Value *tmpArgAddr = tmpLV.getAddress();
  5066. Value *outVal = nullptr;
  5067. bool isAggregateTy = hlsl::IsHLSLAggregateType(ArgTy);
  5068. bool isObject = dxilutil::IsHLSLObjectType(
  5069. tmpArgAddr->getType()->getPointerElementType());
  5070. if (!isObject) {
  5071. if (!isAggregateTy) {
  5072. if (!IsHLSLMatType(ParamTy))
  5073. outVal = CGF.Builder.CreateLoad(tmpArgAddr);
  5074. else
  5075. outVal = EmitHLSLMatrixLoad(CGF, tmpArgAddr, ParamTy);
  5076. outVal = CGF.EmitFromMemory(outVal, ParamTy);
  5077. llvm::Type *ToTy = CGF.ConvertType(ArgTy);
  5078. llvm::Type *FromTy = outVal->getType();
  5079. Value *castVal = outVal;
  5080. if (ToTy == FromTy) {
  5081. // Don't need cast.
  5082. } else if (ToTy->getScalarType() == FromTy->getScalarType()) {
  5083. if (ToTy->getScalarType() == ToTy) {
  5084. DXASSERT(FromTy->isVectorTy() &&
  5085. FromTy->getVectorNumElements() == 1,
  5086. "must be vector of 1 element");
  5087. castVal = CGF.Builder.CreateExtractElement(outVal, (uint64_t)0);
  5088. } else {
  5089. DXASSERT(!FromTy->isVectorTy(), "must be scalar type");
  5090. DXASSERT(ToTy->isVectorTy() && ToTy->getVectorNumElements() == 1,
  5091. "must be vector of 1 element");
  5092. castVal = UndefValue::get(ToTy);
  5093. castVal =
  5094. CGF.Builder.CreateInsertElement(castVal, outVal, (uint64_t)0);
  5095. }
  5096. } else {
  5097. castVal = ConvertScalarOrVector(CGF,
  5098. outVal, tmpLV.getType(), argLV.getType());
  5099. }
  5100. if (!HLMatrixType::isa(ToTy))
  5101. CGF.EmitStoreThroughLValue(RValue::get(castVal), argLV);
  5102. else {
  5103. Value *destPtr = argLV.getAddress();
  5104. EmitHLSLMatrixStore(CGF, castVal, destPtr, ArgTy);
  5105. }
  5106. } else {
  5107. SmallVector<Value *, 4> idxList;
  5108. EmitHLSLAggregateCopy(CGF, tmpLV.getAddress(), argLV.getAddress(),
  5109. idxList, ParamTy, ArgTy,
  5110. argLV.getAddress()->getType());
  5111. }
  5112. } else
  5113. tmpArgAddr->replaceAllUsesWith(argLV.getAddress());
  5114. }
  5115. }
  5116. CGHLSLRuntime *CodeGen::CreateMSHLSLRuntime(CodeGenModule &CGM) {
  5117. return new CGMSHLSLRuntime(CGM);
  5118. }