Driver.cpp 223 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878
  1. //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Driver/Driver.h"
  9. #include "ToolChains/AIX.h"
  10. #include "ToolChains/AMDGPU.h"
  11. #include "ToolChains/AMDGPUOpenMP.h"
  12. #include "ToolChains/AVR.h"
  13. #include "ToolChains/Ananas.h"
  14. #include "ToolChains/BareMetal.h"
  15. #include "ToolChains/Clang.h"
  16. #include "ToolChains/CloudABI.h"
  17. #include "ToolChains/Contiki.h"
  18. #include "ToolChains/CrossWindows.h"
  19. #include "ToolChains/Cuda.h"
  20. #include "ToolChains/Darwin.h"
  21. #include "ToolChains/DragonFly.h"
  22. #include "ToolChains/FreeBSD.h"
  23. #include "ToolChains/Fuchsia.h"
  24. #include "ToolChains/Gnu.h"
  25. #include "ToolChains/HIPAMD.h"
  26. #include "ToolChains/HIPSPV.h"
  27. #include "ToolChains/Haiku.h"
  28. #include "ToolChains/Hexagon.h"
  29. #include "ToolChains/Hurd.h"
  30. #include "ToolChains/Lanai.h"
  31. #include "ToolChains/Linux.h"
  32. #include "ToolChains/MSP430.h"
  33. #include "ToolChains/MSVC.h"
  34. #include "ToolChains/MinGW.h"
  35. #include "ToolChains/Minix.h"
  36. #include "ToolChains/MipsLinux.h"
  37. #include "ToolChains/Myriad.h"
  38. #include "ToolChains/NaCl.h"
  39. #include "ToolChains/NetBSD.h"
  40. #include "ToolChains/OpenBSD.h"
  41. #include "ToolChains/PPCFreeBSD.h"
  42. #include "ToolChains/PPCLinux.h"
  43. #include "ToolChains/PS4CPU.h"
  44. #include "ToolChains/RISCVToolchain.h"
  45. #include "ToolChains/SPIRV.h"
  46. #include "ToolChains/Solaris.h"
  47. #include "ToolChains/TCE.h"
  48. #include "ToolChains/VEToolchain.h"
  49. #include "ToolChains/WebAssembly.h"
  50. #include "ToolChains/XCore.h"
  51. #include "ToolChains/ZOS.h"
  52. #include "clang/Basic/TargetID.h"
  53. #include "clang/Basic/Version.h"
  54. #include "clang/Config/config.h"
  55. #include "clang/Driver/Action.h"
  56. #include "clang/Driver/Compilation.h"
  57. #include "clang/Driver/DriverDiagnostic.h"
  58. #include "clang/Driver/InputInfo.h"
  59. #include "clang/Driver/Job.h"
  60. #include "clang/Driver/Options.h"
  61. #include "clang/Driver/SanitizerArgs.h"
  62. #include "clang/Driver/Tool.h"
  63. #include "clang/Driver/ToolChain.h"
  64. #include "clang/Driver/Types.h"
  65. #include "llvm/ADT/ArrayRef.h"
  66. #include "llvm/ADT/STLExtras.h"
  67. #include "llvm/ADT/SmallSet.h"
  68. #include "llvm/ADT/StringExtras.h"
  69. #include "llvm/ADT/StringRef.h"
  70. #include "llvm/ADT/StringSet.h"
  71. #include "llvm/ADT/StringSwitch.h"
  72. #include "llvm/Config/llvm-config.h"
  73. #include "llvm/MC/TargetRegistry.h"
  74. #include "llvm/Option/Arg.h"
  75. #include "llvm/Option/ArgList.h"
  76. #include "llvm/Option/OptSpecifier.h"
  77. #include "llvm/Option/OptTable.h"
  78. #include "llvm/Option/Option.h"
  79. #include "llvm/Support/CommandLine.h"
  80. #include "llvm/Support/ErrorHandling.h"
  81. #include "llvm/Support/ExitCodes.h"
  82. #include "llvm/Support/FileSystem.h"
  83. #include "llvm/Support/FormatVariadic.h"
  84. #include "llvm/Support/Host.h"
  85. #include "llvm/Support/MD5.h"
  86. #include "llvm/Support/Path.h"
  87. #include "llvm/Support/PrettyStackTrace.h"
  88. #include "llvm/Support/Process.h"
  89. #include "llvm/Support/Program.h"
  90. #include "llvm/Support/StringSaver.h"
  91. #include "llvm/Support/VirtualFileSystem.h"
  92. #include "llvm/Support/raw_ostream.h"
  93. #include <map>
  94. #include <memory>
  95. #include <utility>
  96. #if LLVM_ON_UNIX
  97. #include <unistd.h> // getpid
  98. #endif
  99. using namespace clang::driver;
  100. using namespace clang;
  101. using namespace llvm::opt;
  102. static llvm::Optional<llvm::Triple>
  103. getOffloadTargetTriple(const Driver &D, const ArgList &Args) {
  104. auto OffloadTargets = Args.getAllArgValues(options::OPT_offload_EQ);
  105. // Offload compilation flow does not support multiple targets for now. We
  106. // need the HIPActionBuilder (and possibly the CudaActionBuilder{,Base}too)
  107. // to support multiple tool chains first.
  108. switch (OffloadTargets.size()) {
  109. default:
  110. D.Diag(diag::err_drv_only_one_offload_target_supported);
  111. return llvm::None;
  112. case 0:
  113. D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << "";
  114. return llvm::None;
  115. case 1:
  116. break;
  117. }
  118. return llvm::Triple(OffloadTargets[0]);
  119. }
  120. static llvm::Optional<llvm::Triple>
  121. getNVIDIAOffloadTargetTriple(const Driver &D, const ArgList &Args,
  122. const llvm::Triple &HostTriple) {
  123. if (!Args.hasArg(options::OPT_offload_EQ)) {
  124. return llvm::Triple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
  125. : "nvptx-nvidia-cuda");
  126. }
  127. auto TT = getOffloadTargetTriple(D, Args);
  128. if (TT && (TT->getArch() == llvm::Triple::spirv32 ||
  129. TT->getArch() == llvm::Triple::spirv64)) {
  130. if (Args.hasArg(options::OPT_emit_llvm))
  131. return TT;
  132. D.Diag(diag::err_drv_cuda_offload_only_emit_bc);
  133. return llvm::None;
  134. }
  135. D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
  136. return llvm::None;
  137. }
  138. static llvm::Optional<llvm::Triple>
  139. getHIPOffloadTargetTriple(const Driver &D, const ArgList &Args) {
  140. if (!Args.hasArg(options::OPT_offload_EQ)) {
  141. return llvm::Triple("amdgcn-amd-amdhsa"); // Default HIP triple.
  142. }
  143. auto TT = getOffloadTargetTriple(D, Args);
  144. if (!TT)
  145. return llvm::None;
  146. if (TT->getArch() == llvm::Triple::amdgcn &&
  147. TT->getVendor() == llvm::Triple::AMD &&
  148. TT->getOS() == llvm::Triple::AMDHSA)
  149. return TT;
  150. if (TT->getArch() == llvm::Triple::spirv64)
  151. return TT;
  152. D.Diag(diag::err_drv_invalid_or_unsupported_offload_target) << TT->str();
  153. return llvm::None;
  154. }
  155. // static
  156. std::string Driver::GetResourcesPath(StringRef BinaryPath,
  157. StringRef CustomResourceDir) {
  158. // Since the resource directory is embedded in the module hash, it's important
  159. // that all places that need it call this function, so that they get the
  160. // exact same string ("a/../b/" and "b/" get different hashes, for example).
  161. // Dir is bin/ or lib/, depending on where BinaryPath is.
  162. std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
  163. SmallString<128> P(Dir);
  164. if (CustomResourceDir != "") {
  165. llvm::sys::path::append(P, CustomResourceDir);
  166. } else {
  167. // On Windows, libclang.dll is in bin/.
  168. // On non-Windows, libclang.so/.dylib is in lib/.
  169. // With a static-library build of libclang, LibClangPath will contain the
  170. // path of the embedding binary, which for LLVM binaries will be in bin/.
  171. // ../lib gets us to lib/ in both cases.
  172. P = llvm::sys::path::parent_path(Dir);
  173. llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
  174. CLANG_VERSION_STRING);
  175. }
  176. return std::string(P.str());
  177. }
  178. Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
  179. DiagnosticsEngine &Diags, std::string Title,
  180. IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
  181. : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
  182. SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
  183. ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
  184. DriverTitle(Title), CCCPrintBindings(false), CCPrintOptions(false),
  185. CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false),
  186. CCPrintProcessStats(false), TargetTriple(TargetTriple), Saver(Alloc),
  187. CheckInputsExist(true), GenReproducer(false),
  188. SuppressMissingInputWarning(false) {
  189. // Provide a sane fallback if no VFS is specified.
  190. if (!this->VFS)
  191. this->VFS = llvm::vfs::getRealFileSystem();
  192. Name = std::string(llvm::sys::path::filename(ClangExecutable));
  193. Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
  194. InstalledDir = Dir; // Provide a sensible default installed dir.
  195. if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
  196. // Prepend InstalledDir if SysRoot is relative
  197. SmallString<128> P(InstalledDir);
  198. llvm::sys::path::append(P, SysRoot);
  199. SysRoot = std::string(P);
  200. }
  201. #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
  202. SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
  203. #endif
  204. #if defined(CLANG_CONFIG_FILE_USER_DIR)
  205. UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
  206. #endif
  207. // Compute the path to the resource directory.
  208. ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
  209. }
  210. void Driver::setDriverMode(StringRef Value) {
  211. static const std::string OptName =
  212. getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
  213. if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
  214. .Case("gcc", GCCMode)
  215. .Case("g++", GXXMode)
  216. .Case("cpp", CPPMode)
  217. .Case("cl", CLMode)
  218. .Case("flang", FlangMode)
  219. .Default(None))
  220. Mode = *M;
  221. else
  222. Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
  223. }
  224. InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
  225. bool IsClCompatMode,
  226. bool &ContainsError) {
  227. llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
  228. ContainsError = false;
  229. unsigned IncludedFlagsBitmask;
  230. unsigned ExcludedFlagsBitmask;
  231. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  232. getIncludeExcludeOptionFlagMasks(IsClCompatMode);
  233. // Make sure that Flang-only options don't pollute the Clang output
  234. // TODO: Make sure that Clang-only options don't pollute Flang output
  235. if (!IsFlangMode())
  236. ExcludedFlagsBitmask |= options::FlangOnlyOption;
  237. unsigned MissingArgIndex, MissingArgCount;
  238. InputArgList Args =
  239. getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
  240. IncludedFlagsBitmask, ExcludedFlagsBitmask);
  241. // Check for missing argument error.
  242. if (MissingArgCount) {
  243. Diag(diag::err_drv_missing_argument)
  244. << Args.getArgString(MissingArgIndex) << MissingArgCount;
  245. ContainsError |=
  246. Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
  247. SourceLocation()) > DiagnosticsEngine::Warning;
  248. }
  249. // Check for unsupported options.
  250. for (const Arg *A : Args) {
  251. if (A->getOption().hasFlag(options::Unsupported)) {
  252. unsigned DiagID;
  253. auto ArgString = A->getAsString(Args);
  254. std::string Nearest;
  255. if (getOpts().findNearest(
  256. ArgString, Nearest, IncludedFlagsBitmask,
  257. ExcludedFlagsBitmask | options::Unsupported) > 1) {
  258. DiagID = diag::err_drv_unsupported_opt;
  259. Diag(DiagID) << ArgString;
  260. } else {
  261. DiagID = diag::err_drv_unsupported_opt_with_suggestion;
  262. Diag(DiagID) << ArgString << Nearest;
  263. }
  264. ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
  265. DiagnosticsEngine::Warning;
  266. continue;
  267. }
  268. // Warn about -mcpu= without an argument.
  269. if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
  270. Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
  271. ContainsError |= Diags.getDiagnosticLevel(
  272. diag::warn_drv_empty_joined_argument,
  273. SourceLocation()) > DiagnosticsEngine::Warning;
  274. }
  275. }
  276. for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
  277. unsigned DiagID;
  278. auto ArgString = A->getAsString(Args);
  279. std::string Nearest;
  280. if (getOpts().findNearest(
  281. ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
  282. DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
  283. : diag::err_drv_unknown_argument;
  284. Diags.Report(DiagID) << ArgString;
  285. } else {
  286. DiagID = IsCLMode()
  287. ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
  288. : diag::err_drv_unknown_argument_with_suggestion;
  289. Diags.Report(DiagID) << ArgString << Nearest;
  290. }
  291. ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
  292. DiagnosticsEngine::Warning;
  293. }
  294. return Args;
  295. }
  296. // Determine which compilation mode we are in. We look for options which
  297. // affect the phase, starting with the earliest phases, and record which
  298. // option we used to determine the final phase.
  299. phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
  300. Arg **FinalPhaseArg) const {
  301. Arg *PhaseArg = nullptr;
  302. phases::ID FinalPhase;
  303. // -{E,EP,P,M,MM} only run the preprocessor.
  304. if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
  305. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
  306. (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
  307. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P)) ||
  308. CCGenDiagnostics) {
  309. FinalPhase = phases::Preprocess;
  310. // --precompile only runs up to precompilation.
  311. } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
  312. FinalPhase = phases::Precompile;
  313. // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
  314. } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
  315. (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
  316. (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
  317. (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
  318. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
  319. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
  320. (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
  321. (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
  322. (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
  323. (PhaseArg = DAL.getLastArg(options::OPT_extract_api))) {
  324. FinalPhase = phases::Compile;
  325. // -S only runs up to the backend.
  326. } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
  327. FinalPhase = phases::Backend;
  328. // -c compilation only runs up to the assembler.
  329. } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
  330. FinalPhase = phases::Assemble;
  331. } else if ((PhaseArg = DAL.getLastArg(options::OPT_emit_interface_stubs))) {
  332. FinalPhase = phases::IfsMerge;
  333. // Otherwise do everything.
  334. } else
  335. FinalPhase = phases::Link;
  336. if (FinalPhaseArg)
  337. *FinalPhaseArg = PhaseArg;
  338. return FinalPhase;
  339. }
  340. static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
  341. StringRef Value, bool Claim = true) {
  342. Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
  343. Args.getBaseArgs().MakeIndex(Value), Value.data());
  344. Args.AddSynthesizedArg(A);
  345. if (Claim)
  346. A->claim();
  347. return A;
  348. }
  349. DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
  350. const llvm::opt::OptTable &Opts = getOpts();
  351. DerivedArgList *DAL = new DerivedArgList(Args);
  352. bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
  353. bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
  354. bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
  355. bool IgnoreUnused = false;
  356. for (Arg *A : Args) {
  357. if (IgnoreUnused)
  358. A->claim();
  359. if (A->getOption().matches(options::OPT_start_no_unused_arguments)) {
  360. IgnoreUnused = true;
  361. continue;
  362. }
  363. if (A->getOption().matches(options::OPT_end_no_unused_arguments)) {
  364. IgnoreUnused = false;
  365. continue;
  366. }
  367. // Unfortunately, we have to parse some forwarding options (-Xassembler,
  368. // -Xlinker, -Xpreprocessor) because we either integrate their functionality
  369. // (assembler and preprocessor), or bypass a previous driver ('collect2').
  370. // Rewrite linker options, to replace --no-demangle with a custom internal
  371. // option.
  372. if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
  373. A->getOption().matches(options::OPT_Xlinker)) &&
  374. A->containsValue("--no-demangle")) {
  375. // Add the rewritten no-demangle argument.
  376. DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
  377. // Add the remaining values as Xlinker arguments.
  378. for (StringRef Val : A->getValues())
  379. if (Val != "--no-demangle")
  380. DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
  381. continue;
  382. }
  383. // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
  384. // some build systems. We don't try to be complete here because we don't
  385. // care to encourage this usage model.
  386. if (A->getOption().matches(options::OPT_Wp_COMMA) &&
  387. (A->getValue(0) == StringRef("-MD") ||
  388. A->getValue(0) == StringRef("-MMD"))) {
  389. // Rewrite to -MD/-MMD along with -MF.
  390. if (A->getValue(0) == StringRef("-MD"))
  391. DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
  392. else
  393. DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
  394. if (A->getNumValues() == 2)
  395. DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
  396. continue;
  397. }
  398. // Rewrite reserved library names.
  399. if (A->getOption().matches(options::OPT_l)) {
  400. StringRef Value = A->getValue();
  401. // Rewrite unless -nostdlib is present.
  402. if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
  403. Value == "stdc++") {
  404. DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
  405. continue;
  406. }
  407. // Rewrite unconditionally.
  408. if (Value == "cc_kext") {
  409. DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
  410. continue;
  411. }
  412. }
  413. // Pick up inputs via the -- option.
  414. if (A->getOption().matches(options::OPT__DASH_DASH)) {
  415. A->claim();
  416. for (StringRef Val : A->getValues())
  417. DAL->append(MakeInputArg(*DAL, Opts, Val, false));
  418. continue;
  419. }
  420. DAL->append(A);
  421. }
  422. // Enforce -static if -miamcu is present.
  423. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
  424. DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_static));
  425. // Add a default value of -mlinker-version=, if one was given and the user
  426. // didn't specify one.
  427. #if defined(HOST_LINK_VERSION)
  428. if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
  429. strlen(HOST_LINK_VERSION) > 0) {
  430. DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
  431. HOST_LINK_VERSION);
  432. DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
  433. }
  434. #endif
  435. return DAL;
  436. }
  437. /// Compute target triple from args.
  438. ///
  439. /// This routine provides the logic to compute a target triple from various
  440. /// args passed to the driver and the default triple string.
  441. static llvm::Triple computeTargetTriple(const Driver &D,
  442. StringRef TargetTriple,
  443. const ArgList &Args,
  444. StringRef DarwinArchName = "") {
  445. // FIXME: Already done in Compilation *Driver::BuildCompilation
  446. if (const Arg *A = Args.getLastArg(options::OPT_target))
  447. TargetTriple = A->getValue();
  448. llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
  449. // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
  450. // -gnu* only, and we can not change this, so we have to detect that case as
  451. // being the Hurd OS.
  452. if (TargetTriple.contains("-unknown-gnu") || TargetTriple.contains("-pc-gnu"))
  453. Target.setOSName("hurd");
  454. // Handle Apple-specific options available here.
  455. if (Target.isOSBinFormatMachO()) {
  456. // If an explicit Darwin arch name is given, that trumps all.
  457. if (!DarwinArchName.empty()) {
  458. tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
  459. return Target;
  460. }
  461. // Handle the Darwin '-arch' flag.
  462. if (Arg *A = Args.getLastArg(options::OPT_arch)) {
  463. StringRef ArchName = A->getValue();
  464. tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
  465. }
  466. }
  467. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  468. // '-mbig-endian'/'-EB'.
  469. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  470. options::OPT_mbig_endian)) {
  471. if (A->getOption().matches(options::OPT_mlittle_endian)) {
  472. llvm::Triple LE = Target.getLittleEndianArchVariant();
  473. if (LE.getArch() != llvm::Triple::UnknownArch)
  474. Target = std::move(LE);
  475. } else {
  476. llvm::Triple BE = Target.getBigEndianArchVariant();
  477. if (BE.getArch() != llvm::Triple::UnknownArch)
  478. Target = std::move(BE);
  479. }
  480. }
  481. // Skip further flag support on OSes which don't support '-m32' or '-m64'.
  482. if (Target.getArch() == llvm::Triple::tce ||
  483. Target.getOS() == llvm::Triple::Minix)
  484. return Target;
  485. // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
  486. if (Target.isOSAIX()) {
  487. if (Optional<std::string> ObjectModeValue =
  488. llvm::sys::Process::GetEnv("OBJECT_MODE")) {
  489. StringRef ObjectMode = *ObjectModeValue;
  490. llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
  491. if (ObjectMode.equals("64")) {
  492. AT = Target.get64BitArchVariant().getArch();
  493. } else if (ObjectMode.equals("32")) {
  494. AT = Target.get32BitArchVariant().getArch();
  495. } else {
  496. D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
  497. }
  498. if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
  499. Target.setArch(AT);
  500. }
  501. }
  502. // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
  503. Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
  504. options::OPT_m32, options::OPT_m16);
  505. if (A) {
  506. llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
  507. if (A->getOption().matches(options::OPT_m64)) {
  508. AT = Target.get64BitArchVariant().getArch();
  509. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  510. Target.setEnvironment(llvm::Triple::GNU);
  511. else if (Target.getEnvironment() == llvm::Triple::MuslX32)
  512. Target.setEnvironment(llvm::Triple::Musl);
  513. } else if (A->getOption().matches(options::OPT_mx32) &&
  514. Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
  515. AT = llvm::Triple::x86_64;
  516. if (Target.getEnvironment() == llvm::Triple::Musl)
  517. Target.setEnvironment(llvm::Triple::MuslX32);
  518. else
  519. Target.setEnvironment(llvm::Triple::GNUX32);
  520. } else if (A->getOption().matches(options::OPT_m32)) {
  521. AT = Target.get32BitArchVariant().getArch();
  522. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  523. Target.setEnvironment(llvm::Triple::GNU);
  524. else if (Target.getEnvironment() == llvm::Triple::MuslX32)
  525. Target.setEnvironment(llvm::Triple::Musl);
  526. } else if (A->getOption().matches(options::OPT_m16) &&
  527. Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
  528. AT = llvm::Triple::x86;
  529. Target.setEnvironment(llvm::Triple::CODE16);
  530. }
  531. if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) {
  532. Target.setArch(AT);
  533. if (Target.isWindowsGNUEnvironment())
  534. toolchains::MinGW::fixTripleArch(D, Target, Args);
  535. }
  536. }
  537. // Handle -miamcu flag.
  538. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
  539. if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
  540. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
  541. << Target.str();
  542. if (A && !A->getOption().matches(options::OPT_m32))
  543. D.Diag(diag::err_drv_argument_not_allowed_with)
  544. << "-miamcu" << A->getBaseArg().getAsString(Args);
  545. Target.setArch(llvm::Triple::x86);
  546. Target.setArchName("i586");
  547. Target.setEnvironment(llvm::Triple::UnknownEnvironment);
  548. Target.setEnvironmentName("");
  549. Target.setOS(llvm::Triple::ELFIAMCU);
  550. Target.setVendor(llvm::Triple::UnknownVendor);
  551. Target.setVendorName("intel");
  552. }
  553. // If target is MIPS adjust the target triple
  554. // accordingly to provided ABI name.
  555. A = Args.getLastArg(options::OPT_mabi_EQ);
  556. if (A && Target.isMIPS()) {
  557. StringRef ABIName = A->getValue();
  558. if (ABIName == "32") {
  559. Target = Target.get32BitArchVariant();
  560. if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
  561. Target.getEnvironment() == llvm::Triple::GNUABIN32)
  562. Target.setEnvironment(llvm::Triple::GNU);
  563. } else if (ABIName == "n32") {
  564. Target = Target.get64BitArchVariant();
  565. if (Target.getEnvironment() == llvm::Triple::GNU ||
  566. Target.getEnvironment() == llvm::Triple::GNUABI64)
  567. Target.setEnvironment(llvm::Triple::GNUABIN32);
  568. } else if (ABIName == "64") {
  569. Target = Target.get64BitArchVariant();
  570. if (Target.getEnvironment() == llvm::Triple::GNU ||
  571. Target.getEnvironment() == llvm::Triple::GNUABIN32)
  572. Target.setEnvironment(llvm::Triple::GNUABI64);
  573. }
  574. }
  575. // If target is RISC-V adjust the target triple according to
  576. // provided architecture name
  577. A = Args.getLastArg(options::OPT_march_EQ);
  578. if (A && Target.isRISCV()) {
  579. StringRef ArchName = A->getValue();
  580. if (ArchName.startswith_insensitive("rv32"))
  581. Target.setArch(llvm::Triple::riscv32);
  582. else if (ArchName.startswith_insensitive("rv64"))
  583. Target.setArch(llvm::Triple::riscv64);
  584. }
  585. return Target;
  586. }
  587. // Parse the LTO options and record the type of LTO compilation
  588. // based on which -f(no-)?lto(=.*)? or -f(no-)?offload-lto(=.*)?
  589. // option occurs last.
  590. static driver::LTOKind parseLTOMode(Driver &D, const llvm::opt::ArgList &Args,
  591. OptSpecifier OptEq, OptSpecifier OptNeg) {
  592. if (!Args.hasFlag(OptEq, OptNeg, false))
  593. return LTOK_None;
  594. const Arg *A = Args.getLastArg(OptEq);
  595. StringRef LTOName = A->getValue();
  596. driver::LTOKind LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
  597. .Case("full", LTOK_Full)
  598. .Case("thin", LTOK_Thin)
  599. .Default(LTOK_Unknown);
  600. if (LTOMode == LTOK_Unknown) {
  601. D.Diag(diag::err_drv_unsupported_option_argument)
  602. << A->getOption().getName() << A->getValue();
  603. return LTOK_None;
  604. }
  605. return LTOMode;
  606. }
  607. // Parse the LTO options.
  608. void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
  609. LTOMode =
  610. parseLTOMode(*this, Args, options::OPT_flto_EQ, options::OPT_fno_lto);
  611. OffloadLTOMode = parseLTOMode(*this, Args, options::OPT_foffload_lto_EQ,
  612. options::OPT_fno_offload_lto);
  613. }
  614. /// Compute the desired OpenMP runtime from the flags provided.
  615. Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
  616. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  617. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  618. if (A)
  619. RuntimeName = A->getValue();
  620. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  621. .Case("libomp", OMPRT_OMP)
  622. .Case("libgomp", OMPRT_GOMP)
  623. .Case("libiomp5", OMPRT_IOMP5)
  624. .Default(OMPRT_Unknown);
  625. if (RT == OMPRT_Unknown) {
  626. if (A)
  627. Diag(diag::err_drv_unsupported_option_argument)
  628. << A->getOption().getName() << A->getValue();
  629. else
  630. // FIXME: We could use a nicer diagnostic here.
  631. Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  632. }
  633. return RT;
  634. }
  635. void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
  636. InputList &Inputs) {
  637. //
  638. // CUDA/HIP
  639. //
  640. // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
  641. // or HIP type. However, mixed CUDA/HIP compilation is not supported.
  642. bool IsCuda =
  643. llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
  644. return types::isCuda(I.first);
  645. });
  646. bool IsHIP =
  647. llvm::any_of(Inputs,
  648. [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
  649. return types::isHIP(I.first);
  650. }) ||
  651. C.getInputArgs().hasArg(options::OPT_hip_link);
  652. if (IsCuda && IsHIP) {
  653. Diag(clang::diag::err_drv_mix_cuda_hip);
  654. return;
  655. }
  656. if (IsCuda) {
  657. const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
  658. const llvm::Triple &HostTriple = HostTC->getTriple();
  659. auto OFK = Action::OFK_Cuda;
  660. auto CudaTriple =
  661. getNVIDIAOffloadTargetTriple(*this, C.getInputArgs(), HostTriple);
  662. if (!CudaTriple)
  663. return;
  664. // Use the CUDA and host triples as the key into the ToolChains map,
  665. // because the device toolchain we create depends on both.
  666. auto &CudaTC = ToolChains[CudaTriple->str() + "/" + HostTriple.str()];
  667. if (!CudaTC) {
  668. CudaTC = std::make_unique<toolchains::CudaToolChain>(
  669. *this, *CudaTriple, *HostTC, C.getInputArgs(), OFK);
  670. }
  671. C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
  672. } else if (IsHIP) {
  673. if (auto *OMPTargetArg =
  674. C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
  675. Diag(clang::diag::err_drv_unsupported_opt_for_language_mode)
  676. << OMPTargetArg->getSpelling() << "HIP";
  677. return;
  678. }
  679. const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
  680. auto OFK = Action::OFK_HIP;
  681. auto HIPTriple = getHIPOffloadTargetTriple(*this, C.getInputArgs());
  682. if (!HIPTriple)
  683. return;
  684. auto *HIPTC = &getOffloadingDeviceToolChain(C.getInputArgs(), *HIPTriple,
  685. *HostTC, OFK);
  686. assert(HIPTC && "Could not create offloading device tool chain.");
  687. C.addOffloadDeviceToolChain(HIPTC, OFK);
  688. }
  689. //
  690. // OpenMP
  691. //
  692. // We need to generate an OpenMP toolchain if the user specified targets with
  693. // the -fopenmp-targets option.
  694. if (Arg *OpenMPTargets =
  695. C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
  696. if (OpenMPTargets->getNumValues()) {
  697. // We expect that -fopenmp-targets is always used in conjunction with the
  698. // option -fopenmp specifying a valid runtime with offloading support,
  699. // i.e. libomp or libiomp.
  700. bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
  701. options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  702. options::OPT_fno_openmp, false);
  703. if (HasValidOpenMPRuntime) {
  704. OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
  705. HasValidOpenMPRuntime =
  706. OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
  707. }
  708. if (HasValidOpenMPRuntime) {
  709. llvm::StringMap<const char *> FoundNormalizedTriples;
  710. for (const char *Val : OpenMPTargets->getValues()) {
  711. llvm::Triple TT(ToolChain::getOpenMPTriple(Val));
  712. std::string NormalizedName = TT.normalize();
  713. // Make sure we don't have a duplicate triple.
  714. auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
  715. if (Duplicate != FoundNormalizedTriples.end()) {
  716. Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
  717. << Val << Duplicate->second;
  718. continue;
  719. }
  720. // Store the current triple so that we can check for duplicates in the
  721. // following iterations.
  722. FoundNormalizedTriples[NormalizedName] = Val;
  723. // If the specified target is invalid, emit a diagnostic.
  724. if (TT.getArch() == llvm::Triple::UnknownArch)
  725. Diag(clang::diag::err_drv_invalid_omp_target) << Val;
  726. else {
  727. const ToolChain *TC;
  728. // Device toolchains have to be selected differently. They pair host
  729. // and device in their implementation.
  730. if (TT.isNVPTX() || TT.isAMDGCN()) {
  731. const ToolChain *HostTC =
  732. C.getSingleOffloadToolChain<Action::OFK_Host>();
  733. assert(HostTC && "Host toolchain should be always defined.");
  734. auto &DeviceTC =
  735. ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
  736. if (!DeviceTC) {
  737. if (TT.isNVPTX())
  738. DeviceTC = std::make_unique<toolchains::CudaToolChain>(
  739. *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
  740. else if (TT.isAMDGCN())
  741. DeviceTC =
  742. std::make_unique<toolchains::AMDGPUOpenMPToolChain>(
  743. *this, TT, *HostTC, C.getInputArgs());
  744. else
  745. assert(DeviceTC && "Device toolchain not defined.");
  746. }
  747. TC = DeviceTC.get();
  748. } else
  749. TC = &getToolChain(C.getInputArgs(), TT);
  750. C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
  751. }
  752. }
  753. } else
  754. Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
  755. } else
  756. Diag(clang::diag::warn_drv_empty_joined_argument)
  757. << OpenMPTargets->getAsString(C.getInputArgs());
  758. }
  759. //
  760. // TODO: Add support for other offloading programming models here.
  761. //
  762. }
  763. /// Looks the given directories for the specified file.
  764. ///
  765. /// \param[out] FilePath File path, if the file was found.
  766. /// \param[in] Dirs Directories used for the search.
  767. /// \param[in] FileName Name of the file to search for.
  768. /// \return True if file was found.
  769. ///
  770. /// Looks for file specified by FileName sequentially in directories specified
  771. /// by Dirs.
  772. ///
  773. static bool searchForFile(SmallVectorImpl<char> &FilePath,
  774. ArrayRef<StringRef> Dirs, StringRef FileName) {
  775. SmallString<128> WPath;
  776. for (const StringRef &Dir : Dirs) {
  777. if (Dir.empty())
  778. continue;
  779. WPath.clear();
  780. llvm::sys::path::append(WPath, Dir, FileName);
  781. llvm::sys::path::native(WPath);
  782. if (llvm::sys::fs::is_regular_file(WPath)) {
  783. FilePath = std::move(WPath);
  784. return true;
  785. }
  786. }
  787. return false;
  788. }
  789. bool Driver::readConfigFile(StringRef FileName) {
  790. // Try reading the given file.
  791. SmallVector<const char *, 32> NewCfgArgs;
  792. if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
  793. Diag(diag::err_drv_cannot_read_config_file) << FileName;
  794. return true;
  795. }
  796. // Read options from config file.
  797. llvm::SmallString<128> CfgFileName(FileName);
  798. llvm::sys::path::native(CfgFileName);
  799. ConfigFile = std::string(CfgFileName);
  800. bool ContainErrors;
  801. CfgOptions = std::make_unique<InputArgList>(
  802. ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
  803. if (ContainErrors) {
  804. CfgOptions.reset();
  805. return true;
  806. }
  807. if (CfgOptions->hasArg(options::OPT_config)) {
  808. CfgOptions.reset();
  809. Diag(diag::err_drv_nested_config_file);
  810. return true;
  811. }
  812. // Claim all arguments that come from a configuration file so that the driver
  813. // does not warn on any that is unused.
  814. for (Arg *A : *CfgOptions)
  815. A->claim();
  816. return false;
  817. }
  818. bool Driver::loadConfigFile() {
  819. std::string CfgFileName;
  820. bool FileSpecifiedExplicitly = false;
  821. // Process options that change search path for config files.
  822. if (CLOptions) {
  823. if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
  824. SmallString<128> CfgDir;
  825. CfgDir.append(
  826. CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
  827. if (!CfgDir.empty()) {
  828. if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
  829. SystemConfigDir.clear();
  830. else
  831. SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
  832. }
  833. }
  834. if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
  835. SmallString<128> CfgDir;
  836. CfgDir.append(
  837. CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
  838. if (!CfgDir.empty()) {
  839. if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
  840. UserConfigDir.clear();
  841. else
  842. UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
  843. }
  844. }
  845. }
  846. // First try to find config file specified in command line.
  847. if (CLOptions) {
  848. std::vector<std::string> ConfigFiles =
  849. CLOptions->getAllArgValues(options::OPT_config);
  850. if (ConfigFiles.size() > 1) {
  851. if (!llvm::all_of(ConfigFiles, [ConfigFiles](const std::string &s) {
  852. return s == ConfigFiles[0];
  853. })) {
  854. Diag(diag::err_drv_duplicate_config);
  855. return true;
  856. }
  857. }
  858. if (!ConfigFiles.empty()) {
  859. CfgFileName = ConfigFiles.front();
  860. assert(!CfgFileName.empty());
  861. // If argument contains directory separator, treat it as a path to
  862. // configuration file.
  863. if (llvm::sys::path::has_parent_path(CfgFileName)) {
  864. SmallString<128> CfgFilePath;
  865. if (llvm::sys::path::is_relative(CfgFileName))
  866. llvm::sys::fs::current_path(CfgFilePath);
  867. llvm::sys::path::append(CfgFilePath, CfgFileName);
  868. if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
  869. Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
  870. return true;
  871. }
  872. return readConfigFile(CfgFilePath);
  873. }
  874. FileSpecifiedExplicitly = true;
  875. }
  876. }
  877. // If config file is not specified explicitly, try to deduce configuration
  878. // from executable name. For instance, an executable 'armv7l-clang' will
  879. // search for config file 'armv7l-clang.cfg'.
  880. if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
  881. CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
  882. if (CfgFileName.empty())
  883. return false;
  884. // Determine architecture part of the file name, if it is present.
  885. StringRef CfgFileArch = CfgFileName;
  886. size_t ArchPrefixLen = CfgFileArch.find('-');
  887. if (ArchPrefixLen == StringRef::npos)
  888. ArchPrefixLen = CfgFileArch.size();
  889. llvm::Triple CfgTriple;
  890. CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
  891. CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
  892. if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
  893. ArchPrefixLen = 0;
  894. if (!StringRef(CfgFileName).endswith(".cfg"))
  895. CfgFileName += ".cfg";
  896. // If config file starts with architecture name and command line options
  897. // redefine architecture (with options like -m32 -LE etc), try finding new
  898. // config file with that architecture.
  899. SmallString<128> FixedConfigFile;
  900. size_t FixedArchPrefixLen = 0;
  901. if (ArchPrefixLen) {
  902. // Get architecture name from config file name like 'i386.cfg' or
  903. // 'armv7l-clang.cfg'.
  904. // Check if command line options changes effective triple.
  905. llvm::Triple EffectiveTriple = computeTargetTriple(*this,
  906. CfgTriple.getTriple(), *CLOptions);
  907. if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
  908. FixedConfigFile = EffectiveTriple.getArchName();
  909. FixedArchPrefixLen = FixedConfigFile.size();
  910. // Append the rest of original file name so that file name transforms
  911. // like: i386-clang.cfg -> x86_64-clang.cfg.
  912. if (ArchPrefixLen < CfgFileName.size())
  913. FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
  914. }
  915. }
  916. // Prepare list of directories where config file is searched for.
  917. StringRef CfgFileSearchDirs[] = {UserConfigDir, SystemConfigDir, Dir};
  918. // Try to find config file. First try file with corrected architecture.
  919. llvm::SmallString<128> CfgFilePath;
  920. if (!FixedConfigFile.empty()) {
  921. if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
  922. return readConfigFile(CfgFilePath);
  923. // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
  924. FixedConfigFile.resize(FixedArchPrefixLen);
  925. FixedConfigFile.append(".cfg");
  926. if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
  927. return readConfigFile(CfgFilePath);
  928. }
  929. // Then try original file name.
  930. if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
  931. return readConfigFile(CfgFilePath);
  932. // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
  933. if (!ClangNameParts.ModeSuffix.empty() &&
  934. !ClangNameParts.TargetPrefix.empty()) {
  935. CfgFileName.assign(ClangNameParts.TargetPrefix);
  936. CfgFileName.append(".cfg");
  937. if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
  938. return readConfigFile(CfgFilePath);
  939. }
  940. // Report error but only if config file was specified explicitly, by option
  941. // --config. If it was deduced from executable name, it is not an error.
  942. if (FileSpecifiedExplicitly) {
  943. Diag(diag::err_drv_config_file_not_found) << CfgFileName;
  944. for (const StringRef &SearchDir : CfgFileSearchDirs)
  945. if (!SearchDir.empty())
  946. Diag(diag::note_drv_config_file_searched_in) << SearchDir;
  947. return true;
  948. }
  949. return false;
  950. }
  951. Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
  952. llvm::PrettyStackTraceString CrashInfo("Compilation construction");
  953. // FIXME: Handle environment options which affect driver behavior, somewhere
  954. // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
  955. // We look for the driver mode option early, because the mode can affect
  956. // how other options are parsed.
  957. auto DriverMode = getDriverMode(ClangExecutable, ArgList.slice(1));
  958. if (!DriverMode.empty())
  959. setDriverMode(DriverMode);
  960. // FIXME: What are we going to do with -V and -b?
  961. // Arguments specified in command line.
  962. bool ContainsError;
  963. CLOptions = std::make_unique<InputArgList>(
  964. ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
  965. // Try parsing configuration file.
  966. if (!ContainsError)
  967. ContainsError = loadConfigFile();
  968. bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
  969. // All arguments, from both config file and command line.
  970. InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
  971. : std::move(*CLOptions));
  972. // The args for config files or /clang: flags belong to different InputArgList
  973. // objects than Args. This copies an Arg from one of those other InputArgLists
  974. // to the ownership of Args.
  975. auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
  976. unsigned Index = Args.MakeIndex(Opt->getSpelling());
  977. Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Args.getArgString(Index),
  978. Index, BaseArg);
  979. Copy->getValues() = Opt->getValues();
  980. if (Opt->isClaimed())
  981. Copy->claim();
  982. Copy->setOwnsValues(Opt->getOwnsValues());
  983. Opt->setOwnsValues(false);
  984. Args.append(Copy);
  985. };
  986. if (HasConfigFile)
  987. for (auto *Opt : *CLOptions) {
  988. if (Opt->getOption().matches(options::OPT_config))
  989. continue;
  990. const Arg *BaseArg = &Opt->getBaseArg();
  991. if (BaseArg == Opt)
  992. BaseArg = nullptr;
  993. appendOneArg(Opt, BaseArg);
  994. }
  995. // In CL mode, look for any pass-through arguments
  996. if (IsCLMode() && !ContainsError) {
  997. SmallVector<const char *, 16> CLModePassThroughArgList;
  998. for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
  999. A->claim();
  1000. CLModePassThroughArgList.push_back(A->getValue());
  1001. }
  1002. if (!CLModePassThroughArgList.empty()) {
  1003. // Parse any pass through args using default clang processing rather
  1004. // than clang-cl processing.
  1005. auto CLModePassThroughOptions = std::make_unique<InputArgList>(
  1006. ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
  1007. if (!ContainsError)
  1008. for (auto *Opt : *CLModePassThroughOptions) {
  1009. appendOneArg(Opt, nullptr);
  1010. }
  1011. }
  1012. }
  1013. // Check for working directory option before accessing any files
  1014. if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
  1015. if (VFS->setCurrentWorkingDirectory(WD->getValue()))
  1016. Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
  1017. // FIXME: This stuff needs to go into the Compilation, not the driver.
  1018. bool CCCPrintPhases;
  1019. // Silence driver warnings if requested
  1020. Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
  1021. // -canonical-prefixes, -no-canonical-prefixes are used very early in main.
  1022. Args.ClaimAllArgs(options::OPT_canonical_prefixes);
  1023. Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
  1024. // f(no-)integated-cc1 is also used very early in main.
  1025. Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
  1026. Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
  1027. // Ignore -pipe.
  1028. Args.ClaimAllArgs(options::OPT_pipe);
  1029. // Extract -ccc args.
  1030. //
  1031. // FIXME: We need to figure out where this behavior should live. Most of it
  1032. // should be outside in the client; the parts that aren't should have proper
  1033. // options, either by introducing new ones or by overloading gcc ones like -V
  1034. // or -b.
  1035. CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
  1036. CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
  1037. if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
  1038. CCCGenericGCCName = A->getValue();
  1039. GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
  1040. options::OPT_fno_crash_diagnostics,
  1041. !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
  1042. // Process -fproc-stat-report options.
  1043. if (const Arg *A = Args.getLastArg(options::OPT_fproc_stat_report_EQ)) {
  1044. CCPrintProcessStats = true;
  1045. CCPrintStatReportFilename = A->getValue();
  1046. }
  1047. if (Args.hasArg(options::OPT_fproc_stat_report))
  1048. CCPrintProcessStats = true;
  1049. // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
  1050. // and getToolChain is const.
  1051. if (IsCLMode()) {
  1052. // clang-cl targets MSVC-style Win32.
  1053. llvm::Triple T(TargetTriple);
  1054. T.setOS(llvm::Triple::Win32);
  1055. T.setVendor(llvm::Triple::PC);
  1056. T.setEnvironment(llvm::Triple::MSVC);
  1057. T.setObjectFormat(llvm::Triple::COFF);
  1058. TargetTriple = T.str();
  1059. }
  1060. if (const Arg *A = Args.getLastArg(options::OPT_target))
  1061. TargetTriple = A->getValue();
  1062. if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
  1063. Dir = InstalledDir = A->getValue();
  1064. for (const Arg *A : Args.filtered(options::OPT_B)) {
  1065. A->claim();
  1066. PrefixDirs.push_back(A->getValue(0));
  1067. }
  1068. if (Optional<std::string> CompilerPathValue =
  1069. llvm::sys::Process::GetEnv("COMPILER_PATH")) {
  1070. StringRef CompilerPath = *CompilerPathValue;
  1071. while (!CompilerPath.empty()) {
  1072. std::pair<StringRef, StringRef> Split =
  1073. CompilerPath.split(llvm::sys::EnvPathSeparator);
  1074. PrefixDirs.push_back(std::string(Split.first));
  1075. CompilerPath = Split.second;
  1076. }
  1077. }
  1078. if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
  1079. SysRoot = A->getValue();
  1080. if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
  1081. DyldPrefix = A->getValue();
  1082. if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
  1083. ResourceDir = A->getValue();
  1084. if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
  1085. SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
  1086. .Case("cwd", SaveTempsCwd)
  1087. .Case("obj", SaveTempsObj)
  1088. .Default(SaveTempsCwd);
  1089. }
  1090. setLTOMode(Args);
  1091. // Process -fembed-bitcode= flags.
  1092. if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
  1093. StringRef Name = A->getValue();
  1094. unsigned Model = llvm::StringSwitch<unsigned>(Name)
  1095. .Case("off", EmbedNone)
  1096. .Case("all", EmbedBitcode)
  1097. .Case("bitcode", EmbedBitcode)
  1098. .Case("marker", EmbedMarker)
  1099. .Default(~0U);
  1100. if (Model == ~0U) {
  1101. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
  1102. << Name;
  1103. } else
  1104. BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
  1105. }
  1106. std::unique_ptr<llvm::opt::InputArgList> UArgs =
  1107. std::make_unique<InputArgList>(std::move(Args));
  1108. // Perform the default argument translations.
  1109. DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
  1110. // Owned by the host.
  1111. const ToolChain &TC = getToolChain(
  1112. *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
  1113. // The compilation takes ownership of Args.
  1114. Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
  1115. ContainsError);
  1116. if (!HandleImmediateArgs(*C))
  1117. return C;
  1118. // Construct the list of inputs.
  1119. InputList Inputs;
  1120. BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
  1121. // Populate the tool chains for the offloading devices, if any.
  1122. CreateOffloadingDeviceToolChains(*C, Inputs);
  1123. // Construct the list of abstract actions to perform for this compilation. On
  1124. // MachO targets this uses the driver-driver and universal actions.
  1125. if (TC.getTriple().isOSBinFormatMachO())
  1126. BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
  1127. else
  1128. BuildActions(*C, C->getArgs(), Inputs, C->getActions());
  1129. if (CCCPrintPhases) {
  1130. PrintActions(*C);
  1131. return C;
  1132. }
  1133. BuildJobs(*C);
  1134. return C;
  1135. }
  1136. static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
  1137. llvm::opt::ArgStringList ASL;
  1138. for (const auto *A : Args) {
  1139. // Use user's original spelling of flags. For example, use
  1140. // `/source-charset:utf-8` instead of `-finput-charset=utf-8` if the user
  1141. // wrote the former.
  1142. while (A->getAlias())
  1143. A = A->getAlias();
  1144. A->render(Args, ASL);
  1145. }
  1146. for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
  1147. if (I != ASL.begin())
  1148. OS << ' ';
  1149. llvm::sys::printArg(OS, *I, true);
  1150. }
  1151. OS << '\n';
  1152. }
  1153. bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
  1154. SmallString<128> &CrashDiagDir) {
  1155. using namespace llvm::sys;
  1156. assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
  1157. "Only knows about .crash files on Darwin");
  1158. // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
  1159. // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
  1160. // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
  1161. path::home_directory(CrashDiagDir);
  1162. if (CrashDiagDir.startswith("/var/root"))
  1163. CrashDiagDir = "/";
  1164. path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
  1165. int PID =
  1166. #if LLVM_ON_UNIX
  1167. getpid();
  1168. #else
  1169. 0;
  1170. #endif
  1171. std::error_code EC;
  1172. fs::file_status FileStatus;
  1173. TimePoint<> LastAccessTime;
  1174. SmallString<128> CrashFilePath;
  1175. // Lookup the .crash files and get the one generated by a subprocess spawned
  1176. // by this driver invocation.
  1177. for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
  1178. File != FileEnd && !EC; File.increment(EC)) {
  1179. StringRef FileName = path::filename(File->path());
  1180. if (!FileName.startswith(Name))
  1181. continue;
  1182. if (fs::status(File->path(), FileStatus))
  1183. continue;
  1184. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
  1185. llvm::MemoryBuffer::getFile(File->path());
  1186. if (!CrashFile)
  1187. continue;
  1188. // The first line should start with "Process:", otherwise this isn't a real
  1189. // .crash file.
  1190. StringRef Data = CrashFile.get()->getBuffer();
  1191. if (!Data.startswith("Process:"))
  1192. continue;
  1193. // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
  1194. size_t ParentProcPos = Data.find("Parent Process:");
  1195. if (ParentProcPos == StringRef::npos)
  1196. continue;
  1197. size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
  1198. if (LineEnd == StringRef::npos)
  1199. continue;
  1200. StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
  1201. int OpenBracket = -1, CloseBracket = -1;
  1202. for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
  1203. if (ParentProcess[i] == '[')
  1204. OpenBracket = i;
  1205. if (ParentProcess[i] == ']')
  1206. CloseBracket = i;
  1207. }
  1208. // Extract the parent process PID from the .crash file and check whether
  1209. // it matches this driver invocation pid.
  1210. int CrashPID;
  1211. if (OpenBracket < 0 || CloseBracket < 0 ||
  1212. ParentProcess.slice(OpenBracket + 1, CloseBracket)
  1213. .getAsInteger(10, CrashPID) || CrashPID != PID) {
  1214. continue;
  1215. }
  1216. // Found a .crash file matching the driver pid. To avoid getting an older
  1217. // and misleading crash file, continue looking for the most recent.
  1218. // FIXME: the driver can dispatch multiple cc1 invocations, leading to
  1219. // multiple crashes poiting to the same parent process. Since the driver
  1220. // does not collect pid information for the dispatched invocation there's
  1221. // currently no way to distinguish among them.
  1222. const auto FileAccessTime = FileStatus.getLastModificationTime();
  1223. if (FileAccessTime > LastAccessTime) {
  1224. CrashFilePath.assign(File->path());
  1225. LastAccessTime = FileAccessTime;
  1226. }
  1227. }
  1228. // If found, copy it over to the location of other reproducer files.
  1229. if (!CrashFilePath.empty()) {
  1230. EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
  1231. if (EC)
  1232. return false;
  1233. return true;
  1234. }
  1235. return false;
  1236. }
  1237. // When clang crashes, produce diagnostic information including the fully
  1238. // preprocessed source file(s). Request that the developer attach the
  1239. // diagnostic information to a bug report.
  1240. void Driver::generateCompilationDiagnostics(
  1241. Compilation &C, const Command &FailingCommand,
  1242. StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
  1243. if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
  1244. return;
  1245. // Don't try to generate diagnostics for link or dsymutil jobs.
  1246. if (FailingCommand.getCreator().isLinkJob() ||
  1247. FailingCommand.getCreator().isDsymutilJob())
  1248. return;
  1249. // Print the version of the compiler.
  1250. PrintVersion(C, llvm::errs());
  1251. // Suppress driver output and emit preprocessor output to temp file.
  1252. CCGenDiagnostics = true;
  1253. // Save the original job command(s).
  1254. Command Cmd = FailingCommand;
  1255. // Keep track of whether we produce any errors while trying to produce
  1256. // preprocessed sources.
  1257. DiagnosticErrorTrap Trap(Diags);
  1258. // Suppress tool output.
  1259. C.initCompilationForDiagnostics();
  1260. // Construct the list of inputs.
  1261. InputList Inputs;
  1262. BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
  1263. for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
  1264. bool IgnoreInput = false;
  1265. // Ignore input from stdin or any inputs that cannot be preprocessed.
  1266. // Check type first as not all linker inputs have a value.
  1267. if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
  1268. IgnoreInput = true;
  1269. } else if (!strcmp(it->second->getValue(), "-")) {
  1270. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1271. << "Error generating preprocessed source(s) - "
  1272. "ignoring input from stdin.";
  1273. IgnoreInput = true;
  1274. }
  1275. if (IgnoreInput) {
  1276. it = Inputs.erase(it);
  1277. ie = Inputs.end();
  1278. } else {
  1279. ++it;
  1280. }
  1281. }
  1282. if (Inputs.empty()) {
  1283. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1284. << "Error generating preprocessed source(s) - "
  1285. "no preprocessable inputs.";
  1286. return;
  1287. }
  1288. // Don't attempt to generate preprocessed files if multiple -arch options are
  1289. // used, unless they're all duplicates.
  1290. llvm::StringSet<> ArchNames;
  1291. for (const Arg *A : C.getArgs()) {
  1292. if (A->getOption().matches(options::OPT_arch)) {
  1293. StringRef ArchName = A->getValue();
  1294. ArchNames.insert(ArchName);
  1295. }
  1296. }
  1297. if (ArchNames.size() > 1) {
  1298. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1299. << "Error generating preprocessed source(s) - cannot generate "
  1300. "preprocessed source with multiple -arch options.";
  1301. return;
  1302. }
  1303. // Construct the list of abstract actions to perform for this compilation. On
  1304. // Darwin OSes this uses the driver-driver and builds universal actions.
  1305. const ToolChain &TC = C.getDefaultToolChain();
  1306. if (TC.getTriple().isOSBinFormatMachO())
  1307. BuildUniversalActions(C, TC, Inputs);
  1308. else
  1309. BuildActions(C, C.getArgs(), Inputs, C.getActions());
  1310. BuildJobs(C);
  1311. // If there were errors building the compilation, quit now.
  1312. if (Trap.hasErrorOccurred()) {
  1313. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1314. << "Error generating preprocessed source(s).";
  1315. return;
  1316. }
  1317. // Generate preprocessed output.
  1318. SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
  1319. C.ExecuteJobs(C.getJobs(), FailingCommands);
  1320. // If any of the preprocessing commands failed, clean up and exit.
  1321. if (!FailingCommands.empty()) {
  1322. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1323. << "Error generating preprocessed source(s).";
  1324. return;
  1325. }
  1326. const ArgStringList &TempFiles = C.getTempFiles();
  1327. if (TempFiles.empty()) {
  1328. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1329. << "Error generating preprocessed source(s).";
  1330. return;
  1331. }
  1332. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1333. << "\n********************\n\n"
  1334. "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
  1335. "Preprocessed source(s) and associated run script(s) are located at:";
  1336. SmallString<128> VFS;
  1337. SmallString<128> ReproCrashFilename;
  1338. for (const char *TempFile : TempFiles) {
  1339. Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
  1340. if (Report)
  1341. Report->TemporaryFiles.push_back(TempFile);
  1342. if (ReproCrashFilename.empty()) {
  1343. ReproCrashFilename = TempFile;
  1344. llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
  1345. }
  1346. if (StringRef(TempFile).endswith(".cache")) {
  1347. // In some cases (modules) we'll dump extra data to help with reproducing
  1348. // the crash into a directory next to the output.
  1349. VFS = llvm::sys::path::filename(TempFile);
  1350. llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
  1351. }
  1352. }
  1353. // Assume associated files are based off of the first temporary file.
  1354. CrashReportInfo CrashInfo(TempFiles[0], VFS);
  1355. llvm::SmallString<128> Script(CrashInfo.Filename);
  1356. llvm::sys::path::replace_extension(Script, "sh");
  1357. std::error_code EC;
  1358. llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew,
  1359. llvm::sys::fs::FA_Write,
  1360. llvm::sys::fs::OF_Text);
  1361. if (EC) {
  1362. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1363. << "Error generating run script: " << Script << " " << EC.message();
  1364. } else {
  1365. ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
  1366. << "# Driver args: ";
  1367. printArgList(ScriptOS, C.getInputArgs());
  1368. ScriptOS << "# Original command: ";
  1369. Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
  1370. Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
  1371. if (!AdditionalInformation.empty())
  1372. ScriptOS << "\n# Additional information: " << AdditionalInformation
  1373. << "\n";
  1374. if (Report)
  1375. Report->TemporaryFiles.push_back(std::string(Script.str()));
  1376. Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
  1377. }
  1378. // On darwin, provide information about the .crash diagnostic report.
  1379. if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
  1380. SmallString<128> CrashDiagDir;
  1381. if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
  1382. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1383. << ReproCrashFilename.str();
  1384. } else { // Suggest a directory for the user to look for .crash files.
  1385. llvm::sys::path::append(CrashDiagDir, Name);
  1386. CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
  1387. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1388. << "Crash backtrace is located in";
  1389. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1390. << CrashDiagDir.str();
  1391. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1392. << "(choose the .crash file that corresponds to your crash)";
  1393. }
  1394. }
  1395. for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file_EQ))
  1396. Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
  1397. Diag(clang::diag::note_drv_command_failed_diag_msg)
  1398. << "\n\n********************";
  1399. }
  1400. void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
  1401. // Since commandLineFitsWithinSystemLimits() may underestimate system's
  1402. // capacity if the tool does not support response files, there is a chance/
  1403. // that things will just work without a response file, so we silently just
  1404. // skip it.
  1405. if (Cmd.getResponseFileSupport().ResponseKind ==
  1406. ResponseFileSupport::RF_None ||
  1407. llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
  1408. Cmd.getArguments()))
  1409. return;
  1410. std::string TmpName = GetTemporaryPath("response", "txt");
  1411. Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
  1412. }
  1413. int Driver::ExecuteCompilation(
  1414. Compilation &C,
  1415. SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
  1416. // Just print if -### was present.
  1417. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  1418. C.getJobs().Print(llvm::errs(), "\n", true);
  1419. return 0;
  1420. }
  1421. // If there were errors building the compilation, quit now.
  1422. if (Diags.hasErrorOccurred())
  1423. return 1;
  1424. // Set up response file names for each command, if necessary.
  1425. for (auto &Job : C.getJobs())
  1426. setUpResponseFiles(C, Job);
  1427. C.ExecuteJobs(C.getJobs(), FailingCommands);
  1428. // If the command succeeded, we are done.
  1429. if (FailingCommands.empty())
  1430. return 0;
  1431. // Otherwise, remove result files and print extra information about abnormal
  1432. // failures.
  1433. int Res = 0;
  1434. for (const auto &CmdPair : FailingCommands) {
  1435. int CommandRes = CmdPair.first;
  1436. const Command *FailingCommand = CmdPair.second;
  1437. // Remove result files if we're not saving temps.
  1438. if (!isSaveTempsEnabled()) {
  1439. const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
  1440. C.CleanupFileMap(C.getResultFiles(), JA, true);
  1441. // Failure result files are valid unless we crashed.
  1442. if (CommandRes < 0)
  1443. C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
  1444. }
  1445. #if LLVM_ON_UNIX
  1446. // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
  1447. // for SIGPIPE. Do not print diagnostics for this case.
  1448. if (CommandRes == EX_IOERR) {
  1449. Res = CommandRes;
  1450. continue;
  1451. }
  1452. #endif
  1453. // Print extra information about abnormal failures, if possible.
  1454. //
  1455. // This is ad-hoc, but we don't want to be excessively noisy. If the result
  1456. // status was 1, assume the command failed normally. In particular, if it
  1457. // was the compiler then assume it gave a reasonable error code. Failures
  1458. // in other tools are less common, and they generally have worse
  1459. // diagnostics, so always print the diagnostic there.
  1460. const Tool &FailingTool = FailingCommand->getCreator();
  1461. if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
  1462. // FIXME: See FIXME above regarding result code interpretation.
  1463. if (CommandRes < 0)
  1464. Diag(clang::diag::err_drv_command_signalled)
  1465. << FailingTool.getShortName();
  1466. else
  1467. Diag(clang::diag::err_drv_command_failed)
  1468. << FailingTool.getShortName() << CommandRes;
  1469. }
  1470. }
  1471. return Res;
  1472. }
  1473. void Driver::PrintHelp(bool ShowHidden) const {
  1474. unsigned IncludedFlagsBitmask;
  1475. unsigned ExcludedFlagsBitmask;
  1476. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  1477. getIncludeExcludeOptionFlagMasks(IsCLMode());
  1478. ExcludedFlagsBitmask |= options::NoDriverOption;
  1479. if (!ShowHidden)
  1480. ExcludedFlagsBitmask |= HelpHidden;
  1481. if (IsFlangMode())
  1482. IncludedFlagsBitmask |= options::FlangOption;
  1483. else
  1484. ExcludedFlagsBitmask |= options::FlangOnlyOption;
  1485. std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
  1486. getOpts().printHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
  1487. IncludedFlagsBitmask, ExcludedFlagsBitmask,
  1488. /*ShowAllAliases=*/false);
  1489. }
  1490. void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
  1491. if (IsFlangMode()) {
  1492. OS << getClangToolFullVersion("flang-new") << '\n';
  1493. } else {
  1494. // FIXME: The following handlers should use a callback mechanism, we don't
  1495. // know what the client would like to do.
  1496. OS << getClangFullVersion() << '\n';
  1497. }
  1498. const ToolChain &TC = C.getDefaultToolChain();
  1499. OS << "Target: " << TC.getTripleString() << '\n';
  1500. // Print the threading model.
  1501. if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
  1502. // Don't print if the ToolChain would have barfed on it already
  1503. if (TC.isThreadModelSupported(A->getValue()))
  1504. OS << "Thread model: " << A->getValue();
  1505. } else
  1506. OS << "Thread model: " << TC.getThreadModel();
  1507. OS << '\n';
  1508. // Print out the install directory.
  1509. OS << "InstalledDir: " << InstalledDir << '\n';
  1510. // If configuration file was used, print its path.
  1511. if (!ConfigFile.empty())
  1512. OS << "Configuration file: " << ConfigFile << '\n';
  1513. }
  1514. /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
  1515. /// option.
  1516. static void PrintDiagnosticCategories(raw_ostream &OS) {
  1517. // Skip the empty category.
  1518. for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
  1519. ++i)
  1520. OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
  1521. }
  1522. void Driver::HandleAutocompletions(StringRef PassedFlags) const {
  1523. if (PassedFlags == "")
  1524. return;
  1525. // Print out all options that start with a given argument. This is used for
  1526. // shell autocompletion.
  1527. std::vector<std::string> SuggestedCompletions;
  1528. std::vector<std::string> Flags;
  1529. unsigned int DisableFlags =
  1530. options::NoDriverOption | options::Unsupported | options::Ignored;
  1531. // Make sure that Flang-only options don't pollute the Clang output
  1532. // TODO: Make sure that Clang-only options don't pollute Flang output
  1533. if (!IsFlangMode())
  1534. DisableFlags |= options::FlangOnlyOption;
  1535. // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
  1536. // because the latter indicates that the user put space before pushing tab
  1537. // which should end up in a file completion.
  1538. const bool HasSpace = PassedFlags.endswith(",");
  1539. // Parse PassedFlags by "," as all the command-line flags are passed to this
  1540. // function separated by ","
  1541. StringRef TargetFlags = PassedFlags;
  1542. while (TargetFlags != "") {
  1543. StringRef CurFlag;
  1544. std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
  1545. Flags.push_back(std::string(CurFlag));
  1546. }
  1547. // We want to show cc1-only options only when clang is invoked with -cc1 or
  1548. // -Xclang.
  1549. if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
  1550. DisableFlags &= ~options::NoDriverOption;
  1551. const llvm::opt::OptTable &Opts = getOpts();
  1552. StringRef Cur;
  1553. Cur = Flags.at(Flags.size() - 1);
  1554. StringRef Prev;
  1555. if (Flags.size() >= 2) {
  1556. Prev = Flags.at(Flags.size() - 2);
  1557. SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
  1558. }
  1559. if (SuggestedCompletions.empty())
  1560. SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
  1561. // If Flags were empty, it means the user typed `clang [tab]` where we should
  1562. // list all possible flags. If there was no value completion and the user
  1563. // pressed tab after a space, we should fall back to a file completion.
  1564. // We're printing a newline to be consistent with what we print at the end of
  1565. // this function.
  1566. if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
  1567. llvm::outs() << '\n';
  1568. return;
  1569. }
  1570. // When flag ends with '=' and there was no value completion, return empty
  1571. // string and fall back to the file autocompletion.
  1572. if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
  1573. // If the flag is in the form of "--autocomplete=-foo",
  1574. // we were requested to print out all option names that start with "-foo".
  1575. // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
  1576. SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
  1577. // We have to query the -W flags manually as they're not in the OptTable.
  1578. // TODO: Find a good way to add them to OptTable instead and them remove
  1579. // this code.
  1580. for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
  1581. if (S.startswith(Cur))
  1582. SuggestedCompletions.push_back(std::string(S));
  1583. }
  1584. // Sort the autocomplete candidates so that shells print them out in a
  1585. // deterministic order. We could sort in any way, but we chose
  1586. // case-insensitive sorting for consistency with the -help option
  1587. // which prints out options in the case-insensitive alphabetical order.
  1588. llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
  1589. if (int X = A.compare_insensitive(B))
  1590. return X < 0;
  1591. return A.compare(B) > 0;
  1592. });
  1593. llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
  1594. }
  1595. bool Driver::HandleImmediateArgs(const Compilation &C) {
  1596. // The order these options are handled in gcc is all over the place, but we
  1597. // don't expect inconsistencies w.r.t. that to matter in practice.
  1598. if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
  1599. llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
  1600. return false;
  1601. }
  1602. if (C.getArgs().hasArg(options::OPT_dumpversion)) {
  1603. // Since -dumpversion is only implemented for pedantic GCC compatibility, we
  1604. // return an answer which matches our definition of __VERSION__.
  1605. llvm::outs() << CLANG_VERSION_STRING << "\n";
  1606. return false;
  1607. }
  1608. if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
  1609. PrintDiagnosticCategories(llvm::outs());
  1610. return false;
  1611. }
  1612. if (C.getArgs().hasArg(options::OPT_help) ||
  1613. C.getArgs().hasArg(options::OPT__help_hidden)) {
  1614. PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
  1615. return false;
  1616. }
  1617. if (C.getArgs().hasArg(options::OPT__version)) {
  1618. // Follow gcc behavior and use stdout for --version and stderr for -v.
  1619. PrintVersion(C, llvm::outs());
  1620. return false;
  1621. }
  1622. if (C.getArgs().hasArg(options::OPT_v) ||
  1623. C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
  1624. C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
  1625. PrintVersion(C, llvm::errs());
  1626. SuppressMissingInputWarning = true;
  1627. }
  1628. if (C.getArgs().hasArg(options::OPT_v)) {
  1629. if (!SystemConfigDir.empty())
  1630. llvm::errs() << "System configuration file directory: "
  1631. << SystemConfigDir << "\n";
  1632. if (!UserConfigDir.empty())
  1633. llvm::errs() << "User configuration file directory: "
  1634. << UserConfigDir << "\n";
  1635. }
  1636. const ToolChain &TC = C.getDefaultToolChain();
  1637. if (C.getArgs().hasArg(options::OPT_v))
  1638. TC.printVerboseInfo(llvm::errs());
  1639. if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
  1640. llvm::outs() << ResourceDir << '\n';
  1641. return false;
  1642. }
  1643. if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
  1644. llvm::outs() << "programs: =";
  1645. bool separator = false;
  1646. // Print -B and COMPILER_PATH.
  1647. for (const std::string &Path : PrefixDirs) {
  1648. if (separator)
  1649. llvm::outs() << llvm::sys::EnvPathSeparator;
  1650. llvm::outs() << Path;
  1651. separator = true;
  1652. }
  1653. for (const std::string &Path : TC.getProgramPaths()) {
  1654. if (separator)
  1655. llvm::outs() << llvm::sys::EnvPathSeparator;
  1656. llvm::outs() << Path;
  1657. separator = true;
  1658. }
  1659. llvm::outs() << "\n";
  1660. llvm::outs() << "libraries: =" << ResourceDir;
  1661. StringRef sysroot = C.getSysRoot();
  1662. for (const std::string &Path : TC.getFilePaths()) {
  1663. // Always print a separator. ResourceDir was the first item shown.
  1664. llvm::outs() << llvm::sys::EnvPathSeparator;
  1665. // Interpretation of leading '=' is needed only for NetBSD.
  1666. if (Path[0] == '=')
  1667. llvm::outs() << sysroot << Path.substr(1);
  1668. else
  1669. llvm::outs() << Path;
  1670. }
  1671. llvm::outs() << "\n";
  1672. return false;
  1673. }
  1674. if (C.getArgs().hasArg(options::OPT_print_runtime_dir)) {
  1675. std::string RuntimePath;
  1676. // Get the first existing path, if any.
  1677. for (auto Path : TC.getRuntimePaths()) {
  1678. if (getVFS().exists(Path)) {
  1679. RuntimePath = Path;
  1680. break;
  1681. }
  1682. }
  1683. if (!RuntimePath.empty())
  1684. llvm::outs() << RuntimePath << '\n';
  1685. else
  1686. llvm::outs() << TC.getCompilerRTPath() << '\n';
  1687. return false;
  1688. }
  1689. // FIXME: The following handlers should use a callback mechanism, we don't
  1690. // know what the client would like to do.
  1691. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
  1692. llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
  1693. return false;
  1694. }
  1695. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
  1696. StringRef ProgName = A->getValue();
  1697. // Null program name cannot have a path.
  1698. if (! ProgName.empty())
  1699. llvm::outs() << GetProgramPath(ProgName, TC);
  1700. llvm::outs() << "\n";
  1701. return false;
  1702. }
  1703. if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
  1704. StringRef PassedFlags = A->getValue();
  1705. HandleAutocompletions(PassedFlags);
  1706. return false;
  1707. }
  1708. if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
  1709. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
  1710. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
  1711. RegisterEffectiveTriple TripleRAII(TC, Triple);
  1712. switch (RLT) {
  1713. case ToolChain::RLT_CompilerRT:
  1714. llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
  1715. break;
  1716. case ToolChain::RLT_Libgcc:
  1717. llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
  1718. break;
  1719. }
  1720. return false;
  1721. }
  1722. if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
  1723. for (const Multilib &Multilib : TC.getMultilibs())
  1724. llvm::outs() << Multilib << "\n";
  1725. return false;
  1726. }
  1727. if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
  1728. const Multilib &Multilib = TC.getMultilib();
  1729. if (Multilib.gccSuffix().empty())
  1730. llvm::outs() << ".\n";
  1731. else {
  1732. StringRef Suffix(Multilib.gccSuffix());
  1733. assert(Suffix.front() == '/');
  1734. llvm::outs() << Suffix.substr(1) << "\n";
  1735. }
  1736. return false;
  1737. }
  1738. if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
  1739. llvm::outs() << TC.getTripleString() << "\n";
  1740. return false;
  1741. }
  1742. if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
  1743. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
  1744. llvm::outs() << Triple.getTriple() << "\n";
  1745. return false;
  1746. }
  1747. if (C.getArgs().hasArg(options::OPT_print_multiarch)) {
  1748. llvm::outs() << TC.getMultiarchTriple(*this, TC.getTriple(), SysRoot)
  1749. << "\n";
  1750. return false;
  1751. }
  1752. if (C.getArgs().hasArg(options::OPT_print_targets)) {
  1753. llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
  1754. return false;
  1755. }
  1756. return true;
  1757. }
  1758. enum {
  1759. TopLevelAction = 0,
  1760. HeadSibAction = 1,
  1761. OtherSibAction = 2,
  1762. };
  1763. // Display an action graph human-readably. Action A is the "sink" node
  1764. // and latest-occuring action. Traversal is in pre-order, visiting the
  1765. // inputs to each action before printing the action itself.
  1766. static unsigned PrintActions1(const Compilation &C, Action *A,
  1767. std::map<Action *, unsigned> &Ids,
  1768. Twine Indent = {}, int Kind = TopLevelAction) {
  1769. if (Ids.count(A)) // A was already visited.
  1770. return Ids[A];
  1771. std::string str;
  1772. llvm::raw_string_ostream os(str);
  1773. auto getSibIndent = [](int K) -> Twine {
  1774. return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
  1775. };
  1776. Twine SibIndent = Indent + getSibIndent(Kind);
  1777. int SibKind = HeadSibAction;
  1778. os << Action::getClassName(A->getKind()) << ", ";
  1779. if (InputAction *IA = dyn_cast<InputAction>(A)) {
  1780. os << "\"" << IA->getInputArg().getValue() << "\"";
  1781. } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
  1782. os << '"' << BIA->getArchName() << '"' << ", {"
  1783. << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
  1784. } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
  1785. bool IsFirst = true;
  1786. OA->doOnEachDependence(
  1787. [&](Action *A, const ToolChain *TC, const char *BoundArch) {
  1788. assert(TC && "Unknown host toolchain");
  1789. // E.g. for two CUDA device dependences whose bound arch is sm_20 and
  1790. // sm_35 this will generate:
  1791. // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
  1792. // (nvptx64-nvidia-cuda:sm_35) {#ID}
  1793. if (!IsFirst)
  1794. os << ", ";
  1795. os << '"';
  1796. os << A->getOffloadingKindPrefix();
  1797. os << " (";
  1798. os << TC->getTriple().normalize();
  1799. if (BoundArch)
  1800. os << ":" << BoundArch;
  1801. os << ")";
  1802. os << '"';
  1803. os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
  1804. IsFirst = false;
  1805. SibKind = OtherSibAction;
  1806. });
  1807. } else {
  1808. const ActionList *AL = &A->getInputs();
  1809. if (AL->size()) {
  1810. const char *Prefix = "{";
  1811. for (Action *PreRequisite : *AL) {
  1812. os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
  1813. Prefix = ", ";
  1814. SibKind = OtherSibAction;
  1815. }
  1816. os << "}";
  1817. } else
  1818. os << "{}";
  1819. }
  1820. // Append offload info for all options other than the offloading action
  1821. // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
  1822. std::string offload_str;
  1823. llvm::raw_string_ostream offload_os(offload_str);
  1824. if (!isa<OffloadAction>(A)) {
  1825. auto S = A->getOffloadingKindPrefix();
  1826. if (!S.empty()) {
  1827. offload_os << ", (" << S;
  1828. if (A->getOffloadingArch())
  1829. offload_os << ", " << A->getOffloadingArch();
  1830. offload_os << ")";
  1831. }
  1832. }
  1833. auto getSelfIndent = [](int K) -> Twine {
  1834. return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
  1835. };
  1836. unsigned Id = Ids.size();
  1837. Ids[A] = Id;
  1838. llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
  1839. << types::getTypeName(A->getType()) << offload_os.str() << "\n";
  1840. return Id;
  1841. }
  1842. // Print the action graphs in a compilation C.
  1843. // For example "clang -c file1.c file2.c" is composed of two subgraphs.
  1844. void Driver::PrintActions(const Compilation &C) const {
  1845. std::map<Action *, unsigned> Ids;
  1846. for (Action *A : C.getActions())
  1847. PrintActions1(C, A, Ids);
  1848. }
  1849. /// Check whether the given input tree contains any compilation or
  1850. /// assembly actions.
  1851. static bool ContainsCompileOrAssembleAction(const Action *A) {
  1852. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
  1853. isa<AssembleJobAction>(A))
  1854. return true;
  1855. return llvm::any_of(A->inputs(), ContainsCompileOrAssembleAction);
  1856. }
  1857. void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
  1858. const InputList &BAInputs) const {
  1859. DerivedArgList &Args = C.getArgs();
  1860. ActionList &Actions = C.getActions();
  1861. llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
  1862. // Collect the list of architectures. Duplicates are allowed, but should only
  1863. // be handled once (in the order seen).
  1864. llvm::StringSet<> ArchNames;
  1865. SmallVector<const char *, 4> Archs;
  1866. for (Arg *A : Args) {
  1867. if (A->getOption().matches(options::OPT_arch)) {
  1868. // Validate the option here; we don't save the type here because its
  1869. // particular spelling may participate in other driver choices.
  1870. llvm::Triple::ArchType Arch =
  1871. tools::darwin::getArchTypeForMachOArchName(A->getValue());
  1872. if (Arch == llvm::Triple::UnknownArch) {
  1873. Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
  1874. continue;
  1875. }
  1876. A->claim();
  1877. if (ArchNames.insert(A->getValue()).second)
  1878. Archs.push_back(A->getValue());
  1879. }
  1880. }
  1881. // When there is no explicit arch for this platform, make sure we still bind
  1882. // the architecture (to the default) so that -Xarch_ is handled correctly.
  1883. if (!Archs.size())
  1884. Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
  1885. ActionList SingleActions;
  1886. BuildActions(C, Args, BAInputs, SingleActions);
  1887. // Add in arch bindings for every top level action, as well as lipo and
  1888. // dsymutil steps if needed.
  1889. for (Action* Act : SingleActions) {
  1890. // Make sure we can lipo this kind of output. If not (and it is an actual
  1891. // output) then we disallow, since we can't create an output file with the
  1892. // right name without overwriting it. We could remove this oddity by just
  1893. // changing the output names to include the arch, which would also fix
  1894. // -save-temps. Compatibility wins for now.
  1895. if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
  1896. Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
  1897. << types::getTypeName(Act->getType());
  1898. ActionList Inputs;
  1899. for (unsigned i = 0, e = Archs.size(); i != e; ++i)
  1900. Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
  1901. // Lipo if necessary, we do it this way because we need to set the arch flag
  1902. // so that -Xarch_ gets overwritten.
  1903. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
  1904. Actions.append(Inputs.begin(), Inputs.end());
  1905. else
  1906. Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
  1907. // Handle debug info queries.
  1908. Arg *A = Args.getLastArg(options::OPT_g_Group);
  1909. bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
  1910. !A->getOption().matches(options::OPT_gstabs);
  1911. if ((enablesDebugInfo || willEmitRemarks(Args)) &&
  1912. ContainsCompileOrAssembleAction(Actions.back())) {
  1913. // Add a 'dsymutil' step if necessary, when debug info is enabled and we
  1914. // have a compile input. We need to run 'dsymutil' ourselves in such cases
  1915. // because the debug info will refer to a temporary object file which
  1916. // will be removed at the end of the compilation process.
  1917. if (Act->getType() == types::TY_Image) {
  1918. ActionList Inputs;
  1919. Inputs.push_back(Actions.back());
  1920. Actions.pop_back();
  1921. Actions.push_back(
  1922. C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
  1923. }
  1924. // Verify the debug info output.
  1925. if (Args.hasArg(options::OPT_verify_debug_info)) {
  1926. Action* LastAction = Actions.back();
  1927. Actions.pop_back();
  1928. Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
  1929. LastAction, types::TY_Nothing));
  1930. }
  1931. }
  1932. }
  1933. }
  1934. bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
  1935. types::ID Ty, bool TypoCorrect) const {
  1936. if (!getCheckInputsExist())
  1937. return true;
  1938. // stdin always exists.
  1939. if (Value == "-")
  1940. return true;
  1941. if (getVFS().exists(Value))
  1942. return true;
  1943. if (TypoCorrect) {
  1944. // Check if the filename is a typo for an option flag. OptTable thinks
  1945. // that all args that are not known options and that start with / are
  1946. // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
  1947. // the option `/diagnostics:caret` than a reference to a file in the root
  1948. // directory.
  1949. unsigned IncludedFlagsBitmask;
  1950. unsigned ExcludedFlagsBitmask;
  1951. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  1952. getIncludeExcludeOptionFlagMasks(IsCLMode());
  1953. std::string Nearest;
  1954. if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
  1955. ExcludedFlagsBitmask) <= 1) {
  1956. Diag(clang::diag::err_drv_no_such_file_with_suggestion)
  1957. << Value << Nearest;
  1958. return false;
  1959. }
  1960. }
  1961. // In CL mode, don't error on apparently non-existent linker inputs, because
  1962. // they can be influenced by linker flags the clang driver might not
  1963. // understand.
  1964. // Examples:
  1965. // - `clang-cl main.cc ole32.lib` in a a non-MSVC shell will make the driver
  1966. // module look for an MSVC installation in the registry. (We could ask
  1967. // the MSVCToolChain object if it can find `ole32.lib`, but the logic to
  1968. // look in the registry might move into lld-link in the future so that
  1969. // lld-link invocations in non-MSVC shells just work too.)
  1970. // - `clang-cl ... /link ...` can pass arbitrary flags to the linker,
  1971. // including /libpath:, which is used to find .lib and .obj files.
  1972. // So do not diagnose this on the driver level. Rely on the linker diagnosing
  1973. // it. (If we don't end up invoking the linker, this means we'll emit a
  1974. // "'linker' input unused [-Wunused-command-line-argument]" warning instead
  1975. // of an error.)
  1976. //
  1977. // Only do this skip after the typo correction step above. `/Brepo` is treated
  1978. // as TY_Object, but it's clearly a typo for `/Brepro`. It seems fine to emit
  1979. // an error if we have a flag that's within an edit distance of 1 from a
  1980. // flag. (Users can use `-Wl,` or `/linker` to launder the flag past the
  1981. // driver in the unlikely case they run into this.)
  1982. //
  1983. // Don't do this for inputs that start with a '/', else we'd pass options
  1984. // like /libpath: through to the linker silently.
  1985. //
  1986. // Emitting an error for linker inputs can also cause incorrect diagnostics
  1987. // with the gcc driver. The command
  1988. // clang -fuse-ld=lld -Wl,--chroot,some/dir /file.o
  1989. // will make lld look for some/dir/file.o, while we will diagnose here that
  1990. // `/file.o` does not exist. However, configure scripts check if
  1991. // `clang /GR-` compiles without error to see if the compiler is cl.exe,
  1992. // so we can't downgrade diagnostics for `/GR-` from an error to a warning
  1993. // in cc mode. (We can in cl mode because cl.exe itself only warns on
  1994. // unknown flags.)
  1995. if (IsCLMode() && Ty == types::TY_Object && !Value.startswith("/"))
  1996. return true;
  1997. Diag(clang::diag::err_drv_no_such_file) << Value;
  1998. return false;
  1999. }
  2000. // Construct a the list of inputs and their types.
  2001. void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
  2002. InputList &Inputs) const {
  2003. const llvm::opt::OptTable &Opts = getOpts();
  2004. // Track the current user specified (-x) input. We also explicitly track the
  2005. // argument used to set the type; we only want to claim the type when we
  2006. // actually use it, so we warn about unused -x arguments.
  2007. types::ID InputType = types::TY_Nothing;
  2008. Arg *InputTypeArg = nullptr;
  2009. // The last /TC or /TP option sets the input type to C or C++ globally.
  2010. if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
  2011. options::OPT__SLASH_TP)) {
  2012. InputTypeArg = TCTP;
  2013. InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
  2014. ? types::TY_C
  2015. : types::TY_CXX;
  2016. Arg *Previous = nullptr;
  2017. bool ShowNote = false;
  2018. for (Arg *A :
  2019. Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
  2020. if (Previous) {
  2021. Diag(clang::diag::warn_drv_overriding_flag_option)
  2022. << Previous->getSpelling() << A->getSpelling();
  2023. ShowNote = true;
  2024. }
  2025. Previous = A;
  2026. }
  2027. if (ShowNote)
  2028. Diag(clang::diag::note_drv_t_option_is_global);
  2029. // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
  2030. assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
  2031. }
  2032. for (Arg *A : Args) {
  2033. if (A->getOption().getKind() == Option::InputClass) {
  2034. const char *Value = A->getValue();
  2035. types::ID Ty = types::TY_INVALID;
  2036. // Infer the input type if necessary.
  2037. if (InputType == types::TY_Nothing) {
  2038. // If there was an explicit arg for this, claim it.
  2039. if (InputTypeArg)
  2040. InputTypeArg->claim();
  2041. // stdin must be handled specially.
  2042. if (memcmp(Value, "-", 2) == 0) {
  2043. if (IsFlangMode()) {
  2044. Ty = types::TY_Fortran;
  2045. } else {
  2046. // If running with -E, treat as a C input (this changes the
  2047. // builtin macros, for example). This may be overridden by -ObjC
  2048. // below.
  2049. //
  2050. // Otherwise emit an error but still use a valid type to avoid
  2051. // spurious errors (e.g., no inputs).
  2052. assert(!CCGenDiagnostics && "stdin produces no crash reproducer");
  2053. if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
  2054. Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
  2055. : clang::diag::err_drv_unknown_stdin_type);
  2056. Ty = types::TY_C;
  2057. }
  2058. } else {
  2059. // Otherwise lookup by extension.
  2060. // Fallback is C if invoked as C preprocessor, C++ if invoked with
  2061. // clang-cl /E, or Object otherwise.
  2062. // We use a host hook here because Darwin at least has its own
  2063. // idea of what .s is.
  2064. if (const char *Ext = strrchr(Value, '.'))
  2065. Ty = TC.LookupTypeForExtension(Ext + 1);
  2066. if (Ty == types::TY_INVALID) {
  2067. if (IsCLMode() && (Args.hasArgNoClaim(options::OPT_E) || CCGenDiagnostics))
  2068. Ty = types::TY_CXX;
  2069. else if (CCCIsCPP() || CCGenDiagnostics)
  2070. Ty = types::TY_C;
  2071. else
  2072. Ty = types::TY_Object;
  2073. }
  2074. // If the driver is invoked as C++ compiler (like clang++ or c++) it
  2075. // should autodetect some input files as C++ for g++ compatibility.
  2076. if (CCCIsCXX()) {
  2077. types::ID OldTy = Ty;
  2078. Ty = types::lookupCXXTypeForCType(Ty);
  2079. if (Ty != OldTy)
  2080. Diag(clang::diag::warn_drv_treating_input_as_cxx)
  2081. << getTypeName(OldTy) << getTypeName(Ty);
  2082. }
  2083. // If running with -fthinlto-index=, extensions that normally identify
  2084. // native object files actually identify LLVM bitcode files.
  2085. if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
  2086. Ty == types::TY_Object)
  2087. Ty = types::TY_LLVM_BC;
  2088. }
  2089. // -ObjC and -ObjC++ override the default language, but only for "source
  2090. // files". We just treat everything that isn't a linker input as a
  2091. // source file.
  2092. //
  2093. // FIXME: Clean this up if we move the phase sequence into the type.
  2094. if (Ty != types::TY_Object) {
  2095. if (Args.hasArg(options::OPT_ObjC))
  2096. Ty = types::TY_ObjC;
  2097. else if (Args.hasArg(options::OPT_ObjCXX))
  2098. Ty = types::TY_ObjCXX;
  2099. }
  2100. } else {
  2101. assert(InputTypeArg && "InputType set w/o InputTypeArg");
  2102. if (!InputTypeArg->getOption().matches(options::OPT_x)) {
  2103. // If emulating cl.exe, make sure that /TC and /TP don't affect input
  2104. // object files.
  2105. const char *Ext = strrchr(Value, '.');
  2106. if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
  2107. Ty = types::TY_Object;
  2108. }
  2109. if (Ty == types::TY_INVALID) {
  2110. Ty = InputType;
  2111. InputTypeArg->claim();
  2112. }
  2113. }
  2114. if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
  2115. Inputs.push_back(std::make_pair(Ty, A));
  2116. } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
  2117. StringRef Value = A->getValue();
  2118. if (DiagnoseInputExistence(Args, Value, types::TY_C,
  2119. /*TypoCorrect=*/false)) {
  2120. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  2121. Inputs.push_back(std::make_pair(types::TY_C, InputArg));
  2122. }
  2123. A->claim();
  2124. } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
  2125. StringRef Value = A->getValue();
  2126. if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
  2127. /*TypoCorrect=*/false)) {
  2128. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  2129. Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
  2130. }
  2131. A->claim();
  2132. } else if (A->getOption().hasFlag(options::LinkerInput)) {
  2133. // Just treat as object type, we could make a special type for this if
  2134. // necessary.
  2135. Inputs.push_back(std::make_pair(types::TY_Object, A));
  2136. } else if (A->getOption().matches(options::OPT_x)) {
  2137. InputTypeArg = A;
  2138. InputType = types::lookupTypeForTypeSpecifier(A->getValue());
  2139. A->claim();
  2140. // Follow gcc behavior and treat as linker input for invalid -x
  2141. // options. Its not clear why we shouldn't just revert to unknown; but
  2142. // this isn't very important, we might as well be bug compatible.
  2143. if (!InputType) {
  2144. Diag(clang::diag::err_drv_unknown_language) << A->getValue();
  2145. InputType = types::TY_Object;
  2146. }
  2147. } else if (A->getOption().getID() == options::OPT_U) {
  2148. assert(A->getNumValues() == 1 && "The /U option has one value.");
  2149. StringRef Val = A->getValue(0);
  2150. if (Val.find_first_of("/\\") != StringRef::npos) {
  2151. // Warn about e.g. "/Users/me/myfile.c".
  2152. Diag(diag::warn_slash_u_filename) << Val;
  2153. Diag(diag::note_use_dashdash);
  2154. }
  2155. }
  2156. }
  2157. if (CCCIsCPP() && Inputs.empty()) {
  2158. // If called as standalone preprocessor, stdin is processed
  2159. // if no other input is present.
  2160. Arg *A = MakeInputArg(Args, Opts, "-");
  2161. Inputs.push_back(std::make_pair(types::TY_C, A));
  2162. }
  2163. }
  2164. namespace {
  2165. /// Provides a convenient interface for different programming models to generate
  2166. /// the required device actions.
  2167. class OffloadingActionBuilder final {
  2168. /// Flag used to trace errors in the builder.
  2169. bool IsValid = false;
  2170. /// The compilation that is using this builder.
  2171. Compilation &C;
  2172. /// Map between an input argument and the offload kinds used to process it.
  2173. std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
  2174. /// Builder interface. It doesn't build anything or keep any state.
  2175. class DeviceActionBuilder {
  2176. public:
  2177. typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
  2178. enum ActionBuilderReturnCode {
  2179. // The builder acted successfully on the current action.
  2180. ABRT_Success,
  2181. // The builder didn't have to act on the current action.
  2182. ABRT_Inactive,
  2183. // The builder was successful and requested the host action to not be
  2184. // generated.
  2185. ABRT_Ignore_Host,
  2186. };
  2187. protected:
  2188. /// Compilation associated with this builder.
  2189. Compilation &C;
  2190. /// Tool chains associated with this builder. The same programming
  2191. /// model may have associated one or more tool chains.
  2192. SmallVector<const ToolChain *, 2> ToolChains;
  2193. /// The derived arguments associated with this builder.
  2194. DerivedArgList &Args;
  2195. /// The inputs associated with this builder.
  2196. const Driver::InputList &Inputs;
  2197. /// The associated offload kind.
  2198. Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
  2199. public:
  2200. DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
  2201. const Driver::InputList &Inputs,
  2202. Action::OffloadKind AssociatedOffloadKind)
  2203. : C(C), Args(Args), Inputs(Inputs),
  2204. AssociatedOffloadKind(AssociatedOffloadKind) {}
  2205. virtual ~DeviceActionBuilder() {}
  2206. /// Fill up the array \a DA with all the device dependences that should be
  2207. /// added to the provided host action \a HostAction. By default it is
  2208. /// inactive.
  2209. virtual ActionBuilderReturnCode
  2210. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  2211. phases::ID CurPhase, phases::ID FinalPhase,
  2212. PhasesTy &Phases) {
  2213. return ABRT_Inactive;
  2214. }
  2215. /// Update the state to include the provided host action \a HostAction as a
  2216. /// dependency of the current device action. By default it is inactive.
  2217. virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
  2218. return ABRT_Inactive;
  2219. }
  2220. /// Append top level actions generated by the builder.
  2221. virtual void appendTopLevelActions(ActionList &AL) {}
  2222. /// Append linker device actions generated by the builder.
  2223. virtual void appendLinkDeviceActions(ActionList &AL) {}
  2224. /// Append linker host action generated by the builder.
  2225. virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
  2226. /// Append linker actions generated by the builder.
  2227. virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
  2228. /// Initialize the builder. Return true if any initialization errors are
  2229. /// found.
  2230. virtual bool initialize() { return false; }
  2231. /// Return true if the builder can use bundling/unbundling.
  2232. virtual bool canUseBundlerUnbundler() const { return false; }
  2233. /// Return true if this builder is valid. We have a valid builder if we have
  2234. /// associated device tool chains.
  2235. bool isValid() { return !ToolChains.empty(); }
  2236. /// Return the associated offload kind.
  2237. Action::OffloadKind getAssociatedOffloadKind() {
  2238. return AssociatedOffloadKind;
  2239. }
  2240. };
  2241. /// Base class for CUDA/HIP action builder. It injects device code in
  2242. /// the host backend action.
  2243. class CudaActionBuilderBase : public DeviceActionBuilder {
  2244. protected:
  2245. /// Flags to signal if the user requested host-only or device-only
  2246. /// compilation.
  2247. bool CompileHostOnly = false;
  2248. bool CompileDeviceOnly = false;
  2249. bool EmitLLVM = false;
  2250. bool EmitAsm = false;
  2251. /// ID to identify each device compilation. For CUDA it is simply the
  2252. /// GPU arch string. For HIP it is either the GPU arch string or GPU
  2253. /// arch string plus feature strings delimited by a plus sign, e.g.
  2254. /// gfx906+xnack.
  2255. struct TargetID {
  2256. /// Target ID string which is persistent throughout the compilation.
  2257. const char *ID;
  2258. TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
  2259. TargetID(const char *ID) : ID(ID) {}
  2260. operator const char *() { return ID; }
  2261. operator StringRef() { return StringRef(ID); }
  2262. };
  2263. /// List of GPU architectures to use in this compilation.
  2264. SmallVector<TargetID, 4> GpuArchList;
  2265. /// The CUDA actions for the current input.
  2266. ActionList CudaDeviceActions;
  2267. /// The CUDA fat binary if it was generated for the current input.
  2268. Action *CudaFatBinary = nullptr;
  2269. /// Flag that is set to true if this builder acted on the current input.
  2270. bool IsActive = false;
  2271. /// Flag for -fgpu-rdc.
  2272. bool Relocatable = false;
  2273. /// Default GPU architecture if there's no one specified.
  2274. CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
  2275. /// Method to generate compilation unit ID specified by option
  2276. /// '-fuse-cuid='.
  2277. enum UseCUIDKind { CUID_Hash, CUID_Random, CUID_None, CUID_Invalid };
  2278. UseCUIDKind UseCUID = CUID_Hash;
  2279. /// Compilation unit ID specified by option '-cuid='.
  2280. StringRef FixedCUID;
  2281. public:
  2282. CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
  2283. const Driver::InputList &Inputs,
  2284. Action::OffloadKind OFKind)
  2285. : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
  2286. ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
  2287. // While generating code for CUDA, we only depend on the host input action
  2288. // to trigger the creation of all the CUDA device actions.
  2289. // If we are dealing with an input action, replicate it for each GPU
  2290. // architecture. If we are in host-only mode we return 'success' so that
  2291. // the host uses the CUDA offload kind.
  2292. if (auto *IA = dyn_cast<InputAction>(HostAction)) {
  2293. assert(!GpuArchList.empty() &&
  2294. "We should have at least one GPU architecture.");
  2295. // If the host input is not CUDA or HIP, we don't need to bother about
  2296. // this input.
  2297. if (!(IA->getType() == types::TY_CUDA ||
  2298. IA->getType() == types::TY_HIP ||
  2299. IA->getType() == types::TY_PP_HIP)) {
  2300. // The builder will ignore this input.
  2301. IsActive = false;
  2302. return ABRT_Inactive;
  2303. }
  2304. // Set the flag to true, so that the builder acts on the current input.
  2305. IsActive = true;
  2306. if (CompileHostOnly)
  2307. return ABRT_Success;
  2308. // Replicate inputs for each GPU architecture.
  2309. auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
  2310. : types::TY_CUDA_DEVICE;
  2311. std::string CUID = FixedCUID.str();
  2312. if (CUID.empty()) {
  2313. if (UseCUID == CUID_Random)
  2314. CUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
  2315. /*LowerCase=*/true);
  2316. else if (UseCUID == CUID_Hash) {
  2317. llvm::MD5 Hasher;
  2318. llvm::MD5::MD5Result Hash;
  2319. SmallString<256> RealPath;
  2320. llvm::sys::fs::real_path(IA->getInputArg().getValue(), RealPath,
  2321. /*expand_tilde=*/true);
  2322. Hasher.update(RealPath);
  2323. for (auto *A : Args) {
  2324. if (A->getOption().matches(options::OPT_INPUT))
  2325. continue;
  2326. Hasher.update(A->getAsString(Args));
  2327. }
  2328. Hasher.final(Hash);
  2329. CUID = llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
  2330. }
  2331. }
  2332. IA->setId(CUID);
  2333. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  2334. CudaDeviceActions.push_back(
  2335. C.MakeAction<InputAction>(IA->getInputArg(), Ty, IA->getId()));
  2336. }
  2337. return ABRT_Success;
  2338. }
  2339. // If this is an unbundling action use it as is for each CUDA toolchain.
  2340. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
  2341. // If -fgpu-rdc is disabled, should not unbundle since there is no
  2342. // device code to link.
  2343. if (UA->getType() == types::TY_Object && !Relocatable)
  2344. return ABRT_Inactive;
  2345. CudaDeviceActions.clear();
  2346. auto *IA = cast<InputAction>(UA->getInputs().back());
  2347. std::string FileName = IA->getInputArg().getAsString(Args);
  2348. // Check if the type of the file is the same as the action. Do not
  2349. // unbundle it if it is not. Do not unbundle .so files, for example,
  2350. // which are not object files.
  2351. if (IA->getType() == types::TY_Object &&
  2352. (!llvm::sys::path::has_extension(FileName) ||
  2353. types::lookupTypeForExtension(
  2354. llvm::sys::path::extension(FileName).drop_front()) !=
  2355. types::TY_Object))
  2356. return ABRT_Inactive;
  2357. for (auto Arch : GpuArchList) {
  2358. CudaDeviceActions.push_back(UA);
  2359. UA->registerDependentActionInfo(ToolChains[0], Arch,
  2360. AssociatedOffloadKind);
  2361. }
  2362. return ABRT_Success;
  2363. }
  2364. return IsActive ? ABRT_Success : ABRT_Inactive;
  2365. }
  2366. void appendTopLevelActions(ActionList &AL) override {
  2367. // Utility to append actions to the top level list.
  2368. auto AddTopLevel = [&](Action *A, TargetID TargetID) {
  2369. OffloadAction::DeviceDependences Dep;
  2370. Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
  2371. AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
  2372. };
  2373. // If we have a fat binary, add it to the list.
  2374. if (CudaFatBinary) {
  2375. AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
  2376. CudaDeviceActions.clear();
  2377. CudaFatBinary = nullptr;
  2378. return;
  2379. }
  2380. if (CudaDeviceActions.empty())
  2381. return;
  2382. // If we have CUDA actions at this point, that's because we have a have
  2383. // partial compilation, so we should have an action for each GPU
  2384. // architecture.
  2385. assert(CudaDeviceActions.size() == GpuArchList.size() &&
  2386. "Expecting one action per GPU architecture.");
  2387. assert(ToolChains.size() == 1 &&
  2388. "Expecting to have a single CUDA toolchain.");
  2389. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
  2390. AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
  2391. CudaDeviceActions.clear();
  2392. }
  2393. /// Get canonicalized offload arch option. \returns empty StringRef if the
  2394. /// option is invalid.
  2395. virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
  2396. virtual llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
  2397. getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
  2398. bool initialize() override {
  2399. assert(AssociatedOffloadKind == Action::OFK_Cuda ||
  2400. AssociatedOffloadKind == Action::OFK_HIP);
  2401. // We don't need to support CUDA.
  2402. if (AssociatedOffloadKind == Action::OFK_Cuda &&
  2403. !C.hasOffloadToolChain<Action::OFK_Cuda>())
  2404. return false;
  2405. // We don't need to support HIP.
  2406. if (AssociatedOffloadKind == Action::OFK_HIP &&
  2407. !C.hasOffloadToolChain<Action::OFK_HIP>())
  2408. return false;
  2409. Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
  2410. options::OPT_fno_gpu_rdc, /*Default=*/false);
  2411. const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
  2412. assert(HostTC && "No toolchain for host compilation.");
  2413. if (HostTC->getTriple().isNVPTX() ||
  2414. HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
  2415. // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
  2416. // an error and abort pipeline construction early so we don't trip
  2417. // asserts that assume device-side compilation.
  2418. C.getDriver().Diag(diag::err_drv_cuda_host_arch)
  2419. << HostTC->getTriple().getArchName();
  2420. return true;
  2421. }
  2422. ToolChains.push_back(
  2423. AssociatedOffloadKind == Action::OFK_Cuda
  2424. ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
  2425. : C.getSingleOffloadToolChain<Action::OFK_HIP>());
  2426. Arg *PartialCompilationArg = Args.getLastArg(
  2427. options::OPT_cuda_host_only, options::OPT_cuda_device_only,
  2428. options::OPT_cuda_compile_host_device);
  2429. CompileHostOnly = PartialCompilationArg &&
  2430. PartialCompilationArg->getOption().matches(
  2431. options::OPT_cuda_host_only);
  2432. CompileDeviceOnly = PartialCompilationArg &&
  2433. PartialCompilationArg->getOption().matches(
  2434. options::OPT_cuda_device_only);
  2435. EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
  2436. EmitAsm = Args.getLastArg(options::OPT_S);
  2437. FixedCUID = Args.getLastArgValue(options::OPT_cuid_EQ);
  2438. if (Arg *A = Args.getLastArg(options::OPT_fuse_cuid_EQ)) {
  2439. StringRef UseCUIDStr = A->getValue();
  2440. UseCUID = llvm::StringSwitch<UseCUIDKind>(UseCUIDStr)
  2441. .Case("hash", CUID_Hash)
  2442. .Case("random", CUID_Random)
  2443. .Case("none", CUID_None)
  2444. .Default(CUID_Invalid);
  2445. if (UseCUID == CUID_Invalid) {
  2446. C.getDriver().Diag(diag::err_drv_invalid_value)
  2447. << A->getAsString(Args) << UseCUIDStr;
  2448. C.setContainsError();
  2449. return true;
  2450. }
  2451. }
  2452. // --offload and --offload-arch options are mutually exclusive.
  2453. if (Args.hasArgNoClaim(options::OPT_offload_EQ) &&
  2454. Args.hasArgNoClaim(options::OPT_offload_arch_EQ,
  2455. options::OPT_no_offload_arch_EQ)) {
  2456. C.getDriver().Diag(diag::err_opt_not_valid_with_opt) << "--offload-arch"
  2457. << "--offload";
  2458. }
  2459. // Collect all cuda_gpu_arch parameters, removing duplicates.
  2460. std::set<StringRef> GpuArchs;
  2461. bool Error = false;
  2462. for (Arg *A : Args) {
  2463. if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
  2464. A->getOption().matches(options::OPT_no_offload_arch_EQ)))
  2465. continue;
  2466. A->claim();
  2467. StringRef ArchStr = A->getValue();
  2468. if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
  2469. ArchStr == "all") {
  2470. GpuArchs.clear();
  2471. continue;
  2472. }
  2473. ArchStr = getCanonicalOffloadArch(ArchStr);
  2474. if (ArchStr.empty()) {
  2475. Error = true;
  2476. } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
  2477. GpuArchs.insert(ArchStr);
  2478. else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
  2479. GpuArchs.erase(ArchStr);
  2480. else
  2481. llvm_unreachable("Unexpected option.");
  2482. }
  2483. auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
  2484. if (ConflictingArchs) {
  2485. C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
  2486. << ConflictingArchs.getValue().first
  2487. << ConflictingArchs.getValue().second;
  2488. C.setContainsError();
  2489. return true;
  2490. }
  2491. // Collect list of GPUs remaining in the set.
  2492. for (auto Arch : GpuArchs)
  2493. GpuArchList.push_back(Arch.data());
  2494. // Default to sm_20 which is the lowest common denominator for
  2495. // supported GPUs. sm_20 code should work correctly, if
  2496. // suboptimally, on all newer GPUs.
  2497. if (GpuArchList.empty()) {
  2498. if (ToolChains.front()->getTriple().isSPIRV())
  2499. GpuArchList.push_back(CudaArch::Generic);
  2500. else
  2501. GpuArchList.push_back(DefaultCudaArch);
  2502. }
  2503. return Error;
  2504. }
  2505. };
  2506. /// \brief CUDA action builder. It injects device code in the host backend
  2507. /// action.
  2508. class CudaActionBuilder final : public CudaActionBuilderBase {
  2509. public:
  2510. CudaActionBuilder(Compilation &C, DerivedArgList &Args,
  2511. const Driver::InputList &Inputs)
  2512. : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
  2513. DefaultCudaArch = CudaArch::SM_35;
  2514. }
  2515. StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
  2516. CudaArch Arch = StringToCudaArch(ArchStr);
  2517. if (Arch == CudaArch::UNKNOWN || !IsNVIDIAGpuArch(Arch)) {
  2518. C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
  2519. return StringRef();
  2520. }
  2521. return CudaArchToString(Arch);
  2522. }
  2523. llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
  2524. getConflictOffloadArchCombination(
  2525. const std::set<StringRef> &GpuArchs) override {
  2526. return llvm::None;
  2527. }
  2528. ActionBuilderReturnCode
  2529. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  2530. phases::ID CurPhase, phases::ID FinalPhase,
  2531. PhasesTy &Phases) override {
  2532. if (!IsActive)
  2533. return ABRT_Inactive;
  2534. // If we don't have more CUDA actions, we don't have any dependences to
  2535. // create for the host.
  2536. if (CudaDeviceActions.empty())
  2537. return ABRT_Success;
  2538. assert(CudaDeviceActions.size() == GpuArchList.size() &&
  2539. "Expecting one action per GPU architecture.");
  2540. assert(!CompileHostOnly &&
  2541. "Not expecting CUDA actions in host-only compilation.");
  2542. // If we are generating code for the device or we are in a backend phase,
  2543. // we attempt to generate the fat binary. We compile each arch to ptx and
  2544. // assemble to cubin, then feed the cubin *and* the ptx into a device
  2545. // "link" action, which uses fatbinary to combine these cubins into one
  2546. // fatbin. The fatbin is then an input to the host action if not in
  2547. // device-only mode.
  2548. if (CompileDeviceOnly || CurPhase == phases::Backend) {
  2549. ActionList DeviceActions;
  2550. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  2551. // Produce the device action from the current phase up to the assemble
  2552. // phase.
  2553. for (auto Ph : Phases) {
  2554. // Skip the phases that were already dealt with.
  2555. if (Ph < CurPhase)
  2556. continue;
  2557. // We have to be consistent with the host final phase.
  2558. if (Ph > FinalPhase)
  2559. break;
  2560. CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
  2561. C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
  2562. if (Ph == phases::Assemble)
  2563. break;
  2564. }
  2565. // If we didn't reach the assemble phase, we can't generate the fat
  2566. // binary. We don't need to generate the fat binary if we are not in
  2567. // device-only mode.
  2568. if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
  2569. CompileDeviceOnly)
  2570. continue;
  2571. Action *AssembleAction = CudaDeviceActions[I];
  2572. assert(AssembleAction->getType() == types::TY_Object);
  2573. assert(AssembleAction->getInputs().size() == 1);
  2574. Action *BackendAction = AssembleAction->getInputs()[0];
  2575. assert(BackendAction->getType() == types::TY_PP_Asm);
  2576. for (auto &A : {AssembleAction, BackendAction}) {
  2577. OffloadAction::DeviceDependences DDep;
  2578. DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
  2579. DeviceActions.push_back(
  2580. C.MakeAction<OffloadAction>(DDep, A->getType()));
  2581. }
  2582. }
  2583. // We generate the fat binary if we have device input actions.
  2584. if (!DeviceActions.empty()) {
  2585. CudaFatBinary =
  2586. C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
  2587. if (!CompileDeviceOnly) {
  2588. DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
  2589. Action::OFK_Cuda);
  2590. // Clear the fat binary, it is already a dependence to an host
  2591. // action.
  2592. CudaFatBinary = nullptr;
  2593. }
  2594. // Remove the CUDA actions as they are already connected to an host
  2595. // action or fat binary.
  2596. CudaDeviceActions.clear();
  2597. }
  2598. // We avoid creating host action in device-only mode.
  2599. return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
  2600. } else if (CurPhase > phases::Backend) {
  2601. // If we are past the backend phase and still have a device action, we
  2602. // don't have to do anything as this action is already a device
  2603. // top-level action.
  2604. return ABRT_Success;
  2605. }
  2606. assert(CurPhase < phases::Backend && "Generating single CUDA "
  2607. "instructions should only occur "
  2608. "before the backend phase!");
  2609. // By default, we produce an action for each device arch.
  2610. for (Action *&A : CudaDeviceActions)
  2611. A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
  2612. return ABRT_Success;
  2613. }
  2614. };
  2615. /// \brief HIP action builder. It injects device code in the host backend
  2616. /// action.
  2617. class HIPActionBuilder final : public CudaActionBuilderBase {
  2618. /// The linker inputs obtained for each device arch.
  2619. SmallVector<ActionList, 8> DeviceLinkerInputs;
  2620. // The default bundling behavior depends on the type of output, therefore
  2621. // BundleOutput needs to be tri-value: None, true, or false.
  2622. // Bundle code objects except --no-gpu-output is specified for device
  2623. // only compilation. Bundle other type of output files only if
  2624. // --gpu-bundle-output is specified for device only compilation.
  2625. Optional<bool> BundleOutput;
  2626. public:
  2627. HIPActionBuilder(Compilation &C, DerivedArgList &Args,
  2628. const Driver::InputList &Inputs)
  2629. : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
  2630. DefaultCudaArch = CudaArch::GFX803;
  2631. if (Args.hasArg(options::OPT_gpu_bundle_output,
  2632. options::OPT_no_gpu_bundle_output))
  2633. BundleOutput = Args.hasFlag(options::OPT_gpu_bundle_output,
  2634. options::OPT_no_gpu_bundle_output);
  2635. }
  2636. bool canUseBundlerUnbundler() const override { return true; }
  2637. StringRef getCanonicalOffloadArch(StringRef IdStr) override {
  2638. llvm::StringMap<bool> Features;
  2639. // getHIPOffloadTargetTriple() is known to return valid value as it has
  2640. // been called successfully in the CreateOffloadingDeviceToolChains().
  2641. auto ArchStr = parseTargetID(
  2642. *getHIPOffloadTargetTriple(C.getDriver(), C.getInputArgs()), IdStr,
  2643. &Features);
  2644. if (!ArchStr) {
  2645. C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
  2646. C.setContainsError();
  2647. return StringRef();
  2648. }
  2649. auto CanId = getCanonicalTargetID(ArchStr.getValue(), Features);
  2650. return Args.MakeArgStringRef(CanId);
  2651. };
  2652. llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
  2653. getConflictOffloadArchCombination(
  2654. const std::set<StringRef> &GpuArchs) override {
  2655. return getConflictTargetIDCombination(GpuArchs);
  2656. }
  2657. ActionBuilderReturnCode
  2658. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  2659. phases::ID CurPhase, phases::ID FinalPhase,
  2660. PhasesTy &Phases) override {
  2661. // amdgcn does not support linking of object files, therefore we skip
  2662. // backend and assemble phases to output LLVM IR. Except for generating
  2663. // non-relocatable device coee, where we generate fat binary for device
  2664. // code and pass to host in Backend phase.
  2665. if (CudaDeviceActions.empty())
  2666. return ABRT_Success;
  2667. assert(((CurPhase == phases::Link && Relocatable) ||
  2668. CudaDeviceActions.size() == GpuArchList.size()) &&
  2669. "Expecting one action per GPU architecture.");
  2670. assert(!CompileHostOnly &&
  2671. "Not expecting CUDA actions in host-only compilation.");
  2672. if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
  2673. !EmitAsm) {
  2674. // If we are in backend phase, we attempt to generate the fat binary.
  2675. // We compile each arch to IR and use a link action to generate code
  2676. // object containing ISA. Then we use a special "link" action to create
  2677. // a fat binary containing all the code objects for different GPU's.
  2678. // The fat binary is then an input to the host action.
  2679. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  2680. if (C.getDriver().isUsingLTO(/*IsOffload=*/true)) {
  2681. // When LTO is enabled, skip the backend and assemble phases and
  2682. // use lld to link the bitcode.
  2683. ActionList AL;
  2684. AL.push_back(CudaDeviceActions[I]);
  2685. // Create a link action to link device IR with device library
  2686. // and generate ISA.
  2687. CudaDeviceActions[I] =
  2688. C.MakeAction<LinkJobAction>(AL, types::TY_Image);
  2689. } else {
  2690. // When LTO is not enabled, we follow the conventional
  2691. // compiler phases, including backend and assemble phases.
  2692. ActionList AL;
  2693. Action *BackendAction = nullptr;
  2694. if (ToolChains.front()->getTriple().isSPIRV()) {
  2695. // Emit LLVM bitcode for SPIR-V targets. SPIR-V device tool chain
  2696. // (HIPSPVToolChain) runs post-link LLVM IR passes.
  2697. types::ID Output = Args.hasArg(options::OPT_S)
  2698. ? types::TY_LLVM_IR
  2699. : types::TY_LLVM_BC;
  2700. BackendAction =
  2701. C.MakeAction<BackendJobAction>(CudaDeviceActions[I], Output);
  2702. } else
  2703. BackendAction = C.getDriver().ConstructPhaseAction(
  2704. C, Args, phases::Backend, CudaDeviceActions[I],
  2705. AssociatedOffloadKind);
  2706. auto AssembleAction = C.getDriver().ConstructPhaseAction(
  2707. C, Args, phases::Assemble, BackendAction,
  2708. AssociatedOffloadKind);
  2709. AL.push_back(AssembleAction);
  2710. // Create a link action to link device IR with device library
  2711. // and generate ISA.
  2712. CudaDeviceActions[I] =
  2713. C.MakeAction<LinkJobAction>(AL, types::TY_Image);
  2714. }
  2715. // OffloadingActionBuilder propagates device arch until an offload
  2716. // action. Since the next action for creating fatbin does
  2717. // not have device arch, whereas the above link action and its input
  2718. // have device arch, an offload action is needed to stop the null
  2719. // device arch of the next action being propagated to the above link
  2720. // action.
  2721. OffloadAction::DeviceDependences DDep;
  2722. DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
  2723. AssociatedOffloadKind);
  2724. CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
  2725. DDep, CudaDeviceActions[I]->getType());
  2726. }
  2727. if (!CompileDeviceOnly || !BundleOutput.hasValue() ||
  2728. BundleOutput.getValue()) {
  2729. // Create HIP fat binary with a special "link" action.
  2730. CudaFatBinary = C.MakeAction<LinkJobAction>(CudaDeviceActions,
  2731. types::TY_HIP_FATBIN);
  2732. if (!CompileDeviceOnly) {
  2733. DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
  2734. AssociatedOffloadKind);
  2735. // Clear the fat binary, it is already a dependence to an host
  2736. // action.
  2737. CudaFatBinary = nullptr;
  2738. }
  2739. // Remove the CUDA actions as they are already connected to an host
  2740. // action or fat binary.
  2741. CudaDeviceActions.clear();
  2742. }
  2743. return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
  2744. } else if (CurPhase == phases::Link) {
  2745. // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
  2746. // This happens to each device action originated from each input file.
  2747. // Later on, device actions in DeviceLinkerInputs are used to create
  2748. // device link actions in appendLinkDependences and the created device
  2749. // link actions are passed to the offload action as device dependence.
  2750. DeviceLinkerInputs.resize(CudaDeviceActions.size());
  2751. auto LI = DeviceLinkerInputs.begin();
  2752. for (auto *A : CudaDeviceActions) {
  2753. LI->push_back(A);
  2754. ++LI;
  2755. }
  2756. // We will pass the device action as a host dependence, so we don't
  2757. // need to do anything else with them.
  2758. CudaDeviceActions.clear();
  2759. return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
  2760. }
  2761. // By default, we produce an action for each device arch.
  2762. for (Action *&A : CudaDeviceActions)
  2763. A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
  2764. AssociatedOffloadKind);
  2765. if (CompileDeviceOnly && CurPhase == FinalPhase &&
  2766. BundleOutput.hasValue() && BundleOutput.getValue()) {
  2767. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  2768. OffloadAction::DeviceDependences DDep;
  2769. DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
  2770. AssociatedOffloadKind);
  2771. CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
  2772. DDep, CudaDeviceActions[I]->getType());
  2773. }
  2774. CudaFatBinary =
  2775. C.MakeAction<OffloadBundlingJobAction>(CudaDeviceActions);
  2776. CudaDeviceActions.clear();
  2777. }
  2778. return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
  2779. : ABRT_Success;
  2780. }
  2781. void appendLinkDeviceActions(ActionList &AL) override {
  2782. if (DeviceLinkerInputs.size() == 0)
  2783. return;
  2784. assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
  2785. "Linker inputs and GPU arch list sizes do not match.");
  2786. ActionList Actions;
  2787. // Append a new link action for each device.
  2788. unsigned I = 0;
  2789. for (auto &LI : DeviceLinkerInputs) {
  2790. // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
  2791. auto *DeviceLinkAction =
  2792. C.MakeAction<LinkJobAction>(LI, types::TY_Image);
  2793. // Linking all inputs for the current GPU arch.
  2794. // LI contains all the inputs for the linker.
  2795. OffloadAction::DeviceDependences DeviceLinkDeps;
  2796. DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
  2797. GpuArchList[I], AssociatedOffloadKind);
  2798. Actions.push_back(C.MakeAction<OffloadAction>(
  2799. DeviceLinkDeps, DeviceLinkAction->getType()));
  2800. ++I;
  2801. }
  2802. DeviceLinkerInputs.clear();
  2803. // Create a host object from all the device images by embedding them
  2804. // in a fat binary for mixed host-device compilation. For device-only
  2805. // compilation, creates a fat binary.
  2806. OffloadAction::DeviceDependences DDeps;
  2807. if (!CompileDeviceOnly || !BundleOutput.hasValue() ||
  2808. BundleOutput.getValue()) {
  2809. auto *TopDeviceLinkAction = C.MakeAction<LinkJobAction>(
  2810. Actions,
  2811. CompileDeviceOnly ? types::TY_HIP_FATBIN : types::TY_Object);
  2812. DDeps.add(*TopDeviceLinkAction, *ToolChains[0], nullptr,
  2813. AssociatedOffloadKind);
  2814. // Offload the host object to the host linker.
  2815. AL.push_back(
  2816. C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
  2817. } else {
  2818. AL.append(Actions);
  2819. }
  2820. }
  2821. Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
  2822. void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
  2823. };
  2824. /// OpenMP action builder. The host bitcode is passed to the device frontend
  2825. /// and all the device linked images are passed to the host link phase.
  2826. class OpenMPActionBuilder final : public DeviceActionBuilder {
  2827. /// The OpenMP actions for the current input.
  2828. ActionList OpenMPDeviceActions;
  2829. /// The linker inputs obtained for each toolchain.
  2830. SmallVector<ActionList, 8> DeviceLinkerInputs;
  2831. public:
  2832. OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
  2833. const Driver::InputList &Inputs)
  2834. : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
  2835. ActionBuilderReturnCode
  2836. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  2837. phases::ID CurPhase, phases::ID FinalPhase,
  2838. PhasesTy &Phases) override {
  2839. if (OpenMPDeviceActions.empty())
  2840. return ABRT_Inactive;
  2841. // We should always have an action for each input.
  2842. assert(OpenMPDeviceActions.size() == ToolChains.size() &&
  2843. "Number of OpenMP actions and toolchains do not match.");
  2844. // The host only depends on device action in the linking phase, when all
  2845. // the device images have to be embedded in the host image.
  2846. if (CurPhase == phases::Link) {
  2847. assert(ToolChains.size() == DeviceLinkerInputs.size() &&
  2848. "Toolchains and linker inputs sizes do not match.");
  2849. auto LI = DeviceLinkerInputs.begin();
  2850. for (auto *A : OpenMPDeviceActions) {
  2851. LI->push_back(A);
  2852. ++LI;
  2853. }
  2854. // We passed the device action as a host dependence, so we don't need to
  2855. // do anything else with them.
  2856. OpenMPDeviceActions.clear();
  2857. return ABRT_Success;
  2858. }
  2859. // By default, we produce an action for each device arch.
  2860. for (Action *&A : OpenMPDeviceActions)
  2861. A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
  2862. return ABRT_Success;
  2863. }
  2864. ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
  2865. // If this is an input action replicate it for each OpenMP toolchain.
  2866. if (auto *IA = dyn_cast<InputAction>(HostAction)) {
  2867. OpenMPDeviceActions.clear();
  2868. for (unsigned I = 0; I < ToolChains.size(); ++I)
  2869. OpenMPDeviceActions.push_back(
  2870. C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
  2871. return ABRT_Success;
  2872. }
  2873. // If this is an unbundling action use it as is for each OpenMP toolchain.
  2874. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
  2875. OpenMPDeviceActions.clear();
  2876. auto *IA = cast<InputAction>(UA->getInputs().back());
  2877. std::string FileName = IA->getInputArg().getAsString(Args);
  2878. // Check if the type of the file is the same as the action. Do not
  2879. // unbundle it if it is not. Do not unbundle .so files, for example,
  2880. // which are not object files.
  2881. if (IA->getType() == types::TY_Object &&
  2882. (!llvm::sys::path::has_extension(FileName) ||
  2883. types::lookupTypeForExtension(
  2884. llvm::sys::path::extension(FileName).drop_front()) !=
  2885. types::TY_Object))
  2886. return ABRT_Inactive;
  2887. for (unsigned I = 0; I < ToolChains.size(); ++I) {
  2888. OpenMPDeviceActions.push_back(UA);
  2889. UA->registerDependentActionInfo(
  2890. ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
  2891. }
  2892. return ABRT_Success;
  2893. }
  2894. // When generating code for OpenMP we use the host compile phase result as
  2895. // a dependence to the device compile phase so that it can learn what
  2896. // declarations should be emitted. However, this is not the only use for
  2897. // the host action, so we prevent it from being collapsed.
  2898. if (isa<CompileJobAction>(HostAction)) {
  2899. HostAction->setCannotBeCollapsedWithNextDependentAction();
  2900. assert(ToolChains.size() == OpenMPDeviceActions.size() &&
  2901. "Toolchains and device action sizes do not match.");
  2902. OffloadAction::HostDependence HDep(
  2903. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  2904. /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  2905. auto TC = ToolChains.begin();
  2906. for (Action *&A : OpenMPDeviceActions) {
  2907. assert(isa<CompileJobAction>(A));
  2908. OffloadAction::DeviceDependences DDep;
  2909. DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  2910. A = C.MakeAction<OffloadAction>(HDep, DDep);
  2911. ++TC;
  2912. }
  2913. }
  2914. return ABRT_Success;
  2915. }
  2916. void appendTopLevelActions(ActionList &AL) override {
  2917. if (OpenMPDeviceActions.empty())
  2918. return;
  2919. // We should always have an action for each input.
  2920. assert(OpenMPDeviceActions.size() == ToolChains.size() &&
  2921. "Number of OpenMP actions and toolchains do not match.");
  2922. // Append all device actions followed by the proper offload action.
  2923. auto TI = ToolChains.begin();
  2924. for (auto *A : OpenMPDeviceActions) {
  2925. OffloadAction::DeviceDependences Dep;
  2926. Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  2927. AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
  2928. ++TI;
  2929. }
  2930. // We no longer need the action stored in this builder.
  2931. OpenMPDeviceActions.clear();
  2932. }
  2933. void appendLinkDeviceActions(ActionList &AL) override {
  2934. assert(ToolChains.size() == DeviceLinkerInputs.size() &&
  2935. "Toolchains and linker inputs sizes do not match.");
  2936. // Append a new link action for each device.
  2937. auto TC = ToolChains.begin();
  2938. for (auto &LI : DeviceLinkerInputs) {
  2939. auto *DeviceLinkAction =
  2940. C.MakeAction<LinkJobAction>(LI, types::TY_Image);
  2941. OffloadAction::DeviceDependences DeviceLinkDeps;
  2942. DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
  2943. Action::OFK_OpenMP);
  2944. AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
  2945. DeviceLinkAction->getType()));
  2946. ++TC;
  2947. }
  2948. DeviceLinkerInputs.clear();
  2949. }
  2950. Action* appendLinkHostActions(ActionList &AL) override {
  2951. // Create wrapper bitcode from the result of device link actions and compile
  2952. // it to an object which will be added to the host link command.
  2953. auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC);
  2954. auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
  2955. return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
  2956. }
  2957. void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
  2958. bool initialize() override {
  2959. // Get the OpenMP toolchains. If we don't get any, the action builder will
  2960. // know there is nothing to do related to OpenMP offloading.
  2961. auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
  2962. for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
  2963. ++TI)
  2964. ToolChains.push_back(TI->second);
  2965. DeviceLinkerInputs.resize(ToolChains.size());
  2966. return false;
  2967. }
  2968. bool canUseBundlerUnbundler() const override {
  2969. // OpenMP should use bundled files whenever possible.
  2970. return true;
  2971. }
  2972. };
  2973. ///
  2974. /// TODO: Add the implementation for other specialized builders here.
  2975. ///
  2976. /// Specialized builders being used by this offloading action builder.
  2977. SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
  2978. /// Flag set to true if all valid builders allow file bundling/unbundling.
  2979. bool CanUseBundler;
  2980. public:
  2981. OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
  2982. const Driver::InputList &Inputs)
  2983. : C(C) {
  2984. // Create a specialized builder for each device toolchain.
  2985. IsValid = true;
  2986. // Create a specialized builder for CUDA.
  2987. SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
  2988. // Create a specialized builder for HIP.
  2989. SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
  2990. // Create a specialized builder for OpenMP.
  2991. SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
  2992. //
  2993. // TODO: Build other specialized builders here.
  2994. //
  2995. // Initialize all the builders, keeping track of errors. If all valid
  2996. // builders agree that we can use bundling, set the flag to true.
  2997. unsigned ValidBuilders = 0u;
  2998. unsigned ValidBuildersSupportingBundling = 0u;
  2999. for (auto *SB : SpecializedBuilders) {
  3000. IsValid = IsValid && !SB->initialize();
  3001. // Update the counters if the builder is valid.
  3002. if (SB->isValid()) {
  3003. ++ValidBuilders;
  3004. if (SB->canUseBundlerUnbundler())
  3005. ++ValidBuildersSupportingBundling;
  3006. }
  3007. }
  3008. CanUseBundler =
  3009. ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
  3010. }
  3011. ~OffloadingActionBuilder() {
  3012. for (auto *SB : SpecializedBuilders)
  3013. delete SB;
  3014. }
  3015. /// Generate an action that adds device dependences (if any) to a host action.
  3016. /// If no device dependence actions exist, just return the host action \a
  3017. /// HostAction. If an error is found or if no builder requires the host action
  3018. /// to be generated, return nullptr.
  3019. Action *
  3020. addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
  3021. phases::ID CurPhase, phases::ID FinalPhase,
  3022. DeviceActionBuilder::PhasesTy &Phases) {
  3023. if (!IsValid)
  3024. return nullptr;
  3025. if (SpecializedBuilders.empty())
  3026. return HostAction;
  3027. assert(HostAction && "Invalid host action!");
  3028. OffloadAction::DeviceDependences DDeps;
  3029. // Check if all the programming models agree we should not emit the host
  3030. // action. Also, keep track of the offloading kinds employed.
  3031. auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
  3032. unsigned InactiveBuilders = 0u;
  3033. unsigned IgnoringBuilders = 0u;
  3034. for (auto *SB : SpecializedBuilders) {
  3035. if (!SB->isValid()) {
  3036. ++InactiveBuilders;
  3037. continue;
  3038. }
  3039. auto RetCode =
  3040. SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
  3041. // If the builder explicitly says the host action should be ignored,
  3042. // we need to increment the variable that tracks the builders that request
  3043. // the host object to be ignored.
  3044. if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
  3045. ++IgnoringBuilders;
  3046. // Unless the builder was inactive for this action, we have to record the
  3047. // offload kind because the host will have to use it.
  3048. if (RetCode != DeviceActionBuilder::ABRT_Inactive)
  3049. OffloadKind |= SB->getAssociatedOffloadKind();
  3050. }
  3051. // If all builders agree that the host object should be ignored, just return
  3052. // nullptr.
  3053. if (IgnoringBuilders &&
  3054. SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
  3055. return nullptr;
  3056. if (DDeps.getActions().empty())
  3057. return HostAction;
  3058. // We have dependences we need to bundle together. We use an offload action
  3059. // for that.
  3060. OffloadAction::HostDependence HDep(
  3061. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  3062. /*BoundArch=*/nullptr, DDeps);
  3063. return C.MakeAction<OffloadAction>(HDep, DDeps);
  3064. }
  3065. /// Generate an action that adds a host dependence to a device action. The
  3066. /// results will be kept in this action builder. Return true if an error was
  3067. /// found.
  3068. bool addHostDependenceToDeviceActions(Action *&HostAction,
  3069. const Arg *InputArg) {
  3070. if (!IsValid)
  3071. return true;
  3072. // If we are supporting bundling/unbundling and the current action is an
  3073. // input action of non-source file, we replace the host action by the
  3074. // unbundling action. The bundler tool has the logic to detect if an input
  3075. // is a bundle or not and if the input is not a bundle it assumes it is a
  3076. // host file. Therefore it is safe to create an unbundling action even if
  3077. // the input is not a bundle.
  3078. if (CanUseBundler && isa<InputAction>(HostAction) &&
  3079. InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
  3080. (!types::isSrcFile(HostAction->getType()) ||
  3081. HostAction->getType() == types::TY_PP_HIP)) {
  3082. auto UnbundlingHostAction =
  3083. C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
  3084. UnbundlingHostAction->registerDependentActionInfo(
  3085. C.getSingleOffloadToolChain<Action::OFK_Host>(),
  3086. /*BoundArch=*/StringRef(), Action::OFK_Host);
  3087. HostAction = UnbundlingHostAction;
  3088. }
  3089. assert(HostAction && "Invalid host action!");
  3090. // Register the offload kinds that are used.
  3091. auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
  3092. for (auto *SB : SpecializedBuilders) {
  3093. if (!SB->isValid())
  3094. continue;
  3095. auto RetCode = SB->addDeviceDepences(HostAction);
  3096. // Host dependences for device actions are not compatible with that same
  3097. // action being ignored.
  3098. assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
  3099. "Host dependence not expected to be ignored.!");
  3100. // Unless the builder was inactive for this action, we have to record the
  3101. // offload kind because the host will have to use it.
  3102. if (RetCode != DeviceActionBuilder::ABRT_Inactive)
  3103. OffloadKind |= SB->getAssociatedOffloadKind();
  3104. }
  3105. // Do not use unbundler if the Host does not depend on device action.
  3106. if (OffloadKind == Action::OFK_None && CanUseBundler)
  3107. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
  3108. HostAction = UA->getInputs().back();
  3109. return false;
  3110. }
  3111. /// Add the offloading top level actions to the provided action list. This
  3112. /// function can replace the host action by a bundling action if the
  3113. /// programming models allow it.
  3114. bool appendTopLevelActions(ActionList &AL, Action *HostAction,
  3115. const Arg *InputArg) {
  3116. // Get the device actions to be appended.
  3117. ActionList OffloadAL;
  3118. for (auto *SB : SpecializedBuilders) {
  3119. if (!SB->isValid())
  3120. continue;
  3121. SB->appendTopLevelActions(OffloadAL);
  3122. }
  3123. // If we can use the bundler, replace the host action by the bundling one in
  3124. // the resulting list. Otherwise, just append the device actions. For
  3125. // device only compilation, HostAction is a null pointer, therefore only do
  3126. // this when HostAction is not a null pointer.
  3127. if (CanUseBundler && HostAction &&
  3128. HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
  3129. // Add the host action to the list in order to create the bundling action.
  3130. OffloadAL.push_back(HostAction);
  3131. // We expect that the host action was just appended to the action list
  3132. // before this method was called.
  3133. assert(HostAction == AL.back() && "Host action not in the list??");
  3134. HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
  3135. AL.back() = HostAction;
  3136. } else
  3137. AL.append(OffloadAL.begin(), OffloadAL.end());
  3138. // Propagate to the current host action (if any) the offload information
  3139. // associated with the current input.
  3140. if (HostAction)
  3141. HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
  3142. /*BoundArch=*/nullptr);
  3143. return false;
  3144. }
  3145. void appendDeviceLinkActions(ActionList &AL) {
  3146. for (DeviceActionBuilder *SB : SpecializedBuilders) {
  3147. if (!SB->isValid())
  3148. continue;
  3149. SB->appendLinkDeviceActions(AL);
  3150. }
  3151. }
  3152. Action *makeHostLinkAction() {
  3153. // Build a list of device linking actions.
  3154. ActionList DeviceAL;
  3155. appendDeviceLinkActions(DeviceAL);
  3156. if (DeviceAL.empty())
  3157. return nullptr;
  3158. // Let builders add host linking actions.
  3159. Action* HA = nullptr;
  3160. for (DeviceActionBuilder *SB : SpecializedBuilders) {
  3161. if (!SB->isValid())
  3162. continue;
  3163. HA = SB->appendLinkHostActions(DeviceAL);
  3164. }
  3165. return HA;
  3166. }
  3167. /// Processes the host linker action. This currently consists of replacing it
  3168. /// with an offload action if there are device link objects and propagate to
  3169. /// the host action all the offload kinds used in the current compilation. The
  3170. /// resulting action is returned.
  3171. Action *processHostLinkAction(Action *HostAction) {
  3172. // Add all the dependences from the device linking actions.
  3173. OffloadAction::DeviceDependences DDeps;
  3174. for (auto *SB : SpecializedBuilders) {
  3175. if (!SB->isValid())
  3176. continue;
  3177. SB->appendLinkDependences(DDeps);
  3178. }
  3179. // Calculate all the offload kinds used in the current compilation.
  3180. unsigned ActiveOffloadKinds = 0u;
  3181. for (auto &I : InputArgToOffloadKindMap)
  3182. ActiveOffloadKinds |= I.second;
  3183. // If we don't have device dependencies, we don't have to create an offload
  3184. // action.
  3185. if (DDeps.getActions().empty()) {
  3186. // Propagate all the active kinds to host action. Given that it is a link
  3187. // action it is assumed to depend on all actions generated so far.
  3188. HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
  3189. /*BoundArch=*/nullptr);
  3190. return HostAction;
  3191. }
  3192. // Create the offload action with all dependences. When an offload action
  3193. // is created the kinds are propagated to the host action, so we don't have
  3194. // to do that explicitly here.
  3195. OffloadAction::HostDependence HDep(
  3196. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  3197. /*BoundArch*/ nullptr, ActiveOffloadKinds);
  3198. return C.MakeAction<OffloadAction>(HDep, DDeps);
  3199. }
  3200. };
  3201. } // anonymous namespace.
  3202. void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
  3203. const InputList &Inputs,
  3204. ActionList &Actions) const {
  3205. // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
  3206. Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  3207. Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  3208. if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
  3209. Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
  3210. Args.eraseArg(options::OPT__SLASH_Yc);
  3211. Args.eraseArg(options::OPT__SLASH_Yu);
  3212. YcArg = YuArg = nullptr;
  3213. }
  3214. if (YcArg && Inputs.size() > 1) {
  3215. Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
  3216. Args.eraseArg(options::OPT__SLASH_Yc);
  3217. YcArg = nullptr;
  3218. }
  3219. Arg *FinalPhaseArg;
  3220. phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
  3221. if (FinalPhase == phases::Link) {
  3222. if (Args.hasArg(options::OPT_emit_llvm))
  3223. Diag(clang::diag::err_drv_emit_llvm_link);
  3224. if (IsCLMode() && LTOMode != LTOK_None &&
  3225. !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
  3226. .equals_insensitive("lld"))
  3227. Diag(clang::diag::err_drv_lto_without_lld);
  3228. }
  3229. if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
  3230. // If only preprocessing or /Y- is used, all pch handling is disabled.
  3231. // Rather than check for it everywhere, just remove clang-cl pch-related
  3232. // flags here.
  3233. Args.eraseArg(options::OPT__SLASH_Fp);
  3234. Args.eraseArg(options::OPT__SLASH_Yc);
  3235. Args.eraseArg(options::OPT__SLASH_Yu);
  3236. YcArg = YuArg = nullptr;
  3237. }
  3238. unsigned LastPLSize = 0;
  3239. for (auto &I : Inputs) {
  3240. types::ID InputType = I.first;
  3241. const Arg *InputArg = I.second;
  3242. auto PL = types::getCompilationPhases(InputType);
  3243. LastPLSize = PL.size();
  3244. // If the first step comes after the final phase we are doing as part of
  3245. // this compilation, warn the user about it.
  3246. phases::ID InitialPhase = PL[0];
  3247. if (InitialPhase > FinalPhase) {
  3248. if (InputArg->isClaimed())
  3249. continue;
  3250. // Claim here to avoid the more general unused warning.
  3251. InputArg->claim();
  3252. // Suppress all unused style warnings with -Qunused-arguments
  3253. if (Args.hasArg(options::OPT_Qunused_arguments))
  3254. continue;
  3255. // Special case when final phase determined by binary name, rather than
  3256. // by a command-line argument with a corresponding Arg.
  3257. if (CCCIsCPP())
  3258. Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
  3259. << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
  3260. // Special case '-E' warning on a previously preprocessed file to make
  3261. // more sense.
  3262. else if (InitialPhase == phases::Compile &&
  3263. (Args.getLastArg(options::OPT__SLASH_EP,
  3264. options::OPT__SLASH_P) ||
  3265. Args.getLastArg(options::OPT_E) ||
  3266. Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
  3267. getPreprocessedType(InputType) == types::TY_INVALID)
  3268. Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
  3269. << InputArg->getAsString(Args) << !!FinalPhaseArg
  3270. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  3271. else
  3272. Diag(clang::diag::warn_drv_input_file_unused)
  3273. << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
  3274. << !!FinalPhaseArg
  3275. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  3276. continue;
  3277. }
  3278. if (YcArg) {
  3279. // Add a separate precompile phase for the compile phase.
  3280. if (FinalPhase >= phases::Compile) {
  3281. const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
  3282. // Build the pipeline for the pch file.
  3283. Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
  3284. for (phases::ID Phase : types::getCompilationPhases(HeaderType))
  3285. ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
  3286. assert(ClangClPch);
  3287. Actions.push_back(ClangClPch);
  3288. // The driver currently exits after the first failed command. This
  3289. // relies on that behavior, to make sure if the pch generation fails,
  3290. // the main compilation won't run.
  3291. // FIXME: If the main compilation fails, the PCH generation should
  3292. // probably not be considered successful either.
  3293. }
  3294. }
  3295. }
  3296. // If we are linking, claim any options which are obviously only used for
  3297. // compilation.
  3298. // FIXME: Understand why the last Phase List length is used here.
  3299. if (FinalPhase == phases::Link && LastPLSize == 1) {
  3300. Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
  3301. Args.ClaimAllArgs(options::OPT_cl_compile_Group);
  3302. }
  3303. }
  3304. void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
  3305. const InputList &Inputs, ActionList &Actions) const {
  3306. llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
  3307. if (!SuppressMissingInputWarning && Inputs.empty()) {
  3308. Diag(clang::diag::err_drv_no_input_files);
  3309. return;
  3310. }
  3311. // Reject -Z* at the top level, these options should never have been exposed
  3312. // by gcc.
  3313. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
  3314. Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
  3315. // Diagnose misuse of /Fo.
  3316. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
  3317. StringRef V = A->getValue();
  3318. if (Inputs.size() > 1 && !V.empty() &&
  3319. !llvm::sys::path::is_separator(V.back())) {
  3320. // Check whether /Fo tries to name an output file for multiple inputs.
  3321. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  3322. << A->getSpelling() << V;
  3323. Args.eraseArg(options::OPT__SLASH_Fo);
  3324. }
  3325. }
  3326. // Diagnose misuse of /Fa.
  3327. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
  3328. StringRef V = A->getValue();
  3329. if (Inputs.size() > 1 && !V.empty() &&
  3330. !llvm::sys::path::is_separator(V.back())) {
  3331. // Check whether /Fa tries to name an asm file for multiple inputs.
  3332. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  3333. << A->getSpelling() << V;
  3334. Args.eraseArg(options::OPT__SLASH_Fa);
  3335. }
  3336. }
  3337. // Diagnose misuse of /o.
  3338. if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
  3339. if (A->getValue()[0] == '\0') {
  3340. // It has to have a value.
  3341. Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
  3342. Args.eraseArg(options::OPT__SLASH_o);
  3343. }
  3344. }
  3345. handleArguments(C, Args, Inputs, Actions);
  3346. // Builder to be used to build offloading actions.
  3347. OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
  3348. // Offload kinds active for this compilation.
  3349. unsigned OffloadKinds = Action::OFK_None;
  3350. if (C.hasOffloadToolChain<Action::OFK_OpenMP>())
  3351. OffloadKinds |= Action::OFK_OpenMP;
  3352. // Construct the actions to perform.
  3353. HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
  3354. ActionList LinkerInputs;
  3355. ActionList MergerInputs;
  3356. for (auto &I : Inputs) {
  3357. types::ID InputType = I.first;
  3358. const Arg *InputArg = I.second;
  3359. auto PL = types::getCompilationPhases(*this, Args, InputType);
  3360. if (PL.empty())
  3361. continue;
  3362. auto FullPL = types::getCompilationPhases(InputType);
  3363. // Build the pipeline for this file.
  3364. Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
  3365. // Use the current host action in any of the offloading actions, if
  3366. // required.
  3367. if (!Args.hasArg(options::OPT_fopenmp_new_driver))
  3368. if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
  3369. break;
  3370. for (phases::ID Phase : PL) {
  3371. // Add any offload action the host action depends on.
  3372. if (!Args.hasArg(options::OPT_fopenmp_new_driver))
  3373. Current = OffloadBuilder.addDeviceDependencesToHostAction(
  3374. Current, InputArg, Phase, PL.back(), FullPL);
  3375. if (!Current)
  3376. break;
  3377. // Queue linker inputs.
  3378. if (Phase == phases::Link) {
  3379. assert(Phase == PL.back() && "linking must be final compilation step.");
  3380. LinkerInputs.push_back(Current);
  3381. Current = nullptr;
  3382. break;
  3383. }
  3384. // TODO: Consider removing this because the merged may not end up being
  3385. // the final Phase in the pipeline. Perhaps the merged could just merge
  3386. // and then pass an artifact of some sort to the Link Phase.
  3387. // Queue merger inputs.
  3388. if (Phase == phases::IfsMerge) {
  3389. assert(Phase == PL.back() && "merging must be final compilation step.");
  3390. MergerInputs.push_back(Current);
  3391. Current = nullptr;
  3392. break;
  3393. }
  3394. // Each precompiled header file after a module file action is a module
  3395. // header of that same module file, rather than being compiled to a
  3396. // separate PCH.
  3397. if (Phase == phases::Precompile && HeaderModuleAction &&
  3398. getPrecompiledType(InputType) == types::TY_PCH) {
  3399. HeaderModuleAction->addModuleHeaderInput(Current);
  3400. Current = nullptr;
  3401. break;
  3402. }
  3403. // Try to build the offloading actions and add the result as a dependency
  3404. // to the host.
  3405. if (Args.hasArg(options::OPT_fopenmp_new_driver))
  3406. Current = BuildOffloadingActions(C, Args, I, Current);
  3407. // FIXME: Should we include any prior module file outputs as inputs of
  3408. // later actions in the same command line?
  3409. // Otherwise construct the appropriate action.
  3410. Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
  3411. // We didn't create a new action, so we will just move to the next phase.
  3412. if (NewCurrent == Current)
  3413. continue;
  3414. if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
  3415. HeaderModuleAction = HMA;
  3416. Current = NewCurrent;
  3417. // Use the current host action in any of the offloading actions, if
  3418. // required.
  3419. if (!Args.hasArg(options::OPT_fopenmp_new_driver))
  3420. if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
  3421. break;
  3422. if (Current->getType() == types::TY_Nothing)
  3423. break;
  3424. }
  3425. // If we ended with something, add to the output list.
  3426. if (Current)
  3427. Actions.push_back(Current);
  3428. // Add any top level actions generated for offloading.
  3429. if (!Args.hasArg(options::OPT_fopenmp_new_driver))
  3430. OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
  3431. else if (Current)
  3432. Current->propagateHostOffloadInfo(OffloadKinds,
  3433. /*BoundArch=*/nullptr);
  3434. }
  3435. // Add a link action if necessary.
  3436. if (LinkerInputs.empty()) {
  3437. Arg *FinalPhaseArg;
  3438. if (getFinalPhase(Args, &FinalPhaseArg) == phases::Link)
  3439. OffloadBuilder.appendDeviceLinkActions(Actions);
  3440. }
  3441. if (!LinkerInputs.empty()) {
  3442. if (!Args.hasArg(options::OPT_fopenmp_new_driver))
  3443. if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
  3444. LinkerInputs.push_back(Wrapper);
  3445. Action *LA;
  3446. // Check if this Linker Job should emit a static library.
  3447. if (ShouldEmitStaticLibrary(Args)) {
  3448. LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
  3449. } else if (Args.hasArg(options::OPT_fopenmp_new_driver) &&
  3450. OffloadKinds != Action::OFK_None) {
  3451. LA = C.MakeAction<LinkerWrapperJobAction>(LinkerInputs, types::TY_Image);
  3452. LA->propagateHostOffloadInfo(OffloadKinds,
  3453. /*BoundArch=*/nullptr);
  3454. } else {
  3455. LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
  3456. }
  3457. if (!Args.hasArg(options::OPT_fopenmp_new_driver))
  3458. LA = OffloadBuilder.processHostLinkAction(LA);
  3459. Actions.push_back(LA);
  3460. }
  3461. // Add an interface stubs merge action if necessary.
  3462. if (!MergerInputs.empty())
  3463. Actions.push_back(
  3464. C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
  3465. if (Args.hasArg(options::OPT_emit_interface_stubs)) {
  3466. auto PhaseList = types::getCompilationPhases(
  3467. types::TY_IFS_CPP,
  3468. Args.hasArg(options::OPT_c) ? phases::Compile : phases::IfsMerge);
  3469. ActionList MergerInputs;
  3470. for (auto &I : Inputs) {
  3471. types::ID InputType = I.first;
  3472. const Arg *InputArg = I.second;
  3473. // Currently clang and the llvm assembler do not support generating symbol
  3474. // stubs from assembly, so we skip the input on asm files. For ifs files
  3475. // we rely on the normal pipeline setup in the pipeline setup code above.
  3476. if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
  3477. InputType == types::TY_Asm)
  3478. continue;
  3479. Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
  3480. for (auto Phase : PhaseList) {
  3481. switch (Phase) {
  3482. default:
  3483. llvm_unreachable(
  3484. "IFS Pipeline can only consist of Compile followed by IfsMerge.");
  3485. case phases::Compile: {
  3486. // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
  3487. // files where the .o file is located. The compile action can not
  3488. // handle this.
  3489. if (InputType == types::TY_Object)
  3490. break;
  3491. Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
  3492. break;
  3493. }
  3494. case phases::IfsMerge: {
  3495. assert(Phase == PhaseList.back() &&
  3496. "merging must be final compilation step.");
  3497. MergerInputs.push_back(Current);
  3498. Current = nullptr;
  3499. break;
  3500. }
  3501. }
  3502. }
  3503. // If we ended with something, add to the output list.
  3504. if (Current)
  3505. Actions.push_back(Current);
  3506. }
  3507. // Add an interface stubs merge action if necessary.
  3508. if (!MergerInputs.empty())
  3509. Actions.push_back(
  3510. C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
  3511. }
  3512. // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
  3513. // Compile phase that prints out supported cpu models and quits.
  3514. if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
  3515. // Use the -mcpu=? flag as the dummy input to cc1.
  3516. Actions.clear();
  3517. Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
  3518. Actions.push_back(
  3519. C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
  3520. for (auto &I : Inputs)
  3521. I.second->claim();
  3522. }
  3523. // Claim ignored clang-cl options.
  3524. Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
  3525. // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
  3526. // to non-CUDA compilations and should not trigger warnings there.
  3527. Args.ClaimAllArgs(options::OPT_cuda_host_only);
  3528. Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
  3529. }
  3530. Action *Driver::BuildOffloadingActions(Compilation &C,
  3531. llvm::opt::DerivedArgList &Args,
  3532. const InputTy &Input,
  3533. Action *HostAction) const {
  3534. if (!isa<CompileJobAction>(HostAction))
  3535. return HostAction;
  3536. SmallVector<const ToolChain *, 2> ToolChains;
  3537. ActionList DeviceActions;
  3538. types::ID InputType = Input.first;
  3539. const Arg *InputArg = Input.second;
  3540. auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
  3541. for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE; ++TI)
  3542. ToolChains.push_back(TI->second);
  3543. for (unsigned I = 0; I < ToolChains.size(); ++I)
  3544. DeviceActions.push_back(C.MakeAction<InputAction>(*InputArg, InputType));
  3545. if (DeviceActions.empty())
  3546. return HostAction;
  3547. auto PL = types::getCompilationPhases(*this, Args, InputType);
  3548. for (phases::ID Phase : PL) {
  3549. if (Phase == phases::Link) {
  3550. assert(Phase == PL.back() && "linking must be final compilation step.");
  3551. break;
  3552. }
  3553. auto TC = ToolChains.begin();
  3554. for (Action *&A : DeviceActions) {
  3555. A = ConstructPhaseAction(C, Args, Phase, A, Action::OFK_OpenMP);
  3556. if (isa<CompileJobAction>(A)) {
  3557. HostAction->setCannotBeCollapsedWithNextDependentAction();
  3558. OffloadAction::HostDependence HDep(
  3559. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  3560. /*BourdArch=*/nullptr, Action::OFK_OpenMP);
  3561. OffloadAction::DeviceDependences DDep;
  3562. DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  3563. A = C.MakeAction<OffloadAction>(HDep, DDep);
  3564. }
  3565. ++TC;
  3566. }
  3567. }
  3568. OffloadAction::DeviceDependences DDeps;
  3569. auto TC = ToolChains.begin();
  3570. for (Action *A : DeviceActions) {
  3571. DDeps.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  3572. TC++;
  3573. }
  3574. OffloadAction::HostDependence HDep(
  3575. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  3576. /*BoundArch=*/nullptr, DDeps);
  3577. return C.MakeAction<OffloadAction>(HDep, DDeps);
  3578. }
  3579. Action *Driver::ConstructPhaseAction(
  3580. Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
  3581. Action::OffloadKind TargetDeviceOffloadKind) const {
  3582. llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
  3583. // Some types skip the assembler phase (e.g., llvm-bc), but we can't
  3584. // encode this in the steps because the intermediate type depends on
  3585. // arguments. Just special case here.
  3586. if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
  3587. return Input;
  3588. // Build the appropriate action.
  3589. switch (Phase) {
  3590. case phases::Link:
  3591. llvm_unreachable("link action invalid here.");
  3592. case phases::IfsMerge:
  3593. llvm_unreachable("ifsmerge action invalid here.");
  3594. case phases::Preprocess: {
  3595. types::ID OutputTy;
  3596. // -M and -MM specify the dependency file name by altering the output type,
  3597. // -if -MD and -MMD are not specified.
  3598. if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
  3599. !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
  3600. OutputTy = types::TY_Dependencies;
  3601. } else {
  3602. OutputTy = Input->getType();
  3603. if (!Args.hasFlag(options::OPT_frewrite_includes,
  3604. options::OPT_fno_rewrite_includes, false) &&
  3605. !Args.hasFlag(options::OPT_frewrite_imports,
  3606. options::OPT_fno_rewrite_imports, false) &&
  3607. !CCGenDiagnostics)
  3608. OutputTy = types::getPreprocessedType(OutputTy);
  3609. assert(OutputTy != types::TY_INVALID &&
  3610. "Cannot preprocess this input type!");
  3611. }
  3612. return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
  3613. }
  3614. case phases::Precompile: {
  3615. types::ID OutputTy = getPrecompiledType(Input->getType());
  3616. assert(OutputTy != types::TY_INVALID &&
  3617. "Cannot precompile this input type!");
  3618. // If we're given a module name, precompile header file inputs as a
  3619. // module, not as a precompiled header.
  3620. const char *ModName = nullptr;
  3621. if (OutputTy == types::TY_PCH) {
  3622. if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
  3623. ModName = A->getValue();
  3624. if (ModName)
  3625. OutputTy = types::TY_ModuleFile;
  3626. }
  3627. if (Args.hasArg(options::OPT_fsyntax_only) ||
  3628. Args.hasArg(options::OPT_extract_api)) {
  3629. // Syntax checks should not emit a PCH file
  3630. OutputTy = types::TY_Nothing;
  3631. }
  3632. if (ModName)
  3633. return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
  3634. ModName);
  3635. return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
  3636. }
  3637. case phases::Compile: {
  3638. if (Args.hasArg(options::OPT_fsyntax_only))
  3639. return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
  3640. if (Args.hasArg(options::OPT_rewrite_objc))
  3641. return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
  3642. if (Args.hasArg(options::OPT_rewrite_legacy_objc))
  3643. return C.MakeAction<CompileJobAction>(Input,
  3644. types::TY_RewrittenLegacyObjC);
  3645. if (Args.hasArg(options::OPT__analyze))
  3646. return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
  3647. if (Args.hasArg(options::OPT__migrate))
  3648. return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
  3649. if (Args.hasArg(options::OPT_emit_ast))
  3650. return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
  3651. if (Args.hasArg(options::OPT_module_file_info))
  3652. return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
  3653. if (Args.hasArg(options::OPT_verify_pch))
  3654. return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
  3655. if (Args.hasArg(options::OPT_extract_api))
  3656. return C.MakeAction<CompileJobAction>(Input, types::TY_API_INFO);
  3657. return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
  3658. }
  3659. case phases::Backend: {
  3660. if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
  3661. types::ID Output =
  3662. Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
  3663. return C.MakeAction<BackendJobAction>(Input, Output);
  3664. }
  3665. if (isUsingLTO(/* IsOffload */ true) &&
  3666. TargetDeviceOffloadKind == Action::OFK_OpenMP) {
  3667. types::ID Output =
  3668. Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
  3669. return C.MakeAction<BackendJobAction>(Input, Output);
  3670. }
  3671. if (Args.hasArg(options::OPT_emit_llvm) ||
  3672. (TargetDeviceOffloadKind == Action::OFK_HIP &&
  3673. Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
  3674. false))) {
  3675. types::ID Output =
  3676. Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
  3677. return C.MakeAction<BackendJobAction>(Input, Output);
  3678. }
  3679. return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
  3680. }
  3681. case phases::Assemble:
  3682. return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
  3683. }
  3684. llvm_unreachable("invalid phase in ConstructPhaseAction");
  3685. }
  3686. void Driver::BuildJobs(Compilation &C) const {
  3687. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  3688. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  3689. // It is an error to provide a -o option if we are making multiple output
  3690. // files. There are exceptions:
  3691. //
  3692. // IfsMergeJob: when generating interface stubs enabled we want to be able to
  3693. // generate the stub file at the same time that we generate the real
  3694. // library/a.out. So when a .o, .so, etc are the output, with clang interface
  3695. // stubs there will also be a .ifs and .ifso at the same location.
  3696. //
  3697. // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
  3698. // and -c is passed, we still want to be able to generate a .ifs file while
  3699. // we are also generating .o files. So we allow more than one output file in
  3700. // this case as well.
  3701. //
  3702. if (FinalOutput) {
  3703. unsigned NumOutputs = 0;
  3704. unsigned NumIfsOutputs = 0;
  3705. for (const Action *A : C.getActions())
  3706. if (A->getType() != types::TY_Nothing &&
  3707. !(A->getKind() == Action::IfsMergeJobClass ||
  3708. (A->getType() == clang::driver::types::TY_IFS_CPP &&
  3709. A->getKind() == clang::driver::Action::CompileJobClass &&
  3710. 0 == NumIfsOutputs++) ||
  3711. (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
  3712. A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
  3713. ++NumOutputs;
  3714. if (NumOutputs > 1) {
  3715. Diag(clang::diag::err_drv_output_argument_with_multiple_files);
  3716. FinalOutput = nullptr;
  3717. }
  3718. }
  3719. const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
  3720. if (RawTriple.isOSAIX()) {
  3721. if (Arg *A = C.getArgs().getLastArg(options::OPT_G))
  3722. Diag(diag::err_drv_unsupported_opt_for_target)
  3723. << A->getSpelling() << RawTriple.str();
  3724. if (LTOMode == LTOK_Thin)
  3725. Diag(diag::err_drv_clang_unsupported) << "thinLTO on AIX";
  3726. }
  3727. // Collect the list of architectures.
  3728. llvm::StringSet<> ArchNames;
  3729. if (RawTriple.isOSBinFormatMachO())
  3730. for (const Arg *A : C.getArgs())
  3731. if (A->getOption().matches(options::OPT_arch))
  3732. ArchNames.insert(A->getValue());
  3733. // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
  3734. std::map<std::pair<const Action *, std::string>, InputInfoList> CachedResults;
  3735. for (Action *A : C.getActions()) {
  3736. // If we are linking an image for multiple archs then the linker wants
  3737. // -arch_multiple and -final_output <final image name>. Unfortunately, this
  3738. // doesn't fit in cleanly because we have to pass this information down.
  3739. //
  3740. // FIXME: This is a hack; find a cleaner way to integrate this into the
  3741. // process.
  3742. const char *LinkingOutput = nullptr;
  3743. if (isa<LipoJobAction>(A)) {
  3744. if (FinalOutput)
  3745. LinkingOutput = FinalOutput->getValue();
  3746. else
  3747. LinkingOutput = getDefaultImageName();
  3748. }
  3749. BuildJobsForAction(C, A, &C.getDefaultToolChain(),
  3750. /*BoundArch*/ StringRef(),
  3751. /*AtTopLevel*/ true,
  3752. /*MultipleArchs*/ ArchNames.size() > 1,
  3753. /*LinkingOutput*/ LinkingOutput, CachedResults,
  3754. /*TargetDeviceOffloadKind*/ Action::OFK_None);
  3755. }
  3756. // If we have more than one job, then disable integrated-cc1 for now. Do this
  3757. // also when we need to report process execution statistics.
  3758. if (C.getJobs().size() > 1 || CCPrintProcessStats)
  3759. for (auto &J : C.getJobs())
  3760. J.InProcess = false;
  3761. if (CCPrintProcessStats) {
  3762. C.setPostCallback([=](const Command &Cmd, int Res) {
  3763. Optional<llvm::sys::ProcessStatistics> ProcStat =
  3764. Cmd.getProcessStatistics();
  3765. if (!ProcStat)
  3766. return;
  3767. const char *LinkingOutput = nullptr;
  3768. if (FinalOutput)
  3769. LinkingOutput = FinalOutput->getValue();
  3770. else if (!Cmd.getOutputFilenames().empty())
  3771. LinkingOutput = Cmd.getOutputFilenames().front().c_str();
  3772. else
  3773. LinkingOutput = getDefaultImageName();
  3774. if (CCPrintStatReportFilename.empty()) {
  3775. using namespace llvm;
  3776. // Human readable output.
  3777. outs() << sys::path::filename(Cmd.getExecutable()) << ": "
  3778. << "output=" << LinkingOutput;
  3779. outs() << ", total="
  3780. << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
  3781. << ", user="
  3782. << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
  3783. << ", mem=" << ProcStat->PeakMemory << " Kb\n";
  3784. } else {
  3785. // CSV format.
  3786. std::string Buffer;
  3787. llvm::raw_string_ostream Out(Buffer);
  3788. llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
  3789. /*Quote*/ true);
  3790. Out << ',';
  3791. llvm::sys::printArg(Out, LinkingOutput, true);
  3792. Out << ',' << ProcStat->TotalTime.count() << ','
  3793. << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
  3794. << '\n';
  3795. Out.flush();
  3796. std::error_code EC;
  3797. llvm::raw_fd_ostream OS(CCPrintStatReportFilename, EC,
  3798. llvm::sys::fs::OF_Append |
  3799. llvm::sys::fs::OF_Text);
  3800. if (EC)
  3801. return;
  3802. auto L = OS.lock();
  3803. if (!L) {
  3804. llvm::errs() << "ERROR: Cannot lock file "
  3805. << CCPrintStatReportFilename << ": "
  3806. << toString(L.takeError()) << "\n";
  3807. return;
  3808. }
  3809. OS << Buffer;
  3810. OS.flush();
  3811. }
  3812. });
  3813. }
  3814. // If the user passed -Qunused-arguments or there were errors, don't warn
  3815. // about any unused arguments.
  3816. if (Diags.hasErrorOccurred() ||
  3817. C.getArgs().hasArg(options::OPT_Qunused_arguments))
  3818. return;
  3819. // Claim -### here.
  3820. (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
  3821. // Claim --driver-mode, --rsp-quoting, it was handled earlier.
  3822. (void)C.getArgs().hasArg(options::OPT_driver_mode);
  3823. (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
  3824. for (Arg *A : C.getArgs()) {
  3825. // FIXME: It would be nice to be able to send the argument to the
  3826. // DiagnosticsEngine, so that extra values, position, and so on could be
  3827. // printed.
  3828. if (!A->isClaimed()) {
  3829. if (A->getOption().hasFlag(options::NoArgumentUnused))
  3830. continue;
  3831. // Suppress the warning automatically if this is just a flag, and it is an
  3832. // instance of an argument we already claimed.
  3833. const Option &Opt = A->getOption();
  3834. if (Opt.getKind() == Option::FlagClass) {
  3835. bool DuplicateClaimed = false;
  3836. for (const Arg *AA : C.getArgs().filtered(&Opt)) {
  3837. if (AA->isClaimed()) {
  3838. DuplicateClaimed = true;
  3839. break;
  3840. }
  3841. }
  3842. if (DuplicateClaimed)
  3843. continue;
  3844. }
  3845. // In clang-cl, don't mention unknown arguments here since they have
  3846. // already been warned about.
  3847. if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
  3848. Diag(clang::diag::warn_drv_unused_argument)
  3849. << A->getAsString(C.getArgs());
  3850. }
  3851. }
  3852. }
  3853. namespace {
  3854. /// Utility class to control the collapse of dependent actions and select the
  3855. /// tools accordingly.
  3856. class ToolSelector final {
  3857. /// The tool chain this selector refers to.
  3858. const ToolChain &TC;
  3859. /// The compilation this selector refers to.
  3860. const Compilation &C;
  3861. /// The base action this selector refers to.
  3862. const JobAction *BaseAction;
  3863. /// Set to true if the current toolchain refers to host actions.
  3864. bool IsHostSelector;
  3865. /// Set to true if save-temps and embed-bitcode functionalities are active.
  3866. bool SaveTemps;
  3867. bool EmbedBitcode;
  3868. /// Get previous dependent action or null if that does not exist. If
  3869. /// \a CanBeCollapsed is false, that action must be legal to collapse or
  3870. /// null will be returned.
  3871. const JobAction *getPrevDependentAction(const ActionList &Inputs,
  3872. ActionList &SavedOffloadAction,
  3873. bool CanBeCollapsed = true) {
  3874. // An option can be collapsed only if it has a single input.
  3875. if (Inputs.size() != 1)
  3876. return nullptr;
  3877. Action *CurAction = *Inputs.begin();
  3878. if (CanBeCollapsed &&
  3879. !CurAction->isCollapsingWithNextDependentActionLegal())
  3880. return nullptr;
  3881. // If the input action is an offload action. Look through it and save any
  3882. // offload action that can be dropped in the event of a collapse.
  3883. if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
  3884. // If the dependent action is a device action, we will attempt to collapse
  3885. // only with other device actions. Otherwise, we would do the same but
  3886. // with host actions only.
  3887. if (!IsHostSelector) {
  3888. if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
  3889. CurAction =
  3890. OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
  3891. if (CanBeCollapsed &&
  3892. !CurAction->isCollapsingWithNextDependentActionLegal())
  3893. return nullptr;
  3894. SavedOffloadAction.push_back(OA);
  3895. return dyn_cast<JobAction>(CurAction);
  3896. }
  3897. } else if (OA->hasHostDependence()) {
  3898. CurAction = OA->getHostDependence();
  3899. if (CanBeCollapsed &&
  3900. !CurAction->isCollapsingWithNextDependentActionLegal())
  3901. return nullptr;
  3902. SavedOffloadAction.push_back(OA);
  3903. return dyn_cast<JobAction>(CurAction);
  3904. }
  3905. return nullptr;
  3906. }
  3907. return dyn_cast<JobAction>(CurAction);
  3908. }
  3909. /// Return true if an assemble action can be collapsed.
  3910. bool canCollapseAssembleAction() const {
  3911. return TC.useIntegratedAs() && !SaveTemps &&
  3912. !C.getArgs().hasArg(options::OPT_via_file_asm) &&
  3913. !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
  3914. !C.getArgs().hasArg(options::OPT__SLASH_Fa);
  3915. }
  3916. /// Return true if a preprocessor action can be collapsed.
  3917. bool canCollapsePreprocessorAction() const {
  3918. return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
  3919. !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
  3920. !C.getArgs().hasArg(options::OPT_rewrite_objc);
  3921. }
  3922. /// Struct that relates an action with the offload actions that would be
  3923. /// collapsed with it.
  3924. struct JobActionInfo final {
  3925. /// The action this info refers to.
  3926. const JobAction *JA = nullptr;
  3927. /// The offload actions we need to take care off if this action is
  3928. /// collapsed.
  3929. ActionList SavedOffloadAction;
  3930. };
  3931. /// Append collapsed offload actions from the give nnumber of elements in the
  3932. /// action info array.
  3933. static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
  3934. ArrayRef<JobActionInfo> &ActionInfo,
  3935. unsigned ElementNum) {
  3936. assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
  3937. for (unsigned I = 0; I < ElementNum; ++I)
  3938. CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
  3939. ActionInfo[I].SavedOffloadAction.end());
  3940. }
  3941. /// Functions that attempt to perform the combining. They detect if that is
  3942. /// legal, and if so they update the inputs \a Inputs and the offload action
  3943. /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
  3944. /// the combined action is returned. If the combining is not legal or if the
  3945. /// tool does not exist, null is returned.
  3946. /// Currently three kinds of collapsing are supported:
  3947. /// - Assemble + Backend + Compile;
  3948. /// - Assemble + Backend ;
  3949. /// - Backend + Compile.
  3950. const Tool *
  3951. combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
  3952. ActionList &Inputs,
  3953. ActionList &CollapsedOffloadAction) {
  3954. if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
  3955. return nullptr;
  3956. auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
  3957. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
  3958. auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
  3959. if (!AJ || !BJ || !CJ)
  3960. return nullptr;
  3961. // Get compiler tool.
  3962. const Tool *T = TC.SelectTool(*CJ);
  3963. if (!T)
  3964. return nullptr;
  3965. // Can't collapse if we don't have codegen support unless we are
  3966. // emitting LLVM IR.
  3967. bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
  3968. if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
  3969. return nullptr;
  3970. // When using -fembed-bitcode, it is required to have the same tool (clang)
  3971. // for both CompilerJA and BackendJA. Otherwise, combine two stages.
  3972. if (EmbedBitcode) {
  3973. const Tool *BT = TC.SelectTool(*BJ);
  3974. if (BT == T)
  3975. return nullptr;
  3976. }
  3977. if (!T->hasIntegratedAssembler())
  3978. return nullptr;
  3979. Inputs = CJ->getInputs();
  3980. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  3981. /*NumElements=*/3);
  3982. return T;
  3983. }
  3984. const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
  3985. ActionList &Inputs,
  3986. ActionList &CollapsedOffloadAction) {
  3987. if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
  3988. return nullptr;
  3989. auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
  3990. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
  3991. if (!AJ || !BJ)
  3992. return nullptr;
  3993. // Get backend tool.
  3994. const Tool *T = TC.SelectTool(*BJ);
  3995. if (!T)
  3996. return nullptr;
  3997. if (!T->hasIntegratedAssembler())
  3998. return nullptr;
  3999. Inputs = BJ->getInputs();
  4000. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  4001. /*NumElements=*/2);
  4002. return T;
  4003. }
  4004. const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
  4005. ActionList &Inputs,
  4006. ActionList &CollapsedOffloadAction) {
  4007. if (ActionInfo.size() < 2)
  4008. return nullptr;
  4009. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
  4010. auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
  4011. if (!BJ || !CJ)
  4012. return nullptr;
  4013. // Check if the initial input (to the compile job or its predessor if one
  4014. // exists) is LLVM bitcode. In that case, no preprocessor step is required
  4015. // and we can still collapse the compile and backend jobs when we have
  4016. // -save-temps. I.e. there is no need for a separate compile job just to
  4017. // emit unoptimized bitcode.
  4018. bool InputIsBitcode = true;
  4019. for (size_t i = 1; i < ActionInfo.size(); i++)
  4020. if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
  4021. ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
  4022. InputIsBitcode = false;
  4023. break;
  4024. }
  4025. if (!InputIsBitcode && !canCollapsePreprocessorAction())
  4026. return nullptr;
  4027. // Get compiler tool.
  4028. const Tool *T = TC.SelectTool(*CJ);
  4029. if (!T)
  4030. return nullptr;
  4031. // Can't collapse if we don't have codegen support unless we are
  4032. // emitting LLVM IR.
  4033. bool OutputIsLLVM = types::isLLVMIR(ActionInfo[0].JA->getType());
  4034. if (!T->hasIntegratedBackend() && !(OutputIsLLVM && T->canEmitIR()))
  4035. return nullptr;
  4036. if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
  4037. return nullptr;
  4038. Inputs = CJ->getInputs();
  4039. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  4040. /*NumElements=*/2);
  4041. return T;
  4042. }
  4043. /// Updates the inputs if the obtained tool supports combining with
  4044. /// preprocessor action, and the current input is indeed a preprocessor
  4045. /// action. If combining results in the collapse of offloading actions, those
  4046. /// are appended to \a CollapsedOffloadAction.
  4047. void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
  4048. ActionList &CollapsedOffloadAction) {
  4049. if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
  4050. return;
  4051. // Attempt to get a preprocessor action dependence.
  4052. ActionList PreprocessJobOffloadActions;
  4053. ActionList NewInputs;
  4054. for (Action *A : Inputs) {
  4055. auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
  4056. if (!PJ || !isa<PreprocessJobAction>(PJ)) {
  4057. NewInputs.push_back(A);
  4058. continue;
  4059. }
  4060. // This is legal to combine. Append any offload action we found and add the
  4061. // current input to preprocessor inputs.
  4062. CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
  4063. PreprocessJobOffloadActions.end());
  4064. NewInputs.append(PJ->input_begin(), PJ->input_end());
  4065. }
  4066. Inputs = NewInputs;
  4067. }
  4068. public:
  4069. ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
  4070. const Compilation &C, bool SaveTemps, bool EmbedBitcode)
  4071. : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
  4072. EmbedBitcode(EmbedBitcode) {
  4073. assert(BaseAction && "Invalid base action.");
  4074. IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
  4075. }
  4076. /// Check if a chain of actions can be combined and return the tool that can
  4077. /// handle the combination of actions. The pointer to the current inputs \a
  4078. /// Inputs and the list of offload actions \a CollapsedOffloadActions
  4079. /// connected to collapsed actions are updated accordingly. The latter enables
  4080. /// the caller of the selector to process them afterwards instead of just
  4081. /// dropping them. If no suitable tool is found, null will be returned.
  4082. const Tool *getTool(ActionList &Inputs,
  4083. ActionList &CollapsedOffloadAction) {
  4084. //
  4085. // Get the largest chain of actions that we could combine.
  4086. //
  4087. SmallVector<JobActionInfo, 5> ActionChain(1);
  4088. ActionChain.back().JA = BaseAction;
  4089. while (ActionChain.back().JA) {
  4090. const Action *CurAction = ActionChain.back().JA;
  4091. // Grow the chain by one element.
  4092. ActionChain.resize(ActionChain.size() + 1);
  4093. JobActionInfo &AI = ActionChain.back();
  4094. // Attempt to fill it with the
  4095. AI.JA =
  4096. getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
  4097. }
  4098. // Pop the last action info as it could not be filled.
  4099. ActionChain.pop_back();
  4100. //
  4101. // Attempt to combine actions. If all combining attempts failed, just return
  4102. // the tool of the provided action. At the end we attempt to combine the
  4103. // action with any preprocessor action it may depend on.
  4104. //
  4105. const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
  4106. CollapsedOffloadAction);
  4107. if (!T)
  4108. T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
  4109. if (!T)
  4110. T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
  4111. if (!T) {
  4112. Inputs = BaseAction->getInputs();
  4113. T = TC.SelectTool(*BaseAction);
  4114. }
  4115. combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
  4116. return T;
  4117. }
  4118. };
  4119. }
  4120. /// Return a string that uniquely identifies the result of a job. The bound arch
  4121. /// is not necessarily represented in the toolchain's triple -- for example,
  4122. /// armv7 and armv7s both map to the same triple -- so we need both in our map.
  4123. /// Also, we need to add the offloading device kind, as the same tool chain can
  4124. /// be used for host and device for some programming models, e.g. OpenMP.
  4125. static std::string GetTriplePlusArchString(const ToolChain *TC,
  4126. StringRef BoundArch,
  4127. Action::OffloadKind OffloadKind) {
  4128. std::string TriplePlusArch = TC->getTriple().normalize();
  4129. if (!BoundArch.empty()) {
  4130. TriplePlusArch += "-";
  4131. TriplePlusArch += BoundArch;
  4132. }
  4133. TriplePlusArch += "-";
  4134. TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
  4135. return TriplePlusArch;
  4136. }
  4137. InputInfoList Driver::BuildJobsForAction(
  4138. Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
  4139. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  4140. std::map<std::pair<const Action *, std::string>, InputInfoList>
  4141. &CachedResults,
  4142. Action::OffloadKind TargetDeviceOffloadKind) const {
  4143. std::pair<const Action *, std::string> ActionTC = {
  4144. A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
  4145. auto CachedResult = CachedResults.find(ActionTC);
  4146. if (CachedResult != CachedResults.end()) {
  4147. return CachedResult->second;
  4148. }
  4149. InputInfoList Result = BuildJobsForActionNoCache(
  4150. C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
  4151. CachedResults, TargetDeviceOffloadKind);
  4152. CachedResults[ActionTC] = Result;
  4153. return Result;
  4154. }
  4155. InputInfoList Driver::BuildJobsForActionNoCache(
  4156. Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
  4157. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  4158. std::map<std::pair<const Action *, std::string>, InputInfoList>
  4159. &CachedResults,
  4160. Action::OffloadKind TargetDeviceOffloadKind) const {
  4161. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  4162. InputInfoList OffloadDependencesInputInfo;
  4163. bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
  4164. if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
  4165. // The 'Darwin' toolchain is initialized only when its arguments are
  4166. // computed. Get the default arguments for OFK_None to ensure that
  4167. // initialization is performed before processing the offload action.
  4168. // FIXME: Remove when darwin's toolchain is initialized during construction.
  4169. C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
  4170. // The offload action is expected to be used in four different situations.
  4171. //
  4172. // a) Set a toolchain/architecture/kind for a host action:
  4173. // Host Action 1 -> OffloadAction -> Host Action 2
  4174. //
  4175. // b) Set a toolchain/architecture/kind for a device action;
  4176. // Device Action 1 -> OffloadAction -> Device Action 2
  4177. //
  4178. // c) Specify a device dependence to a host action;
  4179. // Device Action 1 _
  4180. // \
  4181. // Host Action 1 ---> OffloadAction -> Host Action 2
  4182. //
  4183. // d) Specify a host dependence to a device action.
  4184. // Host Action 1 _
  4185. // \
  4186. // Device Action 1 ---> OffloadAction -> Device Action 2
  4187. //
  4188. // For a) and b), we just return the job generated for the dependence. For
  4189. // c) and d) we override the current action with the host/device dependence
  4190. // if the current toolchain is host/device and set the offload dependences
  4191. // info with the jobs obtained from the device/host dependence(s).
  4192. // If there is a single device option, just generate the job for it.
  4193. if (OA->hasSingleDeviceDependence()) {
  4194. InputInfoList DevA;
  4195. OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
  4196. const char *DepBoundArch) {
  4197. DevA =
  4198. BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
  4199. /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
  4200. CachedResults, DepA->getOffloadingDeviceKind());
  4201. });
  4202. return DevA;
  4203. }
  4204. // If 'Action 2' is host, we generate jobs for the device dependences and
  4205. // override the current action with the host dependence. Otherwise, we
  4206. // generate the host dependences and override the action with the device
  4207. // dependence. The dependences can't therefore be a top-level action.
  4208. OA->doOnEachDependence(
  4209. /*IsHostDependence=*/BuildingForOffloadDevice,
  4210. [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
  4211. OffloadDependencesInputInfo.append(BuildJobsForAction(
  4212. C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
  4213. /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
  4214. DepA->getOffloadingDeviceKind()));
  4215. });
  4216. A = BuildingForOffloadDevice
  4217. ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
  4218. : OA->getHostDependence();
  4219. // We may have already built this action as a part of the offloading
  4220. // toolchain, return the cached input if so.
  4221. std::pair<const Action *, std::string> ActionTC = {
  4222. OA->getHostDependence(),
  4223. GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
  4224. if (CachedResults.find(ActionTC) != CachedResults.end()) {
  4225. InputInfoList Inputs = CachedResults[ActionTC];
  4226. Inputs.append(OffloadDependencesInputInfo);
  4227. return Inputs;
  4228. }
  4229. }
  4230. if (const InputAction *IA = dyn_cast<InputAction>(A)) {
  4231. // FIXME: It would be nice to not claim this here; maybe the old scheme of
  4232. // just using Args was better?
  4233. const Arg &Input = IA->getInputArg();
  4234. Input.claim();
  4235. if (Input.getOption().matches(options::OPT_INPUT)) {
  4236. const char *Name = Input.getValue();
  4237. return {InputInfo(A, Name, /* _BaseInput = */ Name)};
  4238. }
  4239. return {InputInfo(A, &Input, /* _BaseInput = */ "")};
  4240. }
  4241. if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
  4242. const ToolChain *TC;
  4243. StringRef ArchName = BAA->getArchName();
  4244. if (!ArchName.empty())
  4245. TC = &getToolChain(C.getArgs(),
  4246. computeTargetTriple(*this, TargetTriple,
  4247. C.getArgs(), ArchName));
  4248. else
  4249. TC = &C.getDefaultToolChain();
  4250. return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
  4251. MultipleArchs, LinkingOutput, CachedResults,
  4252. TargetDeviceOffloadKind);
  4253. }
  4254. ActionList Inputs = A->getInputs();
  4255. const JobAction *JA = cast<JobAction>(A);
  4256. ActionList CollapsedOffloadActions;
  4257. ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
  4258. embedBitcodeInObject() && !isUsingLTO());
  4259. const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
  4260. if (!T)
  4261. return {InputInfo()};
  4262. if (BuildingForOffloadDevice &&
  4263. A->getOffloadingDeviceKind() == Action::OFK_OpenMP) {
  4264. if (TC->getTriple().isAMDGCN()) {
  4265. // AMDGCN treats backend and assemble actions as no-op because
  4266. // linker does not support object files.
  4267. if (const BackendJobAction *BA = dyn_cast<BackendJobAction>(A)) {
  4268. return BuildJobsForAction(C, *BA->input_begin(), TC, BoundArch,
  4269. AtTopLevel, MultipleArchs, LinkingOutput,
  4270. CachedResults, TargetDeviceOffloadKind);
  4271. }
  4272. if (const AssembleJobAction *AA = dyn_cast<AssembleJobAction>(A)) {
  4273. return BuildJobsForAction(C, *AA->input_begin(), TC, BoundArch,
  4274. AtTopLevel, MultipleArchs, LinkingOutput,
  4275. CachedResults, TargetDeviceOffloadKind);
  4276. }
  4277. }
  4278. }
  4279. // If we've collapsed action list that contained OffloadAction we
  4280. // need to build jobs for host/device-side inputs it may have held.
  4281. for (const auto *OA : CollapsedOffloadActions)
  4282. cast<OffloadAction>(OA)->doOnEachDependence(
  4283. /*IsHostDependence=*/BuildingForOffloadDevice,
  4284. [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
  4285. OffloadDependencesInputInfo.append(BuildJobsForAction(
  4286. C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
  4287. /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
  4288. DepA->getOffloadingDeviceKind()));
  4289. });
  4290. // Only use pipes when there is exactly one input.
  4291. InputInfoList InputInfos;
  4292. for (const Action *Input : Inputs) {
  4293. // Treat dsymutil and verify sub-jobs as being at the top-level too, they
  4294. // shouldn't get temporary output names.
  4295. // FIXME: Clean this up.
  4296. bool SubJobAtTopLevel =
  4297. AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
  4298. InputInfos.append(BuildJobsForAction(
  4299. C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
  4300. CachedResults, A->getOffloadingDeviceKind()));
  4301. }
  4302. // Always use the first file input as the base input.
  4303. const char *BaseInput = InputInfos[0].getBaseInput();
  4304. for (auto &Info : InputInfos) {
  4305. if (Info.isFilename()) {
  4306. BaseInput = Info.getBaseInput();
  4307. break;
  4308. }
  4309. }
  4310. // ... except dsymutil actions, which use their actual input as the base
  4311. // input.
  4312. if (JA->getType() == types::TY_dSYM)
  4313. BaseInput = InputInfos[0].getFilename();
  4314. // ... and in header module compilations, which use the module name.
  4315. if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
  4316. BaseInput = ModuleJA->getModuleName();
  4317. // Append outputs of offload device jobs to the input list
  4318. if (!OffloadDependencesInputInfo.empty())
  4319. InputInfos.append(OffloadDependencesInputInfo.begin(),
  4320. OffloadDependencesInputInfo.end());
  4321. // Set the effective triple of the toolchain for the duration of this job.
  4322. llvm::Triple EffectiveTriple;
  4323. const ToolChain &ToolTC = T->getToolChain();
  4324. const ArgList &Args =
  4325. C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
  4326. if (InputInfos.size() != 1) {
  4327. EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
  4328. } else {
  4329. // Pass along the input type if it can be unambiguously determined.
  4330. EffectiveTriple = llvm::Triple(
  4331. ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
  4332. }
  4333. RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
  4334. // Determine the place to write output to, if any.
  4335. InputInfo Result;
  4336. InputInfoList UnbundlingResults;
  4337. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
  4338. // If we have an unbundling job, we need to create results for all the
  4339. // outputs. We also update the results cache so that other actions using
  4340. // this unbundling action can get the right results.
  4341. for (auto &UI : UA->getDependentActionsInfo()) {
  4342. assert(UI.DependentOffloadKind != Action::OFK_None &&
  4343. "Unbundling with no offloading??");
  4344. // Unbundling actions are never at the top level. When we generate the
  4345. // offloading prefix, we also do that for the host file because the
  4346. // unbundling action does not change the type of the output which can
  4347. // cause a overwrite.
  4348. std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
  4349. UI.DependentOffloadKind,
  4350. UI.DependentToolChain->getTriple().normalize(),
  4351. /*CreatePrefixForHost=*/true);
  4352. auto CurI = InputInfo(
  4353. UA,
  4354. GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
  4355. /*AtTopLevel=*/false,
  4356. MultipleArchs ||
  4357. UI.DependentOffloadKind == Action::OFK_HIP,
  4358. OffloadingPrefix),
  4359. BaseInput);
  4360. // Save the unbundling result.
  4361. UnbundlingResults.push_back(CurI);
  4362. // Get the unique string identifier for this dependence and cache the
  4363. // result.
  4364. StringRef Arch;
  4365. if (TargetDeviceOffloadKind == Action::OFK_HIP) {
  4366. if (UI.DependentOffloadKind == Action::OFK_Host)
  4367. Arch = StringRef();
  4368. else
  4369. Arch = UI.DependentBoundArch;
  4370. } else
  4371. Arch = BoundArch;
  4372. CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
  4373. UI.DependentOffloadKind)}] = {
  4374. CurI};
  4375. }
  4376. // Now that we have all the results generated, select the one that should be
  4377. // returned for the current depending action.
  4378. std::pair<const Action *, std::string> ActionTC = {
  4379. A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
  4380. assert(CachedResults.find(ActionTC) != CachedResults.end() &&
  4381. "Result does not exist??");
  4382. Result = CachedResults[ActionTC].front();
  4383. } else if (JA->getType() == types::TY_Nothing)
  4384. Result = {InputInfo(A, BaseInput)};
  4385. else {
  4386. // We only have to generate a prefix for the host if this is not a top-level
  4387. // action.
  4388. std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
  4389. A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
  4390. /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
  4391. !AtTopLevel);
  4392. if (isa<OffloadWrapperJobAction>(JA)) {
  4393. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  4394. BaseInput = FinalOutput->getValue();
  4395. else
  4396. BaseInput = getDefaultImageName();
  4397. BaseInput =
  4398. C.getArgs().MakeArgString(std::string(BaseInput) + "-wrapper");
  4399. }
  4400. Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
  4401. AtTopLevel, MultipleArchs,
  4402. OffloadingPrefix),
  4403. BaseInput);
  4404. }
  4405. if (CCCPrintBindings && !CCGenDiagnostics) {
  4406. llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
  4407. << " - \"" << T->getName() << "\", inputs: [";
  4408. for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
  4409. llvm::errs() << InputInfos[i].getAsString();
  4410. if (i + 1 != e)
  4411. llvm::errs() << ", ";
  4412. }
  4413. if (UnbundlingResults.empty())
  4414. llvm::errs() << "], output: " << Result.getAsString() << "\n";
  4415. else {
  4416. llvm::errs() << "], outputs: [";
  4417. for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
  4418. llvm::errs() << UnbundlingResults[i].getAsString();
  4419. if (i + 1 != e)
  4420. llvm::errs() << ", ";
  4421. }
  4422. llvm::errs() << "] \n";
  4423. }
  4424. } else {
  4425. if (UnbundlingResults.empty())
  4426. T->ConstructJob(
  4427. C, *JA, Result, InputInfos,
  4428. C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
  4429. LinkingOutput);
  4430. else
  4431. T->ConstructJobMultipleOutputs(
  4432. C, *JA, UnbundlingResults, InputInfos,
  4433. C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
  4434. LinkingOutput);
  4435. }
  4436. return {Result};
  4437. }
  4438. const char *Driver::getDefaultImageName() const {
  4439. llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
  4440. return Target.isOSWindows() ? "a.exe" : "a.out";
  4441. }
  4442. /// Create output filename based on ArgValue, which could either be a
  4443. /// full filename, filename without extension, or a directory. If ArgValue
  4444. /// does not provide a filename, then use BaseName, and use the extension
  4445. /// suitable for FileType.
  4446. static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
  4447. StringRef BaseName,
  4448. types::ID FileType) {
  4449. SmallString<128> Filename = ArgValue;
  4450. if (ArgValue.empty()) {
  4451. // If the argument is empty, output to BaseName in the current dir.
  4452. Filename = BaseName;
  4453. } else if (llvm::sys::path::is_separator(Filename.back())) {
  4454. // If the argument is a directory, output to BaseName in that dir.
  4455. llvm::sys::path::append(Filename, BaseName);
  4456. }
  4457. if (!llvm::sys::path::has_extension(ArgValue)) {
  4458. // If the argument didn't provide an extension, then set it.
  4459. const char *Extension = types::getTypeTempSuffix(FileType, true);
  4460. if (FileType == types::TY_Image &&
  4461. Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
  4462. // The output file is a dll.
  4463. Extension = "dll";
  4464. }
  4465. llvm::sys::path::replace_extension(Filename, Extension);
  4466. }
  4467. return Args.MakeArgString(Filename.c_str());
  4468. }
  4469. static bool HasPreprocessOutput(const Action &JA) {
  4470. if (isa<PreprocessJobAction>(JA))
  4471. return true;
  4472. if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
  4473. return true;
  4474. if (isa<OffloadBundlingJobAction>(JA) &&
  4475. HasPreprocessOutput(*(JA.getInputs()[0])))
  4476. return true;
  4477. return false;
  4478. }
  4479. const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
  4480. const char *BaseInput,
  4481. StringRef OrigBoundArch, bool AtTopLevel,
  4482. bool MultipleArchs,
  4483. StringRef OffloadingPrefix) const {
  4484. std::string BoundArch = OrigBoundArch.str();
  4485. if (is_style_windows(llvm::sys::path::Style::native)) {
  4486. // BoundArch may contains ':', which is invalid in file names on Windows,
  4487. // therefore replace it with '%'.
  4488. std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
  4489. }
  4490. llvm::PrettyStackTraceString CrashInfo("Computing output path");
  4491. // Output to a user requested destination?
  4492. if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
  4493. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  4494. return C.addResultFile(FinalOutput->getValue(), &JA);
  4495. }
  4496. // For /P, preprocess to file named after BaseInput.
  4497. if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
  4498. assert(AtTopLevel && isa<PreprocessJobAction>(JA));
  4499. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  4500. StringRef NameArg;
  4501. if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
  4502. NameArg = A->getValue();
  4503. return C.addResultFile(
  4504. MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
  4505. &JA);
  4506. }
  4507. // Default to writing to stdout?
  4508. if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
  4509. return "-";
  4510. }
  4511. if (JA.getType() == types::TY_ModuleFile &&
  4512. C.getArgs().getLastArg(options::OPT_module_file_info)) {
  4513. return "-";
  4514. }
  4515. // Is this the assembly listing for /FA?
  4516. if (JA.getType() == types::TY_PP_Asm &&
  4517. (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
  4518. C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
  4519. // Use /Fa and the input filename to determine the asm file name.
  4520. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  4521. StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
  4522. return C.addResultFile(
  4523. MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
  4524. &JA);
  4525. }
  4526. // Output to a temporary file?
  4527. if ((!AtTopLevel && !isSaveTempsEnabled() &&
  4528. !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
  4529. CCGenDiagnostics) {
  4530. StringRef Name = llvm::sys::path::filename(BaseInput);
  4531. std::pair<StringRef, StringRef> Split = Name.split('.');
  4532. SmallString<128> TmpName;
  4533. const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
  4534. Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
  4535. if (CCGenDiagnostics && A) {
  4536. SmallString<128> CrashDirectory(A->getValue());
  4537. if (!getVFS().exists(CrashDirectory))
  4538. llvm::sys::fs::create_directories(CrashDirectory);
  4539. llvm::sys::path::append(CrashDirectory, Split.first);
  4540. const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
  4541. std::error_code EC = llvm::sys::fs::createUniqueFile(
  4542. CrashDirectory + Middle + Suffix, TmpName);
  4543. if (EC) {
  4544. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  4545. return "";
  4546. }
  4547. } else {
  4548. if (MultipleArchs && !BoundArch.empty()) {
  4549. TmpName = GetTemporaryDirectory(Split.first);
  4550. llvm::sys::path::append(TmpName,
  4551. Split.first + "-" + BoundArch + "." + Suffix);
  4552. } else {
  4553. TmpName = GetTemporaryPath(Split.first, Suffix);
  4554. }
  4555. }
  4556. return C.addTempFile(C.getArgs().MakeArgString(TmpName));
  4557. }
  4558. SmallString<128> BasePath(BaseInput);
  4559. SmallString<128> ExternalPath("");
  4560. StringRef BaseName;
  4561. // Dsymutil actions should use the full path.
  4562. if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
  4563. ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
  4564. // We use posix style here because the tests (specifically
  4565. // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
  4566. // even on Windows and if we don't then the similar test covering this
  4567. // fails.
  4568. llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
  4569. llvm::sys::path::filename(BasePath));
  4570. BaseName = ExternalPath;
  4571. } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
  4572. BaseName = BasePath;
  4573. else
  4574. BaseName = llvm::sys::path::filename(BasePath);
  4575. // Determine what the derived output name should be.
  4576. const char *NamedOutput;
  4577. if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
  4578. C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
  4579. // The /Fo or /o flag decides the object filename.
  4580. StringRef Val =
  4581. C.getArgs()
  4582. .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
  4583. ->getValue();
  4584. NamedOutput =
  4585. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
  4586. } else if (JA.getType() == types::TY_Image &&
  4587. C.getArgs().hasArg(options::OPT__SLASH_Fe,
  4588. options::OPT__SLASH_o)) {
  4589. // The /Fe or /o flag names the linked file.
  4590. StringRef Val =
  4591. C.getArgs()
  4592. .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
  4593. ->getValue();
  4594. NamedOutput =
  4595. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
  4596. } else if (JA.getType() == types::TY_Image) {
  4597. if (IsCLMode()) {
  4598. // clang-cl uses BaseName for the executable name.
  4599. NamedOutput =
  4600. MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
  4601. } else {
  4602. SmallString<128> Output(getDefaultImageName());
  4603. // HIP image for device compilation with -fno-gpu-rdc is per compilation
  4604. // unit.
  4605. bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
  4606. !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
  4607. options::OPT_fno_gpu_rdc, false);
  4608. if (IsHIPNoRDC) {
  4609. Output = BaseName;
  4610. llvm::sys::path::replace_extension(Output, "");
  4611. }
  4612. Output += OffloadingPrefix;
  4613. if (MultipleArchs && !BoundArch.empty()) {
  4614. Output += "-";
  4615. Output.append(BoundArch);
  4616. }
  4617. if (IsHIPNoRDC)
  4618. Output += ".out";
  4619. NamedOutput = C.getArgs().MakeArgString(Output.c_str());
  4620. }
  4621. } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
  4622. NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
  4623. } else {
  4624. const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
  4625. assert(Suffix && "All types used for output should have a suffix.");
  4626. std::string::size_type End = std::string::npos;
  4627. if (!types::appendSuffixForType(JA.getType()))
  4628. End = BaseName.rfind('.');
  4629. SmallString<128> Suffixed(BaseName.substr(0, End));
  4630. Suffixed += OffloadingPrefix;
  4631. if (MultipleArchs && !BoundArch.empty()) {
  4632. Suffixed += "-";
  4633. Suffixed.append(BoundArch);
  4634. }
  4635. // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
  4636. // the unoptimized bitcode so that it does not get overwritten by the ".bc"
  4637. // optimized bitcode output.
  4638. auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
  4639. const llvm::opt::DerivedArgList &Args) {
  4640. // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
  4641. // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
  4642. // phase.)
  4643. return isa<CompileJobAction>(JA) &&
  4644. JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
  4645. Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
  4646. false);
  4647. };
  4648. if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
  4649. (C.getArgs().hasArg(options::OPT_emit_llvm) ||
  4650. IsHIPRDCInCompilePhase(JA, C.getArgs())))
  4651. Suffixed += ".tmp";
  4652. Suffixed += '.';
  4653. Suffixed += Suffix;
  4654. NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
  4655. }
  4656. // Prepend object file path if -save-temps=obj
  4657. if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
  4658. JA.getType() != types::TY_PCH) {
  4659. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  4660. SmallString<128> TempPath(FinalOutput->getValue());
  4661. llvm::sys::path::remove_filename(TempPath);
  4662. StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
  4663. llvm::sys::path::append(TempPath, OutputFileName);
  4664. NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
  4665. }
  4666. // If we're saving temps and the temp file conflicts with the input file,
  4667. // then avoid overwriting input file.
  4668. if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
  4669. bool SameFile = false;
  4670. SmallString<256> Result;
  4671. llvm::sys::fs::current_path(Result);
  4672. llvm::sys::path::append(Result, BaseName);
  4673. llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
  4674. // Must share the same path to conflict.
  4675. if (SameFile) {
  4676. StringRef Name = llvm::sys::path::filename(BaseInput);
  4677. std::pair<StringRef, StringRef> Split = Name.split('.');
  4678. std::string TmpName = GetTemporaryPath(
  4679. Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  4680. return C.addTempFile(C.getArgs().MakeArgString(TmpName));
  4681. }
  4682. }
  4683. // As an annoying special case, PCH generation doesn't strip the pathname.
  4684. if (JA.getType() == types::TY_PCH && !IsCLMode()) {
  4685. llvm::sys::path::remove_filename(BasePath);
  4686. if (BasePath.empty())
  4687. BasePath = NamedOutput;
  4688. else
  4689. llvm::sys::path::append(BasePath, NamedOutput);
  4690. return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
  4691. } else {
  4692. return C.addResultFile(NamedOutput, &JA);
  4693. }
  4694. }
  4695. std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
  4696. // Search for Name in a list of paths.
  4697. auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
  4698. -> llvm::Optional<std::string> {
  4699. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  4700. // attempting to use this prefix when looking for file paths.
  4701. for (const auto &Dir : P) {
  4702. if (Dir.empty())
  4703. continue;
  4704. SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
  4705. llvm::sys::path::append(P, Name);
  4706. if (llvm::sys::fs::exists(Twine(P)))
  4707. return std::string(P);
  4708. }
  4709. return None;
  4710. };
  4711. if (auto P = SearchPaths(PrefixDirs))
  4712. return *P;
  4713. SmallString<128> R(ResourceDir);
  4714. llvm::sys::path::append(R, Name);
  4715. if (llvm::sys::fs::exists(Twine(R)))
  4716. return std::string(R.str());
  4717. SmallString<128> P(TC.getCompilerRTPath());
  4718. llvm::sys::path::append(P, Name);
  4719. if (llvm::sys::fs::exists(Twine(P)))
  4720. return std::string(P.str());
  4721. SmallString<128> D(Dir);
  4722. llvm::sys::path::append(D, "..", Name);
  4723. if (llvm::sys::fs::exists(Twine(D)))
  4724. return std::string(D.str());
  4725. if (auto P = SearchPaths(TC.getLibraryPaths()))
  4726. return *P;
  4727. if (auto P = SearchPaths(TC.getFilePaths()))
  4728. return *P;
  4729. return std::string(Name);
  4730. }
  4731. void Driver::generatePrefixedToolNames(
  4732. StringRef Tool, const ToolChain &TC,
  4733. SmallVectorImpl<std::string> &Names) const {
  4734. // FIXME: Needs a better variable than TargetTriple
  4735. Names.emplace_back((TargetTriple + "-" + Tool).str());
  4736. Names.emplace_back(Tool);
  4737. }
  4738. static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
  4739. llvm::sys::path::append(Dir, Name);
  4740. if (llvm::sys::fs::can_execute(Twine(Dir)))
  4741. return true;
  4742. llvm::sys::path::remove_filename(Dir);
  4743. return false;
  4744. }
  4745. std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
  4746. SmallVector<std::string, 2> TargetSpecificExecutables;
  4747. generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
  4748. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  4749. // attempting to use this prefix when looking for program paths.
  4750. for (const auto &PrefixDir : PrefixDirs) {
  4751. if (llvm::sys::fs::is_directory(PrefixDir)) {
  4752. SmallString<128> P(PrefixDir);
  4753. if (ScanDirForExecutable(P, Name))
  4754. return std::string(P.str());
  4755. } else {
  4756. SmallString<128> P((PrefixDir + Name).str());
  4757. if (llvm::sys::fs::can_execute(Twine(P)))
  4758. return std::string(P.str());
  4759. }
  4760. }
  4761. const ToolChain::path_list &List = TC.getProgramPaths();
  4762. for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
  4763. // For each possible name of the tool look for it in
  4764. // program paths first, then the path.
  4765. // Higher priority names will be first, meaning that
  4766. // a higher priority name in the path will be found
  4767. // instead of a lower priority name in the program path.
  4768. // E.g. <triple>-gcc on the path will be found instead
  4769. // of gcc in the program path
  4770. for (const auto &Path : List) {
  4771. SmallString<128> P(Path);
  4772. if (ScanDirForExecutable(P, TargetSpecificExecutable))
  4773. return std::string(P.str());
  4774. }
  4775. // Fall back to the path
  4776. if (llvm::ErrorOr<std::string> P =
  4777. llvm::sys::findProgramByName(TargetSpecificExecutable))
  4778. return *P;
  4779. }
  4780. return std::string(Name);
  4781. }
  4782. std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
  4783. SmallString<128> Path;
  4784. std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
  4785. if (EC) {
  4786. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  4787. return "";
  4788. }
  4789. return std::string(Path.str());
  4790. }
  4791. std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
  4792. SmallString<128> Path;
  4793. std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
  4794. if (EC) {
  4795. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  4796. return "";
  4797. }
  4798. return std::string(Path.str());
  4799. }
  4800. std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
  4801. SmallString<128> Output;
  4802. if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
  4803. // FIXME: If anybody needs it, implement this obscure rule:
  4804. // "If you specify a directory without a file name, the default file name
  4805. // is VCx0.pch., where x is the major version of Visual C++ in use."
  4806. Output = FpArg->getValue();
  4807. // "If you do not specify an extension as part of the path name, an
  4808. // extension of .pch is assumed. "
  4809. if (!llvm::sys::path::has_extension(Output))
  4810. Output += ".pch";
  4811. } else {
  4812. if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
  4813. Output = YcArg->getValue();
  4814. if (Output.empty())
  4815. Output = BaseName;
  4816. llvm::sys::path::replace_extension(Output, ".pch");
  4817. }
  4818. return std::string(Output.str());
  4819. }
  4820. const ToolChain &Driver::getToolChain(const ArgList &Args,
  4821. const llvm::Triple &Target) const {
  4822. auto &TC = ToolChains[Target.str()];
  4823. if (!TC) {
  4824. switch (Target.getOS()) {
  4825. case llvm::Triple::AIX:
  4826. TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
  4827. break;
  4828. case llvm::Triple::Haiku:
  4829. TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
  4830. break;
  4831. case llvm::Triple::Ananas:
  4832. TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
  4833. break;
  4834. case llvm::Triple::CloudABI:
  4835. TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
  4836. break;
  4837. case llvm::Triple::Darwin:
  4838. case llvm::Triple::MacOSX:
  4839. case llvm::Triple::IOS:
  4840. case llvm::Triple::TvOS:
  4841. case llvm::Triple::WatchOS:
  4842. TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
  4843. break;
  4844. case llvm::Triple::DragonFly:
  4845. TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
  4846. break;
  4847. case llvm::Triple::OpenBSD:
  4848. TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
  4849. break;
  4850. case llvm::Triple::NetBSD:
  4851. TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
  4852. break;
  4853. case llvm::Triple::FreeBSD:
  4854. if (Target.isPPC())
  4855. TC = std::make_unique<toolchains::PPCFreeBSDToolChain>(*this, Target,
  4856. Args);
  4857. else
  4858. TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
  4859. break;
  4860. case llvm::Triple::Minix:
  4861. TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
  4862. break;
  4863. case llvm::Triple::Linux:
  4864. case llvm::Triple::ELFIAMCU:
  4865. if (Target.getArch() == llvm::Triple::hexagon)
  4866. TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
  4867. Args);
  4868. else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
  4869. !Target.hasEnvironment())
  4870. TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
  4871. Args);
  4872. else if (Target.isPPC())
  4873. TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
  4874. Args);
  4875. else if (Target.getArch() == llvm::Triple::ve)
  4876. TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
  4877. else
  4878. TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
  4879. break;
  4880. case llvm::Triple::NaCl:
  4881. TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
  4882. break;
  4883. case llvm::Triple::Fuchsia:
  4884. TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
  4885. break;
  4886. case llvm::Triple::Solaris:
  4887. TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
  4888. break;
  4889. case llvm::Triple::AMDHSA:
  4890. TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
  4891. break;
  4892. case llvm::Triple::AMDPAL:
  4893. case llvm::Triple::Mesa3D:
  4894. TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
  4895. break;
  4896. case llvm::Triple::Win32:
  4897. switch (Target.getEnvironment()) {
  4898. default:
  4899. if (Target.isOSBinFormatELF())
  4900. TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
  4901. else if (Target.isOSBinFormatMachO())
  4902. TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
  4903. else
  4904. TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
  4905. break;
  4906. case llvm::Triple::GNU:
  4907. TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
  4908. break;
  4909. case llvm::Triple::Itanium:
  4910. TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
  4911. Args);
  4912. break;
  4913. case llvm::Triple::MSVC:
  4914. case llvm::Triple::UnknownEnvironment:
  4915. if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
  4916. .startswith_insensitive("bfd"))
  4917. TC = std::make_unique<toolchains::CrossWindowsToolChain>(
  4918. *this, Target, Args);
  4919. else
  4920. TC =
  4921. std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
  4922. break;
  4923. }
  4924. break;
  4925. case llvm::Triple::PS4:
  4926. TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
  4927. break;
  4928. case llvm::Triple::Contiki:
  4929. TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
  4930. break;
  4931. case llvm::Triple::Hurd:
  4932. TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
  4933. break;
  4934. case llvm::Triple::ZOS:
  4935. TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
  4936. break;
  4937. default:
  4938. // Of these targets, Hexagon is the only one that might have
  4939. // an OS of Linux, in which case it got handled above already.
  4940. switch (Target.getArch()) {
  4941. case llvm::Triple::tce:
  4942. TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
  4943. break;
  4944. case llvm::Triple::tcele:
  4945. TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
  4946. break;
  4947. case llvm::Triple::hexagon:
  4948. TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
  4949. Args);
  4950. break;
  4951. case llvm::Triple::lanai:
  4952. TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
  4953. break;
  4954. case llvm::Triple::xcore:
  4955. TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
  4956. break;
  4957. case llvm::Triple::wasm32:
  4958. case llvm::Triple::wasm64:
  4959. TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
  4960. break;
  4961. case llvm::Triple::avr:
  4962. TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
  4963. break;
  4964. case llvm::Triple::msp430:
  4965. TC =
  4966. std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
  4967. break;
  4968. case llvm::Triple::riscv32:
  4969. case llvm::Triple::riscv64:
  4970. if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
  4971. TC =
  4972. std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
  4973. else
  4974. TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
  4975. break;
  4976. case llvm::Triple::ve:
  4977. TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
  4978. break;
  4979. case llvm::Triple::spirv32:
  4980. case llvm::Triple::spirv64:
  4981. TC = std::make_unique<toolchains::SPIRVToolChain>(*this, Target, Args);
  4982. break;
  4983. default:
  4984. if (Target.getVendor() == llvm::Triple::Myriad)
  4985. TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
  4986. Args);
  4987. else if (toolchains::BareMetal::handlesTarget(Target))
  4988. TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
  4989. else if (Target.isOSBinFormatELF())
  4990. TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
  4991. else if (Target.isOSBinFormatMachO())
  4992. TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
  4993. else
  4994. TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
  4995. }
  4996. }
  4997. }
  4998. // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
  4999. // compiles always need two toolchains, the CUDA toolchain and the host
  5000. // toolchain. So the only valid way to create a CUDA toolchain is via
  5001. // CreateOffloadingDeviceToolChains.
  5002. return *TC;
  5003. }
  5004. const ToolChain &Driver::getOffloadingDeviceToolChain(
  5005. const ArgList &Args, const llvm::Triple &Target, const ToolChain &HostTC,
  5006. const Action::OffloadKind &TargetDeviceOffloadKind) const {
  5007. // Use device / host triples as the key into the ToolChains map because the
  5008. // device ToolChain we create depends on both.
  5009. auto &TC = ToolChains[Target.str() + "/" + HostTC.getTriple().str()];
  5010. if (!TC) {
  5011. // Categorized by offload kind > arch rather than OS > arch like
  5012. // the normal getToolChain call, as it seems a reasonable way to categorize
  5013. // things.
  5014. switch (TargetDeviceOffloadKind) {
  5015. case Action::OFK_HIP: {
  5016. if (Target.getArch() == llvm::Triple::amdgcn &&
  5017. Target.getVendor() == llvm::Triple::AMD &&
  5018. Target.getOS() == llvm::Triple::AMDHSA)
  5019. TC = std::make_unique<toolchains::HIPAMDToolChain>(*this, Target,
  5020. HostTC, Args);
  5021. else if (Target.getArch() == llvm::Triple::spirv64 &&
  5022. Target.getVendor() == llvm::Triple::UnknownVendor &&
  5023. Target.getOS() == llvm::Triple::UnknownOS)
  5024. TC = std::make_unique<toolchains::HIPSPVToolChain>(*this, Target,
  5025. HostTC, Args);
  5026. break;
  5027. }
  5028. default:
  5029. break;
  5030. }
  5031. }
  5032. return *TC;
  5033. }
  5034. bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
  5035. // Say "no" if there is not exactly one input of a type clang understands.
  5036. if (JA.size() != 1 ||
  5037. !types::isAcceptedByClang((*JA.input_begin())->getType()))
  5038. return false;
  5039. // And say "no" if this is not a kind of action clang understands.
  5040. if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
  5041. !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  5042. return false;
  5043. return true;
  5044. }
  5045. bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
  5046. // Say "no" if there is not exactly one input of a type flang understands.
  5047. if (JA.size() != 1 ||
  5048. !types::isFortran((*JA.input_begin())->getType()))
  5049. return false;
  5050. // And say "no" if this is not a kind of action flang understands.
  5051. if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  5052. return false;
  5053. return true;
  5054. }
  5055. bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
  5056. // Only emit static library if the flag is set explicitly.
  5057. if (Args.hasArg(options::OPT_emit_static_lib))
  5058. return true;
  5059. return false;
  5060. }
  5061. /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
  5062. /// grouped values as integers. Numbers which are not provided are set to 0.
  5063. ///
  5064. /// \return True if the entire string was parsed (9.2), or all groups were
  5065. /// parsed (10.3.5extrastuff).
  5066. bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
  5067. unsigned &Micro, bool &HadExtra) {
  5068. HadExtra = false;
  5069. Major = Minor = Micro = 0;
  5070. if (Str.empty())
  5071. return false;
  5072. if (Str.consumeInteger(10, Major))
  5073. return false;
  5074. if (Str.empty())
  5075. return true;
  5076. if (Str[0] != '.')
  5077. return false;
  5078. Str = Str.drop_front(1);
  5079. if (Str.consumeInteger(10, Minor))
  5080. return false;
  5081. if (Str.empty())
  5082. return true;
  5083. if (Str[0] != '.')
  5084. return false;
  5085. Str = Str.drop_front(1);
  5086. if (Str.consumeInteger(10, Micro))
  5087. return false;
  5088. if (!Str.empty())
  5089. HadExtra = true;
  5090. return true;
  5091. }
  5092. /// Parse digits from a string \p Str and fulfill \p Digits with
  5093. /// the parsed numbers. This method assumes that the max number of
  5094. /// digits to look for is equal to Digits.size().
  5095. ///
  5096. /// \return True if the entire string was parsed and there are
  5097. /// no extra characters remaining at the end.
  5098. bool Driver::GetReleaseVersion(StringRef Str,
  5099. MutableArrayRef<unsigned> Digits) {
  5100. if (Str.empty())
  5101. return false;
  5102. unsigned CurDigit = 0;
  5103. while (CurDigit < Digits.size()) {
  5104. unsigned Digit;
  5105. if (Str.consumeInteger(10, Digit))
  5106. return false;
  5107. Digits[CurDigit] = Digit;
  5108. if (Str.empty())
  5109. return true;
  5110. if (Str[0] != '.')
  5111. return false;
  5112. Str = Str.drop_front(1);
  5113. CurDigit++;
  5114. }
  5115. // More digits than requested, bail out...
  5116. return false;
  5117. }
  5118. std::pair<unsigned, unsigned>
  5119. Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
  5120. unsigned IncludedFlagsBitmask = 0;
  5121. unsigned ExcludedFlagsBitmask = options::NoDriverOption;
  5122. if (IsClCompatMode) {
  5123. // Include CL and Core options.
  5124. IncludedFlagsBitmask |= options::CLOption;
  5125. IncludedFlagsBitmask |= options::CoreOption;
  5126. } else {
  5127. ExcludedFlagsBitmask |= options::CLOption;
  5128. }
  5129. return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
  5130. }
  5131. bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
  5132. return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
  5133. }
  5134. bool clang::driver::willEmitRemarks(const ArgList &Args) {
  5135. // -fsave-optimization-record enables it.
  5136. if (Args.hasFlag(options::OPT_fsave_optimization_record,
  5137. options::OPT_fno_save_optimization_record, false))
  5138. return true;
  5139. // -fsave-optimization-record=<format> enables it as well.
  5140. if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
  5141. options::OPT_fno_save_optimization_record, false))
  5142. return true;
  5143. // -foptimization-record-file alone enables it too.
  5144. if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
  5145. options::OPT_fno_save_optimization_record, false))
  5146. return true;
  5147. // -foptimization-record-passes alone enables it too.
  5148. if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
  5149. options::OPT_fno_save_optimization_record, false))
  5150. return true;
  5151. return false;
  5152. }
  5153. llvm::StringRef clang::driver::getDriverMode(StringRef ProgName,
  5154. ArrayRef<const char *> Args) {
  5155. static const std::string OptName =
  5156. getDriverOptTable().getOption(options::OPT_driver_mode).getPrefixedName();
  5157. llvm::StringRef Opt;
  5158. for (StringRef Arg : Args) {
  5159. if (!Arg.startswith(OptName))
  5160. continue;
  5161. Opt = Arg;
  5162. }
  5163. if (Opt.empty())
  5164. Opt = ToolChain::getTargetAndModeFromProgramName(ProgName).DriverMode;
  5165. return Opt.consume_front(OptName) ? Opt : "";
  5166. }
  5167. bool driver::IsClangCL(StringRef DriverMode) { return DriverMode.equals("cl"); }