Clang.cpp 241 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451
  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 "Arch/AArch64.h"
  10. #include "Arch/ARM.h"
  11. #include "Arch/Mips.h"
  12. #include "Arch/PPC.h"
  13. #include "Arch/RISCV.h"
  14. #include "Arch/Sparc.h"
  15. #include "Arch/SystemZ.h"
  16. #include "Arch/X86.h"
  17. #include "AMDGPU.h"
  18. #include "CommonArgs.h"
  19. #include "Hexagon.h"
  20. #include "MSP430.h"
  21. #include "InputInfo.h"
  22. #include "PS4CPU.h"
  23. #include "clang/Basic/CharInfo.h"
  24. #include "clang/Basic/CodeGenOptions.h"
  25. #include "clang/Basic/LangOptions.h"
  26. #include "clang/Basic/ObjCRuntime.h"
  27. #include "clang/Basic/Version.h"
  28. #include "clang/Driver/Distro.h"
  29. #include "clang/Driver/DriverDiagnostic.h"
  30. #include "clang/Driver/Options.h"
  31. #include "clang/Driver/SanitizerArgs.h"
  32. #include "clang/Driver/XRayArgs.h"
  33. #include "llvm/ADT/StringExtras.h"
  34. #include "llvm/Config/llvm-config.h"
  35. #include "llvm/Option/ArgList.h"
  36. #include "llvm/Support/CodeGen.h"
  37. #include "llvm/Support/Compression.h"
  38. #include "llvm/Support/FileSystem.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Process.h"
  41. #include "llvm/Support/TargetParser.h"
  42. #include "llvm/Support/YAMLParser.h"
  43. #ifdef LLVM_ON_UNIX
  44. #include <unistd.h> // For getuid().
  45. #endif
  46. using namespace clang::driver;
  47. using namespace clang::driver::tools;
  48. using namespace clang;
  49. using namespace llvm::opt;
  50. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  51. if (Arg *A =
  52. Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
  53. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  54. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  55. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  56. << A->getBaseArg().getAsString(Args)
  57. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  58. }
  59. }
  60. }
  61. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  62. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  63. if (Args.hasArg(options::OPT_static))
  64. if (const Arg *A =
  65. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  66. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  67. << "-static";
  68. }
  69. // Add backslashes to escape spaces and other backslashes.
  70. // This is used for the space-separated argument list specified with
  71. // the -dwarf-debug-flags option.
  72. static void EscapeSpacesAndBackslashes(const char *Arg,
  73. SmallVectorImpl<char> &Res) {
  74. for (; *Arg; ++Arg) {
  75. switch (*Arg) {
  76. default:
  77. break;
  78. case ' ':
  79. case '\\':
  80. Res.push_back('\\');
  81. break;
  82. }
  83. Res.push_back(*Arg);
  84. }
  85. }
  86. // Quote target names for inclusion in GNU Make dependency files.
  87. // Only the characters '$', '#', ' ', '\t' are quoted.
  88. static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
  89. for (unsigned i = 0, e = Target.size(); i != e; ++i) {
  90. switch (Target[i]) {
  91. case ' ':
  92. case '\t':
  93. // Escape the preceding backslashes
  94. for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
  95. Res.push_back('\\');
  96. // Escape the space/tab
  97. Res.push_back('\\');
  98. break;
  99. case '$':
  100. Res.push_back('$');
  101. break;
  102. case '#':
  103. Res.push_back('\\');
  104. break;
  105. default:
  106. break;
  107. }
  108. Res.push_back(Target[i]);
  109. }
  110. }
  111. /// Apply \a Work on the current tool chain \a RegularToolChain and any other
  112. /// offloading tool chain that is associated with the current action \a JA.
  113. static void
  114. forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
  115. const ToolChain &RegularToolChain,
  116. llvm::function_ref<void(const ToolChain &)> Work) {
  117. // Apply Work on the current/regular tool chain.
  118. Work(RegularToolChain);
  119. // Apply Work on all the offloading tool chains associated with the current
  120. // action.
  121. if (JA.isHostOffloading(Action::OFK_Cuda))
  122. Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
  123. else if (JA.isDeviceOffloading(Action::OFK_Cuda))
  124. Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
  125. else if (JA.isHostOffloading(Action::OFK_HIP))
  126. Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
  127. else if (JA.isDeviceOffloading(Action::OFK_HIP))
  128. Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
  129. if (JA.isHostOffloading(Action::OFK_OpenMP)) {
  130. auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
  131. for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
  132. Work(*II->second);
  133. } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
  134. Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
  135. //
  136. // TODO: Add support for other offloading programming models here.
  137. //
  138. }
  139. /// This is a helper function for validating the optional refinement step
  140. /// parameter in reciprocal argument strings. Return false if there is an error
  141. /// parsing the refinement step. Otherwise, return true and set the Position
  142. /// of the refinement step in the input string.
  143. static bool getRefinementStep(StringRef In, const Driver &D,
  144. const Arg &A, size_t &Position) {
  145. const char RefinementStepToken = ':';
  146. Position = In.find(RefinementStepToken);
  147. if (Position != StringRef::npos) {
  148. StringRef Option = A.getOption().getName();
  149. StringRef RefStep = In.substr(Position + 1);
  150. // Allow exactly one numeric character for the additional refinement
  151. // step parameter. This is reasonable for all currently-supported
  152. // operations and architectures because we would expect that a larger value
  153. // of refinement steps would cause the estimate "optimization" to
  154. // under-perform the native operation. Also, if the estimate does not
  155. // converge quickly, it probably will not ever converge, so further
  156. // refinement steps will not produce a better answer.
  157. if (RefStep.size() != 1) {
  158. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  159. return false;
  160. }
  161. char RefStepChar = RefStep[0];
  162. if (RefStepChar < '0' || RefStepChar > '9') {
  163. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  164. return false;
  165. }
  166. }
  167. return true;
  168. }
  169. /// The -mrecip flag requires processing of many optional parameters.
  170. static void ParseMRecip(const Driver &D, const ArgList &Args,
  171. ArgStringList &OutStrings) {
  172. StringRef DisabledPrefixIn = "!";
  173. StringRef DisabledPrefixOut = "!";
  174. StringRef EnabledPrefixOut = "";
  175. StringRef Out = "-mrecip=";
  176. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  177. if (!A)
  178. return;
  179. unsigned NumOptions = A->getNumValues();
  180. if (NumOptions == 0) {
  181. // No option is the same as "all".
  182. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  183. return;
  184. }
  185. // Pass through "all", "none", or "default" with an optional refinement step.
  186. if (NumOptions == 1) {
  187. StringRef Val = A->getValue(0);
  188. size_t RefStepLoc;
  189. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  190. return;
  191. StringRef ValBase = Val.slice(0, RefStepLoc);
  192. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  193. OutStrings.push_back(Args.MakeArgString(Out + Val));
  194. return;
  195. }
  196. }
  197. // Each reciprocal type may be enabled or disabled individually.
  198. // Check each input value for validity, concatenate them all back together,
  199. // and pass through.
  200. llvm::StringMap<bool> OptionStrings;
  201. OptionStrings.insert(std::make_pair("divd", false));
  202. OptionStrings.insert(std::make_pair("divf", false));
  203. OptionStrings.insert(std::make_pair("vec-divd", false));
  204. OptionStrings.insert(std::make_pair("vec-divf", false));
  205. OptionStrings.insert(std::make_pair("sqrtd", false));
  206. OptionStrings.insert(std::make_pair("sqrtf", false));
  207. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  208. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  209. for (unsigned i = 0; i != NumOptions; ++i) {
  210. StringRef Val = A->getValue(i);
  211. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  212. // Ignore the disablement token for string matching.
  213. if (IsDisabled)
  214. Val = Val.substr(1);
  215. size_t RefStep;
  216. if (!getRefinementStep(Val, D, *A, RefStep))
  217. return;
  218. StringRef ValBase = Val.slice(0, RefStep);
  219. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  220. if (OptionIter == OptionStrings.end()) {
  221. // Try again specifying float suffix.
  222. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  223. if (OptionIter == OptionStrings.end()) {
  224. // The input name did not match any known option string.
  225. D.Diag(diag::err_drv_unknown_argument) << Val;
  226. return;
  227. }
  228. // The option was specified without a float or double suffix.
  229. // Make sure that the double entry was not already specified.
  230. // The float entry will be checked below.
  231. if (OptionStrings[ValBase.str() + 'd']) {
  232. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  233. return;
  234. }
  235. }
  236. if (OptionIter->second == true) {
  237. // Duplicate option specified.
  238. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  239. return;
  240. }
  241. // Mark the matched option as found. Do not allow duplicate specifiers.
  242. OptionIter->second = true;
  243. // If the precision was not specified, also mark the double entry as found.
  244. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  245. OptionStrings[ValBase.str() + 'd'] = true;
  246. // Build the output string.
  247. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  248. Out = Args.MakeArgString(Out + Prefix + Val);
  249. if (i != NumOptions - 1)
  250. Out = Args.MakeArgString(Out + ",");
  251. }
  252. OutStrings.push_back(Args.MakeArgString(Out));
  253. }
  254. /// The -mprefer-vector-width option accepts either a positive integer
  255. /// or the string "none".
  256. static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
  257. ArgStringList &CmdArgs) {
  258. Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
  259. if (!A)
  260. return;
  261. StringRef Value = A->getValue();
  262. if (Value == "none") {
  263. CmdArgs.push_back("-mprefer-vector-width=none");
  264. } else {
  265. unsigned Width;
  266. if (Value.getAsInteger(10, Width)) {
  267. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
  268. return;
  269. }
  270. CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
  271. }
  272. }
  273. static bool
  274. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  275. const llvm::Triple &Triple) {
  276. // We use the zero-cost exception tables for Objective-C if the non-fragile
  277. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  278. // later.
  279. if (runtime.isNonFragile())
  280. return true;
  281. if (!Triple.isMacOSX())
  282. return false;
  283. return (!Triple.isMacOSXVersionLT(10, 5) &&
  284. (Triple.getArch() == llvm::Triple::x86_64 ||
  285. Triple.getArch() == llvm::Triple::arm));
  286. }
  287. /// Adds exception related arguments to the driver command arguments. There's a
  288. /// master flag, -fexceptions and also language specific flags to enable/disable
  289. /// C++ and Objective-C exceptions. This makes it possible to for example
  290. /// disable C++ exceptions but enable Objective-C exceptions.
  291. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  292. const ToolChain &TC, bool KernelOrKext,
  293. const ObjCRuntime &objcRuntime,
  294. ArgStringList &CmdArgs) {
  295. const llvm::Triple &Triple = TC.getTriple();
  296. if (KernelOrKext) {
  297. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  298. // arguments now to avoid warnings about unused arguments.
  299. Args.ClaimAllArgs(options::OPT_fexceptions);
  300. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  301. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  302. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  303. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  304. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  305. return;
  306. }
  307. // See if the user explicitly enabled exceptions.
  308. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  309. false);
  310. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  311. // is not necessarily sensible, but follows GCC.
  312. if (types::isObjC(InputType) &&
  313. Args.hasFlag(options::OPT_fobjc_exceptions,
  314. options::OPT_fno_objc_exceptions, true)) {
  315. CmdArgs.push_back("-fobjc-exceptions");
  316. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  317. }
  318. if (types::isCXX(InputType)) {
  319. // Disable C++ EH by default on XCore and PS4.
  320. bool CXXExceptionsEnabled =
  321. Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
  322. Arg *ExceptionArg = Args.getLastArg(
  323. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  324. options::OPT_fexceptions, options::OPT_fno_exceptions);
  325. if (ExceptionArg)
  326. CXXExceptionsEnabled =
  327. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  328. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  329. if (CXXExceptionsEnabled) {
  330. CmdArgs.push_back("-fcxx-exceptions");
  331. EH = true;
  332. }
  333. }
  334. if (EH)
  335. CmdArgs.push_back("-fexceptions");
  336. }
  337. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  338. bool Default = true;
  339. if (TC.getTriple().isOSDarwin()) {
  340. // The native darwin assembler doesn't support the linker_option directives,
  341. // so we disable them if we think the .s file will be passed to it.
  342. Default = TC.useIntegratedAs();
  343. }
  344. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  345. Default);
  346. }
  347. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  348. const ToolChain &TC) {
  349. bool UseDwarfDirectory =
  350. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  351. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  352. return !UseDwarfDirectory;
  353. }
  354. // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
  355. // to the corresponding DebugInfoKind.
  356. static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
  357. assert(A.getOption().matches(options::OPT_gN_Group) &&
  358. "Not a -g option that specifies a debug-info level");
  359. if (A.getOption().matches(options::OPT_g0) ||
  360. A.getOption().matches(options::OPT_ggdb0))
  361. return codegenoptions::NoDebugInfo;
  362. if (A.getOption().matches(options::OPT_gline_tables_only) ||
  363. A.getOption().matches(options::OPT_ggdb1))
  364. return codegenoptions::DebugLineTablesOnly;
  365. if (A.getOption().matches(options::OPT_gline_directives_only))
  366. return codegenoptions::DebugDirectivesOnly;
  367. return codegenoptions::LimitedDebugInfo;
  368. }
  369. static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
  370. switch (Triple.getArch()){
  371. default:
  372. return false;
  373. case llvm::Triple::arm:
  374. case llvm::Triple::thumb:
  375. // ARM Darwin targets require a frame pointer to be always present to aid
  376. // offline debugging via backtraces.
  377. return Triple.isOSDarwin();
  378. }
  379. }
  380. static bool useFramePointerForTargetByDefault(const ArgList &Args,
  381. const llvm::Triple &Triple) {
  382. if (Args.hasArg(options::OPT_pg))
  383. return true;
  384. switch (Triple.getArch()) {
  385. case llvm::Triple::xcore:
  386. case llvm::Triple::wasm32:
  387. case llvm::Triple::wasm64:
  388. case llvm::Triple::msp430:
  389. // XCore never wants frame pointers, regardless of OS.
  390. // WebAssembly never wants frame pointers.
  391. return false;
  392. case llvm::Triple::ppc:
  393. case llvm::Triple::ppc64:
  394. case llvm::Triple::ppc64le:
  395. case llvm::Triple::riscv32:
  396. case llvm::Triple::riscv64:
  397. return !areOptimizationsEnabled(Args);
  398. default:
  399. break;
  400. }
  401. if (Triple.isOSNetBSD()) {
  402. return !areOptimizationsEnabled(Args);
  403. }
  404. if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
  405. Triple.isOSHurd()) {
  406. switch (Triple.getArch()) {
  407. // Don't use a frame pointer on linux if optimizing for certain targets.
  408. case llvm::Triple::mips64:
  409. case llvm::Triple::mips64el:
  410. case llvm::Triple::mips:
  411. case llvm::Triple::mipsel:
  412. case llvm::Triple::systemz:
  413. case llvm::Triple::x86:
  414. case llvm::Triple::x86_64:
  415. return !areOptimizationsEnabled(Args);
  416. default:
  417. return true;
  418. }
  419. }
  420. if (Triple.isOSWindows()) {
  421. switch (Triple.getArch()) {
  422. case llvm::Triple::x86:
  423. return !areOptimizationsEnabled(Args);
  424. case llvm::Triple::x86_64:
  425. return Triple.isOSBinFormatMachO();
  426. case llvm::Triple::arm:
  427. case llvm::Triple::thumb:
  428. // Windows on ARM builds with FPO disabled to aid fast stack walking
  429. return true;
  430. default:
  431. // All other supported Windows ISAs use xdata unwind information, so frame
  432. // pointers are not generally useful.
  433. return false;
  434. }
  435. }
  436. return true;
  437. }
  438. static CodeGenOptions::FramePointerKind
  439. getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
  440. // We have 4 states:
  441. //
  442. // 00) leaf retained, non-leaf retained
  443. // 01) leaf retained, non-leaf omitted (this is invalid)
  444. // 10) leaf omitted, non-leaf retained
  445. // (what -momit-leaf-frame-pointer was designed for)
  446. // 11) leaf omitted, non-leaf omitted
  447. //
  448. // "omit" options taking precedence over "no-omit" options is the only way
  449. // to make 3 valid states representable
  450. Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  451. options::OPT_fno_omit_frame_pointer);
  452. bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
  453. bool NoOmitFP =
  454. A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  455. bool KeepLeaf =
  456. Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
  457. options::OPT_mno_omit_leaf_frame_pointer, Triple.isPS4CPU());
  458. if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
  459. (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
  460. if (KeepLeaf)
  461. return CodeGenOptions::FramePointerKind::NonLeaf;
  462. return CodeGenOptions::FramePointerKind::All;
  463. }
  464. return CodeGenOptions::FramePointerKind::None;
  465. }
  466. /// Add a CC1 option to specify the debug compilation directory.
  467. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
  468. const llvm::vfs::FileSystem &VFS) {
  469. if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
  470. CmdArgs.push_back("-fdebug-compilation-dir");
  471. CmdArgs.push_back(A->getValue());
  472. } else if (llvm::ErrorOr<std::string> CWD =
  473. VFS.getCurrentWorkingDirectory()) {
  474. CmdArgs.push_back("-fdebug-compilation-dir");
  475. CmdArgs.push_back(Args.MakeArgString(*CWD));
  476. }
  477. }
  478. /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
  479. static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
  480. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  481. StringRef Map = A->getValue();
  482. if (Map.find('=') == StringRef::npos)
  483. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  484. else
  485. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  486. A->claim();
  487. }
  488. }
  489. /// Vectorize at all optimization levels greater than 1 except for -Oz.
  490. /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
  491. /// enabled.
  492. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  493. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  494. if (A->getOption().matches(options::OPT_O4) ||
  495. A->getOption().matches(options::OPT_Ofast))
  496. return true;
  497. if (A->getOption().matches(options::OPT_O0))
  498. return false;
  499. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  500. // Vectorize -Os.
  501. StringRef S(A->getValue());
  502. if (S == "s")
  503. return true;
  504. // Don't vectorize -Oz, unless it's the slp vectorizer.
  505. if (S == "z")
  506. return isSlpVec;
  507. unsigned OptLevel = 0;
  508. if (S.getAsInteger(10, OptLevel))
  509. return false;
  510. return OptLevel > 1;
  511. }
  512. return false;
  513. }
  514. /// Add -x lang to \p CmdArgs for \p Input.
  515. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  516. ArgStringList &CmdArgs) {
  517. // When using -verify-pch, we don't want to provide the type
  518. // 'precompiled-header' if it was inferred from the file extension
  519. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  520. return;
  521. CmdArgs.push_back("-x");
  522. if (Args.hasArg(options::OPT_rewrite_objc))
  523. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  524. else {
  525. // Map the driver type to the frontend type. This is mostly an identity
  526. // mapping, except that the distinction between module interface units
  527. // and other source files does not exist at the frontend layer.
  528. const char *ClangType;
  529. switch (Input.getType()) {
  530. case types::TY_CXXModule:
  531. ClangType = "c++";
  532. break;
  533. case types::TY_PP_CXXModule:
  534. ClangType = "c++-cpp-output";
  535. break;
  536. default:
  537. ClangType = types::getTypeName(Input.getType());
  538. break;
  539. }
  540. CmdArgs.push_back(ClangType);
  541. }
  542. }
  543. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  544. #ifdef LLVM_ON_UNIX
  545. const char *Username = getenv("LOGNAME");
  546. #else
  547. const char *Username = getenv("USERNAME");
  548. #endif
  549. if (Username) {
  550. // Validate that LoginName can be used in a path, and get its length.
  551. size_t Len = 0;
  552. for (const char *P = Username; *P; ++P, ++Len) {
  553. if (!clang::isAlphanumeric(*P) && *P != '_') {
  554. Username = nullptr;
  555. break;
  556. }
  557. }
  558. if (Username && Len > 0) {
  559. Result.append(Username, Username + Len);
  560. return;
  561. }
  562. }
  563. // Fallback to user id.
  564. #ifdef LLVM_ON_UNIX
  565. std::string UID = llvm::utostr(getuid());
  566. #else
  567. // FIXME: Windows seems to have an 'SID' that might work.
  568. std::string UID = "9999";
  569. #endif
  570. Result.append(UID.begin(), UID.end());
  571. }
  572. static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
  573. const Driver &D, const InputInfo &Output,
  574. const ArgList &Args,
  575. ArgStringList &CmdArgs) {
  576. auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
  577. options::OPT_fprofile_generate_EQ,
  578. options::OPT_fno_profile_generate);
  579. if (PGOGenerateArg &&
  580. PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
  581. PGOGenerateArg = nullptr;
  582. auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
  583. options::OPT_fcs_profile_generate_EQ,
  584. options::OPT_fno_profile_generate);
  585. if (CSPGOGenerateArg &&
  586. CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
  587. CSPGOGenerateArg = nullptr;
  588. auto *ProfileGenerateArg = Args.getLastArg(
  589. options::OPT_fprofile_instr_generate,
  590. options::OPT_fprofile_instr_generate_EQ,
  591. options::OPT_fno_profile_instr_generate);
  592. if (ProfileGenerateArg &&
  593. ProfileGenerateArg->getOption().matches(
  594. options::OPT_fno_profile_instr_generate))
  595. ProfileGenerateArg = nullptr;
  596. if (PGOGenerateArg && ProfileGenerateArg)
  597. D.Diag(diag::err_drv_argument_not_allowed_with)
  598. << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
  599. auto *ProfileUseArg = getLastProfileUseArg(Args);
  600. if (PGOGenerateArg && ProfileUseArg)
  601. D.Diag(diag::err_drv_argument_not_allowed_with)
  602. << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
  603. if (ProfileGenerateArg && ProfileUseArg)
  604. D.Diag(diag::err_drv_argument_not_allowed_with)
  605. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  606. if (CSPGOGenerateArg && PGOGenerateArg)
  607. D.Diag(diag::err_drv_argument_not_allowed_with)
  608. << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
  609. if (ProfileGenerateArg) {
  610. if (ProfileGenerateArg->getOption().matches(
  611. options::OPT_fprofile_instr_generate_EQ))
  612. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
  613. ProfileGenerateArg->getValue()));
  614. // The default is to use Clang Instrumentation.
  615. CmdArgs.push_back("-fprofile-instrument=clang");
  616. if (TC.getTriple().isWindowsMSVCEnvironment()) {
  617. // Add dependent lib for clang_rt.profile
  618. CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
  619. TC.getCompilerRT(Args, "profile")));
  620. }
  621. }
  622. Arg *PGOGenArg = nullptr;
  623. if (PGOGenerateArg) {
  624. assert(!CSPGOGenerateArg);
  625. PGOGenArg = PGOGenerateArg;
  626. CmdArgs.push_back("-fprofile-instrument=llvm");
  627. }
  628. if (CSPGOGenerateArg) {
  629. assert(!PGOGenerateArg);
  630. PGOGenArg = CSPGOGenerateArg;
  631. CmdArgs.push_back("-fprofile-instrument=csllvm");
  632. }
  633. if (PGOGenArg) {
  634. if (TC.getTriple().isWindowsMSVCEnvironment()) {
  635. CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
  636. TC.getCompilerRT(Args, "profile")));
  637. }
  638. if (PGOGenArg->getOption().matches(
  639. PGOGenerateArg ? options::OPT_fprofile_generate_EQ
  640. : options::OPT_fcs_profile_generate_EQ)) {
  641. SmallString<128> Path(PGOGenArg->getValue());
  642. llvm::sys::path::append(Path, "default_%m.profraw");
  643. CmdArgs.push_back(
  644. Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
  645. }
  646. }
  647. if (ProfileUseArg) {
  648. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  649. CmdArgs.push_back(Args.MakeArgString(
  650. Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
  651. else if ((ProfileUseArg->getOption().matches(
  652. options::OPT_fprofile_use_EQ) ||
  653. ProfileUseArg->getOption().matches(
  654. options::OPT_fprofile_instr_use))) {
  655. SmallString<128> Path(
  656. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  657. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  658. llvm::sys::path::append(Path, "default.profdata");
  659. CmdArgs.push_back(
  660. Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
  661. }
  662. }
  663. bool EmitCovNotes = Args.hasArg(options::OPT_ftest_coverage) ||
  664. Args.hasArg(options::OPT_coverage);
  665. bool EmitCovData = Args.hasFlag(options::OPT_fprofile_arcs,
  666. options::OPT_fno_profile_arcs, false) ||
  667. Args.hasArg(options::OPT_coverage);
  668. if (EmitCovNotes)
  669. CmdArgs.push_back("-femit-coverage-notes");
  670. if (EmitCovData)
  671. CmdArgs.push_back("-femit-coverage-data");
  672. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  673. options::OPT_fno_coverage_mapping, false)) {
  674. if (!ProfileGenerateArg)
  675. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  676. << "-fcoverage-mapping"
  677. << "-fprofile-instr-generate";
  678. CmdArgs.push_back("-fcoverage-mapping");
  679. }
  680. if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
  681. auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
  682. if (!Args.hasArg(options::OPT_coverage))
  683. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  684. << "-fprofile-exclude-files="
  685. << "--coverage";
  686. StringRef v = Arg->getValue();
  687. CmdArgs.push_back(
  688. Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
  689. }
  690. if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
  691. auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
  692. if (!Args.hasArg(options::OPT_coverage))
  693. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  694. << "-fprofile-filter-files="
  695. << "--coverage";
  696. StringRef v = Arg->getValue();
  697. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
  698. }
  699. // Leave -fprofile-dir= an unused argument unless .gcda emission is
  700. // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
  701. // the flag used. There is no -fno-profile-dir, so the user has no
  702. // targeted way to suppress the warning.
  703. Arg *FProfileDir = nullptr;
  704. if (Args.hasArg(options::OPT_fprofile_arcs) ||
  705. Args.hasArg(options::OPT_coverage))
  706. FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
  707. // Put the .gcno and .gcda files (if needed) next to the object file or
  708. // bitcode file in the case of LTO.
  709. // FIXME: There should be a simpler way to find the object file for this
  710. // input, and this code probably does the wrong thing for commands that
  711. // compile and link all at once.
  712. if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
  713. (EmitCovNotes || EmitCovData) && Output.isFilename()) {
  714. SmallString<128> OutputFilename;
  715. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  716. OutputFilename = FinalOutput->getValue();
  717. else
  718. OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
  719. SmallString<128> CoverageFilename = OutputFilename;
  720. if (llvm::sys::path::is_relative(CoverageFilename))
  721. (void)D.getVFS().makeAbsolute(CoverageFilename);
  722. llvm::sys::path::replace_extension(CoverageFilename, "gcno");
  723. CmdArgs.push_back("-coverage-notes-file");
  724. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  725. if (EmitCovData) {
  726. if (FProfileDir) {
  727. CoverageFilename = FProfileDir->getValue();
  728. llvm::sys::path::append(CoverageFilename, OutputFilename);
  729. }
  730. llvm::sys::path::replace_extension(CoverageFilename, "gcda");
  731. CmdArgs.push_back("-coverage-data-file");
  732. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  733. }
  734. }
  735. }
  736. /// Check whether the given input tree contains any compilation actions.
  737. static bool ContainsCompileAction(const Action *A) {
  738. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  739. return true;
  740. for (const auto &AI : A->inputs())
  741. if (ContainsCompileAction(AI))
  742. return true;
  743. return false;
  744. }
  745. /// Check if -relax-all should be passed to the internal assembler.
  746. /// This is done by default when compiling non-assembler source with -O0.
  747. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  748. bool RelaxDefault = true;
  749. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  750. RelaxDefault = A->getOption().matches(options::OPT_O0);
  751. if (RelaxDefault) {
  752. RelaxDefault = false;
  753. for (const auto &Act : C.getActions()) {
  754. if (ContainsCompileAction(Act)) {
  755. RelaxDefault = true;
  756. break;
  757. }
  758. }
  759. }
  760. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  761. RelaxDefault);
  762. }
  763. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  764. // on mismatch. The StringRef input (rather than an Arg) allows
  765. // for use by the "-Xassembler" option parser.
  766. static unsigned DwarfVersionNum(StringRef ArgValue) {
  767. return llvm::StringSwitch<unsigned>(ArgValue)
  768. .Case("-gdwarf-2", 2)
  769. .Case("-gdwarf-3", 3)
  770. .Case("-gdwarf-4", 4)
  771. .Case("-gdwarf-5", 5)
  772. .Default(0);
  773. }
  774. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  775. codegenoptions::DebugInfoKind DebugInfoKind,
  776. unsigned DwarfVersion,
  777. llvm::DebuggerKind DebuggerTuning) {
  778. switch (DebugInfoKind) {
  779. case codegenoptions::DebugDirectivesOnly:
  780. CmdArgs.push_back("-debug-info-kind=line-directives-only");
  781. break;
  782. case codegenoptions::DebugLineTablesOnly:
  783. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  784. break;
  785. case codegenoptions::LimitedDebugInfo:
  786. CmdArgs.push_back("-debug-info-kind=limited");
  787. break;
  788. case codegenoptions::FullDebugInfo:
  789. CmdArgs.push_back("-debug-info-kind=standalone");
  790. break;
  791. default:
  792. break;
  793. }
  794. if (DwarfVersion > 0)
  795. CmdArgs.push_back(
  796. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  797. switch (DebuggerTuning) {
  798. case llvm::DebuggerKind::GDB:
  799. CmdArgs.push_back("-debugger-tuning=gdb");
  800. break;
  801. case llvm::DebuggerKind::LLDB:
  802. CmdArgs.push_back("-debugger-tuning=lldb");
  803. break;
  804. case llvm::DebuggerKind::SCE:
  805. CmdArgs.push_back("-debugger-tuning=sce");
  806. break;
  807. default:
  808. break;
  809. }
  810. }
  811. static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
  812. const Driver &D, const ToolChain &TC) {
  813. assert(A && "Expected non-nullptr argument.");
  814. if (TC.supportsDebugInfoOption(A))
  815. return true;
  816. D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
  817. << A->getAsString(Args) << TC.getTripleString();
  818. return false;
  819. }
  820. static void RenderDebugInfoCompressionArgs(const ArgList &Args,
  821. ArgStringList &CmdArgs,
  822. const Driver &D,
  823. const ToolChain &TC) {
  824. const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
  825. if (!A)
  826. return;
  827. if (checkDebugInfoOption(A, Args, D, TC)) {
  828. if (A->getOption().getID() == options::OPT_gz) {
  829. if (llvm::zlib::isAvailable())
  830. CmdArgs.push_back("--compress-debug-sections");
  831. else
  832. D.Diag(diag::warn_debug_compression_unavailable);
  833. return;
  834. }
  835. StringRef Value = A->getValue();
  836. if (Value == "none") {
  837. CmdArgs.push_back("--compress-debug-sections=none");
  838. } else if (Value == "zlib" || Value == "zlib-gnu") {
  839. if (llvm::zlib::isAvailable()) {
  840. CmdArgs.push_back(
  841. Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
  842. } else {
  843. D.Diag(diag::warn_debug_compression_unavailable);
  844. }
  845. } else {
  846. D.Diag(diag::err_drv_unsupported_option_argument)
  847. << A->getOption().getName() << Value;
  848. }
  849. }
  850. }
  851. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  852. switch (Model) {
  853. case llvm::Reloc::Static:
  854. return "static";
  855. case llvm::Reloc::PIC_:
  856. return "pic";
  857. case llvm::Reloc::DynamicNoPIC:
  858. return "dynamic-no-pic";
  859. case llvm::Reloc::ROPI:
  860. return "ropi";
  861. case llvm::Reloc::RWPI:
  862. return "rwpi";
  863. case llvm::Reloc::ROPI_RWPI:
  864. return "ropi-rwpi";
  865. }
  866. llvm_unreachable("Unknown Reloc::Model kind");
  867. }
  868. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  869. const Driver &D, const ArgList &Args,
  870. ArgStringList &CmdArgs,
  871. const InputInfo &Output,
  872. const InputInfoList &Inputs) const {
  873. const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
  874. CheckPreprocessingOptions(D, Args);
  875. Args.AddLastArg(CmdArgs, options::OPT_C);
  876. Args.AddLastArg(CmdArgs, options::OPT_CC);
  877. // Handle dependency file generation.
  878. Arg *ArgM = Args.getLastArg(options::OPT_MM);
  879. if (!ArgM)
  880. ArgM = Args.getLastArg(options::OPT_M);
  881. Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
  882. if (!ArgMD)
  883. ArgMD = Args.getLastArg(options::OPT_MD);
  884. // -M and -MM imply -w.
  885. if (ArgM)
  886. CmdArgs.push_back("-w");
  887. else
  888. ArgM = ArgMD;
  889. if (ArgM) {
  890. // Determine the output location.
  891. const char *DepFile;
  892. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  893. DepFile = MF->getValue();
  894. C.addFailureResultFile(DepFile, &JA);
  895. } else if (Output.getType() == types::TY_Dependencies) {
  896. DepFile = Output.getFilename();
  897. } else if (!ArgMD) {
  898. DepFile = "-";
  899. } else {
  900. DepFile = getDependencyFileName(Args, Inputs);
  901. C.addFailureResultFile(DepFile, &JA);
  902. }
  903. CmdArgs.push_back("-dependency-file");
  904. CmdArgs.push_back(DepFile);
  905. bool HasTarget = false;
  906. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  907. HasTarget = true;
  908. A->claim();
  909. if (A->getOption().matches(options::OPT_MT)) {
  910. A->render(Args, CmdArgs);
  911. } else {
  912. CmdArgs.push_back("-MT");
  913. SmallString<128> Quoted;
  914. QuoteTarget(A->getValue(), Quoted);
  915. CmdArgs.push_back(Args.MakeArgString(Quoted));
  916. }
  917. }
  918. // Add a default target if one wasn't specified.
  919. if (!HasTarget) {
  920. const char *DepTarget;
  921. // If user provided -o, that is the dependency target, except
  922. // when we are only generating a dependency file.
  923. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  924. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  925. DepTarget = OutputOpt->getValue();
  926. } else {
  927. // Otherwise derive from the base input.
  928. //
  929. // FIXME: This should use the computed output file location.
  930. SmallString<128> P(Inputs[0].getBaseInput());
  931. llvm::sys::path::replace_extension(P, "o");
  932. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  933. }
  934. CmdArgs.push_back("-MT");
  935. SmallString<128> Quoted;
  936. QuoteTarget(DepTarget, Quoted);
  937. CmdArgs.push_back(Args.MakeArgString(Quoted));
  938. }
  939. if (ArgM->getOption().matches(options::OPT_M) ||
  940. ArgM->getOption().matches(options::OPT_MD))
  941. CmdArgs.push_back("-sys-header-deps");
  942. if ((isa<PrecompileJobAction>(JA) &&
  943. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  944. Args.hasArg(options::OPT_fmodule_file_deps))
  945. CmdArgs.push_back("-module-file-deps");
  946. }
  947. if (Args.hasArg(options::OPT_MG)) {
  948. if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
  949. ArgM->getOption().matches(options::OPT_MMD))
  950. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  951. CmdArgs.push_back("-MG");
  952. }
  953. Args.AddLastArg(CmdArgs, options::OPT_MP);
  954. Args.AddLastArg(CmdArgs, options::OPT_MV);
  955. // Add offload include arguments specific for CUDA. This must happen before
  956. // we -I or -include anything else, because we must pick up the CUDA headers
  957. // from the particular CUDA installation, rather than from e.g.
  958. // /usr/local/include.
  959. if (JA.isOffloading(Action::OFK_Cuda))
  960. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  961. // If we are offloading to a target via OpenMP we need to include the
  962. // openmp_wrappers folder which contains alternative system headers.
  963. if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
  964. getToolChain().getTriple().isNVPTX()){
  965. if (!Args.hasArg(options::OPT_nobuiltininc)) {
  966. // Add openmp_wrappers/* to our system include path. This lets us wrap
  967. // standard library headers.
  968. SmallString<128> P(D.ResourceDir);
  969. llvm::sys::path::append(P, "include");
  970. llvm::sys::path::append(P, "openmp_wrappers");
  971. CmdArgs.push_back("-internal-isystem");
  972. CmdArgs.push_back(Args.MakeArgString(P));
  973. }
  974. CmdArgs.push_back("-include");
  975. CmdArgs.push_back("__clang_openmp_math_declares.h");
  976. }
  977. // Add -i* options, and automatically translate to
  978. // -include-pch/-include-pth for transparent PCH support. It's
  979. // wonky, but we include looking for .gch so we can support seamless
  980. // replacement into a build system already set up to be generating
  981. // .gch files.
  982. if (getToolChain().getDriver().IsCLMode()) {
  983. const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  984. const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  985. if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
  986. JA.getKind() <= Action::AssembleJobClass) {
  987. CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
  988. }
  989. if (YcArg || YuArg) {
  990. StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
  991. if (!isa<PrecompileJobAction>(JA)) {
  992. CmdArgs.push_back("-include-pch");
  993. CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
  994. C, !ThroughHeader.empty()
  995. ? ThroughHeader
  996. : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
  997. }
  998. if (ThroughHeader.empty()) {
  999. CmdArgs.push_back(Args.MakeArgString(
  1000. Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
  1001. } else {
  1002. CmdArgs.push_back(
  1003. Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
  1004. }
  1005. }
  1006. }
  1007. bool RenderedImplicitInclude = false;
  1008. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  1009. if (A->getOption().matches(options::OPT_include)) {
  1010. // Handling of gcc-style gch precompiled headers.
  1011. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  1012. RenderedImplicitInclude = true;
  1013. bool FoundPCH = false;
  1014. SmallString<128> P(A->getValue());
  1015. // We want the files to have a name like foo.h.pch. Add a dummy extension
  1016. // so that replace_extension does the right thing.
  1017. P += ".dummy";
  1018. llvm::sys::path::replace_extension(P, "pch");
  1019. if (llvm::sys::fs::exists(P))
  1020. FoundPCH = true;
  1021. if (!FoundPCH) {
  1022. llvm::sys::path::replace_extension(P, "gch");
  1023. if (llvm::sys::fs::exists(P)) {
  1024. FoundPCH = true;
  1025. }
  1026. }
  1027. if (FoundPCH) {
  1028. if (IsFirstImplicitInclude) {
  1029. A->claim();
  1030. CmdArgs.push_back("-include-pch");
  1031. CmdArgs.push_back(Args.MakeArgString(P));
  1032. continue;
  1033. } else {
  1034. // Ignore the PCH if not first on command line and emit warning.
  1035. D.Diag(diag::warn_drv_pch_not_first_include) << P
  1036. << A->getAsString(Args);
  1037. }
  1038. }
  1039. } else if (A->getOption().matches(options::OPT_isystem_after)) {
  1040. // Handling of paths which must come late. These entries are handled by
  1041. // the toolchain itself after the resource dir is inserted in the right
  1042. // search order.
  1043. // Do not claim the argument so that the use of the argument does not
  1044. // silently go unnoticed on toolchains which do not honour the option.
  1045. continue;
  1046. } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
  1047. // Translated to -internal-isystem by the driver, no need to pass to cc1.
  1048. continue;
  1049. }
  1050. // Not translated, render as usual.
  1051. A->claim();
  1052. A->render(Args, CmdArgs);
  1053. }
  1054. Args.AddAllArgs(CmdArgs,
  1055. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  1056. options::OPT_F, options::OPT_index_header_map});
  1057. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  1058. // FIXME: There is a very unfortunate problem here, some troubled
  1059. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  1060. // really support that we would have to parse and then translate
  1061. // those options. :(
  1062. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  1063. options::OPT_Xpreprocessor);
  1064. // -I- is a deprecated GCC feature, reject it.
  1065. if (Arg *A = Args.getLastArg(options::OPT_I_))
  1066. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  1067. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  1068. // -isysroot to the CC1 invocation.
  1069. StringRef sysroot = C.getSysRoot();
  1070. if (sysroot != "") {
  1071. if (!Args.hasArg(options::OPT_isysroot)) {
  1072. CmdArgs.push_back("-isysroot");
  1073. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  1074. }
  1075. }
  1076. // Parse additional include paths from environment variables.
  1077. // FIXME: We should probably sink the logic for handling these from the
  1078. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  1079. // CPATH - included following the user specified includes (but prior to
  1080. // builtin and standard includes).
  1081. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  1082. // C_INCLUDE_PATH - system includes enabled when compiling C.
  1083. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  1084. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  1085. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  1086. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  1087. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  1088. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  1089. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  1090. // While adding the include arguments, we also attempt to retrieve the
  1091. // arguments of related offloading toolchains or arguments that are specific
  1092. // of an offloading programming model.
  1093. // Add C++ include arguments, if needed.
  1094. if (types::isCXX(Inputs[0].getType())) {
  1095. bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
  1096. forAllAssociatedToolChains(
  1097. C, JA, getToolChain(),
  1098. [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
  1099. HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
  1100. : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  1101. });
  1102. }
  1103. // Add system include arguments for all targets but IAMCU.
  1104. if (!IsIAMCU)
  1105. forAllAssociatedToolChains(C, JA, getToolChain(),
  1106. [&Args, &CmdArgs](const ToolChain &TC) {
  1107. TC.AddClangSystemIncludeArgs(Args, CmdArgs);
  1108. });
  1109. else {
  1110. // For IAMCU add special include arguments.
  1111. getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
  1112. }
  1113. }
  1114. // FIXME: Move to target hook.
  1115. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  1116. switch (Triple.getArch()) {
  1117. default:
  1118. return true;
  1119. case llvm::Triple::aarch64:
  1120. case llvm::Triple::aarch64_be:
  1121. case llvm::Triple::arm:
  1122. case llvm::Triple::armeb:
  1123. case llvm::Triple::thumb:
  1124. case llvm::Triple::thumbeb:
  1125. if (Triple.isOSDarwin() || Triple.isOSWindows())
  1126. return true;
  1127. return false;
  1128. case llvm::Triple::ppc:
  1129. case llvm::Triple::ppc64:
  1130. if (Triple.isOSDarwin())
  1131. return true;
  1132. return false;
  1133. case llvm::Triple::hexagon:
  1134. case llvm::Triple::ppc64le:
  1135. case llvm::Triple::riscv32:
  1136. case llvm::Triple::riscv64:
  1137. case llvm::Triple::systemz:
  1138. case llvm::Triple::xcore:
  1139. return false;
  1140. }
  1141. }
  1142. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  1143. switch (Triple.getArch()) {
  1144. default:
  1145. if (Triple.isOSFuchsia())
  1146. return true;
  1147. return false;
  1148. case llvm::Triple::xcore:
  1149. case llvm::Triple::wasm32:
  1150. case llvm::Triple::wasm64:
  1151. return true;
  1152. }
  1153. }
  1154. namespace {
  1155. void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
  1156. ArgStringList &CmdArgs) {
  1157. // Select the ABI to use.
  1158. // FIXME: Support -meabi.
  1159. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  1160. const char *ABIName = nullptr;
  1161. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1162. ABIName = A->getValue();
  1163. } else {
  1164. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  1165. ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
  1166. }
  1167. CmdArgs.push_back("-target-abi");
  1168. CmdArgs.push_back(ABIName);
  1169. }
  1170. }
  1171. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  1172. ArgStringList &CmdArgs, bool KernelOrKext) const {
  1173. RenderARMABI(Triple, Args, CmdArgs);
  1174. // Determine floating point ABI from the options & target defaults.
  1175. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  1176. if (ABI == arm::FloatABI::Soft) {
  1177. // Floating point operations and argument passing are soft.
  1178. // FIXME: This changes CPP defines, we need -target-soft-float.
  1179. CmdArgs.push_back("-msoft-float");
  1180. CmdArgs.push_back("-mfloat-abi");
  1181. CmdArgs.push_back("soft");
  1182. } else if (ABI == arm::FloatABI::SoftFP) {
  1183. // Floating point operations are hard, but argument passing is soft.
  1184. CmdArgs.push_back("-mfloat-abi");
  1185. CmdArgs.push_back("soft");
  1186. } else {
  1187. // Floating point operations and argument passing are hard.
  1188. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  1189. CmdArgs.push_back("-mfloat-abi");
  1190. CmdArgs.push_back("hard");
  1191. }
  1192. // Forward the -mglobal-merge option for explicit control over the pass.
  1193. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1194. options::OPT_mno_global_merge)) {
  1195. CmdArgs.push_back("-mllvm");
  1196. if (A->getOption().matches(options::OPT_mno_global_merge))
  1197. CmdArgs.push_back("-arm-global-merge=false");
  1198. else
  1199. CmdArgs.push_back("-arm-global-merge=true");
  1200. }
  1201. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1202. options::OPT_mno_implicit_float, true))
  1203. CmdArgs.push_back("-no-implicit-float");
  1204. if (Args.getLastArg(options::OPT_mcmse))
  1205. CmdArgs.push_back("-mcmse");
  1206. }
  1207. void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
  1208. const ArgList &Args, bool KernelOrKext,
  1209. ArgStringList &CmdArgs) const {
  1210. const ToolChain &TC = getToolChain();
  1211. // Add the target features
  1212. getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
  1213. // Add target specific flags.
  1214. switch (TC.getArch()) {
  1215. default:
  1216. break;
  1217. case llvm::Triple::arm:
  1218. case llvm::Triple::armeb:
  1219. case llvm::Triple::thumb:
  1220. case llvm::Triple::thumbeb:
  1221. // Use the effective triple, which takes into account the deployment target.
  1222. AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
  1223. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  1224. break;
  1225. case llvm::Triple::aarch64:
  1226. case llvm::Triple::aarch64_be:
  1227. AddAArch64TargetArgs(Args, CmdArgs);
  1228. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  1229. break;
  1230. case llvm::Triple::mips:
  1231. case llvm::Triple::mipsel:
  1232. case llvm::Triple::mips64:
  1233. case llvm::Triple::mips64el:
  1234. AddMIPSTargetArgs(Args, CmdArgs);
  1235. break;
  1236. case llvm::Triple::ppc:
  1237. case llvm::Triple::ppc64:
  1238. case llvm::Triple::ppc64le:
  1239. AddPPCTargetArgs(Args, CmdArgs);
  1240. break;
  1241. case llvm::Triple::riscv32:
  1242. case llvm::Triple::riscv64:
  1243. AddRISCVTargetArgs(Args, CmdArgs);
  1244. break;
  1245. case llvm::Triple::sparc:
  1246. case llvm::Triple::sparcel:
  1247. case llvm::Triple::sparcv9:
  1248. AddSparcTargetArgs(Args, CmdArgs);
  1249. break;
  1250. case llvm::Triple::systemz:
  1251. AddSystemZTargetArgs(Args, CmdArgs);
  1252. break;
  1253. case llvm::Triple::x86:
  1254. case llvm::Triple::x86_64:
  1255. AddX86TargetArgs(Args, CmdArgs);
  1256. break;
  1257. case llvm::Triple::lanai:
  1258. AddLanaiTargetArgs(Args, CmdArgs);
  1259. break;
  1260. case llvm::Triple::hexagon:
  1261. AddHexagonTargetArgs(Args, CmdArgs);
  1262. break;
  1263. case llvm::Triple::wasm32:
  1264. case llvm::Triple::wasm64:
  1265. AddWebAssemblyTargetArgs(Args, CmdArgs);
  1266. break;
  1267. }
  1268. }
  1269. // Parse -mbranch-protection=<protection>[+<protection>]* where
  1270. // <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
  1271. // Returns a triple of (return address signing Scope, signing key, require
  1272. // landing pads)
  1273. static std::tuple<StringRef, StringRef, bool>
  1274. ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
  1275. const Arg *A) {
  1276. StringRef Scope = "none";
  1277. StringRef Key = "a_key";
  1278. bool IndirectBranches = false;
  1279. StringRef Value = A->getValue();
  1280. // This maps onto -mbranch-protection=<scope>+<key>
  1281. if (Value.equals("standard")) {
  1282. Scope = "non-leaf";
  1283. Key = "a_key";
  1284. IndirectBranches = true;
  1285. } else if (!Value.equals("none")) {
  1286. SmallVector<StringRef, 4> BranchProtection;
  1287. StringRef(A->getValue()).split(BranchProtection, '+');
  1288. auto Protection = BranchProtection.begin();
  1289. while (Protection != BranchProtection.end()) {
  1290. if (Protection->equals("bti"))
  1291. IndirectBranches = true;
  1292. else if (Protection->equals("pac-ret")) {
  1293. Scope = "non-leaf";
  1294. while (++Protection != BranchProtection.end()) {
  1295. // Inner loop as "leaf" and "b-key" options must only appear attached
  1296. // to pac-ret.
  1297. if (Protection->equals("leaf"))
  1298. Scope = "all";
  1299. else if (Protection->equals("b-key"))
  1300. Key = "b_key";
  1301. else
  1302. break;
  1303. }
  1304. Protection--;
  1305. } else
  1306. D.Diag(diag::err_invalid_branch_protection)
  1307. << *Protection << A->getAsString(Args);
  1308. Protection++;
  1309. }
  1310. }
  1311. return std::make_tuple(Scope, Key, IndirectBranches);
  1312. }
  1313. namespace {
  1314. void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
  1315. ArgStringList &CmdArgs) {
  1316. const char *ABIName = nullptr;
  1317. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1318. ABIName = A->getValue();
  1319. else if (Triple.isOSDarwin())
  1320. ABIName = "darwinpcs";
  1321. else
  1322. ABIName = "aapcs";
  1323. CmdArgs.push_back("-target-abi");
  1324. CmdArgs.push_back(ABIName);
  1325. }
  1326. }
  1327. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  1328. ArgStringList &CmdArgs) const {
  1329. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  1330. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1331. Args.hasArg(options::OPT_mkernel) ||
  1332. Args.hasArg(options::OPT_fapple_kext))
  1333. CmdArgs.push_back("-disable-red-zone");
  1334. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1335. options::OPT_mno_implicit_float, true))
  1336. CmdArgs.push_back("-no-implicit-float");
  1337. RenderAArch64ABI(Triple, Args, CmdArgs);
  1338. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  1339. options::OPT_mno_fix_cortex_a53_835769)) {
  1340. CmdArgs.push_back("-mllvm");
  1341. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  1342. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1343. else
  1344. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  1345. } else if (Triple.isAndroid()) {
  1346. // Enabled A53 errata (835769) workaround by default on android
  1347. CmdArgs.push_back("-mllvm");
  1348. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1349. }
  1350. // Forward the -mglobal-merge option for explicit control over the pass.
  1351. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1352. options::OPT_mno_global_merge)) {
  1353. CmdArgs.push_back("-mllvm");
  1354. if (A->getOption().matches(options::OPT_mno_global_merge))
  1355. CmdArgs.push_back("-aarch64-enable-global-merge=false");
  1356. else
  1357. CmdArgs.push_back("-aarch64-enable-global-merge=true");
  1358. }
  1359. // Enable/disable return address signing and indirect branch targets.
  1360. if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
  1361. options::OPT_mbranch_protection_EQ)) {
  1362. const Driver &D = getToolChain().getDriver();
  1363. StringRef Scope, Key;
  1364. bool IndirectBranches;
  1365. if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
  1366. Scope = A->getValue();
  1367. if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
  1368. !Scope.equals("all"))
  1369. D.Diag(diag::err_invalid_branch_protection)
  1370. << Scope << A->getAsString(Args);
  1371. Key = "a_key";
  1372. IndirectBranches = false;
  1373. } else
  1374. std::tie(Scope, Key, IndirectBranches) =
  1375. ParseAArch64BranchProtection(D, Args, A);
  1376. CmdArgs.push_back(
  1377. Args.MakeArgString(Twine("-msign-return-address=") + Scope));
  1378. CmdArgs.push_back(
  1379. Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
  1380. if (IndirectBranches)
  1381. CmdArgs.push_back("-mbranch-target-enforce");
  1382. }
  1383. }
  1384. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1385. ArgStringList &CmdArgs) const {
  1386. const Driver &D = getToolChain().getDriver();
  1387. StringRef CPUName;
  1388. StringRef ABIName;
  1389. const llvm::Triple &Triple = getToolChain().getTriple();
  1390. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1391. CmdArgs.push_back("-target-abi");
  1392. CmdArgs.push_back(ABIName.data());
  1393. mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
  1394. if (ABI == mips::FloatABI::Soft) {
  1395. // Floating point operations and argument passing are soft.
  1396. CmdArgs.push_back("-msoft-float");
  1397. CmdArgs.push_back("-mfloat-abi");
  1398. CmdArgs.push_back("soft");
  1399. } else {
  1400. // Floating point operations and argument passing are hard.
  1401. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1402. CmdArgs.push_back("-mfloat-abi");
  1403. CmdArgs.push_back("hard");
  1404. }
  1405. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1406. options::OPT_mno_ldc1_sdc1)) {
  1407. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1408. CmdArgs.push_back("-mllvm");
  1409. CmdArgs.push_back("-mno-ldc1-sdc1");
  1410. }
  1411. }
  1412. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1413. options::OPT_mno_check_zero_division)) {
  1414. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1415. CmdArgs.push_back("-mllvm");
  1416. CmdArgs.push_back("-mno-check-zero-division");
  1417. }
  1418. }
  1419. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1420. StringRef v = A->getValue();
  1421. CmdArgs.push_back("-mllvm");
  1422. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1423. A->claim();
  1424. }
  1425. Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
  1426. Arg *ABICalls =
  1427. Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
  1428. // -mabicalls is the default for many MIPS environments, even with -fno-pic.
  1429. // -mgpopt is the default for static, -fno-pic environments but these two
  1430. // options conflict. We want to be certain that -mno-abicalls -mgpopt is
  1431. // the only case where -mllvm -mgpopt is passed.
  1432. // NOTE: We need a warning here or in the backend to warn when -mgpopt is
  1433. // passed explicitly when compiling something with -mabicalls
  1434. // (implictly) in affect. Currently the warning is in the backend.
  1435. //
  1436. // When the ABI in use is N64, we also need to determine the PIC mode that
  1437. // is in use, as -fno-pic for N64 implies -mno-abicalls.
  1438. bool NoABICalls =
  1439. ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
  1440. llvm::Reloc::Model RelocationModel;
  1441. unsigned PICLevel;
  1442. bool IsPIE;
  1443. std::tie(RelocationModel, PICLevel, IsPIE) =
  1444. ParsePICArgs(getToolChain(), Args);
  1445. NoABICalls = NoABICalls ||
  1446. (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
  1447. bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
  1448. // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
  1449. if (NoABICalls && (!GPOpt || WantGPOpt)) {
  1450. CmdArgs.push_back("-mllvm");
  1451. CmdArgs.push_back("-mgpopt");
  1452. Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
  1453. options::OPT_mno_local_sdata);
  1454. Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
  1455. options::OPT_mno_extern_sdata);
  1456. Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
  1457. options::OPT_mno_embedded_data);
  1458. if (LocalSData) {
  1459. CmdArgs.push_back("-mllvm");
  1460. if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
  1461. CmdArgs.push_back("-mlocal-sdata=1");
  1462. } else {
  1463. CmdArgs.push_back("-mlocal-sdata=0");
  1464. }
  1465. LocalSData->claim();
  1466. }
  1467. if (ExternSData) {
  1468. CmdArgs.push_back("-mllvm");
  1469. if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
  1470. CmdArgs.push_back("-mextern-sdata=1");
  1471. } else {
  1472. CmdArgs.push_back("-mextern-sdata=0");
  1473. }
  1474. ExternSData->claim();
  1475. }
  1476. if (EmbeddedData) {
  1477. CmdArgs.push_back("-mllvm");
  1478. if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
  1479. CmdArgs.push_back("-membedded-data=1");
  1480. } else {
  1481. CmdArgs.push_back("-membedded-data=0");
  1482. }
  1483. EmbeddedData->claim();
  1484. }
  1485. } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
  1486. D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
  1487. if (GPOpt)
  1488. GPOpt->claim();
  1489. if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
  1490. StringRef Val = StringRef(A->getValue());
  1491. if (mips::hasCompactBranches(CPUName)) {
  1492. if (Val == "never" || Val == "always" || Val == "optimal") {
  1493. CmdArgs.push_back("-mllvm");
  1494. CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
  1495. } else
  1496. D.Diag(diag::err_drv_unsupported_option_argument)
  1497. << A->getOption().getName() << Val;
  1498. } else
  1499. D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
  1500. }
  1501. if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
  1502. options::OPT_mno_relax_pic_calls)) {
  1503. if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
  1504. CmdArgs.push_back("-mllvm");
  1505. CmdArgs.push_back("-mips-jalr-reloc=0");
  1506. }
  1507. }
  1508. }
  1509. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1510. ArgStringList &CmdArgs) const {
  1511. // Select the ABI to use.
  1512. const char *ABIName = nullptr;
  1513. if (getToolChain().getTriple().isOSLinux())
  1514. switch (getToolChain().getArch()) {
  1515. case llvm::Triple::ppc64: {
  1516. // When targeting a processor that supports QPX, or if QPX is
  1517. // specifically enabled, default to using the ABI that supports QPX (so
  1518. // long as it is not specifically disabled).
  1519. bool HasQPX = false;
  1520. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1521. HasQPX = A->getValue() == StringRef("a2q");
  1522. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1523. if (HasQPX) {
  1524. ABIName = "elfv1-qpx";
  1525. break;
  1526. }
  1527. ABIName = "elfv1";
  1528. break;
  1529. }
  1530. case llvm::Triple::ppc64le:
  1531. ABIName = "elfv2";
  1532. break;
  1533. default:
  1534. break;
  1535. }
  1536. bool IEEELongDouble = false;
  1537. for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
  1538. StringRef V = A->getValue();
  1539. if (V == "ieeelongdouble")
  1540. IEEELongDouble = true;
  1541. else if (V == "ibmlongdouble")
  1542. IEEELongDouble = false;
  1543. else if (V != "altivec")
  1544. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1545. // the option if given as we don't have backend support for any targets
  1546. // that don't use the altivec abi.
  1547. ABIName = A->getValue();
  1548. }
  1549. if (IEEELongDouble)
  1550. CmdArgs.push_back("-mabi=ieeelongdouble");
  1551. ppc::FloatABI FloatABI =
  1552. ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
  1553. if (FloatABI == ppc::FloatABI::Soft) {
  1554. // Floating point operations and argument passing are soft.
  1555. CmdArgs.push_back("-msoft-float");
  1556. CmdArgs.push_back("-mfloat-abi");
  1557. CmdArgs.push_back("soft");
  1558. } else {
  1559. // Floating point operations and argument passing are hard.
  1560. assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
  1561. CmdArgs.push_back("-mfloat-abi");
  1562. CmdArgs.push_back("hard");
  1563. }
  1564. if (ABIName) {
  1565. CmdArgs.push_back("-target-abi");
  1566. CmdArgs.push_back(ABIName);
  1567. }
  1568. }
  1569. void Clang::AddRISCVTargetArgs(const ArgList &Args,
  1570. ArgStringList &CmdArgs) const {
  1571. const llvm::Triple &Triple = getToolChain().getTriple();
  1572. StringRef ABIName = riscv::getRISCVABI(Args, Triple);
  1573. CmdArgs.push_back("-target-abi");
  1574. CmdArgs.push_back(ABIName.data());
  1575. }
  1576. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1577. ArgStringList &CmdArgs) const {
  1578. sparc::FloatABI FloatABI =
  1579. sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
  1580. if (FloatABI == sparc::FloatABI::Soft) {
  1581. // Floating point operations and argument passing are soft.
  1582. CmdArgs.push_back("-msoft-float");
  1583. CmdArgs.push_back("-mfloat-abi");
  1584. CmdArgs.push_back("soft");
  1585. } else {
  1586. // Floating point operations and argument passing are hard.
  1587. assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
  1588. CmdArgs.push_back("-mfloat-abi");
  1589. CmdArgs.push_back("hard");
  1590. }
  1591. }
  1592. void Clang::AddSystemZTargetArgs(const ArgList &Args,
  1593. ArgStringList &CmdArgs) const {
  1594. if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
  1595. CmdArgs.push_back("-mbackchain");
  1596. }
  1597. void Clang::AddX86TargetArgs(const ArgList &Args,
  1598. ArgStringList &CmdArgs) const {
  1599. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1600. Args.hasArg(options::OPT_mkernel) ||
  1601. Args.hasArg(options::OPT_fapple_kext))
  1602. CmdArgs.push_back("-disable-red-zone");
  1603. if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
  1604. options::OPT_mno_tls_direct_seg_refs, true))
  1605. CmdArgs.push_back("-mno-tls-direct-seg-refs");
  1606. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1607. // that to be overridden with -mno-soft-float.
  1608. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1609. Args.hasArg(options::OPT_fapple_kext));
  1610. if (Arg *A = Args.getLastArg(
  1611. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1612. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1613. const Option &O = A->getOption();
  1614. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1615. O.matches(options::OPT_msoft_float));
  1616. }
  1617. if (NoImplicitFloat)
  1618. CmdArgs.push_back("-no-implicit-float");
  1619. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1620. StringRef Value = A->getValue();
  1621. if (Value == "intel" || Value == "att") {
  1622. CmdArgs.push_back("-mllvm");
  1623. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1624. } else {
  1625. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  1626. << A->getOption().getName() << Value;
  1627. }
  1628. } else if (getToolChain().getDriver().IsCLMode()) {
  1629. CmdArgs.push_back("-mllvm");
  1630. CmdArgs.push_back("-x86-asm-syntax=intel");
  1631. }
  1632. // Set flags to support MCU ABI.
  1633. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
  1634. CmdArgs.push_back("-mfloat-abi");
  1635. CmdArgs.push_back("soft");
  1636. CmdArgs.push_back("-mstack-alignment=4");
  1637. }
  1638. }
  1639. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  1640. ArgStringList &CmdArgs) const {
  1641. CmdArgs.push_back("-mqdsp6-compat");
  1642. CmdArgs.push_back("-Wreturn-type");
  1643. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  1644. CmdArgs.push_back("-mllvm");
  1645. CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
  1646. Twine(G.getValue())));
  1647. }
  1648. if (!Args.hasArg(options::OPT_fno_short_enums))
  1649. CmdArgs.push_back("-fshort-enums");
  1650. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  1651. CmdArgs.push_back("-mllvm");
  1652. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  1653. }
  1654. CmdArgs.push_back("-mllvm");
  1655. CmdArgs.push_back("-machine-sink-split=0");
  1656. }
  1657. void Clang::AddLanaiTargetArgs(const ArgList &Args,
  1658. ArgStringList &CmdArgs) const {
  1659. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1660. StringRef CPUName = A->getValue();
  1661. CmdArgs.push_back("-target-cpu");
  1662. CmdArgs.push_back(Args.MakeArgString(CPUName));
  1663. }
  1664. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  1665. StringRef Value = A->getValue();
  1666. // Only support mregparm=4 to support old usage. Report error for all other
  1667. // cases.
  1668. int Mregparm;
  1669. if (Value.getAsInteger(10, Mregparm)) {
  1670. if (Mregparm != 4) {
  1671. getToolChain().getDriver().Diag(
  1672. diag::err_drv_unsupported_option_argument)
  1673. << A->getOption().getName() << Value;
  1674. }
  1675. }
  1676. }
  1677. }
  1678. void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
  1679. ArgStringList &CmdArgs) const {
  1680. // Default to "hidden" visibility.
  1681. if (!Args.hasArg(options::OPT_fvisibility_EQ,
  1682. options::OPT_fvisibility_ms_compat)) {
  1683. CmdArgs.push_back("-fvisibility");
  1684. CmdArgs.push_back("hidden");
  1685. }
  1686. }
  1687. void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
  1688. StringRef Target, const InputInfo &Output,
  1689. const InputInfo &Input, const ArgList &Args) const {
  1690. // If this is a dry run, do not create the compilation database file.
  1691. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
  1692. return;
  1693. using llvm::yaml::escape;
  1694. const Driver &D = getToolChain().getDriver();
  1695. if (!CompilationDatabase) {
  1696. std::error_code EC;
  1697. auto File = std::make_unique<llvm::raw_fd_ostream>(Filename, EC,
  1698. llvm::sys::fs::OF_Text);
  1699. if (EC) {
  1700. D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
  1701. << EC.message();
  1702. return;
  1703. }
  1704. CompilationDatabase = std::move(File);
  1705. }
  1706. auto &CDB = *CompilationDatabase;
  1707. auto CWD = D.getVFS().getCurrentWorkingDirectory();
  1708. if (!CWD)
  1709. CWD = ".";
  1710. CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
  1711. CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
  1712. CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
  1713. CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
  1714. SmallString<128> Buf;
  1715. Buf = "-x";
  1716. Buf += types::getTypeName(Input.getType());
  1717. CDB << ", \"" << escape(Buf) << "\"";
  1718. if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
  1719. Buf = "--sysroot=";
  1720. Buf += D.SysRoot;
  1721. CDB << ", \"" << escape(Buf) << "\"";
  1722. }
  1723. CDB << ", \"" << escape(Input.getFilename()) << "\"";
  1724. for (auto &A: Args) {
  1725. auto &O = A->getOption();
  1726. // Skip language selection, which is positional.
  1727. if (O.getID() == options::OPT_x)
  1728. continue;
  1729. // Skip writing dependency output and the compilation database itself.
  1730. if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
  1731. continue;
  1732. if (O.getID() == options::OPT_gen_cdb_fragment_path)
  1733. continue;
  1734. // Skip inputs.
  1735. if (O.getKind() == Option::InputClass)
  1736. continue;
  1737. // All other arguments are quoted and appended.
  1738. ArgStringList ASL;
  1739. A->render(Args, ASL);
  1740. for (auto &it: ASL)
  1741. CDB << ", \"" << escape(it) << "\"";
  1742. }
  1743. Buf = "--target=";
  1744. Buf += Target;
  1745. CDB << ", \"" << escape(Buf) << "\"]},\n";
  1746. }
  1747. void Clang::DumpCompilationDatabaseFragmentToDir(
  1748. StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
  1749. const InputInfo &Input, const llvm::opt::ArgList &Args) const {
  1750. // If this is a dry run, do not create the compilation database file.
  1751. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
  1752. return;
  1753. if (CompilationDatabase)
  1754. DumpCompilationDatabase(C, "", Target, Output, Input, Args);
  1755. SmallString<256> Path = Dir;
  1756. const auto &Driver = C.getDriver();
  1757. Driver.getVFS().makeAbsolute(Path);
  1758. auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
  1759. if (Err) {
  1760. Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
  1761. return;
  1762. }
  1763. llvm::sys::path::append(
  1764. Path,
  1765. Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
  1766. int FD;
  1767. SmallString<256> TempPath;
  1768. Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath);
  1769. if (Err) {
  1770. Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
  1771. return;
  1772. }
  1773. CompilationDatabase =
  1774. std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
  1775. DumpCompilationDatabase(C, "", Target, Output, Input, Args);
  1776. }
  1777. static void CollectArgsForIntegratedAssembler(Compilation &C,
  1778. const ArgList &Args,
  1779. ArgStringList &CmdArgs,
  1780. const Driver &D) {
  1781. if (UseRelaxAll(C, Args))
  1782. CmdArgs.push_back("-mrelax-all");
  1783. // Only default to -mincremental-linker-compatible if we think we are
  1784. // targeting the MSVC linker.
  1785. bool DefaultIncrementalLinkerCompatible =
  1786. C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
  1787. if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
  1788. options::OPT_mno_incremental_linker_compatible,
  1789. DefaultIncrementalLinkerCompatible))
  1790. CmdArgs.push_back("-mincremental-linker-compatible");
  1791. switch (C.getDefaultToolChain().getArch()) {
  1792. case llvm::Triple::arm:
  1793. case llvm::Triple::armeb:
  1794. case llvm::Triple::thumb:
  1795. case llvm::Triple::thumbeb:
  1796. if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
  1797. StringRef Value = A->getValue();
  1798. if (Value == "always" || Value == "never" || Value == "arm" ||
  1799. Value == "thumb") {
  1800. CmdArgs.push_back("-mllvm");
  1801. CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
  1802. } else {
  1803. D.Diag(diag::err_drv_unsupported_option_argument)
  1804. << A->getOption().getName() << Value;
  1805. }
  1806. }
  1807. break;
  1808. default:
  1809. break;
  1810. }
  1811. // If you add more args here, also add them to the block below that
  1812. // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
  1813. // When passing -I arguments to the assembler we sometimes need to
  1814. // unconditionally take the next argument. For example, when parsing
  1815. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  1816. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  1817. // arg after parsing the '-I' arg.
  1818. bool TakeNextArg = false;
  1819. bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
  1820. bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
  1821. const char *MipsTargetFeature = nullptr;
  1822. for (const Arg *A :
  1823. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  1824. A->claim();
  1825. for (StringRef Value : A->getValues()) {
  1826. if (TakeNextArg) {
  1827. CmdArgs.push_back(Value.data());
  1828. TakeNextArg = false;
  1829. continue;
  1830. }
  1831. if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
  1832. Value == "-mbig-obj")
  1833. continue; // LLVM handles bigobj automatically
  1834. switch (C.getDefaultToolChain().getArch()) {
  1835. default:
  1836. break;
  1837. case llvm::Triple::thumb:
  1838. case llvm::Triple::thumbeb:
  1839. case llvm::Triple::arm:
  1840. case llvm::Triple::armeb:
  1841. if (Value == "-mthumb")
  1842. // -mthumb has already been processed in ComputeLLVMTriple()
  1843. // recognize but skip over here.
  1844. continue;
  1845. break;
  1846. case llvm::Triple::mips:
  1847. case llvm::Triple::mipsel:
  1848. case llvm::Triple::mips64:
  1849. case llvm::Triple::mips64el:
  1850. if (Value == "--trap") {
  1851. CmdArgs.push_back("-target-feature");
  1852. CmdArgs.push_back("+use-tcc-in-div");
  1853. continue;
  1854. }
  1855. if (Value == "--break") {
  1856. CmdArgs.push_back("-target-feature");
  1857. CmdArgs.push_back("-use-tcc-in-div");
  1858. continue;
  1859. }
  1860. if (Value.startswith("-msoft-float")) {
  1861. CmdArgs.push_back("-target-feature");
  1862. CmdArgs.push_back("+soft-float");
  1863. continue;
  1864. }
  1865. if (Value.startswith("-mhard-float")) {
  1866. CmdArgs.push_back("-target-feature");
  1867. CmdArgs.push_back("-soft-float");
  1868. continue;
  1869. }
  1870. MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
  1871. .Case("-mips1", "+mips1")
  1872. .Case("-mips2", "+mips2")
  1873. .Case("-mips3", "+mips3")
  1874. .Case("-mips4", "+mips4")
  1875. .Case("-mips5", "+mips5")
  1876. .Case("-mips32", "+mips32")
  1877. .Case("-mips32r2", "+mips32r2")
  1878. .Case("-mips32r3", "+mips32r3")
  1879. .Case("-mips32r5", "+mips32r5")
  1880. .Case("-mips32r6", "+mips32r6")
  1881. .Case("-mips64", "+mips64")
  1882. .Case("-mips64r2", "+mips64r2")
  1883. .Case("-mips64r3", "+mips64r3")
  1884. .Case("-mips64r5", "+mips64r5")
  1885. .Case("-mips64r6", "+mips64r6")
  1886. .Default(nullptr);
  1887. if (MipsTargetFeature)
  1888. continue;
  1889. }
  1890. if (Value == "-force_cpusubtype_ALL") {
  1891. // Do nothing, this is the default and we don't support anything else.
  1892. } else if (Value == "-L") {
  1893. CmdArgs.push_back("-msave-temp-labels");
  1894. } else if (Value == "--fatal-warnings") {
  1895. CmdArgs.push_back("-massembler-fatal-warnings");
  1896. } else if (Value == "--no-warn" || Value == "-W") {
  1897. CmdArgs.push_back("-massembler-no-warn");
  1898. } else if (Value == "--noexecstack") {
  1899. UseNoExecStack = true;
  1900. } else if (Value.startswith("-compress-debug-sections") ||
  1901. Value.startswith("--compress-debug-sections") ||
  1902. Value == "-nocompress-debug-sections" ||
  1903. Value == "--nocompress-debug-sections") {
  1904. CmdArgs.push_back(Value.data());
  1905. } else if (Value == "-mrelax-relocations=yes" ||
  1906. Value == "--mrelax-relocations=yes") {
  1907. UseRelaxRelocations = true;
  1908. } else if (Value == "-mrelax-relocations=no" ||
  1909. Value == "--mrelax-relocations=no") {
  1910. UseRelaxRelocations = false;
  1911. } else if (Value.startswith("-I")) {
  1912. CmdArgs.push_back(Value.data());
  1913. // We need to consume the next argument if the current arg is a plain
  1914. // -I. The next arg will be the include directory.
  1915. if (Value == "-I")
  1916. TakeNextArg = true;
  1917. } else if (Value.startswith("-gdwarf-")) {
  1918. // "-gdwarf-N" options are not cc1as options.
  1919. unsigned DwarfVersion = DwarfVersionNum(Value);
  1920. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  1921. CmdArgs.push_back(Value.data());
  1922. } else {
  1923. RenderDebugEnablingArgs(Args, CmdArgs,
  1924. codegenoptions::LimitedDebugInfo,
  1925. DwarfVersion, llvm::DebuggerKind::Default);
  1926. }
  1927. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  1928. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  1929. // Do nothing, we'll validate it later.
  1930. } else if (Value == "-defsym") {
  1931. if (A->getNumValues() != 2) {
  1932. D.Diag(diag::err_drv_defsym_invalid_format) << Value;
  1933. break;
  1934. }
  1935. const char *S = A->getValue(1);
  1936. auto Pair = StringRef(S).split('=');
  1937. auto Sym = Pair.first;
  1938. auto SVal = Pair.second;
  1939. if (Sym.empty() || SVal.empty()) {
  1940. D.Diag(diag::err_drv_defsym_invalid_format) << S;
  1941. break;
  1942. }
  1943. int64_t IVal;
  1944. if (SVal.getAsInteger(0, IVal)) {
  1945. D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
  1946. break;
  1947. }
  1948. CmdArgs.push_back(Value.data());
  1949. TakeNextArg = true;
  1950. } else if (Value == "-fdebug-compilation-dir") {
  1951. CmdArgs.push_back("-fdebug-compilation-dir");
  1952. TakeNextArg = true;
  1953. } else {
  1954. D.Diag(diag::err_drv_unsupported_option_argument)
  1955. << A->getOption().getName() << Value;
  1956. }
  1957. }
  1958. }
  1959. if (UseRelaxRelocations)
  1960. CmdArgs.push_back("--mrelax-relocations");
  1961. if (UseNoExecStack)
  1962. CmdArgs.push_back("-mnoexecstack");
  1963. if (MipsTargetFeature != nullptr) {
  1964. CmdArgs.push_back("-target-feature");
  1965. CmdArgs.push_back(MipsTargetFeature);
  1966. }
  1967. // forward -fembed-bitcode to assmebler
  1968. if (C.getDriver().embedBitcodeEnabled() ||
  1969. C.getDriver().embedBitcodeMarkerOnly())
  1970. Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
  1971. }
  1972. static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
  1973. bool OFastEnabled, const ArgList &Args,
  1974. ArgStringList &CmdArgs) {
  1975. // Handle various floating point optimization flags, mapping them to the
  1976. // appropriate LLVM code generation flags. This is complicated by several
  1977. // "umbrella" flags, so we do this by stepping through the flags incrementally
  1978. // adjusting what we think is enabled/disabled, then at the end setting the
  1979. // LLVM flags based on the final state.
  1980. bool HonorINFs = true;
  1981. bool HonorNaNs = true;
  1982. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  1983. bool MathErrno = TC.IsMathErrnoDefault();
  1984. bool AssociativeMath = false;
  1985. bool ReciprocalMath = false;
  1986. bool SignedZeros = true;
  1987. bool TrappingMath = true;
  1988. StringRef DenormalFPMath = "";
  1989. StringRef FPContract = "";
  1990. if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  1991. CmdArgs.push_back("-mlimit-float-precision");
  1992. CmdArgs.push_back(A->getValue());
  1993. }
  1994. for (const Arg *A : Args) {
  1995. switch (A->getOption().getID()) {
  1996. // If this isn't an FP option skip the claim below
  1997. default: continue;
  1998. // Options controlling individual features
  1999. case options::OPT_fhonor_infinities: HonorINFs = true; break;
  2000. case options::OPT_fno_honor_infinities: HonorINFs = false; break;
  2001. case options::OPT_fhonor_nans: HonorNaNs = true; break;
  2002. case options::OPT_fno_honor_nans: HonorNaNs = false; break;
  2003. case options::OPT_fmath_errno: MathErrno = true; break;
  2004. case options::OPT_fno_math_errno: MathErrno = false; break;
  2005. case options::OPT_fassociative_math: AssociativeMath = true; break;
  2006. case options::OPT_fno_associative_math: AssociativeMath = false; break;
  2007. case options::OPT_freciprocal_math: ReciprocalMath = true; break;
  2008. case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
  2009. case options::OPT_fsigned_zeros: SignedZeros = true; break;
  2010. case options::OPT_fno_signed_zeros: SignedZeros = false; break;
  2011. case options::OPT_ftrapping_math: TrappingMath = true; break;
  2012. case options::OPT_fno_trapping_math: TrappingMath = false; break;
  2013. case options::OPT_fdenormal_fp_math_EQ:
  2014. DenormalFPMath = A->getValue();
  2015. break;
  2016. // Validate and pass through -fp-contract option.
  2017. case options::OPT_ffp_contract: {
  2018. StringRef Val = A->getValue();
  2019. if (Val == "fast" || Val == "on" || Val == "off")
  2020. FPContract = Val;
  2021. else
  2022. D.Diag(diag::err_drv_unsupported_option_argument)
  2023. << A->getOption().getName() << Val;
  2024. break;
  2025. }
  2026. case options::OPT_ffinite_math_only:
  2027. HonorINFs = false;
  2028. HonorNaNs = false;
  2029. break;
  2030. case options::OPT_fno_finite_math_only:
  2031. HonorINFs = true;
  2032. HonorNaNs = true;
  2033. break;
  2034. case options::OPT_funsafe_math_optimizations:
  2035. AssociativeMath = true;
  2036. ReciprocalMath = true;
  2037. SignedZeros = false;
  2038. TrappingMath = false;
  2039. break;
  2040. case options::OPT_fno_unsafe_math_optimizations:
  2041. AssociativeMath = false;
  2042. ReciprocalMath = false;
  2043. SignedZeros = true;
  2044. TrappingMath = true;
  2045. // -fno_unsafe_math_optimizations restores default denormal handling
  2046. DenormalFPMath = "";
  2047. break;
  2048. case options::OPT_Ofast:
  2049. // If -Ofast is the optimization level, then -ffast-math should be enabled
  2050. if (!OFastEnabled)
  2051. continue;
  2052. LLVM_FALLTHROUGH;
  2053. case options::OPT_ffast_math:
  2054. HonorINFs = false;
  2055. HonorNaNs = false;
  2056. MathErrno = false;
  2057. AssociativeMath = true;
  2058. ReciprocalMath = true;
  2059. SignedZeros = false;
  2060. TrappingMath = false;
  2061. // If fast-math is set then set the fp-contract mode to fast.
  2062. FPContract = "fast";
  2063. break;
  2064. case options::OPT_fno_fast_math:
  2065. HonorINFs = true;
  2066. HonorNaNs = true;
  2067. // Turning on -ffast-math (with either flag) removes the need for
  2068. // MathErrno. However, turning *off* -ffast-math merely restores the
  2069. // toolchain default (which may be false).
  2070. MathErrno = TC.IsMathErrnoDefault();
  2071. AssociativeMath = false;
  2072. ReciprocalMath = false;
  2073. SignedZeros = true;
  2074. TrappingMath = true;
  2075. // -fno_fast_math restores default denormal and fpcontract handling
  2076. DenormalFPMath = "";
  2077. FPContract = "";
  2078. break;
  2079. }
  2080. // If we handled this option claim it
  2081. A->claim();
  2082. }
  2083. if (!HonorINFs)
  2084. CmdArgs.push_back("-menable-no-infs");
  2085. if (!HonorNaNs)
  2086. CmdArgs.push_back("-menable-no-nans");
  2087. if (MathErrno)
  2088. CmdArgs.push_back("-fmath-errno");
  2089. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  2090. !TrappingMath)
  2091. CmdArgs.push_back("-menable-unsafe-fp-math");
  2092. if (!SignedZeros)
  2093. CmdArgs.push_back("-fno-signed-zeros");
  2094. if (AssociativeMath && !SignedZeros && !TrappingMath)
  2095. CmdArgs.push_back("-mreassociate");
  2096. if (ReciprocalMath)
  2097. CmdArgs.push_back("-freciprocal-math");
  2098. if (!TrappingMath)
  2099. CmdArgs.push_back("-fno-trapping-math");
  2100. if (!DenormalFPMath.empty())
  2101. CmdArgs.push_back(
  2102. Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
  2103. if (!FPContract.empty())
  2104. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
  2105. ParseMRecip(D, Args, CmdArgs);
  2106. // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
  2107. // individual features enabled by -ffast-math instead of the option itself as
  2108. // that's consistent with gcc's behaviour.
  2109. if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
  2110. ReciprocalMath && !SignedZeros && !TrappingMath)
  2111. CmdArgs.push_back("-ffast-math");
  2112. // Handle __FINITE_MATH_ONLY__ similarly.
  2113. if (!HonorINFs && !HonorNaNs)
  2114. CmdArgs.push_back("-ffinite-math-only");
  2115. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  2116. CmdArgs.push_back("-mfpmath");
  2117. CmdArgs.push_back(A->getValue());
  2118. }
  2119. // Disable a codegen optimization for floating-point casts.
  2120. if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
  2121. options::OPT_fstrict_float_cast_overflow, false))
  2122. CmdArgs.push_back("-fno-strict-float-cast-overflow");
  2123. }
  2124. static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
  2125. const llvm::Triple &Triple,
  2126. const InputInfo &Input) {
  2127. // Enable region store model by default.
  2128. CmdArgs.push_back("-analyzer-store=region");
  2129. // Treat blocks as analysis entry points.
  2130. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  2131. // Add default argument set.
  2132. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  2133. CmdArgs.push_back("-analyzer-checker=core");
  2134. CmdArgs.push_back("-analyzer-checker=apiModeling");
  2135. if (!Triple.isWindowsMSVCEnvironment()) {
  2136. CmdArgs.push_back("-analyzer-checker=unix");
  2137. } else {
  2138. // Enable "unix" checkers that also work on Windows.
  2139. CmdArgs.push_back("-analyzer-checker=unix.API");
  2140. CmdArgs.push_back("-analyzer-checker=unix.Malloc");
  2141. CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
  2142. CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
  2143. CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
  2144. CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
  2145. }
  2146. // Disable some unix checkers for PS4.
  2147. if (Triple.isPS4CPU()) {
  2148. CmdArgs.push_back("-analyzer-disable-checker=unix.API");
  2149. CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
  2150. }
  2151. if (Triple.isOSDarwin())
  2152. CmdArgs.push_back("-analyzer-checker=osx");
  2153. CmdArgs.push_back("-analyzer-checker=deadcode");
  2154. if (types::isCXX(Input.getType()))
  2155. CmdArgs.push_back("-analyzer-checker=cplusplus");
  2156. if (!Triple.isPS4CPU()) {
  2157. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
  2158. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  2159. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  2160. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  2161. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  2162. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  2163. }
  2164. // Default nullability checks.
  2165. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  2166. CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
  2167. }
  2168. // Set the output format. The default is plist, for (lame) historical reasons.
  2169. CmdArgs.push_back("-analyzer-output");
  2170. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  2171. CmdArgs.push_back(A->getValue());
  2172. else
  2173. CmdArgs.push_back("plist");
  2174. // Disable the presentation of standard compiler warnings when using
  2175. // --analyze. We only want to show static analyzer diagnostics or frontend
  2176. // errors.
  2177. CmdArgs.push_back("-w");
  2178. // Add -Xanalyzer arguments when running as analyzer.
  2179. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  2180. }
  2181. static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
  2182. ArgStringList &CmdArgs, bool KernelOrKext) {
  2183. const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
  2184. // NVPTX doesn't support stack protectors; from the compiler's perspective, it
  2185. // doesn't even have a stack!
  2186. if (EffectiveTriple.isNVPTX())
  2187. return;
  2188. // -stack-protector=0 is default.
  2189. unsigned StackProtectorLevel = 0;
  2190. unsigned DefaultStackProtectorLevel =
  2191. TC.GetDefaultStackProtectorLevel(KernelOrKext);
  2192. if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  2193. options::OPT_fstack_protector_all,
  2194. options::OPT_fstack_protector_strong,
  2195. options::OPT_fstack_protector)) {
  2196. if (A->getOption().matches(options::OPT_fstack_protector))
  2197. StackProtectorLevel =
  2198. std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
  2199. else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  2200. StackProtectorLevel = LangOptions::SSPStrong;
  2201. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  2202. StackProtectorLevel = LangOptions::SSPReq;
  2203. } else {
  2204. StackProtectorLevel = DefaultStackProtectorLevel;
  2205. }
  2206. if (StackProtectorLevel) {
  2207. CmdArgs.push_back("-stack-protector");
  2208. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  2209. }
  2210. // --param ssp-buffer-size=
  2211. for (const Arg *A : Args.filtered(options::OPT__param)) {
  2212. StringRef Str(A->getValue());
  2213. if (Str.startswith("ssp-buffer-size=")) {
  2214. if (StackProtectorLevel) {
  2215. CmdArgs.push_back("-stack-protector-buffer-size");
  2216. // FIXME: Verify the argument is a valid integer.
  2217. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  2218. }
  2219. A->claim();
  2220. }
  2221. }
  2222. }
  2223. static void RenderTrivialAutoVarInitOptions(const Driver &D,
  2224. const ToolChain &TC,
  2225. const ArgList &Args,
  2226. ArgStringList &CmdArgs) {
  2227. auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
  2228. StringRef TrivialAutoVarInit = "";
  2229. for (const Arg *A : Args) {
  2230. switch (A->getOption().getID()) {
  2231. default:
  2232. continue;
  2233. case options::OPT_ftrivial_auto_var_init: {
  2234. A->claim();
  2235. StringRef Val = A->getValue();
  2236. if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
  2237. TrivialAutoVarInit = Val;
  2238. else
  2239. D.Diag(diag::err_drv_unsupported_option_argument)
  2240. << A->getOption().getName() << Val;
  2241. break;
  2242. }
  2243. }
  2244. }
  2245. if (TrivialAutoVarInit.empty())
  2246. switch (DefaultTrivialAutoVarInit) {
  2247. case LangOptions::TrivialAutoVarInitKind::Uninitialized:
  2248. break;
  2249. case LangOptions::TrivialAutoVarInitKind::Pattern:
  2250. TrivialAutoVarInit = "pattern";
  2251. break;
  2252. case LangOptions::TrivialAutoVarInitKind::Zero:
  2253. TrivialAutoVarInit = "zero";
  2254. break;
  2255. }
  2256. if (!TrivialAutoVarInit.empty()) {
  2257. if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
  2258. D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
  2259. CmdArgs.push_back(
  2260. Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
  2261. }
  2262. }
  2263. static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
  2264. const unsigned ForwardedArguments[] = {
  2265. options::OPT_cl_opt_disable,
  2266. options::OPT_cl_strict_aliasing,
  2267. options::OPT_cl_single_precision_constant,
  2268. options::OPT_cl_finite_math_only,
  2269. options::OPT_cl_kernel_arg_info,
  2270. options::OPT_cl_unsafe_math_optimizations,
  2271. options::OPT_cl_fast_relaxed_math,
  2272. options::OPT_cl_mad_enable,
  2273. options::OPT_cl_no_signed_zeros,
  2274. options::OPT_cl_denorms_are_zero,
  2275. options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
  2276. options::OPT_cl_uniform_work_group_size
  2277. };
  2278. if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
  2279. std::string CLStdStr = std::string("-cl-std=") + A->getValue();
  2280. CmdArgs.push_back(Args.MakeArgString(CLStdStr));
  2281. }
  2282. for (const auto &Arg : ForwardedArguments)
  2283. if (const auto *A = Args.getLastArg(Arg))
  2284. CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
  2285. }
  2286. static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
  2287. ArgStringList &CmdArgs) {
  2288. bool ARCMTEnabled = false;
  2289. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  2290. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  2291. options::OPT_ccc_arcmt_modify,
  2292. options::OPT_ccc_arcmt_migrate)) {
  2293. ARCMTEnabled = true;
  2294. switch (A->getOption().getID()) {
  2295. default: llvm_unreachable("missed a case");
  2296. case options::OPT_ccc_arcmt_check:
  2297. CmdArgs.push_back("-arcmt-check");
  2298. break;
  2299. case options::OPT_ccc_arcmt_modify:
  2300. CmdArgs.push_back("-arcmt-modify");
  2301. break;
  2302. case options::OPT_ccc_arcmt_migrate:
  2303. CmdArgs.push_back("-arcmt-migrate");
  2304. CmdArgs.push_back("-mt-migrate-directory");
  2305. CmdArgs.push_back(A->getValue());
  2306. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  2307. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  2308. break;
  2309. }
  2310. }
  2311. } else {
  2312. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  2313. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  2314. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  2315. }
  2316. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  2317. if (ARCMTEnabled)
  2318. D.Diag(diag::err_drv_argument_not_allowed_with)
  2319. << A->getAsString(Args) << "-ccc-arcmt-migrate";
  2320. CmdArgs.push_back("-mt-migrate-directory");
  2321. CmdArgs.push_back(A->getValue());
  2322. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  2323. options::OPT_objcmt_migrate_subscripting,
  2324. options::OPT_objcmt_migrate_property)) {
  2325. // None specified, means enable them all.
  2326. CmdArgs.push_back("-objcmt-migrate-literals");
  2327. CmdArgs.push_back("-objcmt-migrate-subscripting");
  2328. CmdArgs.push_back("-objcmt-migrate-property");
  2329. } else {
  2330. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  2331. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  2332. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  2333. }
  2334. } else {
  2335. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  2336. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  2337. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  2338. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  2339. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  2340. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  2341. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  2342. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  2343. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  2344. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  2345. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  2346. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  2347. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  2348. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  2349. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  2350. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  2351. }
  2352. }
  2353. static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
  2354. const ArgList &Args, ArgStringList &CmdArgs) {
  2355. // -fbuiltin is default unless -mkernel is used.
  2356. bool UseBuiltins =
  2357. Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  2358. !Args.hasArg(options::OPT_mkernel));
  2359. if (!UseBuiltins)
  2360. CmdArgs.push_back("-fno-builtin");
  2361. // -ffreestanding implies -fno-builtin.
  2362. if (Args.hasArg(options::OPT_ffreestanding))
  2363. UseBuiltins = false;
  2364. // Process the -fno-builtin-* options.
  2365. for (const auto &Arg : Args) {
  2366. const Option &O = Arg->getOption();
  2367. if (!O.matches(options::OPT_fno_builtin_))
  2368. continue;
  2369. Arg->claim();
  2370. // If -fno-builtin is specified, then there's no need to pass the option to
  2371. // the frontend.
  2372. if (!UseBuiltins)
  2373. continue;
  2374. StringRef FuncName = Arg->getValue();
  2375. CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
  2376. }
  2377. // le32-specific flags:
  2378. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  2379. // by default.
  2380. if (TC.getArch() == llvm::Triple::le32)
  2381. CmdArgs.push_back("-fno-math-builtin");
  2382. }
  2383. void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
  2384. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
  2385. llvm::sys::path::append(Result, "org.llvm.clang.");
  2386. appendUserToPath(Result);
  2387. llvm::sys::path::append(Result, "ModuleCache");
  2388. }
  2389. static void RenderModulesOptions(Compilation &C, const Driver &D,
  2390. const ArgList &Args, const InputInfo &Input,
  2391. const InputInfo &Output,
  2392. ArgStringList &CmdArgs, bool &HaveModules) {
  2393. // -fmodules enables the use of precompiled modules (off by default).
  2394. // Users can pass -fno-cxx-modules to turn off modules support for
  2395. // C++/Objective-C++ programs.
  2396. bool HaveClangModules = false;
  2397. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  2398. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  2399. options::OPT_fno_cxx_modules, true);
  2400. if (AllowedInCXX || !types::isCXX(Input.getType())) {
  2401. CmdArgs.push_back("-fmodules");
  2402. HaveClangModules = true;
  2403. }
  2404. }
  2405. HaveModules |= HaveClangModules;
  2406. if (Args.hasArg(options::OPT_fmodules_ts)) {
  2407. CmdArgs.push_back("-fmodules-ts");
  2408. HaveModules = true;
  2409. }
  2410. // -fmodule-maps enables implicit reading of module map files. By default,
  2411. // this is enabled if we are using Clang's flavor of precompiled modules.
  2412. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  2413. options::OPT_fno_implicit_module_maps, HaveClangModules))
  2414. CmdArgs.push_back("-fimplicit-module-maps");
  2415. // -fmodules-decluse checks that modules used are declared so (off by default)
  2416. if (Args.hasFlag(options::OPT_fmodules_decluse,
  2417. options::OPT_fno_modules_decluse, false))
  2418. CmdArgs.push_back("-fmodules-decluse");
  2419. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  2420. // all #included headers are part of modules.
  2421. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  2422. options::OPT_fno_modules_strict_decluse, false))
  2423. CmdArgs.push_back("-fmodules-strict-decluse");
  2424. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  2425. bool ImplicitModules = false;
  2426. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  2427. options::OPT_fno_implicit_modules, HaveClangModules)) {
  2428. if (HaveModules)
  2429. CmdArgs.push_back("-fno-implicit-modules");
  2430. } else if (HaveModules) {
  2431. ImplicitModules = true;
  2432. // -fmodule-cache-path specifies where our implicitly-built module files
  2433. // should be written.
  2434. SmallString<128> Path;
  2435. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  2436. Path = A->getValue();
  2437. if (C.isForDiagnostics()) {
  2438. // When generating crash reports, we want to emit the modules along with
  2439. // the reproduction sources, so we ignore any provided module path.
  2440. Path = Output.getFilename();
  2441. llvm::sys::path::replace_extension(Path, ".cache");
  2442. llvm::sys::path::append(Path, "modules");
  2443. } else if (Path.empty()) {
  2444. // No module path was provided: use the default.
  2445. Driver::getDefaultModuleCachePath(Path);
  2446. }
  2447. const char Arg[] = "-fmodules-cache-path=";
  2448. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  2449. CmdArgs.push_back(Args.MakeArgString(Path));
  2450. }
  2451. if (HaveModules) {
  2452. // -fprebuilt-module-path specifies where to load the prebuilt module files.
  2453. for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
  2454. CmdArgs.push_back(Args.MakeArgString(
  2455. std::string("-fprebuilt-module-path=") + A->getValue()));
  2456. A->claim();
  2457. }
  2458. if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
  2459. options::OPT_fno_modules_validate_input_files_content,
  2460. false))
  2461. CmdArgs.push_back("-fvalidate-ast-input-files-content");
  2462. }
  2463. // -fmodule-name specifies the module that is currently being built (or
  2464. // used for header checking by -fmodule-maps).
  2465. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
  2466. // -fmodule-map-file can be used to specify files containing module
  2467. // definitions.
  2468. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  2469. // -fbuiltin-module-map can be used to load the clang
  2470. // builtin headers modulemap file.
  2471. if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
  2472. SmallString<128> BuiltinModuleMap(D.ResourceDir);
  2473. llvm::sys::path::append(BuiltinModuleMap, "include");
  2474. llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
  2475. if (llvm::sys::fs::exists(BuiltinModuleMap))
  2476. CmdArgs.push_back(
  2477. Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
  2478. }
  2479. // The -fmodule-file=<name>=<file> form specifies the mapping of module
  2480. // names to precompiled module files (the module is loaded only if used).
  2481. // The -fmodule-file=<file> form can be used to unconditionally load
  2482. // precompiled module files (whether used or not).
  2483. if (HaveModules)
  2484. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  2485. else
  2486. Args.ClaimAllArgs(options::OPT_fmodule_file);
  2487. // When building modules and generating crashdumps, we need to dump a module
  2488. // dependency VFS alongside the output.
  2489. if (HaveClangModules && C.isForDiagnostics()) {
  2490. SmallString<128> VFSDir(Output.getFilename());
  2491. llvm::sys::path::replace_extension(VFSDir, ".cache");
  2492. // Add the cache directory as a temp so the crash diagnostics pick it up.
  2493. C.addTempFile(Args.MakeArgString(VFSDir));
  2494. llvm::sys::path::append(VFSDir, "vfs");
  2495. CmdArgs.push_back("-module-dependency-dir");
  2496. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  2497. }
  2498. if (HaveClangModules)
  2499. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  2500. // Pass through all -fmodules-ignore-macro arguments.
  2501. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  2502. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  2503. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  2504. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  2505. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  2506. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  2507. D.Diag(diag::err_drv_argument_not_allowed_with)
  2508. << A->getAsString(Args) << "-fbuild-session-timestamp";
  2509. llvm::sys::fs::file_status Status;
  2510. if (llvm::sys::fs::status(A->getValue(), Status))
  2511. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  2512. CmdArgs.push_back(
  2513. Args.MakeArgString("-fbuild-session-timestamp=" +
  2514. Twine((uint64_t)Status.getLastModificationTime()
  2515. .time_since_epoch()
  2516. .count())));
  2517. }
  2518. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  2519. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  2520. options::OPT_fbuild_session_file))
  2521. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  2522. Args.AddLastArg(CmdArgs,
  2523. options::OPT_fmodules_validate_once_per_build_session);
  2524. }
  2525. if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
  2526. options::OPT_fno_modules_validate_system_headers,
  2527. ImplicitModules))
  2528. CmdArgs.push_back("-fmodules-validate-system-headers");
  2529. Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
  2530. }
  2531. static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
  2532. ArgStringList &CmdArgs) {
  2533. // -fsigned-char is default.
  2534. if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
  2535. options::OPT_fno_signed_char,
  2536. options::OPT_funsigned_char,
  2537. options::OPT_fno_unsigned_char)) {
  2538. if (A->getOption().matches(options::OPT_funsigned_char) ||
  2539. A->getOption().matches(options::OPT_fno_signed_char)) {
  2540. CmdArgs.push_back("-fno-signed-char");
  2541. }
  2542. } else if (!isSignedCharDefault(T)) {
  2543. CmdArgs.push_back("-fno-signed-char");
  2544. }
  2545. // The default depends on the language standard.
  2546. Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
  2547. if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  2548. options::OPT_fno_short_wchar)) {
  2549. if (A->getOption().matches(options::OPT_fshort_wchar)) {
  2550. CmdArgs.push_back("-fwchar-type=short");
  2551. CmdArgs.push_back("-fno-signed-wchar");
  2552. } else {
  2553. bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
  2554. CmdArgs.push_back("-fwchar-type=int");
  2555. if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
  2556. T.isOSOpenBSD()))
  2557. CmdArgs.push_back("-fno-signed-wchar");
  2558. else
  2559. CmdArgs.push_back("-fsigned-wchar");
  2560. }
  2561. }
  2562. }
  2563. static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
  2564. const llvm::Triple &T, const ArgList &Args,
  2565. ObjCRuntime &Runtime, bool InferCovariantReturns,
  2566. const InputInfo &Input, ArgStringList &CmdArgs) {
  2567. const llvm::Triple::ArchType Arch = TC.getArch();
  2568. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
  2569. // is the default. Except for deployment target of 10.5, next runtime is
  2570. // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
  2571. if (Runtime.isNonFragile()) {
  2572. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  2573. options::OPT_fno_objc_legacy_dispatch,
  2574. Runtime.isLegacyDispatchDefaultForArch(Arch))) {
  2575. if (TC.UseObjCMixedDispatch())
  2576. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  2577. else
  2578. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  2579. }
  2580. }
  2581. // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
  2582. // to do Array/Dictionary subscripting by default.
  2583. if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
  2584. Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
  2585. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  2586. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  2587. // NOTE: This logic is duplicated in ToolChains.cpp.
  2588. if (isObjCAutoRefCount(Args)) {
  2589. TC.CheckObjCARC();
  2590. CmdArgs.push_back("-fobjc-arc");
  2591. // FIXME: It seems like this entire block, and several around it should be
  2592. // wrapped in isObjC, but for now we just use it here as this is where it
  2593. // was being used previously.
  2594. if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
  2595. if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  2596. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  2597. else
  2598. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  2599. }
  2600. // Allow the user to enable full exceptions code emission.
  2601. // We default off for Objective-C, on for Objective-C++.
  2602. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  2603. options::OPT_fno_objc_arc_exceptions,
  2604. /*Default=*/types::isCXX(Input.getType())))
  2605. CmdArgs.push_back("-fobjc-arc-exceptions");
  2606. }
  2607. // Silence warning for full exception code emission options when explicitly
  2608. // set to use no ARC.
  2609. if (Args.hasArg(options::OPT_fno_objc_arc)) {
  2610. Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
  2611. Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
  2612. }
  2613. // Allow the user to control whether messages can be converted to runtime
  2614. // functions.
  2615. if (types::isObjC(Input.getType())) {
  2616. auto *Arg = Args.getLastArg(
  2617. options::OPT_fobjc_convert_messages_to_runtime_calls,
  2618. options::OPT_fno_objc_convert_messages_to_runtime_calls);
  2619. if (Arg &&
  2620. Arg->getOption().matches(
  2621. options::OPT_fno_objc_convert_messages_to_runtime_calls))
  2622. CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
  2623. }
  2624. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  2625. // rewriter.
  2626. if (InferCovariantReturns)
  2627. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  2628. // Pass down -fobjc-weak or -fno-objc-weak if present.
  2629. if (types::isObjC(Input.getType())) {
  2630. auto WeakArg =
  2631. Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
  2632. if (!WeakArg) {
  2633. // nothing to do
  2634. } else if (!Runtime.allowsWeak()) {
  2635. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  2636. D.Diag(diag::err_objc_weak_unsupported);
  2637. } else {
  2638. WeakArg->render(Args, CmdArgs);
  2639. }
  2640. }
  2641. }
  2642. static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
  2643. ArgStringList &CmdArgs) {
  2644. bool CaretDefault = true;
  2645. bool ColumnDefault = true;
  2646. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
  2647. options::OPT__SLASH_diagnostics_column,
  2648. options::OPT__SLASH_diagnostics_caret)) {
  2649. switch (A->getOption().getID()) {
  2650. case options::OPT__SLASH_diagnostics_caret:
  2651. CaretDefault = true;
  2652. ColumnDefault = true;
  2653. break;
  2654. case options::OPT__SLASH_diagnostics_column:
  2655. CaretDefault = false;
  2656. ColumnDefault = true;
  2657. break;
  2658. case options::OPT__SLASH_diagnostics_classic:
  2659. CaretDefault = false;
  2660. ColumnDefault = false;
  2661. break;
  2662. }
  2663. }
  2664. // -fcaret-diagnostics is default.
  2665. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  2666. options::OPT_fno_caret_diagnostics, CaretDefault))
  2667. CmdArgs.push_back("-fno-caret-diagnostics");
  2668. // -fdiagnostics-fixit-info is default, only pass non-default.
  2669. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  2670. options::OPT_fno_diagnostics_fixit_info))
  2671. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  2672. // Enable -fdiagnostics-show-option by default.
  2673. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  2674. options::OPT_fno_diagnostics_show_option))
  2675. CmdArgs.push_back("-fdiagnostics-show-option");
  2676. if (const Arg *A =
  2677. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  2678. CmdArgs.push_back("-fdiagnostics-show-category");
  2679. CmdArgs.push_back(A->getValue());
  2680. }
  2681. if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
  2682. options::OPT_fno_diagnostics_show_hotness, false))
  2683. CmdArgs.push_back("-fdiagnostics-show-hotness");
  2684. if (const Arg *A =
  2685. Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
  2686. std::string Opt =
  2687. std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
  2688. CmdArgs.push_back(Args.MakeArgString(Opt));
  2689. }
  2690. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  2691. CmdArgs.push_back("-fdiagnostics-format");
  2692. CmdArgs.push_back(A->getValue());
  2693. }
  2694. if (const Arg *A = Args.getLastArg(
  2695. options::OPT_fdiagnostics_show_note_include_stack,
  2696. options::OPT_fno_diagnostics_show_note_include_stack)) {
  2697. const Option &O = A->getOption();
  2698. if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
  2699. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  2700. else
  2701. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  2702. }
  2703. // Color diagnostics are parsed by the driver directly from argv and later
  2704. // re-parsed to construct this job; claim any possible color diagnostic here
  2705. // to avoid warn_drv_unused_argument and diagnose bad
  2706. // OPT_fdiagnostics_color_EQ values.
  2707. for (const Arg *A : Args) {
  2708. const Option &O = A->getOption();
  2709. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  2710. !O.matches(options::OPT_fdiagnostics_color) &&
  2711. !O.matches(options::OPT_fno_color_diagnostics) &&
  2712. !O.matches(options::OPT_fno_diagnostics_color) &&
  2713. !O.matches(options::OPT_fdiagnostics_color_EQ))
  2714. continue;
  2715. if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
  2716. StringRef Value(A->getValue());
  2717. if (Value != "always" && Value != "never" && Value != "auto")
  2718. D.Diag(diag::err_drv_clang_unsupported)
  2719. << ("-fdiagnostics-color=" + Value).str();
  2720. }
  2721. A->claim();
  2722. }
  2723. if (D.getDiags().getDiagnosticOptions().ShowColors)
  2724. CmdArgs.push_back("-fcolor-diagnostics");
  2725. if (Args.hasArg(options::OPT_fansi_escape_codes))
  2726. CmdArgs.push_back("-fansi-escape-codes");
  2727. if (!Args.hasFlag(options::OPT_fshow_source_location,
  2728. options::OPT_fno_show_source_location))
  2729. CmdArgs.push_back("-fno-show-source-location");
  2730. if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
  2731. CmdArgs.push_back("-fdiagnostics-absolute-paths");
  2732. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  2733. ColumnDefault))
  2734. CmdArgs.push_back("-fno-show-column");
  2735. if (!Args.hasFlag(options::OPT_fspell_checking,
  2736. options::OPT_fno_spell_checking))
  2737. CmdArgs.push_back("-fno-spell-checking");
  2738. }
  2739. enum class DwarfFissionKind { None, Split, Single };
  2740. static DwarfFissionKind getDebugFissionKind(const Driver &D,
  2741. const ArgList &Args, Arg *&Arg) {
  2742. Arg =
  2743. Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
  2744. if (!Arg)
  2745. return DwarfFissionKind::None;
  2746. if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
  2747. return DwarfFissionKind::Split;
  2748. StringRef Value = Arg->getValue();
  2749. if (Value == "split")
  2750. return DwarfFissionKind::Split;
  2751. if (Value == "single")
  2752. return DwarfFissionKind::Single;
  2753. D.Diag(diag::err_drv_unsupported_option_argument)
  2754. << Arg->getOption().getName() << Arg->getValue();
  2755. return DwarfFissionKind::None;
  2756. }
  2757. static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
  2758. const llvm::Triple &T, const ArgList &Args,
  2759. bool EmitCodeView, bool IsWindowsMSVC,
  2760. ArgStringList &CmdArgs,
  2761. codegenoptions::DebugInfoKind &DebugInfoKind,
  2762. DwarfFissionKind &DwarfFission) {
  2763. if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
  2764. options::OPT_fno_debug_info_for_profiling, false) &&
  2765. checkDebugInfoOption(
  2766. Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
  2767. CmdArgs.push_back("-fdebug-info-for-profiling");
  2768. // The 'g' groups options involve a somewhat intricate sequence of decisions
  2769. // about what to pass from the driver to the frontend, but by the time they
  2770. // reach cc1 they've been factored into three well-defined orthogonal choices:
  2771. // * what level of debug info to generate
  2772. // * what dwarf version to write
  2773. // * what debugger tuning to use
  2774. // This avoids having to monkey around further in cc1 other than to disable
  2775. // codeview if not running in a Windows environment. Perhaps even that
  2776. // decision should be made in the driver as well though.
  2777. unsigned DWARFVersion = 0;
  2778. llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
  2779. bool SplitDWARFInlining =
  2780. Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
  2781. options::OPT_fno_split_dwarf_inlining, true);
  2782. Args.ClaimAllArgs(options::OPT_g_Group);
  2783. Arg* SplitDWARFArg;
  2784. DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
  2785. if (DwarfFission != DwarfFissionKind::None &&
  2786. !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
  2787. DwarfFission = DwarfFissionKind::None;
  2788. SplitDWARFInlining = false;
  2789. }
  2790. if (const Arg *A =
  2791. Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
  2792. options::OPT_gsplit_dwarf_EQ)) {
  2793. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  2794. // If the last option explicitly specified a debug-info level, use it.
  2795. if (checkDebugInfoOption(A, Args, D, TC) &&
  2796. A->getOption().matches(options::OPT_gN_Group)) {
  2797. DebugInfoKind = DebugLevelToInfoKind(*A);
  2798. // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
  2799. // complicated if you've disabled inline info in the skeleton CUs
  2800. // (SplitDWARFInlining) - then there's value in composing split-dwarf and
  2801. // line-tables-only, so let those compose naturally in that case.
  2802. if (DebugInfoKind == codegenoptions::NoDebugInfo ||
  2803. DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
  2804. (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
  2805. SplitDWARFInlining))
  2806. DwarfFission = DwarfFissionKind::None;
  2807. }
  2808. }
  2809. // If a debugger tuning argument appeared, remember it.
  2810. if (const Arg *A =
  2811. Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
  2812. if (checkDebugInfoOption(A, Args, D, TC)) {
  2813. if (A->getOption().matches(options::OPT_glldb))
  2814. DebuggerTuning = llvm::DebuggerKind::LLDB;
  2815. else if (A->getOption().matches(options::OPT_gsce))
  2816. DebuggerTuning = llvm::DebuggerKind::SCE;
  2817. else
  2818. DebuggerTuning = llvm::DebuggerKind::GDB;
  2819. }
  2820. }
  2821. // If a -gdwarf argument appeared, remember it.
  2822. if (const Arg *A =
  2823. Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  2824. options::OPT_gdwarf_4, options::OPT_gdwarf_5))
  2825. if (checkDebugInfoOption(A, Args, D, TC))
  2826. DWARFVersion = DwarfVersionNum(A->getSpelling());
  2827. if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
  2828. if (checkDebugInfoOption(A, Args, D, TC))
  2829. EmitCodeView = true;
  2830. }
  2831. // If the user asked for debug info but did not explicitly specify -gcodeview
  2832. // or -gdwarf, ask the toolchain for the default format.
  2833. if (!EmitCodeView && DWARFVersion == 0 &&
  2834. DebugInfoKind != codegenoptions::NoDebugInfo) {
  2835. switch (TC.getDefaultDebugFormat()) {
  2836. case codegenoptions::DIF_CodeView:
  2837. EmitCodeView = true;
  2838. break;
  2839. case codegenoptions::DIF_DWARF:
  2840. DWARFVersion = TC.GetDefaultDwarfVersion();
  2841. break;
  2842. }
  2843. }
  2844. // -gline-directives-only supported only for the DWARF debug info.
  2845. if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
  2846. DebugInfoKind = codegenoptions::NoDebugInfo;
  2847. // We ignore flag -gstrict-dwarf for now.
  2848. // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
  2849. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  2850. // Column info is included by default for everything except SCE and
  2851. // CodeView. Clang doesn't track end columns, just starting columns, which,
  2852. // in theory, is fine for CodeView (and PDB). In practice, however, the
  2853. // Microsoft debuggers don't handle missing end columns well, so it's better
  2854. // not to include any column info.
  2855. if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
  2856. (void)checkDebugInfoOption(A, Args, D, TC);
  2857. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  2858. /*Default=*/!EmitCodeView &&
  2859. DebuggerTuning != llvm::DebuggerKind::SCE))
  2860. CmdArgs.push_back("-dwarf-column-info");
  2861. // FIXME: Move backend command line options to the module.
  2862. // If -gline-tables-only or -gline-directives-only is the last option it wins.
  2863. if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
  2864. if (checkDebugInfoOption(A, Args, D, TC)) {
  2865. if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
  2866. DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
  2867. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  2868. CmdArgs.push_back("-dwarf-ext-refs");
  2869. CmdArgs.push_back("-fmodule-format=obj");
  2870. }
  2871. }
  2872. if (T.isOSBinFormatELF() && !SplitDWARFInlining)
  2873. CmdArgs.push_back("-fno-split-dwarf-inlining");
  2874. // After we've dealt with all combinations of things that could
  2875. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  2876. // figure out if we need to "upgrade" it to standalone debug info.
  2877. // We parse these two '-f' options whether or not they will be used,
  2878. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  2879. bool NeedFullDebug = Args.hasFlag(
  2880. options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
  2881. DebuggerTuning == llvm::DebuggerKind::LLDB ||
  2882. TC.GetDefaultStandaloneDebug());
  2883. if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
  2884. (void)checkDebugInfoOption(A, Args, D, TC);
  2885. if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
  2886. DebugInfoKind = codegenoptions::FullDebugInfo;
  2887. if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
  2888. false)) {
  2889. // Source embedding is a vendor extension to DWARF v5. By now we have
  2890. // checked if a DWARF version was stated explicitly, and have otherwise
  2891. // fallen back to the target default, so if this is still not at least 5
  2892. // we emit an error.
  2893. const Arg *A = Args.getLastArg(options::OPT_gembed_source);
  2894. if (DWARFVersion < 5)
  2895. D.Diag(diag::err_drv_argument_only_allowed_with)
  2896. << A->getAsString(Args) << "-gdwarf-5";
  2897. else if (checkDebugInfoOption(A, Args, D, TC))
  2898. CmdArgs.push_back("-gembed-source");
  2899. }
  2900. if (EmitCodeView) {
  2901. CmdArgs.push_back("-gcodeview");
  2902. // Emit codeview type hashes if requested.
  2903. if (Args.hasFlag(options::OPT_gcodeview_ghash,
  2904. options::OPT_gno_codeview_ghash, false)) {
  2905. CmdArgs.push_back("-gcodeview-ghash");
  2906. }
  2907. }
  2908. // Adjust the debug info kind for the given toolchain.
  2909. TC.adjustDebugInfoKind(DebugInfoKind, Args);
  2910. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
  2911. DebuggerTuning);
  2912. // -fdebug-macro turns on macro debug info generation.
  2913. if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
  2914. false))
  2915. if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
  2916. D, TC))
  2917. CmdArgs.push_back("-debug-info-macro");
  2918. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  2919. const auto *PubnamesArg =
  2920. Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
  2921. options::OPT_gpubnames, options::OPT_gno_pubnames);
  2922. if (DwarfFission != DwarfFissionKind::None ||
  2923. (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
  2924. if (!PubnamesArg ||
  2925. (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
  2926. !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
  2927. CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
  2928. options::OPT_gpubnames)
  2929. ? "-gpubnames"
  2930. : "-ggnu-pubnames");
  2931. if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
  2932. options::OPT_fno_debug_ranges_base_address, false)) {
  2933. CmdArgs.push_back("-fdebug-ranges-base-address");
  2934. }
  2935. // -gdwarf-aranges turns on the emission of the aranges section in the
  2936. // backend.
  2937. // Always enabled for SCE tuning.
  2938. bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
  2939. if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
  2940. NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
  2941. if (NeedAranges) {
  2942. CmdArgs.push_back("-mllvm");
  2943. CmdArgs.push_back("-generate-arange-section");
  2944. }
  2945. if (Args.hasFlag(options::OPT_fdebug_types_section,
  2946. options::OPT_fno_debug_types_section, false)) {
  2947. if (!T.isOSBinFormatELF()) {
  2948. D.Diag(diag::err_drv_unsupported_opt_for_target)
  2949. << Args.getLastArg(options::OPT_fdebug_types_section)
  2950. ->getAsString(Args)
  2951. << T.getTriple();
  2952. } else if (checkDebugInfoOption(
  2953. Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
  2954. TC)) {
  2955. CmdArgs.push_back("-mllvm");
  2956. CmdArgs.push_back("-generate-type-units");
  2957. }
  2958. }
  2959. // Decide how to render forward declarations of template instantiations.
  2960. // SCE wants full descriptions, others just get them in the name.
  2961. if (DebuggerTuning == llvm::DebuggerKind::SCE)
  2962. CmdArgs.push_back("-debug-forward-template-params");
  2963. // Do we need to explicitly import anonymous namespaces into the parent
  2964. // scope?
  2965. if (DebuggerTuning == llvm::DebuggerKind::SCE)
  2966. CmdArgs.push_back("-dwarf-explicit-import");
  2967. RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
  2968. }
  2969. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  2970. const InputInfo &Output, const InputInfoList &Inputs,
  2971. const ArgList &Args, const char *LinkingOutput) const {
  2972. const auto &TC = getToolChain();
  2973. const llvm::Triple &RawTriple = TC.getTriple();
  2974. const llvm::Triple &Triple = TC.getEffectiveTriple();
  2975. const std::string &TripleStr = Triple.getTriple();
  2976. bool KernelOrKext =
  2977. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  2978. const Driver &D = TC.getDriver();
  2979. ArgStringList CmdArgs;
  2980. // Check number of inputs for sanity. We need at least one input.
  2981. assert(Inputs.size() >= 1 && "Must have at least one input.");
  2982. // CUDA/HIP compilation may have multiple inputs (source file + results of
  2983. // device-side compilations). OpenMP device jobs also take the host IR as a
  2984. // second input. Module precompilation accepts a list of header files to
  2985. // include as part of the module. All other jobs are expected to have exactly
  2986. // one input.
  2987. bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
  2988. bool IsHIP = JA.isOffloading(Action::OFK_HIP);
  2989. bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
  2990. bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
  2991. // A header module compilation doesn't have a main input file, so invent a
  2992. // fake one as a placeholder.
  2993. const char *ModuleName = [&]{
  2994. auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
  2995. return ModuleNameArg ? ModuleNameArg->getValue() : "";
  2996. }();
  2997. InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
  2998. const InputInfo &Input =
  2999. IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
  3000. InputInfoList ModuleHeaderInputs;
  3001. const InputInfo *CudaDeviceInput = nullptr;
  3002. const InputInfo *OpenMPDeviceInput = nullptr;
  3003. for (const InputInfo &I : Inputs) {
  3004. if (&I == &Input) {
  3005. // This is the primary input.
  3006. } else if (IsHeaderModulePrecompile &&
  3007. types::getPrecompiledType(I.getType()) == types::TY_PCH) {
  3008. types::ID Expected = HeaderModuleInput.getType();
  3009. if (I.getType() != Expected) {
  3010. D.Diag(diag::err_drv_module_header_wrong_kind)
  3011. << I.getFilename() << types::getTypeName(I.getType())
  3012. << types::getTypeName(Expected);
  3013. }
  3014. ModuleHeaderInputs.push_back(I);
  3015. } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
  3016. CudaDeviceInput = &I;
  3017. } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
  3018. OpenMPDeviceInput = &I;
  3019. } else {
  3020. llvm_unreachable("unexpectedly given multiple inputs");
  3021. }
  3022. }
  3023. const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
  3024. bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
  3025. bool IsIAMCU = RawTriple.isOSIAMCU();
  3026. // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
  3027. // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
  3028. // Windows), we need to pass Windows-specific flags to cc1.
  3029. if (IsCuda || IsHIP)
  3030. IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
  3031. // C++ is not supported for IAMCU.
  3032. if (IsIAMCU && types::isCXX(Input.getType()))
  3033. D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
  3034. // Invoke ourselves in -cc1 mode.
  3035. //
  3036. // FIXME: Implement custom jobs for internal actions.
  3037. CmdArgs.push_back("-cc1");
  3038. // Add the "effective" target triple.
  3039. CmdArgs.push_back("-triple");
  3040. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  3041. if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
  3042. DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
  3043. Args.ClaimAllArgs(options::OPT_MJ);
  3044. } else if (const Arg *GenCDBFragment =
  3045. Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
  3046. DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
  3047. TripleStr, Output, Input, Args);
  3048. Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
  3049. }
  3050. if (IsCuda || IsHIP) {
  3051. // We have to pass the triple of the host if compiling for a CUDA/HIP device
  3052. // and vice-versa.
  3053. std::string NormalizedTriple;
  3054. if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
  3055. JA.isDeviceOffloading(Action::OFK_HIP))
  3056. NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
  3057. ->getTriple()
  3058. .normalize();
  3059. else {
  3060. // Host-side compilation.
  3061. NormalizedTriple =
  3062. (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
  3063. : C.getSingleOffloadToolChain<Action::OFK_HIP>())
  3064. ->getTriple()
  3065. .normalize();
  3066. if (IsCuda) {
  3067. // We need to figure out which CUDA version we're compiling for, as that
  3068. // determines how we load and launch GPU kernels.
  3069. auto *CTC = static_cast<const toolchains::CudaToolChain *>(
  3070. C.getSingleOffloadToolChain<Action::OFK_Cuda>());
  3071. assert(CTC && "Expected valid CUDA Toolchain.");
  3072. if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
  3073. CmdArgs.push_back(Args.MakeArgString(
  3074. Twine("-target-sdk-version=") +
  3075. CudaVersionToString(CTC->CudaInstallation.version())));
  3076. }
  3077. }
  3078. CmdArgs.push_back("-aux-triple");
  3079. CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
  3080. }
  3081. if (IsOpenMPDevice) {
  3082. // We have to pass the triple of the host if compiling for an OpenMP device.
  3083. std::string NormalizedTriple =
  3084. C.getSingleOffloadToolChain<Action::OFK_Host>()
  3085. ->getTriple()
  3086. .normalize();
  3087. CmdArgs.push_back("-aux-triple");
  3088. CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
  3089. }
  3090. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  3091. Triple.getArch() == llvm::Triple::thumb)) {
  3092. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  3093. unsigned Version;
  3094. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  3095. if (Version < 7)
  3096. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  3097. << TripleStr;
  3098. }
  3099. // Push all default warning arguments that are specific to
  3100. // the given target. These come before user provided warning options
  3101. // are provided.
  3102. TC.addClangWarningOptions(CmdArgs);
  3103. // Select the appropriate action.
  3104. RewriteKind rewriteKind = RK_None;
  3105. // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
  3106. // it claims when not running an assembler. Otherwise, clang would emit
  3107. // "argument unused" warnings for assembler flags when e.g. adding "-E" to
  3108. // flags while debugging something. That'd be somewhat inconvenient, and it's
  3109. // also inconsistent with most other flags -- we don't warn on
  3110. // -ffunction-sections not being used in -E mode either for example, even
  3111. // though it's not really used either.
  3112. if (!isa<AssembleJobAction>(JA)) {
  3113. // The args claimed here should match the args used in
  3114. // CollectArgsForIntegratedAssembler().
  3115. if (TC.useIntegratedAs()) {
  3116. Args.ClaimAllArgs(options::OPT_mrelax_all);
  3117. Args.ClaimAllArgs(options::OPT_mno_relax_all);
  3118. Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
  3119. Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
  3120. switch (C.getDefaultToolChain().getArch()) {
  3121. case llvm::Triple::arm:
  3122. case llvm::Triple::armeb:
  3123. case llvm::Triple::thumb:
  3124. case llvm::Triple::thumbeb:
  3125. Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
  3126. break;
  3127. default:
  3128. break;
  3129. }
  3130. }
  3131. Args.ClaimAllArgs(options::OPT_Wa_COMMA);
  3132. Args.ClaimAllArgs(options::OPT_Xassembler);
  3133. }
  3134. if (isa<AnalyzeJobAction>(JA)) {
  3135. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  3136. CmdArgs.push_back("-analyze");
  3137. } else if (isa<MigrateJobAction>(JA)) {
  3138. CmdArgs.push_back("-migrate");
  3139. } else if (isa<PreprocessJobAction>(JA)) {
  3140. if (Output.getType() == types::TY_Dependencies)
  3141. CmdArgs.push_back("-Eonly");
  3142. else {
  3143. CmdArgs.push_back("-E");
  3144. if (Args.hasArg(options::OPT_rewrite_objc) &&
  3145. !Args.hasArg(options::OPT_g_Group))
  3146. CmdArgs.push_back("-P");
  3147. }
  3148. } else if (isa<AssembleJobAction>(JA)) {
  3149. CmdArgs.push_back("-emit-obj");
  3150. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  3151. // Also ignore explicit -force_cpusubtype_ALL option.
  3152. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  3153. } else if (isa<PrecompileJobAction>(JA)) {
  3154. if (JA.getType() == types::TY_Nothing)
  3155. CmdArgs.push_back("-fsyntax-only");
  3156. else if (JA.getType() == types::TY_ModuleFile)
  3157. CmdArgs.push_back(IsHeaderModulePrecompile
  3158. ? "-emit-header-module"
  3159. : "-emit-module-interface");
  3160. else
  3161. CmdArgs.push_back("-emit-pch");
  3162. } else if (isa<VerifyPCHJobAction>(JA)) {
  3163. CmdArgs.push_back("-verify-pch");
  3164. } else {
  3165. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  3166. "Invalid action for clang tool.");
  3167. if (JA.getType() == types::TY_Nothing) {
  3168. CmdArgs.push_back("-fsyntax-only");
  3169. } else if (JA.getType() == types::TY_LLVM_IR ||
  3170. JA.getType() == types::TY_LTO_IR) {
  3171. CmdArgs.push_back("-emit-llvm");
  3172. } else if (JA.getType() == types::TY_LLVM_BC ||
  3173. JA.getType() == types::TY_LTO_BC) {
  3174. CmdArgs.push_back("-emit-llvm-bc");
  3175. } else if (JA.getType() == types::TY_IFS ||
  3176. JA.getType() == types::TY_IFS_CPP) {
  3177. StringRef ArgStr =
  3178. Args.hasArg(options::OPT_interface_stub_version_EQ)
  3179. ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
  3180. : "experimental-ifs-v1";
  3181. CmdArgs.push_back("-emit-interface-stubs");
  3182. CmdArgs.push_back(
  3183. Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
  3184. } else if (JA.getType() == types::TY_PP_Asm) {
  3185. CmdArgs.push_back("-S");
  3186. } else if (JA.getType() == types::TY_AST) {
  3187. CmdArgs.push_back("-emit-pch");
  3188. } else if (JA.getType() == types::TY_ModuleFile) {
  3189. CmdArgs.push_back("-module-file-info");
  3190. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3191. CmdArgs.push_back("-rewrite-objc");
  3192. rewriteKind = RK_NonFragile;
  3193. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3194. CmdArgs.push_back("-rewrite-objc");
  3195. rewriteKind = RK_Fragile;
  3196. } else {
  3197. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3198. }
  3199. // Preserve use-list order by default when emitting bitcode, so that
  3200. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3201. // same result as running passes here. For LTO, we don't need to preserve
  3202. // the use-list order, since serialization to bitcode is part of the flow.
  3203. if (JA.getType() == types::TY_LLVM_BC)
  3204. CmdArgs.push_back("-emit-llvm-uselists");
  3205. // Device-side jobs do not support LTO.
  3206. bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
  3207. JA.isDeviceOffloading(Action::OFK_Host));
  3208. if (D.isUsingLTO() && !isDeviceOffloadAction) {
  3209. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3210. CmdArgs.push_back("-flto-unit");
  3211. }
  3212. }
  3213. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  3214. if (!types::isLLVMIR(Input.getType()))
  3215. D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
  3216. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  3217. }
  3218. if (Args.getLastArg(options::OPT_save_temps_EQ))
  3219. Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
  3220. // Embed-bitcode option.
  3221. // Only white-listed flags below are allowed to be embedded.
  3222. if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
  3223. (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
  3224. // Add flags implied by -fembed-bitcode.
  3225. Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
  3226. // Disable all llvm IR level optimizations.
  3227. CmdArgs.push_back("-disable-llvm-passes");
  3228. // Render target options such as -fuse-init-array on modern ELF platforms.
  3229. TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
  3230. // reject options that shouldn't be supported in bitcode
  3231. // also reject kernel/kext
  3232. static const constexpr unsigned kBitcodeOptionBlacklist[] = {
  3233. options::OPT_mkernel,
  3234. options::OPT_fapple_kext,
  3235. options::OPT_ffunction_sections,
  3236. options::OPT_fno_function_sections,
  3237. options::OPT_fdata_sections,
  3238. options::OPT_fno_data_sections,
  3239. options::OPT_funique_section_names,
  3240. options::OPT_fno_unique_section_names,
  3241. options::OPT_mrestrict_it,
  3242. options::OPT_mno_restrict_it,
  3243. options::OPT_mstackrealign,
  3244. options::OPT_mno_stackrealign,
  3245. options::OPT_mstack_alignment,
  3246. options::OPT_mcmodel_EQ,
  3247. options::OPT_mlong_calls,
  3248. options::OPT_mno_long_calls,
  3249. options::OPT_ggnu_pubnames,
  3250. options::OPT_gdwarf_aranges,
  3251. options::OPT_fdebug_types_section,
  3252. options::OPT_fno_debug_types_section,
  3253. options::OPT_fdwarf_directory_asm,
  3254. options::OPT_fno_dwarf_directory_asm,
  3255. options::OPT_mrelax_all,
  3256. options::OPT_mno_relax_all,
  3257. options::OPT_ftrap_function_EQ,
  3258. options::OPT_ffixed_r9,
  3259. options::OPT_mfix_cortex_a53_835769,
  3260. options::OPT_mno_fix_cortex_a53_835769,
  3261. options::OPT_ffixed_x18,
  3262. options::OPT_mglobal_merge,
  3263. options::OPT_mno_global_merge,
  3264. options::OPT_mred_zone,
  3265. options::OPT_mno_red_zone,
  3266. options::OPT_Wa_COMMA,
  3267. options::OPT_Xassembler,
  3268. options::OPT_mllvm,
  3269. };
  3270. for (const auto &A : Args)
  3271. if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
  3272. std::end(kBitcodeOptionBlacklist))
  3273. D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
  3274. // Render the CodeGen options that need to be passed.
  3275. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3276. options::OPT_fno_optimize_sibling_calls))
  3277. CmdArgs.push_back("-mdisable-tail-calls");
  3278. RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
  3279. CmdArgs);
  3280. // Render ABI arguments
  3281. switch (TC.getArch()) {
  3282. default: break;
  3283. case llvm::Triple::arm:
  3284. case llvm::Triple::armeb:
  3285. case llvm::Triple::thumbeb:
  3286. RenderARMABI(Triple, Args, CmdArgs);
  3287. break;
  3288. case llvm::Triple::aarch64:
  3289. case llvm::Triple::aarch64_be:
  3290. RenderAArch64ABI(Triple, Args, CmdArgs);
  3291. break;
  3292. }
  3293. // Optimization level for CodeGen.
  3294. if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  3295. if (A->getOption().matches(options::OPT_O4)) {
  3296. CmdArgs.push_back("-O3");
  3297. D.Diag(diag::warn_O4_is_O3);
  3298. } else {
  3299. A->render(Args, CmdArgs);
  3300. }
  3301. }
  3302. // Input/Output file.
  3303. if (Output.getType() == types::TY_Dependencies) {
  3304. // Handled with other dependency code.
  3305. } else if (Output.isFilename()) {
  3306. CmdArgs.push_back("-o");
  3307. CmdArgs.push_back(Output.getFilename());
  3308. } else {
  3309. assert(Output.isNothing() && "Input output.");
  3310. }
  3311. for (const auto &II : Inputs) {
  3312. addDashXForInput(Args, II, CmdArgs);
  3313. if (II.isFilename())
  3314. CmdArgs.push_back(II.getFilename());
  3315. else
  3316. II.getInputArg().renderAsInput(Args, CmdArgs);
  3317. }
  3318. C.addCommand(std::make_unique<Command>(JA, *this, D.getClangProgramPath(),
  3319. CmdArgs, Inputs));
  3320. return;
  3321. }
  3322. if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
  3323. CmdArgs.push_back("-fembed-bitcode=marker");
  3324. // We normally speed up the clang process a bit by skipping destructors at
  3325. // exit, but when we're generating diagnostics we can rely on some of the
  3326. // cleanup.
  3327. if (!C.isForDiagnostics())
  3328. CmdArgs.push_back("-disable-free");
  3329. #ifdef NDEBUG
  3330. const bool IsAssertBuild = false;
  3331. #else
  3332. const bool IsAssertBuild = true;
  3333. #endif
  3334. // Disable the verification pass in -asserts builds.
  3335. if (!IsAssertBuild)
  3336. CmdArgs.push_back("-disable-llvm-verifier");
  3337. // Discard value names in assert builds unless otherwise specified.
  3338. if (Args.hasFlag(options::OPT_fdiscard_value_names,
  3339. options::OPT_fno_discard_value_names, !IsAssertBuild))
  3340. CmdArgs.push_back("-discard-value-names");
  3341. // Set the main file name, so that debug info works even with
  3342. // -save-temps.
  3343. CmdArgs.push_back("-main-file-name");
  3344. CmdArgs.push_back(getBaseInputName(Args, Input));
  3345. // Some flags which affect the language (via preprocessor
  3346. // defines).
  3347. if (Args.hasArg(options::OPT_static))
  3348. CmdArgs.push_back("-static-define");
  3349. if (Args.hasArg(options::OPT_municode))
  3350. CmdArgs.push_back("-DUNICODE");
  3351. if (isa<AnalyzeJobAction>(JA))
  3352. RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
  3353. if (isa<AnalyzeJobAction>(JA) ||
  3354. (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
  3355. CmdArgs.push_back("-setup-static-analyzer");
  3356. // Enable compatilibily mode to avoid analyzer-config related errors.
  3357. // Since we can't access frontend flags through hasArg, let's manually iterate
  3358. // through them.
  3359. bool FoundAnalyzerConfig = false;
  3360. for (auto Arg : Args.filtered(options::OPT_Xclang))
  3361. if (StringRef(Arg->getValue()) == "-analyzer-config") {
  3362. FoundAnalyzerConfig = true;
  3363. break;
  3364. }
  3365. if (!FoundAnalyzerConfig)
  3366. for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
  3367. if (StringRef(Arg->getValue()) == "-analyzer-config") {
  3368. FoundAnalyzerConfig = true;
  3369. break;
  3370. }
  3371. if (FoundAnalyzerConfig)
  3372. CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
  3373. CheckCodeGenerationOptions(D, Args);
  3374. unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
  3375. assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
  3376. if (FunctionAlignment) {
  3377. CmdArgs.push_back("-function-alignment");
  3378. CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
  3379. }
  3380. llvm::Reloc::Model RelocationModel;
  3381. unsigned PICLevel;
  3382. bool IsPIE;
  3383. std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
  3384. const char *RMName = RelocationModelName(RelocationModel);
  3385. if ((RelocationModel == llvm::Reloc::ROPI ||
  3386. RelocationModel == llvm::Reloc::ROPI_RWPI) &&
  3387. types::isCXX(Input.getType()) &&
  3388. !Args.hasArg(options::OPT_fallow_unsupported))
  3389. D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
  3390. if (RMName) {
  3391. CmdArgs.push_back("-mrelocation-model");
  3392. CmdArgs.push_back(RMName);
  3393. }
  3394. if (PICLevel > 0) {
  3395. CmdArgs.push_back("-pic-level");
  3396. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3397. if (IsPIE)
  3398. CmdArgs.push_back("-pic-is-pie");
  3399. }
  3400. if (RelocationModel == llvm::Reloc::ROPI ||
  3401. RelocationModel == llvm::Reloc::ROPI_RWPI)
  3402. CmdArgs.push_back("-fropi");
  3403. if (RelocationModel == llvm::Reloc::RWPI ||
  3404. RelocationModel == llvm::Reloc::ROPI_RWPI)
  3405. CmdArgs.push_back("-frwpi");
  3406. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3407. CmdArgs.push_back("-meabi");
  3408. CmdArgs.push_back(A->getValue());
  3409. }
  3410. CmdArgs.push_back("-mthread-model");
  3411. if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
  3412. if (!TC.isThreadModelSupported(A->getValue()))
  3413. D.Diag(diag::err_drv_invalid_thread_model_for_target)
  3414. << A->getValue() << A->getAsString(Args);
  3415. CmdArgs.push_back(A->getValue());
  3416. }
  3417. else
  3418. CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
  3419. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3420. if (Args.hasFlag(options::OPT_fmerge_all_constants,
  3421. options::OPT_fno_merge_all_constants, false))
  3422. CmdArgs.push_back("-fmerge-all-constants");
  3423. if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
  3424. options::OPT_fdelete_null_pointer_checks, false))
  3425. CmdArgs.push_back("-fno-delete-null-pointer-checks");
  3426. // LLVM Code Generator Options.
  3427. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3428. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3429. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3430. options::OPT_frewrite_map_file_EQ)) {
  3431. StringRef Map = A->getValue();
  3432. if (!llvm::sys::fs::exists(Map)) {
  3433. D.Diag(diag::err_drv_no_such_file) << Map;
  3434. } else {
  3435. CmdArgs.push_back("-frewrite-map-file");
  3436. CmdArgs.push_back(A->getValue());
  3437. A->claim();
  3438. }
  3439. }
  3440. }
  3441. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3442. StringRef v = A->getValue();
  3443. CmdArgs.push_back("-mllvm");
  3444. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3445. A->claim();
  3446. }
  3447. if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
  3448. true))
  3449. CmdArgs.push_back("-fno-jump-tables");
  3450. if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
  3451. options::OPT_fno_profile_sample_accurate, false))
  3452. CmdArgs.push_back("-fprofile-sample-accurate");
  3453. if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
  3454. options::OPT_fno_preserve_as_comments, true))
  3455. CmdArgs.push_back("-fno-preserve-as-comments");
  3456. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3457. CmdArgs.push_back("-mregparm");
  3458. CmdArgs.push_back(A->getValue());
  3459. }
  3460. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3461. options::OPT_freg_struct_return)) {
  3462. if (TC.getArch() != llvm::Triple::x86) {
  3463. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3464. << A->getSpelling() << RawTriple.str();
  3465. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3466. CmdArgs.push_back("-fpcc-struct-return");
  3467. } else {
  3468. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3469. CmdArgs.push_back("-freg-struct-return");
  3470. }
  3471. }
  3472. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3473. CmdArgs.push_back("-fdefault-calling-conv=stdcall");
  3474. CodeGenOptions::FramePointerKind FPKeepKind =
  3475. getFramePointerKind(Args, RawTriple);
  3476. const char *FPKeepKindStr = nullptr;
  3477. switch (FPKeepKind) {
  3478. case CodeGenOptions::FramePointerKind::None:
  3479. FPKeepKindStr = "-mframe-pointer=none";
  3480. break;
  3481. case CodeGenOptions::FramePointerKind::NonLeaf:
  3482. FPKeepKindStr = "-mframe-pointer=non-leaf";
  3483. break;
  3484. case CodeGenOptions::FramePointerKind::All:
  3485. FPKeepKindStr = "-mframe-pointer=all";
  3486. break;
  3487. }
  3488. assert(FPKeepKindStr && "unknown FramePointerKind");
  3489. CmdArgs.push_back(FPKeepKindStr);
  3490. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3491. options::OPT_fno_zero_initialized_in_bss))
  3492. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3493. bool OFastEnabled = isOptimizationLevelFast(Args);
  3494. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3495. // enabled. This alias option is being used to simplify the hasFlag logic.
  3496. OptSpecifier StrictAliasingAliasOption =
  3497. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3498. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3499. // doesn't do any TBAA.
  3500. bool TBAAOnByDefault = !D.IsCLMode();
  3501. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3502. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3503. CmdArgs.push_back("-relaxed-aliasing");
  3504. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3505. options::OPT_fno_struct_path_tbaa))
  3506. CmdArgs.push_back("-no-struct-path-tbaa");
  3507. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3508. false))
  3509. CmdArgs.push_back("-fstrict-enums");
  3510. if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
  3511. true))
  3512. CmdArgs.push_back("-fno-strict-return");
  3513. if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
  3514. options::OPT_fno_allow_editor_placeholders, false))
  3515. CmdArgs.push_back("-fallow-editor-placeholders");
  3516. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3517. options::OPT_fno_strict_vtable_pointers,
  3518. false))
  3519. CmdArgs.push_back("-fstrict-vtable-pointers");
  3520. if (Args.hasFlag(options::OPT_fforce_emit_vtables,
  3521. options::OPT_fno_force_emit_vtables,
  3522. false))
  3523. CmdArgs.push_back("-fforce-emit-vtables");
  3524. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3525. options::OPT_fno_optimize_sibling_calls))
  3526. CmdArgs.push_back("-mdisable-tail-calls");
  3527. if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
  3528. options::OPT_fescaping_block_tail_calls, false))
  3529. CmdArgs.push_back("-fno-escaping-block-tail-calls");
  3530. Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
  3531. options::OPT_fno_fine_grained_bitfield_accesses);
  3532. // Handle segmented stacks.
  3533. if (Args.hasArg(options::OPT_fsplit_stack))
  3534. CmdArgs.push_back("-split-stacks");
  3535. RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
  3536. if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
  3537. if (TC.getArch() == llvm::Triple::x86 ||
  3538. TC.getArch() == llvm::Triple::x86_64)
  3539. A->render(Args, CmdArgs);
  3540. else if ((TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64()) &&
  3541. (A->getOption().getID() != options::OPT_mlong_double_80))
  3542. A->render(Args, CmdArgs);
  3543. else
  3544. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3545. << A->getAsString(Args) << TripleStr;
  3546. }
  3547. // Decide whether to use verbose asm. Verbose assembly is the default on
  3548. // toolchains which have the integrated assembler on by default.
  3549. bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
  3550. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3551. IsIntegratedAssemblerDefault))
  3552. CmdArgs.push_back("-masm-verbose");
  3553. if (!TC.useIntegratedAs())
  3554. CmdArgs.push_back("-no-integrated-as");
  3555. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3556. CmdArgs.push_back("-mdebug-pass");
  3557. CmdArgs.push_back("Structure");
  3558. }
  3559. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3560. CmdArgs.push_back("-mdebug-pass");
  3561. CmdArgs.push_back("Arguments");
  3562. }
  3563. // Enable -mconstructor-aliases except on darwin, where we have to work around
  3564. // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
  3565. // aliases aren't supported.
  3566. if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
  3567. CmdArgs.push_back("-mconstructor-aliases");
  3568. // Darwin's kernel doesn't support guard variables; just die if we
  3569. // try to use them.
  3570. if (KernelOrKext && RawTriple.isOSDarwin())
  3571. CmdArgs.push_back("-fforbid-guard-variables");
  3572. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  3573. false)) {
  3574. CmdArgs.push_back("-mms-bitfields");
  3575. }
  3576. if (Args.hasFlag(options::OPT_mpie_copy_relocations,
  3577. options::OPT_mno_pie_copy_relocations,
  3578. false)) {
  3579. CmdArgs.push_back("-mpie-copy-relocations");
  3580. }
  3581. if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
  3582. CmdArgs.push_back("-fno-plt");
  3583. }
  3584. // -fhosted is default.
  3585. // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
  3586. // use Freestanding.
  3587. bool Freestanding =
  3588. Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  3589. KernelOrKext;
  3590. if (Freestanding)
  3591. CmdArgs.push_back("-ffreestanding");
  3592. // This is a coarse approximation of what llvm-gcc actually does, both
  3593. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3594. // complicated ways.
  3595. bool AsynchronousUnwindTables =
  3596. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3597. options::OPT_fno_asynchronous_unwind_tables,
  3598. (TC.IsUnwindTablesDefault(Args) ||
  3599. TC.getSanitizerArgs().needsUnwindTables()) &&
  3600. !Freestanding);
  3601. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3602. AsynchronousUnwindTables))
  3603. CmdArgs.push_back("-munwind-tables");
  3604. TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
  3605. // FIXME: Handle -mtune=.
  3606. (void)Args.hasArg(options::OPT_mtune_EQ);
  3607. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3608. CmdArgs.push_back("-mcode-model");
  3609. CmdArgs.push_back(A->getValue());
  3610. }
  3611. // Add the target cpu
  3612. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3613. if (!CPU.empty()) {
  3614. CmdArgs.push_back("-target-cpu");
  3615. CmdArgs.push_back(Args.MakeArgString(CPU));
  3616. }
  3617. RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
  3618. // These two are potentially updated by AddClangCLArgs.
  3619. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  3620. bool EmitCodeView = false;
  3621. // Add clang-cl arguments.
  3622. types::ID InputType = Input.getType();
  3623. if (D.IsCLMode())
  3624. AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
  3625. DwarfFissionKind DwarfFission;
  3626. RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
  3627. CmdArgs, DebugInfoKind, DwarfFission);
  3628. // Add the split debug info name to the command lines here so we
  3629. // can propagate it to the backend.
  3630. bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
  3631. TC.getTriple().isOSBinFormatELF() &&
  3632. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  3633. isa<BackendJobAction>(JA));
  3634. if (SplitDWARF) {
  3635. const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
  3636. CmdArgs.push_back("-split-dwarf-file");
  3637. CmdArgs.push_back(SplitDWARFOut);
  3638. if (DwarfFission == DwarfFissionKind::Split) {
  3639. CmdArgs.push_back("-split-dwarf-output");
  3640. CmdArgs.push_back(SplitDWARFOut);
  3641. }
  3642. }
  3643. // Pass the linker version in use.
  3644. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  3645. CmdArgs.push_back("-target-linker-version");
  3646. CmdArgs.push_back(A->getValue());
  3647. }
  3648. // Explicitly error on some things we know we don't support and can't just
  3649. // ignore.
  3650. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  3651. Arg *Unsupported;
  3652. if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
  3653. TC.getArch() == llvm::Triple::x86) {
  3654. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  3655. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  3656. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  3657. << Unsupported->getOption().getName();
  3658. }
  3659. // The faltivec option has been superseded by the maltivec option.
  3660. if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
  3661. D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
  3662. << Unsupported->getOption().getName()
  3663. << "please use -maltivec and include altivec.h explicitly";
  3664. if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
  3665. D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
  3666. << Unsupported->getOption().getName() << "please use -mno-altivec";
  3667. }
  3668. Args.AddAllArgs(CmdArgs, options::OPT_v);
  3669. Args.AddLastArg(CmdArgs, options::OPT_H);
  3670. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  3671. CmdArgs.push_back("-header-include-file");
  3672. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  3673. : "-");
  3674. }
  3675. Args.AddLastArg(CmdArgs, options::OPT_P);
  3676. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  3677. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  3678. CmdArgs.push_back("-diagnostic-log-file");
  3679. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  3680. : "-");
  3681. }
  3682. bool UseSeparateSections = isUseSeparateSections(Triple);
  3683. if (Args.hasFlag(options::OPT_ffunction_sections,
  3684. options::OPT_fno_function_sections, UseSeparateSections)) {
  3685. CmdArgs.push_back("-ffunction-sections");
  3686. }
  3687. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  3688. UseSeparateSections)) {
  3689. CmdArgs.push_back("-fdata-sections");
  3690. }
  3691. if (!Args.hasFlag(options::OPT_funique_section_names,
  3692. options::OPT_fno_unique_section_names, true))
  3693. CmdArgs.push_back("-fno-unique-section-names");
  3694. Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
  3695. options::OPT_finstrument_functions_after_inlining,
  3696. options::OPT_finstrument_function_entry_bare);
  3697. // NVPTX doesn't support PGO or coverage. There's no runtime support for
  3698. // sampling, overhead of call arc collection is way too high and there's no
  3699. // way to collect the output.
  3700. if (!Triple.isNVPTX())
  3701. addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
  3702. Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
  3703. // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
  3704. if (RawTriple.isPS4CPU() &&
  3705. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  3706. PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
  3707. PS4cpu::addSanitizerArgs(TC, CmdArgs);
  3708. }
  3709. // Pass options for controlling the default header search paths.
  3710. if (Args.hasArg(options::OPT_nostdinc)) {
  3711. CmdArgs.push_back("-nostdsysteminc");
  3712. CmdArgs.push_back("-nobuiltininc");
  3713. } else {
  3714. if (Args.hasArg(options::OPT_nostdlibinc))
  3715. CmdArgs.push_back("-nostdsysteminc");
  3716. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  3717. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  3718. }
  3719. // Pass the path to compiler resource files.
  3720. CmdArgs.push_back("-resource-dir");
  3721. CmdArgs.push_back(D.ResourceDir.c_str());
  3722. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  3723. RenderARCMigrateToolOptions(D, Args, CmdArgs);
  3724. // Add preprocessing options like -I, -D, etc. if we are using the
  3725. // preprocessor.
  3726. //
  3727. // FIXME: Support -fpreprocessed
  3728. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  3729. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
  3730. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  3731. // that "The compiler can only warn and ignore the option if not recognized".
  3732. // When building with ccache, it will pass -D options to clang even on
  3733. // preprocessed inputs and configure concludes that -fPIC is not supported.
  3734. Args.ClaimAllArgs(options::OPT_D);
  3735. // Manually translate -O4 to -O3; let clang reject others.
  3736. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  3737. if (A->getOption().matches(options::OPT_O4)) {
  3738. CmdArgs.push_back("-O3");
  3739. D.Diag(diag::warn_O4_is_O3);
  3740. } else {
  3741. A->render(Args, CmdArgs);
  3742. }
  3743. }
  3744. // Warn about ignored options to clang.
  3745. for (const Arg *A :
  3746. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  3747. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  3748. A->claim();
  3749. }
  3750. for (const Arg *A :
  3751. Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
  3752. D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
  3753. A->claim();
  3754. }
  3755. claimNoWarnArgs(Args);
  3756. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  3757. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  3758. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  3759. CmdArgs.push_back("-pedantic");
  3760. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  3761. Args.AddLastArg(CmdArgs, options::OPT_w);
  3762. // Fixed point flags
  3763. if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
  3764. /*Default=*/false))
  3765. Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
  3766. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  3767. // (-ansi is equivalent to -std=c89 or -std=c++98).
  3768. //
  3769. // If a std is supplied, only add -trigraphs if it follows the
  3770. // option.
  3771. bool ImplyVCPPCXXVer = false;
  3772. const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
  3773. if (Std) {
  3774. if (Std->getOption().matches(options::OPT_ansi))
  3775. if (types::isCXX(InputType))
  3776. CmdArgs.push_back("-std=c++98");
  3777. else
  3778. CmdArgs.push_back("-std=c89");
  3779. else
  3780. Std->render(Args, CmdArgs);
  3781. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  3782. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  3783. options::OPT_ftrigraphs,
  3784. options::OPT_fno_trigraphs))
  3785. if (A != Std)
  3786. A->render(Args, CmdArgs);
  3787. } else {
  3788. // Honor -std-default.
  3789. //
  3790. // FIXME: Clang doesn't correctly handle -std= when the input language
  3791. // doesn't match. For the time being just ignore this for C++ inputs;
  3792. // eventually we want to do all the standard defaulting here instead of
  3793. // splitting it between the driver and clang -cc1.
  3794. if (!types::isCXX(InputType))
  3795. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  3796. /*Joined=*/true);
  3797. else if (IsWindowsMSVC)
  3798. ImplyVCPPCXXVer = true;
  3799. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  3800. options::OPT_fno_trigraphs);
  3801. }
  3802. // GCC's behavior for -Wwrite-strings is a bit strange:
  3803. // * In C, this "warning flag" changes the types of string literals from
  3804. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  3805. // for the discarded qualifier.
  3806. // * In C++, this is just a normal warning flag.
  3807. //
  3808. // Implementing this warning correctly in C is hard, so we follow GCC's
  3809. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  3810. // a non-const char* in C, rather than using this crude hack.
  3811. if (!types::isCXX(InputType)) {
  3812. // FIXME: This should behave just like a warning flag, and thus should also
  3813. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  3814. Arg *WriteStrings =
  3815. Args.getLastArg(options::OPT_Wwrite_strings,
  3816. options::OPT_Wno_write_strings, options::OPT_w);
  3817. if (WriteStrings &&
  3818. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  3819. CmdArgs.push_back("-fconst-strings");
  3820. }
  3821. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  3822. // during C++ compilation, which it is by default. GCC keeps this define even
  3823. // in the presence of '-w', match this behavior bug-for-bug.
  3824. if (types::isCXX(InputType) &&
  3825. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  3826. true)) {
  3827. CmdArgs.push_back("-fdeprecated-macro");
  3828. }
  3829. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  3830. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  3831. if (Asm->getOption().matches(options::OPT_fasm))
  3832. CmdArgs.push_back("-fgnu-keywords");
  3833. else
  3834. CmdArgs.push_back("-fno-gnu-keywords");
  3835. }
  3836. if (ShouldDisableDwarfDirectory(Args, TC))
  3837. CmdArgs.push_back("-fno-dwarf-directory-asm");
  3838. if (ShouldDisableAutolink(Args, TC))
  3839. CmdArgs.push_back("-fno-autolink");
  3840. // Add in -fdebug-compilation-dir if necessary.
  3841. addDebugCompDirArg(Args, CmdArgs, D.getVFS());
  3842. addDebugPrefixMapArg(D, Args, CmdArgs);
  3843. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  3844. options::OPT_ftemplate_depth_EQ)) {
  3845. CmdArgs.push_back("-ftemplate-depth");
  3846. CmdArgs.push_back(A->getValue());
  3847. }
  3848. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  3849. CmdArgs.push_back("-foperator-arrow-depth");
  3850. CmdArgs.push_back(A->getValue());
  3851. }
  3852. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  3853. CmdArgs.push_back("-fconstexpr-depth");
  3854. CmdArgs.push_back(A->getValue());
  3855. }
  3856. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  3857. CmdArgs.push_back("-fconstexpr-steps");
  3858. CmdArgs.push_back(A->getValue());
  3859. }
  3860. if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
  3861. CmdArgs.push_back("-fexperimental-new-constant-interpreter");
  3862. if (Args.hasArg(options::OPT_fforce_experimental_new_constant_interpreter))
  3863. CmdArgs.push_back("-fforce-experimental-new-constant-interpreter");
  3864. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  3865. CmdArgs.push_back("-fbracket-depth");
  3866. CmdArgs.push_back(A->getValue());
  3867. }
  3868. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  3869. options::OPT_Wlarge_by_value_copy_def)) {
  3870. if (A->getNumValues()) {
  3871. StringRef bytes = A->getValue();
  3872. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  3873. } else
  3874. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  3875. }
  3876. if (Args.hasArg(options::OPT_relocatable_pch))
  3877. CmdArgs.push_back("-relocatable-pch");
  3878. if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
  3879. static const char *kCFABIs[] = {
  3880. "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
  3881. };
  3882. if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
  3883. D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
  3884. else
  3885. A->render(Args, CmdArgs);
  3886. }
  3887. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  3888. CmdArgs.push_back("-fconstant-string-class");
  3889. CmdArgs.push_back(A->getValue());
  3890. }
  3891. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  3892. CmdArgs.push_back("-ftabstop");
  3893. CmdArgs.push_back(A->getValue());
  3894. }
  3895. if (Args.hasFlag(options::OPT_fstack_size_section,
  3896. options::OPT_fno_stack_size_section, RawTriple.isPS4()))
  3897. CmdArgs.push_back("-fstack-size-section");
  3898. CmdArgs.push_back("-ferror-limit");
  3899. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  3900. CmdArgs.push_back(A->getValue());
  3901. else
  3902. CmdArgs.push_back("19");
  3903. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  3904. CmdArgs.push_back("-fmacro-backtrace-limit");
  3905. CmdArgs.push_back(A->getValue());
  3906. }
  3907. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  3908. CmdArgs.push_back("-ftemplate-backtrace-limit");
  3909. CmdArgs.push_back(A->getValue());
  3910. }
  3911. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  3912. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  3913. CmdArgs.push_back(A->getValue());
  3914. }
  3915. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  3916. CmdArgs.push_back("-fspell-checking-limit");
  3917. CmdArgs.push_back(A->getValue());
  3918. }
  3919. // Pass -fmessage-length=.
  3920. CmdArgs.push_back("-fmessage-length");
  3921. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  3922. CmdArgs.push_back(A->getValue());
  3923. } else {
  3924. // If -fmessage-length=N was not specified, determine whether this is a
  3925. // terminal and, if so, implicitly define -fmessage-length appropriately.
  3926. unsigned N = llvm::sys::Process::StandardErrColumns();
  3927. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  3928. }
  3929. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  3930. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  3931. options::OPT_fvisibility_ms_compat)) {
  3932. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  3933. CmdArgs.push_back("-fvisibility");
  3934. CmdArgs.push_back(A->getValue());
  3935. } else {
  3936. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  3937. CmdArgs.push_back("-fvisibility");
  3938. CmdArgs.push_back("hidden");
  3939. CmdArgs.push_back("-ftype-visibility");
  3940. CmdArgs.push_back("default");
  3941. }
  3942. }
  3943. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  3944. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
  3945. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  3946. // Forward -f (flag) options which we can pass directly.
  3947. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  3948. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  3949. Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
  3950. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  3951. Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
  3952. options::OPT_fno_emulated_tls);
  3953. Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
  3954. // AltiVec-like language extensions aren't relevant for assembling.
  3955. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
  3956. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  3957. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  3958. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  3959. // Forward flags for OpenMP. We don't do this if the current action is an
  3960. // device offloading action other than OpenMP.
  3961. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  3962. options::OPT_fno_openmp, false) &&
  3963. (JA.isDeviceOffloading(Action::OFK_None) ||
  3964. JA.isDeviceOffloading(Action::OFK_OpenMP))) {
  3965. switch (D.getOpenMPRuntime(Args)) {
  3966. case Driver::OMPRT_OMP:
  3967. case Driver::OMPRT_IOMP5:
  3968. // Clang can generate useful OpenMP code for these two runtime libraries.
  3969. CmdArgs.push_back("-fopenmp");
  3970. // If no option regarding the use of TLS in OpenMP codegeneration is
  3971. // given, decide a default based on the target. Otherwise rely on the
  3972. // options and pass the right information to the frontend.
  3973. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  3974. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  3975. CmdArgs.push_back("-fnoopenmp-use-tls");
  3976. Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
  3977. options::OPT_fno_openmp_simd);
  3978. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
  3979. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
  3980. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
  3981. Args.AddAllArgs(CmdArgs,
  3982. options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
  3983. if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
  3984. options::OPT_fno_openmp_optimistic_collapse,
  3985. /*Default=*/false))
  3986. CmdArgs.push_back("-fopenmp-optimistic-collapse");
  3987. // When in OpenMP offloading mode with NVPTX target, forward
  3988. // cuda-mode flag
  3989. if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
  3990. options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
  3991. CmdArgs.push_back("-fopenmp-cuda-mode");
  3992. // When in OpenMP offloading mode with NVPTX target, check if full runtime
  3993. // is required.
  3994. if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
  3995. options::OPT_fno_openmp_cuda_force_full_runtime,
  3996. /*Default=*/false))
  3997. CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
  3998. break;
  3999. default:
  4000. // By default, if Clang doesn't know how to generate useful OpenMP code
  4001. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  4002. // down to the actual compilation.
  4003. // FIXME: It would be better to have a mode which *only* omits IR
  4004. // generation based on the OpenMP support so that we get consistent
  4005. // semantic analysis, etc.
  4006. break;
  4007. }
  4008. } else {
  4009. Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
  4010. options::OPT_fno_openmp_simd);
  4011. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
  4012. }
  4013. const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  4014. Sanitize.addArgs(TC, Args, CmdArgs, InputType);
  4015. const XRayArgs &XRay = TC.getXRayArgs();
  4016. XRay.addArgs(TC, Args, CmdArgs, InputType);
  4017. if (TC.SupportsProfiling())
  4018. Args.AddLastArg(CmdArgs, options::OPT_pg);
  4019. if (TC.SupportsProfiling())
  4020. Args.AddLastArg(CmdArgs, options::OPT_mfentry);
  4021. if (Args.getLastArg(options::OPT_fapple_kext) ||
  4022. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  4023. CmdArgs.push_back("-fapple-kext");
  4024. Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
  4025. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  4026. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  4027. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  4028. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  4029. Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
  4030. Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
  4031. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  4032. Args.AddLastArg(CmdArgs, options::OPT_malign_double);
  4033. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  4034. CmdArgs.push_back("-ftrapv-handler");
  4035. CmdArgs.push_back(A->getValue());
  4036. }
  4037. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  4038. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  4039. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  4040. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  4041. if (A->getOption().matches(options::OPT_fwrapv))
  4042. CmdArgs.push_back("-fwrapv");
  4043. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  4044. options::OPT_fno_strict_overflow)) {
  4045. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  4046. CmdArgs.push_back("-fwrapv");
  4047. }
  4048. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  4049. options::OPT_fno_reroll_loops))
  4050. if (A->getOption().matches(options::OPT_freroll_loops))
  4051. CmdArgs.push_back("-freroll-loops");
  4052. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  4053. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  4054. options::OPT_fno_unroll_loops);
  4055. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  4056. if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
  4057. false))
  4058. CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
  4059. RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
  4060. RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
  4061. // Translate -mstackrealign
  4062. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  4063. false))
  4064. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  4065. if (Args.hasArg(options::OPT_mstack_alignment)) {
  4066. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  4067. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  4068. }
  4069. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  4070. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  4071. if (!Size.empty())
  4072. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  4073. else
  4074. CmdArgs.push_back("-mstack-probe-size=0");
  4075. }
  4076. if (!Args.hasFlag(options::OPT_mstack_arg_probe,
  4077. options::OPT_mno_stack_arg_probe, true))
  4078. CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
  4079. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4080. options::OPT_mno_restrict_it)) {
  4081. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4082. CmdArgs.push_back("-mllvm");
  4083. CmdArgs.push_back("-arm-restrict-it");
  4084. } else {
  4085. CmdArgs.push_back("-mllvm");
  4086. CmdArgs.push_back("-arm-no-restrict-it");
  4087. }
  4088. } else if (Triple.isOSWindows() &&
  4089. (Triple.getArch() == llvm::Triple::arm ||
  4090. Triple.getArch() == llvm::Triple::thumb)) {
  4091. // Windows on ARM expects restricted IT blocks
  4092. CmdArgs.push_back("-mllvm");
  4093. CmdArgs.push_back("-arm-restrict-it");
  4094. }
  4095. // Forward -cl options to -cc1
  4096. RenderOpenCLOptions(Args, CmdArgs);
  4097. if (Args.hasFlag(options::OPT_fhip_new_launch_api,
  4098. options::OPT_fno_hip_new_launch_api, false))
  4099. CmdArgs.push_back("-fhip-new-launch-api");
  4100. if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
  4101. CmdArgs.push_back(
  4102. Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
  4103. }
  4104. // Forward -f options with positive and negative forms; we translate
  4105. // these by hand.
  4106. if (Arg *A = getLastProfileSampleUseArg(Args)) {
  4107. auto *PGOArg = Args.getLastArg(
  4108. options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
  4109. options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
  4110. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
  4111. if (PGOArg)
  4112. D.Diag(diag::err_drv_argument_not_allowed_with)
  4113. << "SampleUse with PGO options";
  4114. StringRef fname = A->getValue();
  4115. if (!llvm::sys::fs::exists(fname))
  4116. D.Diag(diag::err_drv_no_such_file) << fname;
  4117. else
  4118. A->render(Args, CmdArgs);
  4119. }
  4120. Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
  4121. RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
  4122. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4123. options::OPT_fno_assume_sane_operator_new))
  4124. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4125. // -fblocks=0 is default.
  4126. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  4127. TC.IsBlocksDefault()) ||
  4128. (Args.hasArg(options::OPT_fgnu_runtime) &&
  4129. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  4130. !Args.hasArg(options::OPT_fno_blocks))) {
  4131. CmdArgs.push_back("-fblocks");
  4132. if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
  4133. CmdArgs.push_back("-fblocks-runtime-optional");
  4134. }
  4135. // -fencode-extended-block-signature=1 is default.
  4136. if (TC.IsEncodeExtendedBlockSignatureDefault())
  4137. CmdArgs.push_back("-fencode-extended-block-signature");
  4138. if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
  4139. false) &&
  4140. types::isCXX(InputType)) {
  4141. CmdArgs.push_back("-fcoroutines-ts");
  4142. }
  4143. Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
  4144. options::OPT_fno_double_square_bracket_attributes);
  4145. // -faccess-control is default.
  4146. if (Args.hasFlag(options::OPT_fno_access_control,
  4147. options::OPT_faccess_control, false))
  4148. CmdArgs.push_back("-fno-access-control");
  4149. // -felide-constructors is the default.
  4150. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4151. options::OPT_felide_constructors, false))
  4152. CmdArgs.push_back("-fno-elide-constructors");
  4153. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  4154. if (KernelOrKext || (types::isCXX(InputType) &&
  4155. (RTTIMode == ToolChain::RM_Disabled)))
  4156. CmdArgs.push_back("-fno-rtti");
  4157. // -fshort-enums=0 is default for all architectures except Hexagon.
  4158. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4159. TC.getArch() == llvm::Triple::hexagon))
  4160. CmdArgs.push_back("-fshort-enums");
  4161. RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
  4162. // -fuse-cxa-atexit is default.
  4163. if (!Args.hasFlag(
  4164. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  4165. !RawTriple.isOSWindows() &&
  4166. TC.getArch() != llvm::Triple::xcore &&
  4167. ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
  4168. RawTriple.hasEnvironment())) ||
  4169. KernelOrKext)
  4170. CmdArgs.push_back("-fno-use-cxa-atexit");
  4171. if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
  4172. options::OPT_fno_register_global_dtors_with_atexit,
  4173. RawTriple.isOSDarwin() && !KernelOrKext))
  4174. CmdArgs.push_back("-fregister-global-dtors-with-atexit");
  4175. // -fms-extensions=0 is default.
  4176. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4177. IsWindowsMSVC))
  4178. CmdArgs.push_back("-fms-extensions");
  4179. // -fno-use-line-directives is default.
  4180. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4181. options::OPT_fno_use_line_directives, false))
  4182. CmdArgs.push_back("-fuse-line-directives");
  4183. // -fms-compatibility=0 is default.
  4184. bool IsMSVCCompat = Args.hasFlag(
  4185. options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
  4186. (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  4187. options::OPT_fno_ms_extensions, true)));
  4188. if (IsMSVCCompat)
  4189. CmdArgs.push_back("-fms-compatibility");
  4190. // Handle -fgcc-version, if present.
  4191. VersionTuple GNUCVer;
  4192. if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
  4193. // Check that the version has 1 to 3 components and the minor and patch
  4194. // versions fit in two decimal digits.
  4195. StringRef Val = A->getValue();
  4196. Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
  4197. bool Invalid = GNUCVer.tryParse(Val);
  4198. unsigned Minor = GNUCVer.getMinor().getValueOr(0);
  4199. unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
  4200. if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
  4201. D.Diag(diag::err_drv_invalid_value)
  4202. << A->getAsString(Args) << A->getValue();
  4203. }
  4204. } else if (!IsMSVCCompat) {
  4205. // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
  4206. GNUCVer = VersionTuple(4, 2, 1);
  4207. }
  4208. if (!GNUCVer.empty()) {
  4209. CmdArgs.push_back(
  4210. Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
  4211. }
  4212. VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
  4213. if (!MSVT.empty())
  4214. CmdArgs.push_back(
  4215. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4216. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4217. if (ImplyVCPPCXXVer) {
  4218. StringRef LanguageStandard;
  4219. if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
  4220. Std = StdArg;
  4221. LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
  4222. .Case("c++14", "-std=c++14")
  4223. .Case("c++17", "-std=c++17")
  4224. .Case("c++latest", "-std=c++2a")
  4225. .Default("");
  4226. if (LanguageStandard.empty())
  4227. D.Diag(clang::diag::warn_drv_unused_argument)
  4228. << StdArg->getAsString(Args);
  4229. }
  4230. if (LanguageStandard.empty()) {
  4231. if (IsMSVC2015Compatible)
  4232. LanguageStandard = "-std=c++14";
  4233. else
  4234. LanguageStandard = "-std=c++11";
  4235. }
  4236. CmdArgs.push_back(LanguageStandard.data());
  4237. }
  4238. // -fno-borland-extensions is default.
  4239. if (Args.hasFlag(options::OPT_fborland_extensions,
  4240. options::OPT_fno_borland_extensions, false))
  4241. CmdArgs.push_back("-fborland-extensions");
  4242. // -fno-declspec is default, except for PS4.
  4243. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4244. RawTriple.isPS4()))
  4245. CmdArgs.push_back("-fdeclspec");
  4246. else if (Args.hasArg(options::OPT_fno_declspec))
  4247. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  4248. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  4249. // than 19.
  4250. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  4251. options::OPT_fno_threadsafe_statics,
  4252. !IsWindowsMSVC || IsMSVC2015Compatible))
  4253. CmdArgs.push_back("-fno-threadsafe-statics");
  4254. // -fno-delayed-template-parsing is default, except when targeting MSVC.
  4255. // Many old Windows SDK versions require this to parse.
  4256. // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
  4257. // compiler. We should be able to disable this by default at some point.
  4258. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  4259. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  4260. CmdArgs.push_back("-fdelayed-template-parsing");
  4261. // -fgnu-keywords default varies depending on language; only pass if
  4262. // specified.
  4263. Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
  4264. options::OPT_fno_gnu_keywords);
  4265. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  4266. false))
  4267. CmdArgs.push_back("-fgnu89-inline");
  4268. if (Args.hasArg(options::OPT_fno_inline))
  4269. CmdArgs.push_back("-fno-inline");
  4270. Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
  4271. options::OPT_finline_hint_functions,
  4272. options::OPT_fno_inline_functions);
  4273. // FIXME: Find a better way to determine whether the language has modules
  4274. // support by default, or just assume that all languages do.
  4275. bool HaveModules =
  4276. Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
  4277. RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
  4278. if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
  4279. options::OPT_fno_pch_validate_input_files_content, false))
  4280. CmdArgs.push_back("-fvalidate-ast-input-files-content");
  4281. Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
  4282. options::OPT_fno_experimental_new_pass_manager);
  4283. ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  4284. RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
  4285. Input, CmdArgs);
  4286. if (Args.hasFlag(options::OPT_fapplication_extension,
  4287. options::OPT_fno_application_extension, false))
  4288. CmdArgs.push_back("-fapplication-extension");
  4289. // Handle GCC-style exception args.
  4290. if (!C.getDriver().IsCLMode())
  4291. addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
  4292. // Handle exception personalities
  4293. Arg *A = Args.getLastArg(
  4294. options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
  4295. options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
  4296. if (A) {
  4297. const Option &Opt = A->getOption();
  4298. if (Opt.matches(options::OPT_fsjlj_exceptions))
  4299. CmdArgs.push_back("-fsjlj-exceptions");
  4300. if (Opt.matches(options::OPT_fseh_exceptions))
  4301. CmdArgs.push_back("-fseh-exceptions");
  4302. if (Opt.matches(options::OPT_fdwarf_exceptions))
  4303. CmdArgs.push_back("-fdwarf-exceptions");
  4304. if (Opt.matches(options::OPT_fwasm_exceptions))
  4305. CmdArgs.push_back("-fwasm-exceptions");
  4306. } else {
  4307. switch (TC.GetExceptionModel(Args)) {
  4308. default:
  4309. break;
  4310. case llvm::ExceptionHandling::DwarfCFI:
  4311. CmdArgs.push_back("-fdwarf-exceptions");
  4312. break;
  4313. case llvm::ExceptionHandling::SjLj:
  4314. CmdArgs.push_back("-fsjlj-exceptions");
  4315. break;
  4316. case llvm::ExceptionHandling::WinEH:
  4317. CmdArgs.push_back("-fseh-exceptions");
  4318. break;
  4319. }
  4320. }
  4321. // C++ "sane" operator new.
  4322. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4323. options::OPT_fno_assume_sane_operator_new))
  4324. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4325. // -frelaxed-template-template-args is off by default, as it is a severe
  4326. // breaking change until a corresponding change to template partial ordering
  4327. // is provided.
  4328. if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
  4329. options::OPT_fno_relaxed_template_template_args, false))
  4330. CmdArgs.push_back("-frelaxed-template-template-args");
  4331. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  4332. // most platforms.
  4333. if (Args.hasFlag(options::OPT_fsized_deallocation,
  4334. options::OPT_fno_sized_deallocation, false))
  4335. CmdArgs.push_back("-fsized-deallocation");
  4336. // -faligned-allocation is on by default in C++17 onwards and otherwise off
  4337. // by default.
  4338. if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
  4339. options::OPT_fno_aligned_allocation,
  4340. options::OPT_faligned_new_EQ)) {
  4341. if (A->getOption().matches(options::OPT_fno_aligned_allocation))
  4342. CmdArgs.push_back("-fno-aligned-allocation");
  4343. else
  4344. CmdArgs.push_back("-faligned-allocation");
  4345. }
  4346. // The default new alignment can be specified using a dedicated option or via
  4347. // a GCC-compatible option that also turns on aligned allocation.
  4348. if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
  4349. options::OPT_faligned_new_EQ))
  4350. CmdArgs.push_back(
  4351. Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
  4352. // -fconstant-cfstrings is default, and may be subject to argument translation
  4353. // on Darwin.
  4354. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  4355. options::OPT_fno_constant_cfstrings) ||
  4356. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  4357. options::OPT_mno_constant_cfstrings))
  4358. CmdArgs.push_back("-fno-constant-cfstrings");
  4359. // -fno-pascal-strings is default, only pass non-default.
  4360. if (Args.hasFlag(options::OPT_fpascal_strings,
  4361. options::OPT_fno_pascal_strings, false))
  4362. CmdArgs.push_back("-fpascal-strings");
  4363. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  4364. // -fno-pack-struct doesn't apply to -fpack-struct=.
  4365. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  4366. std::string PackStructStr = "-fpack-struct=";
  4367. PackStructStr += A->getValue();
  4368. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  4369. } else if (Args.hasFlag(options::OPT_fpack_struct,
  4370. options::OPT_fno_pack_struct, false)) {
  4371. CmdArgs.push_back("-fpack-struct=1");
  4372. }
  4373. // Handle -fmax-type-align=N and -fno-type-align
  4374. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  4375. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  4376. if (!SkipMaxTypeAlign) {
  4377. std::string MaxTypeAlignStr = "-fmax-type-align=";
  4378. MaxTypeAlignStr += A->getValue();
  4379. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4380. }
  4381. } else if (RawTriple.isOSDarwin()) {
  4382. if (!SkipMaxTypeAlign) {
  4383. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  4384. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4385. }
  4386. }
  4387. if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
  4388. CmdArgs.push_back("-Qn");
  4389. // -fcommon is the default unless compiling kernel code or the target says so
  4390. bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
  4391. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  4392. !NoCommonDefault))
  4393. CmdArgs.push_back("-fno-common");
  4394. // -fsigned-bitfields is default, and clang doesn't yet support
  4395. // -funsigned-bitfields.
  4396. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  4397. options::OPT_funsigned_bitfields))
  4398. D.Diag(diag::warn_drv_clang_unsupported)
  4399. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  4400. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  4401. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  4402. D.Diag(diag::err_drv_clang_unsupported)
  4403. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  4404. // -finput_charset=UTF-8 is default. Reject others
  4405. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  4406. StringRef value = inputCharset->getValue();
  4407. if (!value.equals_lower("utf-8"))
  4408. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  4409. << value;
  4410. }
  4411. // -fexec_charset=UTF-8 is default. Reject others
  4412. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  4413. StringRef value = execCharset->getValue();
  4414. if (!value.equals_lower("utf-8"))
  4415. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  4416. << value;
  4417. }
  4418. RenderDiagnosticsOptions(D, Args, CmdArgs);
  4419. // -fno-asm-blocks is default.
  4420. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  4421. false))
  4422. CmdArgs.push_back("-fasm-blocks");
  4423. // -fgnu-inline-asm is default.
  4424. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  4425. options::OPT_fno_gnu_inline_asm, true))
  4426. CmdArgs.push_back("-fno-gnu-inline-asm");
  4427. // Enable vectorization per default according to the optimization level
  4428. // selected. For optimization levels that want vectorization we use the alias
  4429. // option to simplify the hasFlag logic.
  4430. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  4431. OptSpecifier VectorizeAliasOption =
  4432. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  4433. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  4434. options::OPT_fno_vectorize, EnableVec))
  4435. CmdArgs.push_back("-vectorize-loops");
  4436. // -fslp-vectorize is enabled based on the optimization level selected.
  4437. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  4438. OptSpecifier SLPVectAliasOption =
  4439. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  4440. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  4441. options::OPT_fno_slp_vectorize, EnableSLPVec))
  4442. CmdArgs.push_back("-vectorize-slp");
  4443. ParseMPreferVectorWidth(D, Args, CmdArgs);
  4444. Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
  4445. Args.AddLastArg(CmdArgs,
  4446. options::OPT_fsanitize_undefined_strip_path_components_EQ);
  4447. // -fdollars-in-identifiers default varies depending on platform and
  4448. // language; only pass if specified.
  4449. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  4450. options::OPT_fno_dollars_in_identifiers)) {
  4451. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  4452. CmdArgs.push_back("-fdollars-in-identifiers");
  4453. else
  4454. CmdArgs.push_back("-fno-dollars-in-identifiers");
  4455. }
  4456. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  4457. // practical purposes.
  4458. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  4459. options::OPT_fno_unit_at_a_time)) {
  4460. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  4461. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  4462. }
  4463. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  4464. options::OPT_fno_apple_pragma_pack, false))
  4465. CmdArgs.push_back("-fapple-pragma-pack");
  4466. // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
  4467. if (Args.hasFlag(options::OPT_fsave_optimization_record,
  4468. options::OPT_foptimization_record_file_EQ,
  4469. options::OPT_fno_save_optimization_record, false) ||
  4470. Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
  4471. options::OPT_fno_save_optimization_record, false) ||
  4472. Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
  4473. options::OPT_fno_save_optimization_record, false)) {
  4474. CmdArgs.push_back("-opt-record-file");
  4475. const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
  4476. if (A) {
  4477. CmdArgs.push_back(A->getValue());
  4478. } else {
  4479. SmallString<128> F;
  4480. if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
  4481. if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
  4482. F = FinalOutput->getValue();
  4483. }
  4484. if (F.empty()) {
  4485. // Use the input filename.
  4486. F = llvm::sys::path::stem(Input.getBaseInput());
  4487. // If we're compiling for an offload architecture (i.e. a CUDA device),
  4488. // we need to make the file name for the device compilation different
  4489. // from the host compilation.
  4490. if (!JA.isDeviceOffloading(Action::OFK_None) &&
  4491. !JA.isDeviceOffloading(Action::OFK_Host)) {
  4492. llvm::sys::path::replace_extension(F, "");
  4493. F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
  4494. Triple.normalize());
  4495. F += "-";
  4496. F += JA.getOffloadingArch();
  4497. }
  4498. }
  4499. std::string Extension = "opt.";
  4500. if (const Arg *A =
  4501. Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
  4502. Extension += A->getValue();
  4503. else
  4504. Extension += "yaml";
  4505. llvm::sys::path::replace_extension(F, Extension);
  4506. CmdArgs.push_back(Args.MakeArgString(F));
  4507. }
  4508. if (const Arg *A =
  4509. Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
  4510. CmdArgs.push_back("-opt-record-passes");
  4511. CmdArgs.push_back(A->getValue());
  4512. }
  4513. if (const Arg *A =
  4514. Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
  4515. CmdArgs.push_back("-opt-record-format");
  4516. CmdArgs.push_back(A->getValue());
  4517. }
  4518. }
  4519. bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
  4520. options::OPT_fno_rewrite_imports, false);
  4521. if (RewriteImports)
  4522. CmdArgs.push_back("-frewrite-imports");
  4523. // Enable rewrite includes if the user's asked for it or if we're generating
  4524. // diagnostics.
  4525. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  4526. // nice to enable this when doing a crashdump for modules as well.
  4527. if (Args.hasFlag(options::OPT_frewrite_includes,
  4528. options::OPT_fno_rewrite_includes, false) ||
  4529. (C.isForDiagnostics() && !HaveModules))
  4530. CmdArgs.push_back("-frewrite-includes");
  4531. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  4532. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  4533. options::OPT_traditional_cpp)) {
  4534. if (isa<PreprocessJobAction>(JA))
  4535. CmdArgs.push_back("-traditional-cpp");
  4536. else
  4537. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  4538. }
  4539. Args.AddLastArg(CmdArgs, options::OPT_dM);
  4540. Args.AddLastArg(CmdArgs, options::OPT_dD);
  4541. // Handle serialized diagnostics.
  4542. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  4543. CmdArgs.push_back("-serialize-diagnostic-file");
  4544. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  4545. }
  4546. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  4547. CmdArgs.push_back("-fretain-comments-from-system-headers");
  4548. // Forward -fcomment-block-commands to -cc1.
  4549. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  4550. // Forward -fparse-all-comments to -cc1.
  4551. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  4552. // Turn -fplugin=name.so into -load name.so
  4553. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  4554. CmdArgs.push_back("-load");
  4555. CmdArgs.push_back(A->getValue());
  4556. A->claim();
  4557. }
  4558. // Forward -fpass-plugin=name.so to -cc1.
  4559. for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
  4560. CmdArgs.push_back(
  4561. Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
  4562. A->claim();
  4563. }
  4564. // Setup statistics file output.
  4565. SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
  4566. if (!StatsFile.empty())
  4567. CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
  4568. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  4569. // parser.
  4570. // -finclude-default-header flag is for preprocessor,
  4571. // do not pass it to other cc1 commands when save-temps is enabled
  4572. if (C.getDriver().isSaveTempsEnabled() &&
  4573. !isa<PreprocessJobAction>(JA)) {
  4574. for (auto Arg : Args.filtered(options::OPT_Xclang)) {
  4575. Arg->claim();
  4576. if (StringRef(Arg->getValue()) != "-finclude-default-header")
  4577. CmdArgs.push_back(Arg->getValue());
  4578. }
  4579. }
  4580. else {
  4581. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  4582. }
  4583. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  4584. A->claim();
  4585. // We translate this by hand to the -cc1 argument, since nightly test uses
  4586. // it and developers have been trained to spell it with -mllvm. Both
  4587. // spellings are now deprecated and should be removed.
  4588. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  4589. CmdArgs.push_back("-disable-llvm-optzns");
  4590. } else {
  4591. A->render(Args, CmdArgs);
  4592. }
  4593. }
  4594. // With -save-temps, we want to save the unoptimized bitcode output from the
  4595. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  4596. // by the frontend.
  4597. // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
  4598. // has slightly different breakdown between stages.
  4599. // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
  4600. // pristine IR generated by the frontend. Ideally, a new compile action should
  4601. // be added so both IR can be captured.
  4602. if (C.getDriver().isSaveTempsEnabled() &&
  4603. !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
  4604. isa<CompileJobAction>(JA))
  4605. CmdArgs.push_back("-disable-llvm-passes");
  4606. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  4607. const char *Exec = D.getClangProgramPath();
  4608. // Optionally embed the -cc1 level arguments into the debug info or a
  4609. // section, for build analysis.
  4610. // Also record command line arguments into the debug info if
  4611. // -grecord-gcc-switches options is set on.
  4612. // By default, -gno-record-gcc-switches is set on and no recording.
  4613. auto GRecordSwitches =
  4614. Args.hasFlag(options::OPT_grecord_command_line,
  4615. options::OPT_gno_record_command_line, false);
  4616. auto FRecordSwitches =
  4617. Args.hasFlag(options::OPT_frecord_command_line,
  4618. options::OPT_fno_record_command_line, false);
  4619. if (FRecordSwitches && !Triple.isOSBinFormatELF())
  4620. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4621. << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
  4622. << TripleStr;
  4623. if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
  4624. ArgStringList OriginalArgs;
  4625. for (const auto &Arg : Args)
  4626. Arg->render(Args, OriginalArgs);
  4627. SmallString<256> Flags;
  4628. Flags += Exec;
  4629. for (const char *OriginalArg : OriginalArgs) {
  4630. SmallString<128> EscapedArg;
  4631. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  4632. Flags += " ";
  4633. Flags += EscapedArg;
  4634. }
  4635. auto FlagsArgString = Args.MakeArgString(Flags);
  4636. if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
  4637. CmdArgs.push_back("-dwarf-debug-flags");
  4638. CmdArgs.push_back(FlagsArgString);
  4639. }
  4640. if (FRecordSwitches) {
  4641. CmdArgs.push_back("-record-command-line");
  4642. CmdArgs.push_back(FlagsArgString);
  4643. }
  4644. }
  4645. // Host-side cuda compilation receives all device-side outputs in a single
  4646. // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
  4647. if ((IsCuda || IsHIP) && CudaDeviceInput) {
  4648. CmdArgs.push_back("-fcuda-include-gpubinary");
  4649. CmdArgs.push_back(CudaDeviceInput->getFilename());
  4650. if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
  4651. CmdArgs.push_back("-fgpu-rdc");
  4652. }
  4653. if (IsCuda) {
  4654. if (Args.hasFlag(options::OPT_fcuda_short_ptr,
  4655. options::OPT_fno_cuda_short_ptr, false))
  4656. CmdArgs.push_back("-fcuda-short-ptr");
  4657. }
  4658. // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
  4659. // to specify the result of the compile phase on the host, so the meaningful
  4660. // device declarations can be identified. Also, -fopenmp-is-device is passed
  4661. // along to tell the frontend that it is generating code for a device, so that
  4662. // only the relevant declarations are emitted.
  4663. if (IsOpenMPDevice) {
  4664. CmdArgs.push_back("-fopenmp-is-device");
  4665. if (OpenMPDeviceInput) {
  4666. CmdArgs.push_back("-fopenmp-host-ir-file-path");
  4667. CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
  4668. }
  4669. }
  4670. // For all the host OpenMP offloading compile jobs we need to pass the targets
  4671. // information using -fopenmp-targets= option.
  4672. if (JA.isHostOffloading(Action::OFK_OpenMP)) {
  4673. SmallString<128> TargetInfo("-fopenmp-targets=");
  4674. Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
  4675. assert(Tgts && Tgts->getNumValues() &&
  4676. "OpenMP offloading has to have targets specified.");
  4677. for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
  4678. if (i)
  4679. TargetInfo += ',';
  4680. // We need to get the string from the triple because it may be not exactly
  4681. // the same as the one we get directly from the arguments.
  4682. llvm::Triple T(Tgts->getValue(i));
  4683. TargetInfo += T.getTriple();
  4684. }
  4685. CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
  4686. }
  4687. bool VirtualFunctionElimination =
  4688. Args.hasFlag(options::OPT_fvirtual_function_elimination,
  4689. options::OPT_fno_virtual_function_elimination, false);
  4690. if (VirtualFunctionElimination) {
  4691. // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
  4692. // in the future).
  4693. if (D.getLTOMode() != LTOK_Full)
  4694. D.Diag(diag::err_drv_argument_only_allowed_with)
  4695. << "-fvirtual-function-elimination"
  4696. << "-flto=full";
  4697. CmdArgs.push_back("-fvirtual-function-elimination");
  4698. }
  4699. // VFE requires whole-program-vtables, and enables it by default.
  4700. bool WholeProgramVTables = Args.hasFlag(
  4701. options::OPT_fwhole_program_vtables,
  4702. options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
  4703. if (VirtualFunctionElimination && !WholeProgramVTables) {
  4704. D.Diag(diag::err_drv_argument_not_allowed_with)
  4705. << "-fno-whole-program-vtables"
  4706. << "-fvirtual-function-elimination";
  4707. }
  4708. if (WholeProgramVTables) {
  4709. if (!D.isUsingLTO())
  4710. D.Diag(diag::err_drv_argument_only_allowed_with)
  4711. << "-fwhole-program-vtables"
  4712. << "-flto";
  4713. CmdArgs.push_back("-fwhole-program-vtables");
  4714. }
  4715. bool DefaultsSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
  4716. bool SplitLTOUnit =
  4717. Args.hasFlag(options::OPT_fsplit_lto_unit,
  4718. options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
  4719. if (Sanitize.needsLTO() && !SplitLTOUnit)
  4720. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
  4721. << "-fsanitize=cfi";
  4722. if (SplitLTOUnit)
  4723. CmdArgs.push_back("-fsplit-lto-unit");
  4724. if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
  4725. options::OPT_fno_experimental_isel)) {
  4726. CmdArgs.push_back("-mllvm");
  4727. if (A->getOption().matches(options::OPT_fexperimental_isel)) {
  4728. CmdArgs.push_back("-global-isel=1");
  4729. // GISel is on by default on AArch64 -O0, so don't bother adding
  4730. // the fallback remarks for it. Other combinations will add a warning of
  4731. // some kind.
  4732. bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
  4733. bool IsOptLevelSupported = false;
  4734. Arg *A = Args.getLastArg(options::OPT_O_Group);
  4735. if (Triple.getArch() == llvm::Triple::aarch64) {
  4736. if (!A || A->getOption().matches(options::OPT_O0))
  4737. IsOptLevelSupported = true;
  4738. }
  4739. if (!IsArchSupported || !IsOptLevelSupported) {
  4740. CmdArgs.push_back("-mllvm");
  4741. CmdArgs.push_back("-global-isel-abort=2");
  4742. if (!IsArchSupported)
  4743. D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
  4744. else
  4745. D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
  4746. }
  4747. } else {
  4748. CmdArgs.push_back("-global-isel=0");
  4749. }
  4750. }
  4751. if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
  4752. CmdArgs.push_back("-forder-file-instrumentation");
  4753. // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
  4754. // on, we need to pass these flags as linker flags and that will be handled
  4755. // outside of the compiler.
  4756. if (!D.isUsingLTO()) {
  4757. CmdArgs.push_back("-mllvm");
  4758. CmdArgs.push_back("-enable-order-file-instrumentation");
  4759. }
  4760. }
  4761. if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
  4762. options::OPT_fno_force_enable_int128)) {
  4763. if (A->getOption().matches(options::OPT_fforce_enable_int128))
  4764. CmdArgs.push_back("-fforce-enable-int128");
  4765. }
  4766. if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
  4767. options::OPT_fno_complete_member_pointers, false))
  4768. CmdArgs.push_back("-fcomplete-member-pointers");
  4769. if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
  4770. options::OPT_fno_cxx_static_destructors, true))
  4771. CmdArgs.push_back("-fno-c++-static-destructors");
  4772. if (Arg *A = Args.getLastArg(options::OPT_moutline,
  4773. options::OPT_mno_outline)) {
  4774. if (A->getOption().matches(options::OPT_moutline)) {
  4775. // We only support -moutline in AArch64 right now. If we're not compiling
  4776. // for AArch64, emit a warning and ignore the flag. Otherwise, add the
  4777. // proper mllvm flags.
  4778. if (Triple.getArch() != llvm::Triple::aarch64) {
  4779. D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
  4780. } else {
  4781. CmdArgs.push_back("-mllvm");
  4782. CmdArgs.push_back("-enable-machine-outliner");
  4783. }
  4784. } else {
  4785. // Disable all outlining behaviour.
  4786. CmdArgs.push_back("-mllvm");
  4787. CmdArgs.push_back("-enable-machine-outliner=never");
  4788. }
  4789. }
  4790. if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
  4791. (TC.getTriple().isOSBinFormatELF() ||
  4792. TC.getTriple().isOSBinFormatCOFF()) &&
  4793. !TC.getTriple().isPS4() &&
  4794. !TC.getTriple().isOSNetBSD() &&
  4795. !Distro(D.getVFS()).IsGentoo() &&
  4796. !TC.getTriple().isAndroid() &&
  4797. TC.useIntegratedAs()))
  4798. CmdArgs.push_back("-faddrsig");
  4799. if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
  4800. std::string Str = A->getAsString(Args);
  4801. if (!TC.getTriple().isOSBinFormatELF())
  4802. D.Diag(diag::err_drv_unsupported_opt_for_target)
  4803. << Str << TC.getTripleString();
  4804. CmdArgs.push_back(Args.MakeArgString(Str));
  4805. }
  4806. // Add the "-o out -x type src.c" flags last. This is done primarily to make
  4807. // the -cc1 command easier to edit when reproducing compiler crashes.
  4808. if (Output.getType() == types::TY_Dependencies) {
  4809. // Handled with other dependency code.
  4810. } else if (Output.isFilename()) {
  4811. CmdArgs.push_back("-o");
  4812. CmdArgs.push_back(Output.getFilename());
  4813. } else {
  4814. assert(Output.isNothing() && "Invalid output.");
  4815. }
  4816. addDashXForInput(Args, Input, CmdArgs);
  4817. ArrayRef<InputInfo> FrontendInputs = Input;
  4818. if (IsHeaderModulePrecompile)
  4819. FrontendInputs = ModuleHeaderInputs;
  4820. else if (Input.isNothing())
  4821. FrontendInputs = {};
  4822. for (const InputInfo &Input : FrontendInputs) {
  4823. if (Input.isFilename())
  4824. CmdArgs.push_back(Input.getFilename());
  4825. else
  4826. Input.getInputArg().renderAsInput(Args, CmdArgs);
  4827. }
  4828. // Finally add the compile command to the compilation.
  4829. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  4830. Output.getType() == types::TY_Object &&
  4831. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  4832. auto CLCommand =
  4833. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  4834. C.addCommand(std::make_unique<FallbackCommand>(
  4835. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  4836. } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
  4837. isa<PrecompileJobAction>(JA)) {
  4838. // In /fallback builds, run the main compilation even if the pch generation
  4839. // fails, so that the main compilation's fallback to cl.exe runs.
  4840. C.addCommand(std::make_unique<ForceSuccessCommand>(JA, *this, Exec,
  4841. CmdArgs, Inputs));
  4842. } else {
  4843. C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  4844. }
  4845. // Make the compile command echo its inputs for /showFilenames.
  4846. if (Output.getType() == types::TY_Object &&
  4847. Args.hasFlag(options::OPT__SLASH_showFilenames,
  4848. options::OPT__SLASH_showFilenames_, false)) {
  4849. C.getJobs().getJobs().back()->setPrintInputFilenames(true);
  4850. }
  4851. if (Arg *A = Args.getLastArg(options::OPT_pg))
  4852. if (FPKeepKind == CodeGenOptions::FramePointerKind::None)
  4853. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  4854. << A->getAsString(Args);
  4855. // Claim some arguments which clang supports automatically.
  4856. // -fpch-preprocess is used with gcc to add a special marker in the output to
  4857. // include the PCH file.
  4858. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  4859. // Claim some arguments which clang doesn't support, but we don't
  4860. // care to warn the user about.
  4861. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  4862. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  4863. // Disable warnings for clang -E -emit-llvm foo.c
  4864. Args.ClaimAllArgs(options::OPT_emit_llvm);
  4865. }
  4866. Clang::Clang(const ToolChain &TC)
  4867. // CAUTION! The first constructor argument ("clang") is not arbitrary,
  4868. // as it is for other tools. Some operations on a Tool actually test
  4869. // whether that tool is Clang based on the Tool's Name as a string.
  4870. : Tool("clang", "clang frontend", TC, RF_Full) {}
  4871. Clang::~Clang() {}
  4872. /// Add options related to the Objective-C runtime/ABI.
  4873. ///
  4874. /// Returns true if the runtime is non-fragile.
  4875. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  4876. ArgStringList &cmdArgs,
  4877. RewriteKind rewriteKind) const {
  4878. // Look for the controlling runtime option.
  4879. Arg *runtimeArg =
  4880. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  4881. options::OPT_fobjc_runtime_EQ);
  4882. // Just forward -fobjc-runtime= to the frontend. This supercedes
  4883. // options about fragility.
  4884. if (runtimeArg &&
  4885. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  4886. ObjCRuntime runtime;
  4887. StringRef value = runtimeArg->getValue();
  4888. if (runtime.tryParse(value)) {
  4889. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  4890. << value;
  4891. }
  4892. if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
  4893. (runtime.getVersion() >= VersionTuple(2, 0)))
  4894. if (!getToolChain().getTriple().isOSBinFormatELF() &&
  4895. !getToolChain().getTriple().isOSBinFormatCOFF()) {
  4896. getToolChain().getDriver().Diag(
  4897. diag::err_drv_gnustep_objc_runtime_incompatible_binary)
  4898. << runtime.getVersion().getMajor();
  4899. }
  4900. runtimeArg->render(args, cmdArgs);
  4901. return runtime;
  4902. }
  4903. // Otherwise, we'll need the ABI "version". Version numbers are
  4904. // slightly confusing for historical reasons:
  4905. // 1 - Traditional "fragile" ABI
  4906. // 2 - Non-fragile ABI, version 1
  4907. // 3 - Non-fragile ABI, version 2
  4908. unsigned objcABIVersion = 1;
  4909. // If -fobjc-abi-version= is present, use that to set the version.
  4910. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  4911. StringRef value = abiArg->getValue();
  4912. if (value == "1")
  4913. objcABIVersion = 1;
  4914. else if (value == "2")
  4915. objcABIVersion = 2;
  4916. else if (value == "3")
  4917. objcABIVersion = 3;
  4918. else
  4919. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  4920. } else {
  4921. // Otherwise, determine if we are using the non-fragile ABI.
  4922. bool nonFragileABIIsDefault =
  4923. (rewriteKind == RK_NonFragile ||
  4924. (rewriteKind == RK_None &&
  4925. getToolChain().IsObjCNonFragileABIDefault()));
  4926. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  4927. options::OPT_fno_objc_nonfragile_abi,
  4928. nonFragileABIIsDefault)) {
  4929. // Determine the non-fragile ABI version to use.
  4930. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  4931. unsigned nonFragileABIVersion = 1;
  4932. #else
  4933. unsigned nonFragileABIVersion = 2;
  4934. #endif
  4935. if (Arg *abiArg =
  4936. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  4937. StringRef value = abiArg->getValue();
  4938. if (value == "1")
  4939. nonFragileABIVersion = 1;
  4940. else if (value == "2")
  4941. nonFragileABIVersion = 2;
  4942. else
  4943. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4944. << value;
  4945. }
  4946. objcABIVersion = 1 + nonFragileABIVersion;
  4947. } else {
  4948. objcABIVersion = 1;
  4949. }
  4950. }
  4951. // We don't actually care about the ABI version other than whether
  4952. // it's non-fragile.
  4953. bool isNonFragile = objcABIVersion != 1;
  4954. // If we have no runtime argument, ask the toolchain for its default runtime.
  4955. // However, the rewriter only really supports the Mac runtime, so assume that.
  4956. ObjCRuntime runtime;
  4957. if (!runtimeArg) {
  4958. switch (rewriteKind) {
  4959. case RK_None:
  4960. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  4961. break;
  4962. case RK_Fragile:
  4963. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  4964. break;
  4965. case RK_NonFragile:
  4966. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  4967. break;
  4968. }
  4969. // -fnext-runtime
  4970. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  4971. // On Darwin, make this use the default behavior for the toolchain.
  4972. if (getToolChain().getTriple().isOSDarwin()) {
  4973. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  4974. // Otherwise, build for a generic macosx port.
  4975. } else {
  4976. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  4977. }
  4978. // -fgnu-runtime
  4979. } else {
  4980. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  4981. // Legacy behaviour is to target the gnustep runtime if we are in
  4982. // non-fragile mode or the GCC runtime in fragile mode.
  4983. if (isNonFragile)
  4984. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
  4985. else
  4986. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  4987. }
  4988. cmdArgs.push_back(
  4989. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  4990. return runtime;
  4991. }
  4992. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  4993. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  4994. I += HaveDash;
  4995. return !HaveDash;
  4996. }
  4997. namespace {
  4998. struct EHFlags {
  4999. bool Synch = false;
  5000. bool Asynch = false;
  5001. bool NoUnwindC = false;
  5002. };
  5003. } // end anonymous namespace
  5004. /// /EH controls whether to run destructor cleanups when exceptions are
  5005. /// thrown. There are three modifiers:
  5006. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  5007. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  5008. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  5009. /// - c: Assume that extern "C" functions are implicitly nounwind.
  5010. /// The default is /EHs-c-, meaning cleanups are disabled.
  5011. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  5012. EHFlags EH;
  5013. std::vector<std::string> EHArgs =
  5014. Args.getAllArgValues(options::OPT__SLASH_EH);
  5015. for (auto EHVal : EHArgs) {
  5016. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  5017. switch (EHVal[I]) {
  5018. case 'a':
  5019. EH.Asynch = maybeConsumeDash(EHVal, I);
  5020. if (EH.Asynch)
  5021. EH.Synch = false;
  5022. continue;
  5023. case 'c':
  5024. EH.NoUnwindC = maybeConsumeDash(EHVal, I);
  5025. continue;
  5026. case 's':
  5027. EH.Synch = maybeConsumeDash(EHVal, I);
  5028. if (EH.Synch)
  5029. EH.Asynch = false;
  5030. continue;
  5031. default:
  5032. break;
  5033. }
  5034. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  5035. break;
  5036. }
  5037. }
  5038. // The /GX, /GX- flags are only processed if there are not /EH flags.
  5039. // The default is that /GX is not specified.
  5040. if (EHArgs.empty() &&
  5041. Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
  5042. /*Default=*/false)) {
  5043. EH.Synch = true;
  5044. EH.NoUnwindC = true;
  5045. }
  5046. return EH;
  5047. }
  5048. void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
  5049. ArgStringList &CmdArgs,
  5050. codegenoptions::DebugInfoKind *DebugInfoKind,
  5051. bool *EmitCodeView) const {
  5052. unsigned RTOptionID = options::OPT__SLASH_MT;
  5053. if (Args.hasArg(options::OPT__SLASH_LDd))
  5054. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  5055. // but defining _DEBUG is sticky.
  5056. RTOptionID = options::OPT__SLASH_MTd;
  5057. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  5058. RTOptionID = A->getOption().getID();
  5059. StringRef FlagForCRT;
  5060. switch (RTOptionID) {
  5061. case options::OPT__SLASH_MD:
  5062. if (Args.hasArg(options::OPT__SLASH_LDd))
  5063. CmdArgs.push_back("-D_DEBUG");
  5064. CmdArgs.push_back("-D_MT");
  5065. CmdArgs.push_back("-D_DLL");
  5066. FlagForCRT = "--dependent-lib=msvcrt";
  5067. break;
  5068. case options::OPT__SLASH_MDd:
  5069. CmdArgs.push_back("-D_DEBUG");
  5070. CmdArgs.push_back("-D_MT");
  5071. CmdArgs.push_back("-D_DLL");
  5072. FlagForCRT = "--dependent-lib=msvcrtd";
  5073. break;
  5074. case options::OPT__SLASH_MT:
  5075. if (Args.hasArg(options::OPT__SLASH_LDd))
  5076. CmdArgs.push_back("-D_DEBUG");
  5077. CmdArgs.push_back("-D_MT");
  5078. CmdArgs.push_back("-flto-visibility-public-std");
  5079. FlagForCRT = "--dependent-lib=libcmt";
  5080. break;
  5081. case options::OPT__SLASH_MTd:
  5082. CmdArgs.push_back("-D_DEBUG");
  5083. CmdArgs.push_back("-D_MT");
  5084. CmdArgs.push_back("-flto-visibility-public-std");
  5085. FlagForCRT = "--dependent-lib=libcmtd";
  5086. break;
  5087. default:
  5088. llvm_unreachable("Unexpected option ID.");
  5089. }
  5090. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  5091. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  5092. } else {
  5093. CmdArgs.push_back(FlagForCRT.data());
  5094. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  5095. // users want. The /Za flag to cl.exe turns this off, but it's not
  5096. // implemented in clang.
  5097. CmdArgs.push_back("--dependent-lib=oldnames");
  5098. }
  5099. Args.AddLastArg(CmdArgs, options::OPT_show_includes);
  5100. // This controls whether or not we emit RTTI data for polymorphic types.
  5101. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  5102. /*Default=*/false))
  5103. CmdArgs.push_back("-fno-rtti-data");
  5104. // This controls whether or not we emit stack-protector instrumentation.
  5105. // In MSVC, Buffer Security Check (/GS) is on by default.
  5106. if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
  5107. /*Default=*/true)) {
  5108. CmdArgs.push_back("-stack-protector");
  5109. CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
  5110. }
  5111. // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
  5112. if (Arg *DebugInfoArg =
  5113. Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
  5114. options::OPT_gline_tables_only)) {
  5115. *EmitCodeView = true;
  5116. if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
  5117. *DebugInfoKind = codegenoptions::LimitedDebugInfo;
  5118. else
  5119. *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
  5120. } else {
  5121. *EmitCodeView = false;
  5122. }
  5123. const Driver &D = getToolChain().getDriver();
  5124. EHFlags EH = parseClangCLEHFlags(D, Args);
  5125. if (EH.Synch || EH.Asynch) {
  5126. if (types::isCXX(InputType))
  5127. CmdArgs.push_back("-fcxx-exceptions");
  5128. CmdArgs.push_back("-fexceptions");
  5129. }
  5130. if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
  5131. CmdArgs.push_back("-fexternc-nounwind");
  5132. // /EP should expand to -E -P.
  5133. if (Args.hasArg(options::OPT__SLASH_EP)) {
  5134. CmdArgs.push_back("-E");
  5135. CmdArgs.push_back("-P");
  5136. }
  5137. unsigned VolatileOptionID;
  5138. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  5139. getToolChain().getArch() == llvm::Triple::x86)
  5140. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  5141. else
  5142. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  5143. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  5144. VolatileOptionID = A->getOption().getID();
  5145. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  5146. CmdArgs.push_back("-fms-volatile");
  5147. if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
  5148. options::OPT__SLASH_Zc_dllexportInlines,
  5149. false)) {
  5150. if (Args.hasArg(options::OPT__SLASH_fallback)) {
  5151. D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
  5152. } else {
  5153. CmdArgs.push_back("-fno-dllexport-inlines");
  5154. }
  5155. }
  5156. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  5157. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  5158. if (MostGeneralArg && BestCaseArg)
  5159. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5160. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  5161. if (MostGeneralArg) {
  5162. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  5163. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  5164. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  5165. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  5166. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  5167. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  5168. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5169. << FirstConflict->getAsString(Args)
  5170. << SecondConflict->getAsString(Args);
  5171. if (SingleArg)
  5172. CmdArgs.push_back("-fms-memptr-rep=single");
  5173. else if (MultipleArg)
  5174. CmdArgs.push_back("-fms-memptr-rep=multiple");
  5175. else
  5176. CmdArgs.push_back("-fms-memptr-rep=virtual");
  5177. }
  5178. // Parse the default calling convention options.
  5179. if (Arg *CCArg =
  5180. Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
  5181. options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
  5182. options::OPT__SLASH_Gregcall)) {
  5183. unsigned DCCOptId = CCArg->getOption().getID();
  5184. const char *DCCFlag = nullptr;
  5185. bool ArchSupported = true;
  5186. llvm::Triple::ArchType Arch = getToolChain().getArch();
  5187. switch (DCCOptId) {
  5188. case options::OPT__SLASH_Gd:
  5189. DCCFlag = "-fdefault-calling-conv=cdecl";
  5190. break;
  5191. case options::OPT__SLASH_Gr:
  5192. ArchSupported = Arch == llvm::Triple::x86;
  5193. DCCFlag = "-fdefault-calling-conv=fastcall";
  5194. break;
  5195. case options::OPT__SLASH_Gz:
  5196. ArchSupported = Arch == llvm::Triple::x86;
  5197. DCCFlag = "-fdefault-calling-conv=stdcall";
  5198. break;
  5199. case options::OPT__SLASH_Gv:
  5200. ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
  5201. DCCFlag = "-fdefault-calling-conv=vectorcall";
  5202. break;
  5203. case options::OPT__SLASH_Gregcall:
  5204. ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
  5205. DCCFlag = "-fdefault-calling-conv=regcall";
  5206. break;
  5207. }
  5208. // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
  5209. if (ArchSupported && DCCFlag)
  5210. CmdArgs.push_back(DCCFlag);
  5211. }
  5212. Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
  5213. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  5214. CmdArgs.push_back("-fdiagnostics-format");
  5215. if (Args.hasArg(options::OPT__SLASH_fallback))
  5216. CmdArgs.push_back("msvc-fallback");
  5217. else
  5218. CmdArgs.push_back("msvc");
  5219. }
  5220. if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
  5221. SmallVector<StringRef, 1> SplitArgs;
  5222. StringRef(A->getValue()).split(SplitArgs, ",");
  5223. bool Instrument = false;
  5224. bool NoChecks = false;
  5225. for (StringRef Arg : SplitArgs) {
  5226. if (Arg.equals_lower("cf"))
  5227. Instrument = true;
  5228. else if (Arg.equals_lower("cf-"))
  5229. Instrument = false;
  5230. else if (Arg.equals_lower("nochecks"))
  5231. NoChecks = true;
  5232. else if (Arg.equals_lower("nochecks-"))
  5233. NoChecks = false;
  5234. else
  5235. D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
  5236. }
  5237. // Currently there's no support emitting CFG instrumentation; the flag only
  5238. // emits the table of address-taken functions.
  5239. if (Instrument || NoChecks)
  5240. CmdArgs.push_back("-cfguard");
  5241. }
  5242. }
  5243. visualstudio::Compiler *Clang::getCLFallback() const {
  5244. if (!CLFallback)
  5245. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  5246. return CLFallback.get();
  5247. }
  5248. const char *Clang::getBaseInputName(const ArgList &Args,
  5249. const InputInfo &Input) {
  5250. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  5251. }
  5252. const char *Clang::getBaseInputStem(const ArgList &Args,
  5253. const InputInfoList &Inputs) {
  5254. const char *Str = getBaseInputName(Args, Inputs[0]);
  5255. if (const char *End = strrchr(Str, '.'))
  5256. return Args.MakeArgString(std::string(Str, End));
  5257. return Str;
  5258. }
  5259. const char *Clang::getDependencyFileName(const ArgList &Args,
  5260. const InputInfoList &Inputs) {
  5261. // FIXME: Think about this more.
  5262. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  5263. SmallString<128> OutputFilename(OutputOpt->getValue());
  5264. llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
  5265. return Args.MakeArgString(OutputFilename);
  5266. }
  5267. return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
  5268. }
  5269. // Begin ClangAs
  5270. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  5271. ArgStringList &CmdArgs) const {
  5272. StringRef CPUName;
  5273. StringRef ABIName;
  5274. const llvm::Triple &Triple = getToolChain().getTriple();
  5275. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  5276. CmdArgs.push_back("-target-abi");
  5277. CmdArgs.push_back(ABIName.data());
  5278. }
  5279. void ClangAs::AddX86TargetArgs(const ArgList &Args,
  5280. ArgStringList &CmdArgs) const {
  5281. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  5282. StringRef Value = A->getValue();
  5283. if (Value == "intel" || Value == "att") {
  5284. CmdArgs.push_back("-mllvm");
  5285. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  5286. } else {
  5287. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  5288. << A->getOption().getName() << Value;
  5289. }
  5290. }
  5291. }
  5292. void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
  5293. ArgStringList &CmdArgs) const {
  5294. const llvm::Triple &Triple = getToolChain().getTriple();
  5295. StringRef ABIName = riscv::getRISCVABI(Args, Triple);
  5296. CmdArgs.push_back("-target-abi");
  5297. CmdArgs.push_back(ABIName.data());
  5298. }
  5299. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  5300. const InputInfo &Output, const InputInfoList &Inputs,
  5301. const ArgList &Args,
  5302. const char *LinkingOutput) const {
  5303. ArgStringList CmdArgs;
  5304. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5305. const InputInfo &Input = Inputs[0];
  5306. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  5307. const std::string &TripleStr = Triple.getTriple();
  5308. const auto &D = getToolChain().getDriver();
  5309. // Don't warn about "clang -w -c foo.s"
  5310. Args.ClaimAllArgs(options::OPT_w);
  5311. // and "clang -emit-llvm -c foo.s"
  5312. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5313. claimNoWarnArgs(Args);
  5314. // Invoke ourselves in -cc1as mode.
  5315. //
  5316. // FIXME: Implement custom jobs for internal actions.
  5317. CmdArgs.push_back("-cc1as");
  5318. // Add the "effective" target triple.
  5319. CmdArgs.push_back("-triple");
  5320. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  5321. // Set the output mode, we currently only expect to be used as a real
  5322. // assembler.
  5323. CmdArgs.push_back("-filetype");
  5324. CmdArgs.push_back("obj");
  5325. // Set the main file name, so that debug info works even with
  5326. // -save-temps or preprocessed assembly.
  5327. CmdArgs.push_back("-main-file-name");
  5328. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  5329. // Add the target cpu
  5330. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  5331. if (!CPU.empty()) {
  5332. CmdArgs.push_back("-target-cpu");
  5333. CmdArgs.push_back(Args.MakeArgString(CPU));
  5334. }
  5335. // Add the target features
  5336. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  5337. // Ignore explicit -force_cpusubtype_ALL option.
  5338. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  5339. // Pass along any -I options so we get proper .include search paths.
  5340. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  5341. // Determine the original source input.
  5342. const Action *SourceAction = &JA;
  5343. while (SourceAction->getKind() != Action::InputClass) {
  5344. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5345. SourceAction = SourceAction->getInputs()[0];
  5346. }
  5347. // Forward -g and handle debug info related flags, assuming we are dealing
  5348. // with an actual assembly file.
  5349. bool WantDebug = false;
  5350. unsigned DwarfVersion = 0;
  5351. Args.ClaimAllArgs(options::OPT_g_Group);
  5352. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  5353. WantDebug = !A->getOption().matches(options::OPT_g0) &&
  5354. !A->getOption().matches(options::OPT_ggdb0);
  5355. if (WantDebug)
  5356. DwarfVersion = DwarfVersionNum(A->getSpelling());
  5357. }
  5358. if (DwarfVersion == 0)
  5359. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  5360. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  5361. if (SourceAction->getType() == types::TY_Asm ||
  5362. SourceAction->getType() == types::TY_PP_Asm) {
  5363. // You might think that it would be ok to set DebugInfoKind outside of
  5364. // the guard for source type, however there is a test which asserts
  5365. // that some assembler invocation receives no -debug-info-kind,
  5366. // and it's not clear whether that test is just overly restrictive.
  5367. DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
  5368. : codegenoptions::NoDebugInfo);
  5369. // Add the -fdebug-compilation-dir flag if needed.
  5370. addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
  5371. addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
  5372. // Set the AT_producer to the clang version when using the integrated
  5373. // assembler on assembly source files.
  5374. CmdArgs.push_back("-dwarf-debug-producer");
  5375. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  5376. // And pass along -I options
  5377. Args.AddAllArgs(CmdArgs, options::OPT_I);
  5378. }
  5379. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  5380. llvm::DebuggerKind::Default);
  5381. RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
  5382. // Handle -fPIC et al -- the relocation-model affects the assembler
  5383. // for some targets.
  5384. llvm::Reloc::Model RelocationModel;
  5385. unsigned PICLevel;
  5386. bool IsPIE;
  5387. std::tie(RelocationModel, PICLevel, IsPIE) =
  5388. ParsePICArgs(getToolChain(), Args);
  5389. const char *RMName = RelocationModelName(RelocationModel);
  5390. if (RMName) {
  5391. CmdArgs.push_back("-mrelocation-model");
  5392. CmdArgs.push_back(RMName);
  5393. }
  5394. // Optionally embed the -cc1as level arguments into the debug info, for build
  5395. // analysis.
  5396. if (getToolChain().UseDwarfDebugFlags()) {
  5397. ArgStringList OriginalArgs;
  5398. for (const auto &Arg : Args)
  5399. Arg->render(Args, OriginalArgs);
  5400. SmallString<256> Flags;
  5401. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5402. Flags += Exec;
  5403. for (const char *OriginalArg : OriginalArgs) {
  5404. SmallString<128> EscapedArg;
  5405. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5406. Flags += " ";
  5407. Flags += EscapedArg;
  5408. }
  5409. CmdArgs.push_back("-dwarf-debug-flags");
  5410. CmdArgs.push_back(Args.MakeArgString(Flags));
  5411. }
  5412. // FIXME: Add -static support, once we have it.
  5413. // Add target specific flags.
  5414. switch (getToolChain().getArch()) {
  5415. default:
  5416. break;
  5417. case llvm::Triple::mips:
  5418. case llvm::Triple::mipsel:
  5419. case llvm::Triple::mips64:
  5420. case llvm::Triple::mips64el:
  5421. AddMIPSTargetArgs(Args, CmdArgs);
  5422. break;
  5423. case llvm::Triple::x86:
  5424. case llvm::Triple::x86_64:
  5425. AddX86TargetArgs(Args, CmdArgs);
  5426. break;
  5427. case llvm::Triple::arm:
  5428. case llvm::Triple::armeb:
  5429. case llvm::Triple::thumb:
  5430. case llvm::Triple::thumbeb:
  5431. // This isn't in AddARMTargetArgs because we want to do this for assembly
  5432. // only, not C/C++.
  5433. if (Args.hasFlag(options::OPT_mdefault_build_attributes,
  5434. options::OPT_mno_default_build_attributes, true)) {
  5435. CmdArgs.push_back("-mllvm");
  5436. CmdArgs.push_back("-arm-add-build-attributes");
  5437. }
  5438. break;
  5439. case llvm::Triple::riscv32:
  5440. case llvm::Triple::riscv64:
  5441. AddRISCVTargetArgs(Args, CmdArgs);
  5442. break;
  5443. }
  5444. // Consume all the warning flags. Usually this would be handled more
  5445. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  5446. // doesn't handle that so rather than warning about unused flags that are
  5447. // actually used, we'll lie by omission instead.
  5448. // FIXME: Stop lying and consume only the appropriate driver flags
  5449. Args.ClaimAllArgs(options::OPT_W_Group);
  5450. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  5451. getToolChain().getDriver());
  5452. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  5453. assert(Output.isFilename() && "Unexpected lipo output.");
  5454. CmdArgs.push_back("-o");
  5455. CmdArgs.push_back(Output.getFilename());
  5456. const llvm::Triple &T = getToolChain().getTriple();
  5457. Arg *A;
  5458. if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
  5459. T.isOSBinFormatELF()) {
  5460. CmdArgs.push_back("-split-dwarf-output");
  5461. CmdArgs.push_back(SplitDebugName(Args, Input, Output));
  5462. }
  5463. assert(Input.isFilename() && "Invalid input.");
  5464. CmdArgs.push_back(Input.getFilename());
  5465. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5466. C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5467. }
  5468. // Begin OffloadBundler
  5469. void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
  5470. const InputInfo &Output,
  5471. const InputInfoList &Inputs,
  5472. const llvm::opt::ArgList &TCArgs,
  5473. const char *LinkingOutput) const {
  5474. // The version with only one output is expected to refer to a bundling job.
  5475. assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
  5476. // The bundling command looks like this:
  5477. // clang-offload-bundler -type=bc
  5478. // -targets=host-triple,openmp-triple1,openmp-triple2
  5479. // -outputs=input_file
  5480. // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
  5481. ArgStringList CmdArgs;
  5482. // Get the type.
  5483. CmdArgs.push_back(TCArgs.MakeArgString(
  5484. Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
  5485. assert(JA.getInputs().size() == Inputs.size() &&
  5486. "Not have inputs for all dependence actions??");
  5487. // Get the targets.
  5488. SmallString<128> Triples;
  5489. Triples += "-targets=";
  5490. for (unsigned I = 0; I < Inputs.size(); ++I) {
  5491. if (I)
  5492. Triples += ',';
  5493. // Find ToolChain for this input.
  5494. Action::OffloadKind CurKind = Action::OFK_Host;
  5495. const ToolChain *CurTC = &getToolChain();
  5496. const Action *CurDep = JA.getInputs()[I];
  5497. if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
  5498. CurTC = nullptr;
  5499. OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
  5500. assert(CurTC == nullptr && "Expected one dependence!");
  5501. CurKind = A->getOffloadingDeviceKind();
  5502. CurTC = TC;
  5503. });
  5504. }
  5505. Triples += Action::GetOffloadKindName(CurKind);
  5506. Triples += '-';
  5507. Triples += CurTC->getTriple().normalize();
  5508. if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
  5509. Triples += '-';
  5510. Triples += CurDep->getOffloadingArch();
  5511. }
  5512. }
  5513. CmdArgs.push_back(TCArgs.MakeArgString(Triples));
  5514. // Get bundled file command.
  5515. CmdArgs.push_back(
  5516. TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
  5517. // Get unbundled files command.
  5518. SmallString<128> UB;
  5519. UB += "-inputs=";
  5520. for (unsigned I = 0; I < Inputs.size(); ++I) {
  5521. if (I)
  5522. UB += ',';
  5523. // Find ToolChain for this input.
  5524. const ToolChain *CurTC = &getToolChain();
  5525. if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
  5526. CurTC = nullptr;
  5527. OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
  5528. assert(CurTC == nullptr && "Expected one dependence!");
  5529. CurTC = TC;
  5530. });
  5531. }
  5532. UB += CurTC->getInputFilename(Inputs[I]);
  5533. }
  5534. CmdArgs.push_back(TCArgs.MakeArgString(UB));
  5535. // All the inputs are encoded as commands.
  5536. C.addCommand(std::make_unique<Command>(
  5537. JA, *this,
  5538. TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
  5539. CmdArgs, None));
  5540. }
  5541. void OffloadBundler::ConstructJobMultipleOutputs(
  5542. Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
  5543. const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
  5544. const char *LinkingOutput) const {
  5545. // The version with multiple outputs is expected to refer to a unbundling job.
  5546. auto &UA = cast<OffloadUnbundlingJobAction>(JA);
  5547. // The unbundling command looks like this:
  5548. // clang-offload-bundler -type=bc
  5549. // -targets=host-triple,openmp-triple1,openmp-triple2
  5550. // -inputs=input_file
  5551. // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
  5552. // -unbundle
  5553. ArgStringList CmdArgs;
  5554. assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
  5555. InputInfo Input = Inputs.front();
  5556. // Get the type.
  5557. CmdArgs.push_back(TCArgs.MakeArgString(
  5558. Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
  5559. // Get the targets.
  5560. SmallString<128> Triples;
  5561. Triples += "-targets=";
  5562. auto DepInfo = UA.getDependentActionsInfo();
  5563. for (unsigned I = 0; I < DepInfo.size(); ++I) {
  5564. if (I)
  5565. Triples += ',';
  5566. auto &Dep = DepInfo[I];
  5567. Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
  5568. Triples += '-';
  5569. Triples += Dep.DependentToolChain->getTriple().normalize();
  5570. if (Dep.DependentOffloadKind == Action::OFK_HIP &&
  5571. !Dep.DependentBoundArch.empty()) {
  5572. Triples += '-';
  5573. Triples += Dep.DependentBoundArch;
  5574. }
  5575. }
  5576. CmdArgs.push_back(TCArgs.MakeArgString(Triples));
  5577. // Get bundled file command.
  5578. CmdArgs.push_back(
  5579. TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
  5580. // Get unbundled files command.
  5581. SmallString<128> UB;
  5582. UB += "-outputs=";
  5583. for (unsigned I = 0; I < Outputs.size(); ++I) {
  5584. if (I)
  5585. UB += ',';
  5586. UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
  5587. }
  5588. CmdArgs.push_back(TCArgs.MakeArgString(UB));
  5589. CmdArgs.push_back("-unbundle");
  5590. // All the inputs are encoded as commands.
  5591. C.addCommand(std::make_unique<Command>(
  5592. JA, *this,
  5593. TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
  5594. CmdArgs, None));
  5595. }
  5596. void OffloadWrapper::ConstructJob(Compilation &C, const JobAction &JA,
  5597. const InputInfo &Output,
  5598. const InputInfoList &Inputs,
  5599. const ArgList &Args,
  5600. const char *LinkingOutput) const {
  5601. ArgStringList CmdArgs;
  5602. const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
  5603. // Add the "effective" target triple.
  5604. CmdArgs.push_back("-target");
  5605. CmdArgs.push_back(Args.MakeArgString(Triple.getTriple()));
  5606. // Add the output file name.
  5607. assert(Output.isFilename() && "Invalid output.");
  5608. CmdArgs.push_back("-o");
  5609. CmdArgs.push_back(Output.getFilename());
  5610. // Add inputs.
  5611. for (const InputInfo &I : Inputs) {
  5612. assert(I.isFilename() && "Invalid input.");
  5613. CmdArgs.push_back(I.getFilename());
  5614. }
  5615. C.addCommand(std::make_unique<Command>(
  5616. JA, *this,
  5617. Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
  5618. CmdArgs, Inputs));
  5619. }