Clang.cpp 327 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488
  1. //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
  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.h"
  9. #include "AMDGPU.h"
  10. #include "Arch/AArch64.h"
  11. #include "Arch/ARM.h"
  12. #include "Arch/CSKY.h"
  13. #include "Arch/LoongArch.h"
  14. #include "Arch/M68k.h"
  15. #include "Arch/Mips.h"
  16. #include "Arch/PPC.h"
  17. #include "Arch/RISCV.h"
  18. #include "Arch/Sparc.h"
  19. #include "Arch/SystemZ.h"
  20. #include "Arch/VE.h"
  21. #include "Arch/X86.h"
  22. #include "CommonArgs.h"
  23. #include "Hexagon.h"
  24. #include "MSP430.h"
  25. #include "PS4CPU.h"
  26. #include "clang/Basic/CLWarnings.h"
  27. #include "clang/Basic/CharInfo.h"
  28. #include "clang/Basic/CodeGenOptions.h"
  29. #include "clang/Basic/HeaderInclude.h"
  30. #include "clang/Basic/LangOptions.h"
  31. #include "clang/Basic/MakeSupport.h"
  32. #include "clang/Basic/ObjCRuntime.h"
  33. #include "clang/Basic/Version.h"
  34. #include "clang/Config/config.h"
  35. #include "clang/Driver/Action.h"
  36. #include "clang/Driver/Distro.h"
  37. #include "clang/Driver/DriverDiagnostic.h"
  38. #include "clang/Driver/InputInfo.h"
  39. #include "clang/Driver/Options.h"
  40. #include "clang/Driver/SanitizerArgs.h"
  41. #include "clang/Driver/Types.h"
  42. #include "clang/Driver/XRayArgs.h"
  43. #include "llvm/ADT/SmallSet.h"
  44. #include "llvm/ADT/StringExtras.h"
  45. #include "llvm/Config/llvm-config.h"
  46. #include "llvm/Option/ArgList.h"
  47. #include "llvm/Support/ARMTargetParserCommon.h"
  48. #include "llvm/Support/CodeGen.h"
  49. #include "llvm/Support/Compiler.h"
  50. #include "llvm/Support/Compression.h"
  51. #include "llvm/Support/FileSystem.h"
  52. #include "llvm/Support/Host.h"
  53. #include "llvm/Support/Path.h"
  54. #include "llvm/Support/Process.h"
  55. #include "llvm/Support/YAMLParser.h"
  56. #include <cctype>
  57. using namespace clang::driver;
  58. using namespace clang::driver::tools;
  59. using namespace clang;
  60. using namespace llvm::opt;
  61. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  62. if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
  63. options::OPT_fminimize_whitespace,
  64. options::OPT_fno_minimize_whitespace)) {
  65. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  66. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  67. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  68. << A->getBaseArg().getAsString(Args)
  69. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  70. }
  71. }
  72. }
  73. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  74. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  75. if (Args.hasArg(options::OPT_static))
  76. if (const Arg *A =
  77. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  78. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  79. << "-static";
  80. }
  81. // Add backslashes to escape spaces and other backslashes.
  82. // This is used for the space-separated argument list specified with
  83. // the -dwarf-debug-flags option.
  84. static void EscapeSpacesAndBackslashes(const char *Arg,
  85. SmallVectorImpl<char> &Res) {
  86. for (; *Arg; ++Arg) {
  87. switch (*Arg) {
  88. default:
  89. break;
  90. case ' ':
  91. case '\\':
  92. Res.push_back('\\');
  93. break;
  94. }
  95. Res.push_back(*Arg);
  96. }
  97. }
  98. /// Apply \a Work on the current tool chain \a RegularToolChain and any other
  99. /// offloading tool chain that is associated with the current action \a JA.
  100. static void
  101. forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
  102. const ToolChain &RegularToolChain,
  103. llvm::function_ref<void(const ToolChain &)> Work) {
  104. // Apply Work on the current/regular tool chain.
  105. Work(RegularToolChain);
  106. // Apply Work on all the offloading tool chains associated with the current
  107. // action.
  108. if (JA.isHostOffloading(Action::OFK_Cuda))
  109. Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
  110. else if (JA.isDeviceOffloading(Action::OFK_Cuda))
  111. Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
  112. else if (JA.isHostOffloading(Action::OFK_HIP))
  113. Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
  114. else if (JA.isDeviceOffloading(Action::OFK_HIP))
  115. Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
  116. if (JA.isHostOffloading(Action::OFK_OpenMP)) {
  117. auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
  118. for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
  119. Work(*II->second);
  120. } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
  121. Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
  122. //
  123. // TODO: Add support for other offloading programming models here.
  124. //
  125. }
  126. /// This is a helper function for validating the optional refinement step
  127. /// parameter in reciprocal argument strings. Return false if there is an error
  128. /// parsing the refinement step. Otherwise, return true and set the Position
  129. /// of the refinement step in the input string.
  130. static bool getRefinementStep(StringRef In, const Driver &D,
  131. const Arg &A, size_t &Position) {
  132. const char RefinementStepToken = ':';
  133. Position = In.find(RefinementStepToken);
  134. if (Position != StringRef::npos) {
  135. StringRef Option = A.getOption().getName();
  136. StringRef RefStep = In.substr(Position + 1);
  137. // Allow exactly one numeric character for the additional refinement
  138. // step parameter. This is reasonable for all currently-supported
  139. // operations and architectures because we would expect that a larger value
  140. // of refinement steps would cause the estimate "optimization" to
  141. // under-perform the native operation. Also, if the estimate does not
  142. // converge quickly, it probably will not ever converge, so further
  143. // refinement steps will not produce a better answer.
  144. if (RefStep.size() != 1) {
  145. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  146. return false;
  147. }
  148. char RefStepChar = RefStep[0];
  149. if (RefStepChar < '0' || RefStepChar > '9') {
  150. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  151. return false;
  152. }
  153. }
  154. return true;
  155. }
  156. /// The -mrecip flag requires processing of many optional parameters.
  157. static void ParseMRecip(const Driver &D, const ArgList &Args,
  158. ArgStringList &OutStrings) {
  159. StringRef DisabledPrefixIn = "!";
  160. StringRef DisabledPrefixOut = "!";
  161. StringRef EnabledPrefixOut = "";
  162. StringRef Out = "-mrecip=";
  163. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  164. if (!A)
  165. return;
  166. unsigned NumOptions = A->getNumValues();
  167. if (NumOptions == 0) {
  168. // No option is the same as "all".
  169. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  170. return;
  171. }
  172. // Pass through "all", "none", or "default" with an optional refinement step.
  173. if (NumOptions == 1) {
  174. StringRef Val = A->getValue(0);
  175. size_t RefStepLoc;
  176. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  177. return;
  178. StringRef ValBase = Val.slice(0, RefStepLoc);
  179. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  180. OutStrings.push_back(Args.MakeArgString(Out + Val));
  181. return;
  182. }
  183. }
  184. // Each reciprocal type may be enabled or disabled individually.
  185. // Check each input value for validity, concatenate them all back together,
  186. // and pass through.
  187. llvm::StringMap<bool> OptionStrings;
  188. OptionStrings.insert(std::make_pair("divd", false));
  189. OptionStrings.insert(std::make_pair("divf", false));
  190. OptionStrings.insert(std::make_pair("divh", false));
  191. OptionStrings.insert(std::make_pair("vec-divd", false));
  192. OptionStrings.insert(std::make_pair("vec-divf", false));
  193. OptionStrings.insert(std::make_pair("vec-divh", false));
  194. OptionStrings.insert(std::make_pair("sqrtd", false));
  195. OptionStrings.insert(std::make_pair("sqrtf", false));
  196. OptionStrings.insert(std::make_pair("sqrth", false));
  197. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  198. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  199. OptionStrings.insert(std::make_pair("vec-sqrth", false));
  200. for (unsigned i = 0; i != NumOptions; ++i) {
  201. StringRef Val = A->getValue(i);
  202. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  203. // Ignore the disablement token for string matching.
  204. if (IsDisabled)
  205. Val = Val.substr(1);
  206. size_t RefStep;
  207. if (!getRefinementStep(Val, D, *A, RefStep))
  208. return;
  209. StringRef ValBase = Val.slice(0, RefStep);
  210. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  211. if (OptionIter == OptionStrings.end()) {
  212. // Try again specifying float suffix.
  213. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  214. if (OptionIter == OptionStrings.end()) {
  215. // The input name did not match any known option string.
  216. D.Diag(diag::err_drv_unknown_argument) << Val;
  217. return;
  218. }
  219. // The option was specified without a half or float or double suffix.
  220. // Make sure that the double or half entry was not already specified.
  221. // The float entry will be checked below.
  222. if (OptionStrings[ValBase.str() + 'd'] ||
  223. OptionStrings[ValBase.str() + 'h']) {
  224. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  225. return;
  226. }
  227. }
  228. if (OptionIter->second == true) {
  229. // Duplicate option specified.
  230. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  231. return;
  232. }
  233. // Mark the matched option as found. Do not allow duplicate specifiers.
  234. OptionIter->second = true;
  235. // If the precision was not specified, also mark the double and half entry
  236. // as found.
  237. if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
  238. OptionStrings[ValBase.str() + 'd'] = true;
  239. OptionStrings[ValBase.str() + 'h'] = true;
  240. }
  241. // Build the output string.
  242. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  243. Out = Args.MakeArgString(Out + Prefix + Val);
  244. if (i != NumOptions - 1)
  245. Out = Args.MakeArgString(Out + ",");
  246. }
  247. OutStrings.push_back(Args.MakeArgString(Out));
  248. }
  249. /// The -mprefer-vector-width option accepts either a positive integer
  250. /// or the string "none".
  251. static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
  252. ArgStringList &CmdArgs) {
  253. Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
  254. if (!A)
  255. return;
  256. StringRef Value = A->getValue();
  257. if (Value == "none") {
  258. CmdArgs.push_back("-mprefer-vector-width=none");
  259. } else {
  260. unsigned Width;
  261. if (Value.getAsInteger(10, Width)) {
  262. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
  263. return;
  264. }
  265. CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
  266. }
  267. }
  268. static bool
  269. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  270. const llvm::Triple &Triple) {
  271. // We use the zero-cost exception tables for Objective-C if the non-fragile
  272. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  273. // later.
  274. if (runtime.isNonFragile())
  275. return true;
  276. if (!Triple.isMacOSX())
  277. return false;
  278. return (!Triple.isMacOSXVersionLT(10, 5) &&
  279. (Triple.getArch() == llvm::Triple::x86_64 ||
  280. Triple.getArch() == llvm::Triple::arm));
  281. }
  282. /// Adds exception related arguments to the driver command arguments. There's a
  283. /// main flag, -fexceptions and also language specific flags to enable/disable
  284. /// C++ and Objective-C exceptions. This makes it possible to for example
  285. /// disable C++ exceptions but enable Objective-C exceptions.
  286. static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
  287. const ToolChain &TC, bool KernelOrKext,
  288. const ObjCRuntime &objcRuntime,
  289. ArgStringList &CmdArgs) {
  290. const llvm::Triple &Triple = TC.getTriple();
  291. if (KernelOrKext) {
  292. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  293. // arguments now to avoid warnings about unused arguments.
  294. Args.ClaimAllArgs(options::OPT_fexceptions);
  295. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  296. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  297. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  298. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  299. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  300. Args.ClaimAllArgs(options::OPT_fasync_exceptions);
  301. Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
  302. return false;
  303. }
  304. // See if the user explicitly enabled exceptions.
  305. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  306. false);
  307. bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
  308. options::OPT_fno_async_exceptions, false);
  309. if (EHa) {
  310. CmdArgs.push_back("-fasync-exceptions");
  311. EH = true;
  312. }
  313. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  314. // is not necessarily sensible, but follows GCC.
  315. if (types::isObjC(InputType) &&
  316. Args.hasFlag(options::OPT_fobjc_exceptions,
  317. options::OPT_fno_objc_exceptions, true)) {
  318. CmdArgs.push_back("-fobjc-exceptions");
  319. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  320. }
  321. if (types::isCXX(InputType)) {
  322. // Disable C++ EH by default on XCore and PS4/PS5.
  323. bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
  324. !Triple.isPS() && !Triple.isDriverKit();
  325. Arg *ExceptionArg = Args.getLastArg(
  326. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  327. options::OPT_fexceptions, options::OPT_fno_exceptions);
  328. if (ExceptionArg)
  329. CXXExceptionsEnabled =
  330. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  331. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  332. if (CXXExceptionsEnabled) {
  333. CmdArgs.push_back("-fcxx-exceptions");
  334. EH = true;
  335. }
  336. }
  337. // OPT_fignore_exceptions means exception could still be thrown,
  338. // but no clean up or catch would happen in current module.
  339. // So we do not set EH to false.
  340. Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
  341. if (EH)
  342. CmdArgs.push_back("-fexceptions");
  343. return EH;
  344. }
  345. static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
  346. const JobAction &JA) {
  347. bool Default = true;
  348. if (TC.getTriple().isOSDarwin()) {
  349. // The native darwin assembler doesn't support the linker_option directives,
  350. // so we disable them if we think the .s file will be passed to it.
  351. Default = TC.useIntegratedAs();
  352. }
  353. // The linker_option directives are intended for host compilation.
  354. if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
  355. JA.isDeviceOffloading(Action::OFK_HIP))
  356. Default = false;
  357. return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  358. Default);
  359. }
  360. // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
  361. // to the corresponding DebugInfoKind.
  362. static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
  363. assert(A.getOption().matches(options::OPT_gN_Group) &&
  364. "Not a -g option that specifies a debug-info level");
  365. if (A.getOption().matches(options::OPT_g0) ||
  366. A.getOption().matches(options::OPT_ggdb0))
  367. return codegenoptions::NoDebugInfo;
  368. if (A.getOption().matches(options::OPT_gline_tables_only) ||
  369. A.getOption().matches(options::OPT_ggdb1))
  370. return codegenoptions::DebugLineTablesOnly;
  371. if (A.getOption().matches(options::OPT_gline_directives_only))
  372. return codegenoptions::DebugDirectivesOnly;
  373. return codegenoptions::DebugInfoConstructor;
  374. }
  375. static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
  376. switch (Triple.getArch()){
  377. default:
  378. return false;
  379. case llvm::Triple::arm:
  380. case llvm::Triple::thumb:
  381. // ARM Darwin targets require a frame pointer to be always present to aid
  382. // offline debugging via backtraces.
  383. return Triple.isOSDarwin();
  384. }
  385. }
  386. static bool useFramePointerForTargetByDefault(const ArgList &Args,
  387. const llvm::Triple &Triple) {
  388. if (Args.hasArg(options::OPT_pg) && !Args.hasArg(options::OPT_mfentry))
  389. return true;
  390. switch (Triple.getArch()) {
  391. case llvm::Triple::xcore:
  392. case llvm::Triple::wasm32:
  393. case llvm::Triple::wasm64:
  394. case llvm::Triple::msp430:
  395. // XCore never wants frame pointers, regardless of OS.
  396. // WebAssembly never wants frame pointers.
  397. return false;
  398. case llvm::Triple::ppc:
  399. case llvm::Triple::ppcle:
  400. case llvm::Triple::ppc64:
  401. case llvm::Triple::ppc64le:
  402. case llvm::Triple::riscv32:
  403. case llvm::Triple::riscv64:
  404. case llvm::Triple::sparc:
  405. case llvm::Triple::sparcel:
  406. case llvm::Triple::sparcv9:
  407. case llvm::Triple::amdgcn:
  408. case llvm::Triple::r600:
  409. case llvm::Triple::csky:
  410. case llvm::Triple::loongarch32:
  411. case llvm::Triple::loongarch64:
  412. return !areOptimizationsEnabled(Args);
  413. default:
  414. break;
  415. }
  416. if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
  417. return !areOptimizationsEnabled(Args);
  418. }
  419. if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
  420. Triple.isOSHurd()) {
  421. switch (Triple.getArch()) {
  422. // Don't use a frame pointer on linux if optimizing for certain targets.
  423. case llvm::Triple::arm:
  424. case llvm::Triple::armeb:
  425. case llvm::Triple::thumb:
  426. case llvm::Triple::thumbeb:
  427. if (Triple.isAndroid())
  428. return true;
  429. [[fallthrough]];
  430. case llvm::Triple::mips64:
  431. case llvm::Triple::mips64el:
  432. case llvm::Triple::mips:
  433. case llvm::Triple::mipsel:
  434. case llvm::Triple::systemz:
  435. case llvm::Triple::x86:
  436. case llvm::Triple::x86_64:
  437. return !areOptimizationsEnabled(Args);
  438. default:
  439. return true;
  440. }
  441. }
  442. if (Triple.isOSWindows()) {
  443. switch (Triple.getArch()) {
  444. case llvm::Triple::x86:
  445. return !areOptimizationsEnabled(Args);
  446. case llvm::Triple::x86_64:
  447. return Triple.isOSBinFormatMachO();
  448. case llvm::Triple::arm:
  449. case llvm::Triple::thumb:
  450. // Windows on ARM builds with FPO disabled to aid fast stack walking
  451. return true;
  452. default:
  453. // All other supported Windows ISAs use xdata unwind information, so frame
  454. // pointers are not generally useful.
  455. return false;
  456. }
  457. }
  458. return true;
  459. }
  460. static CodeGenOptions::FramePointerKind
  461. getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
  462. // We have 4 states:
  463. //
  464. // 00) leaf retained, non-leaf retained
  465. // 01) leaf retained, non-leaf omitted (this is invalid)
  466. // 10) leaf omitted, non-leaf retained
  467. // (what -momit-leaf-frame-pointer was designed for)
  468. // 11) leaf omitted, non-leaf omitted
  469. //
  470. // "omit" options taking precedence over "no-omit" options is the only way
  471. // to make 3 valid states representable
  472. Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  473. options::OPT_fno_omit_frame_pointer);
  474. bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
  475. bool NoOmitFP =
  476. A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  477. bool OmitLeafFP =
  478. Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
  479. options::OPT_mno_omit_leaf_frame_pointer,
  480. Triple.isAArch64() || Triple.isPS() || Triple.isVE());
  481. if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
  482. (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
  483. if (OmitLeafFP)
  484. return CodeGenOptions::FramePointerKind::NonLeaf;
  485. return CodeGenOptions::FramePointerKind::All;
  486. }
  487. return CodeGenOptions::FramePointerKind::None;
  488. }
  489. /// Add a CC1 option to specify the debug compilation directory.
  490. static const char *addDebugCompDirArg(const ArgList &Args,
  491. ArgStringList &CmdArgs,
  492. const llvm::vfs::FileSystem &VFS) {
  493. if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
  494. options::OPT_fdebug_compilation_dir_EQ)) {
  495. if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
  496. CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
  497. A->getValue()));
  498. else
  499. A->render(Args, CmdArgs);
  500. } else if (llvm::ErrorOr<std::string> CWD =
  501. VFS.getCurrentWorkingDirectory()) {
  502. CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
  503. }
  504. StringRef Path(CmdArgs.back());
  505. return Path.substr(Path.find('=') + 1).data();
  506. }
  507. static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
  508. const char *DebugCompilationDir,
  509. const char *OutputFileName) {
  510. // No need to generate a value for -object-file-name if it was provided.
  511. for (auto *Arg : Args.filtered(options::OPT_Xclang))
  512. if (StringRef(Arg->getValue()).startswith("-object-file-name"))
  513. return;
  514. if (Args.hasArg(options::OPT_object_file_name_EQ))
  515. return;
  516. SmallString<128> ObjFileNameForDebug(OutputFileName);
  517. if (ObjFileNameForDebug != "-" &&
  518. !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
  519. (!DebugCompilationDir ||
  520. llvm::sys::path::is_absolute(DebugCompilationDir))) {
  521. // Make the path absolute in the debug infos like MSVC does.
  522. llvm::sys::fs::make_absolute(ObjFileNameForDebug);
  523. }
  524. CmdArgs.push_back(
  525. Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
  526. }
  527. /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
  528. static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
  529. const ArgList &Args, ArgStringList &CmdArgs) {
  530. auto AddOneArg = [&](StringRef Map, StringRef Name) {
  531. if (!Map.contains('='))
  532. D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
  533. else
  534. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  535. };
  536. for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
  537. options::OPT_fdebug_prefix_map_EQ)) {
  538. AddOneArg(A->getValue(), A->getOption().getName());
  539. A->claim();
  540. }
  541. std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
  542. if (GlobalRemapEntry.empty())
  543. return;
  544. AddOneArg(GlobalRemapEntry, "environment");
  545. }
  546. /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
  547. static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
  548. ArgStringList &CmdArgs) {
  549. for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
  550. options::OPT_fmacro_prefix_map_EQ)) {
  551. StringRef Map = A->getValue();
  552. if (!Map.contains('='))
  553. D.Diag(diag::err_drv_invalid_argument_to_option)
  554. << Map << A->getOption().getName();
  555. else
  556. CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
  557. A->claim();
  558. }
  559. }
  560. /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
  561. static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
  562. ArgStringList &CmdArgs) {
  563. for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
  564. options::OPT_fcoverage_prefix_map_EQ)) {
  565. StringRef Map = A->getValue();
  566. if (!Map.contains('='))
  567. D.Diag(diag::err_drv_invalid_argument_to_option)
  568. << Map << A->getOption().getName();
  569. else
  570. CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
  571. A->claim();
  572. }
  573. }
  574. /// Vectorize at all optimization levels greater than 1 except for -Oz.
  575. /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
  576. /// enabled.
  577. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  578. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  579. if (A->getOption().matches(options::OPT_O4) ||
  580. A->getOption().matches(options::OPT_Ofast))
  581. return true;
  582. if (A->getOption().matches(options::OPT_O0))
  583. return false;
  584. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  585. // Vectorize -Os.
  586. StringRef S(A->getValue());
  587. if (S == "s")
  588. return true;
  589. // Don't vectorize -Oz, unless it's the slp vectorizer.
  590. if (S == "z")
  591. return isSlpVec;
  592. unsigned OptLevel = 0;
  593. if (S.getAsInteger(10, OptLevel))
  594. return false;
  595. return OptLevel > 1;
  596. }
  597. return false;
  598. }
  599. /// Add -x lang to \p CmdArgs for \p Input.
  600. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  601. ArgStringList &CmdArgs) {
  602. // When using -verify-pch, we don't want to provide the type
  603. // 'precompiled-header' if it was inferred from the file extension
  604. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  605. return;
  606. CmdArgs.push_back("-x");
  607. if (Args.hasArg(options::OPT_rewrite_objc))
  608. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  609. else {
  610. // Map the driver type to the frontend type. This is mostly an identity
  611. // mapping, except that the distinction between module interface units
  612. // and other source files does not exist at the frontend layer.
  613. const char *ClangType;
  614. switch (Input.getType()) {
  615. case types::TY_CXXModule:
  616. ClangType = "c++";
  617. break;
  618. case types::TY_PP_CXXModule:
  619. ClangType = "c++-cpp-output";
  620. break;
  621. default:
  622. ClangType = types::getTypeName(Input.getType());
  623. break;
  624. }
  625. CmdArgs.push_back(ClangType);
  626. }
  627. }
  628. static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
  629. const Driver &D, const InputInfo &Output,
  630. const ArgList &Args, SanitizerArgs &SanArgs,
  631. ArgStringList &CmdArgs) {
  632. auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
  633. options::OPT_fprofile_generate_EQ,
  634. options::OPT_fno_profile_generate);
  635. if (PGOGenerateArg &&
  636. PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
  637. PGOGenerateArg = nullptr;
  638. auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
  639. options::OPT_fcs_profile_generate_EQ,
  640. options::OPT_fno_profile_generate);
  641. if (CSPGOGenerateArg &&
  642. CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
  643. CSPGOGenerateArg = nullptr;
  644. auto *ProfileGenerateArg = Args.getLastArg(
  645. options::OPT_fprofile_instr_generate,
  646. options::OPT_fprofile_instr_generate_EQ,
  647. options::OPT_fno_profile_instr_generate);
  648. if (ProfileGenerateArg &&
  649. ProfileGenerateArg->getOption().matches(
  650. options::OPT_fno_profile_instr_generate))
  651. ProfileGenerateArg = nullptr;
  652. if (PGOGenerateArg && ProfileGenerateArg)
  653. D.Diag(diag::err_drv_argument_not_allowed_with)
  654. << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
  655. auto *ProfileUseArg = getLastProfileUseArg(Args);
  656. if (PGOGenerateArg && ProfileUseArg)
  657. D.Diag(diag::err_drv_argument_not_allowed_with)
  658. << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
  659. if (ProfileGenerateArg && ProfileUseArg)
  660. D.Diag(diag::err_drv_argument_not_allowed_with)
  661. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  662. if (CSPGOGenerateArg && PGOGenerateArg) {
  663. D.Diag(diag::err_drv_argument_not_allowed_with)
  664. << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
  665. PGOGenerateArg = nullptr;
  666. }
  667. if (TC.getTriple().isOSAIX()) {
  668. if (ProfileGenerateArg)
  669. D.Diag(diag::err_drv_unsupported_opt_for_target)
  670. << ProfileGenerateArg->getSpelling() << TC.getTriple().str();
  671. if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
  672. D.Diag(diag::err_drv_unsupported_opt_for_target)
  673. << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
  674. }
  675. if (ProfileGenerateArg) {
  676. if (ProfileGenerateArg->getOption().matches(
  677. options::OPT_fprofile_instr_generate_EQ))
  678. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
  679. ProfileGenerateArg->getValue()));
  680. // The default is to use Clang Instrumentation.
  681. CmdArgs.push_back("-fprofile-instrument=clang");
  682. if (TC.getTriple().isWindowsMSVCEnvironment()) {
  683. // Add dependent lib for clang_rt.profile
  684. CmdArgs.push_back(Args.MakeArgString(
  685. "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
  686. }
  687. }
  688. Arg *PGOGenArg = nullptr;
  689. if (PGOGenerateArg) {
  690. assert(!CSPGOGenerateArg);
  691. PGOGenArg = PGOGenerateArg;
  692. CmdArgs.push_back("-fprofile-instrument=llvm");
  693. }
  694. if (CSPGOGenerateArg) {
  695. assert(!PGOGenerateArg);
  696. PGOGenArg = CSPGOGenerateArg;
  697. CmdArgs.push_back("-fprofile-instrument=csllvm");
  698. }
  699. if (PGOGenArg) {
  700. if (TC.getTriple().isWindowsMSVCEnvironment()) {
  701. // Add dependent lib for clang_rt.profile
  702. CmdArgs.push_back(Args.MakeArgString(
  703. "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
  704. }
  705. if (PGOGenArg->getOption().matches(
  706. PGOGenerateArg ? options::OPT_fprofile_generate_EQ
  707. : options::OPT_fcs_profile_generate_EQ)) {
  708. SmallString<128> Path(PGOGenArg->getValue());
  709. llvm::sys::path::append(Path, "default_%m.profraw");
  710. CmdArgs.push_back(
  711. Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
  712. }
  713. }
  714. if (ProfileUseArg) {
  715. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  716. CmdArgs.push_back(Args.MakeArgString(
  717. Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
  718. else if ((ProfileUseArg->getOption().matches(
  719. options::OPT_fprofile_use_EQ) ||
  720. ProfileUseArg->getOption().matches(
  721. options::OPT_fprofile_instr_use))) {
  722. SmallString<128> Path(
  723. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  724. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  725. llvm::sys::path::append(Path, "default.profdata");
  726. CmdArgs.push_back(
  727. Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
  728. }
  729. }
  730. bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
  731. options::OPT_fno_test_coverage, false) ||
  732. Args.hasArg(options::OPT_coverage);
  733. bool EmitCovData = TC.needsGCovInstrumentation(Args);
  734. if (EmitCovNotes)
  735. CmdArgs.push_back("-ftest-coverage");
  736. if (EmitCovData)
  737. CmdArgs.push_back("-fprofile-arcs");
  738. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  739. options::OPT_fno_coverage_mapping, false)) {
  740. if (!ProfileGenerateArg)
  741. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  742. << "-fcoverage-mapping"
  743. << "-fprofile-instr-generate";
  744. CmdArgs.push_back("-fcoverage-mapping");
  745. }
  746. if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
  747. options::OPT_fcoverage_compilation_dir_EQ)) {
  748. if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
  749. CmdArgs.push_back(Args.MakeArgString(
  750. Twine("-fcoverage-compilation-dir=") + A->getValue()));
  751. else
  752. A->render(Args, CmdArgs);
  753. } else if (llvm::ErrorOr<std::string> CWD =
  754. D.getVFS().getCurrentWorkingDirectory()) {
  755. CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
  756. }
  757. if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
  758. auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
  759. if (!Args.hasArg(options::OPT_coverage))
  760. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  761. << "-fprofile-exclude-files="
  762. << "--coverage";
  763. StringRef v = Arg->getValue();
  764. CmdArgs.push_back(
  765. Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
  766. }
  767. if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
  768. auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
  769. if (!Args.hasArg(options::OPT_coverage))
  770. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  771. << "-fprofile-filter-files="
  772. << "--coverage";
  773. StringRef v = Arg->getValue();
  774. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
  775. }
  776. if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
  777. StringRef Val = A->getValue();
  778. if (Val == "atomic" || Val == "prefer-atomic")
  779. CmdArgs.push_back("-fprofile-update=atomic");
  780. else if (Val != "single")
  781. D.Diag(diag::err_drv_unsupported_option_argument)
  782. << A->getSpelling() << Val;
  783. } else if (SanArgs.needsTsanRt()) {
  784. CmdArgs.push_back("-fprofile-update=atomic");
  785. }
  786. int FunctionGroups = 1;
  787. int SelectedFunctionGroup = 0;
  788. if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
  789. StringRef Val = A->getValue();
  790. if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
  791. D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
  792. }
  793. if (const auto *A =
  794. Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
  795. StringRef Val = A->getValue();
  796. if (Val.getAsInteger(0, SelectedFunctionGroup) ||
  797. SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
  798. D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
  799. }
  800. if (FunctionGroups != 1)
  801. CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
  802. Twine(FunctionGroups)));
  803. if (SelectedFunctionGroup != 0)
  804. CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
  805. Twine(SelectedFunctionGroup)));
  806. // Leave -fprofile-dir= an unused argument unless .gcda emission is
  807. // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
  808. // the flag used. There is no -fno-profile-dir, so the user has no
  809. // targeted way to suppress the warning.
  810. Arg *FProfileDir = nullptr;
  811. if (Args.hasArg(options::OPT_fprofile_arcs) ||
  812. Args.hasArg(options::OPT_coverage))
  813. FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
  814. // Put the .gcno and .gcda files (if needed) next to the object file or
  815. // bitcode file in the case of LTO.
  816. // FIXME: There should be a simpler way to find the object file for this
  817. // input, and this code probably does the wrong thing for commands that
  818. // compile and link all at once.
  819. if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
  820. (EmitCovNotes || EmitCovData) && Output.isFilename()) {
  821. SmallString<128> OutputFilename;
  822. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT__SLASH_Fo))
  823. OutputFilename = FinalOutput->getValue();
  824. else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  825. OutputFilename = FinalOutput->getValue();
  826. else
  827. OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
  828. SmallString<128> CoverageFilename = OutputFilename;
  829. if (llvm::sys::path::is_relative(CoverageFilename))
  830. (void)D.getVFS().makeAbsolute(CoverageFilename);
  831. llvm::sys::path::replace_extension(CoverageFilename, "gcno");
  832. CmdArgs.push_back("-coverage-notes-file");
  833. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  834. if (EmitCovData) {
  835. if (FProfileDir) {
  836. CoverageFilename = FProfileDir->getValue();
  837. llvm::sys::path::append(CoverageFilename, OutputFilename);
  838. }
  839. llvm::sys::path::replace_extension(CoverageFilename, "gcda");
  840. CmdArgs.push_back("-coverage-data-file");
  841. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  842. }
  843. }
  844. }
  845. /// Check whether the given input tree contains any compilation actions.
  846. static bool ContainsCompileAction(const Action *A) {
  847. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  848. return true;
  849. return llvm::any_of(A->inputs(), ContainsCompileAction);
  850. }
  851. /// Check if -relax-all should be passed to the internal assembler.
  852. /// This is done by default when compiling non-assembler source with -O0.
  853. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  854. bool RelaxDefault = true;
  855. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  856. RelaxDefault = A->getOption().matches(options::OPT_O0);
  857. if (RelaxDefault) {
  858. RelaxDefault = false;
  859. for (const auto &Act : C.getActions()) {
  860. if (ContainsCompileAction(Act)) {
  861. RelaxDefault = true;
  862. break;
  863. }
  864. }
  865. }
  866. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  867. RelaxDefault);
  868. }
  869. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  870. codegenoptions::DebugInfoKind DebugInfoKind,
  871. unsigned DwarfVersion,
  872. llvm::DebuggerKind DebuggerTuning) {
  873. switch (DebugInfoKind) {
  874. case codegenoptions::DebugDirectivesOnly:
  875. CmdArgs.push_back("-debug-info-kind=line-directives-only");
  876. break;
  877. case codegenoptions::DebugLineTablesOnly:
  878. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  879. break;
  880. case codegenoptions::DebugInfoConstructor:
  881. CmdArgs.push_back("-debug-info-kind=constructor");
  882. break;
  883. case codegenoptions::LimitedDebugInfo:
  884. CmdArgs.push_back("-debug-info-kind=limited");
  885. break;
  886. case codegenoptions::FullDebugInfo:
  887. CmdArgs.push_back("-debug-info-kind=standalone");
  888. break;
  889. case codegenoptions::UnusedTypeInfo:
  890. CmdArgs.push_back("-debug-info-kind=unused-types");
  891. break;
  892. default:
  893. break;
  894. }
  895. if (DwarfVersion > 0)
  896. CmdArgs.push_back(
  897. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  898. switch (DebuggerTuning) {
  899. case llvm::DebuggerKind::GDB:
  900. CmdArgs.push_back("-debugger-tuning=gdb");
  901. break;
  902. case llvm::DebuggerKind::LLDB:
  903. CmdArgs.push_back("-debugger-tuning=lldb");
  904. break;
  905. case llvm::DebuggerKind::SCE:
  906. CmdArgs.push_back("-debugger-tuning=sce");
  907. break;
  908. case llvm::DebuggerKind::DBX:
  909. CmdArgs.push_back("-debugger-tuning=dbx");
  910. break;
  911. default:
  912. break;
  913. }
  914. }
  915. static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
  916. const Driver &D, const ToolChain &TC) {
  917. assert(A && "Expected non-nullptr argument.");
  918. if (TC.supportsDebugInfoOption(A))
  919. return true;
  920. D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
  921. << A->getAsString(Args) << TC.getTripleString();
  922. return false;
  923. }
  924. static void RenderDebugInfoCompressionArgs(const ArgList &Args,
  925. ArgStringList &CmdArgs,
  926. const Driver &D,
  927. const ToolChain &TC) {
  928. const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
  929. if (!A)
  930. return;
  931. if (checkDebugInfoOption(A, Args, D, TC)) {
  932. StringRef Value = A->getValue();
  933. if (Value == "none") {
  934. CmdArgs.push_back("--compress-debug-sections=none");
  935. } else if (Value == "zlib") {
  936. if (llvm::compression::zlib::isAvailable()) {
  937. CmdArgs.push_back(
  938. Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
  939. } else {
  940. D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
  941. }
  942. } else if (Value == "zstd") {
  943. if (llvm::compression::zstd::isAvailable()) {
  944. CmdArgs.push_back(
  945. Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
  946. } else {
  947. D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
  948. }
  949. } else {
  950. D.Diag(diag::err_drv_unsupported_option_argument)
  951. << A->getSpelling() << Value;
  952. }
  953. }
  954. }
  955. static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
  956. const ArgList &Args,
  957. ArgStringList &CmdArgs,
  958. bool IsCC1As = false) {
  959. // If no version was requested by the user, use the default value from the
  960. // back end. This is consistent with the value returned from
  961. // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
  962. // requiring the corresponding llvm to have the AMDGPU target enabled,
  963. // provided the user (e.g. front end tests) can use the default.
  964. if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
  965. unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
  966. CmdArgs.insert(CmdArgs.begin() + 1,
  967. Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
  968. Twine(CodeObjVer)));
  969. CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
  970. // -cc1as does not accept -mcode-object-version option.
  971. if (!IsCC1As)
  972. CmdArgs.insert(CmdArgs.begin() + 1,
  973. Args.MakeArgString(Twine("-mcode-object-version=") +
  974. Twine(CodeObjVer)));
  975. }
  976. }
  977. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  978. const Driver &D, const ArgList &Args,
  979. ArgStringList &CmdArgs,
  980. const InputInfo &Output,
  981. const InputInfoList &Inputs) const {
  982. const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
  983. CheckPreprocessingOptions(D, Args);
  984. Args.AddLastArg(CmdArgs, options::OPT_C);
  985. Args.AddLastArg(CmdArgs, options::OPT_CC);
  986. // Handle dependency file generation.
  987. Arg *ArgM = Args.getLastArg(options::OPT_MM);
  988. if (!ArgM)
  989. ArgM = Args.getLastArg(options::OPT_M);
  990. Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
  991. if (!ArgMD)
  992. ArgMD = Args.getLastArg(options::OPT_MD);
  993. // -M and -MM imply -w.
  994. if (ArgM)
  995. CmdArgs.push_back("-w");
  996. else
  997. ArgM = ArgMD;
  998. if (ArgM) {
  999. // Determine the output location.
  1000. const char *DepFile;
  1001. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  1002. DepFile = MF->getValue();
  1003. C.addFailureResultFile(DepFile, &JA);
  1004. } else if (Output.getType() == types::TY_Dependencies) {
  1005. DepFile = Output.getFilename();
  1006. } else if (!ArgMD) {
  1007. DepFile = "-";
  1008. } else {
  1009. DepFile = getDependencyFileName(Args, Inputs);
  1010. C.addFailureResultFile(DepFile, &JA);
  1011. }
  1012. CmdArgs.push_back("-dependency-file");
  1013. CmdArgs.push_back(DepFile);
  1014. bool HasTarget = false;
  1015. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  1016. HasTarget = true;
  1017. A->claim();
  1018. if (A->getOption().matches(options::OPT_MT)) {
  1019. A->render(Args, CmdArgs);
  1020. } else {
  1021. CmdArgs.push_back("-MT");
  1022. SmallString<128> Quoted;
  1023. quoteMakeTarget(A->getValue(), Quoted);
  1024. CmdArgs.push_back(Args.MakeArgString(Quoted));
  1025. }
  1026. }
  1027. // Add a default target if one wasn't specified.
  1028. if (!HasTarget) {
  1029. const char *DepTarget;
  1030. // If user provided -o, that is the dependency target, except
  1031. // when we are only generating a dependency file.
  1032. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  1033. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  1034. DepTarget = OutputOpt->getValue();
  1035. } else {
  1036. // Otherwise derive from the base input.
  1037. //
  1038. // FIXME: This should use the computed output file location.
  1039. SmallString<128> P(Inputs[0].getBaseInput());
  1040. llvm::sys::path::replace_extension(P, "o");
  1041. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  1042. }
  1043. CmdArgs.push_back("-MT");
  1044. SmallString<128> Quoted;
  1045. quoteMakeTarget(DepTarget, Quoted);
  1046. CmdArgs.push_back(Args.MakeArgString(Quoted));
  1047. }
  1048. if (ArgM->getOption().matches(options::OPT_M) ||
  1049. ArgM->getOption().matches(options::OPT_MD))
  1050. CmdArgs.push_back("-sys-header-deps");
  1051. if ((isa<PrecompileJobAction>(JA) &&
  1052. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  1053. Args.hasArg(options::OPT_fmodule_file_deps))
  1054. CmdArgs.push_back("-module-file-deps");
  1055. }
  1056. if (Args.hasArg(options::OPT_MG)) {
  1057. if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
  1058. ArgM->getOption().matches(options::OPT_MMD))
  1059. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  1060. CmdArgs.push_back("-MG");
  1061. }
  1062. Args.AddLastArg(CmdArgs, options::OPT_MP);
  1063. Args.AddLastArg(CmdArgs, options::OPT_MV);
  1064. // Add offload include arguments specific for CUDA/HIP. This must happen
  1065. // before we -I or -include anything else, because we must pick up the
  1066. // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
  1067. // from e.g. /usr/local/include.
  1068. if (JA.isOffloading(Action::OFK_Cuda))
  1069. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  1070. if (JA.isOffloading(Action::OFK_HIP))
  1071. getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
  1072. // If we are offloading to a target via OpenMP we need to include the
  1073. // openmp_wrappers folder which contains alternative system headers.
  1074. if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
  1075. !Args.hasArg(options::OPT_nostdinc) &&
  1076. !Args.hasArg(options::OPT_nogpuinc) &&
  1077. (getToolChain().getTriple().isNVPTX() ||
  1078. getToolChain().getTriple().isAMDGCN())) {
  1079. if (!Args.hasArg(options::OPT_nobuiltininc)) {
  1080. // Add openmp_wrappers/* to our system include path. This lets us wrap
  1081. // standard library headers.
  1082. SmallString<128> P(D.ResourceDir);
  1083. llvm::sys::path::append(P, "include");
  1084. llvm::sys::path::append(P, "openmp_wrappers");
  1085. CmdArgs.push_back("-internal-isystem");
  1086. CmdArgs.push_back(Args.MakeArgString(P));
  1087. }
  1088. CmdArgs.push_back("-include");
  1089. CmdArgs.push_back("__clang_openmp_device_functions.h");
  1090. }
  1091. // Add -i* options, and automatically translate to
  1092. // -include-pch/-include-pth for transparent PCH support. It's
  1093. // wonky, but we include looking for .gch so we can support seamless
  1094. // replacement into a build system already set up to be generating
  1095. // .gch files.
  1096. if (getToolChain().getDriver().IsCLMode()) {
  1097. const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  1098. const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  1099. if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
  1100. JA.getKind() <= Action::AssembleJobClass) {
  1101. CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
  1102. // -fpch-instantiate-templates is the default when creating
  1103. // precomp using /Yc
  1104. if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
  1105. options::OPT_fno_pch_instantiate_templates, true))
  1106. CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
  1107. }
  1108. if (YcArg || YuArg) {
  1109. StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
  1110. if (!isa<PrecompileJobAction>(JA)) {
  1111. CmdArgs.push_back("-include-pch");
  1112. CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
  1113. C, !ThroughHeader.empty()
  1114. ? ThroughHeader
  1115. : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
  1116. }
  1117. if (ThroughHeader.empty()) {
  1118. CmdArgs.push_back(Args.MakeArgString(
  1119. Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
  1120. } else {
  1121. CmdArgs.push_back(
  1122. Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
  1123. }
  1124. }
  1125. }
  1126. bool RenderedImplicitInclude = false;
  1127. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  1128. if (A->getOption().matches(options::OPT_include) &&
  1129. D.getProbePrecompiled()) {
  1130. // Handling of gcc-style gch precompiled headers.
  1131. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  1132. RenderedImplicitInclude = true;
  1133. bool FoundPCH = false;
  1134. SmallString<128> P(A->getValue());
  1135. // We want the files to have a name like foo.h.pch. Add a dummy extension
  1136. // so that replace_extension does the right thing.
  1137. P += ".dummy";
  1138. llvm::sys::path::replace_extension(P, "pch");
  1139. if (D.getVFS().exists(P))
  1140. FoundPCH = true;
  1141. if (!FoundPCH) {
  1142. llvm::sys::path::replace_extension(P, "gch");
  1143. if (D.getVFS().exists(P)) {
  1144. FoundPCH = true;
  1145. }
  1146. }
  1147. if (FoundPCH) {
  1148. if (IsFirstImplicitInclude) {
  1149. A->claim();
  1150. CmdArgs.push_back("-include-pch");
  1151. CmdArgs.push_back(Args.MakeArgString(P));
  1152. continue;
  1153. } else {
  1154. // Ignore the PCH if not first on command line and emit warning.
  1155. D.Diag(diag::warn_drv_pch_not_first_include) << P
  1156. << A->getAsString(Args);
  1157. }
  1158. }
  1159. } else if (A->getOption().matches(options::OPT_isystem_after)) {
  1160. // Handling of paths which must come late. These entries are handled by
  1161. // the toolchain itself after the resource dir is inserted in the right
  1162. // search order.
  1163. // Do not claim the argument so that the use of the argument does not
  1164. // silently go unnoticed on toolchains which do not honour the option.
  1165. continue;
  1166. } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
  1167. // Translated to -internal-isystem by the driver, no need to pass to cc1.
  1168. continue;
  1169. }
  1170. // Not translated, render as usual.
  1171. A->claim();
  1172. A->render(Args, CmdArgs);
  1173. }
  1174. Args.AddAllArgs(CmdArgs,
  1175. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  1176. options::OPT_F, options::OPT_index_header_map});
  1177. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  1178. // FIXME: There is a very unfortunate problem here, some troubled
  1179. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  1180. // really support that we would have to parse and then translate
  1181. // those options. :(
  1182. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  1183. options::OPT_Xpreprocessor);
  1184. // -I- is a deprecated GCC feature, reject it.
  1185. if (Arg *A = Args.getLastArg(options::OPT_I_))
  1186. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  1187. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  1188. // -isysroot to the CC1 invocation.
  1189. StringRef sysroot = C.getSysRoot();
  1190. if (sysroot != "") {
  1191. if (!Args.hasArg(options::OPT_isysroot)) {
  1192. CmdArgs.push_back("-isysroot");
  1193. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  1194. }
  1195. }
  1196. // Parse additional include paths from environment variables.
  1197. // FIXME: We should probably sink the logic for handling these from the
  1198. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  1199. // CPATH - included following the user specified includes (but prior to
  1200. // builtin and standard includes).
  1201. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  1202. // C_INCLUDE_PATH - system includes enabled when compiling C.
  1203. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  1204. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  1205. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  1206. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  1207. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  1208. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  1209. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  1210. if (Args.hasArg(options::OPT_fcase_insensitive_paths))
  1211. CmdArgs.push_back("-fcase-insensitive-paths");
  1212. // While adding the include arguments, we also attempt to retrieve the
  1213. // arguments of related offloading toolchains or arguments that are specific
  1214. // of an offloading programming model.
  1215. // Add C++ include arguments, if needed.
  1216. if (types::isCXX(Inputs[0].getType())) {
  1217. bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
  1218. forAllAssociatedToolChains(
  1219. C, JA, getToolChain(),
  1220. [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
  1221. HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
  1222. : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  1223. });
  1224. }
  1225. // Add system include arguments for all targets but IAMCU.
  1226. if (!IsIAMCU)
  1227. forAllAssociatedToolChains(C, JA, getToolChain(),
  1228. [&Args, &CmdArgs](const ToolChain &TC) {
  1229. TC.AddClangSystemIncludeArgs(Args, CmdArgs);
  1230. });
  1231. else {
  1232. // For IAMCU add special include arguments.
  1233. getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
  1234. }
  1235. addMacroPrefixMapArg(D, Args, CmdArgs);
  1236. addCoveragePrefixMapArg(D, Args, CmdArgs);
  1237. Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
  1238. options::OPT_fno_file_reproducible);
  1239. if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
  1240. CmdArgs.push_back("-source-date-epoch");
  1241. CmdArgs.push_back(Args.MakeArgString(Epoch));
  1242. }
  1243. }
  1244. // FIXME: Move to target hook.
  1245. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  1246. switch (Triple.getArch()) {
  1247. default:
  1248. return true;
  1249. case llvm::Triple::aarch64:
  1250. case llvm::Triple::aarch64_32:
  1251. case llvm::Triple::aarch64_be:
  1252. case llvm::Triple::arm:
  1253. case llvm::Triple::armeb:
  1254. case llvm::Triple::thumb:
  1255. case llvm::Triple::thumbeb:
  1256. if (Triple.isOSDarwin() || Triple.isOSWindows())
  1257. return true;
  1258. return false;
  1259. case llvm::Triple::ppc:
  1260. case llvm::Triple::ppc64:
  1261. if (Triple.isOSDarwin())
  1262. return true;
  1263. return false;
  1264. case llvm::Triple::hexagon:
  1265. case llvm::Triple::ppcle:
  1266. case llvm::Triple::ppc64le:
  1267. case llvm::Triple::riscv32:
  1268. case llvm::Triple::riscv64:
  1269. case llvm::Triple::systemz:
  1270. case llvm::Triple::xcore:
  1271. return false;
  1272. }
  1273. }
  1274. static bool hasMultipleInvocations(const llvm::Triple &Triple,
  1275. const ArgList &Args) {
  1276. // Supported only on Darwin where we invoke the compiler multiple times
  1277. // followed by an invocation to lipo.
  1278. if (!Triple.isOSDarwin())
  1279. return false;
  1280. // If more than one "-arch <arch>" is specified, we're targeting multiple
  1281. // architectures resulting in a fat binary.
  1282. return Args.getAllArgValues(options::OPT_arch).size() > 1;
  1283. }
  1284. static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
  1285. const llvm::Triple &Triple) {
  1286. // When enabling remarks, we need to error if:
  1287. // * The remark file is specified but we're targeting multiple architectures,
  1288. // which means more than one remark file is being generated.
  1289. bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
  1290. bool hasExplicitOutputFile =
  1291. Args.getLastArg(options::OPT_foptimization_record_file_EQ);
  1292. if (hasMultipleInvocations && hasExplicitOutputFile) {
  1293. D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
  1294. << "-foptimization-record-file";
  1295. return false;
  1296. }
  1297. return true;
  1298. }
  1299. static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
  1300. const llvm::Triple &Triple,
  1301. const InputInfo &Input,
  1302. const InputInfo &Output, const JobAction &JA) {
  1303. StringRef Format = "yaml";
  1304. if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
  1305. Format = A->getValue();
  1306. CmdArgs.push_back("-opt-record-file");
  1307. const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
  1308. if (A) {
  1309. CmdArgs.push_back(A->getValue());
  1310. } else {
  1311. bool hasMultipleArchs =
  1312. Triple.isOSDarwin() && // Only supported on Darwin platforms.
  1313. Args.getAllArgValues(options::OPT_arch).size() > 1;
  1314. SmallString<128> F;
  1315. if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
  1316. if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
  1317. F = FinalOutput->getValue();
  1318. } else {
  1319. if (Format != "yaml" && // For YAML, keep the original behavior.
  1320. Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
  1321. Output.isFilename())
  1322. F = Output.getFilename();
  1323. }
  1324. if (F.empty()) {
  1325. // Use the input filename.
  1326. F = llvm::sys::path::stem(Input.getBaseInput());
  1327. // If we're compiling for an offload architecture (i.e. a CUDA device),
  1328. // we need to make the file name for the device compilation different
  1329. // from the host compilation.
  1330. if (!JA.isDeviceOffloading(Action::OFK_None) &&
  1331. !JA.isDeviceOffloading(Action::OFK_Host)) {
  1332. llvm::sys::path::replace_extension(F, "");
  1333. F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
  1334. Triple.normalize());
  1335. F += "-";
  1336. F += JA.getOffloadingArch();
  1337. }
  1338. }
  1339. // If we're having more than one "-arch", we should name the files
  1340. // differently so that every cc1 invocation writes to a different file.
  1341. // We're doing that by appending "-<arch>" with "<arch>" being the arch
  1342. // name from the triple.
  1343. if (hasMultipleArchs) {
  1344. // First, remember the extension.
  1345. SmallString<64> OldExtension = llvm::sys::path::extension(F);
  1346. // then, remove it.
  1347. llvm::sys::path::replace_extension(F, "");
  1348. // attach -<arch> to it.
  1349. F += "-";
  1350. F += Triple.getArchName();
  1351. // put back the extension.
  1352. llvm::sys::path::replace_extension(F, OldExtension);
  1353. }
  1354. SmallString<32> Extension;
  1355. Extension += "opt.";
  1356. Extension += Format;
  1357. llvm::sys::path::replace_extension(F, Extension);
  1358. CmdArgs.push_back(Args.MakeArgString(F));
  1359. }
  1360. if (const Arg *A =
  1361. Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
  1362. CmdArgs.push_back("-opt-record-passes");
  1363. CmdArgs.push_back(A->getValue());
  1364. }
  1365. if (!Format.empty()) {
  1366. CmdArgs.push_back("-opt-record-format");
  1367. CmdArgs.push_back(Format.data());
  1368. }
  1369. }
  1370. void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
  1371. if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
  1372. options::OPT_fno_aapcs_bitfield_width, true))
  1373. CmdArgs.push_back("-fno-aapcs-bitfield-width");
  1374. if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
  1375. CmdArgs.push_back("-faapcs-bitfield-load");
  1376. }
  1377. namespace {
  1378. void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
  1379. const ArgList &Args, ArgStringList &CmdArgs) {
  1380. // Select the ABI to use.
  1381. // FIXME: Support -meabi.
  1382. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  1383. const char *ABIName = nullptr;
  1384. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1385. ABIName = A->getValue();
  1386. } else {
  1387. std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
  1388. ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
  1389. }
  1390. CmdArgs.push_back("-target-abi");
  1391. CmdArgs.push_back(ABIName);
  1392. }
  1393. void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
  1394. auto StrictAlignIter =
  1395. llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
  1396. return Arg == "+strict-align" || Arg == "-strict-align";
  1397. });
  1398. if (StrictAlignIter != CmdArgs.rend() &&
  1399. StringRef(*StrictAlignIter) == "+strict-align")
  1400. CmdArgs.push_back("-Wunaligned-access");
  1401. }
  1402. }
  1403. static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
  1404. ArgStringList &CmdArgs, bool isAArch64) {
  1405. const Arg *A = isAArch64
  1406. ? Args.getLastArg(options::OPT_msign_return_address_EQ,
  1407. options::OPT_mbranch_protection_EQ)
  1408. : Args.getLastArg(options::OPT_mbranch_protection_EQ);
  1409. if (!A)
  1410. return;
  1411. const Driver &D = TC.getDriver();
  1412. const llvm::Triple &Triple = TC.getEffectiveTriple();
  1413. if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
  1414. D.Diag(diag::warn_incompatible_branch_protection_option)
  1415. << Triple.getArchName();
  1416. StringRef Scope, Key;
  1417. bool IndirectBranches;
  1418. if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
  1419. Scope = A->getValue();
  1420. if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
  1421. D.Diag(diag::err_drv_unsupported_option_argument)
  1422. << A->getSpelling() << Scope;
  1423. Key = "a_key";
  1424. IndirectBranches = false;
  1425. } else {
  1426. StringRef DiagMsg;
  1427. llvm::ARM::ParsedBranchProtection PBP;
  1428. if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
  1429. D.Diag(diag::err_drv_unsupported_option_argument)
  1430. << A->getSpelling() << DiagMsg;
  1431. if (!isAArch64 && PBP.Key == "b_key")
  1432. D.Diag(diag::warn_unsupported_branch_protection)
  1433. << "b-key" << A->getAsString(Args);
  1434. Scope = PBP.Scope;
  1435. Key = PBP.Key;
  1436. IndirectBranches = PBP.BranchTargetEnforcement;
  1437. }
  1438. CmdArgs.push_back(
  1439. Args.MakeArgString(Twine("-msign-return-address=") + Scope));
  1440. if (!Scope.equals("none"))
  1441. CmdArgs.push_back(
  1442. Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
  1443. if (IndirectBranches)
  1444. CmdArgs.push_back("-mbranch-target-enforce");
  1445. }
  1446. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  1447. ArgStringList &CmdArgs, bool KernelOrKext) const {
  1448. RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
  1449. // Determine floating point ABI from the options & target defaults.
  1450. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  1451. if (ABI == arm::FloatABI::Soft) {
  1452. // Floating point operations and argument passing are soft.
  1453. // FIXME: This changes CPP defines, we need -target-soft-float.
  1454. CmdArgs.push_back("-msoft-float");
  1455. CmdArgs.push_back("-mfloat-abi");
  1456. CmdArgs.push_back("soft");
  1457. } else if (ABI == arm::FloatABI::SoftFP) {
  1458. // Floating point operations are hard, but argument passing is soft.
  1459. CmdArgs.push_back("-mfloat-abi");
  1460. CmdArgs.push_back("soft");
  1461. } else {
  1462. // Floating point operations and argument passing are hard.
  1463. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  1464. CmdArgs.push_back("-mfloat-abi");
  1465. CmdArgs.push_back("hard");
  1466. }
  1467. // Forward the -mglobal-merge option for explicit control over the pass.
  1468. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1469. options::OPT_mno_global_merge)) {
  1470. CmdArgs.push_back("-mllvm");
  1471. if (A->getOption().matches(options::OPT_mno_global_merge))
  1472. CmdArgs.push_back("-arm-global-merge=false");
  1473. else
  1474. CmdArgs.push_back("-arm-global-merge=true");
  1475. }
  1476. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1477. options::OPT_mno_implicit_float, true))
  1478. CmdArgs.push_back("-no-implicit-float");
  1479. if (Args.getLastArg(options::OPT_mcmse))
  1480. CmdArgs.push_back("-mcmse");
  1481. AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
  1482. // Enable/disable return address signing and indirect branch targets.
  1483. CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
  1484. AddUnalignedAccessWarning(CmdArgs);
  1485. }
  1486. void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
  1487. const ArgList &Args, bool KernelOrKext,
  1488. ArgStringList &CmdArgs) const {
  1489. const ToolChain &TC = getToolChain();
  1490. // Add the target features
  1491. getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
  1492. // Add target specific flags.
  1493. switch (TC.getArch()) {
  1494. default:
  1495. break;
  1496. case llvm::Triple::arm:
  1497. case llvm::Triple::armeb:
  1498. case llvm::Triple::thumb:
  1499. case llvm::Triple::thumbeb:
  1500. // Use the effective triple, which takes into account the deployment target.
  1501. AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
  1502. break;
  1503. case llvm::Triple::aarch64:
  1504. case llvm::Triple::aarch64_32:
  1505. case llvm::Triple::aarch64_be:
  1506. AddAArch64TargetArgs(Args, CmdArgs);
  1507. break;
  1508. case llvm::Triple::loongarch32:
  1509. case llvm::Triple::loongarch64:
  1510. AddLoongArchTargetArgs(Args, CmdArgs);
  1511. break;
  1512. case llvm::Triple::mips:
  1513. case llvm::Triple::mipsel:
  1514. case llvm::Triple::mips64:
  1515. case llvm::Triple::mips64el:
  1516. AddMIPSTargetArgs(Args, CmdArgs);
  1517. break;
  1518. case llvm::Triple::ppc:
  1519. case llvm::Triple::ppcle:
  1520. case llvm::Triple::ppc64:
  1521. case llvm::Triple::ppc64le:
  1522. AddPPCTargetArgs(Args, CmdArgs);
  1523. break;
  1524. case llvm::Triple::riscv32:
  1525. case llvm::Triple::riscv64:
  1526. AddRISCVTargetArgs(Args, CmdArgs);
  1527. break;
  1528. case llvm::Triple::sparc:
  1529. case llvm::Triple::sparcel:
  1530. case llvm::Triple::sparcv9:
  1531. AddSparcTargetArgs(Args, CmdArgs);
  1532. break;
  1533. case llvm::Triple::systemz:
  1534. AddSystemZTargetArgs(Args, CmdArgs);
  1535. break;
  1536. case llvm::Triple::x86:
  1537. case llvm::Triple::x86_64:
  1538. AddX86TargetArgs(Args, CmdArgs);
  1539. break;
  1540. case llvm::Triple::lanai:
  1541. AddLanaiTargetArgs(Args, CmdArgs);
  1542. break;
  1543. case llvm::Triple::hexagon:
  1544. AddHexagonTargetArgs(Args, CmdArgs);
  1545. break;
  1546. case llvm::Triple::wasm32:
  1547. case llvm::Triple::wasm64:
  1548. AddWebAssemblyTargetArgs(Args, CmdArgs);
  1549. break;
  1550. case llvm::Triple::ve:
  1551. AddVETargetArgs(Args, CmdArgs);
  1552. break;
  1553. }
  1554. }
  1555. namespace {
  1556. void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
  1557. ArgStringList &CmdArgs) {
  1558. const char *ABIName = nullptr;
  1559. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1560. ABIName = A->getValue();
  1561. else if (Triple.isOSDarwin())
  1562. ABIName = "darwinpcs";
  1563. else
  1564. ABIName = "aapcs";
  1565. CmdArgs.push_back("-target-abi");
  1566. CmdArgs.push_back(ABIName);
  1567. }
  1568. }
  1569. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  1570. ArgStringList &CmdArgs) const {
  1571. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  1572. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1573. Args.hasArg(options::OPT_mkernel) ||
  1574. Args.hasArg(options::OPT_fapple_kext))
  1575. CmdArgs.push_back("-disable-red-zone");
  1576. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1577. options::OPT_mno_implicit_float, true))
  1578. CmdArgs.push_back("-no-implicit-float");
  1579. RenderAArch64ABI(Triple, Args, CmdArgs);
  1580. // Forward the -mglobal-merge option for explicit control over the pass.
  1581. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1582. options::OPT_mno_global_merge)) {
  1583. CmdArgs.push_back("-mllvm");
  1584. if (A->getOption().matches(options::OPT_mno_global_merge))
  1585. CmdArgs.push_back("-aarch64-enable-global-merge=false");
  1586. else
  1587. CmdArgs.push_back("-aarch64-enable-global-merge=true");
  1588. }
  1589. // Enable/disable return address signing and indirect branch targets.
  1590. CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
  1591. // Handle -msve_vector_bits=<bits>
  1592. if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
  1593. StringRef Val = A->getValue();
  1594. const Driver &D = getToolChain().getDriver();
  1595. if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
  1596. Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
  1597. Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
  1598. Val.equals("2048+")) {
  1599. unsigned Bits = 0;
  1600. if (Val.endswith("+"))
  1601. Val = Val.substr(0, Val.size() - 1);
  1602. else {
  1603. bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
  1604. assert(!Invalid && "Failed to parse value");
  1605. CmdArgs.push_back(
  1606. Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
  1607. }
  1608. bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
  1609. assert(!Invalid && "Failed to parse value");
  1610. CmdArgs.push_back(
  1611. Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
  1612. // Silently drop requests for vector-length agnostic code as it's implied.
  1613. } else if (!Val.equals("scalable"))
  1614. // Handle the unsupported values passed to msve-vector-bits.
  1615. D.Diag(diag::err_drv_unsupported_option_argument)
  1616. << A->getSpelling() << Val;
  1617. }
  1618. AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
  1619. if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
  1620. CmdArgs.push_back("-tune-cpu");
  1621. if (strcmp(A->getValue(), "native") == 0)
  1622. CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
  1623. else
  1624. CmdArgs.push_back(A->getValue());
  1625. }
  1626. AddUnalignedAccessWarning(CmdArgs);
  1627. }
  1628. void Clang::AddLoongArchTargetArgs(const ArgList &Args,
  1629. ArgStringList &CmdArgs) const {
  1630. CmdArgs.push_back("-target-abi");
  1631. CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
  1632. getToolChain().getTriple())
  1633. .data());
  1634. }
  1635. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1636. ArgStringList &CmdArgs) const {
  1637. const Driver &D = getToolChain().getDriver();
  1638. StringRef CPUName;
  1639. StringRef ABIName;
  1640. const llvm::Triple &Triple = getToolChain().getTriple();
  1641. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1642. CmdArgs.push_back("-target-abi");
  1643. CmdArgs.push_back(ABIName.data());
  1644. mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
  1645. if (ABI == mips::FloatABI::Soft) {
  1646. // Floating point operations and argument passing are soft.
  1647. CmdArgs.push_back("-msoft-float");
  1648. CmdArgs.push_back("-mfloat-abi");
  1649. CmdArgs.push_back("soft");
  1650. } else {
  1651. // Floating point operations and argument passing are hard.
  1652. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1653. CmdArgs.push_back("-mfloat-abi");
  1654. CmdArgs.push_back("hard");
  1655. }
  1656. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1657. options::OPT_mno_ldc1_sdc1)) {
  1658. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1659. CmdArgs.push_back("-mllvm");
  1660. CmdArgs.push_back("-mno-ldc1-sdc1");
  1661. }
  1662. }
  1663. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1664. options::OPT_mno_check_zero_division)) {
  1665. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1666. CmdArgs.push_back("-mllvm");
  1667. CmdArgs.push_back("-mno-check-zero-division");
  1668. }
  1669. }
  1670. if (Args.getLastArg(options::OPT_mfix4300)) {
  1671. CmdArgs.push_back("-mllvm");
  1672. CmdArgs.push_back("-mfix4300");
  1673. }
  1674. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1675. StringRef v = A->getValue();
  1676. CmdArgs.push_back("-mllvm");
  1677. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1678. A->claim();
  1679. }
  1680. Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
  1681. Arg *ABICalls =
  1682. Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
  1683. // -mabicalls is the default for many MIPS environments, even with -fno-pic.
  1684. // -mgpopt is the default for static, -fno-pic environments but these two
  1685. // options conflict. We want to be certain that -mno-abicalls -mgpopt is
  1686. // the only case where -mllvm -mgpopt is passed.
  1687. // NOTE: We need a warning here or in the backend to warn when -mgpopt is
  1688. // passed explicitly when compiling something with -mabicalls
  1689. // (implictly) in affect. Currently the warning is in the backend.
  1690. //
  1691. // When the ABI in use is N64, we also need to determine the PIC mode that
  1692. // is in use, as -fno-pic for N64 implies -mno-abicalls.
  1693. bool NoABICalls =
  1694. ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
  1695. llvm::Reloc::Model RelocationModel;
  1696. unsigned PICLevel;
  1697. bool IsPIE;
  1698. std::tie(RelocationModel, PICLevel, IsPIE) =
  1699. ParsePICArgs(getToolChain(), Args);
  1700. NoABICalls = NoABICalls ||
  1701. (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
  1702. bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
  1703. // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
  1704. if (NoABICalls && (!GPOpt || WantGPOpt)) {
  1705. CmdArgs.push_back("-mllvm");
  1706. CmdArgs.push_back("-mgpopt");
  1707. Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
  1708. options::OPT_mno_local_sdata);
  1709. Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
  1710. options::OPT_mno_extern_sdata);
  1711. Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
  1712. options::OPT_mno_embedded_data);
  1713. if (LocalSData) {
  1714. CmdArgs.push_back("-mllvm");
  1715. if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
  1716. CmdArgs.push_back("-mlocal-sdata=1");
  1717. } else {
  1718. CmdArgs.push_back("-mlocal-sdata=0");
  1719. }
  1720. LocalSData->claim();
  1721. }
  1722. if (ExternSData) {
  1723. CmdArgs.push_back("-mllvm");
  1724. if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
  1725. CmdArgs.push_back("-mextern-sdata=1");
  1726. } else {
  1727. CmdArgs.push_back("-mextern-sdata=0");
  1728. }
  1729. ExternSData->claim();
  1730. }
  1731. if (EmbeddedData) {
  1732. CmdArgs.push_back("-mllvm");
  1733. if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
  1734. CmdArgs.push_back("-membedded-data=1");
  1735. } else {
  1736. CmdArgs.push_back("-membedded-data=0");
  1737. }
  1738. EmbeddedData->claim();
  1739. }
  1740. } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
  1741. D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
  1742. if (GPOpt)
  1743. GPOpt->claim();
  1744. if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
  1745. StringRef Val = StringRef(A->getValue());
  1746. if (mips::hasCompactBranches(CPUName)) {
  1747. if (Val == "never" || Val == "always" || Val == "optimal") {
  1748. CmdArgs.push_back("-mllvm");
  1749. CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
  1750. } else
  1751. D.Diag(diag::err_drv_unsupported_option_argument)
  1752. << A->getSpelling() << Val;
  1753. } else
  1754. D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
  1755. }
  1756. if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
  1757. options::OPT_mno_relax_pic_calls)) {
  1758. if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
  1759. CmdArgs.push_back("-mllvm");
  1760. CmdArgs.push_back("-mips-jalr-reloc=0");
  1761. }
  1762. }
  1763. }
  1764. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1765. ArgStringList &CmdArgs) const {
  1766. const llvm::Triple &T = getToolChain().getTriple();
  1767. if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
  1768. CmdArgs.push_back("-tune-cpu");
  1769. std::string CPU = ppc::getPPCTuneCPU(Args, T);
  1770. CmdArgs.push_back(Args.MakeArgString(CPU));
  1771. }
  1772. // Select the ABI to use.
  1773. const char *ABIName = nullptr;
  1774. if (T.isOSBinFormatELF()) {
  1775. switch (getToolChain().getArch()) {
  1776. case llvm::Triple::ppc64: {
  1777. if (T.isPPC64ELFv2ABI())
  1778. ABIName = "elfv2";
  1779. else
  1780. ABIName = "elfv1";
  1781. break;
  1782. }
  1783. case llvm::Triple::ppc64le:
  1784. ABIName = "elfv2";
  1785. break;
  1786. default:
  1787. break;
  1788. }
  1789. }
  1790. bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
  1791. for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
  1792. StringRef V = A->getValue();
  1793. if (V == "ieeelongdouble")
  1794. IEEELongDouble = true;
  1795. else if (V == "ibmlongdouble")
  1796. IEEELongDouble = false;
  1797. else if (V != "altivec")
  1798. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1799. // the option if given as we don't have backend support for any targets
  1800. // that don't use the altivec abi.
  1801. ABIName = A->getValue();
  1802. }
  1803. if (IEEELongDouble)
  1804. CmdArgs.push_back("-mabi=ieeelongdouble");
  1805. ppc::FloatABI FloatABI =
  1806. ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
  1807. if (FloatABI == ppc::FloatABI::Soft) {
  1808. // Floating point operations and argument passing are soft.
  1809. CmdArgs.push_back("-msoft-float");
  1810. CmdArgs.push_back("-mfloat-abi");
  1811. CmdArgs.push_back("soft");
  1812. } else {
  1813. // Floating point operations and argument passing are hard.
  1814. assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
  1815. CmdArgs.push_back("-mfloat-abi");
  1816. CmdArgs.push_back("hard");
  1817. }
  1818. if (ABIName) {
  1819. CmdArgs.push_back("-target-abi");
  1820. CmdArgs.push_back(ABIName);
  1821. }
  1822. }
  1823. static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
  1824. ArgStringList &CmdArgs) {
  1825. const Driver &D = TC.getDriver();
  1826. const llvm::Triple &Triple = TC.getTriple();
  1827. // Default small data limitation is eight.
  1828. const char *SmallDataLimit = "8";
  1829. // Get small data limitation.
  1830. if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
  1831. options::OPT_fPIC)) {
  1832. // Not support linker relaxation for PIC.
  1833. SmallDataLimit = "0";
  1834. if (Args.hasArg(options::OPT_G)) {
  1835. D.Diag(diag::warn_drv_unsupported_sdata);
  1836. }
  1837. } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
  1838. .equals_insensitive("large") &&
  1839. (Triple.getArch() == llvm::Triple::riscv64)) {
  1840. // Not support linker relaxation for RV64 with large code model.
  1841. SmallDataLimit = "0";
  1842. if (Args.hasArg(options::OPT_G)) {
  1843. D.Diag(diag::warn_drv_unsupported_sdata);
  1844. }
  1845. } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1846. SmallDataLimit = A->getValue();
  1847. }
  1848. // Forward the -msmall-data-limit= option.
  1849. CmdArgs.push_back("-msmall-data-limit");
  1850. CmdArgs.push_back(SmallDataLimit);
  1851. }
  1852. void Clang::AddRISCVTargetArgs(const ArgList &Args,
  1853. ArgStringList &CmdArgs) const {
  1854. const llvm::Triple &Triple = getToolChain().getTriple();
  1855. StringRef ABIName = riscv::getRISCVABI(Args, Triple);
  1856. CmdArgs.push_back("-target-abi");
  1857. CmdArgs.push_back(ABIName.data());
  1858. SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
  1859. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1860. options::OPT_mno_implicit_float, true))
  1861. CmdArgs.push_back("-no-implicit-float");
  1862. if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
  1863. CmdArgs.push_back("-tune-cpu");
  1864. if (strcmp(A->getValue(), "native") == 0)
  1865. CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
  1866. else
  1867. CmdArgs.push_back(A->getValue());
  1868. }
  1869. }
  1870. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1871. ArgStringList &CmdArgs) const {
  1872. sparc::FloatABI FloatABI =
  1873. sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
  1874. if (FloatABI == sparc::FloatABI::Soft) {
  1875. // Floating point operations and argument passing are soft.
  1876. CmdArgs.push_back("-msoft-float");
  1877. CmdArgs.push_back("-mfloat-abi");
  1878. CmdArgs.push_back("soft");
  1879. } else {
  1880. // Floating point operations and argument passing are hard.
  1881. assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
  1882. CmdArgs.push_back("-mfloat-abi");
  1883. CmdArgs.push_back("hard");
  1884. }
  1885. if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
  1886. StringRef Name = A->getValue();
  1887. std::string TuneCPU;
  1888. if (Name == "native")
  1889. TuneCPU = std::string(llvm::sys::getHostCPUName());
  1890. else
  1891. TuneCPU = std::string(Name);
  1892. CmdArgs.push_back("-tune-cpu");
  1893. CmdArgs.push_back(Args.MakeArgString(TuneCPU));
  1894. }
  1895. }
  1896. void Clang::AddSystemZTargetArgs(const ArgList &Args,
  1897. ArgStringList &CmdArgs) const {
  1898. if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
  1899. CmdArgs.push_back("-tune-cpu");
  1900. if (strcmp(A->getValue(), "native") == 0)
  1901. CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
  1902. else
  1903. CmdArgs.push_back(A->getValue());
  1904. }
  1905. bool HasBackchain =
  1906. Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
  1907. bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
  1908. options::OPT_mno_packed_stack, false);
  1909. systemz::FloatABI FloatABI =
  1910. systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
  1911. bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
  1912. if (HasBackchain && HasPackedStack && !HasSoftFloat) {
  1913. const Driver &D = getToolChain().getDriver();
  1914. D.Diag(diag::err_drv_unsupported_opt)
  1915. << "-mpacked-stack -mbackchain -mhard-float";
  1916. }
  1917. if (HasBackchain)
  1918. CmdArgs.push_back("-mbackchain");
  1919. if (HasPackedStack)
  1920. CmdArgs.push_back("-mpacked-stack");
  1921. if (HasSoftFloat) {
  1922. // Floating point operations and argument passing are soft.
  1923. CmdArgs.push_back("-msoft-float");
  1924. CmdArgs.push_back("-mfloat-abi");
  1925. CmdArgs.push_back("soft");
  1926. }
  1927. }
  1928. void Clang::AddX86TargetArgs(const ArgList &Args,
  1929. ArgStringList &CmdArgs) const {
  1930. const Driver &D = getToolChain().getDriver();
  1931. addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
  1932. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1933. Args.hasArg(options::OPT_mkernel) ||
  1934. Args.hasArg(options::OPT_fapple_kext))
  1935. CmdArgs.push_back("-disable-red-zone");
  1936. if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
  1937. options::OPT_mno_tls_direct_seg_refs, true))
  1938. CmdArgs.push_back("-mno-tls-direct-seg-refs");
  1939. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1940. // that to be overridden with -mno-soft-float.
  1941. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1942. Args.hasArg(options::OPT_fapple_kext));
  1943. if (Arg *A = Args.getLastArg(
  1944. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1945. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1946. const Option &O = A->getOption();
  1947. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1948. O.matches(options::OPT_msoft_float));
  1949. }
  1950. if (NoImplicitFloat)
  1951. CmdArgs.push_back("-no-implicit-float");
  1952. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1953. StringRef Value = A->getValue();
  1954. if (Value == "intel" || Value == "att") {
  1955. CmdArgs.push_back("-mllvm");
  1956. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1957. CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
  1958. } else {
  1959. D.Diag(diag::err_drv_unsupported_option_argument)
  1960. << A->getSpelling() << Value;
  1961. }
  1962. } else if (D.IsCLMode()) {
  1963. CmdArgs.push_back("-mllvm");
  1964. CmdArgs.push_back("-x86-asm-syntax=intel");
  1965. }
  1966. if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
  1967. options::OPT_mno_skip_rax_setup))
  1968. if (A->getOption().matches(options::OPT_mskip_rax_setup))
  1969. CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
  1970. // Set flags to support MCU ABI.
  1971. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
  1972. CmdArgs.push_back("-mfloat-abi");
  1973. CmdArgs.push_back("soft");
  1974. CmdArgs.push_back("-mstack-alignment=4");
  1975. }
  1976. // Handle -mtune.
  1977. // Default to "generic" unless -march is present or targetting the PS4/PS5.
  1978. std::string TuneCPU;
  1979. if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
  1980. !getToolChain().getTriple().isPS())
  1981. TuneCPU = "generic";
  1982. // Override based on -mtune.
  1983. if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
  1984. StringRef Name = A->getValue();
  1985. if (Name == "native") {
  1986. Name = llvm::sys::getHostCPUName();
  1987. if (!Name.empty())
  1988. TuneCPU = std::string(Name);
  1989. } else
  1990. TuneCPU = std::string(Name);
  1991. }
  1992. if (!TuneCPU.empty()) {
  1993. CmdArgs.push_back("-tune-cpu");
  1994. CmdArgs.push_back(Args.MakeArgString(TuneCPU));
  1995. }
  1996. }
  1997. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  1998. ArgStringList &CmdArgs) const {
  1999. CmdArgs.push_back("-mqdsp6-compat");
  2000. CmdArgs.push_back("-Wreturn-type");
  2001. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  2002. CmdArgs.push_back("-mllvm");
  2003. CmdArgs.push_back(
  2004. Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
  2005. }
  2006. if (!Args.hasArg(options::OPT_fno_short_enums))
  2007. CmdArgs.push_back("-fshort-enums");
  2008. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  2009. CmdArgs.push_back("-mllvm");
  2010. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  2011. }
  2012. CmdArgs.push_back("-mllvm");
  2013. CmdArgs.push_back("-machine-sink-split=0");
  2014. }
  2015. void Clang::AddLanaiTargetArgs(const ArgList &Args,
  2016. ArgStringList &CmdArgs) const {
  2017. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  2018. StringRef CPUName = A->getValue();
  2019. CmdArgs.push_back("-target-cpu");
  2020. CmdArgs.push_back(Args.MakeArgString(CPUName));
  2021. }
  2022. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  2023. StringRef Value = A->getValue();
  2024. // Only support mregparm=4 to support old usage. Report error for all other
  2025. // cases.
  2026. int Mregparm;
  2027. if (Value.getAsInteger(10, Mregparm)) {
  2028. if (Mregparm != 4) {
  2029. getToolChain().getDriver().Diag(
  2030. diag::err_drv_unsupported_option_argument)
  2031. << A->getSpelling() << Value;
  2032. }
  2033. }
  2034. }
  2035. }
  2036. void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
  2037. ArgStringList &CmdArgs) const {
  2038. // Default to "hidden" visibility.
  2039. if (!Args.hasArg(options::OPT_fvisibility_EQ,
  2040. options::OPT_fvisibility_ms_compat))
  2041. CmdArgs.push_back("-fvisibility=hidden");
  2042. }
  2043. void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
  2044. // Floating point operations and argument passing are hard.
  2045. CmdArgs.push_back("-mfloat-abi");
  2046. CmdArgs.push_back("hard");
  2047. }
  2048. void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
  2049. StringRef Target, const InputInfo &Output,
  2050. const InputInfo &Input, const ArgList &Args) const {
  2051. // If this is a dry run, do not create the compilation database file.
  2052. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
  2053. return;
  2054. using llvm::yaml::escape;
  2055. const Driver &D = getToolChain().getDriver();
  2056. if (!CompilationDatabase) {
  2057. std::error_code EC;
  2058. auto File = std::make_unique<llvm::raw_fd_ostream>(
  2059. Filename, EC,
  2060. llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
  2061. if (EC) {
  2062. D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
  2063. << EC.message();
  2064. return;
  2065. }
  2066. CompilationDatabase = std::move(File);
  2067. }
  2068. auto &CDB = *CompilationDatabase;
  2069. auto CWD = D.getVFS().getCurrentWorkingDirectory();
  2070. if (!CWD)
  2071. CWD = ".";
  2072. CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
  2073. CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
  2074. CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
  2075. CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
  2076. SmallString<128> Buf;
  2077. Buf = "-x";
  2078. Buf += types::getTypeName(Input.getType());
  2079. CDB << ", \"" << escape(Buf) << "\"";
  2080. if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
  2081. Buf = "--sysroot=";
  2082. Buf += D.SysRoot;
  2083. CDB << ", \"" << escape(Buf) << "\"";
  2084. }
  2085. CDB << ", \"" << escape(Input.getFilename()) << "\"";
  2086. CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
  2087. for (auto &A: Args) {
  2088. auto &O = A->getOption();
  2089. // Skip language selection, which is positional.
  2090. if (O.getID() == options::OPT_x)
  2091. continue;
  2092. // Skip writing dependency output and the compilation database itself.
  2093. if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
  2094. continue;
  2095. if (O.getID() == options::OPT_gen_cdb_fragment_path)
  2096. continue;
  2097. // Skip inputs.
  2098. if (O.getKind() == Option::InputClass)
  2099. continue;
  2100. // Skip output.
  2101. if (O.getID() == options::OPT_o)
  2102. continue;
  2103. // All other arguments are quoted and appended.
  2104. ArgStringList ASL;
  2105. A->render(Args, ASL);
  2106. for (auto &it: ASL)
  2107. CDB << ", \"" << escape(it) << "\"";
  2108. }
  2109. Buf = "--target=";
  2110. Buf += Target;
  2111. CDB << ", \"" << escape(Buf) << "\"]},\n";
  2112. }
  2113. void Clang::DumpCompilationDatabaseFragmentToDir(
  2114. StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
  2115. const InputInfo &Input, const llvm::opt::ArgList &Args) const {
  2116. // If this is a dry run, do not create the compilation database file.
  2117. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
  2118. return;
  2119. if (CompilationDatabase)
  2120. DumpCompilationDatabase(C, "", Target, Output, Input, Args);
  2121. SmallString<256> Path = Dir;
  2122. const auto &Driver = C.getDriver();
  2123. Driver.getVFS().makeAbsolute(Path);
  2124. auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
  2125. if (Err) {
  2126. Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
  2127. return;
  2128. }
  2129. llvm::sys::path::append(
  2130. Path,
  2131. Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
  2132. int FD;
  2133. SmallString<256> TempPath;
  2134. Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
  2135. llvm::sys::fs::OF_Text);
  2136. if (Err) {
  2137. Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
  2138. return;
  2139. }
  2140. CompilationDatabase =
  2141. std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
  2142. DumpCompilationDatabase(C, "", Target, Output, Input, Args);
  2143. }
  2144. static bool CheckARMImplicitITArg(StringRef Value) {
  2145. return Value == "always" || Value == "never" || Value == "arm" ||
  2146. Value == "thumb";
  2147. }
  2148. static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2149. StringRef Value) {
  2150. CmdArgs.push_back("-mllvm");
  2151. CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
  2152. }
  2153. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2154. const ArgList &Args,
  2155. ArgStringList &CmdArgs,
  2156. const Driver &D) {
  2157. if (UseRelaxAll(C, Args))
  2158. CmdArgs.push_back("-mrelax-all");
  2159. // Only default to -mincremental-linker-compatible if we think we are
  2160. // targeting the MSVC linker.
  2161. bool DefaultIncrementalLinkerCompatible =
  2162. C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
  2163. if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
  2164. options::OPT_mno_incremental_linker_compatible,
  2165. DefaultIncrementalLinkerCompatible))
  2166. CmdArgs.push_back("-mincremental-linker-compatible");
  2167. Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
  2168. // If you add more args here, also add them to the block below that
  2169. // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
  2170. // When passing -I arguments to the assembler we sometimes need to
  2171. // unconditionally take the next argument. For example, when parsing
  2172. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2173. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2174. // arg after parsing the '-I' arg.
  2175. bool TakeNextArg = false;
  2176. bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
  2177. bool UseNoExecStack = false;
  2178. const char *MipsTargetFeature = nullptr;
  2179. StringRef ImplicitIt;
  2180. for (const Arg *A :
  2181. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
  2182. options::OPT_mimplicit_it_EQ)) {
  2183. A->claim();
  2184. if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
  2185. switch (C.getDefaultToolChain().getArch()) {
  2186. case llvm::Triple::arm:
  2187. case llvm::Triple::armeb:
  2188. case llvm::Triple::thumb:
  2189. case llvm::Triple::thumbeb:
  2190. // Only store the value; the last value set takes effect.
  2191. ImplicitIt = A->getValue();
  2192. if (!CheckARMImplicitITArg(ImplicitIt))
  2193. D.Diag(diag::err_drv_unsupported_option_argument)
  2194. << A->getSpelling() << ImplicitIt;
  2195. continue;
  2196. default:
  2197. break;
  2198. }
  2199. }
  2200. for (StringRef Value : A->getValues()) {
  2201. if (TakeNextArg) {
  2202. CmdArgs.push_back(Value.data());
  2203. TakeNextArg = false;
  2204. continue;
  2205. }
  2206. if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
  2207. Value == "-mbig-obj")
  2208. continue; // LLVM handles bigobj automatically
  2209. switch (C.getDefaultToolChain().getArch()) {
  2210. default:
  2211. break;
  2212. case llvm::Triple::wasm32:
  2213. case llvm::Triple::wasm64:
  2214. if (Value == "--no-type-check") {
  2215. CmdArgs.push_back("-mno-type-check");
  2216. continue;
  2217. }
  2218. break;
  2219. case llvm::Triple::thumb:
  2220. case llvm::Triple::thumbeb:
  2221. case llvm::Triple::arm:
  2222. case llvm::Triple::armeb:
  2223. if (Value.startswith("-mimplicit-it=")) {
  2224. // Only store the value; the last value set takes effect.
  2225. ImplicitIt = Value.split("=").second;
  2226. if (CheckARMImplicitITArg(ImplicitIt))
  2227. continue;
  2228. }
  2229. if (Value == "-mthumb")
  2230. // -mthumb has already been processed in ComputeLLVMTriple()
  2231. // recognize but skip over here.
  2232. continue;
  2233. break;
  2234. case llvm::Triple::mips:
  2235. case llvm::Triple::mipsel:
  2236. case llvm::Triple::mips64:
  2237. case llvm::Triple::mips64el:
  2238. if (Value == "--trap") {
  2239. CmdArgs.push_back("-target-feature");
  2240. CmdArgs.push_back("+use-tcc-in-div");
  2241. continue;
  2242. }
  2243. if (Value == "--break") {
  2244. CmdArgs.push_back("-target-feature");
  2245. CmdArgs.push_back("-use-tcc-in-div");
  2246. continue;
  2247. }
  2248. if (Value.startswith("-msoft-float")) {
  2249. CmdArgs.push_back("-target-feature");
  2250. CmdArgs.push_back("+soft-float");
  2251. continue;
  2252. }
  2253. if (Value.startswith("-mhard-float")) {
  2254. CmdArgs.push_back("-target-feature");
  2255. CmdArgs.push_back("-soft-float");
  2256. continue;
  2257. }
  2258. MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
  2259. .Case("-mips1", "+mips1")
  2260. .Case("-mips2", "+mips2")
  2261. .Case("-mips3", "+mips3")
  2262. .Case("-mips4", "+mips4")
  2263. .Case("-mips5", "+mips5")
  2264. .Case("-mips32", "+mips32")
  2265. .Case("-mips32r2", "+mips32r2")
  2266. .Case("-mips32r3", "+mips32r3")
  2267. .Case("-mips32r5", "+mips32r5")
  2268. .Case("-mips32r6", "+mips32r6")
  2269. .Case("-mips64", "+mips64")
  2270. .Case("-mips64r2", "+mips64r2")
  2271. .Case("-mips64r3", "+mips64r3")
  2272. .Case("-mips64r5", "+mips64r5")
  2273. .Case("-mips64r6", "+mips64r6")
  2274. .Default(nullptr);
  2275. if (MipsTargetFeature)
  2276. continue;
  2277. }
  2278. if (Value == "-force_cpusubtype_ALL") {
  2279. // Do nothing, this is the default and we don't support anything else.
  2280. } else if (Value == "-L") {
  2281. CmdArgs.push_back("-msave-temp-labels");
  2282. } else if (Value == "--fatal-warnings") {
  2283. CmdArgs.push_back("-massembler-fatal-warnings");
  2284. } else if (Value == "--no-warn" || Value == "-W") {
  2285. CmdArgs.push_back("-massembler-no-warn");
  2286. } else if (Value == "--noexecstack") {
  2287. UseNoExecStack = true;
  2288. } else if (Value.startswith("-compress-debug-sections") ||
  2289. Value.startswith("--compress-debug-sections") ||
  2290. Value == "-nocompress-debug-sections" ||
  2291. Value == "--nocompress-debug-sections") {
  2292. CmdArgs.push_back(Value.data());
  2293. } else if (Value == "-mrelax-relocations=yes" ||
  2294. Value == "--mrelax-relocations=yes") {
  2295. UseRelaxRelocations = true;
  2296. } else if (Value == "-mrelax-relocations=no" ||
  2297. Value == "--mrelax-relocations=no") {
  2298. UseRelaxRelocations = false;
  2299. } else if (Value.startswith("-I")) {
  2300. CmdArgs.push_back(Value.data());
  2301. // We need to consume the next argument if the current arg is a plain
  2302. // -I. The next arg will be the include directory.
  2303. if (Value == "-I")
  2304. TakeNextArg = true;
  2305. } else if (Value.startswith("-gdwarf-")) {
  2306. // "-gdwarf-N" options are not cc1as options.
  2307. unsigned DwarfVersion = DwarfVersionNum(Value);
  2308. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2309. CmdArgs.push_back(Value.data());
  2310. } else {
  2311. RenderDebugEnablingArgs(Args, CmdArgs,
  2312. codegenoptions::DebugInfoConstructor,
  2313. DwarfVersion, llvm::DebuggerKind::Default);
  2314. }
  2315. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2316. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2317. // Do nothing, we'll validate it later.
  2318. } else if (Value == "-defsym") {
  2319. if (A->getNumValues() != 2) {
  2320. D.Diag(diag::err_drv_defsym_invalid_format) << Value;
  2321. break;
  2322. }
  2323. const char *S = A->getValue(1);
  2324. auto Pair = StringRef(S).split('=');
  2325. auto Sym = Pair.first;
  2326. auto SVal = Pair.second;
  2327. if (Sym.empty() || SVal.empty()) {
  2328. D.Diag(diag::err_drv_defsym_invalid_format) << S;
  2329. break;
  2330. }
  2331. int64_t IVal;
  2332. if (SVal.getAsInteger(0, IVal)) {
  2333. D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
  2334. break;
  2335. }
  2336. CmdArgs.push_back(Value.data());
  2337. TakeNextArg = true;
  2338. } else if (Value == "-fdebug-compilation-dir") {
  2339. CmdArgs.push_back("-fdebug-compilation-dir");
  2340. TakeNextArg = true;
  2341. } else if (Value.consume_front("-fdebug-compilation-dir=")) {
  2342. // The flag is a -Wa / -Xassembler argument and Options doesn't
  2343. // parse the argument, so this isn't automatically aliased to
  2344. // -fdebug-compilation-dir (without '=') here.
  2345. CmdArgs.push_back("-fdebug-compilation-dir");
  2346. CmdArgs.push_back(Value.data());
  2347. } else if (Value == "--version") {
  2348. D.PrintVersion(C, llvm::outs());
  2349. } else {
  2350. D.Diag(diag::err_drv_unsupported_option_argument)
  2351. << A->getSpelling() << Value;
  2352. }
  2353. }
  2354. }
  2355. if (ImplicitIt.size())
  2356. AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
  2357. if (!UseRelaxRelocations)
  2358. CmdArgs.push_back("-mrelax-relocations=no");
  2359. if (UseNoExecStack)
  2360. CmdArgs.push_back("-mnoexecstack");
  2361. if (MipsTargetFeature != nullptr) {
  2362. CmdArgs.push_back("-target-feature");
  2363. CmdArgs.push_back(MipsTargetFeature);
  2364. }
  2365. // forward -fembed-bitcode to assmebler
  2366. if (C.getDriver().embedBitcodeEnabled() ||
  2367. C.getDriver().embedBitcodeMarkerOnly())
  2368. Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
  2369. if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
  2370. CmdArgs.push_back("-as-secure-log-file");
  2371. CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
  2372. }
  2373. }
  2374. static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
  2375. bool OFastEnabled, const ArgList &Args,
  2376. ArgStringList &CmdArgs,
  2377. const JobAction &JA) {
  2378. // Handle various floating point optimization flags, mapping them to the
  2379. // appropriate LLVM code generation flags. This is complicated by several
  2380. // "umbrella" flags, so we do this by stepping through the flags incrementally
  2381. // adjusting what we think is enabled/disabled, then at the end setting the
  2382. // LLVM flags based on the final state.
  2383. bool HonorINFs = true;
  2384. bool HonorNaNs = true;
  2385. bool ApproxFunc = false;
  2386. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  2387. bool MathErrno = TC.IsMathErrnoDefault();
  2388. bool AssociativeMath = false;
  2389. bool ReciprocalMath = false;
  2390. bool SignedZeros = true;
  2391. bool TrappingMath = false; // Implemented via -ffp-exception-behavior
  2392. bool TrappingMathPresent = false; // Is trapping-math in args, and not
  2393. // overriden by ffp-exception-behavior?
  2394. bool RoundingFPMath = false;
  2395. bool RoundingMathPresent = false; // Is rounding-math in args?
  2396. // -ffp-model values: strict, fast, precise
  2397. StringRef FPModel = "";
  2398. // -ffp-exception-behavior options: strict, maytrap, ignore
  2399. StringRef FPExceptionBehavior = "";
  2400. // -ffp-eval-method options: double, extended, source
  2401. StringRef FPEvalMethod = "";
  2402. const llvm::DenormalMode DefaultDenormalFPMath =
  2403. TC.getDefaultDenormalModeForType(Args, JA);
  2404. const llvm::DenormalMode DefaultDenormalFP32Math =
  2405. TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
  2406. llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
  2407. llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
  2408. // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
  2409. // If one wasn't given by the user, don't pass it here.
  2410. StringRef FPContract;
  2411. StringRef LastSeenFfpContractOption;
  2412. bool SeenUnsafeMathModeOption = false;
  2413. if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
  2414. !JA.isOffloading(Action::OFK_HIP))
  2415. FPContract = "on";
  2416. bool StrictFPModel = false;
  2417. StringRef Float16ExcessPrecision = "";
  2418. if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  2419. CmdArgs.push_back("-mlimit-float-precision");
  2420. CmdArgs.push_back(A->getValue());
  2421. }
  2422. for (const Arg *A : Args) {
  2423. auto optID = A->getOption().getID();
  2424. bool PreciseFPModel = false;
  2425. switch (optID) {
  2426. default:
  2427. break;
  2428. case options::OPT_ffp_model_EQ: {
  2429. // If -ffp-model= is seen, reset to fno-fast-math
  2430. HonorINFs = true;
  2431. HonorNaNs = true;
  2432. ApproxFunc = false;
  2433. // Turning *off* -ffast-math restores the toolchain default.
  2434. MathErrno = TC.IsMathErrnoDefault();
  2435. AssociativeMath = false;
  2436. ReciprocalMath = false;
  2437. SignedZeros = true;
  2438. // -fno_fast_math restores default denormal and fpcontract handling
  2439. FPContract = "on";
  2440. DenormalFPMath = llvm::DenormalMode::getIEEE();
  2441. // FIXME: The target may have picked a non-IEEE default mode here based on
  2442. // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
  2443. DenormalFP32Math = llvm::DenormalMode::getIEEE();
  2444. StringRef Val = A->getValue();
  2445. if (OFastEnabled && !Val.equals("fast")) {
  2446. // Only -ffp-model=fast is compatible with OFast, ignore.
  2447. D.Diag(clang::diag::warn_drv_overriding_flag_option)
  2448. << Args.MakeArgString("-ffp-model=" + Val)
  2449. << "-Ofast";
  2450. break;
  2451. }
  2452. StrictFPModel = false;
  2453. PreciseFPModel = true;
  2454. // ffp-model= is a Driver option, it is entirely rewritten into more
  2455. // granular options before being passed into cc1.
  2456. // Use the gcc option in the switch below.
  2457. if (!FPModel.empty() && !FPModel.equals(Val))
  2458. D.Diag(clang::diag::warn_drv_overriding_flag_option)
  2459. << Args.MakeArgString("-ffp-model=" + FPModel)
  2460. << Args.MakeArgString("-ffp-model=" + Val);
  2461. if (Val.equals("fast")) {
  2462. optID = options::OPT_ffast_math;
  2463. FPModel = Val;
  2464. FPContract = "fast";
  2465. } else if (Val.equals("precise")) {
  2466. optID = options::OPT_ffp_contract;
  2467. FPModel = Val;
  2468. FPContract = "on";
  2469. PreciseFPModel = true;
  2470. } else if (Val.equals("strict")) {
  2471. StrictFPModel = true;
  2472. optID = options::OPT_frounding_math;
  2473. FPExceptionBehavior = "strict";
  2474. FPModel = Val;
  2475. FPContract = "off";
  2476. TrappingMath = true;
  2477. } else
  2478. D.Diag(diag::err_drv_unsupported_option_argument)
  2479. << A->getSpelling() << Val;
  2480. break;
  2481. }
  2482. }
  2483. switch (optID) {
  2484. // If this isn't an FP option skip the claim below
  2485. default: continue;
  2486. // Options controlling individual features
  2487. case options::OPT_fhonor_infinities: HonorINFs = true; break;
  2488. case options::OPT_fno_honor_infinities: HonorINFs = false; break;
  2489. case options::OPT_fhonor_nans: HonorNaNs = true; break;
  2490. case options::OPT_fno_honor_nans: HonorNaNs = false; break;
  2491. case options::OPT_fapprox_func: ApproxFunc = true; break;
  2492. case options::OPT_fno_approx_func: ApproxFunc = false; break;
  2493. case options::OPT_fmath_errno: MathErrno = true; break;
  2494. case options::OPT_fno_math_errno: MathErrno = false; break;
  2495. case options::OPT_fassociative_math: AssociativeMath = true; break;
  2496. case options::OPT_fno_associative_math: AssociativeMath = false; break;
  2497. case options::OPT_freciprocal_math: ReciprocalMath = true; break;
  2498. case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
  2499. case options::OPT_fsigned_zeros: SignedZeros = true; break;
  2500. case options::OPT_fno_signed_zeros: SignedZeros = false; break;
  2501. case options::OPT_ftrapping_math:
  2502. if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
  2503. !FPExceptionBehavior.equals("strict"))
  2504. // Warn that previous value of option is overridden.
  2505. D.Diag(clang::diag::warn_drv_overriding_flag_option)
  2506. << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
  2507. << "-ftrapping-math";
  2508. TrappingMath = true;
  2509. TrappingMathPresent = true;
  2510. FPExceptionBehavior = "strict";
  2511. break;
  2512. case options::OPT_fno_trapping_math:
  2513. if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
  2514. !FPExceptionBehavior.equals("ignore"))
  2515. // Warn that previous value of option is overridden.
  2516. D.Diag(clang::diag::warn_drv_overriding_flag_option)
  2517. << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
  2518. << "-fno-trapping-math";
  2519. TrappingMath = false;
  2520. TrappingMathPresent = true;
  2521. FPExceptionBehavior = "ignore";
  2522. break;
  2523. case options::OPT_frounding_math:
  2524. RoundingFPMath = true;
  2525. RoundingMathPresent = true;
  2526. break;
  2527. case options::OPT_fno_rounding_math:
  2528. RoundingFPMath = false;
  2529. RoundingMathPresent = false;
  2530. break;
  2531. case options::OPT_fdenormal_fp_math_EQ:
  2532. DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
  2533. DenormalFP32Math = DenormalFPMath;
  2534. if (!DenormalFPMath.isValid()) {
  2535. D.Diag(diag::err_drv_invalid_value)
  2536. << A->getAsString(Args) << A->getValue();
  2537. }
  2538. break;
  2539. case options::OPT_fdenormal_fp_math_f32_EQ:
  2540. DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
  2541. if (!DenormalFP32Math.isValid()) {
  2542. D.Diag(diag::err_drv_invalid_value)
  2543. << A->getAsString(Args) << A->getValue();
  2544. }
  2545. break;
  2546. // Validate and pass through -ffp-contract option.
  2547. case options::OPT_ffp_contract: {
  2548. StringRef Val = A->getValue();
  2549. if (PreciseFPModel) {
  2550. // -ffp-model=precise enables ffp-contract=on.
  2551. // -ffp-model=precise sets PreciseFPModel to on and Val to
  2552. // "precise". FPContract is set.
  2553. ;
  2554. } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off")) {
  2555. FPContract = Val;
  2556. LastSeenFfpContractOption = Val;
  2557. } else
  2558. D.Diag(diag::err_drv_unsupported_option_argument)
  2559. << A->getSpelling() << Val;
  2560. break;
  2561. }
  2562. // Validate and pass through -ffp-model option.
  2563. case options::OPT_ffp_model_EQ:
  2564. // This should only occur in the error case
  2565. // since the optID has been replaced by a more granular
  2566. // floating point option.
  2567. break;
  2568. // Validate and pass through -ffp-exception-behavior option.
  2569. case options::OPT_ffp_exception_behavior_EQ: {
  2570. StringRef Val = A->getValue();
  2571. if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
  2572. !FPExceptionBehavior.equals(Val))
  2573. // Warn that previous value of option is overridden.
  2574. D.Diag(clang::diag::warn_drv_overriding_flag_option)
  2575. << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
  2576. << Args.MakeArgString("-ffp-exception-behavior=" + Val);
  2577. TrappingMath = TrappingMathPresent = false;
  2578. if (Val.equals("ignore") || Val.equals("maytrap"))
  2579. FPExceptionBehavior = Val;
  2580. else if (Val.equals("strict")) {
  2581. FPExceptionBehavior = Val;
  2582. TrappingMath = TrappingMathPresent = true;
  2583. } else
  2584. D.Diag(diag::err_drv_unsupported_option_argument)
  2585. << A->getSpelling() << Val;
  2586. break;
  2587. }
  2588. // Validate and pass through -ffp-eval-method option.
  2589. case options::OPT_ffp_eval_method_EQ: {
  2590. StringRef Val = A->getValue();
  2591. if (Val.equals("double") || Val.equals("extended") ||
  2592. Val.equals("source"))
  2593. FPEvalMethod = Val;
  2594. else
  2595. D.Diag(diag::err_drv_unsupported_option_argument)
  2596. << A->getSpelling() << Val;
  2597. break;
  2598. }
  2599. case options::OPT_fexcess_precision_EQ: {
  2600. StringRef Val = A->getValue();
  2601. const llvm::Triple::ArchType Arch = TC.getArch();
  2602. if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  2603. if (Val.equals("standard") || Val.equals("fast"))
  2604. Float16ExcessPrecision = Val;
  2605. // To make it GCC compatible, allow the value of "16" which
  2606. // means disable excess precision, the same meaning than clang's
  2607. // equivalent value "none".
  2608. else if (Val.equals("16"))
  2609. Float16ExcessPrecision = "none";
  2610. else
  2611. D.Diag(diag::err_drv_unsupported_option_argument)
  2612. << A->getSpelling() << Val;
  2613. } else {
  2614. if (!(Val.equals("standard") || Val.equals("fast")))
  2615. D.Diag(diag::err_drv_unsupported_option_argument)
  2616. << A->getSpelling() << Val;
  2617. }
  2618. break;
  2619. }
  2620. case options::OPT_ffinite_math_only:
  2621. HonorINFs = false;
  2622. HonorNaNs = false;
  2623. break;
  2624. case options::OPT_fno_finite_math_only:
  2625. HonorINFs = true;
  2626. HonorNaNs = true;
  2627. break;
  2628. case options::OPT_funsafe_math_optimizations:
  2629. AssociativeMath = true;
  2630. ReciprocalMath = true;
  2631. SignedZeros = false;
  2632. ApproxFunc = true;
  2633. TrappingMath = false;
  2634. FPExceptionBehavior = "";
  2635. FPContract = "fast";
  2636. SeenUnsafeMathModeOption = true;
  2637. break;
  2638. case options::OPT_fno_unsafe_math_optimizations:
  2639. AssociativeMath = false;
  2640. ReciprocalMath = false;
  2641. SignedZeros = true;
  2642. ApproxFunc = false;
  2643. TrappingMath = true;
  2644. FPExceptionBehavior = "strict";
  2645. // The target may have opted to flush by default, so force IEEE.
  2646. DenormalFPMath = llvm::DenormalMode::getIEEE();
  2647. DenormalFP32Math = llvm::DenormalMode::getIEEE();
  2648. if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
  2649. !JA.isOffloading(Action::OFK_HIP)) {
  2650. if (LastSeenFfpContractOption != "") {
  2651. FPContract = LastSeenFfpContractOption;
  2652. } else if (SeenUnsafeMathModeOption)
  2653. FPContract = "on";
  2654. }
  2655. break;
  2656. case options::OPT_Ofast:
  2657. // If -Ofast is the optimization level, then -ffast-math should be enabled
  2658. if (!OFastEnabled)
  2659. continue;
  2660. [[fallthrough]];
  2661. case options::OPT_ffast_math:
  2662. HonorINFs = false;
  2663. HonorNaNs = false;
  2664. MathErrno = false;
  2665. AssociativeMath = true;
  2666. ReciprocalMath = true;
  2667. ApproxFunc = true;
  2668. SignedZeros = false;
  2669. TrappingMath = false;
  2670. RoundingFPMath = false;
  2671. FPExceptionBehavior = "";
  2672. // If fast-math is set then set the fp-contract mode to fast.
  2673. FPContract = "fast";
  2674. SeenUnsafeMathModeOption = true;
  2675. break;
  2676. case options::OPT_fno_fast_math:
  2677. HonorINFs = true;
  2678. HonorNaNs = true;
  2679. // Turning on -ffast-math (with either flag) removes the need for
  2680. // MathErrno. However, turning *off* -ffast-math merely restores the
  2681. // toolchain default (which may be false).
  2682. MathErrno = TC.IsMathErrnoDefault();
  2683. AssociativeMath = false;
  2684. ReciprocalMath = false;
  2685. ApproxFunc = false;
  2686. SignedZeros = true;
  2687. // -fno_fast_math restores default denormal and fpcontract handling
  2688. DenormalFPMath = DefaultDenormalFPMath;
  2689. DenormalFP32Math = llvm::DenormalMode::getIEEE();
  2690. if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
  2691. !JA.isOffloading(Action::OFK_HIP)) {
  2692. if (LastSeenFfpContractOption != "") {
  2693. FPContract = LastSeenFfpContractOption;
  2694. } else if (SeenUnsafeMathModeOption)
  2695. FPContract = "on";
  2696. }
  2697. break;
  2698. }
  2699. if (StrictFPModel) {
  2700. // If -ffp-model=strict has been specified on command line but
  2701. // subsequent options conflict then emit warning diagnostic.
  2702. if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
  2703. SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
  2704. DenormalFPMath == llvm::DenormalMode::getIEEE() &&
  2705. DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
  2706. FPContract.equals("off"))
  2707. // OK: Current Arg doesn't conflict with -ffp-model=strict
  2708. ;
  2709. else {
  2710. StrictFPModel = false;
  2711. FPModel = "";
  2712. auto RHS = (A->getNumValues() == 0)
  2713. ? A->getSpelling()
  2714. : Args.MakeArgString(A->getSpelling() + A->getValue());
  2715. if (RHS != "-ffp-model=strict")
  2716. D.Diag(clang::diag::warn_drv_overriding_flag_option)
  2717. << "-ffp-model=strict" << RHS;
  2718. }
  2719. }
  2720. // If we handled this option claim it
  2721. A->claim();
  2722. }
  2723. if (!HonorINFs)
  2724. CmdArgs.push_back("-menable-no-infs");
  2725. if (!HonorNaNs)
  2726. CmdArgs.push_back("-menable-no-nans");
  2727. if (ApproxFunc)
  2728. CmdArgs.push_back("-fapprox-func");
  2729. if (MathErrno)
  2730. CmdArgs.push_back("-fmath-errno");
  2731. if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
  2732. !TrappingMath)
  2733. CmdArgs.push_back("-funsafe-math-optimizations");
  2734. if (!SignedZeros)
  2735. CmdArgs.push_back("-fno-signed-zeros");
  2736. if (AssociativeMath && !SignedZeros && !TrappingMath)
  2737. CmdArgs.push_back("-mreassociate");
  2738. if (ReciprocalMath)
  2739. CmdArgs.push_back("-freciprocal-math");
  2740. if (TrappingMath) {
  2741. // FP Exception Behavior is also set to strict
  2742. assert(FPExceptionBehavior.equals("strict"));
  2743. }
  2744. // The default is IEEE.
  2745. if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
  2746. llvm::SmallString<64> DenormFlag;
  2747. llvm::raw_svector_ostream ArgStr(DenormFlag);
  2748. ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
  2749. CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
  2750. }
  2751. // Add f32 specific denormal mode flag if it's different.
  2752. if (DenormalFP32Math != DenormalFPMath) {
  2753. llvm::SmallString<64> DenormFlag;
  2754. llvm::raw_svector_ostream ArgStr(DenormFlag);
  2755. ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
  2756. CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
  2757. }
  2758. if (!FPContract.empty())
  2759. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
  2760. if (!RoundingFPMath)
  2761. CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
  2762. if (RoundingFPMath && RoundingMathPresent)
  2763. CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
  2764. if (!FPExceptionBehavior.empty())
  2765. CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
  2766. FPExceptionBehavior));
  2767. if (!FPEvalMethod.empty())
  2768. CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
  2769. if (!Float16ExcessPrecision.empty())
  2770. CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
  2771. Float16ExcessPrecision));
  2772. ParseMRecip(D, Args, CmdArgs);
  2773. // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
  2774. // individual features enabled by -ffast-math instead of the option itself as
  2775. // that's consistent with gcc's behaviour.
  2776. if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
  2777. ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
  2778. CmdArgs.push_back("-ffast-math");
  2779. if (FPModel.equals("fast")) {
  2780. if (FPContract.equals("fast"))
  2781. // All set, do nothing.
  2782. ;
  2783. else if (FPContract.empty())
  2784. // Enable -ffp-contract=fast
  2785. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  2786. else
  2787. D.Diag(clang::diag::warn_drv_overriding_flag_option)
  2788. << "-ffp-model=fast"
  2789. << Args.MakeArgString("-ffp-contract=" + FPContract);
  2790. }
  2791. }
  2792. // Handle __FINITE_MATH_ONLY__ similarly.
  2793. if (!HonorINFs && !HonorNaNs)
  2794. CmdArgs.push_back("-ffinite-math-only");
  2795. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  2796. CmdArgs.push_back("-mfpmath");
  2797. CmdArgs.push_back(A->getValue());
  2798. }
  2799. // Disable a codegen optimization for floating-point casts.
  2800. if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
  2801. options::OPT_fstrict_float_cast_overflow, false))
  2802. CmdArgs.push_back("-fno-strict-float-cast-overflow");
  2803. }
  2804. static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
  2805. const llvm::Triple &Triple,
  2806. const InputInfo &Input) {
  2807. // Add default argument set.
  2808. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  2809. CmdArgs.push_back("-analyzer-checker=core");
  2810. CmdArgs.push_back("-analyzer-checker=apiModeling");
  2811. if (!Triple.isWindowsMSVCEnvironment()) {
  2812. CmdArgs.push_back("-analyzer-checker=unix");
  2813. } else {
  2814. // Enable "unix" checkers that also work on Windows.
  2815. CmdArgs.push_back("-analyzer-checker=unix.API");
  2816. CmdArgs.push_back("-analyzer-checker=unix.Malloc");
  2817. CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
  2818. CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
  2819. CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
  2820. CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
  2821. }
  2822. // Disable some unix checkers for PS4/PS5.
  2823. if (Triple.isPS()) {
  2824. CmdArgs.push_back("-analyzer-disable-checker=unix.API");
  2825. CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
  2826. }
  2827. if (Triple.isOSDarwin()) {
  2828. CmdArgs.push_back("-analyzer-checker=osx");
  2829. CmdArgs.push_back(
  2830. "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
  2831. }
  2832. else if (Triple.isOSFuchsia())
  2833. CmdArgs.push_back("-analyzer-checker=fuchsia");
  2834. CmdArgs.push_back("-analyzer-checker=deadcode");
  2835. if (types::isCXX(Input.getType()))
  2836. CmdArgs.push_back("-analyzer-checker=cplusplus");
  2837. if (!Triple.isPS()) {
  2838. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
  2839. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  2840. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  2841. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  2842. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  2843. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  2844. }
  2845. // Default nullability checks.
  2846. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  2847. CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
  2848. }
  2849. // Set the output format. The default is plist, for (lame) historical reasons.
  2850. CmdArgs.push_back("-analyzer-output");
  2851. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  2852. CmdArgs.push_back(A->getValue());
  2853. else
  2854. CmdArgs.push_back("plist");
  2855. // Disable the presentation of standard compiler warnings when using
  2856. // --analyze. We only want to show static analyzer diagnostics or frontend
  2857. // errors.
  2858. CmdArgs.push_back("-w");
  2859. // Add -Xanalyzer arguments when running as analyzer.
  2860. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  2861. }
  2862. static bool isValidSymbolName(StringRef S) {
  2863. if (S.empty())
  2864. return false;
  2865. if (std::isdigit(S[0]))
  2866. return false;
  2867. return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
  2868. }
  2869. static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
  2870. const ArgList &Args, ArgStringList &CmdArgs,
  2871. bool KernelOrKext) {
  2872. const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
  2873. // NVPTX doesn't support stack protectors; from the compiler's perspective, it
  2874. // doesn't even have a stack!
  2875. if (EffectiveTriple.isNVPTX())
  2876. return;
  2877. // -stack-protector=0 is default.
  2878. LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
  2879. LangOptions::StackProtectorMode DefaultStackProtectorLevel =
  2880. TC.GetDefaultStackProtectorLevel(KernelOrKext);
  2881. if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  2882. options::OPT_fstack_protector_all,
  2883. options::OPT_fstack_protector_strong,
  2884. options::OPT_fstack_protector)) {
  2885. if (A->getOption().matches(options::OPT_fstack_protector))
  2886. StackProtectorLevel =
  2887. std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
  2888. else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  2889. StackProtectorLevel = LangOptions::SSPStrong;
  2890. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  2891. StackProtectorLevel = LangOptions::SSPReq;
  2892. if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
  2893. D.Diag(diag::warn_drv_unsupported_option_for_target)
  2894. << A->getSpelling() << EffectiveTriple.getTriple();
  2895. StackProtectorLevel = DefaultStackProtectorLevel;
  2896. }
  2897. } else {
  2898. StackProtectorLevel = DefaultStackProtectorLevel;
  2899. }
  2900. if (StackProtectorLevel) {
  2901. CmdArgs.push_back("-stack-protector");
  2902. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  2903. }
  2904. // --param ssp-buffer-size=
  2905. for (const Arg *A : Args.filtered(options::OPT__param)) {
  2906. StringRef Str(A->getValue());
  2907. if (Str.startswith("ssp-buffer-size=")) {
  2908. if (StackProtectorLevel) {
  2909. CmdArgs.push_back("-stack-protector-buffer-size");
  2910. // FIXME: Verify the argument is a valid integer.
  2911. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  2912. }
  2913. A->claim();
  2914. }
  2915. }
  2916. const std::string &TripleStr = EffectiveTriple.getTriple();
  2917. if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
  2918. StringRef Value = A->getValue();
  2919. if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
  2920. !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
  2921. D.Diag(diag::err_drv_unsupported_opt_for_target)
  2922. << A->getAsString(Args) << TripleStr;
  2923. if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
  2924. EffectiveTriple.isThumb()) &&
  2925. Value != "tls" && Value != "global") {
  2926. D.Diag(diag::err_drv_invalid_value_with_suggestion)
  2927. << A->getOption().getName() << Value << "tls global";
  2928. return;
  2929. }
  2930. if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
  2931. Value == "tls") {
  2932. if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
  2933. D.Diag(diag::err_drv_ssp_missing_offset_argument)
  2934. << A->getAsString(Args);
  2935. return;
  2936. }
  2937. // Check whether the target subarch supports the hardware TLS register
  2938. if (!arm::isHardTPSupported(EffectiveTriple)) {
  2939. D.Diag(diag::err_target_unsupported_tp_hard)
  2940. << EffectiveTriple.getArchName();
  2941. return;
  2942. }
  2943. // Check whether the user asked for something other than -mtp=cp15
  2944. if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
  2945. StringRef Value = A->getValue();
  2946. if (Value != "cp15") {
  2947. D.Diag(diag::err_drv_argument_not_allowed_with)
  2948. << A->getAsString(Args) << "-mstack-protector-guard=tls";
  2949. return;
  2950. }
  2951. }
  2952. CmdArgs.push_back("-target-feature");
  2953. CmdArgs.push_back("+read-tp-hard");
  2954. }
  2955. if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
  2956. D.Diag(diag::err_drv_invalid_value_with_suggestion)
  2957. << A->getOption().getName() << Value << "sysreg global";
  2958. return;
  2959. }
  2960. A->render(Args, CmdArgs);
  2961. }
  2962. if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
  2963. StringRef Value = A->getValue();
  2964. if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
  2965. !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
  2966. D.Diag(diag::err_drv_unsupported_opt_for_target)
  2967. << A->getAsString(Args) << TripleStr;
  2968. int Offset;
  2969. if (Value.getAsInteger(10, Offset)) {
  2970. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
  2971. return;
  2972. }
  2973. if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
  2974. (Offset < 0 || Offset > 0xfffff)) {
  2975. D.Diag(diag::err_drv_invalid_int_value)
  2976. << A->getOption().getName() << Value;
  2977. return;
  2978. }
  2979. A->render(Args, CmdArgs);
  2980. }
  2981. if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
  2982. StringRef Value = A->getValue();
  2983. if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
  2984. D.Diag(diag::err_drv_unsupported_opt_for_target)
  2985. << A->getAsString(Args) << TripleStr;
  2986. if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
  2987. D.Diag(diag::err_drv_invalid_value_with_suggestion)
  2988. << A->getOption().getName() << Value << "fs gs";
  2989. return;
  2990. }
  2991. if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
  2992. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
  2993. return;
  2994. }
  2995. A->render(Args, CmdArgs);
  2996. }
  2997. if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
  2998. StringRef Value = A->getValue();
  2999. if (!isValidSymbolName(Value)) {
  3000. D.Diag(diag::err_drv_argument_only_allowed_with)
  3001. << A->getOption().getName() << "legal symbol name";
  3002. return;
  3003. }
  3004. A->render(Args, CmdArgs);
  3005. }
  3006. }
  3007. static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
  3008. ArgStringList &CmdArgs) {
  3009. const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
  3010. if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
  3011. return;
  3012. if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
  3013. !EffectiveTriple.isPPC64())
  3014. return;
  3015. Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
  3016. options::OPT_fno_stack_clash_protection);
  3017. }
  3018. static void RenderTrivialAutoVarInitOptions(const Driver &D,
  3019. const ToolChain &TC,
  3020. const ArgList &Args,
  3021. ArgStringList &CmdArgs) {
  3022. auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
  3023. StringRef TrivialAutoVarInit = "";
  3024. for (const Arg *A : Args) {
  3025. switch (A->getOption().getID()) {
  3026. default:
  3027. continue;
  3028. case options::OPT_ftrivial_auto_var_init: {
  3029. A->claim();
  3030. StringRef Val = A->getValue();
  3031. if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
  3032. TrivialAutoVarInit = Val;
  3033. else
  3034. D.Diag(diag::err_drv_unsupported_option_argument)
  3035. << A->getSpelling() << Val;
  3036. break;
  3037. }
  3038. }
  3039. }
  3040. if (TrivialAutoVarInit.empty())
  3041. switch (DefaultTrivialAutoVarInit) {
  3042. case LangOptions::TrivialAutoVarInitKind::Uninitialized:
  3043. break;
  3044. case LangOptions::TrivialAutoVarInitKind::Pattern:
  3045. TrivialAutoVarInit = "pattern";
  3046. break;
  3047. case LangOptions::TrivialAutoVarInitKind::Zero:
  3048. TrivialAutoVarInit = "zero";
  3049. break;
  3050. }
  3051. if (!TrivialAutoVarInit.empty()) {
  3052. CmdArgs.push_back(
  3053. Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
  3054. }
  3055. if (Arg *A =
  3056. Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
  3057. if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
  3058. StringRef(
  3059. Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
  3060. "uninitialized")
  3061. D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
  3062. A->claim();
  3063. StringRef Val = A->getValue();
  3064. if (std::stoi(Val.str()) <= 0)
  3065. D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
  3066. CmdArgs.push_back(
  3067. Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
  3068. }
  3069. }
  3070. static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
  3071. types::ID InputType) {
  3072. // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
  3073. // for denormal flushing handling based on the target.
  3074. const unsigned ForwardedArguments[] = {
  3075. options::OPT_cl_opt_disable,
  3076. options::OPT_cl_strict_aliasing,
  3077. options::OPT_cl_single_precision_constant,
  3078. options::OPT_cl_finite_math_only,
  3079. options::OPT_cl_kernel_arg_info,
  3080. options::OPT_cl_unsafe_math_optimizations,
  3081. options::OPT_cl_fast_relaxed_math,
  3082. options::OPT_cl_mad_enable,
  3083. options::OPT_cl_no_signed_zeros,
  3084. options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
  3085. options::OPT_cl_uniform_work_group_size
  3086. };
  3087. if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
  3088. std::string CLStdStr = std::string("-cl-std=") + A->getValue();
  3089. CmdArgs.push_back(Args.MakeArgString(CLStdStr));
  3090. } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
  3091. std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
  3092. CmdArgs.push_back(Args.MakeArgString(CLExtStr));
  3093. }
  3094. for (const auto &Arg : ForwardedArguments)
  3095. if (const auto *A = Args.getLastArg(Arg))
  3096. CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
  3097. // Only add the default headers if we are compiling OpenCL sources.
  3098. if ((types::isOpenCL(InputType) ||
  3099. (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
  3100. !Args.hasArg(options::OPT_cl_no_stdinc)) {
  3101. CmdArgs.push_back("-finclude-default-header");
  3102. CmdArgs.push_back("-fdeclare-opencl-builtins");
  3103. }
  3104. }
  3105. static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
  3106. types::ID InputType) {
  3107. const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
  3108. options::OPT_D,
  3109. options::OPT_I,
  3110. options::OPT_S,
  3111. options::OPT_O,
  3112. options::OPT_emit_llvm,
  3113. options::OPT_emit_obj,
  3114. options::OPT_disable_llvm_passes,
  3115. options::OPT_fnative_half_type,
  3116. options::OPT_hlsl_entrypoint};
  3117. if (!types::isHLSL(InputType))
  3118. return;
  3119. for (const auto &Arg : ForwardedArguments)
  3120. if (const auto *A = Args.getLastArg(Arg))
  3121. A->renderAsInput(Args, CmdArgs);
  3122. // Add the default headers if dxc_no_stdinc is not set.
  3123. if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
  3124. !Args.hasArg(options::OPT_nostdinc))
  3125. CmdArgs.push_back("-finclude-default-header");
  3126. }
  3127. static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
  3128. ArgStringList &CmdArgs) {
  3129. bool ARCMTEnabled = false;
  3130. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  3131. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  3132. options::OPT_ccc_arcmt_modify,
  3133. options::OPT_ccc_arcmt_migrate)) {
  3134. ARCMTEnabled = true;
  3135. switch (A->getOption().getID()) {
  3136. default: llvm_unreachable("missed a case");
  3137. case options::OPT_ccc_arcmt_check:
  3138. CmdArgs.push_back("-arcmt-action=check");
  3139. break;
  3140. case options::OPT_ccc_arcmt_modify:
  3141. CmdArgs.push_back("-arcmt-action=modify");
  3142. break;
  3143. case options::OPT_ccc_arcmt_migrate:
  3144. CmdArgs.push_back("-arcmt-action=migrate");
  3145. CmdArgs.push_back("-mt-migrate-directory");
  3146. CmdArgs.push_back(A->getValue());
  3147. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  3148. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  3149. break;
  3150. }
  3151. }
  3152. } else {
  3153. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  3154. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  3155. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  3156. }
  3157. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  3158. if (ARCMTEnabled)
  3159. D.Diag(diag::err_drv_argument_not_allowed_with)
  3160. << A->getAsString(Args) << "-ccc-arcmt-migrate";
  3161. CmdArgs.push_back("-mt-migrate-directory");
  3162. CmdArgs.push_back(A->getValue());
  3163. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  3164. options::OPT_objcmt_migrate_subscripting,
  3165. options::OPT_objcmt_migrate_property)) {
  3166. // None specified, means enable them all.
  3167. CmdArgs.push_back("-objcmt-migrate-literals");
  3168. CmdArgs.push_back("-objcmt-migrate-subscripting");
  3169. CmdArgs.push_back("-objcmt-migrate-property");
  3170. } else {
  3171. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3172. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3173. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3174. }
  3175. } else {
  3176. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3177. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3178. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3179. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  3180. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  3181. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  3182. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  3183. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  3184. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  3185. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  3186. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  3187. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  3188. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  3189. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  3190. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  3191. Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
  3192. }
  3193. }
  3194. static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
  3195. const ArgList &Args, ArgStringList &CmdArgs) {
  3196. // -fbuiltin is default unless -mkernel is used.
  3197. bool UseBuiltins =
  3198. Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  3199. !Args.hasArg(options::OPT_mkernel));
  3200. if (!UseBuiltins)
  3201. CmdArgs.push_back("-fno-builtin");
  3202. // -ffreestanding implies -fno-builtin.
  3203. if (Args.hasArg(options::OPT_ffreestanding))
  3204. UseBuiltins = false;
  3205. // Process the -fno-builtin-* options.
  3206. for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
  3207. A->claim();
  3208. // If -fno-builtin is specified, then there's no need to pass the option to
  3209. // the frontend.
  3210. if (UseBuiltins)
  3211. A->render(Args, CmdArgs);
  3212. }
  3213. // le32-specific flags:
  3214. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  3215. // by default.
  3216. if (TC.getArch() == llvm::Triple::le32)
  3217. CmdArgs.push_back("-fno-math-builtin");
  3218. }
  3219. bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
  3220. if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
  3221. Twine Path{Str};
  3222. Path.toVector(Result);
  3223. return Path.getSingleStringRef() != "";
  3224. }
  3225. if (llvm::sys::path::cache_directory(Result)) {
  3226. llvm::sys::path::append(Result, "clang");
  3227. llvm::sys::path::append(Result, "ModuleCache");
  3228. return true;
  3229. }
  3230. return false;
  3231. }
  3232. static bool RenderModulesOptions(Compilation &C, const Driver &D,
  3233. const ArgList &Args, const InputInfo &Input,
  3234. const InputInfo &Output, const Arg *Std,
  3235. ArgStringList &CmdArgs) {
  3236. bool IsCXX = types::isCXX(Input.getType());
  3237. // FIXME: Find a better way to determine whether the input has standard c++
  3238. // modules support by default.
  3239. bool HaveStdCXXModules =
  3240. IsCXX && Std &&
  3241. (Std->containsValue("c++2a") || Std->containsValue("c++20") ||
  3242. Std->containsValue("c++2b") || Std->containsValue("c++latest"));
  3243. bool HaveModules = HaveStdCXXModules;
  3244. // -fmodules enables the use of precompiled modules (off by default).
  3245. // Users can pass -fno-cxx-modules to turn off modules support for
  3246. // C++/Objective-C++ programs.
  3247. bool HaveClangModules = false;
  3248. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  3249. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  3250. options::OPT_fno_cxx_modules, true);
  3251. if (AllowedInCXX || !IsCXX) {
  3252. CmdArgs.push_back("-fmodules");
  3253. HaveClangModules = true;
  3254. }
  3255. }
  3256. HaveModules |= HaveClangModules;
  3257. if (Args.hasArg(options::OPT_fmodules_ts)) {
  3258. D.Diag(diag::warn_deprecated_fmodules_ts_flag);
  3259. CmdArgs.push_back("-fmodules-ts");
  3260. HaveModules = true;
  3261. }
  3262. // -fmodule-maps enables implicit reading of module map files. By default,
  3263. // this is enabled if we are using Clang's flavor of precompiled modules.
  3264. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  3265. options::OPT_fno_implicit_module_maps, HaveClangModules))
  3266. CmdArgs.push_back("-fimplicit-module-maps");
  3267. // -fmodules-decluse checks that modules used are declared so (off by default)
  3268. Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
  3269. options::OPT_fno_modules_decluse);
  3270. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  3271. // all #included headers are part of modules.
  3272. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  3273. options::OPT_fno_modules_strict_decluse, false))
  3274. CmdArgs.push_back("-fmodules-strict-decluse");
  3275. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  3276. bool ImplicitModules = false;
  3277. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  3278. options::OPT_fno_implicit_modules, HaveClangModules)) {
  3279. if (HaveModules)
  3280. CmdArgs.push_back("-fno-implicit-modules");
  3281. } else if (HaveModules) {
  3282. ImplicitModules = true;
  3283. // -fmodule-cache-path specifies where our implicitly-built module files
  3284. // should be written.
  3285. SmallString<128> Path;
  3286. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  3287. Path = A->getValue();
  3288. bool HasPath = true;
  3289. if (C.isForDiagnostics()) {
  3290. // When generating crash reports, we want to emit the modules along with
  3291. // the reproduction sources, so we ignore any provided module path.
  3292. Path = Output.getFilename();
  3293. llvm::sys::path::replace_extension(Path, ".cache");
  3294. llvm::sys::path::append(Path, "modules");
  3295. } else if (Path.empty()) {
  3296. // No module path was provided: use the default.
  3297. HasPath = Driver::getDefaultModuleCachePath(Path);
  3298. }
  3299. // `HasPath` will only be false if getDefaultModuleCachePath() fails.
  3300. // That being said, that failure is unlikely and not caching is harmless.
  3301. if (HasPath) {
  3302. const char Arg[] = "-fmodules-cache-path=";
  3303. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  3304. CmdArgs.push_back(Args.MakeArgString(Path));
  3305. }
  3306. }
  3307. if (HaveModules) {
  3308. // -fprebuilt-module-path specifies where to load the prebuilt module files.
  3309. for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
  3310. CmdArgs.push_back(Args.MakeArgString(
  3311. std::string("-fprebuilt-module-path=") + A->getValue()));
  3312. A->claim();
  3313. }
  3314. if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
  3315. options::OPT_fno_prebuilt_implicit_modules, false))
  3316. CmdArgs.push_back("-fprebuilt-implicit-modules");
  3317. if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
  3318. options::OPT_fno_modules_validate_input_files_content,
  3319. false))
  3320. CmdArgs.push_back("-fvalidate-ast-input-files-content");
  3321. }
  3322. // -fmodule-name specifies the module that is currently being built (or
  3323. // used for header checking by -fmodule-maps).
  3324. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
  3325. // -fmodule-map-file can be used to specify files containing module
  3326. // definitions.
  3327. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  3328. // -fbuiltin-module-map can be used to load the clang
  3329. // builtin headers modulemap file.
  3330. if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
  3331. SmallString<128> BuiltinModuleMap(D.ResourceDir);
  3332. llvm::sys::path::append(BuiltinModuleMap, "include");
  3333. llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
  3334. if (llvm::sys::fs::exists(BuiltinModuleMap))
  3335. CmdArgs.push_back(
  3336. Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
  3337. }
  3338. // The -fmodule-file=<name>=<file> form specifies the mapping of module
  3339. // names to precompiled module files (the module is loaded only if used).
  3340. // The -fmodule-file=<file> form can be used to unconditionally load
  3341. // precompiled module files (whether used or not).
  3342. if (HaveModules)
  3343. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  3344. else
  3345. Args.ClaimAllArgs(options::OPT_fmodule_file);
  3346. // When building modules and generating crashdumps, we need to dump a module
  3347. // dependency VFS alongside the output.
  3348. if (HaveClangModules && C.isForDiagnostics()) {
  3349. SmallString<128> VFSDir(Output.getFilename());
  3350. llvm::sys::path::replace_extension(VFSDir, ".cache");
  3351. // Add the cache directory as a temp so the crash diagnostics pick it up.
  3352. C.addTempFile(Args.MakeArgString(VFSDir));
  3353. llvm::sys::path::append(VFSDir, "vfs");
  3354. CmdArgs.push_back("-module-dependency-dir");
  3355. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  3356. }
  3357. if (HaveClangModules)
  3358. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  3359. // Pass through all -fmodules-ignore-macro arguments.
  3360. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  3361. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  3362. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  3363. if (HaveClangModules) {
  3364. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  3365. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  3366. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  3367. D.Diag(diag::err_drv_argument_not_allowed_with)
  3368. << A->getAsString(Args) << "-fbuild-session-timestamp";
  3369. llvm::sys::fs::file_status Status;
  3370. if (llvm::sys::fs::status(A->getValue(), Status))
  3371. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  3372. CmdArgs.push_back(Args.MakeArgString(
  3373. "-fbuild-session-timestamp=" +
  3374. Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
  3375. Status.getLastModificationTime().time_since_epoch())
  3376. .count())));
  3377. }
  3378. if (Args.getLastArg(
  3379. options::OPT_fmodules_validate_once_per_build_session)) {
  3380. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  3381. options::OPT_fbuild_session_file))
  3382. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  3383. Args.AddLastArg(CmdArgs,
  3384. options::OPT_fmodules_validate_once_per_build_session);
  3385. }
  3386. if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
  3387. options::OPT_fno_modules_validate_system_headers,
  3388. ImplicitModules))
  3389. CmdArgs.push_back("-fmodules-validate-system-headers");
  3390. Args.AddLastArg(CmdArgs,
  3391. options::OPT_fmodules_disable_diagnostic_validation);
  3392. } else {
  3393. Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
  3394. Args.ClaimAllArgs(options::OPT_fbuild_session_file);
  3395. Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
  3396. Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
  3397. Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
  3398. Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
  3399. }
  3400. // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
  3401. Args.ClaimAllArgs(options::OPT_fmodule_output);
  3402. Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
  3403. return HaveModules;
  3404. }
  3405. static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
  3406. ArgStringList &CmdArgs) {
  3407. // -fsigned-char is default.
  3408. if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
  3409. options::OPT_fno_signed_char,
  3410. options::OPT_funsigned_char,
  3411. options::OPT_fno_unsigned_char)) {
  3412. if (A->getOption().matches(options::OPT_funsigned_char) ||
  3413. A->getOption().matches(options::OPT_fno_signed_char)) {
  3414. CmdArgs.push_back("-fno-signed-char");
  3415. }
  3416. } else if (!isSignedCharDefault(T)) {
  3417. CmdArgs.push_back("-fno-signed-char");
  3418. }
  3419. // The default depends on the language standard.
  3420. Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
  3421. if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  3422. options::OPT_fno_short_wchar)) {
  3423. if (A->getOption().matches(options::OPT_fshort_wchar)) {
  3424. CmdArgs.push_back("-fwchar-type=short");
  3425. CmdArgs.push_back("-fno-signed-wchar");
  3426. } else {
  3427. bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
  3428. CmdArgs.push_back("-fwchar-type=int");
  3429. if (T.isOSzOS() ||
  3430. (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
  3431. CmdArgs.push_back("-fno-signed-wchar");
  3432. else
  3433. CmdArgs.push_back("-fsigned-wchar");
  3434. }
  3435. }
  3436. }
  3437. static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
  3438. const llvm::Triple &T, const ArgList &Args,
  3439. ObjCRuntime &Runtime, bool InferCovariantReturns,
  3440. const InputInfo &Input, ArgStringList &CmdArgs) {
  3441. const llvm::Triple::ArchType Arch = TC.getArch();
  3442. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
  3443. // is the default. Except for deployment target of 10.5, next runtime is
  3444. // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
  3445. if (Runtime.isNonFragile()) {
  3446. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  3447. options::OPT_fno_objc_legacy_dispatch,
  3448. Runtime.isLegacyDispatchDefaultForArch(Arch))) {
  3449. if (TC.UseObjCMixedDispatch())
  3450. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  3451. else
  3452. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  3453. }
  3454. }
  3455. // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
  3456. // to do Array/Dictionary subscripting by default.
  3457. if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
  3458. Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
  3459. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  3460. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  3461. // NOTE: This logic is duplicated in ToolChains.cpp.
  3462. if (isObjCAutoRefCount(Args)) {
  3463. TC.CheckObjCARC();
  3464. CmdArgs.push_back("-fobjc-arc");
  3465. // FIXME: It seems like this entire block, and several around it should be
  3466. // wrapped in isObjC, but for now we just use it here as this is where it
  3467. // was being used previously.
  3468. if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
  3469. if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  3470. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  3471. else
  3472. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  3473. }
  3474. // Allow the user to enable full exceptions code emission.
  3475. // We default off for Objective-C, on for Objective-C++.
  3476. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  3477. options::OPT_fno_objc_arc_exceptions,
  3478. /*Default=*/types::isCXX(Input.getType())))
  3479. CmdArgs.push_back("-fobjc-arc-exceptions");
  3480. }
  3481. // Silence warning for full exception code emission options when explicitly
  3482. // set to use no ARC.
  3483. if (Args.hasArg(options::OPT_fno_objc_arc)) {
  3484. Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
  3485. Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
  3486. }
  3487. // Allow the user to control whether messages can be converted to runtime
  3488. // functions.
  3489. if (types::isObjC(Input.getType())) {
  3490. auto *Arg = Args.getLastArg(
  3491. options::OPT_fobjc_convert_messages_to_runtime_calls,
  3492. options::OPT_fno_objc_convert_messages_to_runtime_calls);
  3493. if (Arg &&
  3494. Arg->getOption().matches(
  3495. options::OPT_fno_objc_convert_messages_to_runtime_calls))
  3496. CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
  3497. }
  3498. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  3499. // rewriter.
  3500. if (InferCovariantReturns)
  3501. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  3502. // Pass down -fobjc-weak or -fno-objc-weak if present.
  3503. if (types::isObjC(Input.getType())) {
  3504. auto WeakArg =
  3505. Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
  3506. if (!WeakArg) {
  3507. // nothing to do
  3508. } else if (!Runtime.allowsWeak()) {
  3509. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  3510. D.Diag(diag::err_objc_weak_unsupported);
  3511. } else {
  3512. WeakArg->render(Args, CmdArgs);
  3513. }
  3514. }
  3515. if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
  3516. CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
  3517. }
  3518. static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
  3519. ArgStringList &CmdArgs) {
  3520. bool CaretDefault = true;
  3521. bool ColumnDefault = true;
  3522. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
  3523. options::OPT__SLASH_diagnostics_column,
  3524. options::OPT__SLASH_diagnostics_caret)) {
  3525. switch (A->getOption().getID()) {
  3526. case options::OPT__SLASH_diagnostics_caret:
  3527. CaretDefault = true;
  3528. ColumnDefault = true;
  3529. break;
  3530. case options::OPT__SLASH_diagnostics_column:
  3531. CaretDefault = false;
  3532. ColumnDefault = true;
  3533. break;
  3534. case options::OPT__SLASH_diagnostics_classic:
  3535. CaretDefault = false;
  3536. ColumnDefault = false;
  3537. break;
  3538. }
  3539. }
  3540. // -fcaret-diagnostics is default.
  3541. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  3542. options::OPT_fno_caret_diagnostics, CaretDefault))
  3543. CmdArgs.push_back("-fno-caret-diagnostics");
  3544. Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
  3545. options::OPT_fno_diagnostics_fixit_info);
  3546. Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
  3547. options::OPT_fno_diagnostics_show_option);
  3548. if (const Arg *A =
  3549. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  3550. CmdArgs.push_back("-fdiagnostics-show-category");
  3551. CmdArgs.push_back(A->getValue());
  3552. }
  3553. Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
  3554. options::OPT_fno_diagnostics_show_hotness);
  3555. if (const Arg *A =
  3556. Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
  3557. std::string Opt =
  3558. std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
  3559. CmdArgs.push_back(Args.MakeArgString(Opt));
  3560. }
  3561. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  3562. CmdArgs.push_back("-fdiagnostics-format");
  3563. CmdArgs.push_back(A->getValue());
  3564. if (StringRef(A->getValue()) == "sarif" ||
  3565. StringRef(A->getValue()) == "SARIF")
  3566. D.Diag(diag::warn_drv_sarif_format_unstable);
  3567. }
  3568. if (const Arg *A = Args.getLastArg(
  3569. options::OPT_fdiagnostics_show_note_include_stack,
  3570. options::OPT_fno_diagnostics_show_note_include_stack)) {
  3571. const Option &O = A->getOption();
  3572. if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
  3573. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  3574. else
  3575. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  3576. }
  3577. // Color diagnostics are parsed by the driver directly from argv and later
  3578. // re-parsed to construct this job; claim any possible color diagnostic here
  3579. // to avoid warn_drv_unused_argument and diagnose bad
  3580. // OPT_fdiagnostics_color_EQ values.
  3581. Args.getLastArg(options::OPT_fcolor_diagnostics,
  3582. options::OPT_fno_color_diagnostics);
  3583. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
  3584. StringRef Value(A->getValue());
  3585. if (Value != "always" && Value != "never" && Value != "auto")
  3586. D.Diag(diag::err_drv_invalid_argument_to_option)
  3587. << Value << A->getOption().getName();
  3588. }
  3589. if (D.getDiags().getDiagnosticOptions().ShowColors)
  3590. CmdArgs.push_back("-fcolor-diagnostics");
  3591. if (Args.hasArg(options::OPT_fansi_escape_codes))
  3592. CmdArgs.push_back("-fansi-escape-codes");
  3593. Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
  3594. options::OPT_fno_show_source_location);
  3595. if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
  3596. CmdArgs.push_back("-fdiagnostics-absolute-paths");
  3597. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  3598. ColumnDefault))
  3599. CmdArgs.push_back("-fno-show-column");
  3600. Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
  3601. options::OPT_fno_spell_checking);
  3602. }
  3603. DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
  3604. const ArgList &Args, Arg *&Arg) {
  3605. Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
  3606. options::OPT_gno_split_dwarf);
  3607. if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
  3608. return DwarfFissionKind::None;
  3609. if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
  3610. return DwarfFissionKind::Split;
  3611. StringRef Value = Arg->getValue();
  3612. if (Value == "split")
  3613. return DwarfFissionKind::Split;
  3614. if (Value == "single")
  3615. return DwarfFissionKind::Single;
  3616. D.Diag(diag::err_drv_unsupported_option_argument)
  3617. << Arg->getSpelling() << Arg->getValue();
  3618. return DwarfFissionKind::None;
  3619. }
  3620. static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
  3621. const ArgList &Args, ArgStringList &CmdArgs,
  3622. unsigned DwarfVersion) {
  3623. auto *DwarfFormatArg =
  3624. Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
  3625. if (!DwarfFormatArg)
  3626. return;
  3627. if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
  3628. if (DwarfVersion < 3)
  3629. D.Diag(diag::err_drv_argument_only_allowed_with)
  3630. << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
  3631. else if (!T.isArch64Bit())
  3632. D.Diag(diag::err_drv_argument_only_allowed_with)
  3633. << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
  3634. else if (!T.isOSBinFormatELF())
  3635. D.Diag(diag::err_drv_argument_only_allowed_with)
  3636. << DwarfFormatArg->getAsString(Args) << "ELF platforms";
  3637. }
  3638. DwarfFormatArg->render(Args, CmdArgs);
  3639. }
  3640. static void renderDebugOptions(const ToolChain &TC, const Driver &D,
  3641. const llvm::Triple &T, const ArgList &Args,
  3642. bool EmitCodeView, bool IRInput,
  3643. ArgStringList &CmdArgs,
  3644. codegenoptions::DebugInfoKind &DebugInfoKind,
  3645. DwarfFissionKind &DwarfFission) {
  3646. if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
  3647. options::OPT_fno_debug_info_for_profiling, false) &&
  3648. checkDebugInfoOption(
  3649. Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
  3650. CmdArgs.push_back("-fdebug-info-for-profiling");
  3651. // The 'g' groups options involve a somewhat intricate sequence of decisions
  3652. // about what to pass from the driver to the frontend, but by the time they
  3653. // reach cc1 they've been factored into three well-defined orthogonal choices:
  3654. // * what level of debug info to generate
  3655. // * what dwarf version to write
  3656. // * what debugger tuning to use
  3657. // This avoids having to monkey around further in cc1 other than to disable
  3658. // codeview if not running in a Windows environment. Perhaps even that
  3659. // decision should be made in the driver as well though.
  3660. llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
  3661. bool SplitDWARFInlining =
  3662. Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
  3663. options::OPT_fno_split_dwarf_inlining, false);
  3664. // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
  3665. // object file generation and no IR generation, -gN should not be needed. So
  3666. // allow -gsplit-dwarf with either -gN or IR input.
  3667. if (IRInput || Args.hasArg(options::OPT_g_Group)) {
  3668. Arg *SplitDWARFArg;
  3669. DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
  3670. if (DwarfFission != DwarfFissionKind::None &&
  3671. !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
  3672. DwarfFission = DwarfFissionKind::None;
  3673. SplitDWARFInlining = false;
  3674. }
  3675. }
  3676. if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  3677. DebugInfoKind = codegenoptions::DebugInfoConstructor;
  3678. // If the last option explicitly specified a debug-info level, use it.
  3679. if (checkDebugInfoOption(A, Args, D, TC) &&
  3680. A->getOption().matches(options::OPT_gN_Group)) {
  3681. DebugInfoKind = DebugLevelToInfoKind(*A);
  3682. // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
  3683. // complicated if you've disabled inline info in the skeleton CUs
  3684. // (SplitDWARFInlining) - then there's value in composing split-dwarf and
  3685. // line-tables-only, so let those compose naturally in that case.
  3686. if (DebugInfoKind == codegenoptions::NoDebugInfo ||
  3687. DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
  3688. (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
  3689. SplitDWARFInlining))
  3690. DwarfFission = DwarfFissionKind::None;
  3691. }
  3692. }
  3693. // If a debugger tuning argument appeared, remember it.
  3694. bool HasDebuggerTuning = false;
  3695. if (const Arg *A =
  3696. Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
  3697. HasDebuggerTuning = true;
  3698. if (checkDebugInfoOption(A, Args, D, TC)) {
  3699. if (A->getOption().matches(options::OPT_glldb))
  3700. DebuggerTuning = llvm::DebuggerKind::LLDB;
  3701. else if (A->getOption().matches(options::OPT_gsce))
  3702. DebuggerTuning = llvm::DebuggerKind::SCE;
  3703. else if (A->getOption().matches(options::OPT_gdbx))
  3704. DebuggerTuning = llvm::DebuggerKind::DBX;
  3705. else
  3706. DebuggerTuning = llvm::DebuggerKind::GDB;
  3707. }
  3708. }
  3709. // If a -gdwarf argument appeared, remember it.
  3710. bool EmitDwarf = false;
  3711. if (const Arg *A = getDwarfNArg(Args))
  3712. EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
  3713. if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
  3714. EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
  3715. // If the user asked for debug info but did not explicitly specify -gcodeview
  3716. // or -gdwarf, ask the toolchain for the default format.
  3717. if (!EmitCodeView && !EmitDwarf &&
  3718. DebugInfoKind != codegenoptions::NoDebugInfo) {
  3719. switch (TC.getDefaultDebugFormat()) {
  3720. case codegenoptions::DIF_CodeView:
  3721. EmitCodeView = true;
  3722. break;
  3723. case codegenoptions::DIF_DWARF:
  3724. EmitDwarf = true;
  3725. break;
  3726. }
  3727. }
  3728. unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
  3729. unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
  3730. // be lower than what the user wanted.
  3731. if (EmitDwarf) {
  3732. RequestedDWARFVersion = getDwarfVersion(TC, Args);
  3733. // Clamp effective DWARF version to the max supported by the toolchain.
  3734. EffectiveDWARFVersion =
  3735. std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
  3736. } else {
  3737. Args.ClaimAllArgs(options::OPT_fdebug_default_version);
  3738. }
  3739. // -gline-directives-only supported only for the DWARF debug info.
  3740. if (RequestedDWARFVersion == 0 &&
  3741. DebugInfoKind == codegenoptions::DebugDirectivesOnly)
  3742. DebugInfoKind = codegenoptions::NoDebugInfo;
  3743. // strict DWARF is set to false by default. But for DBX, we need it to be set
  3744. // as true by default.
  3745. if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
  3746. (void)checkDebugInfoOption(A, Args, D, TC);
  3747. if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
  3748. DebuggerTuning == llvm::DebuggerKind::DBX))
  3749. CmdArgs.push_back("-gstrict-dwarf");
  3750. // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
  3751. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  3752. // Column info is included by default for everything except SCE and
  3753. // CodeView. Clang doesn't track end columns, just starting columns, which,
  3754. // in theory, is fine for CodeView (and PDB). In practice, however, the
  3755. // Microsoft debuggers don't handle missing end columns well, and the AIX
  3756. // debugger DBX also doesn't handle the columns well, so it's better not to
  3757. // include any column info.
  3758. if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
  3759. (void)checkDebugInfoOption(A, Args, D, TC);
  3760. if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  3761. !EmitCodeView &&
  3762. (DebuggerTuning != llvm::DebuggerKind::SCE &&
  3763. DebuggerTuning != llvm::DebuggerKind::DBX)))
  3764. CmdArgs.push_back("-gno-column-info");
  3765. // FIXME: Move backend command line options to the module.
  3766. if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
  3767. // If -gline-tables-only or -gline-directives-only is the last option it
  3768. // wins.
  3769. if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
  3770. TC)) {
  3771. if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
  3772. DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
  3773. DebugInfoKind = codegenoptions::DebugInfoConstructor;
  3774. CmdArgs.push_back("-dwarf-ext-refs");
  3775. CmdArgs.push_back("-fmodule-format=obj");
  3776. }
  3777. }
  3778. }
  3779. if (T.isOSBinFormatELF() && SplitDWARFInlining)
  3780. CmdArgs.push_back("-fsplit-dwarf-inlining");
  3781. // After we've dealt with all combinations of things that could
  3782. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  3783. // figure out if we need to "upgrade" it to standalone debug info.
  3784. // We parse these two '-f' options whether or not they will be used,
  3785. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  3786. bool NeedFullDebug = Args.hasFlag(
  3787. options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
  3788. DebuggerTuning == llvm::DebuggerKind::LLDB ||
  3789. TC.GetDefaultStandaloneDebug());
  3790. if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
  3791. (void)checkDebugInfoOption(A, Args, D, TC);
  3792. if (DebugInfoKind == codegenoptions::LimitedDebugInfo ||
  3793. DebugInfoKind == codegenoptions::DebugInfoConstructor) {
  3794. if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
  3795. options::OPT_feliminate_unused_debug_types, false))
  3796. DebugInfoKind = codegenoptions::UnusedTypeInfo;
  3797. else if (NeedFullDebug)
  3798. DebugInfoKind = codegenoptions::FullDebugInfo;
  3799. }
  3800. if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
  3801. false)) {
  3802. // Source embedding is a vendor extension to DWARF v5. By now we have
  3803. // checked if a DWARF version was stated explicitly, and have otherwise
  3804. // fallen back to the target default, so if this is still not at least 5
  3805. // we emit an error.
  3806. const Arg *A = Args.getLastArg(options::OPT_gembed_source);
  3807. if (RequestedDWARFVersion < 5)
  3808. D.Diag(diag::err_drv_argument_only_allowed_with)
  3809. << A->getAsString(Args) << "-gdwarf-5";
  3810. else if (EffectiveDWARFVersion < 5)
  3811. // The toolchain has reduced allowed dwarf version, so we can't enable
  3812. // -gembed-source.
  3813. D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
  3814. << A->getAsString(Args) << TC.getTripleString() << 5
  3815. << EffectiveDWARFVersion;
  3816. else if (checkDebugInfoOption(A, Args, D, TC))
  3817. CmdArgs.push_back("-gembed-source");
  3818. }
  3819. if (EmitCodeView) {
  3820. CmdArgs.push_back("-gcodeview");
  3821. Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
  3822. options::OPT_gno_codeview_ghash);
  3823. Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
  3824. options::OPT_gno_codeview_command_line);
  3825. }
  3826. Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
  3827. options::OPT_gno_inline_line_tables);
  3828. // When emitting remarks, we need at least debug lines in the output.
  3829. if (willEmitRemarks(Args) &&
  3830. DebugInfoKind <= codegenoptions::DebugDirectivesOnly)
  3831. DebugInfoKind = codegenoptions::DebugLineTablesOnly;
  3832. // Adjust the debug info kind for the given toolchain.
  3833. TC.adjustDebugInfoKind(DebugInfoKind, Args);
  3834. // On AIX, the debugger tuning option can be omitted if it is not explicitly
  3835. // set.
  3836. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
  3837. T.isOSAIX() && !HasDebuggerTuning
  3838. ? llvm::DebuggerKind::Default
  3839. : DebuggerTuning);
  3840. // -fdebug-macro turns on macro debug info generation.
  3841. if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
  3842. false))
  3843. if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
  3844. D, TC))
  3845. CmdArgs.push_back("-debug-info-macro");
  3846. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  3847. const auto *PubnamesArg =
  3848. Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
  3849. options::OPT_gpubnames, options::OPT_gno_pubnames);
  3850. if (DwarfFission != DwarfFissionKind::None ||
  3851. (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
  3852. if (!PubnamesArg ||
  3853. (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
  3854. !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
  3855. CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
  3856. options::OPT_gpubnames)
  3857. ? "-gpubnames"
  3858. : "-ggnu-pubnames");
  3859. const auto *SimpleTemplateNamesArg =
  3860. Args.getLastArg(options::OPT_gsimple_template_names,
  3861. options::OPT_gno_simple_template_names);
  3862. bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
  3863. if (SimpleTemplateNamesArg &&
  3864. checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
  3865. const auto &Opt = SimpleTemplateNamesArg->getOption();
  3866. if (Opt.matches(options::OPT_gsimple_template_names)) {
  3867. ForwardTemplateParams = true;
  3868. CmdArgs.push_back("-gsimple-template-names=simple");
  3869. }
  3870. }
  3871. if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
  3872. StringRef v = A->getValue();
  3873. CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
  3874. }
  3875. Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
  3876. options::OPT_fno_debug_ranges_base_address);
  3877. // -gdwarf-aranges turns on the emission of the aranges section in the
  3878. // backend.
  3879. // Always enabled for SCE tuning.
  3880. bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
  3881. if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
  3882. NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
  3883. if (NeedAranges) {
  3884. CmdArgs.push_back("-mllvm");
  3885. CmdArgs.push_back("-generate-arange-section");
  3886. }
  3887. Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
  3888. options::OPT_fno_force_dwarf_frame);
  3889. if (Args.hasFlag(options::OPT_fdebug_types_section,
  3890. options::OPT_fno_debug_types_section, false)) {
  3891. if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
  3892. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3893. << Args.getLastArg(options::OPT_fdebug_types_section)
  3894. ->getAsString(Args)
  3895. << T.getTriple();
  3896. } else if (checkDebugInfoOption(
  3897. Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
  3898. TC)) {
  3899. CmdArgs.push_back("-mllvm");
  3900. CmdArgs.push_back("-generate-type-units");
  3901. }
  3902. }
  3903. // To avoid join/split of directory+filename, the integrated assembler prefers
  3904. // the directory form of .file on all DWARF versions. GNU as doesn't allow the
  3905. // form before DWARF v5.
  3906. if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
  3907. options::OPT_fno_dwarf_directory_asm,
  3908. TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
  3909. CmdArgs.push_back("-fno-dwarf-directory-asm");
  3910. // Decide how to render forward declarations of template instantiations.
  3911. // SCE wants full descriptions, others just get them in the name.
  3912. if (ForwardTemplateParams)
  3913. CmdArgs.push_back("-debug-forward-template-params");
  3914. // Do we need to explicitly import anonymous namespaces into the parent
  3915. // scope?
  3916. if (DebuggerTuning == llvm::DebuggerKind::SCE)
  3917. CmdArgs.push_back("-dwarf-explicit-import");
  3918. renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
  3919. RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
  3920. }
  3921. static void ProcessVSRuntimeLibrary(const ArgList &Args,
  3922. ArgStringList &CmdArgs) {
  3923. unsigned RTOptionID = options::OPT__SLASH_MT;
  3924. if (Args.hasArg(options::OPT__SLASH_LDd))
  3925. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  3926. // but defining _DEBUG is sticky.
  3927. RTOptionID = options::OPT__SLASH_MTd;
  3928. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  3929. RTOptionID = A->getOption().getID();
  3930. if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
  3931. RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
  3932. .Case("static", options::OPT__SLASH_MT)
  3933. .Case("static_dbg", options::OPT__SLASH_MTd)
  3934. .Case("dll", options::OPT__SLASH_MD)
  3935. .Case("dll_dbg", options::OPT__SLASH_MDd)
  3936. .Default(options::OPT__SLASH_MT);
  3937. }
  3938. StringRef FlagForCRT;
  3939. switch (RTOptionID) {
  3940. case options::OPT__SLASH_MD:
  3941. if (Args.hasArg(options::OPT__SLASH_LDd))
  3942. CmdArgs.push_back("-D_DEBUG");
  3943. CmdArgs.push_back("-D_MT");
  3944. CmdArgs.push_back("-D_DLL");
  3945. FlagForCRT = "--dependent-lib=msvcrt";
  3946. break;
  3947. case options::OPT__SLASH_MDd:
  3948. CmdArgs.push_back("-D_DEBUG");
  3949. CmdArgs.push_back("-D_MT");
  3950. CmdArgs.push_back("-D_DLL");
  3951. FlagForCRT = "--dependent-lib=msvcrtd";
  3952. break;
  3953. case options::OPT__SLASH_MT:
  3954. if (Args.hasArg(options::OPT__SLASH_LDd))
  3955. CmdArgs.push_back("-D_DEBUG");
  3956. CmdArgs.push_back("-D_MT");
  3957. CmdArgs.push_back("-flto-visibility-public-std");
  3958. FlagForCRT = "--dependent-lib=libcmt";
  3959. break;
  3960. case options::OPT__SLASH_MTd:
  3961. CmdArgs.push_back("-D_DEBUG");
  3962. CmdArgs.push_back("-D_MT");
  3963. CmdArgs.push_back("-flto-visibility-public-std");
  3964. FlagForCRT = "--dependent-lib=libcmtd";
  3965. break;
  3966. default:
  3967. llvm_unreachable("Unexpected option ID.");
  3968. }
  3969. if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
  3970. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  3971. } else {
  3972. CmdArgs.push_back(FlagForCRT.data());
  3973. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  3974. // users want. The /Za flag to cl.exe turns this off, but it's not
  3975. // implemented in clang.
  3976. CmdArgs.push_back("--dependent-lib=oldnames");
  3977. }
  3978. }
  3979. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  3980. const InputInfo &Output, const InputInfoList &Inputs,
  3981. const ArgList &Args, const char *LinkingOutput) const {
  3982. const auto &TC = getToolChain();
  3983. const llvm::Triple &RawTriple = TC.getTriple();
  3984. const llvm::Triple &Triple = TC.getEffectiveTriple();
  3985. const std::string &TripleStr = Triple.getTriple();
  3986. bool KernelOrKext =
  3987. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3988. const Driver &D = TC.getDriver();
  3989. ArgStringList CmdArgs;
  3990. assert(Inputs.size() >= 1 && "Must have at least one input.");
  3991. // CUDA/HIP compilation may have multiple inputs (source file + results of
  3992. // device-side compilations). OpenMP device jobs also take the host IR as a
  3993. // second input. Module precompilation accepts a list of header files to
  3994. // include as part of the module. API extraction accepts a list of header
  3995. // files whose API information is emitted in the output. All other jobs are
  3996. // expected to have exactly one input.
  3997. bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
  3998. bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
  3999. bool IsHIP = JA.isOffloading(Action::OFK_HIP);
  4000. bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
  4001. bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
  4002. bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
  4003. bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
  4004. JA.isDeviceOffloading(Action::OFK_Host));
  4005. bool IsHostOffloadingAction =
  4006. JA.isHostOffloading(Action::OFK_OpenMP) ||
  4007. (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
  4008. Args.hasFlag(options::OPT_offload_new_driver,
  4009. options::OPT_no_offload_new_driver, false));
  4010. bool IsRDCMode =
  4011. Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
  4012. bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
  4013. auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
  4014. // Extract API doesn't have a main input file, so invent a fake one as a
  4015. // placeholder.
  4016. InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
  4017. "extract-api");
  4018. const InputInfo &Input =
  4019. IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
  4020. InputInfoList ExtractAPIInputs;
  4021. InputInfoList HostOffloadingInputs;
  4022. const InputInfo *CudaDeviceInput = nullptr;
  4023. const InputInfo *OpenMPDeviceInput = nullptr;
  4024. for (const InputInfo &I : Inputs) {
  4025. if (&I == &Input || I.getType() == types::TY_Nothing) {
  4026. // This is the primary input or contains nothing.
  4027. } else if (IsExtractAPI) {
  4028. auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
  4029. if (I.getType() != ExpectedInputType) {
  4030. D.Diag(diag::err_drv_extract_api_wrong_kind)
  4031. << I.getFilename() << types::getTypeName(I.getType())
  4032. << types::getTypeName(ExpectedInputType);
  4033. }
  4034. ExtractAPIInputs.push_back(I);
  4035. } else if (IsHostOffloadingAction) {
  4036. HostOffloadingInputs.push_back(I);
  4037. } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
  4038. CudaDeviceInput = &I;
  4039. } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
  4040. OpenMPDeviceInput = &I;
  4041. } else {
  4042. llvm_unreachable("unexpectedly given multiple inputs");
  4043. }
  4044. }
  4045. const llvm::Triple *AuxTriple =
  4046. (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
  4047. bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
  4048. bool IsIAMCU = RawTriple.isOSIAMCU();
  4049. // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
  4050. // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
  4051. // Windows), we need to pass Windows-specific flags to cc1.
  4052. if (IsCuda || IsHIP)
  4053. IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
  4054. // C++ is not supported for IAMCU.
  4055. if (IsIAMCU && types::isCXX(Input.getType()))
  4056. D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
  4057. // Invoke ourselves in -cc1 mode.
  4058. //
  4059. // FIXME: Implement custom jobs for internal actions.
  4060. CmdArgs.push_back("-cc1");
  4061. // Add the "effective" target triple.
  4062. CmdArgs.push_back("-triple");
  4063. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  4064. if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
  4065. DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
  4066. Args.ClaimAllArgs(options::OPT_MJ);
  4067. } else if (const Arg *GenCDBFragment =
  4068. Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
  4069. DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
  4070. TripleStr, Output, Input, Args);
  4071. Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
  4072. }
  4073. if (IsCuda || IsHIP) {
  4074. // We have to pass the triple of the host if compiling for a CUDA/HIP device
  4075. // and vice-versa.
  4076. std::string NormalizedTriple;
  4077. if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
  4078. JA.isDeviceOffloading(Action::OFK_HIP))
  4079. NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
  4080. ->getTriple()
  4081. .normalize();
  4082. else {
  4083. // Host-side compilation.
  4084. NormalizedTriple =
  4085. (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
  4086. : C.getSingleOffloadToolChain<Action::OFK_HIP>())
  4087. ->getTriple()
  4088. .normalize();
  4089. if (IsCuda) {
  4090. // We need to figure out which CUDA version we're compiling for, as that
  4091. // determines how we load and launch GPU kernels.
  4092. auto *CTC = static_cast<const toolchains::CudaToolChain *>(
  4093. C.getSingleOffloadToolChain<Action::OFK_Cuda>());
  4094. assert(CTC && "Expected valid CUDA Toolchain.");
  4095. if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
  4096. CmdArgs.push_back(Args.MakeArgString(
  4097. Twine("-target-sdk-version=") +
  4098. CudaVersionToString(CTC->CudaInstallation.version())));
  4099. }
  4100. }
  4101. CmdArgs.push_back("-aux-triple");
  4102. CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
  4103. }
  4104. if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
  4105. CmdArgs.push_back("-fsycl-is-device");
  4106. if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
  4107. A->render(Args, CmdArgs);
  4108. } else {
  4109. // Ensure the default version in SYCL mode is 2020.
  4110. CmdArgs.push_back("-sycl-std=2020");
  4111. }
  4112. }
  4113. if (IsOpenMPDevice) {
  4114. // We have to pass the triple of the host if compiling for an OpenMP device.
  4115. std::string NormalizedTriple =
  4116. C.getSingleOffloadToolChain<Action::OFK_Host>()
  4117. ->getTriple()
  4118. .normalize();
  4119. CmdArgs.push_back("-aux-triple");
  4120. CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
  4121. }
  4122. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  4123. Triple.getArch() == llvm::Triple::thumb)) {
  4124. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  4125. unsigned Version = 0;
  4126. bool Failure =
  4127. Triple.getArchName().substr(Offset).consumeInteger(10, Version);
  4128. if (Failure || Version < 7)
  4129. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  4130. << TripleStr;
  4131. }
  4132. // Push all default warning arguments that are specific to
  4133. // the given target. These come before user provided warning options
  4134. // are provided.
  4135. TC.addClangWarningOptions(CmdArgs);
  4136. // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
  4137. if (Triple.isSPIR() || Triple.isSPIRV())
  4138. CmdArgs.push_back("-Wspir-compat");
  4139. // Select the appropriate action.
  4140. RewriteKind rewriteKind = RK_None;
  4141. // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
  4142. // it claims when not running an assembler. Otherwise, clang would emit
  4143. // "argument unused" warnings for assembler flags when e.g. adding "-E" to
  4144. // flags while debugging something. That'd be somewhat inconvenient, and it's
  4145. // also inconsistent with most other flags -- we don't warn on
  4146. // -ffunction-sections not being used in -E mode either for example, even
  4147. // though it's not really used either.
  4148. if (!isa<AssembleJobAction>(JA)) {
  4149. // The args claimed here should match the args used in
  4150. // CollectArgsForIntegratedAssembler().
  4151. if (TC.useIntegratedAs()) {
  4152. Args.ClaimAllArgs(options::OPT_mrelax_all);
  4153. Args.ClaimAllArgs(options::OPT_mno_relax_all);
  4154. Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
  4155. Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
  4156. switch (C.getDefaultToolChain().getArch()) {
  4157. case llvm::Triple::arm:
  4158. case llvm::Triple::armeb:
  4159. case llvm::Triple::thumb:
  4160. case llvm::Triple::thumbeb:
  4161. Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
  4162. break;
  4163. default:
  4164. break;
  4165. }
  4166. }
  4167. Args.ClaimAllArgs(options::OPT_Wa_COMMA);
  4168. Args.ClaimAllArgs(options::OPT_Xassembler);
  4169. Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
  4170. }
  4171. if (isa<AnalyzeJobAction>(JA)) {
  4172. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  4173. CmdArgs.push_back("-analyze");
  4174. } else if (isa<MigrateJobAction>(JA)) {
  4175. CmdArgs.push_back("-migrate");
  4176. } else if (isa<PreprocessJobAction>(JA)) {
  4177. if (Output.getType() == types::TY_Dependencies)
  4178. CmdArgs.push_back("-Eonly");
  4179. else {
  4180. CmdArgs.push_back("-E");
  4181. if (Args.hasArg(options::OPT_rewrite_objc) &&
  4182. !Args.hasArg(options::OPT_g_Group))
  4183. CmdArgs.push_back("-P");
  4184. else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
  4185. CmdArgs.push_back("-fdirectives-only");
  4186. }
  4187. } else if (isa<AssembleJobAction>(JA)) {
  4188. CmdArgs.push_back("-emit-obj");
  4189. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  4190. // Also ignore explicit -force_cpusubtype_ALL option.
  4191. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  4192. } else if (isa<PrecompileJobAction>(JA)) {
  4193. if (JA.getType() == types::TY_Nothing)
  4194. CmdArgs.push_back("-fsyntax-only");
  4195. else if (JA.getType() == types::TY_ModuleFile)
  4196. CmdArgs.push_back("-emit-module-interface");
  4197. else if (JA.getType() == types::TY_HeaderUnit)
  4198. CmdArgs.push_back("-emit-header-unit");
  4199. else
  4200. CmdArgs.push_back("-emit-pch");
  4201. } else if (isa<VerifyPCHJobAction>(JA)) {
  4202. CmdArgs.push_back("-verify-pch");
  4203. } else if (isa<ExtractAPIJobAction>(JA)) {
  4204. assert(JA.getType() == types::TY_API_INFO &&
  4205. "Extract API actions must generate a API information.");
  4206. CmdArgs.push_back("-extract-api");
  4207. if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
  4208. ProductNameArg->render(Args, CmdArgs);
  4209. if (Arg *ExtractAPIIgnoresFileArg =
  4210. Args.getLastArg(options::OPT_extract_api_ignores_EQ))
  4211. ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
  4212. } else {
  4213. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  4214. "Invalid action for clang tool.");
  4215. if (JA.getType() == types::TY_Nothing) {
  4216. CmdArgs.push_back("-fsyntax-only");
  4217. } else if (JA.getType() == types::TY_LLVM_IR ||
  4218. JA.getType() == types::TY_LTO_IR) {
  4219. CmdArgs.push_back("-emit-llvm");
  4220. } else if (JA.getType() == types::TY_LLVM_BC ||
  4221. JA.getType() == types::TY_LTO_BC) {
  4222. // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
  4223. if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
  4224. Args.hasArg(options::OPT_emit_llvm)) {
  4225. CmdArgs.push_back("-emit-llvm");
  4226. } else {
  4227. CmdArgs.push_back("-emit-llvm-bc");
  4228. }
  4229. } else if (JA.getType() == types::TY_IFS ||
  4230. JA.getType() == types::TY_IFS_CPP) {
  4231. StringRef ArgStr =
  4232. Args.hasArg(options::OPT_interface_stub_version_EQ)
  4233. ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
  4234. : "ifs-v1";
  4235. CmdArgs.push_back("-emit-interface-stubs");
  4236. CmdArgs.push_back(
  4237. Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
  4238. } else if (JA.getType() == types::TY_PP_Asm) {
  4239. CmdArgs.push_back("-S");
  4240. } else if (JA.getType() == types::TY_AST) {
  4241. CmdArgs.push_back("-emit-pch");
  4242. } else if (JA.getType() == types::TY_ModuleFile) {
  4243. CmdArgs.push_back("-module-file-info");
  4244. } else if (JA.getType() == types::TY_RewrittenObjC) {
  4245. CmdArgs.push_back("-rewrite-objc");
  4246. rewriteKind = RK_NonFragile;
  4247. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  4248. CmdArgs.push_back("-rewrite-objc");
  4249. rewriteKind = RK_Fragile;
  4250. } else {
  4251. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  4252. }
  4253. // Preserve use-list order by default when emitting bitcode, so that
  4254. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  4255. // same result as running passes here. For LTO, we don't need to preserve
  4256. // the use-list order, since serialization to bitcode is part of the flow.
  4257. if (JA.getType() == types::TY_LLVM_BC)
  4258. CmdArgs.push_back("-emit-llvm-uselists");
  4259. if (IsUsingLTO) {
  4260. if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
  4261. !Args.hasFlag(options::OPT_offload_new_driver,
  4262. options::OPT_no_offload_new_driver, false) &&
  4263. !Triple.isAMDGPU()) {
  4264. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4265. << Args.getLastArg(options::OPT_foffload_lto,
  4266. options::OPT_foffload_lto_EQ)
  4267. ->getAsString(Args)
  4268. << Triple.getTriple();
  4269. } else if (Triple.isNVPTX() && !IsRDCMode &&
  4270. JA.isDeviceOffloading(Action::OFK_Cuda)) {
  4271. D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
  4272. << Args.getLastArg(options::OPT_foffload_lto,
  4273. options::OPT_foffload_lto_EQ)
  4274. ->getAsString(Args)
  4275. << "-fno-gpu-rdc";
  4276. } else {
  4277. assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
  4278. CmdArgs.push_back(Args.MakeArgString(
  4279. Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
  4280. CmdArgs.push_back("-flto-unit");
  4281. }
  4282. }
  4283. }
  4284. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  4285. if (!types::isLLVMIR(Input.getType()))
  4286. D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
  4287. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  4288. }
  4289. if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
  4290. Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
  4291. if (Args.getLastArg(options::OPT_save_temps_EQ))
  4292. Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
  4293. auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
  4294. options::OPT_fmemory_profile_EQ,
  4295. options::OPT_fno_memory_profile);
  4296. if (MemProfArg &&
  4297. !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
  4298. MemProfArg->render(Args, CmdArgs);
  4299. // Embed-bitcode option.
  4300. // Only white-listed flags below are allowed to be embedded.
  4301. if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
  4302. (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
  4303. // Add flags implied by -fembed-bitcode.
  4304. Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
  4305. // Disable all llvm IR level optimizations.
  4306. CmdArgs.push_back("-disable-llvm-passes");
  4307. // Render target options.
  4308. TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
  4309. // reject options that shouldn't be supported in bitcode
  4310. // also reject kernel/kext
  4311. static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
  4312. options::OPT_mkernel,
  4313. options::OPT_fapple_kext,
  4314. options::OPT_ffunction_sections,
  4315. options::OPT_fno_function_sections,
  4316. options::OPT_fdata_sections,
  4317. options::OPT_fno_data_sections,
  4318. options::OPT_fbasic_block_sections_EQ,
  4319. options::OPT_funique_internal_linkage_names,
  4320. options::OPT_fno_unique_internal_linkage_names,
  4321. options::OPT_funique_section_names,
  4322. options::OPT_fno_unique_section_names,
  4323. options::OPT_funique_basic_block_section_names,
  4324. options::OPT_fno_unique_basic_block_section_names,
  4325. options::OPT_mrestrict_it,
  4326. options::OPT_mno_restrict_it,
  4327. options::OPT_mstackrealign,
  4328. options::OPT_mno_stackrealign,
  4329. options::OPT_mstack_alignment,
  4330. options::OPT_mcmodel_EQ,
  4331. options::OPT_mlong_calls,
  4332. options::OPT_mno_long_calls,
  4333. options::OPT_ggnu_pubnames,
  4334. options::OPT_gdwarf_aranges,
  4335. options::OPT_fdebug_types_section,
  4336. options::OPT_fno_debug_types_section,
  4337. options::OPT_fdwarf_directory_asm,
  4338. options::OPT_fno_dwarf_directory_asm,
  4339. options::OPT_mrelax_all,
  4340. options::OPT_mno_relax_all,
  4341. options::OPT_ftrap_function_EQ,
  4342. options::OPT_ffixed_r9,
  4343. options::OPT_mfix_cortex_a53_835769,
  4344. options::OPT_mno_fix_cortex_a53_835769,
  4345. options::OPT_ffixed_x18,
  4346. options::OPT_mglobal_merge,
  4347. options::OPT_mno_global_merge,
  4348. options::OPT_mred_zone,
  4349. options::OPT_mno_red_zone,
  4350. options::OPT_Wa_COMMA,
  4351. options::OPT_Xassembler,
  4352. options::OPT_mllvm,
  4353. };
  4354. for (const auto &A : Args)
  4355. if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
  4356. D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
  4357. // Render the CodeGen options that need to be passed.
  4358. Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
  4359. options::OPT_fno_optimize_sibling_calls);
  4360. RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
  4361. CmdArgs, JA);
  4362. // Render ABI arguments
  4363. switch (TC.getArch()) {
  4364. default: break;
  4365. case llvm::Triple::arm:
  4366. case llvm::Triple::armeb:
  4367. case llvm::Triple::thumbeb:
  4368. RenderARMABI(D, Triple, Args, CmdArgs);
  4369. break;
  4370. case llvm::Triple::aarch64:
  4371. case llvm::Triple::aarch64_32:
  4372. case llvm::Triple::aarch64_be:
  4373. RenderAArch64ABI(Triple, Args, CmdArgs);
  4374. break;
  4375. }
  4376. // Optimization level for CodeGen.
  4377. if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  4378. if (A->getOption().matches(options::OPT_O4)) {
  4379. CmdArgs.push_back("-O3");
  4380. D.Diag(diag::warn_O4_is_O3);
  4381. } else {
  4382. A->render(Args, CmdArgs);
  4383. }
  4384. }
  4385. // Input/Output file.
  4386. if (Output.getType() == types::TY_Dependencies) {
  4387. // Handled with other dependency code.
  4388. } else if (Output.isFilename()) {
  4389. CmdArgs.push_back("-o");
  4390. CmdArgs.push_back(Output.getFilename());
  4391. } else {
  4392. assert(Output.isNothing() && "Input output.");
  4393. }
  4394. for (const auto &II : Inputs) {
  4395. addDashXForInput(Args, II, CmdArgs);
  4396. if (II.isFilename())
  4397. CmdArgs.push_back(II.getFilename());
  4398. else
  4399. II.getInputArg().renderAsInput(Args, CmdArgs);
  4400. }
  4401. C.addCommand(std::make_unique<Command>(
  4402. JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
  4403. CmdArgs, Inputs, Output));
  4404. return;
  4405. }
  4406. if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
  4407. CmdArgs.push_back("-fembed-bitcode=marker");
  4408. // We normally speed up the clang process a bit by skipping destructors at
  4409. // exit, but when we're generating diagnostics we can rely on some of the
  4410. // cleanup.
  4411. if (!C.isForDiagnostics())
  4412. CmdArgs.push_back("-disable-free");
  4413. CmdArgs.push_back("-clear-ast-before-backend");
  4414. #ifdef NDEBUG
  4415. const bool IsAssertBuild = false;
  4416. #else
  4417. const bool IsAssertBuild = true;
  4418. #endif
  4419. // Disable the verification pass in -asserts builds.
  4420. if (!IsAssertBuild)
  4421. CmdArgs.push_back("-disable-llvm-verifier");
  4422. // Discard value names in assert builds unless otherwise specified.
  4423. if (Args.hasFlag(options::OPT_fdiscard_value_names,
  4424. options::OPT_fno_discard_value_names, !IsAssertBuild)) {
  4425. if (Args.hasArg(options::OPT_fdiscard_value_names) &&
  4426. llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
  4427. return types::isLLVMIR(II.getType());
  4428. })) {
  4429. D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
  4430. }
  4431. CmdArgs.push_back("-discard-value-names");
  4432. }
  4433. // Set the main file name, so that debug info works even with
  4434. // -save-temps.
  4435. CmdArgs.push_back("-main-file-name");
  4436. CmdArgs.push_back(getBaseInputName(Args, Input));
  4437. // Some flags which affect the language (via preprocessor
  4438. // defines).
  4439. if (Args.hasArg(options::OPT_static))
  4440. CmdArgs.push_back("-static-define");
  4441. if (Args.hasArg(options::OPT_municode))
  4442. CmdArgs.push_back("-DUNICODE");
  4443. if (isa<AnalyzeJobAction>(JA))
  4444. RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
  4445. if (isa<AnalyzeJobAction>(JA) ||
  4446. (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
  4447. CmdArgs.push_back("-setup-static-analyzer");
  4448. // Enable compatilibily mode to avoid analyzer-config related errors.
  4449. // Since we can't access frontend flags through hasArg, let's manually iterate
  4450. // through them.
  4451. bool FoundAnalyzerConfig = false;
  4452. for (auto *Arg : Args.filtered(options::OPT_Xclang))
  4453. if (StringRef(Arg->getValue()) == "-analyzer-config") {
  4454. FoundAnalyzerConfig = true;
  4455. break;
  4456. }
  4457. if (!FoundAnalyzerConfig)
  4458. for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
  4459. if (StringRef(Arg->getValue()) == "-analyzer-config") {
  4460. FoundAnalyzerConfig = true;
  4461. break;
  4462. }
  4463. if (FoundAnalyzerConfig)
  4464. CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
  4465. CheckCodeGenerationOptions(D, Args);
  4466. unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
  4467. assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
  4468. if (FunctionAlignment) {
  4469. CmdArgs.push_back("-function-alignment");
  4470. CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
  4471. }
  4472. // We support -falign-loops=N where N is a power of 2. GCC supports more
  4473. // forms.
  4474. if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
  4475. unsigned Value = 0;
  4476. if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
  4477. TC.getDriver().Diag(diag::err_drv_invalid_int_value)
  4478. << A->getAsString(Args) << A->getValue();
  4479. else if (Value & (Value - 1))
  4480. TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
  4481. << A->getAsString(Args) << A->getValue();
  4482. // Treat =0 as unspecified (use the target preference).
  4483. if (Value)
  4484. CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
  4485. Twine(std::min(Value, 65536u))));
  4486. }
  4487. llvm::Reloc::Model RelocationModel;
  4488. unsigned PICLevel;
  4489. bool IsPIE;
  4490. std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
  4491. Arg *LastPICDataRelArg =
  4492. Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
  4493. options::OPT_mpic_data_is_text_relative);
  4494. bool NoPICDataIsTextRelative = false;
  4495. if (LastPICDataRelArg) {
  4496. if (LastPICDataRelArg->getOption().matches(
  4497. options::OPT_mno_pic_data_is_text_relative)) {
  4498. NoPICDataIsTextRelative = true;
  4499. if (!PICLevel)
  4500. D.Diag(diag::err_drv_argument_only_allowed_with)
  4501. << "-mno-pic-data-is-text-relative"
  4502. << "-fpic/-fpie";
  4503. }
  4504. if (!Triple.isSystemZ())
  4505. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4506. << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
  4507. : "-mpic-data-is-text-relative")
  4508. << RawTriple.str();
  4509. }
  4510. bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
  4511. RelocationModel == llvm::Reloc::ROPI_RWPI;
  4512. bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
  4513. RelocationModel == llvm::Reloc::ROPI_RWPI;
  4514. if (Args.hasArg(options::OPT_mcmse) &&
  4515. !Args.hasArg(options::OPT_fallow_unsupported)) {
  4516. if (IsROPI)
  4517. D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
  4518. if (IsRWPI)
  4519. D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
  4520. }
  4521. if (IsROPI && types::isCXX(Input.getType()) &&
  4522. !Args.hasArg(options::OPT_fallow_unsupported))
  4523. D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
  4524. const char *RMName = RelocationModelName(RelocationModel);
  4525. if (RMName) {
  4526. CmdArgs.push_back("-mrelocation-model");
  4527. CmdArgs.push_back(RMName);
  4528. }
  4529. if (PICLevel > 0) {
  4530. CmdArgs.push_back("-pic-level");
  4531. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  4532. if (IsPIE)
  4533. CmdArgs.push_back("-pic-is-pie");
  4534. if (NoPICDataIsTextRelative)
  4535. CmdArgs.push_back("-mcmodel=medium");
  4536. }
  4537. if (RelocationModel == llvm::Reloc::ROPI ||
  4538. RelocationModel == llvm::Reloc::ROPI_RWPI)
  4539. CmdArgs.push_back("-fropi");
  4540. if (RelocationModel == llvm::Reloc::RWPI ||
  4541. RelocationModel == llvm::Reloc::ROPI_RWPI)
  4542. CmdArgs.push_back("-frwpi");
  4543. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  4544. CmdArgs.push_back("-meabi");
  4545. CmdArgs.push_back(A->getValue());
  4546. }
  4547. // -fsemantic-interposition is forwarded to CC1: set the
  4548. // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
  4549. // make default visibility external linkage definitions dso_preemptable.
  4550. //
  4551. // -fno-semantic-interposition: if the target supports .Lfoo$local local
  4552. // aliases (make default visibility external linkage definitions dso_local).
  4553. // This is the CC1 default for ELF to match COFF/Mach-O.
  4554. //
  4555. // Otherwise use Clang's traditional behavior: like
  4556. // -fno-semantic-interposition but local aliases are not used. So references
  4557. // can be interposed if not optimized out.
  4558. if (Triple.isOSBinFormatELF()) {
  4559. Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
  4560. options::OPT_fno_semantic_interposition);
  4561. if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
  4562. // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
  4563. bool SupportsLocalAlias =
  4564. Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
  4565. if (!A)
  4566. CmdArgs.push_back("-fhalf-no-semantic-interposition");
  4567. else if (A->getOption().matches(options::OPT_fsemantic_interposition))
  4568. A->render(Args, CmdArgs);
  4569. else if (!SupportsLocalAlias)
  4570. CmdArgs.push_back("-fhalf-no-semantic-interposition");
  4571. }
  4572. }
  4573. {
  4574. std::string Model;
  4575. if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
  4576. if (!TC.isThreadModelSupported(A->getValue()))
  4577. D.Diag(diag::err_drv_invalid_thread_model_for_target)
  4578. << A->getValue() << A->getAsString(Args);
  4579. Model = A->getValue();
  4580. } else
  4581. Model = TC.getThreadModel();
  4582. if (Model != "posix") {
  4583. CmdArgs.push_back("-mthread-model");
  4584. CmdArgs.push_back(Args.MakeArgString(Model));
  4585. }
  4586. }
  4587. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  4588. StringRef Name = A->getValue();
  4589. if (Name == "SVML") {
  4590. if (Triple.getArch() != llvm::Triple::x86 &&
  4591. Triple.getArch() != llvm::Triple::x86_64)
  4592. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4593. << Name << Triple.getArchName();
  4594. } else if (Name == "LIBMVEC-X86") {
  4595. if (Triple.getArch() != llvm::Triple::x86 &&
  4596. Triple.getArch() != llvm::Triple::x86_64)
  4597. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4598. << Name << Triple.getArchName();
  4599. } else if (Name == "SLEEF") {
  4600. if (Triple.getArch() != llvm::Triple::aarch64 &&
  4601. Triple.getArch() != llvm::Triple::aarch64_be)
  4602. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4603. << Name << Triple.getArchName();
  4604. }
  4605. A->render(Args, CmdArgs);
  4606. }
  4607. if (Args.hasFlag(options::OPT_fmerge_all_constants,
  4608. options::OPT_fno_merge_all_constants, false))
  4609. CmdArgs.push_back("-fmerge-all-constants");
  4610. Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
  4611. options::OPT_fno_delete_null_pointer_checks);
  4612. // LLVM Code Generator Options.
  4613. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) {
  4614. StringRef Map = A->getValue();
  4615. if (!llvm::sys::fs::exists(Map)) {
  4616. D.Diag(diag::err_drv_no_such_file) << Map;
  4617. } else {
  4618. A->render(Args, CmdArgs);
  4619. A->claim();
  4620. }
  4621. }
  4622. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi,
  4623. options::OPT_mabi_EQ_vec_default)) {
  4624. if (!Triple.isOSAIX())
  4625. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4626. << A->getSpelling() << RawTriple.str();
  4627. if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi)
  4628. CmdArgs.push_back("-mabi=vec-extabi");
  4629. else
  4630. CmdArgs.push_back("-mabi=vec-default");
  4631. }
  4632. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
  4633. if (!Triple.isOSAIX() || Triple.isPPC32())
  4634. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4635. << A->getSpelling() << RawTriple.str();
  4636. CmdArgs.push_back("-mabi=quadword-atomics");
  4637. }
  4638. if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
  4639. // Emit the unsupported option error until the Clang's library integration
  4640. // support for 128-bit long double is available for AIX.
  4641. if (Triple.isOSAIX())
  4642. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4643. << A->getSpelling() << RawTriple.str();
  4644. }
  4645. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  4646. StringRef v = A->getValue();
  4647. // FIXME: Validate the argument here so we don't produce meaningless errors
  4648. // about -fwarn-stack-size=.
  4649. if (v.empty())
  4650. D.Diag(diag::err_drv_missing_argument) << A->getSpelling() << 1;
  4651. else
  4652. CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + v));
  4653. A->claim();
  4654. }
  4655. Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
  4656. options::OPT_fno_jump_tables);
  4657. Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
  4658. options::OPT_fno_profile_sample_accurate);
  4659. Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
  4660. options::OPT_fno_preserve_as_comments);
  4661. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  4662. CmdArgs.push_back("-mregparm");
  4663. CmdArgs.push_back(A->getValue());
  4664. }
  4665. if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
  4666. options::OPT_msvr4_struct_return)) {
  4667. if (!TC.getTriple().isPPC32()) {
  4668. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4669. << A->getSpelling() << RawTriple.str();
  4670. } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
  4671. CmdArgs.push_back("-maix-struct-return");
  4672. } else {
  4673. assert(A->getOption().matches(options::OPT_msvr4_struct_return));
  4674. CmdArgs.push_back("-msvr4-struct-return");
  4675. }
  4676. }
  4677. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  4678. options::OPT_freg_struct_return)) {
  4679. if (TC.getArch() != llvm::Triple::x86) {
  4680. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4681. << A->getSpelling() << RawTriple.str();
  4682. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  4683. CmdArgs.push_back("-fpcc-struct-return");
  4684. } else {
  4685. assert(A->getOption().matches(options::OPT_freg_struct_return));
  4686. CmdArgs.push_back("-freg-struct-return");
  4687. }
  4688. }
  4689. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  4690. CmdArgs.push_back("-fdefault-calling-conv=stdcall");
  4691. if (Args.hasArg(options::OPT_fenable_matrix)) {
  4692. // enable-matrix is needed by both the LangOpts and by LLVM.
  4693. CmdArgs.push_back("-fenable-matrix");
  4694. CmdArgs.push_back("-mllvm");
  4695. CmdArgs.push_back("-enable-matrix");
  4696. }
  4697. CodeGenOptions::FramePointerKind FPKeepKind =
  4698. getFramePointerKind(Args, RawTriple);
  4699. const char *FPKeepKindStr = nullptr;
  4700. switch (FPKeepKind) {
  4701. case CodeGenOptions::FramePointerKind::None:
  4702. FPKeepKindStr = "-mframe-pointer=none";
  4703. break;
  4704. case CodeGenOptions::FramePointerKind::NonLeaf:
  4705. FPKeepKindStr = "-mframe-pointer=non-leaf";
  4706. break;
  4707. case CodeGenOptions::FramePointerKind::All:
  4708. FPKeepKindStr = "-mframe-pointer=all";
  4709. break;
  4710. }
  4711. assert(FPKeepKindStr && "unknown FramePointerKind");
  4712. CmdArgs.push_back(FPKeepKindStr);
  4713. Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
  4714. options::OPT_fno_zero_initialized_in_bss);
  4715. bool OFastEnabled = isOptimizationLevelFast(Args);
  4716. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  4717. // enabled. This alias option is being used to simplify the hasFlag logic.
  4718. OptSpecifier StrictAliasingAliasOption =
  4719. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  4720. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  4721. // doesn't do any TBAA.
  4722. bool TBAAOnByDefault = !D.IsCLMode();
  4723. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  4724. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  4725. CmdArgs.push_back("-relaxed-aliasing");
  4726. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  4727. options::OPT_fno_struct_path_tbaa, true))
  4728. CmdArgs.push_back("-no-struct-path-tbaa");
  4729. Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
  4730. options::OPT_fno_strict_enums);
  4731. Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
  4732. options::OPT_fno_strict_return);
  4733. Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
  4734. options::OPT_fno_allow_editor_placeholders);
  4735. Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
  4736. options::OPT_fno_strict_vtable_pointers);
  4737. Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
  4738. options::OPT_fno_force_emit_vtables);
  4739. Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
  4740. options::OPT_fno_optimize_sibling_calls);
  4741. Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
  4742. options::OPT_fno_escaping_block_tail_calls);
  4743. Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
  4744. options::OPT_fno_fine_grained_bitfield_accesses);
  4745. Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
  4746. options::OPT_fno_experimental_relative_cxx_abi_vtables);
  4747. // Handle segmented stacks.
  4748. Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
  4749. options::OPT_fno_split_stack);
  4750. // -fprotect-parens=0 is default.
  4751. if (Args.hasFlag(options::OPT_fprotect_parens,
  4752. options::OPT_fno_protect_parens, false))
  4753. CmdArgs.push_back("-fprotect-parens");
  4754. RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
  4755. if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
  4756. const llvm::Triple::ArchType Arch = TC.getArch();
  4757. if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  4758. StringRef V = A->getValue();
  4759. if (V == "64")
  4760. CmdArgs.push_back("-fextend-arguments=64");
  4761. else if (V != "32")
  4762. D.Diag(diag::err_drv_invalid_argument_to_option)
  4763. << A->getValue() << A->getOption().getName();
  4764. } else
  4765. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4766. << A->getOption().getName() << TripleStr;
  4767. }
  4768. if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
  4769. if (TC.getArch() == llvm::Triple::avr)
  4770. A->render(Args, CmdArgs);
  4771. else
  4772. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4773. << A->getAsString(Args) << TripleStr;
  4774. }
  4775. if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
  4776. if (TC.getTriple().isX86())
  4777. A->render(Args, CmdArgs);
  4778. else if (TC.getTriple().isPPC() &&
  4779. (A->getOption().getID() != options::OPT_mlong_double_80))
  4780. A->render(Args, CmdArgs);
  4781. else
  4782. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4783. << A->getAsString(Args) << TripleStr;
  4784. }
  4785. // Decide whether to use verbose asm. Verbose assembly is the default on
  4786. // toolchains which have the integrated assembler on by default.
  4787. bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
  4788. if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  4789. IsIntegratedAssemblerDefault))
  4790. CmdArgs.push_back("-fno-verbose-asm");
  4791. // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
  4792. // use that to indicate the MC default in the backend.
  4793. if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
  4794. StringRef V = A->getValue();
  4795. unsigned Num;
  4796. if (V == "none")
  4797. A->render(Args, CmdArgs);
  4798. else if (!V.consumeInteger(10, Num) && Num > 0 &&
  4799. (V.empty() || (V.consume_front(".") &&
  4800. !V.consumeInteger(10, Num) && V.empty())))
  4801. A->render(Args, CmdArgs);
  4802. else
  4803. D.Diag(diag::err_drv_invalid_argument_to_option)
  4804. << A->getValue() << A->getOption().getName();
  4805. }
  4806. // If toolchain choose to use MCAsmParser for inline asm don't pass the
  4807. // option to disable integrated-as explictly.
  4808. if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
  4809. CmdArgs.push_back("-no-integrated-as");
  4810. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  4811. CmdArgs.push_back("-mdebug-pass");
  4812. CmdArgs.push_back("Structure");
  4813. }
  4814. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  4815. CmdArgs.push_back("-mdebug-pass");
  4816. CmdArgs.push_back("Arguments");
  4817. }
  4818. // Enable -mconstructor-aliases except on darwin, where we have to work around
  4819. // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
  4820. // aliases aren't supported.
  4821. if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
  4822. CmdArgs.push_back("-mconstructor-aliases");
  4823. // Darwin's kernel doesn't support guard variables; just die if we
  4824. // try to use them.
  4825. if (KernelOrKext && RawTriple.isOSDarwin())
  4826. CmdArgs.push_back("-fforbid-guard-variables");
  4827. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  4828. Triple.isWindowsGNUEnvironment())) {
  4829. CmdArgs.push_back("-mms-bitfields");
  4830. }
  4831. // Non-PIC code defaults to -fdirect-access-external-data while PIC code
  4832. // defaults to -fno-direct-access-external-data. Pass the option if different
  4833. // from the default.
  4834. if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
  4835. options::OPT_fno_direct_access_external_data))
  4836. if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
  4837. (PICLevel == 0))
  4838. A->render(Args, CmdArgs);
  4839. if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
  4840. CmdArgs.push_back("-fno-plt");
  4841. }
  4842. // -fhosted is default.
  4843. // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
  4844. // use Freestanding.
  4845. bool Freestanding =
  4846. Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  4847. KernelOrKext;
  4848. if (Freestanding)
  4849. CmdArgs.push_back("-ffreestanding");
  4850. Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
  4851. // This is a coarse approximation of what llvm-gcc actually does, both
  4852. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  4853. // complicated ways.
  4854. auto SanitizeArgs = TC.getSanitizerArgs(Args);
  4855. bool IsAsyncUnwindTablesDefault =
  4856. TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
  4857. bool IsSyncUnwindTablesDefault =
  4858. TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
  4859. bool AsyncUnwindTables = Args.hasFlag(
  4860. options::OPT_fasynchronous_unwind_tables,
  4861. options::OPT_fno_asynchronous_unwind_tables,
  4862. (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
  4863. !Freestanding);
  4864. bool UnwindTables =
  4865. Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  4866. IsSyncUnwindTablesDefault && !Freestanding);
  4867. if (AsyncUnwindTables)
  4868. CmdArgs.push_back("-funwind-tables=2");
  4869. else if (UnwindTables)
  4870. CmdArgs.push_back("-funwind-tables=1");
  4871. // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
  4872. // `--gpu-use-aux-triple-only` is specified.
  4873. if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
  4874. (IsCudaDevice || IsHIPDevice)) {
  4875. const ArgList &HostArgs =
  4876. C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
  4877. std::string HostCPU =
  4878. getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
  4879. if (!HostCPU.empty()) {
  4880. CmdArgs.push_back("-aux-target-cpu");
  4881. CmdArgs.push_back(Args.MakeArgString(HostCPU));
  4882. }
  4883. getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
  4884. /*ForAS*/ false, /*IsAux*/ true);
  4885. }
  4886. TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
  4887. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  4888. StringRef CM = A->getValue();
  4889. if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" ||
  4890. CM == "tiny") {
  4891. if (Triple.isOSAIX() && CM == "medium")
  4892. CmdArgs.push_back("-mcmodel=large");
  4893. else if (Triple.isAArch64() && (CM == "kernel" || CM == "medium"))
  4894. D.Diag(diag::err_drv_invalid_argument_to_option)
  4895. << CM << A->getOption().getName();
  4896. else
  4897. A->render(Args, CmdArgs);
  4898. } else {
  4899. D.Diag(diag::err_drv_invalid_argument_to_option)
  4900. << CM << A->getOption().getName();
  4901. }
  4902. }
  4903. if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
  4904. StringRef Value = A->getValue();
  4905. unsigned TLSSize = 0;
  4906. Value.getAsInteger(10, TLSSize);
  4907. if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
  4908. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4909. << A->getOption().getName() << TripleStr;
  4910. if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
  4911. D.Diag(diag::err_drv_invalid_int_value)
  4912. << A->getOption().getName() << Value;
  4913. Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
  4914. }
  4915. // Add the target cpu
  4916. std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
  4917. if (!CPU.empty()) {
  4918. CmdArgs.push_back("-target-cpu");
  4919. CmdArgs.push_back(Args.MakeArgString(CPU));
  4920. }
  4921. RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
  4922. // FIXME: For now we want to demote any errors to warnings, when they have
  4923. // been raised for asking the wrong question of scalable vectors, such as
  4924. // asking for the fixed number of elements. This may happen because code that
  4925. // is not yet ported to work for scalable vectors uses the wrong interfaces,
  4926. // whereas the behaviour is actually correct. Emitting a warning helps bring
  4927. // up scalable vector support in an incremental way. When scalable vector
  4928. // support is stable enough, all uses of wrong interfaces should be considered
  4929. // as errors, but until then, we can live with a warning being emitted by the
  4930. // compiler. This way, Clang can be used to compile code with scalable vectors
  4931. // and identify possible issues.
  4932. if (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  4933. isa<BackendJobAction>(JA)) {
  4934. CmdArgs.push_back("-mllvm");
  4935. CmdArgs.push_back("-treat-scalable-fixed-error-as-warning");
  4936. }
  4937. // These two are potentially updated by AddClangCLArgs.
  4938. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  4939. bool EmitCodeView = false;
  4940. // Add clang-cl arguments.
  4941. types::ID InputType = Input.getType();
  4942. if (D.IsCLMode())
  4943. AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
  4944. DwarfFissionKind DwarfFission = DwarfFissionKind::None;
  4945. renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
  4946. types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
  4947. DwarfFission);
  4948. // This controls whether or not we perform JustMyCode instrumentation.
  4949. if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
  4950. if (TC.getTriple().isOSBinFormatELF()) {
  4951. if (DebugInfoKind >= codegenoptions::DebugInfoConstructor)
  4952. CmdArgs.push_back("-fjmc");
  4953. else
  4954. D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
  4955. << "-g";
  4956. } else {
  4957. D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
  4958. }
  4959. }
  4960. // Add the split debug info name to the command lines here so we
  4961. // can propagate it to the backend.
  4962. bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
  4963. (TC.getTriple().isOSBinFormatELF() ||
  4964. TC.getTriple().isOSBinFormatWasm()) &&
  4965. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  4966. isa<BackendJobAction>(JA));
  4967. if (SplitDWARF) {
  4968. const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
  4969. CmdArgs.push_back("-split-dwarf-file");
  4970. CmdArgs.push_back(SplitDWARFOut);
  4971. if (DwarfFission == DwarfFissionKind::Split) {
  4972. CmdArgs.push_back("-split-dwarf-output");
  4973. CmdArgs.push_back(SplitDWARFOut);
  4974. }
  4975. }
  4976. // Pass the linker version in use.
  4977. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  4978. CmdArgs.push_back("-target-linker-version");
  4979. CmdArgs.push_back(A->getValue());
  4980. }
  4981. // Explicitly error on some things we know we don't support and can't just
  4982. // ignore.
  4983. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  4984. Arg *Unsupported;
  4985. if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
  4986. TC.getArch() == llvm::Triple::x86) {
  4987. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  4988. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  4989. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  4990. << Unsupported->getOption().getName();
  4991. }
  4992. // The faltivec option has been superseded by the maltivec option.
  4993. if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
  4994. D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
  4995. << Unsupported->getOption().getName()
  4996. << "please use -maltivec and include altivec.h explicitly";
  4997. if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
  4998. D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
  4999. << Unsupported->getOption().getName() << "please use -mno-altivec";
  5000. }
  5001. Args.AddAllArgs(CmdArgs, options::OPT_v);
  5002. if (Args.getLastArg(options::OPT_H)) {
  5003. CmdArgs.push_back("-H");
  5004. CmdArgs.push_back("-sys-header-deps");
  5005. }
  5006. Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
  5007. if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
  5008. CmdArgs.push_back("-header-include-file");
  5009. CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
  5010. ? D.CCPrintHeadersFilename.c_str()
  5011. : "-");
  5012. CmdArgs.push_back("-sys-header-deps");
  5013. CmdArgs.push_back(Args.MakeArgString(
  5014. "-header-include-format=" +
  5015. std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
  5016. CmdArgs.push_back(
  5017. Args.MakeArgString("-header-include-filtering=" +
  5018. std::string(headerIncludeFilteringKindToString(
  5019. D.CCPrintHeadersFiltering))));
  5020. }
  5021. Args.AddLastArg(CmdArgs, options::OPT_P);
  5022. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  5023. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  5024. CmdArgs.push_back("-diagnostic-log-file");
  5025. CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
  5026. ? D.CCLogDiagnosticsFilename.c_str()
  5027. : "-");
  5028. }
  5029. // Give the gen diagnostics more chances to succeed, by avoiding intentional
  5030. // crashes.
  5031. if (D.CCGenDiagnostics)
  5032. CmdArgs.push_back("-disable-pragma-debug-crash");
  5033. // Allow backend to put its diagnostic files in the same place as frontend
  5034. // crash diagnostics files.
  5035. if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
  5036. StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
  5037. CmdArgs.push_back("-mllvm");
  5038. CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
  5039. }
  5040. bool UseSeparateSections = isUseSeparateSections(Triple);
  5041. if (Args.hasFlag(options::OPT_ffunction_sections,
  5042. options::OPT_fno_function_sections, UseSeparateSections)) {
  5043. CmdArgs.push_back("-ffunction-sections");
  5044. }
  5045. if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
  5046. StringRef Val = A->getValue();
  5047. if (Triple.isX86() && Triple.isOSBinFormatELF()) {
  5048. if (Val != "all" && Val != "labels" && Val != "none" &&
  5049. !Val.startswith("list="))
  5050. D.Diag(diag::err_drv_invalid_value)
  5051. << A->getAsString(Args) << A->getValue();
  5052. else
  5053. A->render(Args, CmdArgs);
  5054. } else if (Triple.isNVPTX()) {
  5055. // Do not pass the option to the GPU compilation. We still want it enabled
  5056. // for the host-side compilation, so seeing it here is not an error.
  5057. } else if (Val != "none") {
  5058. // =none is allowed everywhere. It's useful for overriding the option
  5059. // and is the same as not specifying the option.
  5060. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5061. << A->getAsString(Args) << TripleStr;
  5062. }
  5063. }
  5064. bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
  5065. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  5066. UseSeparateSections || HasDefaultDataSections)) {
  5067. CmdArgs.push_back("-fdata-sections");
  5068. }
  5069. Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
  5070. options::OPT_fno_unique_section_names);
  5071. Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
  5072. options::OPT_fno_unique_internal_linkage_names);
  5073. Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
  5074. options::OPT_fno_unique_basic_block_section_names);
  5075. if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
  5076. options::OPT_fno_split_machine_functions)) {
  5077. // This codegen pass is only available on x86-elf targets.
  5078. if (Triple.isX86() && Triple.isOSBinFormatELF()) {
  5079. if (A->getOption().matches(options::OPT_fsplit_machine_functions))
  5080. A->render(Args, CmdArgs);
  5081. } else {
  5082. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5083. << A->getAsString(Args) << TripleStr;
  5084. }
  5085. }
  5086. Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
  5087. options::OPT_finstrument_functions_after_inlining,
  5088. options::OPT_finstrument_function_entry_bare);
  5089. // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
  5090. // for sampling, overhead of call arc collection is way too high and there's
  5091. // no way to collect the output.
  5092. if (!Triple.isNVPTX() && !Triple.isAMDGCN())
  5093. addPGOAndCoverageFlags(TC, C, D, Output, Args, SanitizeArgs, CmdArgs);
  5094. Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
  5095. if (getLastProfileSampleUseArg(Args) &&
  5096. Args.hasArg(options::OPT_fsample_profile_use_profi)) {
  5097. CmdArgs.push_back("-mllvm");
  5098. CmdArgs.push_back("-sample-profile-use-profi");
  5099. }
  5100. // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
  5101. if (RawTriple.isPS() &&
  5102. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  5103. PScpu::addProfileRTArgs(TC, Args, CmdArgs);
  5104. PScpu::addSanitizerArgs(TC, Args, CmdArgs);
  5105. }
  5106. // Pass options for controlling the default header search paths.
  5107. if (Args.hasArg(options::OPT_nostdinc)) {
  5108. CmdArgs.push_back("-nostdsysteminc");
  5109. CmdArgs.push_back("-nobuiltininc");
  5110. } else {
  5111. if (Args.hasArg(options::OPT_nostdlibinc))
  5112. CmdArgs.push_back("-nostdsysteminc");
  5113. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  5114. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  5115. }
  5116. // Pass the path to compiler resource files.
  5117. CmdArgs.push_back("-resource-dir");
  5118. CmdArgs.push_back(D.ResourceDir.c_str());
  5119. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  5120. RenderARCMigrateToolOptions(D, Args, CmdArgs);
  5121. // Add preprocessing options like -I, -D, etc. if we are using the
  5122. // preprocessor.
  5123. //
  5124. // FIXME: Support -fpreprocessed
  5125. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  5126. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
  5127. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  5128. // that "The compiler can only warn and ignore the option if not recognized".
  5129. // When building with ccache, it will pass -D options to clang even on
  5130. // preprocessed inputs and configure concludes that -fPIC is not supported.
  5131. Args.ClaimAllArgs(options::OPT_D);
  5132. // Manually translate -O4 to -O3; let clang reject others.
  5133. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  5134. if (A->getOption().matches(options::OPT_O4)) {
  5135. CmdArgs.push_back("-O3");
  5136. D.Diag(diag::warn_O4_is_O3);
  5137. } else {
  5138. A->render(Args, CmdArgs);
  5139. }
  5140. }
  5141. // Warn about ignored options to clang.
  5142. for (const Arg *A :
  5143. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  5144. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  5145. A->claim();
  5146. }
  5147. for (const Arg *A :
  5148. Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
  5149. D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
  5150. A->claim();
  5151. }
  5152. claimNoWarnArgs(Args);
  5153. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  5154. for (const Arg *A :
  5155. Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
  5156. A->claim();
  5157. if (A->getOption().getID() == options::OPT__SLASH_wd) {
  5158. unsigned WarningNumber;
  5159. if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
  5160. D.Diag(diag::err_drv_invalid_int_value)
  5161. << A->getAsString(Args) << A->getValue();
  5162. continue;
  5163. }
  5164. if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
  5165. CmdArgs.push_back(Args.MakeArgString(
  5166. "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
  5167. }
  5168. continue;
  5169. }
  5170. A->render(Args, CmdArgs);
  5171. }
  5172. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  5173. CmdArgs.push_back("-pedantic");
  5174. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  5175. Args.AddLastArg(CmdArgs, options::OPT_w);
  5176. Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
  5177. options::OPT_fno_fixed_point);
  5178. if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
  5179. A->render(Args, CmdArgs);
  5180. Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
  5181. options::OPT_fno_experimental_relative_cxx_abi_vtables);
  5182. if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
  5183. A->render(Args, CmdArgs);
  5184. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  5185. // (-ansi is equivalent to -std=c89 or -std=c++98).
  5186. //
  5187. // If a std is supplied, only add -trigraphs if it follows the
  5188. // option.
  5189. bool ImplyVCPPCVer = false;
  5190. bool ImplyVCPPCXXVer = false;
  5191. const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
  5192. if (Std) {
  5193. if (Std->getOption().matches(options::OPT_ansi))
  5194. if (types::isCXX(InputType))
  5195. CmdArgs.push_back("-std=c++98");
  5196. else
  5197. CmdArgs.push_back("-std=c89");
  5198. else
  5199. Std->render(Args, CmdArgs);
  5200. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  5201. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  5202. options::OPT_ftrigraphs,
  5203. options::OPT_fno_trigraphs))
  5204. if (A != Std)
  5205. A->render(Args, CmdArgs);
  5206. } else {
  5207. // Honor -std-default.
  5208. //
  5209. // FIXME: Clang doesn't correctly handle -std= when the input language
  5210. // doesn't match. For the time being just ignore this for C++ inputs;
  5211. // eventually we want to do all the standard defaulting here instead of
  5212. // splitting it between the driver and clang -cc1.
  5213. if (!types::isCXX(InputType)) {
  5214. if (!Args.hasArg(options::OPT__SLASH_std)) {
  5215. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  5216. /*Joined=*/true);
  5217. } else
  5218. ImplyVCPPCVer = true;
  5219. }
  5220. else if (IsWindowsMSVC)
  5221. ImplyVCPPCXXVer = true;
  5222. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  5223. options::OPT_fno_trigraphs);
  5224. }
  5225. // GCC's behavior for -Wwrite-strings is a bit strange:
  5226. // * In C, this "warning flag" changes the types of string literals from
  5227. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  5228. // for the discarded qualifier.
  5229. // * In C++, this is just a normal warning flag.
  5230. //
  5231. // Implementing this warning correctly in C is hard, so we follow GCC's
  5232. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  5233. // a non-const char* in C, rather than using this crude hack.
  5234. if (!types::isCXX(InputType)) {
  5235. // FIXME: This should behave just like a warning flag, and thus should also
  5236. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  5237. Arg *WriteStrings =
  5238. Args.getLastArg(options::OPT_Wwrite_strings,
  5239. options::OPT_Wno_write_strings, options::OPT_w);
  5240. if (WriteStrings &&
  5241. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  5242. CmdArgs.push_back("-fconst-strings");
  5243. }
  5244. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  5245. // during C++ compilation, which it is by default. GCC keeps this define even
  5246. // in the presence of '-w', match this behavior bug-for-bug.
  5247. if (types::isCXX(InputType) &&
  5248. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  5249. true)) {
  5250. CmdArgs.push_back("-fdeprecated-macro");
  5251. }
  5252. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  5253. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  5254. if (Asm->getOption().matches(options::OPT_fasm))
  5255. CmdArgs.push_back("-fgnu-keywords");
  5256. else
  5257. CmdArgs.push_back("-fno-gnu-keywords");
  5258. }
  5259. if (!ShouldEnableAutolink(Args, TC, JA))
  5260. CmdArgs.push_back("-fno-autolink");
  5261. // Add in -fdebug-compilation-dir if necessary.
  5262. const char *DebugCompilationDir =
  5263. addDebugCompDirArg(Args, CmdArgs, D.getVFS());
  5264. addDebugPrefixMapArg(D, TC, Args, CmdArgs);
  5265. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  5266. options::OPT_ftemplate_depth_EQ)) {
  5267. CmdArgs.push_back("-ftemplate-depth");
  5268. CmdArgs.push_back(A->getValue());
  5269. }
  5270. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  5271. CmdArgs.push_back("-foperator-arrow-depth");
  5272. CmdArgs.push_back(A->getValue());
  5273. }
  5274. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  5275. CmdArgs.push_back("-fconstexpr-depth");
  5276. CmdArgs.push_back(A->getValue());
  5277. }
  5278. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  5279. CmdArgs.push_back("-fconstexpr-steps");
  5280. CmdArgs.push_back(A->getValue());
  5281. }
  5282. Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
  5283. if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
  5284. CmdArgs.push_back("-fexperimental-new-constant-interpreter");
  5285. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  5286. CmdArgs.push_back("-fbracket-depth");
  5287. CmdArgs.push_back(A->getValue());
  5288. }
  5289. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  5290. options::OPT_Wlarge_by_value_copy_def)) {
  5291. if (A->getNumValues()) {
  5292. StringRef bytes = A->getValue();
  5293. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  5294. } else
  5295. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  5296. }
  5297. if (Args.hasArg(options::OPT_relocatable_pch))
  5298. CmdArgs.push_back("-relocatable-pch");
  5299. if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
  5300. static const char *kCFABIs[] = {
  5301. "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
  5302. };
  5303. if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
  5304. D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
  5305. else
  5306. A->render(Args, CmdArgs);
  5307. }
  5308. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  5309. CmdArgs.push_back("-fconstant-string-class");
  5310. CmdArgs.push_back(A->getValue());
  5311. }
  5312. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  5313. CmdArgs.push_back("-ftabstop");
  5314. CmdArgs.push_back(A->getValue());
  5315. }
  5316. Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
  5317. options::OPT_fno_stack_size_section);
  5318. if (Args.hasArg(options::OPT_fstack_usage)) {
  5319. CmdArgs.push_back("-stack-usage-file");
  5320. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  5321. SmallString<128> OutputFilename(OutputOpt->getValue());
  5322. llvm::sys::path::replace_extension(OutputFilename, "su");
  5323. CmdArgs.push_back(Args.MakeArgString(OutputFilename));
  5324. } else
  5325. CmdArgs.push_back(
  5326. Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
  5327. }
  5328. CmdArgs.push_back("-ferror-limit");
  5329. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  5330. CmdArgs.push_back(A->getValue());
  5331. else
  5332. CmdArgs.push_back("19");
  5333. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  5334. CmdArgs.push_back("-fmacro-backtrace-limit");
  5335. CmdArgs.push_back(A->getValue());
  5336. }
  5337. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  5338. CmdArgs.push_back("-ftemplate-backtrace-limit");
  5339. CmdArgs.push_back(A->getValue());
  5340. }
  5341. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  5342. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  5343. CmdArgs.push_back(A->getValue());
  5344. }
  5345. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  5346. CmdArgs.push_back("-fspell-checking-limit");
  5347. CmdArgs.push_back(A->getValue());
  5348. }
  5349. // Pass -fmessage-length=.
  5350. unsigned MessageLength = 0;
  5351. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  5352. StringRef V(A->getValue());
  5353. if (V.getAsInteger(0, MessageLength))
  5354. D.Diag(diag::err_drv_invalid_argument_to_option)
  5355. << V << A->getOption().getName();
  5356. } else {
  5357. // If -fmessage-length=N was not specified, determine whether this is a
  5358. // terminal and, if so, implicitly define -fmessage-length appropriately.
  5359. MessageLength = llvm::sys::Process::StandardErrColumns();
  5360. }
  5361. if (MessageLength != 0)
  5362. CmdArgs.push_back(
  5363. Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
  5364. if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
  5365. CmdArgs.push_back(
  5366. Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
  5367. if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
  5368. CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
  5369. Twine(A->getValue(0))));
  5370. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  5371. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  5372. options::OPT_fvisibility_ms_compat)) {
  5373. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  5374. A->render(Args, CmdArgs);
  5375. } else {
  5376. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  5377. CmdArgs.push_back("-fvisibility=hidden");
  5378. CmdArgs.push_back("-ftype-visibility=default");
  5379. }
  5380. } else if (IsOpenMPDevice) {
  5381. // When compiling for the OpenMP device we want protected visibility by
  5382. // default. This prevents the device from accidentally preempting code on
  5383. // the host, makes the system more robust, and improves performance.
  5384. CmdArgs.push_back("-fvisibility=protected");
  5385. }
  5386. // PS4/PS5 process these options in addClangTargetOptions.
  5387. if (!RawTriple.isPS()) {
  5388. if (const Arg *A =
  5389. Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
  5390. options::OPT_fno_visibility_from_dllstorageclass)) {
  5391. if (A->getOption().matches(
  5392. options::OPT_fvisibility_from_dllstorageclass)) {
  5393. CmdArgs.push_back("-fvisibility-from-dllstorageclass");
  5394. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
  5395. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
  5396. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
  5397. Args.AddLastArg(CmdArgs,
  5398. options::OPT_fvisibility_externs_nodllstorageclass_EQ);
  5399. }
  5400. }
  5401. }
  5402. if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) {
  5403. if (Triple.isOSAIX())
  5404. CmdArgs.push_back("-mignore-xcoff-visibility");
  5405. else
  5406. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5407. << A->getAsString(Args) << TripleStr;
  5408. }
  5409. if (const Arg *A =
  5410. Args.getLastArg(options::OPT_mdefault_visibility_export_mapping_EQ)) {
  5411. if (Triple.isOSAIX())
  5412. A->render(Args, CmdArgs);
  5413. else
  5414. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5415. << A->getAsString(Args) << TripleStr;
  5416. }
  5417. if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
  5418. options::OPT_fno_visibility_inlines_hidden, false))
  5419. CmdArgs.push_back("-fvisibility-inlines-hidden");
  5420. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
  5421. options::OPT_fno_visibility_inlines_hidden_static_local_var);
  5422. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
  5423. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  5424. if (Args.hasFlag(options::OPT_fnew_infallible,
  5425. options::OPT_fno_new_infallible, false))
  5426. CmdArgs.push_back("-fnew-infallible");
  5427. if (Args.hasFlag(options::OPT_fno_operator_names,
  5428. options::OPT_foperator_names, false))
  5429. CmdArgs.push_back("-fno-operator-names");
  5430. // Forward -f (flag) options which we can pass directly.
  5431. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  5432. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  5433. Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
  5434. Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
  5435. options::OPT_fno_emulated_tls);
  5436. Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
  5437. if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
  5438. // FIXME: There's no reason for this to be restricted to X86. The backend
  5439. // code needs to be changed to include the appropriate function calls
  5440. // automatically.
  5441. if (!Triple.isX86() && !Triple.isAArch64())
  5442. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5443. << A->getAsString(Args) << TripleStr;
  5444. }
  5445. // AltiVec-like language extensions aren't relevant for assembling.
  5446. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
  5447. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  5448. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  5449. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  5450. // Forward flags for OpenMP. We don't do this if the current action is an
  5451. // device offloading action other than OpenMP.
  5452. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  5453. options::OPT_fno_openmp, false) &&
  5454. (JA.isDeviceOffloading(Action::OFK_None) ||
  5455. JA.isDeviceOffloading(Action::OFK_OpenMP))) {
  5456. switch (D.getOpenMPRuntime(Args)) {
  5457. case Driver::OMPRT_OMP:
  5458. case Driver::OMPRT_IOMP5:
  5459. // Clang can generate useful OpenMP code for these two runtime libraries.
  5460. CmdArgs.push_back("-fopenmp");
  5461. // If no option regarding the use of TLS in OpenMP codegeneration is
  5462. // given, decide a default based on the target. Otherwise rely on the
  5463. // options and pass the right information to the frontend.
  5464. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  5465. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  5466. CmdArgs.push_back("-fnoopenmp-use-tls");
  5467. Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
  5468. options::OPT_fno_openmp_simd);
  5469. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
  5470. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
  5471. if (!Args.hasFlag(options::OPT_fopenmp_extensions,
  5472. options::OPT_fno_openmp_extensions, /*Default=*/true))
  5473. CmdArgs.push_back("-fno-openmp-extensions");
  5474. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
  5475. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
  5476. Args.AddAllArgs(CmdArgs,
  5477. options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
  5478. if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
  5479. options::OPT_fno_openmp_optimistic_collapse,
  5480. /*Default=*/false))
  5481. CmdArgs.push_back("-fopenmp-optimistic-collapse");
  5482. // When in OpenMP offloading mode with NVPTX target, forward
  5483. // cuda-mode flag
  5484. if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
  5485. options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
  5486. CmdArgs.push_back("-fopenmp-cuda-mode");
  5487. // When in OpenMP offloading mode, enable debugging on the device.
  5488. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
  5489. if (Args.hasFlag(options::OPT_fopenmp_target_debug,
  5490. options::OPT_fno_openmp_target_debug, /*Default=*/false))
  5491. CmdArgs.push_back("-fopenmp-target-debug");
  5492. // When in OpenMP offloading mode, forward assumptions information about
  5493. // thread and team counts in the device.
  5494. if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
  5495. options::OPT_fno_openmp_assume_teams_oversubscription,
  5496. /*Default=*/false))
  5497. CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
  5498. if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
  5499. options::OPT_fno_openmp_assume_threads_oversubscription,
  5500. /*Default=*/false))
  5501. CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
  5502. if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
  5503. CmdArgs.push_back("-fopenmp-assume-no-thread-state");
  5504. if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
  5505. CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
  5506. if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
  5507. CmdArgs.push_back("-fopenmp-offload-mandatory");
  5508. break;
  5509. default:
  5510. // By default, if Clang doesn't know how to generate useful OpenMP code
  5511. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  5512. // down to the actual compilation.
  5513. // FIXME: It would be better to have a mode which *only* omits IR
  5514. // generation based on the OpenMP support so that we get consistent
  5515. // semantic analysis, etc.
  5516. break;
  5517. }
  5518. } else {
  5519. Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
  5520. options::OPT_fno_openmp_simd);
  5521. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
  5522. Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
  5523. options::OPT_fno_openmp_extensions);
  5524. }
  5525. // Forward the new driver to change offloading code generation.
  5526. if (Args.hasFlag(options::OPT_offload_new_driver,
  5527. options::OPT_no_offload_new_driver, false))
  5528. CmdArgs.push_back("--offload-new-driver");
  5529. SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
  5530. const XRayArgs &XRay = TC.getXRayArgs();
  5531. XRay.addArgs(TC, Args, CmdArgs, InputType);
  5532. for (const auto &Filename :
  5533. Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
  5534. if (D.getVFS().exists(Filename))
  5535. CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
  5536. else
  5537. D.Diag(clang::diag::err_drv_no_such_file) << Filename;
  5538. }
  5539. if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
  5540. StringRef S0 = A->getValue(), S = S0;
  5541. unsigned Size, Offset = 0;
  5542. if (!Triple.isAArch64() && !Triple.isRISCV() && !Triple.isX86())
  5543. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5544. << A->getAsString(Args) << TripleStr;
  5545. else if (S.consumeInteger(10, Size) ||
  5546. (!S.empty() && (!S.consume_front(",") ||
  5547. S.consumeInteger(10, Offset) || !S.empty())))
  5548. D.Diag(diag::err_drv_invalid_argument_to_option)
  5549. << S0 << A->getOption().getName();
  5550. else if (Size < Offset)
  5551. D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
  5552. else {
  5553. CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
  5554. CmdArgs.push_back(Args.MakeArgString(
  5555. "-fpatchable-function-entry-offset=" + Twine(Offset)));
  5556. }
  5557. }
  5558. Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
  5559. if (TC.SupportsProfiling()) {
  5560. Args.AddLastArg(CmdArgs, options::OPT_pg);
  5561. llvm::Triple::ArchType Arch = TC.getArch();
  5562. if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
  5563. if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
  5564. A->render(Args, CmdArgs);
  5565. else
  5566. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5567. << A->getAsString(Args) << TripleStr;
  5568. }
  5569. if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
  5570. if (Arch == llvm::Triple::systemz)
  5571. A->render(Args, CmdArgs);
  5572. else
  5573. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5574. << A->getAsString(Args) << TripleStr;
  5575. }
  5576. if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
  5577. if (Arch == llvm::Triple::systemz)
  5578. A->render(Args, CmdArgs);
  5579. else
  5580. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5581. << A->getAsString(Args) << TripleStr;
  5582. }
  5583. }
  5584. if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
  5585. if (!TC.getTriple().isOSAIX() && !TC.getTriple().isOSOpenBSD()) {
  5586. D.Diag(diag::err_drv_unsupported_opt_for_target)
  5587. << A->getAsString(Args) << TripleStr;
  5588. }
  5589. }
  5590. if (Args.getLastArg(options::OPT_fapple_kext) ||
  5591. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  5592. CmdArgs.push_back("-fapple-kext");
  5593. Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
  5594. Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
  5595. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  5596. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  5597. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  5598. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  5599. Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
  5600. Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
  5601. Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
  5602. Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_EQ);
  5603. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  5604. Args.AddLastArg(CmdArgs, options::OPT_malign_double);
  5605. Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
  5606. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  5607. CmdArgs.push_back("-ftrapv-handler");
  5608. CmdArgs.push_back(A->getValue());
  5609. }
  5610. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  5611. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  5612. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  5613. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  5614. if (A->getOption().matches(options::OPT_fwrapv))
  5615. CmdArgs.push_back("-fwrapv");
  5616. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  5617. options::OPT_fno_strict_overflow)) {
  5618. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  5619. CmdArgs.push_back("-fwrapv");
  5620. }
  5621. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  5622. options::OPT_fno_reroll_loops))
  5623. if (A->getOption().matches(options::OPT_freroll_loops))
  5624. CmdArgs.push_back("-freroll-loops");
  5625. Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
  5626. options::OPT_fno_finite_loops);
  5627. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  5628. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  5629. options::OPT_fno_unroll_loops);
  5630. Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
  5631. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  5632. Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
  5633. options::OPT_mno_speculative_load_hardening);
  5634. RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
  5635. RenderSCPOptions(TC, Args, CmdArgs);
  5636. RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
  5637. Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
  5638. Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
  5639. options::OPT_mno_stackrealign);
  5640. if (Args.hasArg(options::OPT_mstack_alignment)) {
  5641. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  5642. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  5643. }
  5644. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  5645. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  5646. if (!Size.empty())
  5647. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  5648. else
  5649. CmdArgs.push_back("-mstack-probe-size=0");
  5650. }
  5651. Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
  5652. options::OPT_mno_stack_arg_probe);
  5653. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  5654. options::OPT_mno_restrict_it)) {
  5655. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  5656. CmdArgs.push_back("-mllvm");
  5657. CmdArgs.push_back("-arm-restrict-it");
  5658. } else {
  5659. CmdArgs.push_back("-mllvm");
  5660. CmdArgs.push_back("-arm-default-it");
  5661. }
  5662. }
  5663. // Forward -cl options to -cc1
  5664. RenderOpenCLOptions(Args, CmdArgs, InputType);
  5665. // Forward hlsl options to -cc1
  5666. RenderHLSLOptions(Args, CmdArgs, InputType);
  5667. if (IsHIP) {
  5668. if (Args.hasFlag(options::OPT_fhip_new_launch_api,
  5669. options::OPT_fno_hip_new_launch_api, true))
  5670. CmdArgs.push_back("-fhip-new-launch-api");
  5671. if (Args.hasFlag(options::OPT_fgpu_allow_device_init,
  5672. options::OPT_fno_gpu_allow_device_init, false))
  5673. CmdArgs.push_back("-fgpu-allow-device-init");
  5674. Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
  5675. options::OPT_fno_hip_kernel_arg_name);
  5676. }
  5677. if (IsCuda || IsHIP) {
  5678. if (IsRDCMode)
  5679. CmdArgs.push_back("-fgpu-rdc");
  5680. if (Args.hasFlag(options::OPT_fgpu_defer_diag,
  5681. options::OPT_fno_gpu_defer_diag, false))
  5682. CmdArgs.push_back("-fgpu-defer-diag");
  5683. if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
  5684. options::OPT_fno_gpu_exclude_wrong_side_overloads,
  5685. false)) {
  5686. CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
  5687. CmdArgs.push_back("-fgpu-defer-diag");
  5688. }
  5689. }
  5690. // Forward -nogpulib to -cc1.
  5691. if (Args.hasArg(options::OPT_nogpulib))
  5692. CmdArgs.push_back("-nogpulib");
  5693. if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
  5694. CmdArgs.push_back(
  5695. Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
  5696. }
  5697. if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
  5698. CmdArgs.push_back(
  5699. Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
  5700. Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
  5701. // Forward -f options with positive and negative forms; we translate these by
  5702. // hand. Do not propagate PGO options to the GPU-side compilations as the
  5703. // profile info is for the host-side compilation only.
  5704. if (!(IsCudaDevice || IsHIPDevice)) {
  5705. if (Arg *A = getLastProfileSampleUseArg(Args)) {
  5706. auto *PGOArg = Args.getLastArg(
  5707. options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
  5708. options::OPT_fcs_profile_generate,
  5709. options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
  5710. options::OPT_fprofile_use_EQ);
  5711. if (PGOArg)
  5712. D.Diag(diag::err_drv_argument_not_allowed_with)
  5713. << "SampleUse with PGO options";
  5714. StringRef fname = A->getValue();
  5715. if (!llvm::sys::fs::exists(fname))
  5716. D.Diag(diag::err_drv_no_such_file) << fname;
  5717. else
  5718. A->render(Args, CmdArgs);
  5719. }
  5720. Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
  5721. if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
  5722. options::OPT_fno_pseudo_probe_for_profiling, false)) {
  5723. CmdArgs.push_back("-fpseudo-probe-for-profiling");
  5724. // Enforce -funique-internal-linkage-names if it's not explicitly turned
  5725. // off.
  5726. if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
  5727. options::OPT_fno_unique_internal_linkage_names, true))
  5728. CmdArgs.push_back("-funique-internal-linkage-names");
  5729. }
  5730. }
  5731. RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
  5732. Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
  5733. options::OPT_fno_assume_sane_operator_new);
  5734. // -fblocks=0 is default.
  5735. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  5736. TC.IsBlocksDefault()) ||
  5737. (Args.hasArg(options::OPT_fgnu_runtime) &&
  5738. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  5739. !Args.hasArg(options::OPT_fno_blocks))) {
  5740. CmdArgs.push_back("-fblocks");
  5741. if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
  5742. CmdArgs.push_back("-fblocks-runtime-optional");
  5743. }
  5744. // -fencode-extended-block-signature=1 is default.
  5745. if (TC.IsEncodeExtendedBlockSignatureDefault())
  5746. CmdArgs.push_back("-fencode-extended-block-signature");
  5747. if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
  5748. false) &&
  5749. types::isCXX(InputType)) {
  5750. D.Diag(diag::warn_deperecated_fcoroutines_ts_flag);
  5751. CmdArgs.push_back("-fcoroutines-ts");
  5752. }
  5753. if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
  5754. options::OPT_fno_coro_aligned_allocation, false) &&
  5755. types::isCXX(InputType))
  5756. CmdArgs.push_back("-fcoro-aligned-allocation");
  5757. Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
  5758. options::OPT_fno_double_square_bracket_attributes);
  5759. Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
  5760. options::OPT_fno_access_control);
  5761. Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
  5762. options::OPT_fno_elide_constructors);
  5763. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  5764. if (KernelOrKext || (types::isCXX(InputType) &&
  5765. (RTTIMode == ToolChain::RM_Disabled)))
  5766. CmdArgs.push_back("-fno-rtti");
  5767. // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
  5768. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  5769. TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
  5770. CmdArgs.push_back("-fshort-enums");
  5771. RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
  5772. // -fuse-cxa-atexit is default.
  5773. if (!Args.hasFlag(
  5774. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  5775. !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
  5776. ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
  5777. RawTriple.hasEnvironment())) ||
  5778. KernelOrKext)
  5779. CmdArgs.push_back("-fno-use-cxa-atexit");
  5780. if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
  5781. options::OPT_fno_register_global_dtors_with_atexit,
  5782. RawTriple.isOSDarwin() && !KernelOrKext))
  5783. CmdArgs.push_back("-fregister-global-dtors-with-atexit");
  5784. Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
  5785. options::OPT_fno_use_line_directives);
  5786. // -fno-minimize-whitespace is default.
  5787. if (Args.hasFlag(options::OPT_fminimize_whitespace,
  5788. options::OPT_fno_minimize_whitespace, false)) {
  5789. types::ID InputType = Inputs[0].getType();
  5790. if (!isDerivedFromC(InputType))
  5791. D.Diag(diag::err_drv_minws_unsupported_input_type)
  5792. << types::getTypeName(InputType);
  5793. CmdArgs.push_back("-fminimize-whitespace");
  5794. }
  5795. // -fms-extensions=0 is default.
  5796. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  5797. IsWindowsMSVC))
  5798. CmdArgs.push_back("-fms-extensions");
  5799. // -fms-compatibility=0 is default.
  5800. bool IsMSVCCompat = Args.hasFlag(
  5801. options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
  5802. (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  5803. options::OPT_fno_ms_extensions, true)));
  5804. if (IsMSVCCompat)
  5805. CmdArgs.push_back("-fms-compatibility");
  5806. if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
  5807. Args.hasArg(options::OPT_fms_runtime_lib_EQ))
  5808. ProcessVSRuntimeLibrary(Args, CmdArgs);
  5809. // Handle -fgcc-version, if present.
  5810. VersionTuple GNUCVer;
  5811. if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
  5812. // Check that the version has 1 to 3 components and the minor and patch
  5813. // versions fit in two decimal digits.
  5814. StringRef Val = A->getValue();
  5815. Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
  5816. bool Invalid = GNUCVer.tryParse(Val);
  5817. unsigned Minor = GNUCVer.getMinor().value_or(0);
  5818. unsigned Patch = GNUCVer.getSubminor().value_or(0);
  5819. if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
  5820. D.Diag(diag::err_drv_invalid_value)
  5821. << A->getAsString(Args) << A->getValue();
  5822. }
  5823. } else if (!IsMSVCCompat) {
  5824. // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
  5825. GNUCVer = VersionTuple(4, 2, 1);
  5826. }
  5827. if (!GNUCVer.empty()) {
  5828. CmdArgs.push_back(
  5829. Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
  5830. }
  5831. VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
  5832. if (!MSVT.empty())
  5833. CmdArgs.push_back(
  5834. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  5835. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  5836. if (ImplyVCPPCVer) {
  5837. StringRef LanguageStandard;
  5838. if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
  5839. Std = StdArg;
  5840. LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
  5841. .Case("c11", "-std=c11")
  5842. .Case("c17", "-std=c17")
  5843. .Default("");
  5844. if (LanguageStandard.empty())
  5845. D.Diag(clang::diag::warn_drv_unused_argument)
  5846. << StdArg->getAsString(Args);
  5847. }
  5848. CmdArgs.push_back(LanguageStandard.data());
  5849. }
  5850. if (ImplyVCPPCXXVer) {
  5851. StringRef LanguageStandard;
  5852. if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
  5853. Std = StdArg;
  5854. LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
  5855. .Case("c++14", "-std=c++14")
  5856. .Case("c++17", "-std=c++17")
  5857. .Case("c++20", "-std=c++20")
  5858. .Case("c++latest", "-std=c++2b")
  5859. .Default("");
  5860. if (LanguageStandard.empty())
  5861. D.Diag(clang::diag::warn_drv_unused_argument)
  5862. << StdArg->getAsString(Args);
  5863. }
  5864. if (LanguageStandard.empty()) {
  5865. if (IsMSVC2015Compatible)
  5866. LanguageStandard = "-std=c++14";
  5867. else
  5868. LanguageStandard = "-std=c++11";
  5869. }
  5870. CmdArgs.push_back(LanguageStandard.data());
  5871. }
  5872. Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
  5873. options::OPT_fno_borland_extensions);
  5874. // -fno-declspec is default, except for PS4/PS5.
  5875. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  5876. RawTriple.isPS()))
  5877. CmdArgs.push_back("-fdeclspec");
  5878. else if (Args.hasArg(options::OPT_fno_declspec))
  5879. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  5880. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  5881. // than 19.
  5882. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  5883. options::OPT_fno_threadsafe_statics,
  5884. !types::isOpenCL(InputType) &&
  5885. (!IsWindowsMSVC || IsMSVC2015Compatible)))
  5886. CmdArgs.push_back("-fno-threadsafe-statics");
  5887. // -fno-delayed-template-parsing is default, except when targeting MSVC.
  5888. // Many old Windows SDK versions require this to parse.
  5889. // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
  5890. // compiler. We should be able to disable this by default at some point.
  5891. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  5892. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  5893. CmdArgs.push_back("-fdelayed-template-parsing");
  5894. // -fgnu-keywords default varies depending on language; only pass if
  5895. // specified.
  5896. Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
  5897. options::OPT_fno_gnu_keywords);
  5898. Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
  5899. options::OPT_fno_gnu89_inline);
  5900. const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
  5901. options::OPT_finline_hint_functions,
  5902. options::OPT_fno_inline_functions);
  5903. if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
  5904. if (A->getOption().matches(options::OPT_fno_inline))
  5905. A->render(Args, CmdArgs);
  5906. } else if (InlineArg) {
  5907. InlineArg->render(Args, CmdArgs);
  5908. }
  5909. Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
  5910. bool HaveModules =
  5911. RenderModulesOptions(C, D, Args, Input, Output, Std, CmdArgs);
  5912. if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
  5913. options::OPT_fno_pch_validate_input_files_content, false))
  5914. CmdArgs.push_back("-fvalidate-ast-input-files-content");
  5915. if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
  5916. options::OPT_fno_pch_instantiate_templates, false))
  5917. CmdArgs.push_back("-fpch-instantiate-templates");
  5918. if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
  5919. false))
  5920. CmdArgs.push_back("-fmodules-codegen");
  5921. if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
  5922. false))
  5923. CmdArgs.push_back("-fmodules-debuginfo");
  5924. ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
  5925. RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
  5926. Input, CmdArgs);
  5927. if (types::isObjC(Input.getType()) &&
  5928. Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
  5929. options::OPT_fno_objc_encode_cxx_class_template_spec,
  5930. !Runtime.isNeXTFamily()))
  5931. CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
  5932. if (Args.hasFlag(options::OPT_fapplication_extension,
  5933. options::OPT_fno_application_extension, false))
  5934. CmdArgs.push_back("-fapplication-extension");
  5935. // Handle GCC-style exception args.
  5936. bool EH = false;
  5937. if (!C.getDriver().IsCLMode())
  5938. EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
  5939. // Handle exception personalities
  5940. Arg *A = Args.getLastArg(
  5941. options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
  5942. options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
  5943. if (A) {
  5944. const Option &Opt = A->getOption();
  5945. if (Opt.matches(options::OPT_fsjlj_exceptions))
  5946. CmdArgs.push_back("-exception-model=sjlj");
  5947. if (Opt.matches(options::OPT_fseh_exceptions))
  5948. CmdArgs.push_back("-exception-model=seh");
  5949. if (Opt.matches(options::OPT_fdwarf_exceptions))
  5950. CmdArgs.push_back("-exception-model=dwarf");
  5951. if (Opt.matches(options::OPT_fwasm_exceptions))
  5952. CmdArgs.push_back("-exception-model=wasm");
  5953. } else {
  5954. switch (TC.GetExceptionModel(Args)) {
  5955. default:
  5956. break;
  5957. case llvm::ExceptionHandling::DwarfCFI:
  5958. CmdArgs.push_back("-exception-model=dwarf");
  5959. break;
  5960. case llvm::ExceptionHandling::SjLj:
  5961. CmdArgs.push_back("-exception-model=sjlj");
  5962. break;
  5963. case llvm::ExceptionHandling::WinEH:
  5964. CmdArgs.push_back("-exception-model=seh");
  5965. break;
  5966. }
  5967. }
  5968. // C++ "sane" operator new.
  5969. Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
  5970. options::OPT_fno_assume_sane_operator_new);
  5971. // -frelaxed-template-template-args is off by default, as it is a severe
  5972. // breaking change until a corresponding change to template partial ordering
  5973. // is provided.
  5974. Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
  5975. options::OPT_fno_relaxed_template_template_args);
  5976. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  5977. // most platforms.
  5978. Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
  5979. options::OPT_fno_sized_deallocation);
  5980. // -faligned-allocation is on by default in C++17 onwards and otherwise off
  5981. // by default.
  5982. if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
  5983. options::OPT_fno_aligned_allocation,
  5984. options::OPT_faligned_new_EQ)) {
  5985. if (A->getOption().matches(options::OPT_fno_aligned_allocation))
  5986. CmdArgs.push_back("-fno-aligned-allocation");
  5987. else
  5988. CmdArgs.push_back("-faligned-allocation");
  5989. }
  5990. // The default new alignment can be specified using a dedicated option or via
  5991. // a GCC-compatible option that also turns on aligned allocation.
  5992. if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
  5993. options::OPT_faligned_new_EQ))
  5994. CmdArgs.push_back(
  5995. Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
  5996. // -fconstant-cfstrings is default, and may be subject to argument translation
  5997. // on Darwin.
  5998. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  5999. options::OPT_fno_constant_cfstrings, true) ||
  6000. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  6001. options::OPT_mno_constant_cfstrings, true))
  6002. CmdArgs.push_back("-fno-constant-cfstrings");
  6003. Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
  6004. options::OPT_fno_pascal_strings);
  6005. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  6006. // -fno-pack-struct doesn't apply to -fpack-struct=.
  6007. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  6008. std::string PackStructStr = "-fpack-struct=";
  6009. PackStructStr += A->getValue();
  6010. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  6011. } else if (Args.hasFlag(options::OPT_fpack_struct,
  6012. options::OPT_fno_pack_struct, false)) {
  6013. CmdArgs.push_back("-fpack-struct=1");
  6014. }
  6015. // Handle -fmax-type-align=N and -fno-type-align
  6016. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  6017. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  6018. if (!SkipMaxTypeAlign) {
  6019. std::string MaxTypeAlignStr = "-fmax-type-align=";
  6020. MaxTypeAlignStr += A->getValue();
  6021. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  6022. }
  6023. } else if (RawTriple.isOSDarwin()) {
  6024. if (!SkipMaxTypeAlign) {
  6025. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  6026. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  6027. }
  6028. }
  6029. if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
  6030. CmdArgs.push_back("-Qn");
  6031. // -fno-common is the default, set -fcommon only when that flag is set.
  6032. Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
  6033. // -fsigned-bitfields is default, and clang doesn't yet support
  6034. // -funsigned-bitfields.
  6035. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  6036. options::OPT_funsigned_bitfields, true))
  6037. D.Diag(diag::warn_drv_clang_unsupported)
  6038. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  6039. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  6040. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
  6041. D.Diag(diag::err_drv_clang_unsupported)
  6042. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  6043. // -finput_charset=UTF-8 is default. Reject others
  6044. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  6045. StringRef value = inputCharset->getValue();
  6046. if (!value.equals_insensitive("utf-8"))
  6047. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  6048. << value;
  6049. }
  6050. // -fexec_charset=UTF-8 is default. Reject others
  6051. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  6052. StringRef value = execCharset->getValue();
  6053. if (!value.equals_insensitive("utf-8"))
  6054. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  6055. << value;
  6056. }
  6057. RenderDiagnosticsOptions(D, Args, CmdArgs);
  6058. Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
  6059. options::OPT_fno_asm_blocks);
  6060. Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
  6061. options::OPT_fno_gnu_inline_asm);
  6062. // Enable vectorization per default according to the optimization level
  6063. // selected. For optimization levels that want vectorization we use the alias
  6064. // option to simplify the hasFlag logic.
  6065. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  6066. OptSpecifier VectorizeAliasOption =
  6067. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  6068. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  6069. options::OPT_fno_vectorize, EnableVec))
  6070. CmdArgs.push_back("-vectorize-loops");
  6071. // -fslp-vectorize is enabled based on the optimization level selected.
  6072. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  6073. OptSpecifier SLPVectAliasOption =
  6074. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  6075. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  6076. options::OPT_fno_slp_vectorize, EnableSLPVec))
  6077. CmdArgs.push_back("-vectorize-slp");
  6078. ParseMPreferVectorWidth(D, Args, CmdArgs);
  6079. Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
  6080. Args.AddLastArg(CmdArgs,
  6081. options::OPT_fsanitize_undefined_strip_path_components_EQ);
  6082. // -fdollars-in-identifiers default varies depending on platform and
  6083. // language; only pass if specified.
  6084. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  6085. options::OPT_fno_dollars_in_identifiers)) {
  6086. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  6087. CmdArgs.push_back("-fdollars-in-identifiers");
  6088. else
  6089. CmdArgs.push_back("-fno-dollars-in-identifiers");
  6090. }
  6091. Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
  6092. options::OPT_fno_apple_pragma_pack);
  6093. if (Args.hasFlag(options::OPT_fxl_pragma_pack,
  6094. options::OPT_fno_xl_pragma_pack, RawTriple.isOSAIX()))
  6095. CmdArgs.push_back("-fxl-pragma-pack");
  6096. // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
  6097. if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
  6098. renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
  6099. bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
  6100. options::OPT_fno_rewrite_imports, false);
  6101. if (RewriteImports)
  6102. CmdArgs.push_back("-frewrite-imports");
  6103. Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
  6104. options::OPT_fno_directives_only);
  6105. // Enable rewrite includes if the user's asked for it or if we're generating
  6106. // diagnostics.
  6107. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  6108. // nice to enable this when doing a crashdump for modules as well.
  6109. if (Args.hasFlag(options::OPT_frewrite_includes,
  6110. options::OPT_fno_rewrite_includes, false) ||
  6111. (C.isForDiagnostics() && !HaveModules))
  6112. CmdArgs.push_back("-frewrite-includes");
  6113. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  6114. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  6115. options::OPT_traditional_cpp)) {
  6116. if (isa<PreprocessJobAction>(JA))
  6117. CmdArgs.push_back("-traditional-cpp");
  6118. else
  6119. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  6120. }
  6121. Args.AddLastArg(CmdArgs, options::OPT_dM);
  6122. Args.AddLastArg(CmdArgs, options::OPT_dD);
  6123. Args.AddLastArg(CmdArgs, options::OPT_dI);
  6124. Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
  6125. // Handle serialized diagnostics.
  6126. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  6127. CmdArgs.push_back("-serialize-diagnostic-file");
  6128. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  6129. }
  6130. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  6131. CmdArgs.push_back("-fretain-comments-from-system-headers");
  6132. // Forward -fcomment-block-commands to -cc1.
  6133. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  6134. // Forward -fparse-all-comments to -cc1.
  6135. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  6136. // Turn -fplugin=name.so into -load name.so
  6137. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  6138. CmdArgs.push_back("-load");
  6139. CmdArgs.push_back(A->getValue());
  6140. A->claim();
  6141. }
  6142. // Turn -fplugin-arg-pluginname-key=value into
  6143. // -plugin-arg-pluginname key=value
  6144. // GCC has an actual plugin_argument struct with key/value pairs that it
  6145. // passes to its plugins, but we don't, so just pass it on as-is.
  6146. //
  6147. // The syntax for -fplugin-arg- is ambiguous if both plugin name and
  6148. // argument key are allowed to contain dashes. GCC therefore only
  6149. // allows dashes in the key. We do the same.
  6150. for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
  6151. auto ArgValue = StringRef(A->getValue());
  6152. auto FirstDashIndex = ArgValue.find('-');
  6153. StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
  6154. StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
  6155. A->claim();
  6156. if (FirstDashIndex == StringRef::npos || Arg.empty()) {
  6157. if (PluginName.empty()) {
  6158. D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
  6159. } else {
  6160. D.Diag(diag::warn_drv_missing_plugin_arg)
  6161. << PluginName << A->getAsString(Args);
  6162. }
  6163. continue;
  6164. }
  6165. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
  6166. CmdArgs.push_back(Args.MakeArgString(Arg));
  6167. }
  6168. // Forward -fpass-plugin=name.so to -cc1.
  6169. for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
  6170. CmdArgs.push_back(
  6171. Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
  6172. A->claim();
  6173. }
  6174. // Setup statistics file output.
  6175. SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
  6176. if (!StatsFile.empty())
  6177. CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
  6178. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  6179. // parser.
  6180. for (auto Arg : Args.filtered(options::OPT_Xclang)) {
  6181. Arg->claim();
  6182. // -finclude-default-header flag is for preprocessor,
  6183. // do not pass it to other cc1 commands when save-temps is enabled
  6184. if (C.getDriver().isSaveTempsEnabled() &&
  6185. !isa<PreprocessJobAction>(JA)) {
  6186. if (StringRef(Arg->getValue()) == "-finclude-default-header")
  6187. continue;
  6188. }
  6189. CmdArgs.push_back(Arg->getValue());
  6190. }
  6191. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  6192. A->claim();
  6193. // We translate this by hand to the -cc1 argument, since nightly test uses
  6194. // it and developers have been trained to spell it with -mllvm. Both
  6195. // spellings are now deprecated and should be removed.
  6196. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  6197. CmdArgs.push_back("-disable-llvm-optzns");
  6198. } else {
  6199. A->render(Args, CmdArgs);
  6200. }
  6201. }
  6202. // With -save-temps, we want to save the unoptimized bitcode output from the
  6203. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  6204. // by the frontend.
  6205. // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
  6206. // has slightly different breakdown between stages.
  6207. // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
  6208. // pristine IR generated by the frontend. Ideally, a new compile action should
  6209. // be added so both IR can be captured.
  6210. if ((C.getDriver().isSaveTempsEnabled() ||
  6211. JA.isHostOffloading(Action::OFK_OpenMP)) &&
  6212. !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
  6213. isa<CompileJobAction>(JA))
  6214. CmdArgs.push_back("-disable-llvm-passes");
  6215. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  6216. const char *Exec = D.getClangProgramPath();
  6217. // Optionally embed the -cc1 level arguments into the debug info or a
  6218. // section, for build analysis.
  6219. // Also record command line arguments into the debug info if
  6220. // -grecord-gcc-switches options is set on.
  6221. // By default, -gno-record-gcc-switches is set on and no recording.
  6222. auto GRecordSwitches =
  6223. Args.hasFlag(options::OPT_grecord_command_line,
  6224. options::OPT_gno_record_command_line, false);
  6225. auto FRecordSwitches =
  6226. Args.hasFlag(options::OPT_frecord_command_line,
  6227. options::OPT_fno_record_command_line, false);
  6228. if (FRecordSwitches && !Triple.isOSBinFormatELF())
  6229. D.Diag(diag::err_drv_unsupported_opt_for_target)
  6230. << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
  6231. << TripleStr;
  6232. if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
  6233. ArgStringList OriginalArgs;
  6234. for (const auto &Arg : Args)
  6235. Arg->render(Args, OriginalArgs);
  6236. SmallString<256> Flags;
  6237. EscapeSpacesAndBackslashes(Exec, Flags);
  6238. for (const char *OriginalArg : OriginalArgs) {
  6239. SmallString<128> EscapedArg;
  6240. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  6241. Flags += " ";
  6242. Flags += EscapedArg;
  6243. }
  6244. auto FlagsArgString = Args.MakeArgString(Flags);
  6245. if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
  6246. CmdArgs.push_back("-dwarf-debug-flags");
  6247. CmdArgs.push_back(FlagsArgString);
  6248. }
  6249. if (FRecordSwitches) {
  6250. CmdArgs.push_back("-record-command-line");
  6251. CmdArgs.push_back(FlagsArgString);
  6252. }
  6253. }
  6254. // Host-side offloading compilation receives all device-side outputs. Include
  6255. // them in the host compilation depending on the target. If the host inputs
  6256. // are not empty we use the new-driver scheme, otherwise use the old scheme.
  6257. if ((IsCuda || IsHIP) && CudaDeviceInput) {
  6258. CmdArgs.push_back("-fcuda-include-gpubinary");
  6259. CmdArgs.push_back(CudaDeviceInput->getFilename());
  6260. } else if (!HostOffloadingInputs.empty()) {
  6261. if ((IsCuda || IsHIP) && !IsRDCMode) {
  6262. assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
  6263. CmdArgs.push_back("-fcuda-include-gpubinary");
  6264. CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
  6265. } else {
  6266. for (const InputInfo Input : HostOffloadingInputs)
  6267. CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
  6268. TC.getInputFilename(Input)));
  6269. }
  6270. }
  6271. if (IsCuda) {
  6272. if (Args.hasFlag(options::OPT_fcuda_short_ptr,
  6273. options::OPT_fno_cuda_short_ptr, false))
  6274. CmdArgs.push_back("-fcuda-short-ptr");
  6275. }
  6276. if (IsCuda || IsHIP) {
  6277. // Determine the original source input.
  6278. const Action *SourceAction = &JA;
  6279. while (SourceAction->getKind() != Action::InputClass) {
  6280. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  6281. SourceAction = SourceAction->getInputs()[0];
  6282. }
  6283. auto CUID = cast<InputAction>(SourceAction)->getId();
  6284. if (!CUID.empty())
  6285. CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
  6286. }
  6287. if (IsHIP) {
  6288. CmdArgs.push_back("-fcuda-allow-variadic-functions");
  6289. Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
  6290. }
  6291. if (IsCudaDevice || IsHIPDevice) {
  6292. StringRef InlineThresh =
  6293. Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
  6294. if (!InlineThresh.empty()) {
  6295. std::string ArgStr =
  6296. std::string("-inline-threshold=") + InlineThresh.str();
  6297. CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
  6298. }
  6299. }
  6300. // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
  6301. // to specify the result of the compile phase on the host, so the meaningful
  6302. // device declarations can be identified. Also, -fopenmp-is-device is passed
  6303. // along to tell the frontend that it is generating code for a device, so that
  6304. // only the relevant declarations are emitted.
  6305. if (IsOpenMPDevice) {
  6306. CmdArgs.push_back("-fopenmp-is-device");
  6307. if (OpenMPDeviceInput) {
  6308. CmdArgs.push_back("-fopenmp-host-ir-file-path");
  6309. CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
  6310. }
  6311. }
  6312. if (Triple.isAMDGPU()) {
  6313. handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
  6314. Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
  6315. options::OPT_mno_unsafe_fp_atomics);
  6316. }
  6317. // For all the host OpenMP offloading compile jobs we need to pass the targets
  6318. // information using -fopenmp-targets= option.
  6319. if (JA.isHostOffloading(Action::OFK_OpenMP)) {
  6320. SmallString<128> Targets("-fopenmp-targets=");
  6321. SmallVector<std::string, 4> Triples;
  6322. auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
  6323. std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
  6324. [](auto TC) { return TC.second->getTripleString(); });
  6325. CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
  6326. }
  6327. bool VirtualFunctionElimination =
  6328. Args.hasFlag(options::OPT_fvirtual_function_elimination,
  6329. options::OPT_fno_virtual_function_elimination, false);
  6330. if (VirtualFunctionElimination) {
  6331. // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
  6332. // in the future).
  6333. if (LTOMode != LTOK_Full)
  6334. D.Diag(diag::err_drv_argument_only_allowed_with)
  6335. << "-fvirtual-function-elimination"
  6336. << "-flto=full";
  6337. CmdArgs.push_back("-fvirtual-function-elimination");
  6338. }
  6339. // VFE requires whole-program-vtables, and enables it by default.
  6340. bool WholeProgramVTables = Args.hasFlag(
  6341. options::OPT_fwhole_program_vtables,
  6342. options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
  6343. if (VirtualFunctionElimination && !WholeProgramVTables) {
  6344. D.Diag(diag::err_drv_argument_not_allowed_with)
  6345. << "-fno-whole-program-vtables"
  6346. << "-fvirtual-function-elimination";
  6347. }
  6348. if (WholeProgramVTables) {
  6349. // Propagate -fwhole-program-vtables if this is an LTO compile.
  6350. if (IsUsingLTO)
  6351. CmdArgs.push_back("-fwhole-program-vtables");
  6352. // Check if we passed LTO options but they were suppressed because this is a
  6353. // device offloading action, or we passed device offload LTO options which
  6354. // were suppressed because this is not the device offload action.
  6355. // Otherwise, issue an error.
  6356. else if (!D.isUsingLTO(!IsDeviceOffloadAction))
  6357. D.Diag(diag::err_drv_argument_only_allowed_with)
  6358. << "-fwhole-program-vtables"
  6359. << "-flto";
  6360. }
  6361. bool DefaultsSplitLTOUnit =
  6362. (WholeProgramVTables || SanitizeArgs.needsLTO()) &&
  6363. (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit());
  6364. bool SplitLTOUnit =
  6365. Args.hasFlag(options::OPT_fsplit_lto_unit,
  6366. options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
  6367. if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
  6368. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
  6369. << "-fsanitize=cfi";
  6370. if (SplitLTOUnit)
  6371. CmdArgs.push_back("-fsplit-lto-unit");
  6372. if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
  6373. options::OPT_fno_global_isel)) {
  6374. CmdArgs.push_back("-mllvm");
  6375. if (A->getOption().matches(options::OPT_fglobal_isel)) {
  6376. CmdArgs.push_back("-global-isel=1");
  6377. // GISel is on by default on AArch64 -O0, so don't bother adding
  6378. // the fallback remarks for it. Other combinations will add a warning of
  6379. // some kind.
  6380. bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
  6381. bool IsOptLevelSupported = false;
  6382. Arg *A = Args.getLastArg(options::OPT_O_Group);
  6383. if (Triple.getArch() == llvm::Triple::aarch64) {
  6384. if (!A || A->getOption().matches(options::OPT_O0))
  6385. IsOptLevelSupported = true;
  6386. }
  6387. if (!IsArchSupported || !IsOptLevelSupported) {
  6388. CmdArgs.push_back("-mllvm");
  6389. CmdArgs.push_back("-global-isel-abort=2");
  6390. if (!IsArchSupported)
  6391. D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
  6392. else
  6393. D.Diag(diag::warn_drv_global_isel_incomplete_opt);
  6394. }
  6395. } else {
  6396. CmdArgs.push_back("-global-isel=0");
  6397. }
  6398. }
  6399. if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
  6400. CmdArgs.push_back("-forder-file-instrumentation");
  6401. // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
  6402. // on, we need to pass these flags as linker flags and that will be handled
  6403. // outside of the compiler.
  6404. if (!IsUsingLTO) {
  6405. CmdArgs.push_back("-mllvm");
  6406. CmdArgs.push_back("-enable-order-file-instrumentation");
  6407. }
  6408. }
  6409. if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
  6410. options::OPT_fno_force_enable_int128)) {
  6411. if (A->getOption().matches(options::OPT_fforce_enable_int128))
  6412. CmdArgs.push_back("-fforce-enable-int128");
  6413. }
  6414. Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
  6415. options::OPT_fno_keep_static_consts);
  6416. Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
  6417. options::OPT_fno_complete_member_pointers);
  6418. Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
  6419. options::OPT_fno_cxx_static_destructors);
  6420. addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
  6421. if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
  6422. options::OPT_mno_outline_atomics)) {
  6423. // Option -moutline-atomics supported for AArch64 target only.
  6424. if (!Triple.isAArch64()) {
  6425. D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
  6426. << Triple.getArchName() << A->getOption().getName();
  6427. } else {
  6428. if (A->getOption().matches(options::OPT_moutline_atomics)) {
  6429. CmdArgs.push_back("-target-feature");
  6430. CmdArgs.push_back("+outline-atomics");
  6431. } else {
  6432. CmdArgs.push_back("-target-feature");
  6433. CmdArgs.push_back("-outline-atomics");
  6434. }
  6435. }
  6436. } else if (Triple.isAArch64() &&
  6437. getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
  6438. CmdArgs.push_back("-target-feature");
  6439. CmdArgs.push_back("+outline-atomics");
  6440. }
  6441. if (Triple.isAArch64() &&
  6442. (Args.hasArg(options::OPT_mno_fmv) ||
  6443. getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
  6444. // Disable Function Multiversioning on AArch64 target.
  6445. CmdArgs.push_back("-target-feature");
  6446. CmdArgs.push_back("-fmv");
  6447. }
  6448. if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
  6449. (TC.getTriple().isOSBinFormatELF() ||
  6450. TC.getTriple().isOSBinFormatCOFF()) &&
  6451. !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
  6452. !TC.getTriple().isOSNetBSD() &&
  6453. !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
  6454. !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
  6455. CmdArgs.push_back("-faddrsig");
  6456. if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
  6457. (EH || UnwindTables || AsyncUnwindTables ||
  6458. DebugInfoKind != codegenoptions::NoDebugInfo))
  6459. CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
  6460. if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
  6461. std::string Str = A->getAsString(Args);
  6462. if (!TC.getTriple().isOSBinFormatELF())
  6463. D.Diag(diag::err_drv_unsupported_opt_for_target)
  6464. << Str << TC.getTripleString();
  6465. CmdArgs.push_back(Args.MakeArgString(Str));
  6466. }
  6467. // Add the output path to the object file for CodeView debug infos.
  6468. if (EmitCodeView && Output.isFilename())
  6469. addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
  6470. Output.getFilename());
  6471. // Add the "-o out -x type src.c" flags last. This is done primarily to make
  6472. // the -cc1 command easier to edit when reproducing compiler crashes.
  6473. if (Output.getType() == types::TY_Dependencies) {
  6474. // Handled with other dependency code.
  6475. } else if (Output.isFilename()) {
  6476. if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
  6477. Output.getType() == clang::driver::types::TY_IFS) {
  6478. SmallString<128> OutputFilename(Output.getFilename());
  6479. llvm::sys::path::replace_extension(OutputFilename, "ifs");
  6480. CmdArgs.push_back("-o");
  6481. CmdArgs.push_back(Args.MakeArgString(OutputFilename));
  6482. } else {
  6483. CmdArgs.push_back("-o");
  6484. CmdArgs.push_back(Output.getFilename());
  6485. }
  6486. } else {
  6487. assert(Output.isNothing() && "Invalid output.");
  6488. }
  6489. addDashXForInput(Args, Input, CmdArgs);
  6490. ArrayRef<InputInfo> FrontendInputs = Input;
  6491. if (IsExtractAPI)
  6492. FrontendInputs = ExtractAPIInputs;
  6493. else if (Input.isNothing())
  6494. FrontendInputs = {};
  6495. for (const InputInfo &Input : FrontendInputs) {
  6496. if (Input.isFilename())
  6497. CmdArgs.push_back(Input.getFilename());
  6498. else
  6499. Input.getInputArg().renderAsInput(Args, CmdArgs);
  6500. }
  6501. if (D.CC1Main && !D.CCGenDiagnostics) {
  6502. // Invoke the CC1 directly in this process
  6503. C.addCommand(std::make_unique<CC1Command>(JA, *this,
  6504. ResponseFileSupport::AtFileUTF8(),
  6505. Exec, CmdArgs, Inputs, Output));
  6506. } else {
  6507. C.addCommand(std::make_unique<Command>(JA, *this,
  6508. ResponseFileSupport::AtFileUTF8(),
  6509. Exec, CmdArgs, Inputs, Output));
  6510. }
  6511. // Make the compile command echo its inputs for /showFilenames.
  6512. if (Output.getType() == types::TY_Object &&
  6513. Args.hasFlag(options::OPT__SLASH_showFilenames,
  6514. options::OPT__SLASH_showFilenames_, false)) {
  6515. C.getJobs().getJobs().back()->PrintInputFilenames = true;
  6516. }
  6517. if (Arg *A = Args.getLastArg(options::OPT_pg))
  6518. if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
  6519. !Args.hasArg(options::OPT_mfentry))
  6520. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  6521. << A->getAsString(Args);
  6522. // Claim some arguments which clang supports automatically.
  6523. // -fpch-preprocess is used with gcc to add a special marker in the output to
  6524. // include the PCH file.
  6525. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  6526. // Claim some arguments which clang doesn't support, but we don't
  6527. // care to warn the user about.
  6528. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  6529. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  6530. // Disable warnings for clang -E -emit-llvm foo.c
  6531. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6532. }
  6533. Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
  6534. // CAUTION! The first constructor argument ("clang") is not arbitrary,
  6535. // as it is for other tools. Some operations on a Tool actually test
  6536. // whether that tool is Clang based on the Tool's Name as a string.
  6537. : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
  6538. Clang::~Clang() {}
  6539. /// Add options related to the Objective-C runtime/ABI.
  6540. ///
  6541. /// Returns true if the runtime is non-fragile.
  6542. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  6543. const InputInfoList &inputs,
  6544. ArgStringList &cmdArgs,
  6545. RewriteKind rewriteKind) const {
  6546. // Look for the controlling runtime option.
  6547. Arg *runtimeArg =
  6548. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  6549. options::OPT_fobjc_runtime_EQ);
  6550. // Just forward -fobjc-runtime= to the frontend. This supercedes
  6551. // options about fragility.
  6552. if (runtimeArg &&
  6553. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  6554. ObjCRuntime runtime;
  6555. StringRef value = runtimeArg->getValue();
  6556. if (runtime.tryParse(value)) {
  6557. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  6558. << value;
  6559. }
  6560. if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
  6561. (runtime.getVersion() >= VersionTuple(2, 0)))
  6562. if (!getToolChain().getTriple().isOSBinFormatELF() &&
  6563. !getToolChain().getTriple().isOSBinFormatCOFF()) {
  6564. getToolChain().getDriver().Diag(
  6565. diag::err_drv_gnustep_objc_runtime_incompatible_binary)
  6566. << runtime.getVersion().getMajor();
  6567. }
  6568. runtimeArg->render(args, cmdArgs);
  6569. return runtime;
  6570. }
  6571. // Otherwise, we'll need the ABI "version". Version numbers are
  6572. // slightly confusing for historical reasons:
  6573. // 1 - Traditional "fragile" ABI
  6574. // 2 - Non-fragile ABI, version 1
  6575. // 3 - Non-fragile ABI, version 2
  6576. unsigned objcABIVersion = 1;
  6577. // If -fobjc-abi-version= is present, use that to set the version.
  6578. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  6579. StringRef value = abiArg->getValue();
  6580. if (value == "1")
  6581. objcABIVersion = 1;
  6582. else if (value == "2")
  6583. objcABIVersion = 2;
  6584. else if (value == "3")
  6585. objcABIVersion = 3;
  6586. else
  6587. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  6588. } else {
  6589. // Otherwise, determine if we are using the non-fragile ABI.
  6590. bool nonFragileABIIsDefault =
  6591. (rewriteKind == RK_NonFragile ||
  6592. (rewriteKind == RK_None &&
  6593. getToolChain().IsObjCNonFragileABIDefault()));
  6594. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  6595. options::OPT_fno_objc_nonfragile_abi,
  6596. nonFragileABIIsDefault)) {
  6597. // Determine the non-fragile ABI version to use.
  6598. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  6599. unsigned nonFragileABIVersion = 1;
  6600. #else
  6601. unsigned nonFragileABIVersion = 2;
  6602. #endif
  6603. if (Arg *abiArg =
  6604. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  6605. StringRef value = abiArg->getValue();
  6606. if (value == "1")
  6607. nonFragileABIVersion = 1;
  6608. else if (value == "2")
  6609. nonFragileABIVersion = 2;
  6610. else
  6611. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  6612. << value;
  6613. }
  6614. objcABIVersion = 1 + nonFragileABIVersion;
  6615. } else {
  6616. objcABIVersion = 1;
  6617. }
  6618. }
  6619. // We don't actually care about the ABI version other than whether
  6620. // it's non-fragile.
  6621. bool isNonFragile = objcABIVersion != 1;
  6622. // If we have no runtime argument, ask the toolchain for its default runtime.
  6623. // However, the rewriter only really supports the Mac runtime, so assume that.
  6624. ObjCRuntime runtime;
  6625. if (!runtimeArg) {
  6626. switch (rewriteKind) {
  6627. case RK_None:
  6628. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  6629. break;
  6630. case RK_Fragile:
  6631. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  6632. break;
  6633. case RK_NonFragile:
  6634. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  6635. break;
  6636. }
  6637. // -fnext-runtime
  6638. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  6639. // On Darwin, make this use the default behavior for the toolchain.
  6640. if (getToolChain().getTriple().isOSDarwin()) {
  6641. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  6642. // Otherwise, build for a generic macosx port.
  6643. } else {
  6644. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  6645. }
  6646. // -fgnu-runtime
  6647. } else {
  6648. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  6649. // Legacy behaviour is to target the gnustep runtime if we are in
  6650. // non-fragile mode or the GCC runtime in fragile mode.
  6651. if (isNonFragile)
  6652. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
  6653. else
  6654. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  6655. }
  6656. if (llvm::any_of(inputs, [](const InputInfo &input) {
  6657. return types::isObjC(input.getType());
  6658. }))
  6659. cmdArgs.push_back(
  6660. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  6661. return runtime;
  6662. }
  6663. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  6664. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  6665. I += HaveDash;
  6666. return !HaveDash;
  6667. }
  6668. namespace {
  6669. struct EHFlags {
  6670. bool Synch = false;
  6671. bool Asynch = false;
  6672. bool NoUnwindC = false;
  6673. };
  6674. } // end anonymous namespace
  6675. /// /EH controls whether to run destructor cleanups when exceptions are
  6676. /// thrown. There are three modifiers:
  6677. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  6678. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  6679. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  6680. /// - c: Assume that extern "C" functions are implicitly nounwind.
  6681. /// The default is /EHs-c-, meaning cleanups are disabled.
  6682. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  6683. EHFlags EH;
  6684. std::vector<std::string> EHArgs =
  6685. Args.getAllArgValues(options::OPT__SLASH_EH);
  6686. for (auto EHVal : EHArgs) {
  6687. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  6688. switch (EHVal[I]) {
  6689. case 'a':
  6690. EH.Asynch = maybeConsumeDash(EHVal, I);
  6691. if (EH.Asynch)
  6692. EH.Synch = false;
  6693. continue;
  6694. case 'c':
  6695. EH.NoUnwindC = maybeConsumeDash(EHVal, I);
  6696. continue;
  6697. case 's':
  6698. EH.Synch = maybeConsumeDash(EHVal, I);
  6699. if (EH.Synch)
  6700. EH.Asynch = false;
  6701. continue;
  6702. default:
  6703. break;
  6704. }
  6705. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  6706. break;
  6707. }
  6708. }
  6709. // The /GX, /GX- flags are only processed if there are not /EH flags.
  6710. // The default is that /GX is not specified.
  6711. if (EHArgs.empty() &&
  6712. Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
  6713. /*Default=*/false)) {
  6714. EH.Synch = true;
  6715. EH.NoUnwindC = true;
  6716. }
  6717. if (Args.hasArg(options::OPT__SLASH_kernel)) {
  6718. EH.Synch = false;
  6719. EH.NoUnwindC = false;
  6720. EH.Asynch = false;
  6721. }
  6722. return EH;
  6723. }
  6724. void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
  6725. ArgStringList &CmdArgs,
  6726. codegenoptions::DebugInfoKind *DebugInfoKind,
  6727. bool *EmitCodeView) const {
  6728. bool isNVPTX = getToolChain().getTriple().isNVPTX();
  6729. ProcessVSRuntimeLibrary(Args, CmdArgs);
  6730. if (Arg *ShowIncludes =
  6731. Args.getLastArg(options::OPT__SLASH_showIncludes,
  6732. options::OPT__SLASH_showIncludes_user)) {
  6733. CmdArgs.push_back("--show-includes");
  6734. if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
  6735. CmdArgs.push_back("-sys-header-deps");
  6736. }
  6737. // This controls whether or not we emit RTTI data for polymorphic types.
  6738. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  6739. /*Default=*/false))
  6740. CmdArgs.push_back("-fno-rtti-data");
  6741. // This controls whether or not we emit stack-protector instrumentation.
  6742. // In MSVC, Buffer Security Check (/GS) is on by default.
  6743. if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
  6744. /*Default=*/true)) {
  6745. CmdArgs.push_back("-stack-protector");
  6746. CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
  6747. }
  6748. // Emit CodeView if -Z7 or -gline-tables-only are present.
  6749. if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7,
  6750. options::OPT_gline_tables_only)) {
  6751. *EmitCodeView = true;
  6752. if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
  6753. *DebugInfoKind = codegenoptions::DebugInfoConstructor;
  6754. else
  6755. *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
  6756. } else {
  6757. *EmitCodeView = false;
  6758. }
  6759. const Driver &D = getToolChain().getDriver();
  6760. // This controls whether or not we perform JustMyCode instrumentation.
  6761. if (Args.hasFlag(options::OPT__SLASH_JMC, options::OPT__SLASH_JMC_,
  6762. /*Default=*/false)) {
  6763. if (*EmitCodeView && *DebugInfoKind >= codegenoptions::DebugInfoConstructor)
  6764. CmdArgs.push_back("-fjmc");
  6765. else
  6766. D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
  6767. << "'/Zi', '/Z7'";
  6768. }
  6769. EHFlags EH = parseClangCLEHFlags(D, Args);
  6770. if (!isNVPTX && (EH.Synch || EH.Asynch)) {
  6771. if (types::isCXX(InputType))
  6772. CmdArgs.push_back("-fcxx-exceptions");
  6773. CmdArgs.push_back("-fexceptions");
  6774. }
  6775. if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
  6776. CmdArgs.push_back("-fexternc-nounwind");
  6777. // /EP should expand to -E -P.
  6778. if (Args.hasArg(options::OPT__SLASH_EP)) {
  6779. CmdArgs.push_back("-E");
  6780. CmdArgs.push_back("-P");
  6781. }
  6782. unsigned VolatileOptionID;
  6783. if (getToolChain().getTriple().isX86())
  6784. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  6785. else
  6786. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  6787. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  6788. VolatileOptionID = A->getOption().getID();
  6789. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  6790. CmdArgs.push_back("-fms-volatile");
  6791. if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
  6792. options::OPT__SLASH_Zc_dllexportInlines,
  6793. false)) {
  6794. CmdArgs.push_back("-fno-dllexport-inlines");
  6795. }
  6796. if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
  6797. options::OPT__SLASH_Zc_wchar_t, false)) {
  6798. CmdArgs.push_back("-fno-wchar");
  6799. }
  6800. if (Args.hasArg(options::OPT__SLASH_kernel)) {
  6801. llvm::Triple::ArchType Arch = getToolChain().getArch();
  6802. std::vector<std::string> Values =
  6803. Args.getAllArgValues(options::OPT__SLASH_arch);
  6804. if (!Values.empty()) {
  6805. llvm::SmallSet<std::string, 4> SupportedArches;
  6806. if (Arch == llvm::Triple::x86)
  6807. SupportedArches.insert("IA32");
  6808. for (auto &V : Values)
  6809. if (!SupportedArches.contains(V))
  6810. D.Diag(diag::err_drv_argument_not_allowed_with)
  6811. << std::string("/arch:").append(V) << "/kernel";
  6812. }
  6813. CmdArgs.push_back("-fno-rtti");
  6814. if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
  6815. D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
  6816. << "/kernel";
  6817. }
  6818. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  6819. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  6820. if (MostGeneralArg && BestCaseArg)
  6821. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  6822. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  6823. if (MostGeneralArg) {
  6824. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  6825. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  6826. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  6827. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  6828. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  6829. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  6830. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  6831. << FirstConflict->getAsString(Args)
  6832. << SecondConflict->getAsString(Args);
  6833. if (SingleArg)
  6834. CmdArgs.push_back("-fms-memptr-rep=single");
  6835. else if (MultipleArg)
  6836. CmdArgs.push_back("-fms-memptr-rep=multiple");
  6837. else
  6838. CmdArgs.push_back("-fms-memptr-rep=virtual");
  6839. }
  6840. // Parse the default calling convention options.
  6841. if (Arg *CCArg =
  6842. Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
  6843. options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
  6844. options::OPT__SLASH_Gregcall)) {
  6845. unsigned DCCOptId = CCArg->getOption().getID();
  6846. const char *DCCFlag = nullptr;
  6847. bool ArchSupported = !isNVPTX;
  6848. llvm::Triple::ArchType Arch = getToolChain().getArch();
  6849. switch (DCCOptId) {
  6850. case options::OPT__SLASH_Gd:
  6851. DCCFlag = "-fdefault-calling-conv=cdecl";
  6852. break;
  6853. case options::OPT__SLASH_Gr:
  6854. ArchSupported = Arch == llvm::Triple::x86;
  6855. DCCFlag = "-fdefault-calling-conv=fastcall";
  6856. break;
  6857. case options::OPT__SLASH_Gz:
  6858. ArchSupported = Arch == llvm::Triple::x86;
  6859. DCCFlag = "-fdefault-calling-conv=stdcall";
  6860. break;
  6861. case options::OPT__SLASH_Gv:
  6862. ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
  6863. DCCFlag = "-fdefault-calling-conv=vectorcall";
  6864. break;
  6865. case options::OPT__SLASH_Gregcall:
  6866. ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
  6867. DCCFlag = "-fdefault-calling-conv=regcall";
  6868. break;
  6869. }
  6870. // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
  6871. if (ArchSupported && DCCFlag)
  6872. CmdArgs.push_back(DCCFlag);
  6873. }
  6874. Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
  6875. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  6876. CmdArgs.push_back("-fdiagnostics-format");
  6877. CmdArgs.push_back("msvc");
  6878. }
  6879. if (Args.hasArg(options::OPT__SLASH_kernel))
  6880. CmdArgs.push_back("-fms-kernel");
  6881. if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
  6882. StringRef GuardArgs = A->getValue();
  6883. // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
  6884. // "ehcont-".
  6885. if (GuardArgs.equals_insensitive("cf")) {
  6886. // Emit CFG instrumentation and the table of address-taken functions.
  6887. CmdArgs.push_back("-cfguard");
  6888. } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
  6889. // Emit only the table of address-taken functions.
  6890. CmdArgs.push_back("-cfguard-no-checks");
  6891. } else if (GuardArgs.equals_insensitive("ehcont")) {
  6892. // Emit EH continuation table.
  6893. CmdArgs.push_back("-ehcontguard");
  6894. } else if (GuardArgs.equals_insensitive("cf-") ||
  6895. GuardArgs.equals_insensitive("ehcont-")) {
  6896. // Do nothing, but we might want to emit a security warning in future.
  6897. } else {
  6898. D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
  6899. }
  6900. }
  6901. }
  6902. const char *Clang::getBaseInputName(const ArgList &Args,
  6903. const InputInfo &Input) {
  6904. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  6905. }
  6906. const char *Clang::getBaseInputStem(const ArgList &Args,
  6907. const InputInfoList &Inputs) {
  6908. const char *Str = getBaseInputName(Args, Inputs[0]);
  6909. if (const char *End = strrchr(Str, '.'))
  6910. return Args.MakeArgString(std::string(Str, End));
  6911. return Str;
  6912. }
  6913. const char *Clang::getDependencyFileName(const ArgList &Args,
  6914. const InputInfoList &Inputs) {
  6915. // FIXME: Think about this more.
  6916. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  6917. SmallString<128> OutputFilename(OutputOpt->getValue());
  6918. llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
  6919. return Args.MakeArgString(OutputFilename);
  6920. }
  6921. return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
  6922. }
  6923. // Begin ClangAs
  6924. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  6925. ArgStringList &CmdArgs) const {
  6926. StringRef CPUName;
  6927. StringRef ABIName;
  6928. const llvm::Triple &Triple = getToolChain().getTriple();
  6929. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  6930. CmdArgs.push_back("-target-abi");
  6931. CmdArgs.push_back(ABIName.data());
  6932. }
  6933. void ClangAs::AddX86TargetArgs(const ArgList &Args,
  6934. ArgStringList &CmdArgs) const {
  6935. addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
  6936. /*IsLTO=*/false);
  6937. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  6938. StringRef Value = A->getValue();
  6939. if (Value == "intel" || Value == "att") {
  6940. CmdArgs.push_back("-mllvm");
  6941. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  6942. } else {
  6943. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  6944. << A->getSpelling() << Value;
  6945. }
  6946. }
  6947. }
  6948. void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
  6949. ArgStringList &CmdArgs) const {
  6950. const llvm::Triple &Triple = getToolChain().getTriple();
  6951. StringRef ABIName = riscv::getRISCVABI(Args, Triple);
  6952. CmdArgs.push_back("-target-abi");
  6953. CmdArgs.push_back(ABIName.data());
  6954. }
  6955. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  6956. const InputInfo &Output, const InputInfoList &Inputs,
  6957. const ArgList &Args,
  6958. const char *LinkingOutput) const {
  6959. ArgStringList CmdArgs;
  6960. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  6961. const InputInfo &Input = Inputs[0];
  6962. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  6963. const std::string &TripleStr = Triple.getTriple();
  6964. const auto &D = getToolChain().getDriver();
  6965. // Don't warn about "clang -w -c foo.s"
  6966. Args.ClaimAllArgs(options::OPT_w);
  6967. // and "clang -emit-llvm -c foo.s"
  6968. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6969. claimNoWarnArgs(Args);
  6970. // Invoke ourselves in -cc1as mode.
  6971. //
  6972. // FIXME: Implement custom jobs for internal actions.
  6973. CmdArgs.push_back("-cc1as");
  6974. // Add the "effective" target triple.
  6975. CmdArgs.push_back("-triple");
  6976. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  6977. getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
  6978. // Set the output mode, we currently only expect to be used as a real
  6979. // assembler.
  6980. CmdArgs.push_back("-filetype");
  6981. CmdArgs.push_back("obj");
  6982. // Set the main file name, so that debug info works even with
  6983. // -save-temps or preprocessed assembly.
  6984. CmdArgs.push_back("-main-file-name");
  6985. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  6986. // Add the target cpu
  6987. std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
  6988. if (!CPU.empty()) {
  6989. CmdArgs.push_back("-target-cpu");
  6990. CmdArgs.push_back(Args.MakeArgString(CPU));
  6991. }
  6992. // Add the target features
  6993. getTargetFeatures(D, Triple, Args, CmdArgs, true);
  6994. // Ignore explicit -force_cpusubtype_ALL option.
  6995. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  6996. // Pass along any -I options so we get proper .include search paths.
  6997. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  6998. // Determine the original source input.
  6999. auto FindSource = [](const Action *S) -> const Action * {
  7000. while (S->getKind() != Action::InputClass) {
  7001. assert(!S->getInputs().empty() && "unexpected root action!");
  7002. S = S->getInputs()[0];
  7003. }
  7004. return S;
  7005. };
  7006. const Action *SourceAction = FindSource(&JA);
  7007. // Forward -g and handle debug info related flags, assuming we are dealing
  7008. // with an actual assembly file.
  7009. bool WantDebug = false;
  7010. Args.ClaimAllArgs(options::OPT_g_Group);
  7011. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  7012. WantDebug = !A->getOption().matches(options::OPT_g0) &&
  7013. !A->getOption().matches(options::OPT_ggdb0);
  7014. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  7015. // Add the -fdebug-compilation-dir flag if needed.
  7016. const char *DebugCompilationDir =
  7017. addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
  7018. if (SourceAction->getType() == types::TY_Asm ||
  7019. SourceAction->getType() == types::TY_PP_Asm) {
  7020. // You might think that it would be ok to set DebugInfoKind outside of
  7021. // the guard for source type, however there is a test which asserts
  7022. // that some assembler invocation receives no -debug-info-kind,
  7023. // and it's not clear whether that test is just overly restrictive.
  7024. DebugInfoKind = (WantDebug ? codegenoptions::DebugInfoConstructor
  7025. : codegenoptions::NoDebugInfo);
  7026. addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
  7027. CmdArgs);
  7028. // Set the AT_producer to the clang version when using the integrated
  7029. // assembler on assembly source files.
  7030. CmdArgs.push_back("-dwarf-debug-producer");
  7031. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  7032. // And pass along -I options
  7033. Args.AddAllArgs(CmdArgs, options::OPT_I);
  7034. }
  7035. const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
  7036. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  7037. llvm::DebuggerKind::Default);
  7038. renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
  7039. RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
  7040. // Handle -fPIC et al -- the relocation-model affects the assembler
  7041. // for some targets.
  7042. llvm::Reloc::Model RelocationModel;
  7043. unsigned PICLevel;
  7044. bool IsPIE;
  7045. std::tie(RelocationModel, PICLevel, IsPIE) =
  7046. ParsePICArgs(getToolChain(), Args);
  7047. const char *RMName = RelocationModelName(RelocationModel);
  7048. if (RMName) {
  7049. CmdArgs.push_back("-mrelocation-model");
  7050. CmdArgs.push_back(RMName);
  7051. }
  7052. // Optionally embed the -cc1as level arguments into the debug info, for build
  7053. // analysis.
  7054. if (getToolChain().UseDwarfDebugFlags()) {
  7055. ArgStringList OriginalArgs;
  7056. for (const auto &Arg : Args)
  7057. Arg->render(Args, OriginalArgs);
  7058. SmallString<256> Flags;
  7059. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  7060. EscapeSpacesAndBackslashes(Exec, Flags);
  7061. for (const char *OriginalArg : OriginalArgs) {
  7062. SmallString<128> EscapedArg;
  7063. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  7064. Flags += " ";
  7065. Flags += EscapedArg;
  7066. }
  7067. CmdArgs.push_back("-dwarf-debug-flags");
  7068. CmdArgs.push_back(Args.MakeArgString(Flags));
  7069. }
  7070. // FIXME: Add -static support, once we have it.
  7071. // Add target specific flags.
  7072. switch (getToolChain().getArch()) {
  7073. default:
  7074. break;
  7075. case llvm::Triple::mips:
  7076. case llvm::Triple::mipsel:
  7077. case llvm::Triple::mips64:
  7078. case llvm::Triple::mips64el:
  7079. AddMIPSTargetArgs(Args, CmdArgs);
  7080. break;
  7081. case llvm::Triple::x86:
  7082. case llvm::Triple::x86_64:
  7083. AddX86TargetArgs(Args, CmdArgs);
  7084. break;
  7085. case llvm::Triple::arm:
  7086. case llvm::Triple::armeb:
  7087. case llvm::Triple::thumb:
  7088. case llvm::Triple::thumbeb:
  7089. // This isn't in AddARMTargetArgs because we want to do this for assembly
  7090. // only, not C/C++.
  7091. if (Args.hasFlag(options::OPT_mdefault_build_attributes,
  7092. options::OPT_mno_default_build_attributes, true)) {
  7093. CmdArgs.push_back("-mllvm");
  7094. CmdArgs.push_back("-arm-add-build-attributes");
  7095. }
  7096. break;
  7097. case llvm::Triple::aarch64:
  7098. case llvm::Triple::aarch64_32:
  7099. case llvm::Triple::aarch64_be:
  7100. if (Args.hasArg(options::OPT_mmark_bti_property)) {
  7101. CmdArgs.push_back("-mllvm");
  7102. CmdArgs.push_back("-aarch64-mark-bti-property");
  7103. }
  7104. break;
  7105. case llvm::Triple::riscv32:
  7106. case llvm::Triple::riscv64:
  7107. AddRISCVTargetArgs(Args, CmdArgs);
  7108. break;
  7109. }
  7110. // Consume all the warning flags. Usually this would be handled more
  7111. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  7112. // doesn't handle that so rather than warning about unused flags that are
  7113. // actually used, we'll lie by omission instead.
  7114. // FIXME: Stop lying and consume only the appropriate driver flags
  7115. Args.ClaimAllArgs(options::OPT_W_Group);
  7116. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  7117. getToolChain().getDriver());
  7118. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  7119. if (DebugInfoKind > codegenoptions::NoDebugInfo && Output.isFilename())
  7120. addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
  7121. Output.getFilename());
  7122. // Fixup any previous commands that use -object-file-name because when we
  7123. // generated them, the final .obj name wasn't yet known.
  7124. for (Command &J : C.getJobs()) {
  7125. if (SourceAction != FindSource(&J.getSource()))
  7126. continue;
  7127. auto &JArgs = J.getArguments();
  7128. for (unsigned I = 0; I < JArgs.size(); ++I) {
  7129. if (StringRef(JArgs[I]).startswith("-object-file-name=") &&
  7130. Output.isFilename()) {
  7131. ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
  7132. addDebugObjectName(Args, NewArgs, DebugCompilationDir,
  7133. Output.getFilename());
  7134. NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
  7135. J.replaceArguments(NewArgs);
  7136. break;
  7137. }
  7138. }
  7139. }
  7140. assert(Output.isFilename() && "Unexpected lipo output.");
  7141. CmdArgs.push_back("-o");
  7142. CmdArgs.push_back(Output.getFilename());
  7143. const llvm::Triple &T = getToolChain().getTriple();
  7144. Arg *A;
  7145. if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
  7146. T.isOSBinFormatELF()) {
  7147. CmdArgs.push_back("-split-dwarf-output");
  7148. CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
  7149. }
  7150. if (Triple.isAMDGPU())
  7151. handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
  7152. assert(Input.isFilename() && "Invalid input.");
  7153. CmdArgs.push_back(Input.getFilename());
  7154. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  7155. if (D.CC1Main && !D.CCGenDiagnostics) {
  7156. // Invoke cc1as directly in this process.
  7157. C.addCommand(std::make_unique<CC1Command>(JA, *this,
  7158. ResponseFileSupport::AtFileUTF8(),
  7159. Exec, CmdArgs, Inputs, Output));
  7160. } else {
  7161. C.addCommand(std::make_unique<Command>(JA, *this,
  7162. ResponseFileSupport::AtFileUTF8(),
  7163. Exec, CmdArgs, Inputs, Output));
  7164. }
  7165. }
  7166. // Begin OffloadBundler
  7167. void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
  7168. const InputInfo &Output,
  7169. const InputInfoList &Inputs,
  7170. const llvm::opt::ArgList &TCArgs,
  7171. const char *LinkingOutput) const {
  7172. // The version with only one output is expected to refer to a bundling job.
  7173. assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
  7174. // The bundling command looks like this:
  7175. // clang-offload-bundler -type=bc
  7176. // -targets=host-triple,openmp-triple1,openmp-triple2
  7177. // -output=output_file
  7178. // -input=unbundle_file_host
  7179. // -input=unbundle_file_tgt1
  7180. // -input=unbundle_file_tgt2
  7181. ArgStringList CmdArgs;
  7182. // Get the type.
  7183. CmdArgs.push_back(TCArgs.MakeArgString(
  7184. Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
  7185. assert(JA.getInputs().size() == Inputs.size() &&
  7186. "Not have inputs for all dependence actions??");
  7187. // Get the targets.
  7188. SmallString<128> Triples;
  7189. Triples += "-targets=";
  7190. for (unsigned I = 0; I < Inputs.size(); ++I) {
  7191. if (I)
  7192. Triples += ',';
  7193. // Find ToolChain for this input.
  7194. Action::OffloadKind CurKind = Action::OFK_Host;
  7195. const ToolChain *CurTC = &getToolChain();
  7196. const Action *CurDep = JA.getInputs()[I];
  7197. if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
  7198. CurTC = nullptr;
  7199. OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
  7200. assert(CurTC == nullptr && "Expected one dependence!");
  7201. CurKind = A->getOffloadingDeviceKind();
  7202. CurTC = TC;
  7203. });
  7204. }
  7205. Triples += Action::GetOffloadKindName(CurKind);
  7206. Triples += '-';
  7207. Triples += CurTC->getTriple().normalize();
  7208. if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
  7209. !StringRef(CurDep->getOffloadingArch()).empty()) {
  7210. Triples += '-';
  7211. Triples += CurDep->getOffloadingArch();
  7212. }
  7213. // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
  7214. // with each toolchain.
  7215. StringRef GPUArchName;
  7216. if (CurKind == Action::OFK_OpenMP) {
  7217. // Extract GPUArch from -march argument in TC argument list.
  7218. for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
  7219. auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
  7220. auto Arch = ArchStr.startswith_insensitive("-march=");
  7221. if (Arch) {
  7222. GPUArchName = ArchStr.substr(7);
  7223. Triples += "-";
  7224. break;
  7225. }
  7226. }
  7227. Triples += GPUArchName.str();
  7228. }
  7229. }
  7230. CmdArgs.push_back(TCArgs.MakeArgString(Triples));
  7231. // Get bundled file command.
  7232. CmdArgs.push_back(
  7233. TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
  7234. // Get unbundled files command.
  7235. for (unsigned I = 0; I < Inputs.size(); ++I) {
  7236. SmallString<128> UB;
  7237. UB += "-input=";
  7238. // Find ToolChain for this input.
  7239. const ToolChain *CurTC = &getToolChain();
  7240. if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
  7241. CurTC = nullptr;
  7242. OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
  7243. assert(CurTC == nullptr && "Expected one dependence!");
  7244. CurTC = TC;
  7245. });
  7246. UB += C.addTempFile(
  7247. C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
  7248. } else {
  7249. UB += CurTC->getInputFilename(Inputs[I]);
  7250. }
  7251. CmdArgs.push_back(TCArgs.MakeArgString(UB));
  7252. }
  7253. // All the inputs are encoded as commands.
  7254. C.addCommand(std::make_unique<Command>(
  7255. JA, *this, ResponseFileSupport::None(),
  7256. TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
  7257. CmdArgs, std::nullopt, Output));
  7258. }
  7259. void OffloadBundler::ConstructJobMultipleOutputs(
  7260. Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
  7261. const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
  7262. const char *LinkingOutput) const {
  7263. // The version with multiple outputs is expected to refer to a unbundling job.
  7264. auto &UA = cast<OffloadUnbundlingJobAction>(JA);
  7265. // The unbundling command looks like this:
  7266. // clang-offload-bundler -type=bc
  7267. // -targets=host-triple,openmp-triple1,openmp-triple2
  7268. // -input=input_file
  7269. // -output=unbundle_file_host
  7270. // -output=unbundle_file_tgt1
  7271. // -output=unbundle_file_tgt2
  7272. // -unbundle
  7273. ArgStringList CmdArgs;
  7274. assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
  7275. InputInfo Input = Inputs.front();
  7276. // Get the type.
  7277. CmdArgs.push_back(TCArgs.MakeArgString(
  7278. Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
  7279. // Get the targets.
  7280. SmallString<128> Triples;
  7281. Triples += "-targets=";
  7282. auto DepInfo = UA.getDependentActionsInfo();
  7283. for (unsigned I = 0; I < DepInfo.size(); ++I) {
  7284. if (I)
  7285. Triples += ',';
  7286. auto &Dep = DepInfo[I];
  7287. Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
  7288. Triples += '-';
  7289. Triples += Dep.DependentToolChain->getTriple().normalize();
  7290. if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
  7291. Dep.DependentOffloadKind == Action::OFK_Cuda) &&
  7292. !Dep.DependentBoundArch.empty()) {
  7293. Triples += '-';
  7294. Triples += Dep.DependentBoundArch;
  7295. }
  7296. // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
  7297. // with each toolchain.
  7298. StringRef GPUArchName;
  7299. if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
  7300. // Extract GPUArch from -march argument in TC argument list.
  7301. for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
  7302. StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
  7303. auto Arch = ArchStr.startswith_insensitive("-march=");
  7304. if (Arch) {
  7305. GPUArchName = ArchStr.substr(7);
  7306. Triples += "-";
  7307. break;
  7308. }
  7309. }
  7310. Triples += GPUArchName.str();
  7311. }
  7312. }
  7313. CmdArgs.push_back(TCArgs.MakeArgString(Triples));
  7314. // Get bundled file command.
  7315. CmdArgs.push_back(
  7316. TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
  7317. // Get unbundled files command.
  7318. for (unsigned I = 0; I < Outputs.size(); ++I) {
  7319. SmallString<128> UB;
  7320. UB += "-output=";
  7321. UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
  7322. CmdArgs.push_back(TCArgs.MakeArgString(UB));
  7323. }
  7324. CmdArgs.push_back("-unbundle");
  7325. CmdArgs.push_back("-allow-missing-bundles");
  7326. // All the inputs are encoded as commands.
  7327. C.addCommand(std::make_unique<Command>(
  7328. JA, *this, ResponseFileSupport::None(),
  7329. TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
  7330. CmdArgs, std::nullopt, Outputs));
  7331. }
  7332. void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
  7333. const InputInfo &Output,
  7334. const InputInfoList &Inputs,
  7335. const llvm::opt::ArgList &Args,
  7336. const char *LinkingOutput) const {
  7337. ArgStringList CmdArgs;
  7338. // Add the output file name.
  7339. assert(Output.isFilename() && "Invalid output.");
  7340. CmdArgs.push_back("-o");
  7341. CmdArgs.push_back(Output.getFilename());
  7342. // Create the inputs to bundle the needed metadata.
  7343. for (const InputInfo &Input : Inputs) {
  7344. const Action *OffloadAction = Input.getAction();
  7345. const ToolChain *TC = OffloadAction->getOffloadingToolChain();
  7346. const ArgList &TCArgs =
  7347. C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
  7348. OffloadAction->getOffloadingDeviceKind());
  7349. StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
  7350. StringRef Arch = (OffloadAction->getOffloadingArch())
  7351. ? OffloadAction->getOffloadingArch()
  7352. : TCArgs.getLastArgValue(options::OPT_march_EQ);
  7353. StringRef Kind =
  7354. Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
  7355. ArgStringList Features;
  7356. SmallVector<StringRef> FeatureArgs;
  7357. getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
  7358. false);
  7359. llvm::copy_if(Features, std::back_inserter(FeatureArgs),
  7360. [](StringRef Arg) { return !Arg.startswith("-target"); });
  7361. SmallVector<std::string> Parts{
  7362. "file=" + File.str(),
  7363. "triple=" + TC->getTripleString(),
  7364. "arch=" + Arch.str(),
  7365. "kind=" + Kind.str(),
  7366. };
  7367. if (TC->getDriver().isUsingLTO(/* IsOffload */ true))
  7368. for (StringRef Feature : FeatureArgs)
  7369. Parts.emplace_back("feature=" + Feature.str());
  7370. CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
  7371. }
  7372. C.addCommand(std::make_unique<Command>(
  7373. JA, *this, ResponseFileSupport::None(),
  7374. Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
  7375. CmdArgs, Inputs, Output));
  7376. }
  7377. void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
  7378. const InputInfo &Output,
  7379. const InputInfoList &Inputs,
  7380. const ArgList &Args,
  7381. const char *LinkingOutput) const {
  7382. const Driver &D = getToolChain().getDriver();
  7383. const llvm::Triple TheTriple = getToolChain().getTriple();
  7384. ArgStringList CmdArgs;
  7385. // Pass the CUDA path to the linker wrapper tool.
  7386. for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
  7387. auto TCRange = C.getOffloadToolChains(Kind);
  7388. for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
  7389. const ToolChain *TC = I.second;
  7390. if (TC->getTriple().isNVPTX()) {
  7391. CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
  7392. if (CudaInstallation.isValid())
  7393. CmdArgs.push_back(Args.MakeArgString(
  7394. "--cuda-path=" + CudaInstallation.getInstallPath()));
  7395. break;
  7396. }
  7397. }
  7398. }
  7399. if (D.isUsingLTO(/* IsOffload */ true)) {
  7400. // Pass in the optimization level to use for LTO.
  7401. if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  7402. StringRef OOpt;
  7403. if (A->getOption().matches(options::OPT_O4) ||
  7404. A->getOption().matches(options::OPT_Ofast))
  7405. OOpt = "3";
  7406. else if (A->getOption().matches(options::OPT_O)) {
  7407. OOpt = A->getValue();
  7408. if (OOpt == "g")
  7409. OOpt = "1";
  7410. else if (OOpt == "s" || OOpt == "z")
  7411. OOpt = "2";
  7412. } else if (A->getOption().matches(options::OPT_O0))
  7413. OOpt = "0";
  7414. if (!OOpt.empty())
  7415. CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
  7416. }
  7417. }
  7418. CmdArgs.push_back(
  7419. Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
  7420. if (Args.hasArg(options::OPT_v))
  7421. CmdArgs.push_back("--wrapper-verbose");
  7422. if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  7423. if (!A->getOption().matches(options::OPT_g0))
  7424. CmdArgs.push_back("--device-debug");
  7425. }
  7426. for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
  7427. CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
  7428. // Forward remarks passes to the LLVM backend in the wrapper.
  7429. if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
  7430. CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
  7431. A->getValue()));
  7432. if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
  7433. CmdArgs.push_back(Args.MakeArgString(
  7434. Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
  7435. if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
  7436. CmdArgs.push_back(Args.MakeArgString(
  7437. Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
  7438. if (Args.getLastArg(options::OPT_save_temps_EQ))
  7439. CmdArgs.push_back("--save-temps");
  7440. // Construct the link job so we can wrap around it.
  7441. Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
  7442. const auto &LinkCommand = C.getJobs().getJobs().back();
  7443. // Forward -Xoffload-linker<-triple> arguments to the device link job.
  7444. for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
  7445. StringRef Val = A->getValue(0);
  7446. if (Val.empty())
  7447. CmdArgs.push_back(
  7448. Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
  7449. else
  7450. CmdArgs.push_back(Args.MakeArgString(
  7451. "--device-linker=" +
  7452. ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
  7453. A->getValue(1)));
  7454. }
  7455. Args.ClaimAllArgs(options::OPT_Xoffload_linker);
  7456. // Embed bitcode instead of an object in JIT mode.
  7457. if (Args.hasFlag(options::OPT_fopenmp_target_jit,
  7458. options::OPT_fno_openmp_target_jit, false))
  7459. CmdArgs.push_back("--embed-bitcode");
  7460. // Forward `-mllvm` arguments to the LLVM invocations if present.
  7461. for (Arg *A : Args.filtered(options::OPT_mllvm)) {
  7462. CmdArgs.push_back("-mllvm");
  7463. CmdArgs.push_back(A->getValue());
  7464. A->claim();
  7465. }
  7466. // Add the linker arguments to be forwarded by the wrapper.
  7467. CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
  7468. LinkCommand->getExecutable()));
  7469. CmdArgs.push_back("--");
  7470. for (const char *LinkArg : LinkCommand->getArguments())
  7471. CmdArgs.push_back(LinkArg);
  7472. const char *Exec =
  7473. Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
  7474. // Replace the executable and arguments of the link job with the
  7475. // wrapper.
  7476. LinkCommand->replaceExecutable(Exec);
  7477. LinkCommand->replaceArguments(CmdArgs);
  7478. }