Tools.cpp 403 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066
  1. //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "Tools.h"
  10. #include "InputInfo.h"
  11. #include "ToolChains.h"
  12. #include "clang/Basic/CharInfo.h"
  13. #include "clang/Basic/LangOptions.h"
  14. #include "clang/Basic/ObjCRuntime.h"
  15. #include "clang/Basic/Version.h"
  16. #include "clang/Config/config.h"
  17. #include "clang/Driver/Action.h"
  18. #include "clang/Driver/Compilation.h"
  19. #include "clang/Driver/Driver.h"
  20. #include "clang/Driver/DriverDiagnostic.h"
  21. #include "clang/Driver/Job.h"
  22. #include "clang/Driver/Options.h"
  23. #include "clang/Driver/SanitizerArgs.h"
  24. #include "clang/Driver/ToolChain.h"
  25. #include "clang/Driver/Util.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/SmallString.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/ADT/StringSwitch.h"
  30. #include "llvm/ADT/Twine.h"
  31. #include "llvm/Option/Arg.h"
  32. #include "llvm/Option/ArgList.h"
  33. #include "llvm/Option/Option.h"
  34. #include "llvm/Support/CodeGen.h"
  35. #include "llvm/Support/Compression.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/FileSystem.h"
  38. #include "llvm/Support/Host.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Process.h"
  41. #include "llvm/Support/Program.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Support/TargetParser.h"
  44. #ifdef LLVM_ON_UNIX
  45. #include <unistd.h> // For getuid().
  46. #endif
  47. using namespace clang::driver;
  48. using namespace clang::driver::tools;
  49. using namespace clang;
  50. using namespace llvm::opt;
  51. static void handleTargetFeaturesGroup(const ArgList &Args,
  52. std::vector<const char *> &Features,
  53. OptSpecifier Group) {
  54. for (const Arg *A : Args.filtered(Group)) {
  55. StringRef Name = A->getOption().getName();
  56. A->claim();
  57. // Skip over "-m".
  58. assert(Name.startswith("m") && "Invalid feature name.");
  59. Name = Name.substr(1);
  60. bool IsNegative = Name.startswith("no-");
  61. if (IsNegative)
  62. Name = Name.substr(3);
  63. Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
  64. }
  65. }
  66. static const char *getSparcAsmModeForCPU(StringRef Name,
  67. const llvm::Triple &Triple) {
  68. if (Triple.getArch() == llvm::Triple::sparcv9) {
  69. return llvm::StringSwitch<const char *>(Name)
  70. .Case("niagara", "-Av9b")
  71. .Case("niagara2", "-Av9b")
  72. .Case("niagara3", "-Av9d")
  73. .Case("niagara4", "-Av9d")
  74. .Default("-Av9");
  75. } else {
  76. return llvm::StringSwitch<const char *>(Name)
  77. .Case("v8", "-Av8")
  78. .Case("supersparc", "-Av8")
  79. .Case("sparclite", "-Asparclite")
  80. .Case("f934", "-Asparclite")
  81. .Case("hypersparc", "-Av8")
  82. .Case("sparclite86x", "-Asparclite")
  83. .Case("sparclet", "-Asparclet")
  84. .Case("tsc701", "-Asparclet")
  85. .Case("v9", "-Av8plus")
  86. .Case("ultrasparc", "-Av8plus")
  87. .Case("ultrasparc3", "-Av8plus")
  88. .Case("niagara", "-Av8plusb")
  89. .Case("niagara2", "-Av8plusb")
  90. .Case("niagara3", "-Av8plusd")
  91. .Case("niagara4", "-Av8plusd")
  92. .Default("-Av8");
  93. }
  94. }
  95. /// CheckPreprocessingOptions - Perform some validation of preprocessing
  96. /// arguments that is shared with gcc.
  97. static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
  98. if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
  99. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
  100. !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
  101. D.Diag(diag::err_drv_argument_only_allowed_with)
  102. << A->getBaseArg().getAsString(Args)
  103. << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
  104. }
  105. }
  106. }
  107. /// CheckCodeGenerationOptions - Perform some validation of code generation
  108. /// arguments that is shared with gcc.
  109. static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
  110. // In gcc, only ARM checks this, but it seems reasonable to check universally.
  111. if (Args.hasArg(options::OPT_static))
  112. if (const Arg *A =
  113. Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
  114. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  115. << "-static";
  116. }
  117. // Add backslashes to escape spaces and other backslashes.
  118. // This is used for the space-separated argument list specified with
  119. // the -dwarf-debug-flags option.
  120. static void EscapeSpacesAndBackslashes(const char *Arg,
  121. SmallVectorImpl<char> &Res) {
  122. for (; *Arg; ++Arg) {
  123. switch (*Arg) {
  124. default:
  125. break;
  126. case ' ':
  127. case '\\':
  128. Res.push_back('\\');
  129. break;
  130. }
  131. Res.push_back(*Arg);
  132. }
  133. }
  134. // Quote target names for inclusion in GNU Make dependency files.
  135. // Only the characters '$', '#', ' ', '\t' are quoted.
  136. static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
  137. for (unsigned i = 0, e = Target.size(); i != e; ++i) {
  138. switch (Target[i]) {
  139. case ' ':
  140. case '\t':
  141. // Escape the preceding backslashes
  142. for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
  143. Res.push_back('\\');
  144. // Escape the space/tab
  145. Res.push_back('\\');
  146. break;
  147. case '$':
  148. Res.push_back('$');
  149. break;
  150. case '#':
  151. Res.push_back('\\');
  152. break;
  153. default:
  154. break;
  155. }
  156. Res.push_back(Target[i]);
  157. }
  158. }
  159. static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
  160. const char *ArgName, const char *EnvVar) {
  161. const char *DirList = ::getenv(EnvVar);
  162. bool CombinedArg = false;
  163. if (!DirList)
  164. return; // Nothing to do.
  165. StringRef Name(ArgName);
  166. if (Name.equals("-I") || Name.equals("-L"))
  167. CombinedArg = true;
  168. StringRef Dirs(DirList);
  169. if (Dirs.empty()) // Empty string should not add '.'.
  170. return;
  171. StringRef::size_type Delim;
  172. while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
  173. if (Delim == 0) { // Leading colon.
  174. if (CombinedArg) {
  175. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  176. } else {
  177. CmdArgs.push_back(ArgName);
  178. CmdArgs.push_back(".");
  179. }
  180. } else {
  181. if (CombinedArg) {
  182. CmdArgs.push_back(
  183. Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
  184. } else {
  185. CmdArgs.push_back(ArgName);
  186. CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
  187. }
  188. }
  189. Dirs = Dirs.substr(Delim + 1);
  190. }
  191. if (Dirs.empty()) { // Trailing colon.
  192. if (CombinedArg) {
  193. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
  194. } else {
  195. CmdArgs.push_back(ArgName);
  196. CmdArgs.push_back(".");
  197. }
  198. } else { // Add the last path.
  199. if (CombinedArg) {
  200. CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
  201. } else {
  202. CmdArgs.push_back(ArgName);
  203. CmdArgs.push_back(Args.MakeArgString(Dirs));
  204. }
  205. }
  206. }
  207. static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
  208. const ArgList &Args, ArgStringList &CmdArgs) {
  209. const Driver &D = TC.getDriver();
  210. // Add extra linker input arguments which are not treated as inputs
  211. // (constructed via -Xarch_).
  212. Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
  213. for (const auto &II : Inputs) {
  214. if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
  215. // Don't try to pass LLVM inputs unless we have native support.
  216. D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
  217. // Add filenames immediately.
  218. if (II.isFilename()) {
  219. CmdArgs.push_back(II.getFilename());
  220. continue;
  221. }
  222. // Otherwise, this is a linker input argument.
  223. const Arg &A = II.getInputArg();
  224. // Handle reserved library options.
  225. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
  226. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  227. else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
  228. TC.AddCCKextLibArgs(Args, CmdArgs);
  229. else if (A.getOption().matches(options::OPT_z)) {
  230. // Pass -z prefix for gcc linker compatibility.
  231. A.claim();
  232. A.render(Args, CmdArgs);
  233. } else {
  234. A.renderAsInput(Args, CmdArgs);
  235. }
  236. }
  237. // LIBRARY_PATH - included following the user specified library paths.
  238. // and only supported on native toolchains.
  239. if (!TC.isCrossCompiling())
  240. addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
  241. }
  242. /// \brief Determine whether Objective-C automated reference counting is
  243. /// enabled.
  244. static bool isObjCAutoRefCount(const ArgList &Args) {
  245. return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
  246. }
  247. /// \brief Determine whether we are linking the ObjC runtime.
  248. static bool isObjCRuntimeLinked(const ArgList &Args) {
  249. if (isObjCAutoRefCount(Args)) {
  250. Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
  251. return true;
  252. }
  253. return Args.hasArg(options::OPT_fobjc_link_runtime);
  254. }
  255. static bool forwardToGCC(const Option &O) {
  256. // Don't forward inputs from the original command line. They are added from
  257. // InputInfoList.
  258. return O.getKind() != Option::InputClass &&
  259. !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
  260. }
  261. void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
  262. const Driver &D, const ArgList &Args,
  263. ArgStringList &CmdArgs,
  264. const InputInfo &Output,
  265. const InputInfoList &Inputs,
  266. const ToolChain *AuxToolChain) const {
  267. Arg *A;
  268. CheckPreprocessingOptions(D, Args);
  269. Args.AddLastArg(CmdArgs, options::OPT_C);
  270. Args.AddLastArg(CmdArgs, options::OPT_CC);
  271. // Handle dependency file generation.
  272. if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
  273. (A = Args.getLastArg(options::OPT_MD)) ||
  274. (A = Args.getLastArg(options::OPT_MMD))) {
  275. // Determine the output location.
  276. const char *DepFile;
  277. if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
  278. DepFile = MF->getValue();
  279. C.addFailureResultFile(DepFile, &JA);
  280. } else if (Output.getType() == types::TY_Dependencies) {
  281. DepFile = Output.getFilename();
  282. } else if (A->getOption().matches(options::OPT_M) ||
  283. A->getOption().matches(options::OPT_MM)) {
  284. DepFile = "-";
  285. } else {
  286. DepFile = getDependencyFileName(Args, Inputs);
  287. C.addFailureResultFile(DepFile, &JA);
  288. }
  289. CmdArgs.push_back("-dependency-file");
  290. CmdArgs.push_back(DepFile);
  291. // Add a default target if one wasn't specified.
  292. if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
  293. const char *DepTarget;
  294. // If user provided -o, that is the dependency target, except
  295. // when we are only generating a dependency file.
  296. Arg *OutputOpt = Args.getLastArg(options::OPT_o);
  297. if (OutputOpt && Output.getType() != types::TY_Dependencies) {
  298. DepTarget = OutputOpt->getValue();
  299. } else {
  300. // Otherwise derive from the base input.
  301. //
  302. // FIXME: This should use the computed output file location.
  303. SmallString<128> P(Inputs[0].getBaseInput());
  304. llvm::sys::path::replace_extension(P, "o");
  305. DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
  306. }
  307. CmdArgs.push_back("-MT");
  308. SmallString<128> Quoted;
  309. QuoteTarget(DepTarget, Quoted);
  310. CmdArgs.push_back(Args.MakeArgString(Quoted));
  311. }
  312. if (A->getOption().matches(options::OPT_M) ||
  313. A->getOption().matches(options::OPT_MD))
  314. CmdArgs.push_back("-sys-header-deps");
  315. if ((isa<PrecompileJobAction>(JA) &&
  316. !Args.hasArg(options::OPT_fno_module_file_deps)) ||
  317. Args.hasArg(options::OPT_fmodule_file_deps))
  318. CmdArgs.push_back("-module-file-deps");
  319. }
  320. if (Args.hasArg(options::OPT_MG)) {
  321. if (!A || A->getOption().matches(options::OPT_MD) ||
  322. A->getOption().matches(options::OPT_MMD))
  323. D.Diag(diag::err_drv_mg_requires_m_or_mm);
  324. CmdArgs.push_back("-MG");
  325. }
  326. Args.AddLastArg(CmdArgs, options::OPT_MP);
  327. Args.AddLastArg(CmdArgs, options::OPT_MV);
  328. // Convert all -MQ <target> args to -MT <quoted target>
  329. for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
  330. A->claim();
  331. if (A->getOption().matches(options::OPT_MQ)) {
  332. CmdArgs.push_back("-MT");
  333. SmallString<128> Quoted;
  334. QuoteTarget(A->getValue(), Quoted);
  335. CmdArgs.push_back(Args.MakeArgString(Quoted));
  336. // -MT flag - no change
  337. } else {
  338. A->render(Args, CmdArgs);
  339. }
  340. }
  341. // Add -i* options, and automatically translate to
  342. // -include-pch/-include-pth for transparent PCH support. It's
  343. // wonky, but we include looking for .gch so we can support seamless
  344. // replacement into a build system already set up to be generating
  345. // .gch files.
  346. int YcIndex = -1, YuIndex = -1;
  347. {
  348. int AI = -1;
  349. const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  350. const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  351. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  352. // Walk the whole i_Group and skip non "-include" flags so that the index
  353. // here matches the index in the next loop below.
  354. ++AI;
  355. if (!A->getOption().matches(options::OPT_include))
  356. continue;
  357. if (YcArg && strcmp(A->getValue(), YcArg->getValue()) == 0)
  358. YcIndex = AI;
  359. if (YuArg && strcmp(A->getValue(), YuArg->getValue()) == 0)
  360. YuIndex = AI;
  361. }
  362. }
  363. if (isa<PrecompileJobAction>(JA) && YcIndex != -1) {
  364. Driver::InputList Inputs;
  365. D.BuildInputs(getToolChain(), C.getArgs(), Inputs);
  366. assert(Inputs.size() == 1 && "Need one input when building pch");
  367. CmdArgs.push_back(Args.MakeArgString(Twine("-find-pch-source=") +
  368. Inputs[0].second->getValue()));
  369. }
  370. bool RenderedImplicitInclude = false;
  371. int AI = -1;
  372. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  373. ++AI;
  374. if (getToolChain().getDriver().IsCLMode() &&
  375. A->getOption().matches(options::OPT_include)) {
  376. // In clang-cl mode, /Ycfoo.h means that all code up to a foo.h
  377. // include is compiled into foo.h, and everything after goes into
  378. // the .obj file. /Yufoo.h means that all includes prior to and including
  379. // foo.h are completely skipped and replaced with a use of the pch file
  380. // for foo.h. (Each flag can have at most one value, multiple /Yc flags
  381. // just mean that the last one wins.) If /Yc and /Yu are both present
  382. // and refer to the same file, /Yc wins.
  383. // Note that OPT__SLASH_FI gets mapped to OPT_include.
  384. // FIXME: The code here assumes that /Yc and /Yu refer to the same file.
  385. // cl.exe seems to support both flags with different values, but that
  386. // seems strange (which flag does /Fp now refer to?), so don't implement
  387. // that until someone needs it.
  388. int PchIndex = YcIndex != -1 ? YcIndex : YuIndex;
  389. if (PchIndex != -1) {
  390. if (isa<PrecompileJobAction>(JA)) {
  391. // When building the pch, skip all includes after the pch.
  392. assert(YcIndex != -1 && PchIndex == YcIndex);
  393. if (AI >= YcIndex)
  394. continue;
  395. } else {
  396. // When using the pch, skip all includes prior to the pch.
  397. if (AI < PchIndex) {
  398. A->claim();
  399. continue;
  400. }
  401. if (AI == PchIndex) {
  402. A->claim();
  403. CmdArgs.push_back("-include-pch");
  404. CmdArgs.push_back(
  405. Args.MakeArgString(D.GetClPchPath(C, A->getValue())));
  406. continue;
  407. }
  408. }
  409. }
  410. } else if (A->getOption().matches(options::OPT_include)) {
  411. // Handling of gcc-style gch precompiled headers.
  412. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  413. RenderedImplicitInclude = true;
  414. // Use PCH if the user requested it.
  415. bool UsePCH = D.CCCUsePCH;
  416. bool FoundPTH = false;
  417. bool FoundPCH = false;
  418. SmallString<128> P(A->getValue());
  419. // We want the files to have a name like foo.h.pch. Add a dummy extension
  420. // so that replace_extension does the right thing.
  421. P += ".dummy";
  422. if (UsePCH) {
  423. llvm::sys::path::replace_extension(P, "pch");
  424. if (llvm::sys::fs::exists(P))
  425. FoundPCH = true;
  426. }
  427. if (!FoundPCH) {
  428. llvm::sys::path::replace_extension(P, "pth");
  429. if (llvm::sys::fs::exists(P))
  430. FoundPTH = true;
  431. }
  432. if (!FoundPCH && !FoundPTH) {
  433. llvm::sys::path::replace_extension(P, "gch");
  434. if (llvm::sys::fs::exists(P)) {
  435. FoundPCH = UsePCH;
  436. FoundPTH = !UsePCH;
  437. }
  438. }
  439. if (FoundPCH || FoundPTH) {
  440. if (IsFirstImplicitInclude) {
  441. A->claim();
  442. if (UsePCH)
  443. CmdArgs.push_back("-include-pch");
  444. else
  445. CmdArgs.push_back("-include-pth");
  446. CmdArgs.push_back(Args.MakeArgString(P));
  447. continue;
  448. } else {
  449. // Ignore the PCH if not first on command line and emit warning.
  450. D.Diag(diag::warn_drv_pch_not_first_include) << P
  451. << A->getAsString(Args);
  452. }
  453. }
  454. }
  455. // Not translated, render as usual.
  456. A->claim();
  457. A->render(Args, CmdArgs);
  458. }
  459. Args.AddAllArgs(CmdArgs,
  460. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  461. options::OPT_F, options::OPT_index_header_map});
  462. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  463. // FIXME: There is a very unfortunate problem here, some troubled
  464. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  465. // really support that we would have to parse and then translate
  466. // those options. :(
  467. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  468. options::OPT_Xpreprocessor);
  469. // -I- is a deprecated GCC feature, reject it.
  470. if (Arg *A = Args.getLastArg(options::OPT_I_))
  471. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  472. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  473. // -isysroot to the CC1 invocation.
  474. StringRef sysroot = C.getSysRoot();
  475. if (sysroot != "") {
  476. if (!Args.hasArg(options::OPT_isysroot)) {
  477. CmdArgs.push_back("-isysroot");
  478. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  479. }
  480. }
  481. // Parse additional include paths from environment variables.
  482. // FIXME: We should probably sink the logic for handling these from the
  483. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  484. // CPATH - included following the user specified includes (but prior to
  485. // builtin and standard includes).
  486. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  487. // C_INCLUDE_PATH - system includes enabled when compiling C.
  488. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  489. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  490. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  491. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  492. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  493. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  494. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  495. // Optional AuxToolChain indicates that we need to include headers
  496. // for more than one target. If that's the case, add include paths
  497. // from AuxToolChain right after include paths of the same kind for
  498. // the current target.
  499. // Add C++ include arguments, if needed.
  500. if (types::isCXX(Inputs[0].getType())) {
  501. getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  502. if (AuxToolChain)
  503. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  504. }
  505. // Add system include arguments.
  506. getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
  507. if (AuxToolChain)
  508. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  509. // Add CUDA include arguments, if needed.
  510. if (types::isCuda(Inputs[0].getType()))
  511. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  512. }
  513. // FIXME: Move to target hook.
  514. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  515. switch (Triple.getArch()) {
  516. default:
  517. return true;
  518. case llvm::Triple::aarch64:
  519. case llvm::Triple::aarch64_be:
  520. case llvm::Triple::arm:
  521. case llvm::Triple::armeb:
  522. case llvm::Triple::thumb:
  523. case llvm::Triple::thumbeb:
  524. if (Triple.isOSDarwin() || Triple.isOSWindows())
  525. return true;
  526. return false;
  527. case llvm::Triple::ppc:
  528. case llvm::Triple::ppc64:
  529. if (Triple.isOSDarwin())
  530. return true;
  531. return false;
  532. case llvm::Triple::hexagon:
  533. case llvm::Triple::ppc64le:
  534. case llvm::Triple::systemz:
  535. case llvm::Triple::xcore:
  536. return false;
  537. }
  538. }
  539. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  540. switch (Triple.getArch()) {
  541. default:
  542. return false;
  543. case llvm::Triple::xcore:
  544. case llvm::Triple::wasm32:
  545. case llvm::Triple::wasm64:
  546. return true;
  547. }
  548. }
  549. // ARM tools start.
  550. // Get SubArch (vN).
  551. static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  552. llvm::StringRef Arch = Triple.getArchName();
  553. return llvm::ARM::parseArchVersion(Arch);
  554. }
  555. // True if M-profile.
  556. static bool isARMMProfile(const llvm::Triple &Triple) {
  557. llvm::StringRef Arch = Triple.getArchName();
  558. unsigned Profile = llvm::ARM::parseArchProfile(Arch);
  559. return Profile == llvm::ARM::PK_M;
  560. }
  561. // Get Arch/CPU from args.
  562. static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
  563. llvm::StringRef &CPU, bool FromAs = false) {
  564. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  565. CPU = A->getValue();
  566. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  567. Arch = A->getValue();
  568. if (!FromAs)
  569. return;
  570. for (const Arg *A :
  571. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  572. StringRef Value = A->getValue();
  573. if (Value.startswith("-mcpu="))
  574. CPU = Value.substr(6);
  575. if (Value.startswith("-march="))
  576. Arch = Value.substr(7);
  577. }
  578. }
  579. // Handle -mhwdiv=.
  580. // FIXME: Use ARMTargetParser.
  581. static void getARMHWDivFeatures(const Driver &D, const Arg *A,
  582. const ArgList &Args, StringRef HWDiv,
  583. std::vector<const char *> &Features) {
  584. unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  585. if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
  586. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  587. }
  588. // Handle -mfpu=.
  589. static void getARMFPUFeatures(const Driver &D, const Arg *A,
  590. const ArgList &Args, StringRef FPU,
  591. std::vector<const char *> &Features) {
  592. unsigned FPUID = llvm::ARM::parseFPU(FPU);
  593. if (!llvm::ARM::getFPUFeatures(FPUID, Features))
  594. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  595. }
  596. // Decode ARM features from string like +[no]featureA+[no]featureB+...
  597. static bool DecodeARMFeatures(const Driver &D, StringRef text,
  598. std::vector<const char *> &Features) {
  599. SmallVector<StringRef, 8> Split;
  600. text.split(Split, StringRef("+"), -1, false);
  601. for (StringRef Feature : Split) {
  602. const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
  603. if (FeatureName)
  604. Features.push_back(FeatureName);
  605. else
  606. return false;
  607. }
  608. return true;
  609. }
  610. // Check if -march is valid by checking if it can be canonicalised and parsed.
  611. // getARMArch is used here instead of just checking the -march value in order
  612. // to handle -march=native correctly.
  613. static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
  614. llvm::StringRef ArchName,
  615. std::vector<const char *> &Features,
  616. const llvm::Triple &Triple) {
  617. std::pair<StringRef, StringRef> Split = ArchName.split("+");
  618. std::string MArch = arm::getARMArch(ArchName, Triple);
  619. if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
  620. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  621. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  622. }
  623. // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
  624. static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
  625. llvm::StringRef CPUName, llvm::StringRef ArchName,
  626. std::vector<const char *> &Features,
  627. const llvm::Triple &Triple) {
  628. std::pair<StringRef, StringRef> Split = CPUName.split("+");
  629. std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  630. if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
  631. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  632. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  633. }
  634. static bool useAAPCSForMachO(const llvm::Triple &T) {
  635. // The backend is hardwired to assume AAPCS for M-class processors, ensure
  636. // the frontend matches that.
  637. return T.getEnvironment() == llvm::Triple::EABI ||
  638. T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
  639. }
  640. // Select the float ABI as determined by -msoft-float, -mhard-float, and
  641. // -mfloat-abi=.
  642. arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  643. const Driver &D = TC.getDriver();
  644. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
  645. auto SubArch = getARMSubArchVersionNumber(Triple);
  646. arm::FloatABI ABI = FloatABI::Invalid;
  647. if (Arg *A =
  648. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  649. options::OPT_mfloat_abi_EQ)) {
  650. if (A->getOption().matches(options::OPT_msoft_float)) {
  651. ABI = FloatABI::Soft;
  652. } else if (A->getOption().matches(options::OPT_mhard_float)) {
  653. ABI = FloatABI::Hard;
  654. } else {
  655. ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
  656. .Case("soft", FloatABI::Soft)
  657. .Case("softfp", FloatABI::SoftFP)
  658. .Case("hard", FloatABI::Hard)
  659. .Default(FloatABI::Invalid);
  660. if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  661. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  662. ABI = FloatABI::Soft;
  663. }
  664. }
  665. // It is incorrect to select hard float ABI on MachO platforms if the ABI is
  666. // "apcs-gnu".
  667. if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
  668. ABI == FloatABI::Hard) {
  669. D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
  670. << Triple.getArchName();
  671. }
  672. }
  673. // If unspecified, choose the default based on the platform.
  674. if (ABI == FloatABI::Invalid) {
  675. switch (Triple.getOS()) {
  676. case llvm::Triple::Darwin:
  677. case llvm::Triple::MacOSX:
  678. case llvm::Triple::IOS:
  679. case llvm::Triple::TvOS: {
  680. // Darwin defaults to "softfp" for v6 and v7.
  681. ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  682. ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
  683. break;
  684. }
  685. case llvm::Triple::WatchOS:
  686. ABI = FloatABI::Hard;
  687. break;
  688. // FIXME: this is invalid for WindowsCE
  689. case llvm::Triple::Win32:
  690. ABI = FloatABI::Hard;
  691. break;
  692. case llvm::Triple::FreeBSD:
  693. switch (Triple.getEnvironment()) {
  694. case llvm::Triple::GNUEABIHF:
  695. ABI = FloatABI::Hard;
  696. break;
  697. default:
  698. // FreeBSD defaults to soft float
  699. ABI = FloatABI::Soft;
  700. break;
  701. }
  702. break;
  703. default:
  704. switch (Triple.getEnvironment()) {
  705. case llvm::Triple::GNUEABIHF:
  706. case llvm::Triple::EABIHF:
  707. ABI = FloatABI::Hard;
  708. break;
  709. case llvm::Triple::GNUEABI:
  710. case llvm::Triple::EABI:
  711. // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
  712. ABI = FloatABI::SoftFP;
  713. break;
  714. case llvm::Triple::Android:
  715. ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  716. break;
  717. default:
  718. // Assume "soft", but warn the user we are guessing.
  719. if (Triple.isOSBinFormatMachO() &&
  720. Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
  721. ABI = FloatABI::Hard;
  722. else
  723. ABI = FloatABI::Soft;
  724. if (Triple.getOS() != llvm::Triple::UnknownOS ||
  725. !Triple.isOSBinFormatMachO())
  726. D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
  727. break;
  728. }
  729. }
  730. }
  731. assert(ABI != FloatABI::Invalid && "must select an ABI");
  732. return ABI;
  733. }
  734. static void getARMTargetFeatures(const ToolChain &TC,
  735. const llvm::Triple &Triple,
  736. const ArgList &Args,
  737. std::vector<const char *> &Features,
  738. bool ForAS) {
  739. const Driver &D = TC.getDriver();
  740. bool KernelOrKext =
  741. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  742. arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
  743. const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  744. const Arg *WaHDiv = nullptr, *WaArch = nullptr;
  745. if (!ForAS) {
  746. // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
  747. // yet (it uses the -mfloat-abi and -msoft-float options), and it is
  748. // stripped out by the ARM target. We should probably pass this a new
  749. // -target-option, which is handled by the -cc1/-cc1as invocation.
  750. //
  751. // FIXME2: For consistency, it would be ideal if we set up the target
  752. // machine state the same when using the frontend or the assembler. We don't
  753. // currently do that for the assembler, we pass the options directly to the
  754. // backend and never even instantiate the frontend TargetInfo. If we did,
  755. // and used its handleTargetFeatures hook, then we could ensure the
  756. // assembler and the frontend behave the same.
  757. // Use software floating point operations?
  758. if (ABI == arm::FloatABI::Soft)
  759. Features.push_back("+soft-float");
  760. // Use software floating point argument passing?
  761. if (ABI != arm::FloatABI::Hard)
  762. Features.push_back("+soft-float-abi");
  763. } else {
  764. // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
  765. // to the assembler correctly.
  766. for (const Arg *A :
  767. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  768. StringRef Value = A->getValue();
  769. if (Value.startswith("-mfpu=")) {
  770. WaFPU = A;
  771. } else if (Value.startswith("-mcpu=")) {
  772. WaCPU = A;
  773. } else if (Value.startswith("-mhwdiv=")) {
  774. WaHDiv = A;
  775. } else if (Value.startswith("-march=")) {
  776. WaArch = A;
  777. }
  778. }
  779. }
  780. // Check -march. ClangAs gives preference to -Wa,-march=.
  781. const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  782. StringRef ArchName;
  783. if (WaArch) {
  784. if (ArchArg)
  785. D.Diag(clang::diag::warn_drv_unused_argument)
  786. << ArchArg->getAsString(Args);
  787. ArchName = StringRef(WaArch->getValue()).substr(7);
  788. checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
  789. // FIXME: Set Arch.
  790. D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  791. } else if (ArchArg) {
  792. ArchName = ArchArg->getValue();
  793. checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
  794. }
  795. // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  796. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  797. StringRef CPUName;
  798. if (WaCPU) {
  799. if (CPUArg)
  800. D.Diag(clang::diag::warn_drv_unused_argument)
  801. << CPUArg->getAsString(Args);
  802. CPUName = StringRef(WaCPU->getValue()).substr(6);
  803. checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
  804. } else if (CPUArg) {
  805. CPUName = CPUArg->getValue();
  806. checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
  807. }
  808. // Add CPU features for generic CPUs
  809. if (CPUName == "native") {
  810. llvm::StringMap<bool> HostFeatures;
  811. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  812. for (auto &F : HostFeatures)
  813. Features.push_back(
  814. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  815. }
  816. // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  817. const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  818. if (WaFPU) {
  819. if (FPUArg)
  820. D.Diag(clang::diag::warn_drv_unused_argument)
  821. << FPUArg->getAsString(Args);
  822. getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
  823. Features);
  824. } else if (FPUArg) {
  825. getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  826. }
  827. // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  828. const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  829. if (WaHDiv) {
  830. if (HDivArg)
  831. D.Diag(clang::diag::warn_drv_unused_argument)
  832. << HDivArg->getAsString(Args);
  833. getARMHWDivFeatures(D, WaHDiv, Args,
  834. StringRef(WaHDiv->getValue()).substr(8), Features);
  835. } else if (HDivArg)
  836. getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
  837. // Setting -msoft-float effectively disables NEON because of the GCC
  838. // implementation, although the same isn't true of VFP or VFP3.
  839. if (ABI == arm::FloatABI::Soft) {
  840. Features.push_back("-neon");
  841. // Also need to explicitly disable features which imply NEON.
  842. Features.push_back("-crypto");
  843. }
  844. // En/disable crc code generation.
  845. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  846. if (A->getOption().matches(options::OPT_mcrc))
  847. Features.push_back("+crc");
  848. else
  849. Features.push_back("-crc");
  850. }
  851. // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  852. // neither options are specified, see if we are compiling for kernel/kext and
  853. // decide whether to pass "+long-calls" based on the OS and its version.
  854. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  855. options::OPT_mno_long_calls)) {
  856. if (A->getOption().matches(options::OPT_mlong_calls))
  857. Features.push_back("+long-calls");
  858. } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  859. !Triple.isWatchOS()) {
  860. Features.push_back("+long-calls");
  861. }
  862. // Kernel code has more strict alignment requirements.
  863. if (KernelOrKext)
  864. Features.push_back("+strict-align");
  865. else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  866. options::OPT_munaligned_access)) {
  867. if (A->getOption().matches(options::OPT_munaligned_access)) {
  868. // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
  869. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  870. D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
  871. // v8M Baseline follows on from v6M, so doesn't support unaligned memory
  872. // access either.
  873. else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
  874. D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
  875. } else
  876. Features.push_back("+strict-align");
  877. } else {
  878. // Assume pre-ARMv6 doesn't support unaligned accesses.
  879. //
  880. // ARMv6 may or may not support unaligned accesses depending on the
  881. // SCTLR.U bit, which is architecture-specific. We assume ARMv6
  882. // Darwin and NetBSD targets support unaligned accesses, and others don't.
  883. //
  884. // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
  885. // which raises an alignment fault on unaligned accesses. Linux
  886. // defaults this bit to 0 and handles it as a system-wide (not
  887. // per-process) setting. It is therefore safe to assume that ARMv7+
  888. // Linux targets support unaligned accesses. The same goes for NaCl.
  889. //
  890. // The above behavior is consistent with GCC.
  891. int VersionNum = getARMSubArchVersionNumber(Triple);
  892. if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  893. if (VersionNum < 6 ||
  894. Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  895. Features.push_back("+strict-align");
  896. } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
  897. if (VersionNum < 7)
  898. Features.push_back("+strict-align");
  899. } else
  900. Features.push_back("+strict-align");
  901. }
  902. // llvm does not support reserving registers in general. There is support
  903. // for reserving r9 on ARM though (defined as a platform-specific register
  904. // in ARM EABI).
  905. if (Args.hasArg(options::OPT_ffixed_r9))
  906. Features.push_back("+reserve-r9");
  907. // The kext linker doesn't know how to deal with movw/movt.
  908. if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
  909. Features.push_back("+no-movt");
  910. }
  911. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  912. ArgStringList &CmdArgs, bool KernelOrKext) const {
  913. // Select the ABI to use.
  914. // FIXME: Support -meabi.
  915. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  916. const char *ABIName = nullptr;
  917. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  918. ABIName = A->getValue();
  919. } else if (Triple.isOSBinFormatMachO()) {
  920. if (useAAPCSForMachO(Triple)) {
  921. ABIName = "aapcs";
  922. } else if (Triple.isWatchABI()) {
  923. ABIName = "aapcs16";
  924. } else {
  925. ABIName = "apcs-gnu";
  926. }
  927. } else if (Triple.isOSWindows()) {
  928. // FIXME: this is invalid for WindowsCE
  929. ABIName = "aapcs";
  930. } else {
  931. // Select the default based on the platform.
  932. switch (Triple.getEnvironment()) {
  933. case llvm::Triple::Android:
  934. case llvm::Triple::GNUEABI:
  935. case llvm::Triple::GNUEABIHF:
  936. ABIName = "aapcs-linux";
  937. break;
  938. case llvm::Triple::EABIHF:
  939. case llvm::Triple::EABI:
  940. ABIName = "aapcs";
  941. break;
  942. default:
  943. if (Triple.getOS() == llvm::Triple::NetBSD)
  944. ABIName = "apcs-gnu";
  945. else
  946. ABIName = "aapcs";
  947. break;
  948. }
  949. }
  950. CmdArgs.push_back("-target-abi");
  951. CmdArgs.push_back(ABIName);
  952. // Determine floating point ABI from the options & target defaults.
  953. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  954. if (ABI == arm::FloatABI::Soft) {
  955. // Floating point operations and argument passing are soft.
  956. // FIXME: This changes CPP defines, we need -target-soft-float.
  957. CmdArgs.push_back("-msoft-float");
  958. CmdArgs.push_back("-mfloat-abi");
  959. CmdArgs.push_back("soft");
  960. } else if (ABI == arm::FloatABI::SoftFP) {
  961. // Floating point operations are hard, but argument passing is soft.
  962. CmdArgs.push_back("-mfloat-abi");
  963. CmdArgs.push_back("soft");
  964. } else {
  965. // Floating point operations and argument passing are hard.
  966. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  967. CmdArgs.push_back("-mfloat-abi");
  968. CmdArgs.push_back("hard");
  969. }
  970. // Forward the -mglobal-merge option for explicit control over the pass.
  971. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  972. options::OPT_mno_global_merge)) {
  973. CmdArgs.push_back("-backend-option");
  974. if (A->getOption().matches(options::OPT_mno_global_merge))
  975. CmdArgs.push_back("-arm-global-merge=false");
  976. else
  977. CmdArgs.push_back("-arm-global-merge=true");
  978. }
  979. if (!Args.hasFlag(options::OPT_mimplicit_float,
  980. options::OPT_mno_implicit_float, true))
  981. CmdArgs.push_back("-no-implicit-float");
  982. }
  983. // ARM tools end.
  984. /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
  985. /// targeting.
  986. static std::string getAArch64TargetCPU(const ArgList &Args) {
  987. Arg *A;
  988. std::string CPU;
  989. // If we have -mtune or -mcpu, use that.
  990. if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
  991. CPU = StringRef(A->getValue()).lower();
  992. } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
  993. StringRef Mcpu = A->getValue();
  994. CPU = Mcpu.split("+").first.lower();
  995. }
  996. // Handle CPU name is 'native'.
  997. if (CPU == "native")
  998. return llvm::sys::getHostCPUName();
  999. else if (CPU.size())
  1000. return CPU;
  1001. // Make sure we pick "cyclone" if -arch is used.
  1002. // FIXME: Should this be picked by checking the target triple instead?
  1003. if (Args.getLastArg(options::OPT_arch))
  1004. return "cyclone";
  1005. return "generic";
  1006. }
  1007. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  1008. ArgStringList &CmdArgs) const {
  1009. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  1010. llvm::Triple Triple(TripleStr);
  1011. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1012. Args.hasArg(options::OPT_mkernel) ||
  1013. Args.hasArg(options::OPT_fapple_kext))
  1014. CmdArgs.push_back("-disable-red-zone");
  1015. if (!Args.hasFlag(options::OPT_mimplicit_float,
  1016. options::OPT_mno_implicit_float, true))
  1017. CmdArgs.push_back("-no-implicit-float");
  1018. const char *ABIName = nullptr;
  1019. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1020. ABIName = A->getValue();
  1021. else if (Triple.isOSDarwin())
  1022. ABIName = "darwinpcs";
  1023. else
  1024. ABIName = "aapcs";
  1025. CmdArgs.push_back("-target-abi");
  1026. CmdArgs.push_back(ABIName);
  1027. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  1028. options::OPT_mno_fix_cortex_a53_835769)) {
  1029. CmdArgs.push_back("-backend-option");
  1030. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  1031. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1032. else
  1033. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  1034. } else if (Triple.isAndroid()) {
  1035. // Enabled A53 errata (835769) workaround by default on android
  1036. CmdArgs.push_back("-backend-option");
  1037. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  1038. }
  1039. // Forward the -mglobal-merge option for explicit control over the pass.
  1040. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  1041. options::OPT_mno_global_merge)) {
  1042. CmdArgs.push_back("-backend-option");
  1043. if (A->getOption().matches(options::OPT_mno_global_merge))
  1044. CmdArgs.push_back("-aarch64-global-merge=false");
  1045. else
  1046. CmdArgs.push_back("-aarch64-global-merge=true");
  1047. }
  1048. }
  1049. // Get CPU and ABI names. They are not independent
  1050. // so we have to calculate them together.
  1051. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
  1052. StringRef &CPUName, StringRef &ABIName) {
  1053. const char *DefMips32CPU = "mips32r2";
  1054. const char *DefMips64CPU = "mips64r2";
  1055. // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
  1056. // default for mips64(el)?-img-linux-gnu.
  1057. if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  1058. Triple.getEnvironment() == llvm::Triple::GNU) {
  1059. DefMips32CPU = "mips32r6";
  1060. DefMips64CPU = "mips64r6";
  1061. }
  1062. // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
  1063. if (Triple.isAndroid())
  1064. DefMips64CPU = "mips64r6";
  1065. // MIPS3 is the default for mips64*-unknown-openbsd.
  1066. if (Triple.getOS() == llvm::Triple::OpenBSD)
  1067. DefMips64CPU = "mips3";
  1068. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  1069. CPUName = A->getValue();
  1070. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1071. ABIName = A->getValue();
  1072. // Convert a GNU style Mips ABI name to the name
  1073. // accepted by LLVM Mips backend.
  1074. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  1075. .Case("32", "o32")
  1076. .Case("64", "n64")
  1077. .Default(ABIName);
  1078. }
  1079. // Setup default CPU and ABI names.
  1080. if (CPUName.empty() && ABIName.empty()) {
  1081. switch (Triple.getArch()) {
  1082. default:
  1083. llvm_unreachable("Unexpected triple arch name");
  1084. case llvm::Triple::mips:
  1085. case llvm::Triple::mipsel:
  1086. CPUName = DefMips32CPU;
  1087. break;
  1088. case llvm::Triple::mips64:
  1089. case llvm::Triple::mips64el:
  1090. CPUName = DefMips64CPU;
  1091. break;
  1092. }
  1093. }
  1094. if (ABIName.empty()) {
  1095. // Deduce ABI name from the target triple.
  1096. if (Triple.getArch() == llvm::Triple::mips ||
  1097. Triple.getArch() == llvm::Triple::mipsel)
  1098. ABIName = "o32";
  1099. else
  1100. ABIName = "n64";
  1101. }
  1102. if (CPUName.empty()) {
  1103. // Deduce CPU name from ABI name.
  1104. CPUName = llvm::StringSwitch<const char *>(ABIName)
  1105. .Cases("o32", "eabi", DefMips32CPU)
  1106. .Cases("n32", "n64", DefMips64CPU)
  1107. .Default("");
  1108. }
  1109. // FIXME: Warn on inconsistent use of -march and -mabi.
  1110. }
  1111. std::string mips::getMipsABILibSuffix(const ArgList &Args,
  1112. const llvm::Triple &Triple) {
  1113. StringRef CPUName, ABIName;
  1114. tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1115. return llvm::StringSwitch<std::string>(ABIName)
  1116. .Case("o32", "")
  1117. .Case("n32", "32")
  1118. .Case("n64", "64");
  1119. }
  1120. // Convert ABI name to the GNU tools acceptable variant.
  1121. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  1122. return llvm::StringSwitch<llvm::StringRef>(ABI)
  1123. .Case("o32", "32")
  1124. .Case("n64", "64")
  1125. .Default(ABI);
  1126. }
  1127. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  1128. // and -mfloat-abi=.
  1129. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  1130. mips::FloatABI ABI = mips::FloatABI::Invalid;
  1131. if (Arg *A =
  1132. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1133. options::OPT_mfloat_abi_EQ)) {
  1134. if (A->getOption().matches(options::OPT_msoft_float))
  1135. ABI = mips::FloatABI::Soft;
  1136. else if (A->getOption().matches(options::OPT_mhard_float))
  1137. ABI = mips::FloatABI::Hard;
  1138. else {
  1139. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  1140. .Case("soft", mips::FloatABI::Soft)
  1141. .Case("hard", mips::FloatABI::Hard)
  1142. .Default(mips::FloatABI::Invalid);
  1143. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1144. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1145. ABI = mips::FloatABI::Hard;
  1146. }
  1147. }
  1148. }
  1149. // If unspecified, choose the default based on the platform.
  1150. if (ABI == mips::FloatABI::Invalid) {
  1151. // Assume "hard", because it's a default value used by gcc.
  1152. // When we start to recognize specific target MIPS processors,
  1153. // we will be able to select the default more correctly.
  1154. ABI = mips::FloatABI::Hard;
  1155. }
  1156. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  1157. return ABI;
  1158. }
  1159. static void AddTargetFeature(const ArgList &Args,
  1160. std::vector<const char *> &Features,
  1161. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1162. StringRef FeatureName) {
  1163. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1164. if (A->getOption().matches(OnOpt))
  1165. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1166. else
  1167. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1168. }
  1169. }
  1170. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1171. const ArgList &Args,
  1172. std::vector<const char *> &Features) {
  1173. StringRef CPUName;
  1174. StringRef ABIName;
  1175. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1176. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1177. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1178. options::OPT_mabicalls, "noabicalls");
  1179. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1180. if (FloatABI == mips::FloatABI::Soft) {
  1181. // FIXME: Note, this is a hack. We need to pass the selected float
  1182. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1183. // Now it is the only method.
  1184. Features.push_back("+soft-float");
  1185. }
  1186. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1187. StringRef Val = StringRef(A->getValue());
  1188. if (Val == "2008") {
  1189. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1190. Features.push_back("+nan2008");
  1191. else {
  1192. Features.push_back("-nan2008");
  1193. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1194. }
  1195. } else if (Val == "legacy") {
  1196. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1197. Features.push_back("-nan2008");
  1198. else {
  1199. Features.push_back("+nan2008");
  1200. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1201. }
  1202. } else
  1203. D.Diag(diag::err_drv_unsupported_option_argument)
  1204. << A->getOption().getName() << Val;
  1205. }
  1206. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1207. options::OPT_mdouble_float, "single-float");
  1208. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1209. "mips16");
  1210. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1211. options::OPT_mno_micromips, "micromips");
  1212. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1213. "dsp");
  1214. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1215. "dspr2");
  1216. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1217. "msa");
  1218. // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
  1219. // pass -mfpxx
  1220. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1221. options::OPT_mfp64)) {
  1222. if (A->getOption().matches(options::OPT_mfp32))
  1223. Features.push_back(Args.MakeArgString("-fp64"));
  1224. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1225. Features.push_back(Args.MakeArgString("+fpxx"));
  1226. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1227. } else
  1228. Features.push_back(Args.MakeArgString("+fp64"));
  1229. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1230. Features.push_back(Args.MakeArgString("+fpxx"));
  1231. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1232. }
  1233. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1234. options::OPT_modd_spreg, "nooddspreg");
  1235. }
  1236. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1237. ArgStringList &CmdArgs) const {
  1238. const Driver &D = getToolChain().getDriver();
  1239. StringRef CPUName;
  1240. StringRef ABIName;
  1241. const llvm::Triple &Triple = getToolChain().getTriple();
  1242. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1243. CmdArgs.push_back("-target-abi");
  1244. CmdArgs.push_back(ABIName.data());
  1245. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1246. if (ABI == mips::FloatABI::Soft) {
  1247. // Floating point operations and argument passing are soft.
  1248. CmdArgs.push_back("-msoft-float");
  1249. CmdArgs.push_back("-mfloat-abi");
  1250. CmdArgs.push_back("soft");
  1251. } else {
  1252. // Floating point operations and argument passing are hard.
  1253. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1254. CmdArgs.push_back("-mfloat-abi");
  1255. CmdArgs.push_back("hard");
  1256. }
  1257. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1258. if (A->getOption().matches(options::OPT_mxgot)) {
  1259. CmdArgs.push_back("-mllvm");
  1260. CmdArgs.push_back("-mxgot");
  1261. }
  1262. }
  1263. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1264. options::OPT_mno_ldc1_sdc1)) {
  1265. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1266. CmdArgs.push_back("-mllvm");
  1267. CmdArgs.push_back("-mno-ldc1-sdc1");
  1268. }
  1269. }
  1270. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1271. options::OPT_mno_check_zero_division)) {
  1272. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1273. CmdArgs.push_back("-mllvm");
  1274. CmdArgs.push_back("-mno-check-zero-division");
  1275. }
  1276. }
  1277. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1278. StringRef v = A->getValue();
  1279. CmdArgs.push_back("-mllvm");
  1280. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1281. A->claim();
  1282. }
  1283. }
  1284. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1285. static std::string getPPCTargetCPU(const ArgList &Args) {
  1286. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1287. StringRef CPUName = A->getValue();
  1288. if (CPUName == "native") {
  1289. std::string CPU = llvm::sys::getHostCPUName();
  1290. if (!CPU.empty() && CPU != "generic")
  1291. return CPU;
  1292. else
  1293. return "";
  1294. }
  1295. return llvm::StringSwitch<const char *>(CPUName)
  1296. .Case("common", "generic")
  1297. .Case("440", "440")
  1298. .Case("440fp", "440")
  1299. .Case("450", "450")
  1300. .Case("601", "601")
  1301. .Case("602", "602")
  1302. .Case("603", "603")
  1303. .Case("603e", "603e")
  1304. .Case("603ev", "603ev")
  1305. .Case("604", "604")
  1306. .Case("604e", "604e")
  1307. .Case("620", "620")
  1308. .Case("630", "pwr3")
  1309. .Case("G3", "g3")
  1310. .Case("7400", "7400")
  1311. .Case("G4", "g4")
  1312. .Case("7450", "7450")
  1313. .Case("G4+", "g4+")
  1314. .Case("750", "750")
  1315. .Case("970", "970")
  1316. .Case("G5", "g5")
  1317. .Case("a2", "a2")
  1318. .Case("a2q", "a2q")
  1319. .Case("e500mc", "e500mc")
  1320. .Case("e5500", "e5500")
  1321. .Case("power3", "pwr3")
  1322. .Case("power4", "pwr4")
  1323. .Case("power5", "pwr5")
  1324. .Case("power5x", "pwr5x")
  1325. .Case("power6", "pwr6")
  1326. .Case("power6x", "pwr6x")
  1327. .Case("power7", "pwr7")
  1328. .Case("power8", "pwr8")
  1329. .Case("power9", "pwr9")
  1330. .Case("pwr3", "pwr3")
  1331. .Case("pwr4", "pwr4")
  1332. .Case("pwr5", "pwr5")
  1333. .Case("pwr5x", "pwr5x")
  1334. .Case("pwr6", "pwr6")
  1335. .Case("pwr6x", "pwr6x")
  1336. .Case("pwr7", "pwr7")
  1337. .Case("pwr8", "pwr8")
  1338. .Case("pwr9", "pwr9")
  1339. .Case("powerpc", "ppc")
  1340. .Case("powerpc64", "ppc64")
  1341. .Case("powerpc64le", "ppc64le")
  1342. .Default("");
  1343. }
  1344. return "";
  1345. }
  1346. static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1347. const ArgList &Args,
  1348. std::vector<const char *> &Features) {
  1349. handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
  1350. ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
  1351. if (FloatABI == ppc::FloatABI::Soft &&
  1352. !(Triple.getArch() == llvm::Triple::ppc64 ||
  1353. Triple.getArch() == llvm::Triple::ppc64le))
  1354. Features.push_back("+soft-float");
  1355. else if (FloatABI == ppc::FloatABI::Soft &&
  1356. (Triple.getArch() == llvm::Triple::ppc64 ||
  1357. Triple.getArch() == llvm::Triple::ppc64le))
  1358. D.Diag(diag::err_drv_invalid_mfloat_abi)
  1359. << "soft float is not supported for ppc64";
  1360. // Altivec is a bit weird, allow overriding of the Altivec feature here.
  1361. AddTargetFeature(Args, Features, options::OPT_faltivec,
  1362. options::OPT_fno_altivec, "altivec");
  1363. }
  1364. ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
  1365. ppc::FloatABI ABI = ppc::FloatABI::Invalid;
  1366. if (Arg *A =
  1367. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1368. options::OPT_mfloat_abi_EQ)) {
  1369. if (A->getOption().matches(options::OPT_msoft_float))
  1370. ABI = ppc::FloatABI::Soft;
  1371. else if (A->getOption().matches(options::OPT_mhard_float))
  1372. ABI = ppc::FloatABI::Hard;
  1373. else {
  1374. ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
  1375. .Case("soft", ppc::FloatABI::Soft)
  1376. .Case("hard", ppc::FloatABI::Hard)
  1377. .Default(ppc::FloatABI::Invalid);
  1378. if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1379. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1380. ABI = ppc::FloatABI::Hard;
  1381. }
  1382. }
  1383. }
  1384. // If unspecified, choose the default based on the platform.
  1385. if (ABI == ppc::FloatABI::Invalid) {
  1386. ABI = ppc::FloatABI::Hard;
  1387. }
  1388. return ABI;
  1389. }
  1390. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1391. ArgStringList &CmdArgs) const {
  1392. // Select the ABI to use.
  1393. const char *ABIName = nullptr;
  1394. if (getToolChain().getTriple().isOSLinux())
  1395. switch (getToolChain().getArch()) {
  1396. case llvm::Triple::ppc64: {
  1397. // When targeting a processor that supports QPX, or if QPX is
  1398. // specifically enabled, default to using the ABI that supports QPX (so
  1399. // long as it is not specifically disabled).
  1400. bool HasQPX = false;
  1401. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1402. HasQPX = A->getValue() == StringRef("a2q");
  1403. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1404. if (HasQPX) {
  1405. ABIName = "elfv1-qpx";
  1406. break;
  1407. }
  1408. ABIName = "elfv1";
  1409. break;
  1410. }
  1411. case llvm::Triple::ppc64le:
  1412. ABIName = "elfv2";
  1413. break;
  1414. default:
  1415. break;
  1416. }
  1417. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1418. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1419. // the option if given as we don't have backend support for any targets
  1420. // that don't use the altivec abi.
  1421. if (StringRef(A->getValue()) != "altivec")
  1422. ABIName = A->getValue();
  1423. ppc::FloatABI FloatABI =
  1424. ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
  1425. if (FloatABI == ppc::FloatABI::Soft) {
  1426. // Floating point operations and argument passing are soft.
  1427. CmdArgs.push_back("-msoft-float");
  1428. CmdArgs.push_back("-mfloat-abi");
  1429. CmdArgs.push_back("soft");
  1430. } else {
  1431. // Floating point operations and argument passing are hard.
  1432. assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
  1433. CmdArgs.push_back("-mfloat-abi");
  1434. CmdArgs.push_back("hard");
  1435. }
  1436. if (ABIName) {
  1437. CmdArgs.push_back("-target-abi");
  1438. CmdArgs.push_back(ABIName);
  1439. }
  1440. }
  1441. bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  1442. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  1443. return A && (A->getValue() == StringRef(Value));
  1444. }
  1445. /// Get the (LLVM) name of the R600 gpu we are targeting.
  1446. static std::string getR600TargetGPU(const ArgList &Args) {
  1447. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1448. const char *GPUName = A->getValue();
  1449. return llvm::StringSwitch<const char *>(GPUName)
  1450. .Cases("rv630", "rv635", "r600")
  1451. .Cases("rv610", "rv620", "rs780", "rs880")
  1452. .Case("rv740", "rv770")
  1453. .Case("palm", "cedar")
  1454. .Cases("sumo", "sumo2", "sumo")
  1455. .Case("hemlock", "cypress")
  1456. .Case("aruba", "cayman")
  1457. .Default(GPUName);
  1458. }
  1459. return "";
  1460. }
  1461. static std::string getLanaiTargetCPU(const ArgList &Args) {
  1462. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1463. return A->getValue();
  1464. }
  1465. return "";
  1466. }
  1467. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1468. ArgStringList &CmdArgs) const {
  1469. const Driver &D = getToolChain().getDriver();
  1470. std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
  1471. bool SoftFloatABI = false;
  1472. if (Arg *A =
  1473. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
  1474. if (A->getOption().matches(options::OPT_msoft_float))
  1475. SoftFloatABI = true;
  1476. }
  1477. // Only the hard-float ABI on Sparc is standardized, and it is the
  1478. // default. GCC also supports a nonstandard soft-float ABI mode, and
  1479. // perhaps LLVM should implement that, too. However, since llvm
  1480. // currently does not support Sparc soft-float, at all, display an
  1481. // error if it's requested.
  1482. if (SoftFloatABI) {
  1483. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
  1484. << Triple;
  1485. }
  1486. }
  1487. void Clang::AddSystemZTargetArgs(const ArgList &Args,
  1488. ArgStringList &CmdArgs) const {
  1489. if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
  1490. CmdArgs.push_back("-mbackchain");
  1491. }
  1492. static const char *getSystemZTargetCPU(const ArgList &Args) {
  1493. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1494. return A->getValue();
  1495. return "z10";
  1496. }
  1497. static void getSystemZTargetFeatures(const ArgList &Args,
  1498. std::vector<const char *> &Features) {
  1499. // -m(no-)htm overrides use of the transactional-execution facility.
  1500. if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
  1501. if (A->getOption().matches(options::OPT_mhtm))
  1502. Features.push_back("+transactional-execution");
  1503. else
  1504. Features.push_back("-transactional-execution");
  1505. }
  1506. // -m(no-)vx overrides use of the vector facility.
  1507. if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
  1508. if (A->getOption().matches(options::OPT_mvx))
  1509. Features.push_back("+vector");
  1510. else
  1511. Features.push_back("-vector");
  1512. }
  1513. }
  1514. static const char *getX86TargetCPU(const ArgList &Args,
  1515. const llvm::Triple &Triple) {
  1516. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1517. if (StringRef(A->getValue()) != "native") {
  1518. if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
  1519. return "core-avx2";
  1520. return A->getValue();
  1521. }
  1522. // FIXME: Reject attempts to use -march=native unless the target matches
  1523. // the host.
  1524. //
  1525. // FIXME: We should also incorporate the detected target features for use
  1526. // with -native.
  1527. std::string CPU = llvm::sys::getHostCPUName();
  1528. if (!CPU.empty() && CPU != "generic")
  1529. return Args.MakeArgString(CPU);
  1530. }
  1531. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1532. // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
  1533. StringRef Arch = A->getValue();
  1534. const char *CPU;
  1535. if (Triple.getArch() == llvm::Triple::x86) {
  1536. CPU = llvm::StringSwitch<const char *>(Arch)
  1537. .Case("IA32", "i386")
  1538. .Case("SSE", "pentium3")
  1539. .Case("SSE2", "pentium4")
  1540. .Case("AVX", "sandybridge")
  1541. .Case("AVX2", "haswell")
  1542. .Default(nullptr);
  1543. } else {
  1544. CPU = llvm::StringSwitch<const char *>(Arch)
  1545. .Case("AVX", "sandybridge")
  1546. .Case("AVX2", "haswell")
  1547. .Default(nullptr);
  1548. }
  1549. if (CPU)
  1550. return CPU;
  1551. }
  1552. // Select the default CPU if none was given (or detection failed).
  1553. if (Triple.getArch() != llvm::Triple::x86_64 &&
  1554. Triple.getArch() != llvm::Triple::x86)
  1555. return nullptr; // This routine is only handling x86 targets.
  1556. bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
  1557. // FIXME: Need target hooks.
  1558. if (Triple.isOSDarwin()) {
  1559. if (Triple.getArchName() == "x86_64h")
  1560. return "core-avx2";
  1561. return Is64Bit ? "core2" : "yonah";
  1562. }
  1563. // Set up default CPU name for PS4 compilers.
  1564. if (Triple.isPS4CPU())
  1565. return "btver2";
  1566. // On Android use targets compatible with gcc
  1567. if (Triple.isAndroid())
  1568. return Is64Bit ? "x86-64" : "i686";
  1569. // Everything else goes to x86-64 in 64-bit mode.
  1570. if (Is64Bit)
  1571. return "x86-64";
  1572. switch (Triple.getOS()) {
  1573. case llvm::Triple::FreeBSD:
  1574. case llvm::Triple::NetBSD:
  1575. case llvm::Triple::OpenBSD:
  1576. return "i486";
  1577. case llvm::Triple::Haiku:
  1578. return "i586";
  1579. case llvm::Triple::Bitrig:
  1580. return "i686";
  1581. default:
  1582. // Fallback to p4.
  1583. return "pentium4";
  1584. }
  1585. }
  1586. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  1587. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  1588. // If we have -mcpu=, use that.
  1589. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1590. StringRef CPU = A->getValue();
  1591. #ifdef __wasm__
  1592. // Handle "native" by examining the host. "native" isn't meaningful when
  1593. // cross compiling, so only support this when the host is also WebAssembly.
  1594. if (CPU == "native")
  1595. return llvm::sys::getHostCPUName();
  1596. #endif
  1597. return CPU;
  1598. }
  1599. return "generic";
  1600. }
  1601. static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
  1602. bool FromAs = false) {
  1603. switch (T.getArch()) {
  1604. default:
  1605. return "";
  1606. case llvm::Triple::aarch64:
  1607. case llvm::Triple::aarch64_be:
  1608. return getAArch64TargetCPU(Args);
  1609. case llvm::Triple::arm:
  1610. case llvm::Triple::armeb:
  1611. case llvm::Triple::thumb:
  1612. case llvm::Triple::thumbeb: {
  1613. StringRef MArch, MCPU;
  1614. getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  1615. return arm::getARMTargetCPU(MCPU, MArch, T);
  1616. }
  1617. case llvm::Triple::mips:
  1618. case llvm::Triple::mipsel:
  1619. case llvm::Triple::mips64:
  1620. case llvm::Triple::mips64el: {
  1621. StringRef CPUName;
  1622. StringRef ABIName;
  1623. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  1624. return CPUName;
  1625. }
  1626. case llvm::Triple::nvptx:
  1627. case llvm::Triple::nvptx64:
  1628. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1629. return A->getValue();
  1630. return "";
  1631. case llvm::Triple::ppc:
  1632. case llvm::Triple::ppc64:
  1633. case llvm::Triple::ppc64le: {
  1634. std::string TargetCPUName = getPPCTargetCPU(Args);
  1635. // LLVM may default to generating code for the native CPU,
  1636. // but, like gcc, we default to a more generic option for
  1637. // each architecture. (except on Darwin)
  1638. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  1639. if (T.getArch() == llvm::Triple::ppc64)
  1640. TargetCPUName = "ppc64";
  1641. else if (T.getArch() == llvm::Triple::ppc64le)
  1642. TargetCPUName = "ppc64le";
  1643. else
  1644. TargetCPUName = "ppc";
  1645. }
  1646. return TargetCPUName;
  1647. }
  1648. case llvm::Triple::sparc:
  1649. case llvm::Triple::sparcel:
  1650. case llvm::Triple::sparcv9:
  1651. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1652. return A->getValue();
  1653. return "";
  1654. case llvm::Triple::x86:
  1655. case llvm::Triple::x86_64:
  1656. return getX86TargetCPU(Args, T);
  1657. case llvm::Triple::hexagon:
  1658. return "hexagon" +
  1659. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  1660. case llvm::Triple::lanai:
  1661. return getLanaiTargetCPU(Args);
  1662. case llvm::Triple::systemz:
  1663. return getSystemZTargetCPU(Args);
  1664. case llvm::Triple::r600:
  1665. case llvm::Triple::amdgcn:
  1666. return getR600TargetGPU(Args);
  1667. case llvm::Triple::wasm32:
  1668. case llvm::Triple::wasm64:
  1669. return getWebAssemblyTargetCPU(Args);
  1670. }
  1671. }
  1672. static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  1673. ArgStringList &CmdArgs, bool IsThinLTO) {
  1674. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  1675. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  1676. // forward.
  1677. CmdArgs.push_back("-plugin");
  1678. std::string Plugin =
  1679. ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
  1680. CmdArgs.push_back(Args.MakeArgString(Plugin));
  1681. // Try to pass driver level flags relevant to LTO code generation down to
  1682. // the plugin.
  1683. // Handle flags for selecting CPU variants.
  1684. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  1685. if (!CPU.empty())
  1686. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  1687. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  1688. StringRef OOpt;
  1689. if (A->getOption().matches(options::OPT_O4) ||
  1690. A->getOption().matches(options::OPT_Ofast))
  1691. OOpt = "3";
  1692. else if (A->getOption().matches(options::OPT_O))
  1693. OOpt = A->getValue();
  1694. else if (A->getOption().matches(options::OPT_O0))
  1695. OOpt = "0";
  1696. if (!OOpt.empty())
  1697. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
  1698. }
  1699. if (IsThinLTO)
  1700. CmdArgs.push_back("-plugin-opt=thinlto");
  1701. // If an explicit debugger tuning argument appeared, pass it along.
  1702. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  1703. options::OPT_ggdbN_Group)) {
  1704. if (A->getOption().matches(options::OPT_glldb))
  1705. CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
  1706. else if (A->getOption().matches(options::OPT_gsce))
  1707. CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
  1708. else
  1709. CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
  1710. }
  1711. }
  1712. /// This is a helper function for validating the optional refinement step
  1713. /// parameter in reciprocal argument strings. Return false if there is an error
  1714. /// parsing the refinement step. Otherwise, return true and set the Position
  1715. /// of the refinement step in the input string.
  1716. static bool getRefinementStep(StringRef In, const Driver &D,
  1717. const Arg &A, size_t &Position) {
  1718. const char RefinementStepToken = ':';
  1719. Position = In.find(RefinementStepToken);
  1720. if (Position != StringRef::npos) {
  1721. StringRef Option = A.getOption().getName();
  1722. StringRef RefStep = In.substr(Position + 1);
  1723. // Allow exactly one numeric character for the additional refinement
  1724. // step parameter. This is reasonable for all currently-supported
  1725. // operations and architectures because we would expect that a larger value
  1726. // of refinement steps would cause the estimate "optimization" to
  1727. // under-perform the native operation. Also, if the estimate does not
  1728. // converge quickly, it probably will not ever converge, so further
  1729. // refinement steps will not produce a better answer.
  1730. if (RefStep.size() != 1) {
  1731. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1732. return false;
  1733. }
  1734. char RefStepChar = RefStep[0];
  1735. if (RefStepChar < '0' || RefStepChar > '9') {
  1736. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1737. return false;
  1738. }
  1739. }
  1740. return true;
  1741. }
  1742. /// The -mrecip flag requires processing of many optional parameters.
  1743. static void ParseMRecip(const Driver &D, const ArgList &Args,
  1744. ArgStringList &OutStrings) {
  1745. StringRef DisabledPrefixIn = "!";
  1746. StringRef DisabledPrefixOut = "!";
  1747. StringRef EnabledPrefixOut = "";
  1748. StringRef Out = "-mrecip=";
  1749. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  1750. if (!A)
  1751. return;
  1752. unsigned NumOptions = A->getNumValues();
  1753. if (NumOptions == 0) {
  1754. // No option is the same as "all".
  1755. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  1756. return;
  1757. }
  1758. // Pass through "all", "none", or "default" with an optional refinement step.
  1759. if (NumOptions == 1) {
  1760. StringRef Val = A->getValue(0);
  1761. size_t RefStepLoc;
  1762. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  1763. return;
  1764. StringRef ValBase = Val.slice(0, RefStepLoc);
  1765. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  1766. OutStrings.push_back(Args.MakeArgString(Out + Val));
  1767. return;
  1768. }
  1769. }
  1770. // Each reciprocal type may be enabled or disabled individually.
  1771. // Check each input value for validity, concatenate them all back together,
  1772. // and pass through.
  1773. llvm::StringMap<bool> OptionStrings;
  1774. OptionStrings.insert(std::make_pair("divd", false));
  1775. OptionStrings.insert(std::make_pair("divf", false));
  1776. OptionStrings.insert(std::make_pair("vec-divd", false));
  1777. OptionStrings.insert(std::make_pair("vec-divf", false));
  1778. OptionStrings.insert(std::make_pair("sqrtd", false));
  1779. OptionStrings.insert(std::make_pair("sqrtf", false));
  1780. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  1781. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  1782. for (unsigned i = 0; i != NumOptions; ++i) {
  1783. StringRef Val = A->getValue(i);
  1784. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  1785. // Ignore the disablement token for string matching.
  1786. if (IsDisabled)
  1787. Val = Val.substr(1);
  1788. size_t RefStep;
  1789. if (!getRefinementStep(Val, D, *A, RefStep))
  1790. return;
  1791. StringRef ValBase = Val.slice(0, RefStep);
  1792. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  1793. if (OptionIter == OptionStrings.end()) {
  1794. // Try again specifying float suffix.
  1795. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  1796. if (OptionIter == OptionStrings.end()) {
  1797. // The input name did not match any known option string.
  1798. D.Diag(diag::err_drv_unknown_argument) << Val;
  1799. return;
  1800. }
  1801. // The option was specified without a float or double suffix.
  1802. // Make sure that the double entry was not already specified.
  1803. // The float entry will be checked below.
  1804. if (OptionStrings[ValBase.str() + 'd']) {
  1805. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1806. return;
  1807. }
  1808. }
  1809. if (OptionIter->second == true) {
  1810. // Duplicate option specified.
  1811. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1812. return;
  1813. }
  1814. // Mark the matched option as found. Do not allow duplicate specifiers.
  1815. OptionIter->second = true;
  1816. // If the precision was not specified, also mark the double entry as found.
  1817. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  1818. OptionStrings[ValBase.str() + 'd'] = true;
  1819. // Build the output string.
  1820. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  1821. Out = Args.MakeArgString(Out + Prefix + Val);
  1822. if (i != NumOptions - 1)
  1823. Out = Args.MakeArgString(Out + ",");
  1824. }
  1825. OutStrings.push_back(Args.MakeArgString(Out));
  1826. }
  1827. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1828. const ArgList &Args,
  1829. std::vector<const char *> &Features) {
  1830. // If -march=native, autodetect the feature list.
  1831. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1832. if (StringRef(A->getValue()) == "native") {
  1833. llvm::StringMap<bool> HostFeatures;
  1834. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  1835. for (auto &F : HostFeatures)
  1836. Features.push_back(
  1837. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  1838. }
  1839. }
  1840. if (Triple.getArchName() == "x86_64h") {
  1841. // x86_64h implies quite a few of the more modern subtarget features
  1842. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  1843. Features.push_back("-rdrnd");
  1844. Features.push_back("-aes");
  1845. Features.push_back("-pclmul");
  1846. Features.push_back("-rtm");
  1847. Features.push_back("-hle");
  1848. Features.push_back("-fsgsbase");
  1849. }
  1850. const llvm::Triple::ArchType ArchType = Triple.getArch();
  1851. // Add features to be compatible with gcc for Android.
  1852. if (Triple.isAndroid()) {
  1853. if (ArchType == llvm::Triple::x86_64) {
  1854. Features.push_back("+sse4.2");
  1855. Features.push_back("+popcnt");
  1856. } else
  1857. Features.push_back("+ssse3");
  1858. }
  1859. // Set features according to the -arch flag on MSVC.
  1860. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1861. StringRef Arch = A->getValue();
  1862. bool ArchUsed = false;
  1863. // First, look for flags that are shared in x86 and x86-64.
  1864. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  1865. if (Arch == "AVX" || Arch == "AVX2") {
  1866. ArchUsed = true;
  1867. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1868. }
  1869. }
  1870. // Then, look for x86-specific flags.
  1871. if (ArchType == llvm::Triple::x86) {
  1872. if (Arch == "IA32") {
  1873. ArchUsed = true;
  1874. } else if (Arch == "SSE" || Arch == "SSE2") {
  1875. ArchUsed = true;
  1876. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1877. }
  1878. }
  1879. if (!ArchUsed)
  1880. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  1881. }
  1882. // Now add any that the user explicitly requested on the command line,
  1883. // which may override the defaults.
  1884. handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
  1885. }
  1886. void Clang::AddX86TargetArgs(const ArgList &Args,
  1887. ArgStringList &CmdArgs) const {
  1888. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1889. Args.hasArg(options::OPT_mkernel) ||
  1890. Args.hasArg(options::OPT_fapple_kext))
  1891. CmdArgs.push_back("-disable-red-zone");
  1892. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1893. // that to be overridden with -mno-soft-float.
  1894. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1895. Args.hasArg(options::OPT_fapple_kext));
  1896. if (Arg *A = Args.getLastArg(
  1897. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1898. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1899. const Option &O = A->getOption();
  1900. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1901. O.matches(options::OPT_msoft_float));
  1902. }
  1903. if (NoImplicitFloat)
  1904. CmdArgs.push_back("-no-implicit-float");
  1905. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1906. StringRef Value = A->getValue();
  1907. if (Value == "intel" || Value == "att") {
  1908. CmdArgs.push_back("-mllvm");
  1909. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1910. } else {
  1911. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  1912. << A->getOption().getName() << Value;
  1913. }
  1914. }
  1915. // Set flags to support MCU ABI.
  1916. if (Args.hasArg(options::OPT_miamcu)) {
  1917. CmdArgs.push_back("-mfloat-abi");
  1918. CmdArgs.push_back("soft");
  1919. CmdArgs.push_back("-mstack-alignment=4");
  1920. }
  1921. }
  1922. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  1923. ArgStringList &CmdArgs) const {
  1924. CmdArgs.push_back("-mqdsp6-compat");
  1925. CmdArgs.push_back("-Wreturn-type");
  1926. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  1927. std::string N = llvm::utostr(G.getValue());
  1928. std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
  1929. CmdArgs.push_back("-mllvm");
  1930. CmdArgs.push_back(Args.MakeArgString(Opt));
  1931. }
  1932. if (!Args.hasArg(options::OPT_fno_short_enums))
  1933. CmdArgs.push_back("-fshort-enums");
  1934. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  1935. CmdArgs.push_back("-mllvm");
  1936. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  1937. }
  1938. CmdArgs.push_back("-mllvm");
  1939. CmdArgs.push_back("-machine-sink-split=0");
  1940. }
  1941. void Clang::AddLanaiTargetArgs(const ArgList &Args,
  1942. ArgStringList &CmdArgs) const {
  1943. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1944. StringRef CPUName = A->getValue();
  1945. CmdArgs.push_back("-target-cpu");
  1946. CmdArgs.push_back(Args.MakeArgString(CPUName));
  1947. }
  1948. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  1949. StringRef Value = A->getValue();
  1950. // Only support mregparm=4 to support old usage. Report error for all other
  1951. // cases.
  1952. int Mregparm;
  1953. if (Value.getAsInteger(10, Mregparm)) {
  1954. if (Mregparm != 4) {
  1955. getToolChain().getDriver().Diag(
  1956. diag::err_drv_unsupported_option_argument)
  1957. << A->getOption().getName() << Value;
  1958. }
  1959. }
  1960. }
  1961. }
  1962. void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
  1963. ArgStringList &CmdArgs) const {
  1964. // Default to "hidden" visibility.
  1965. if (!Args.hasArg(options::OPT_fvisibility_EQ,
  1966. options::OPT_fvisibility_ms_compat)) {
  1967. CmdArgs.push_back("-fvisibility");
  1968. CmdArgs.push_back("hidden");
  1969. }
  1970. }
  1971. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  1972. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  1973. std::vector<const char *> &Features) {
  1974. SmallVector<StringRef, 8> Split;
  1975. text.split(Split, StringRef("+"), -1, false);
  1976. for (StringRef Feature : Split) {
  1977. const char *result = llvm::StringSwitch<const char *>(Feature)
  1978. .Case("fp", "+fp-armv8")
  1979. .Case("simd", "+neon")
  1980. .Case("crc", "+crc")
  1981. .Case("crypto", "+crypto")
  1982. .Case("fp16", "+fullfp16")
  1983. .Case("profile", "+spe")
  1984. .Case("nofp", "-fp-armv8")
  1985. .Case("nosimd", "-neon")
  1986. .Case("nocrc", "-crc")
  1987. .Case("nocrypto", "-crypto")
  1988. .Case("nofp16", "-fullfp16")
  1989. .Case("noprofile", "-spe")
  1990. .Default(nullptr);
  1991. if (result)
  1992. Features.push_back(result);
  1993. else if (Feature == "neon" || Feature == "noneon")
  1994. D.Diag(diag::err_drv_no_neon_modifier);
  1995. else
  1996. return false;
  1997. }
  1998. return true;
  1999. }
  2000. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  2001. // decode CPU and feature.
  2002. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  2003. std::vector<const char *> &Features) {
  2004. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  2005. CPU = Split.first;
  2006. if (CPU == "cortex-a53" || CPU == "cortex-a57" ||
  2007. CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1" ||
  2008. CPU == "kryo") {
  2009. Features.push_back("+neon");
  2010. Features.push_back("+crc");
  2011. Features.push_back("+crypto");
  2012. } else if (CPU == "cyclone") {
  2013. Features.push_back("+neon");
  2014. Features.push_back("+crypto");
  2015. } else if (CPU == "generic") {
  2016. Features.push_back("+neon");
  2017. } else {
  2018. return false;
  2019. }
  2020. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  2021. return false;
  2022. return true;
  2023. }
  2024. static bool
  2025. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  2026. const ArgList &Args,
  2027. std::vector<const char *> &Features) {
  2028. std::string MarchLowerCase = March.lower();
  2029. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  2030. if (Split.first == "armv8-a" || Split.first == "armv8a") {
  2031. // ok, no additional features.
  2032. } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
  2033. Features.push_back("+v8.1a");
  2034. } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
  2035. Features.push_back("+v8.2a");
  2036. } else {
  2037. return false;
  2038. }
  2039. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  2040. return false;
  2041. return true;
  2042. }
  2043. static bool
  2044. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2045. const ArgList &Args,
  2046. std::vector<const char *> &Features) {
  2047. StringRef CPU;
  2048. std::string McpuLowerCase = Mcpu.lower();
  2049. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  2050. return false;
  2051. return true;
  2052. }
  2053. static bool
  2054. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  2055. const ArgList &Args,
  2056. std::vector<const char *> &Features) {
  2057. std::string MtuneLowerCase = Mtune.lower();
  2058. // Handle CPU name is 'native'.
  2059. if (MtuneLowerCase == "native")
  2060. MtuneLowerCase = llvm::sys::getHostCPUName();
  2061. if (MtuneLowerCase == "cyclone") {
  2062. Features.push_back("+zcm");
  2063. Features.push_back("+zcz");
  2064. }
  2065. return true;
  2066. }
  2067. static bool
  2068. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2069. const ArgList &Args,
  2070. std::vector<const char *> &Features) {
  2071. StringRef CPU;
  2072. std::vector<const char *> DecodedFeature;
  2073. std::string McpuLowerCase = Mcpu.lower();
  2074. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  2075. return false;
  2076. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  2077. }
  2078. static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
  2079. std::vector<const char *> &Features) {
  2080. Arg *A;
  2081. bool success = true;
  2082. // Enable NEON by default.
  2083. Features.push_back("+neon");
  2084. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  2085. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  2086. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2087. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2088. else if (Args.hasArg(options::OPT_arch))
  2089. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
  2090. Features);
  2091. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  2092. success =
  2093. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  2094. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2095. success =
  2096. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2097. else if (Args.hasArg(options::OPT_arch))
  2098. success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
  2099. Args, Features);
  2100. if (!success)
  2101. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  2102. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  2103. Features.push_back("-fp-armv8");
  2104. Features.push_back("-crypto");
  2105. Features.push_back("-neon");
  2106. }
  2107. // En/disable crc
  2108. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  2109. if (A->getOption().matches(options::OPT_mcrc))
  2110. Features.push_back("+crc");
  2111. else
  2112. Features.push_back("-crc");
  2113. }
  2114. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  2115. options::OPT_munaligned_access))
  2116. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  2117. Features.push_back("+strict-align");
  2118. if (Args.hasArg(options::OPT_ffixed_x18))
  2119. Features.push_back("+reserve-x18");
  2120. }
  2121. static void getHexagonTargetFeatures(const ArgList &Args,
  2122. std::vector<const char *> &Features) {
  2123. bool HasHVX = false, HasHVXD = false;
  2124. // FIXME: This should be able to use handleTargetFeaturesGroup except it is
  2125. // doing dependent option handling here rather than in initFeatureMap or a
  2126. // similar handler.
  2127. for (auto &A : Args) {
  2128. auto &Opt = A->getOption();
  2129. if (Opt.matches(options::OPT_mhexagon_hvx))
  2130. HasHVX = true;
  2131. else if (Opt.matches(options::OPT_mno_hexagon_hvx))
  2132. HasHVXD = HasHVX = false;
  2133. else if (Opt.matches(options::OPT_mhexagon_hvx_double))
  2134. HasHVXD = HasHVX = true;
  2135. else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
  2136. HasHVXD = false;
  2137. else
  2138. continue;
  2139. A->claim();
  2140. }
  2141. Features.push_back(HasHVX ? "+hvx" : "-hvx");
  2142. Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
  2143. }
  2144. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  2145. std::vector<const char *> &Features) {
  2146. handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
  2147. }
  2148. static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
  2149. std::vector<const char *> &Features) {
  2150. if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
  2151. StringRef value = dAbi->getValue();
  2152. if (value == "1.0") {
  2153. Features.push_back("+amdgpu-debugger-insert-nops");
  2154. Features.push_back("+amdgpu-debugger-reserve-trap-regs");
  2155. } else {
  2156. D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
  2157. }
  2158. }
  2159. handleTargetFeaturesGroup(
  2160. Args, Features, options::OPT_m_amdgpu_Features_Group);
  2161. }
  2162. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  2163. const ArgList &Args, ArgStringList &CmdArgs,
  2164. bool ForAS) {
  2165. const Driver &D = TC.getDriver();
  2166. std::vector<const char *> Features;
  2167. switch (Triple.getArch()) {
  2168. default:
  2169. break;
  2170. case llvm::Triple::mips:
  2171. case llvm::Triple::mipsel:
  2172. case llvm::Triple::mips64:
  2173. case llvm::Triple::mips64el:
  2174. getMIPSTargetFeatures(D, Triple, Args, Features);
  2175. break;
  2176. case llvm::Triple::arm:
  2177. case llvm::Triple::armeb:
  2178. case llvm::Triple::thumb:
  2179. case llvm::Triple::thumbeb:
  2180. getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
  2181. break;
  2182. case llvm::Triple::ppc:
  2183. case llvm::Triple::ppc64:
  2184. case llvm::Triple::ppc64le:
  2185. getPPCTargetFeatures(D, Triple, Args, Features);
  2186. break;
  2187. case llvm::Triple::systemz:
  2188. getSystemZTargetFeatures(Args, Features);
  2189. break;
  2190. case llvm::Triple::aarch64:
  2191. case llvm::Triple::aarch64_be:
  2192. getAArch64TargetFeatures(D, Args, Features);
  2193. break;
  2194. case llvm::Triple::x86:
  2195. case llvm::Triple::x86_64:
  2196. getX86TargetFeatures(D, Triple, Args, Features);
  2197. break;
  2198. case llvm::Triple::hexagon:
  2199. getHexagonTargetFeatures(Args, Features);
  2200. break;
  2201. case llvm::Triple::wasm32:
  2202. case llvm::Triple::wasm64:
  2203. getWebAssemblyTargetFeatures(Args, Features);
  2204. break;
  2205. case llvm::Triple::r600:
  2206. case llvm::Triple::amdgcn:
  2207. getAMDGPUTargetFeatures(D, Args, Features);
  2208. break;
  2209. }
  2210. // Find the last of each feature.
  2211. llvm::StringMap<unsigned> LastOpt;
  2212. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2213. const char *Name = Features[I];
  2214. assert(Name[0] == '-' || Name[0] == '+');
  2215. LastOpt[Name + 1] = I;
  2216. }
  2217. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2218. // If this feature was overridden, ignore it.
  2219. const char *Name = Features[I];
  2220. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
  2221. assert(LastI != LastOpt.end());
  2222. unsigned Last = LastI->second;
  2223. if (Last != I)
  2224. continue;
  2225. CmdArgs.push_back("-target-feature");
  2226. CmdArgs.push_back(Name);
  2227. }
  2228. }
  2229. static bool
  2230. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  2231. const llvm::Triple &Triple) {
  2232. // We use the zero-cost exception tables for Objective-C if the non-fragile
  2233. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  2234. // later.
  2235. if (runtime.isNonFragile())
  2236. return true;
  2237. if (!Triple.isMacOSX())
  2238. return false;
  2239. return (!Triple.isMacOSXVersionLT(10, 5) &&
  2240. (Triple.getArch() == llvm::Triple::x86_64 ||
  2241. Triple.getArch() == llvm::Triple::arm));
  2242. }
  2243. /// Adds exception related arguments to the driver command arguments. There's a
  2244. /// master flag, -fexceptions and also language specific flags to enable/disable
  2245. /// C++ and Objective-C exceptions. This makes it possible to for example
  2246. /// disable C++ exceptions but enable Objective-C exceptions.
  2247. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  2248. const ToolChain &TC, bool KernelOrKext,
  2249. const ObjCRuntime &objcRuntime,
  2250. ArgStringList &CmdArgs) {
  2251. const Driver &D = TC.getDriver();
  2252. const llvm::Triple &Triple = TC.getTriple();
  2253. if (KernelOrKext) {
  2254. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  2255. // arguments now to avoid warnings about unused arguments.
  2256. Args.ClaimAllArgs(options::OPT_fexceptions);
  2257. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  2258. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  2259. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  2260. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  2261. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  2262. return;
  2263. }
  2264. // See if the user explicitly enabled exceptions.
  2265. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2266. false);
  2267. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  2268. // is not necessarily sensible, but follows GCC.
  2269. if (types::isObjC(InputType) &&
  2270. Args.hasFlag(options::OPT_fobjc_exceptions,
  2271. options::OPT_fno_objc_exceptions, true)) {
  2272. CmdArgs.push_back("-fobjc-exceptions");
  2273. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  2274. }
  2275. if (types::isCXX(InputType)) {
  2276. // Disable C++ EH by default on XCore and PS4.
  2277. bool CXXExceptionsEnabled =
  2278. Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
  2279. Arg *ExceptionArg = Args.getLastArg(
  2280. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  2281. options::OPT_fexceptions, options::OPT_fno_exceptions);
  2282. if (ExceptionArg)
  2283. CXXExceptionsEnabled =
  2284. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  2285. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  2286. if (CXXExceptionsEnabled) {
  2287. if (Triple.isPS4CPU()) {
  2288. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  2289. assert(ExceptionArg &&
  2290. "On the PS4 exceptions should only be enabled if passing "
  2291. "an argument");
  2292. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  2293. const Arg *RTTIArg = TC.getRTTIArg();
  2294. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  2295. D.Diag(diag::err_drv_argument_not_allowed_with)
  2296. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2297. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2298. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2299. } else
  2300. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2301. CmdArgs.push_back("-fcxx-exceptions");
  2302. EH = true;
  2303. }
  2304. }
  2305. if (EH)
  2306. CmdArgs.push_back("-fexceptions");
  2307. }
  2308. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2309. bool Default = true;
  2310. if (TC.getTriple().isOSDarwin()) {
  2311. // The native darwin assembler doesn't support the linker_option directives,
  2312. // so we disable them if we think the .s file will be passed to it.
  2313. Default = TC.useIntegratedAs();
  2314. }
  2315. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2316. Default);
  2317. }
  2318. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2319. const ToolChain &TC) {
  2320. bool UseDwarfDirectory =
  2321. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2322. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2323. return !UseDwarfDirectory;
  2324. }
  2325. /// \brief Check whether the given input tree contains any compilation actions.
  2326. static bool ContainsCompileAction(const Action *A) {
  2327. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2328. return true;
  2329. for (const auto &AI : A->inputs())
  2330. if (ContainsCompileAction(AI))
  2331. return true;
  2332. return false;
  2333. }
  2334. /// \brief Check if -relax-all should be passed to the internal assembler.
  2335. /// This is done by default when compiling non-assembler source with -O0.
  2336. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2337. bool RelaxDefault = true;
  2338. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2339. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2340. if (RelaxDefault) {
  2341. RelaxDefault = false;
  2342. for (const auto &Act : C.getActions()) {
  2343. if (ContainsCompileAction(Act)) {
  2344. RelaxDefault = true;
  2345. break;
  2346. }
  2347. }
  2348. }
  2349. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2350. RelaxDefault);
  2351. }
  2352. // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
  2353. // to the corresponding DebugInfoKind.
  2354. static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
  2355. assert(A.getOption().matches(options::OPT_gN_Group) &&
  2356. "Not a -g option that specifies a debug-info level");
  2357. if (A.getOption().matches(options::OPT_g0) ||
  2358. A.getOption().matches(options::OPT_ggdb0))
  2359. return codegenoptions::NoDebugInfo;
  2360. if (A.getOption().matches(options::OPT_gline_tables_only) ||
  2361. A.getOption().matches(options::OPT_ggdb1))
  2362. return codegenoptions::DebugLineTablesOnly;
  2363. return codegenoptions::LimitedDebugInfo;
  2364. }
  2365. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2366. // on mismatch. The StringRef input (rather than an Arg) allows
  2367. // for use by the "-Xassembler" option parser.
  2368. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2369. return llvm::StringSwitch<unsigned>(ArgValue)
  2370. .Case("-gdwarf-2", 2)
  2371. .Case("-gdwarf-3", 3)
  2372. .Case("-gdwarf-4", 4)
  2373. .Case("-gdwarf-5", 5)
  2374. .Default(0);
  2375. }
  2376. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2377. codegenoptions::DebugInfoKind DebugInfoKind,
  2378. unsigned DwarfVersion,
  2379. llvm::DebuggerKind DebuggerTuning) {
  2380. switch (DebugInfoKind) {
  2381. case codegenoptions::DebugLineTablesOnly:
  2382. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2383. break;
  2384. case codegenoptions::LimitedDebugInfo:
  2385. CmdArgs.push_back("-debug-info-kind=limited");
  2386. break;
  2387. case codegenoptions::FullDebugInfo:
  2388. CmdArgs.push_back("-debug-info-kind=standalone");
  2389. break;
  2390. default:
  2391. break;
  2392. }
  2393. if (DwarfVersion > 0)
  2394. CmdArgs.push_back(
  2395. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2396. switch (DebuggerTuning) {
  2397. case llvm::DebuggerKind::GDB:
  2398. CmdArgs.push_back("-debugger-tuning=gdb");
  2399. break;
  2400. case llvm::DebuggerKind::LLDB:
  2401. CmdArgs.push_back("-debugger-tuning=lldb");
  2402. break;
  2403. case llvm::DebuggerKind::SCE:
  2404. CmdArgs.push_back("-debugger-tuning=sce");
  2405. break;
  2406. default:
  2407. break;
  2408. }
  2409. }
  2410. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2411. const ArgList &Args,
  2412. ArgStringList &CmdArgs,
  2413. const Driver &D) {
  2414. if (UseRelaxAll(C, Args))
  2415. CmdArgs.push_back("-mrelax-all");
  2416. // Only default to -mincremental-linker-compatible if we think we are
  2417. // targeting the MSVC linker.
  2418. bool DefaultIncrementalLinkerCompatible =
  2419. C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
  2420. if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
  2421. options::OPT_mno_incremental_linker_compatible,
  2422. DefaultIncrementalLinkerCompatible))
  2423. CmdArgs.push_back("-mincremental-linker-compatible");
  2424. // When passing -I arguments to the assembler we sometimes need to
  2425. // unconditionally take the next argument. For example, when parsing
  2426. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2427. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2428. // arg after parsing the '-I' arg.
  2429. bool TakeNextArg = false;
  2430. // When using an integrated assembler, translate -Wa, and -Xassembler
  2431. // options.
  2432. bool CompressDebugSections = false;
  2433. const char *MipsTargetFeature = nullptr;
  2434. for (const Arg *A :
  2435. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2436. A->claim();
  2437. for (StringRef Value : A->getValues()) {
  2438. if (TakeNextArg) {
  2439. CmdArgs.push_back(Value.data());
  2440. TakeNextArg = false;
  2441. continue;
  2442. }
  2443. switch (C.getDefaultToolChain().getArch()) {
  2444. default:
  2445. break;
  2446. case llvm::Triple::mips:
  2447. case llvm::Triple::mipsel:
  2448. case llvm::Triple::mips64:
  2449. case llvm::Triple::mips64el:
  2450. if (Value == "--trap") {
  2451. CmdArgs.push_back("-target-feature");
  2452. CmdArgs.push_back("+use-tcc-in-div");
  2453. continue;
  2454. }
  2455. if (Value == "--break") {
  2456. CmdArgs.push_back("-target-feature");
  2457. CmdArgs.push_back("-use-tcc-in-div");
  2458. continue;
  2459. }
  2460. if (Value.startswith("-msoft-float")) {
  2461. CmdArgs.push_back("-target-feature");
  2462. CmdArgs.push_back("+soft-float");
  2463. continue;
  2464. }
  2465. if (Value.startswith("-mhard-float")) {
  2466. CmdArgs.push_back("-target-feature");
  2467. CmdArgs.push_back("-soft-float");
  2468. continue;
  2469. }
  2470. MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
  2471. .Case("-mips1", "+mips1")
  2472. .Case("-mips2", "+mips2")
  2473. .Case("-mips3", "+mips3")
  2474. .Case("-mips4", "+mips4")
  2475. .Case("-mips5", "+mips5")
  2476. .Case("-mips32", "+mips32")
  2477. .Case("-mips32r2", "+mips32r2")
  2478. .Case("-mips32r3", "+mips32r3")
  2479. .Case("-mips32r5", "+mips32r5")
  2480. .Case("-mips32r6", "+mips32r6")
  2481. .Case("-mips64", "+mips64")
  2482. .Case("-mips64r2", "+mips64r2")
  2483. .Case("-mips64r3", "+mips64r3")
  2484. .Case("-mips64r5", "+mips64r5")
  2485. .Case("-mips64r6", "+mips64r6")
  2486. .Default(nullptr);
  2487. if (MipsTargetFeature)
  2488. continue;
  2489. }
  2490. if (Value == "-force_cpusubtype_ALL") {
  2491. // Do nothing, this is the default and we don't support anything else.
  2492. } else if (Value == "-L") {
  2493. CmdArgs.push_back("-msave-temp-labels");
  2494. } else if (Value == "--fatal-warnings") {
  2495. CmdArgs.push_back("-massembler-fatal-warnings");
  2496. } else if (Value == "--noexecstack") {
  2497. CmdArgs.push_back("-mnoexecstack");
  2498. } else if (Value == "-compress-debug-sections" ||
  2499. Value == "--compress-debug-sections") {
  2500. CompressDebugSections = true;
  2501. } else if (Value == "-nocompress-debug-sections" ||
  2502. Value == "--nocompress-debug-sections") {
  2503. CompressDebugSections = false;
  2504. } else if (Value.startswith("-I")) {
  2505. CmdArgs.push_back(Value.data());
  2506. // We need to consume the next argument if the current arg is a plain
  2507. // -I. The next arg will be the include directory.
  2508. if (Value == "-I")
  2509. TakeNextArg = true;
  2510. } else if (Value.startswith("-gdwarf-")) {
  2511. // "-gdwarf-N" options are not cc1as options.
  2512. unsigned DwarfVersion = DwarfVersionNum(Value);
  2513. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2514. CmdArgs.push_back(Value.data());
  2515. } else {
  2516. RenderDebugEnablingArgs(Args, CmdArgs,
  2517. codegenoptions::LimitedDebugInfo,
  2518. DwarfVersion, llvm::DebuggerKind::Default);
  2519. }
  2520. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2521. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2522. // Do nothing, we'll validate it later.
  2523. } else {
  2524. D.Diag(diag::err_drv_unsupported_option_argument)
  2525. << A->getOption().getName() << Value;
  2526. }
  2527. }
  2528. }
  2529. if (CompressDebugSections) {
  2530. if (llvm::zlib::isAvailable())
  2531. CmdArgs.push_back("-compress-debug-sections");
  2532. else
  2533. D.Diag(diag::warn_debug_compression_unavailable);
  2534. }
  2535. if (MipsTargetFeature != nullptr) {
  2536. CmdArgs.push_back("-target-feature");
  2537. CmdArgs.push_back(MipsTargetFeature);
  2538. }
  2539. }
  2540. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2541. // FIXME: Make sure we can also emit shared objects if they're requested
  2542. // and available, check for possible errors, etc.
  2543. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2544. ArgStringList &CmdArgs) {
  2545. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  2546. }
  2547. namespace {
  2548. enum OpenMPRuntimeKind {
  2549. /// An unknown OpenMP runtime. We can't generate effective OpenMP code
  2550. /// without knowing what runtime to target.
  2551. OMPRT_Unknown,
  2552. /// The LLVM OpenMP runtime. When completed and integrated, this will become
  2553. /// the default for Clang.
  2554. OMPRT_OMP,
  2555. /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
  2556. /// this runtime but can swallow the pragmas, and find and link against the
  2557. /// runtime library itself.
  2558. OMPRT_GOMP,
  2559. /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
  2560. /// OpenMP runtime. We support this mode for users with existing dependencies
  2561. /// on this runtime library name.
  2562. OMPRT_IOMP5
  2563. };
  2564. }
  2565. /// Compute the desired OpenMP runtime from the flag provided.
  2566. static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
  2567. const ArgList &Args) {
  2568. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  2569. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  2570. if (A)
  2571. RuntimeName = A->getValue();
  2572. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  2573. .Case("libomp", OMPRT_OMP)
  2574. .Case("libgomp", OMPRT_GOMP)
  2575. .Case("libiomp5", OMPRT_IOMP5)
  2576. .Default(OMPRT_Unknown);
  2577. if (RT == OMPRT_Unknown) {
  2578. if (A)
  2579. TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2580. << A->getOption().getName() << A->getValue();
  2581. else
  2582. // FIXME: We could use a nicer diagnostic here.
  2583. TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  2584. }
  2585. return RT;
  2586. }
  2587. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2588. const ArgList &Args) {
  2589. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2590. options::OPT_fno_openmp, false))
  2591. return;
  2592. switch (getOpenMPRuntime(TC, Args)) {
  2593. case OMPRT_OMP:
  2594. CmdArgs.push_back("-lomp");
  2595. break;
  2596. case OMPRT_GOMP:
  2597. CmdArgs.push_back("-lgomp");
  2598. break;
  2599. case OMPRT_IOMP5:
  2600. CmdArgs.push_back("-liomp5");
  2601. break;
  2602. case OMPRT_Unknown:
  2603. // Already diagnosed.
  2604. break;
  2605. }
  2606. }
  2607. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2608. ArgStringList &CmdArgs, StringRef Sanitizer,
  2609. bool IsShared, bool IsWhole) {
  2610. // Wrap any static runtimes that must be forced into executable in
  2611. // whole-archive.
  2612. if (IsWhole) CmdArgs.push_back("-whole-archive");
  2613. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
  2614. if (IsWhole) CmdArgs.push_back("-no-whole-archive");
  2615. }
  2616. // Tries to use a file with the list of dynamic symbols that need to be exported
  2617. // from the runtime library. Returns true if the file was found.
  2618. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2619. ArgStringList &CmdArgs,
  2620. StringRef Sanitizer) {
  2621. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2622. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2623. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2624. return true;
  2625. }
  2626. return false;
  2627. }
  2628. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2629. ArgStringList &CmdArgs) {
  2630. // Force linking against the system libraries sanitizers depends on
  2631. // (see PR15823 why this is necessary).
  2632. CmdArgs.push_back("--no-as-needed");
  2633. CmdArgs.push_back("-lpthread");
  2634. CmdArgs.push_back("-lrt");
  2635. CmdArgs.push_back("-lm");
  2636. // There's no libdl on FreeBSD.
  2637. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  2638. CmdArgs.push_back("-ldl");
  2639. }
  2640. static void
  2641. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2642. SmallVectorImpl<StringRef> &SharedRuntimes,
  2643. SmallVectorImpl<StringRef> &StaticRuntimes,
  2644. SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
  2645. SmallVectorImpl<StringRef> &HelperStaticRuntimes,
  2646. SmallVectorImpl<StringRef> &RequiredSymbols) {
  2647. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2648. // Collect shared runtimes.
  2649. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2650. SharedRuntimes.push_back("asan");
  2651. }
  2652. // The stats_client library is also statically linked into DSOs.
  2653. if (SanArgs.needsStatsRt())
  2654. StaticRuntimes.push_back("stats_client");
  2655. // Collect static runtimes.
  2656. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2657. // Don't link static runtimes into DSOs or if compiling for Android.
  2658. return;
  2659. }
  2660. if (SanArgs.needsAsanRt()) {
  2661. if (SanArgs.needsSharedAsanRt()) {
  2662. HelperStaticRuntimes.push_back("asan-preinit");
  2663. } else {
  2664. StaticRuntimes.push_back("asan");
  2665. if (SanArgs.linkCXXRuntimes())
  2666. StaticRuntimes.push_back("asan_cxx");
  2667. }
  2668. }
  2669. if (SanArgs.needsDfsanRt())
  2670. StaticRuntimes.push_back("dfsan");
  2671. if (SanArgs.needsLsanRt())
  2672. StaticRuntimes.push_back("lsan");
  2673. if (SanArgs.needsMsanRt()) {
  2674. StaticRuntimes.push_back("msan");
  2675. if (SanArgs.linkCXXRuntimes())
  2676. StaticRuntimes.push_back("msan_cxx");
  2677. }
  2678. if (SanArgs.needsTsanRt()) {
  2679. StaticRuntimes.push_back("tsan");
  2680. if (SanArgs.linkCXXRuntimes())
  2681. StaticRuntimes.push_back("tsan_cxx");
  2682. }
  2683. if (SanArgs.needsUbsanRt()) {
  2684. StaticRuntimes.push_back("ubsan_standalone");
  2685. if (SanArgs.linkCXXRuntimes())
  2686. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2687. }
  2688. if (SanArgs.needsSafeStackRt())
  2689. StaticRuntimes.push_back("safestack");
  2690. if (SanArgs.needsCfiRt())
  2691. StaticRuntimes.push_back("cfi");
  2692. if (SanArgs.needsCfiDiagRt()) {
  2693. StaticRuntimes.push_back("cfi_diag");
  2694. if (SanArgs.linkCXXRuntimes())
  2695. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2696. }
  2697. if (SanArgs.needsStatsRt()) {
  2698. NonWholeStaticRuntimes.push_back("stats");
  2699. RequiredSymbols.push_back("__sanitizer_stats_register");
  2700. }
  2701. if (SanArgs.needsEsanRt())
  2702. StaticRuntimes.push_back("esan");
  2703. }
  2704. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  2705. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  2706. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2707. ArgStringList &CmdArgs) {
  2708. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  2709. NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
  2710. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  2711. NonWholeStaticRuntimes, HelperStaticRuntimes,
  2712. RequiredSymbols);
  2713. for (auto RT : SharedRuntimes)
  2714. addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
  2715. for (auto RT : HelperStaticRuntimes)
  2716. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2717. bool AddExportDynamic = false;
  2718. for (auto RT : StaticRuntimes) {
  2719. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2720. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2721. }
  2722. for (auto RT : NonWholeStaticRuntimes) {
  2723. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
  2724. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2725. }
  2726. for (auto S : RequiredSymbols) {
  2727. CmdArgs.push_back("-u");
  2728. CmdArgs.push_back(Args.MakeArgString(S));
  2729. }
  2730. // If there is a static runtime with no dynamic list, force all the symbols
  2731. // to be dynamic to be sure we export sanitizer interface functions.
  2732. if (AddExportDynamic)
  2733. CmdArgs.push_back("-export-dynamic");
  2734. return !StaticRuntimes.empty();
  2735. }
  2736. static bool areOptimizationsEnabled(const ArgList &Args) {
  2737. // Find the last -O arg and see if it is non-zero.
  2738. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2739. return !A->getOption().matches(options::OPT_O0);
  2740. // Defaults to -O0.
  2741. return false;
  2742. }
  2743. static bool shouldUseFramePointerForTarget(const ArgList &Args,
  2744. const llvm::Triple &Triple) {
  2745. switch (Triple.getArch()) {
  2746. case llvm::Triple::xcore:
  2747. case llvm::Triple::wasm32:
  2748. case llvm::Triple::wasm64:
  2749. // XCore never wants frame pointers, regardless of OS.
  2750. // WebAssembly never wants frame pointers.
  2751. return false;
  2752. default:
  2753. break;
  2754. }
  2755. if (Triple.isOSLinux()) {
  2756. switch (Triple.getArch()) {
  2757. // Don't use a frame pointer on linux if optimizing for certain targets.
  2758. case llvm::Triple::mips64:
  2759. case llvm::Triple::mips64el:
  2760. case llvm::Triple::mips:
  2761. case llvm::Triple::mipsel:
  2762. case llvm::Triple::systemz:
  2763. case llvm::Triple::x86:
  2764. case llvm::Triple::x86_64:
  2765. return !areOptimizationsEnabled(Args);
  2766. default:
  2767. return true;
  2768. }
  2769. }
  2770. if (Triple.isOSWindows()) {
  2771. switch (Triple.getArch()) {
  2772. case llvm::Triple::x86:
  2773. return !areOptimizationsEnabled(Args);
  2774. case llvm::Triple::x86_64:
  2775. return Triple.isOSBinFormatMachO();
  2776. case llvm::Triple::arm:
  2777. case llvm::Triple::thumb:
  2778. // Windows on ARM builds with FPO disabled to aid fast stack walking
  2779. return true;
  2780. default:
  2781. // All other supported Windows ISAs use xdata unwind information, so frame
  2782. // pointers are not generally useful.
  2783. return false;
  2784. }
  2785. }
  2786. return true;
  2787. }
  2788. static bool shouldUseFramePointer(const ArgList &Args,
  2789. const llvm::Triple &Triple) {
  2790. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  2791. options::OPT_fomit_frame_pointer))
  2792. return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  2793. if (Args.hasArg(options::OPT_pg))
  2794. return true;
  2795. return shouldUseFramePointerForTarget(Args, Triple);
  2796. }
  2797. static bool shouldUseLeafFramePointer(const ArgList &Args,
  2798. const llvm::Triple &Triple) {
  2799. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  2800. options::OPT_momit_leaf_frame_pointer))
  2801. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
  2802. if (Args.hasArg(options::OPT_pg))
  2803. return true;
  2804. if (Triple.isPS4CPU())
  2805. return false;
  2806. return shouldUseFramePointerForTarget(Args, Triple);
  2807. }
  2808. /// Add a CC1 option to specify the debug compilation directory.
  2809. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  2810. SmallString<128> cwd;
  2811. if (!llvm::sys::fs::current_path(cwd)) {
  2812. CmdArgs.push_back("-fdebug-compilation-dir");
  2813. CmdArgs.push_back(Args.MakeArgString(cwd));
  2814. }
  2815. }
  2816. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  2817. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  2818. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  2819. SmallString<128> T(FinalOutput->getValue());
  2820. llvm::sys::path::replace_extension(T, "dwo");
  2821. return Args.MakeArgString(T);
  2822. } else {
  2823. // Use the compilation dir.
  2824. SmallString<128> T(
  2825. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  2826. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  2827. llvm::sys::path::replace_extension(F, "dwo");
  2828. T += F;
  2829. return Args.MakeArgString(F);
  2830. }
  2831. }
  2832. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  2833. const JobAction &JA, const ArgList &Args,
  2834. const InputInfo &Output, const char *OutFile) {
  2835. ArgStringList ExtractArgs;
  2836. ExtractArgs.push_back("--extract-dwo");
  2837. ArgStringList StripArgs;
  2838. StripArgs.push_back("--strip-dwo");
  2839. // Grabbing the output of the earlier compile step.
  2840. StripArgs.push_back(Output.getFilename());
  2841. ExtractArgs.push_back(Output.getFilename());
  2842. ExtractArgs.push_back(OutFile);
  2843. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  2844. InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
  2845. // First extract the dwo sections.
  2846. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  2847. // Then remove them from the original .o file.
  2848. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  2849. }
  2850. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  2851. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  2852. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  2853. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  2854. if (A->getOption().matches(options::OPT_O4) ||
  2855. A->getOption().matches(options::OPT_Ofast))
  2856. return true;
  2857. if (A->getOption().matches(options::OPT_O0))
  2858. return false;
  2859. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  2860. // Vectorize -Os.
  2861. StringRef S(A->getValue());
  2862. if (S == "s")
  2863. return true;
  2864. // Don't vectorize -Oz, unless it's the slp vectorizer.
  2865. if (S == "z")
  2866. return isSlpVec;
  2867. unsigned OptLevel = 0;
  2868. if (S.getAsInteger(10, OptLevel))
  2869. return false;
  2870. return OptLevel > 1;
  2871. }
  2872. return false;
  2873. }
  2874. /// Add -x lang to \p CmdArgs for \p Input.
  2875. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  2876. ArgStringList &CmdArgs) {
  2877. // When using -verify-pch, we don't want to provide the type
  2878. // 'precompiled-header' if it was inferred from the file extension
  2879. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  2880. return;
  2881. CmdArgs.push_back("-x");
  2882. if (Args.hasArg(options::OPT_rewrite_objc))
  2883. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  2884. else
  2885. CmdArgs.push_back(types::getTypeName(Input.getType()));
  2886. }
  2887. static VersionTuple getMSCompatibilityVersion(unsigned Version) {
  2888. if (Version < 100)
  2889. return VersionTuple(Version);
  2890. if (Version < 10000)
  2891. return VersionTuple(Version / 100, Version % 100);
  2892. unsigned Build = 0, Factor = 1;
  2893. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  2894. Build = Build + (Version % 10) * Factor;
  2895. return VersionTuple(Version / 100, Version % 100, Build);
  2896. }
  2897. // Claim options we don't want to warn if they are unused. We do this for
  2898. // options that build systems might add but are unused when assembling or only
  2899. // running the preprocessor for example.
  2900. static void claimNoWarnArgs(const ArgList &Args) {
  2901. // Don't warn about unused -f(no-)?lto. This can happen when we're
  2902. // preprocessing, precompiling or assembling.
  2903. Args.ClaimAllArgs(options::OPT_flto_EQ);
  2904. Args.ClaimAllArgs(options::OPT_flto);
  2905. Args.ClaimAllArgs(options::OPT_fno_lto);
  2906. }
  2907. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  2908. #ifdef LLVM_ON_UNIX
  2909. const char *Username = getenv("LOGNAME");
  2910. #else
  2911. const char *Username = getenv("USERNAME");
  2912. #endif
  2913. if (Username) {
  2914. // Validate that LoginName can be used in a path, and get its length.
  2915. size_t Len = 0;
  2916. for (const char *P = Username; *P; ++P, ++Len) {
  2917. if (!isAlphanumeric(*P) && *P != '_') {
  2918. Username = nullptr;
  2919. break;
  2920. }
  2921. }
  2922. if (Username && Len > 0) {
  2923. Result.append(Username, Username + Len);
  2924. return;
  2925. }
  2926. }
  2927. // Fallback to user id.
  2928. #ifdef LLVM_ON_UNIX
  2929. std::string UID = llvm::utostr(getuid());
  2930. #else
  2931. // FIXME: Windows seems to have an 'SID' that might work.
  2932. std::string UID = "9999";
  2933. #endif
  2934. Result.append(UID.begin(), UID.end());
  2935. }
  2936. VersionTuple visualstudio::getMSVCVersion(const Driver *D,
  2937. const llvm::Triple &Triple,
  2938. const llvm::opt::ArgList &Args,
  2939. bool IsWindowsMSVC) {
  2940. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  2941. IsWindowsMSVC) ||
  2942. Args.hasArg(options::OPT_fmsc_version) ||
  2943. Args.hasArg(options::OPT_fms_compatibility_version)) {
  2944. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  2945. const Arg *MSCompatibilityVersion =
  2946. Args.getLastArg(options::OPT_fms_compatibility_version);
  2947. if (MSCVersion && MSCompatibilityVersion) {
  2948. if (D)
  2949. D->Diag(diag::err_drv_argument_not_allowed_with)
  2950. << MSCVersion->getAsString(Args)
  2951. << MSCompatibilityVersion->getAsString(Args);
  2952. return VersionTuple();
  2953. }
  2954. if (MSCompatibilityVersion) {
  2955. VersionTuple MSVT;
  2956. if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
  2957. D->Diag(diag::err_drv_invalid_value)
  2958. << MSCompatibilityVersion->getAsString(Args)
  2959. << MSCompatibilityVersion->getValue();
  2960. return MSVT;
  2961. }
  2962. if (MSCVersion) {
  2963. unsigned Version = 0;
  2964. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
  2965. D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
  2966. << MSCVersion->getValue();
  2967. return getMSCompatibilityVersion(Version);
  2968. }
  2969. unsigned Major, Minor, Micro;
  2970. Triple.getEnvironmentVersion(Major, Minor, Micro);
  2971. if (Major || Minor || Micro)
  2972. return VersionTuple(Major, Minor, Micro);
  2973. // FIXME: Consider bumping this to 19 (MSVC2015) soon.
  2974. return VersionTuple(18);
  2975. }
  2976. return VersionTuple();
  2977. }
  2978. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  2979. const InputInfo &Output, const ArgList &Args,
  2980. ArgStringList &CmdArgs) {
  2981. auto *ProfileGenerateArg = Args.getLastArg(
  2982. options::OPT_fprofile_instr_generate,
  2983. options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
  2984. options::OPT_fprofile_generate_EQ,
  2985. options::OPT_fno_profile_instr_generate);
  2986. if (ProfileGenerateArg &&
  2987. ProfileGenerateArg->getOption().matches(
  2988. options::OPT_fno_profile_instr_generate))
  2989. ProfileGenerateArg = nullptr;
  2990. auto *ProfileUseArg = Args.getLastArg(
  2991. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  2992. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  2993. options::OPT_fno_profile_instr_use);
  2994. if (ProfileUseArg &&
  2995. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  2996. ProfileUseArg = nullptr;
  2997. if (ProfileGenerateArg && ProfileUseArg)
  2998. D.Diag(diag::err_drv_argument_not_allowed_with)
  2999. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  3000. if (ProfileGenerateArg) {
  3001. if (ProfileGenerateArg->getOption().matches(
  3002. options::OPT_fprofile_instr_generate_EQ))
  3003. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
  3004. ProfileGenerateArg->getValue()));
  3005. else if (ProfileGenerateArg->getOption().matches(
  3006. options::OPT_fprofile_generate_EQ)) {
  3007. SmallString<128> Path(ProfileGenerateArg->getValue());
  3008. llvm::sys::path::append(Path, "default.profraw");
  3009. CmdArgs.push_back(
  3010. Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
  3011. }
  3012. // The default is to use Clang Instrumentation.
  3013. CmdArgs.push_back("-fprofile-instrument=clang");
  3014. }
  3015. if (ProfileUseArg) {
  3016. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  3017. CmdArgs.push_back(Args.MakeArgString(
  3018. Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
  3019. else if ((ProfileUseArg->getOption().matches(
  3020. options::OPT_fprofile_use_EQ) ||
  3021. ProfileUseArg->getOption().matches(
  3022. options::OPT_fprofile_instr_use))) {
  3023. SmallString<128> Path(
  3024. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  3025. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  3026. llvm::sys::path::append(Path, "default.profdata");
  3027. CmdArgs.push_back(
  3028. Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
  3029. }
  3030. }
  3031. if (Args.hasArg(options::OPT_ftest_coverage) ||
  3032. Args.hasArg(options::OPT_coverage))
  3033. CmdArgs.push_back("-femit-coverage-notes");
  3034. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3035. false) ||
  3036. Args.hasArg(options::OPT_coverage))
  3037. CmdArgs.push_back("-femit-coverage-data");
  3038. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3039. options::OPT_fno_coverage_mapping, false) &&
  3040. !ProfileGenerateArg)
  3041. D.Diag(diag::err_drv_argument_only_allowed_with)
  3042. << "-fcoverage-mapping"
  3043. << "-fprofile-instr-generate";
  3044. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3045. options::OPT_fno_coverage_mapping, false))
  3046. CmdArgs.push_back("-fcoverage-mapping");
  3047. if (C.getArgs().hasArg(options::OPT_c) ||
  3048. C.getArgs().hasArg(options::OPT_S)) {
  3049. if (Output.isFilename()) {
  3050. CmdArgs.push_back("-coverage-file");
  3051. SmallString<128> CoverageFilename;
  3052. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
  3053. CoverageFilename = FinalOutput->getValue();
  3054. } else {
  3055. CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
  3056. }
  3057. if (llvm::sys::path::is_relative(CoverageFilename)) {
  3058. SmallString<128> Pwd;
  3059. if (!llvm::sys::fs::current_path(Pwd)) {
  3060. llvm::sys::path::append(Pwd, CoverageFilename);
  3061. CoverageFilename.swap(Pwd);
  3062. }
  3063. }
  3064. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  3065. }
  3066. }
  3067. }
  3068. static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
  3069. ArgStringList &CmdArgs) {
  3070. if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3071. false) ||
  3072. Args.hasFlag(options::OPT_fprofile_generate,
  3073. options::OPT_fno_profile_instr_generate, false) ||
  3074. Args.hasFlag(options::OPT_fprofile_generate_EQ,
  3075. options::OPT_fno_profile_instr_generate, false) ||
  3076. Args.hasFlag(options::OPT_fprofile_instr_generate,
  3077. options::OPT_fno_profile_instr_generate, false) ||
  3078. Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
  3079. options::OPT_fno_profile_instr_generate, false) ||
  3080. Args.hasArg(options::OPT_fcreate_profile) ||
  3081. Args.hasArg(options::OPT_coverage)))
  3082. CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
  3083. }
  3084. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  3085. /// smooshes them together with platform defaults, to decide whether
  3086. /// this compile should be using PIC mode or not. Returns a tuple of
  3087. /// (RelocationModel, PICLevel, IsPIE).
  3088. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  3089. ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
  3090. const ArgList &Args) {
  3091. // FIXME: why does this code...and so much everywhere else, use both
  3092. // ToolChain.getTriple() and Triple?
  3093. bool PIE = ToolChain.isPIEDefault();
  3094. bool PIC = PIE || ToolChain.isPICDefault();
  3095. // The Darwin/MachO default to use PIC does not apply when using -static.
  3096. if (ToolChain.getTriple().isOSBinFormatMachO() &&
  3097. Args.hasArg(options::OPT_static))
  3098. PIE = PIC = false;
  3099. bool IsPICLevelTwo = PIC;
  3100. bool KernelOrKext =
  3101. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3102. // Android-specific defaults for PIC/PIE
  3103. if (ToolChain.getTriple().isAndroid()) {
  3104. switch (ToolChain.getArch()) {
  3105. case llvm::Triple::arm:
  3106. case llvm::Triple::armeb:
  3107. case llvm::Triple::thumb:
  3108. case llvm::Triple::thumbeb:
  3109. case llvm::Triple::aarch64:
  3110. case llvm::Triple::mips:
  3111. case llvm::Triple::mipsel:
  3112. case llvm::Triple::mips64:
  3113. case llvm::Triple::mips64el:
  3114. PIC = true; // "-fpic"
  3115. break;
  3116. case llvm::Triple::x86:
  3117. case llvm::Triple::x86_64:
  3118. PIC = true; // "-fPIC"
  3119. IsPICLevelTwo = true;
  3120. break;
  3121. default:
  3122. break;
  3123. }
  3124. }
  3125. // OpenBSD-specific defaults for PIE
  3126. if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
  3127. switch (ToolChain.getArch()) {
  3128. case llvm::Triple::mips64:
  3129. case llvm::Triple::mips64el:
  3130. case llvm::Triple::sparcel:
  3131. case llvm::Triple::x86:
  3132. case llvm::Triple::x86_64:
  3133. IsPICLevelTwo = false; // "-fpie"
  3134. break;
  3135. case llvm::Triple::ppc:
  3136. case llvm::Triple::sparc:
  3137. case llvm::Triple::sparcv9:
  3138. IsPICLevelTwo = true; // "-fPIE"
  3139. break;
  3140. default:
  3141. break;
  3142. }
  3143. }
  3144. // The last argument relating to either PIC or PIE wins, and no
  3145. // other argument is used. If the last argument is any flavor of the
  3146. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  3147. // option implicitly enables PIC at the same level.
  3148. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  3149. options::OPT_fpic, options::OPT_fno_pic,
  3150. options::OPT_fPIE, options::OPT_fno_PIE,
  3151. options::OPT_fpie, options::OPT_fno_pie);
  3152. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  3153. // is forced, then neither PIC nor PIE flags will have no effect.
  3154. if (!ToolChain.isPICDefaultForced()) {
  3155. if (LastPICArg) {
  3156. Option O = LastPICArg->getOption();
  3157. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  3158. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  3159. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  3160. PIC =
  3161. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  3162. IsPICLevelTwo =
  3163. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  3164. } else {
  3165. PIE = PIC = false;
  3166. if (Triple.isPS4CPU()) {
  3167. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  3168. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  3169. if (Model != "kernel") {
  3170. PIC = true;
  3171. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  3172. << LastPICArg->getSpelling();
  3173. }
  3174. }
  3175. }
  3176. }
  3177. }
  3178. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  3179. // PIC level would've been set to level 1, force it back to level 2 PIC
  3180. // instead.
  3181. if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
  3182. IsPICLevelTwo |= ToolChain.isPICDefault();
  3183. // This kernel flags are a trump-card: they will disable PIC/PIE
  3184. // generation, independent of the argument order.
  3185. if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  3186. !Triple.isWatchOS()))
  3187. PIC = PIE = false;
  3188. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  3189. // This is a very special mode. It trumps the other modes, almost no one
  3190. // uses it, and it isn't even valid on any OS but Darwin.
  3191. if (!ToolChain.getTriple().isOSDarwin())
  3192. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3193. << A->getSpelling() << ToolChain.getTriple().str();
  3194. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  3195. // Only a forced PIC mode can cause the actual compile to have PIC defines
  3196. // etc., no flags are sufficient. This behavior was selected to closely
  3197. // match that of llvm-gcc and Apple GCC before that.
  3198. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  3199. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
  3200. }
  3201. if (PIC)
  3202. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
  3203. return std::make_tuple(llvm::Reloc::Static, 0, false);
  3204. }
  3205. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  3206. switch (Model) {
  3207. case llvm::Reloc::Default:
  3208. return nullptr;
  3209. case llvm::Reloc::Static:
  3210. return "static";
  3211. case llvm::Reloc::PIC_:
  3212. return "pic";
  3213. case llvm::Reloc::DynamicNoPIC:
  3214. return "dynamic-no-pic";
  3215. }
  3216. llvm_unreachable("Unknown Reloc::Model kind");
  3217. }
  3218. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  3219. ArgStringList &CmdArgs) {
  3220. llvm::Reloc::Model RelocationModel;
  3221. unsigned PICLevel;
  3222. bool IsPIE;
  3223. std::tie(RelocationModel, PICLevel, IsPIE) =
  3224. ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
  3225. if (RelocationModel != llvm::Reloc::Static)
  3226. CmdArgs.push_back("-KPIC");
  3227. }
  3228. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  3229. const InputInfo &Output, const InputInfoList &Inputs,
  3230. const ArgList &Args, const char *LinkingOutput) const {
  3231. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  3232. const llvm::Triple Triple(TripleStr);
  3233. bool KernelOrKext =
  3234. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3235. const Driver &D = getToolChain().getDriver();
  3236. ArgStringList CmdArgs;
  3237. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  3238. bool IsWindowsCygnus =
  3239. getToolChain().getTriple().isWindowsCygwinEnvironment();
  3240. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  3241. bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
  3242. // Check number of inputs for sanity. We need at least one input.
  3243. assert(Inputs.size() >= 1 && "Must have at least one input.");
  3244. const InputInfo &Input = Inputs[0];
  3245. // CUDA compilation may have multiple inputs (source file + results of
  3246. // device-side compilations). All other jobs are expected to have exactly one
  3247. // input.
  3248. bool IsCuda = types::isCuda(Input.getType());
  3249. assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
  3250. // Invoke ourselves in -cc1 mode.
  3251. //
  3252. // FIXME: Implement custom jobs for internal actions.
  3253. CmdArgs.push_back("-cc1");
  3254. // Add the "effective" target triple.
  3255. CmdArgs.push_back("-triple");
  3256. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  3257. const ToolChain *AuxToolChain = nullptr;
  3258. if (IsCuda) {
  3259. // FIXME: We need a (better) way to pass information about
  3260. // particular compilation pass we're constructing here. For now we
  3261. // can check which toolchain we're using and pick the other one to
  3262. // extract the triple.
  3263. if (&getToolChain() == C.getCudaDeviceToolChain())
  3264. AuxToolChain = C.getCudaHostToolChain();
  3265. else if (&getToolChain() == C.getCudaHostToolChain())
  3266. AuxToolChain = C.getCudaDeviceToolChain();
  3267. else
  3268. llvm_unreachable("Can't figure out CUDA compilation mode.");
  3269. assert(AuxToolChain != nullptr && "No aux toolchain.");
  3270. CmdArgs.push_back("-aux-triple");
  3271. CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
  3272. }
  3273. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  3274. Triple.getArch() == llvm::Triple::thumb)) {
  3275. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  3276. unsigned Version;
  3277. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  3278. if (Version < 7)
  3279. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  3280. << TripleStr;
  3281. }
  3282. // Push all default warning arguments that are specific to
  3283. // the given target. These come before user provided warning options
  3284. // are provided.
  3285. getToolChain().addClangWarningOptions(CmdArgs);
  3286. // Select the appropriate action.
  3287. RewriteKind rewriteKind = RK_None;
  3288. if (isa<AnalyzeJobAction>(JA)) {
  3289. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  3290. CmdArgs.push_back("-analyze");
  3291. } else if (isa<MigrateJobAction>(JA)) {
  3292. CmdArgs.push_back("-migrate");
  3293. } else if (isa<PreprocessJobAction>(JA)) {
  3294. if (Output.getType() == types::TY_Dependencies)
  3295. CmdArgs.push_back("-Eonly");
  3296. else {
  3297. CmdArgs.push_back("-E");
  3298. if (Args.hasArg(options::OPT_rewrite_objc) &&
  3299. !Args.hasArg(options::OPT_g_Group))
  3300. CmdArgs.push_back("-P");
  3301. }
  3302. } else if (isa<AssembleJobAction>(JA)) {
  3303. CmdArgs.push_back("-emit-obj");
  3304. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  3305. // Also ignore explicit -force_cpusubtype_ALL option.
  3306. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  3307. } else if (isa<PrecompileJobAction>(JA)) {
  3308. // Use PCH if the user requested it.
  3309. bool UsePCH = D.CCCUsePCH;
  3310. if (JA.getType() == types::TY_Nothing)
  3311. CmdArgs.push_back("-fsyntax-only");
  3312. else if (UsePCH)
  3313. CmdArgs.push_back("-emit-pch");
  3314. else
  3315. CmdArgs.push_back("-emit-pth");
  3316. } else if (isa<VerifyPCHJobAction>(JA)) {
  3317. CmdArgs.push_back("-verify-pch");
  3318. } else {
  3319. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  3320. "Invalid action for clang tool.");
  3321. if (JA.getType() == types::TY_Nothing) {
  3322. CmdArgs.push_back("-fsyntax-only");
  3323. } else if (JA.getType() == types::TY_LLVM_IR ||
  3324. JA.getType() == types::TY_LTO_IR) {
  3325. CmdArgs.push_back("-emit-llvm");
  3326. } else if (JA.getType() == types::TY_LLVM_BC ||
  3327. JA.getType() == types::TY_LTO_BC) {
  3328. CmdArgs.push_back("-emit-llvm-bc");
  3329. } else if (JA.getType() == types::TY_PP_Asm) {
  3330. CmdArgs.push_back("-S");
  3331. } else if (JA.getType() == types::TY_AST) {
  3332. CmdArgs.push_back("-emit-pch");
  3333. } else if (JA.getType() == types::TY_ModuleFile) {
  3334. CmdArgs.push_back("-module-file-info");
  3335. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3336. CmdArgs.push_back("-rewrite-objc");
  3337. rewriteKind = RK_NonFragile;
  3338. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3339. CmdArgs.push_back("-rewrite-objc");
  3340. rewriteKind = RK_Fragile;
  3341. } else {
  3342. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3343. }
  3344. // Preserve use-list order by default when emitting bitcode, so that
  3345. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3346. // same result as running passes here. For LTO, we don't need to preserve
  3347. // the use-list order, since serialization to bitcode is part of the flow.
  3348. if (JA.getType() == types::TY_LLVM_BC)
  3349. CmdArgs.push_back("-emit-llvm-uselists");
  3350. if (D.isUsingLTO())
  3351. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3352. }
  3353. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  3354. if (!types::isLLVMIR(Input.getType()))
  3355. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3356. << "-x ir";
  3357. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  3358. }
  3359. // Embed-bitcode option.
  3360. if (C.getDriver().embedBitcodeEnabled() &&
  3361. (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
  3362. // Add flags implied by -fembed-bitcode.
  3363. Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
  3364. // Disable all llvm IR level optimizations.
  3365. CmdArgs.push_back("-disable-llvm-optzns");
  3366. }
  3367. if (C.getDriver().embedBitcodeMarkerOnly())
  3368. CmdArgs.push_back("-fembed-bitcode=marker");
  3369. // We normally speed up the clang process a bit by skipping destructors at
  3370. // exit, but when we're generating diagnostics we can rely on some of the
  3371. // cleanup.
  3372. if (!C.isForDiagnostics())
  3373. CmdArgs.push_back("-disable-free");
  3374. // Disable the verification pass in -asserts builds.
  3375. #ifdef NDEBUG
  3376. CmdArgs.push_back("-disable-llvm-verifier");
  3377. // Discard LLVM value names in -asserts builds.
  3378. CmdArgs.push_back("-discard-value-names");
  3379. #endif
  3380. // Set the main file name, so that debug info works even with
  3381. // -save-temps.
  3382. CmdArgs.push_back("-main-file-name");
  3383. CmdArgs.push_back(getBaseInputName(Args, Input));
  3384. // Some flags which affect the language (via preprocessor
  3385. // defines).
  3386. if (Args.hasArg(options::OPT_static))
  3387. CmdArgs.push_back("-static-define");
  3388. if (isa<AnalyzeJobAction>(JA)) {
  3389. // Enable region store model by default.
  3390. CmdArgs.push_back("-analyzer-store=region");
  3391. // Treat blocks as analysis entry points.
  3392. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  3393. CmdArgs.push_back("-analyzer-eagerly-assume");
  3394. // Add default argument set.
  3395. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  3396. CmdArgs.push_back("-analyzer-checker=core");
  3397. if (!IsWindowsMSVC) {
  3398. CmdArgs.push_back("-analyzer-checker=unix");
  3399. } else {
  3400. // Enable "unix" checkers that also work on Windows.
  3401. CmdArgs.push_back("-analyzer-checker=unix.API");
  3402. CmdArgs.push_back("-analyzer-checker=unix.Malloc");
  3403. CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
  3404. CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
  3405. CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
  3406. CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
  3407. }
  3408. // Disable some unix checkers for PS4.
  3409. if (IsPS4CPU) {
  3410. CmdArgs.push_back("-analyzer-disable-checker=unix.API");
  3411. CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
  3412. }
  3413. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  3414. CmdArgs.push_back("-analyzer-checker=osx");
  3415. CmdArgs.push_back("-analyzer-checker=deadcode");
  3416. if (types::isCXX(Input.getType()))
  3417. CmdArgs.push_back("-analyzer-checker=cplusplus");
  3418. if (!IsPS4CPU) {
  3419. CmdArgs.push_back(
  3420. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  3421. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  3422. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  3423. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  3424. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  3425. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  3426. }
  3427. // Default nullability checks.
  3428. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  3429. CmdArgs.push_back(
  3430. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  3431. }
  3432. // Set the output format. The default is plist, for (lame) historical
  3433. // reasons.
  3434. CmdArgs.push_back("-analyzer-output");
  3435. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  3436. CmdArgs.push_back(A->getValue());
  3437. else
  3438. CmdArgs.push_back("plist");
  3439. // Disable the presentation of standard compiler warnings when
  3440. // using --analyze. We only want to show static analyzer diagnostics
  3441. // or frontend errors.
  3442. CmdArgs.push_back("-w");
  3443. // Add -Xanalyzer arguments when running as analyzer.
  3444. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  3445. }
  3446. CheckCodeGenerationOptions(D, Args);
  3447. llvm::Reloc::Model RelocationModel;
  3448. unsigned PICLevel;
  3449. bool IsPIE;
  3450. std::tie(RelocationModel, PICLevel, IsPIE) =
  3451. ParsePICArgs(getToolChain(), Triple, Args);
  3452. const char *RMName = RelocationModelName(RelocationModel);
  3453. if (RMName) {
  3454. CmdArgs.push_back("-mrelocation-model");
  3455. CmdArgs.push_back(RMName);
  3456. }
  3457. if (PICLevel > 0) {
  3458. CmdArgs.push_back("-pic-level");
  3459. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3460. if (IsPIE) {
  3461. CmdArgs.push_back("-pie-level");
  3462. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3463. }
  3464. }
  3465. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3466. CmdArgs.push_back("-meabi");
  3467. CmdArgs.push_back(A->getValue());
  3468. }
  3469. CmdArgs.push_back("-mthread-model");
  3470. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  3471. CmdArgs.push_back(A->getValue());
  3472. else
  3473. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3474. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3475. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3476. options::OPT_fno_merge_all_constants))
  3477. CmdArgs.push_back("-fno-merge-all-constants");
  3478. // LLVM Code Generator Options.
  3479. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3480. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3481. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3482. options::OPT_frewrite_map_file_EQ)) {
  3483. CmdArgs.push_back("-frewrite-map-file");
  3484. CmdArgs.push_back(A->getValue());
  3485. A->claim();
  3486. }
  3487. }
  3488. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3489. StringRef v = A->getValue();
  3490. CmdArgs.push_back("-mllvm");
  3491. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3492. A->claim();
  3493. }
  3494. if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
  3495. true))
  3496. CmdArgs.push_back("-fno-jump-tables");
  3497. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3498. CmdArgs.push_back("-mregparm");
  3499. CmdArgs.push_back(A->getValue());
  3500. }
  3501. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3502. options::OPT_freg_struct_return)) {
  3503. if (getToolChain().getArch() != llvm::Triple::x86) {
  3504. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3505. << A->getSpelling() << getToolChain().getTriple().str();
  3506. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3507. CmdArgs.push_back("-fpcc-struct-return");
  3508. } else {
  3509. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3510. CmdArgs.push_back("-freg-struct-return");
  3511. }
  3512. }
  3513. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3514. CmdArgs.push_back("-mrtd");
  3515. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  3516. CmdArgs.push_back("-mdisable-fp-elim");
  3517. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3518. options::OPT_fno_zero_initialized_in_bss))
  3519. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3520. bool OFastEnabled = isOptimizationLevelFast(Args);
  3521. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3522. // enabled. This alias option is being used to simplify the hasFlag logic.
  3523. OptSpecifier StrictAliasingAliasOption =
  3524. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3525. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3526. // doesn't do any TBAA.
  3527. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  3528. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3529. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3530. CmdArgs.push_back("-relaxed-aliasing");
  3531. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3532. options::OPT_fno_struct_path_tbaa))
  3533. CmdArgs.push_back("-no-struct-path-tbaa");
  3534. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3535. false))
  3536. CmdArgs.push_back("-fstrict-enums");
  3537. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3538. options::OPT_fno_strict_vtable_pointers,
  3539. false))
  3540. CmdArgs.push_back("-fstrict-vtable-pointers");
  3541. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3542. options::OPT_fno_optimize_sibling_calls))
  3543. CmdArgs.push_back("-mdisable-tail-calls");
  3544. // Handle segmented stacks.
  3545. if (Args.hasArg(options::OPT_fsplit_stack))
  3546. CmdArgs.push_back("-split-stacks");
  3547. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  3548. // This alias option is being used to simplify the getLastArg logic.
  3549. OptSpecifier FastMathAliasOption =
  3550. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  3551. // Handle various floating point optimization flags, mapping them to the
  3552. // appropriate LLVM code generation flags. The pattern for all of these is to
  3553. // default off the codegen optimizations, and if any flag enables them and no
  3554. // flag disables them after the flag enabling them, enable the codegen
  3555. // optimization. This is complicated by several "umbrella" flags.
  3556. if (Arg *A = Args.getLastArg(
  3557. options::OPT_ffast_math, FastMathAliasOption,
  3558. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3559. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  3560. options::OPT_fno_honor_infinities))
  3561. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3562. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3563. A->getOption().getID() != options::OPT_fhonor_infinities)
  3564. CmdArgs.push_back("-menable-no-infs");
  3565. if (Arg *A = Args.getLastArg(
  3566. options::OPT_ffast_math, FastMathAliasOption,
  3567. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3568. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  3569. options::OPT_fno_honor_nans))
  3570. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3571. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3572. A->getOption().getID() != options::OPT_fhonor_nans)
  3573. CmdArgs.push_back("-menable-no-nans");
  3574. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  3575. bool MathErrno = getToolChain().IsMathErrnoDefault();
  3576. if (Arg *A =
  3577. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3578. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  3579. options::OPT_fno_math_errno)) {
  3580. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  3581. // However, turning *off* -ffast_math merely restores the toolchain default
  3582. // (which may be false).
  3583. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  3584. A->getOption().getID() == options::OPT_ffast_math ||
  3585. A->getOption().getID() == options::OPT_Ofast)
  3586. MathErrno = false;
  3587. else if (A->getOption().getID() == options::OPT_fmath_errno)
  3588. MathErrno = true;
  3589. }
  3590. if (MathErrno)
  3591. CmdArgs.push_back("-fmath-errno");
  3592. // There are several flags which require disabling very specific
  3593. // optimizations. Any of these being disabled forces us to turn off the
  3594. // entire set of LLVM optimizations, so collect them through all the flag
  3595. // madness.
  3596. bool AssociativeMath = false;
  3597. if (Arg *A = Args.getLastArg(
  3598. options::OPT_ffast_math, FastMathAliasOption,
  3599. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3600. options::OPT_fno_unsafe_math_optimizations,
  3601. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  3602. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3603. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3604. A->getOption().getID() != options::OPT_fno_associative_math)
  3605. AssociativeMath = true;
  3606. bool ReciprocalMath = false;
  3607. if (Arg *A = Args.getLastArg(
  3608. options::OPT_ffast_math, FastMathAliasOption,
  3609. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3610. options::OPT_fno_unsafe_math_optimizations,
  3611. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  3612. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3613. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3614. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  3615. ReciprocalMath = true;
  3616. bool SignedZeros = true;
  3617. if (Arg *A = Args.getLastArg(
  3618. options::OPT_ffast_math, FastMathAliasOption,
  3619. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3620. options::OPT_fno_unsafe_math_optimizations,
  3621. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  3622. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3623. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3624. A->getOption().getID() != options::OPT_fsigned_zeros)
  3625. SignedZeros = false;
  3626. bool TrappingMath = true;
  3627. if (Arg *A = Args.getLastArg(
  3628. options::OPT_ffast_math, FastMathAliasOption,
  3629. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3630. options::OPT_fno_unsafe_math_optimizations,
  3631. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  3632. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3633. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3634. A->getOption().getID() != options::OPT_ftrapping_math)
  3635. TrappingMath = false;
  3636. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  3637. !TrappingMath)
  3638. CmdArgs.push_back("-menable-unsafe-fp-math");
  3639. if (!SignedZeros)
  3640. CmdArgs.push_back("-fno-signed-zeros");
  3641. if (ReciprocalMath)
  3642. CmdArgs.push_back("-freciprocal-math");
  3643. // Validate and pass through -fp-contract option.
  3644. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3645. options::OPT_fno_fast_math,
  3646. options::OPT_ffp_contract)) {
  3647. if (A->getOption().getID() == options::OPT_ffp_contract) {
  3648. StringRef Val = A->getValue();
  3649. if (Val == "fast" || Val == "on" || Val == "off") {
  3650. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  3651. } else {
  3652. D.Diag(diag::err_drv_unsupported_option_argument)
  3653. << A->getOption().getName() << Val;
  3654. }
  3655. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  3656. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  3657. // If fast-math is set then set the fp-contract mode to fast.
  3658. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  3659. }
  3660. }
  3661. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  3662. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  3663. // and if we find them, tell the frontend to provide the appropriate
  3664. // preprocessor macros. This is distinct from enabling any optimizations as
  3665. // these options induce language changes which must survive serialization
  3666. // and deserialization, etc.
  3667. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3668. options::OPT_fno_fast_math))
  3669. if (!A->getOption().matches(options::OPT_fno_fast_math))
  3670. CmdArgs.push_back("-ffast-math");
  3671. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  3672. options::OPT_fno_fast_math))
  3673. if (A->getOption().matches(options::OPT_ffinite_math_only))
  3674. CmdArgs.push_back("-ffinite-math-only");
  3675. // Decide whether to use verbose asm. Verbose assembly is the default on
  3676. // toolchains which have the integrated assembler on by default.
  3677. bool IsIntegratedAssemblerDefault =
  3678. getToolChain().IsIntegratedAssemblerDefault();
  3679. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3680. IsIntegratedAssemblerDefault) ||
  3681. Args.hasArg(options::OPT_dA))
  3682. CmdArgs.push_back("-masm-verbose");
  3683. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  3684. IsIntegratedAssemblerDefault))
  3685. CmdArgs.push_back("-no-integrated-as");
  3686. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3687. CmdArgs.push_back("-mdebug-pass");
  3688. CmdArgs.push_back("Structure");
  3689. }
  3690. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3691. CmdArgs.push_back("-mdebug-pass");
  3692. CmdArgs.push_back("Arguments");
  3693. }
  3694. // Enable -mconstructor-aliases except on darwin, where we have to work around
  3695. // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
  3696. // aliases aren't supported.
  3697. if (!getToolChain().getTriple().isOSDarwin() &&
  3698. !getToolChain().getTriple().isNVPTX())
  3699. CmdArgs.push_back("-mconstructor-aliases");
  3700. // Darwin's kernel doesn't support guard variables; just die if we
  3701. // try to use them.
  3702. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  3703. CmdArgs.push_back("-fforbid-guard-variables");
  3704. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  3705. false)) {
  3706. CmdArgs.push_back("-mms-bitfields");
  3707. }
  3708. // This is a coarse approximation of what llvm-gcc actually does, both
  3709. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3710. // complicated ways.
  3711. bool AsynchronousUnwindTables =
  3712. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3713. options::OPT_fno_asynchronous_unwind_tables,
  3714. (getToolChain().IsUnwindTablesDefault() ||
  3715. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  3716. !KernelOrKext);
  3717. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3718. AsynchronousUnwindTables))
  3719. CmdArgs.push_back("-munwind-tables");
  3720. getToolChain().addClangTargetOptions(Args, CmdArgs);
  3721. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  3722. CmdArgs.push_back("-mlimit-float-precision");
  3723. CmdArgs.push_back(A->getValue());
  3724. }
  3725. // FIXME: Handle -mtune=.
  3726. (void)Args.hasArg(options::OPT_mtune_EQ);
  3727. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3728. CmdArgs.push_back("-mcode-model");
  3729. CmdArgs.push_back(A->getValue());
  3730. }
  3731. // Add the target cpu
  3732. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3733. if (!CPU.empty()) {
  3734. CmdArgs.push_back("-target-cpu");
  3735. CmdArgs.push_back(Args.MakeArgString(CPU));
  3736. }
  3737. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  3738. CmdArgs.push_back("-mfpmath");
  3739. CmdArgs.push_back(A->getValue());
  3740. }
  3741. // Add the target features
  3742. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  3743. // Add target specific flags.
  3744. switch (getToolChain().getArch()) {
  3745. default:
  3746. break;
  3747. case llvm::Triple::arm:
  3748. case llvm::Triple::armeb:
  3749. case llvm::Triple::thumb:
  3750. case llvm::Triple::thumbeb:
  3751. // Use the effective triple, which takes into account the deployment target.
  3752. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  3753. break;
  3754. case llvm::Triple::aarch64:
  3755. case llvm::Triple::aarch64_be:
  3756. AddAArch64TargetArgs(Args, CmdArgs);
  3757. break;
  3758. case llvm::Triple::mips:
  3759. case llvm::Triple::mipsel:
  3760. case llvm::Triple::mips64:
  3761. case llvm::Triple::mips64el:
  3762. AddMIPSTargetArgs(Args, CmdArgs);
  3763. break;
  3764. case llvm::Triple::ppc:
  3765. case llvm::Triple::ppc64:
  3766. case llvm::Triple::ppc64le:
  3767. AddPPCTargetArgs(Args, CmdArgs);
  3768. break;
  3769. case llvm::Triple::sparc:
  3770. case llvm::Triple::sparcel:
  3771. case llvm::Triple::sparcv9:
  3772. AddSparcTargetArgs(Args, CmdArgs);
  3773. break;
  3774. case llvm::Triple::systemz:
  3775. AddSystemZTargetArgs(Args, CmdArgs);
  3776. break;
  3777. case llvm::Triple::x86:
  3778. case llvm::Triple::x86_64:
  3779. AddX86TargetArgs(Args, CmdArgs);
  3780. break;
  3781. case llvm::Triple::lanai:
  3782. AddLanaiTargetArgs(Args, CmdArgs);
  3783. break;
  3784. case llvm::Triple::hexagon:
  3785. AddHexagonTargetArgs(Args, CmdArgs);
  3786. break;
  3787. case llvm::Triple::wasm32:
  3788. case llvm::Triple::wasm64:
  3789. AddWebAssemblyTargetArgs(Args, CmdArgs);
  3790. break;
  3791. }
  3792. // The 'g' groups options involve a somewhat intricate sequence of decisions
  3793. // about what to pass from the driver to the frontend, but by the time they
  3794. // reach cc1 they've been factored into three well-defined orthogonal choices:
  3795. // * what level of debug info to generate
  3796. // * what dwarf version to write
  3797. // * what debugger tuning to use
  3798. // This avoids having to monkey around further in cc1 other than to disable
  3799. // codeview if not running in a Windows environment. Perhaps even that
  3800. // decision should be made in the driver as well though.
  3801. unsigned DwarfVersion = 0;
  3802. llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
  3803. // These two are potentially updated by AddClangCLArgs.
  3804. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  3805. bool EmitCodeView = false;
  3806. // Add clang-cl arguments.
  3807. types::ID InputType = Input.getType();
  3808. if (getToolChain().getDriver().IsCLMode())
  3809. AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
  3810. // Pass the linker version in use.
  3811. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  3812. CmdArgs.push_back("-target-linker-version");
  3813. CmdArgs.push_back(A->getValue());
  3814. }
  3815. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  3816. CmdArgs.push_back("-momit-leaf-frame-pointer");
  3817. // Explicitly error on some things we know we don't support and can't just
  3818. // ignore.
  3819. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  3820. Arg *Unsupported;
  3821. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  3822. getToolChain().getArch() == llvm::Triple::x86) {
  3823. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  3824. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  3825. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  3826. << Unsupported->getOption().getName();
  3827. }
  3828. }
  3829. Args.AddAllArgs(CmdArgs, options::OPT_v);
  3830. Args.AddLastArg(CmdArgs, options::OPT_H);
  3831. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  3832. CmdArgs.push_back("-header-include-file");
  3833. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  3834. : "-");
  3835. }
  3836. Args.AddLastArg(CmdArgs, options::OPT_P);
  3837. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  3838. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  3839. CmdArgs.push_back("-diagnostic-log-file");
  3840. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  3841. : "-");
  3842. }
  3843. Args.ClaimAllArgs(options::OPT_g_Group);
  3844. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  3845. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  3846. // If the last option explicitly specified a debug-info level, use it.
  3847. if (A->getOption().matches(options::OPT_gN_Group)) {
  3848. DebugInfoKind = DebugLevelToInfoKind(*A);
  3849. // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
  3850. // But -gsplit-dwarf is not a g_group option, hence we have to check the
  3851. // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
  3852. if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
  3853. A->getIndex() > SplitDwarfArg->getIndex())
  3854. SplitDwarfArg = nullptr;
  3855. } else
  3856. // For any other 'g' option, use Limited.
  3857. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3858. }
  3859. // If a debugger tuning argument appeared, remember it.
  3860. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  3861. options::OPT_ggdbN_Group)) {
  3862. if (A->getOption().matches(options::OPT_glldb))
  3863. DebuggerTuning = llvm::DebuggerKind::LLDB;
  3864. else if (A->getOption().matches(options::OPT_gsce))
  3865. DebuggerTuning = llvm::DebuggerKind::SCE;
  3866. else
  3867. DebuggerTuning = llvm::DebuggerKind::GDB;
  3868. }
  3869. // If a -gdwarf argument appeared, remember it.
  3870. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  3871. options::OPT_gdwarf_4, options::OPT_gdwarf_5))
  3872. DwarfVersion = DwarfVersionNum(A->getSpelling());
  3873. // Forward -gcodeview.
  3874. // 'EmitCodeView might have been set by CL-compatibility argument parsing.
  3875. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  3876. // DwarfVersion remains at 0 if no explicit choice was made.
  3877. CmdArgs.push_back("-gcodeview");
  3878. } else if (DwarfVersion == 0 &&
  3879. DebugInfoKind != codegenoptions::NoDebugInfo) {
  3880. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  3881. }
  3882. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  3883. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  3884. // PS4 defaults to no column info
  3885. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  3886. /*Default=*/ !IsPS4CPU))
  3887. CmdArgs.push_back("-dwarf-column-info");
  3888. // FIXME: Move backend command line options to the module.
  3889. if (Args.hasArg(options::OPT_gmodules)) {
  3890. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3891. CmdArgs.push_back("-dwarf-ext-refs");
  3892. CmdArgs.push_back("-fmodule-format=obj");
  3893. }
  3894. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  3895. // splitting and extraction.
  3896. // FIXME: Currently only works on Linux.
  3897. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  3898. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3899. CmdArgs.push_back("-backend-option");
  3900. CmdArgs.push_back("-split-dwarf=Enable");
  3901. }
  3902. // After we've dealt with all combinations of things that could
  3903. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  3904. // figure out if we need to "upgrade" it to standalone debug info.
  3905. // We parse these two '-f' options whether or not they will be used,
  3906. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  3907. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  3908. options::OPT_fno_standalone_debug,
  3909. getToolChain().GetDefaultStandaloneDebug());
  3910. if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
  3911. DebugInfoKind = codegenoptions::FullDebugInfo;
  3912. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  3913. DebuggerTuning);
  3914. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  3915. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  3916. CmdArgs.push_back("-backend-option");
  3917. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  3918. }
  3919. // -gdwarf-aranges turns on the emission of the aranges section in the
  3920. // backend.
  3921. // Always enabled on the PS4.
  3922. if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
  3923. CmdArgs.push_back("-backend-option");
  3924. CmdArgs.push_back("-generate-arange-section");
  3925. }
  3926. if (Args.hasFlag(options::OPT_fdebug_types_section,
  3927. options::OPT_fno_debug_types_section, false)) {
  3928. CmdArgs.push_back("-backend-option");
  3929. CmdArgs.push_back("-generate-type-units");
  3930. }
  3931. // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
  3932. // default.
  3933. bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
  3934. Triple.getArch() == llvm::Triple::wasm32 ||
  3935. Triple.getArch() == llvm::Triple::wasm64;
  3936. if (Args.hasFlag(options::OPT_ffunction_sections,
  3937. options::OPT_fno_function_sections, UseSeparateSections)) {
  3938. CmdArgs.push_back("-ffunction-sections");
  3939. }
  3940. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  3941. UseSeparateSections)) {
  3942. CmdArgs.push_back("-fdata-sections");
  3943. }
  3944. if (!Args.hasFlag(options::OPT_funique_section_names,
  3945. options::OPT_fno_unique_section_names, true))
  3946. CmdArgs.push_back("-fno-unique-section-names");
  3947. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  3948. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  3949. // Add runtime flag for PS4 when PGO or Coverage are enabled.
  3950. if (getToolChain().getTriple().isPS4CPU())
  3951. addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
  3952. // Pass options for controlling the default header search paths.
  3953. if (Args.hasArg(options::OPT_nostdinc)) {
  3954. CmdArgs.push_back("-nostdsysteminc");
  3955. CmdArgs.push_back("-nobuiltininc");
  3956. } else {
  3957. if (Args.hasArg(options::OPT_nostdlibinc))
  3958. CmdArgs.push_back("-nostdsysteminc");
  3959. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  3960. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  3961. }
  3962. // Pass the path to compiler resource files.
  3963. CmdArgs.push_back("-resource-dir");
  3964. CmdArgs.push_back(D.ResourceDir.c_str());
  3965. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  3966. bool ARCMTEnabled = false;
  3967. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  3968. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  3969. options::OPT_ccc_arcmt_modify,
  3970. options::OPT_ccc_arcmt_migrate)) {
  3971. ARCMTEnabled = true;
  3972. switch (A->getOption().getID()) {
  3973. default:
  3974. llvm_unreachable("missed a case");
  3975. case options::OPT_ccc_arcmt_check:
  3976. CmdArgs.push_back("-arcmt-check");
  3977. break;
  3978. case options::OPT_ccc_arcmt_modify:
  3979. CmdArgs.push_back("-arcmt-modify");
  3980. break;
  3981. case options::OPT_ccc_arcmt_migrate:
  3982. CmdArgs.push_back("-arcmt-migrate");
  3983. CmdArgs.push_back("-mt-migrate-directory");
  3984. CmdArgs.push_back(A->getValue());
  3985. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  3986. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  3987. break;
  3988. }
  3989. }
  3990. } else {
  3991. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  3992. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  3993. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  3994. }
  3995. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  3996. if (ARCMTEnabled) {
  3997. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  3998. << "-ccc-arcmt-migrate";
  3999. }
  4000. CmdArgs.push_back("-mt-migrate-directory");
  4001. CmdArgs.push_back(A->getValue());
  4002. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  4003. options::OPT_objcmt_migrate_subscripting,
  4004. options::OPT_objcmt_migrate_property)) {
  4005. // None specified, means enable them all.
  4006. CmdArgs.push_back("-objcmt-migrate-literals");
  4007. CmdArgs.push_back("-objcmt-migrate-subscripting");
  4008. CmdArgs.push_back("-objcmt-migrate-property");
  4009. } else {
  4010. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4011. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4012. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4013. }
  4014. } else {
  4015. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4016. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4017. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4018. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  4019. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  4020. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  4021. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  4022. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  4023. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  4024. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  4025. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  4026. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  4027. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  4028. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  4029. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  4030. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  4031. }
  4032. // Add preprocessing options like -I, -D, etc. if we are using the
  4033. // preprocessor.
  4034. //
  4035. // FIXME: Support -fpreprocessed
  4036. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  4037. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
  4038. AuxToolChain);
  4039. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  4040. // that "The compiler can only warn and ignore the option if not recognized".
  4041. // When building with ccache, it will pass -D options to clang even on
  4042. // preprocessed inputs and configure concludes that -fPIC is not supported.
  4043. Args.ClaimAllArgs(options::OPT_D);
  4044. // Manually translate -O4 to -O3; let clang reject others.
  4045. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  4046. if (A->getOption().matches(options::OPT_O4)) {
  4047. CmdArgs.push_back("-O3");
  4048. D.Diag(diag::warn_O4_is_O3);
  4049. } else {
  4050. A->render(Args, CmdArgs);
  4051. }
  4052. }
  4053. // Warn about ignored options to clang.
  4054. for (const Arg *A :
  4055. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  4056. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  4057. A->claim();
  4058. }
  4059. claimNoWarnArgs(Args);
  4060. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  4061. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  4062. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  4063. CmdArgs.push_back("-pedantic");
  4064. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  4065. Args.AddLastArg(CmdArgs, options::OPT_w);
  4066. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  4067. // (-ansi is equivalent to -std=c89 or -std=c++98).
  4068. //
  4069. // If a std is supplied, only add -trigraphs if it follows the
  4070. // option.
  4071. bool ImplyVCPPCXXVer = false;
  4072. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  4073. if (Std->getOption().matches(options::OPT_ansi))
  4074. if (types::isCXX(InputType))
  4075. CmdArgs.push_back("-std=c++98");
  4076. else
  4077. CmdArgs.push_back("-std=c89");
  4078. else
  4079. Std->render(Args, CmdArgs);
  4080. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  4081. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  4082. options::OPT_ftrigraphs,
  4083. options::OPT_fno_trigraphs))
  4084. if (A != Std)
  4085. A->render(Args, CmdArgs);
  4086. } else {
  4087. // Honor -std-default.
  4088. //
  4089. // FIXME: Clang doesn't correctly handle -std= when the input language
  4090. // doesn't match. For the time being just ignore this for C++ inputs;
  4091. // eventually we want to do all the standard defaulting here instead of
  4092. // splitting it between the driver and clang -cc1.
  4093. if (!types::isCXX(InputType))
  4094. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  4095. /*Joined=*/true);
  4096. else if (IsWindowsMSVC)
  4097. ImplyVCPPCXXVer = true;
  4098. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  4099. options::OPT_fno_trigraphs);
  4100. }
  4101. // GCC's behavior for -Wwrite-strings is a bit strange:
  4102. // * In C, this "warning flag" changes the types of string literals from
  4103. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  4104. // for the discarded qualifier.
  4105. // * In C++, this is just a normal warning flag.
  4106. //
  4107. // Implementing this warning correctly in C is hard, so we follow GCC's
  4108. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  4109. // a non-const char* in C, rather than using this crude hack.
  4110. if (!types::isCXX(InputType)) {
  4111. // FIXME: This should behave just like a warning flag, and thus should also
  4112. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  4113. Arg *WriteStrings =
  4114. Args.getLastArg(options::OPT_Wwrite_strings,
  4115. options::OPT_Wno_write_strings, options::OPT_w);
  4116. if (WriteStrings &&
  4117. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  4118. CmdArgs.push_back("-fconst-strings");
  4119. }
  4120. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  4121. // during C++ compilation, which it is by default. GCC keeps this define even
  4122. // in the presence of '-w', match this behavior bug-for-bug.
  4123. if (types::isCXX(InputType) &&
  4124. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  4125. true)) {
  4126. CmdArgs.push_back("-fdeprecated-macro");
  4127. }
  4128. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  4129. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  4130. if (Asm->getOption().matches(options::OPT_fasm))
  4131. CmdArgs.push_back("-fgnu-keywords");
  4132. else
  4133. CmdArgs.push_back("-fno-gnu-keywords");
  4134. }
  4135. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  4136. CmdArgs.push_back("-fno-dwarf-directory-asm");
  4137. if (ShouldDisableAutolink(Args, getToolChain()))
  4138. CmdArgs.push_back("-fno-autolink");
  4139. // Add in -fdebug-compilation-dir if necessary.
  4140. addDebugCompDirArg(Args, CmdArgs);
  4141. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  4142. StringRef Map = A->getValue();
  4143. if (Map.find('=') == StringRef::npos)
  4144. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  4145. else
  4146. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  4147. A->claim();
  4148. }
  4149. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  4150. options::OPT_ftemplate_depth_EQ)) {
  4151. CmdArgs.push_back("-ftemplate-depth");
  4152. CmdArgs.push_back(A->getValue());
  4153. }
  4154. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  4155. CmdArgs.push_back("-foperator-arrow-depth");
  4156. CmdArgs.push_back(A->getValue());
  4157. }
  4158. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  4159. CmdArgs.push_back("-fconstexpr-depth");
  4160. CmdArgs.push_back(A->getValue());
  4161. }
  4162. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  4163. CmdArgs.push_back("-fconstexpr-steps");
  4164. CmdArgs.push_back(A->getValue());
  4165. }
  4166. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  4167. CmdArgs.push_back("-fbracket-depth");
  4168. CmdArgs.push_back(A->getValue());
  4169. }
  4170. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  4171. options::OPT_Wlarge_by_value_copy_def)) {
  4172. if (A->getNumValues()) {
  4173. StringRef bytes = A->getValue();
  4174. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  4175. } else
  4176. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  4177. }
  4178. if (Args.hasArg(options::OPT_relocatable_pch))
  4179. CmdArgs.push_back("-relocatable-pch");
  4180. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  4181. CmdArgs.push_back("-fconstant-string-class");
  4182. CmdArgs.push_back(A->getValue());
  4183. }
  4184. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  4185. CmdArgs.push_back("-ftabstop");
  4186. CmdArgs.push_back(A->getValue());
  4187. }
  4188. CmdArgs.push_back("-ferror-limit");
  4189. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  4190. CmdArgs.push_back(A->getValue());
  4191. else
  4192. CmdArgs.push_back("19");
  4193. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  4194. CmdArgs.push_back("-fmacro-backtrace-limit");
  4195. CmdArgs.push_back(A->getValue());
  4196. }
  4197. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  4198. CmdArgs.push_back("-ftemplate-backtrace-limit");
  4199. CmdArgs.push_back(A->getValue());
  4200. }
  4201. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  4202. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  4203. CmdArgs.push_back(A->getValue());
  4204. }
  4205. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  4206. CmdArgs.push_back("-fspell-checking-limit");
  4207. CmdArgs.push_back(A->getValue());
  4208. }
  4209. // Pass -fmessage-length=.
  4210. CmdArgs.push_back("-fmessage-length");
  4211. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  4212. CmdArgs.push_back(A->getValue());
  4213. } else {
  4214. // If -fmessage-length=N was not specified, determine whether this is a
  4215. // terminal and, if so, implicitly define -fmessage-length appropriately.
  4216. unsigned N = llvm::sys::Process::StandardErrColumns();
  4217. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  4218. }
  4219. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  4220. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  4221. options::OPT_fvisibility_ms_compat)) {
  4222. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  4223. CmdArgs.push_back("-fvisibility");
  4224. CmdArgs.push_back(A->getValue());
  4225. } else {
  4226. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  4227. CmdArgs.push_back("-fvisibility");
  4228. CmdArgs.push_back("hidden");
  4229. CmdArgs.push_back("-ftype-visibility");
  4230. CmdArgs.push_back("default");
  4231. }
  4232. }
  4233. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  4234. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  4235. // -fhosted is default.
  4236. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  4237. KernelOrKext)
  4238. CmdArgs.push_back("-ffreestanding");
  4239. // Forward -f (flag) options which we can pass directly.
  4240. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  4241. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  4242. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  4243. // Emulated TLS is enabled by default on Android, and can be enabled manually
  4244. // with -femulated-tls.
  4245. bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
  4246. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  4247. EmulatedTLSDefault))
  4248. CmdArgs.push_back("-femulated-tls");
  4249. // AltiVec-like language extensions aren't relevant for assembling.
  4250. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  4251. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  4252. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  4253. }
  4254. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  4255. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  4256. // Forward flags for OpenMP
  4257. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  4258. options::OPT_fno_openmp, false))
  4259. switch (getOpenMPRuntime(getToolChain(), Args)) {
  4260. case OMPRT_OMP:
  4261. case OMPRT_IOMP5:
  4262. // Clang can generate useful OpenMP code for these two runtime libraries.
  4263. CmdArgs.push_back("-fopenmp");
  4264. // If no option regarding the use of TLS in OpenMP codegeneration is
  4265. // given, decide a default based on the target. Otherwise rely on the
  4266. // options and pass the right information to the frontend.
  4267. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  4268. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  4269. CmdArgs.push_back("-fnoopenmp-use-tls");
  4270. break;
  4271. default:
  4272. // By default, if Clang doesn't know how to generate useful OpenMP code
  4273. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  4274. // down to the actual compilation.
  4275. // FIXME: It would be better to have a mode which *only* omits IR
  4276. // generation based on the OpenMP support so that we get consistent
  4277. // semantic analysis, etc.
  4278. break;
  4279. }
  4280. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  4281. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  4282. // Report an error for -faltivec on anything other than PowerPC.
  4283. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  4284. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  4285. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  4286. Arch == llvm::Triple::ppc64le))
  4287. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  4288. << "ppc/ppc64/ppc64le";
  4289. }
  4290. // -fzvector is incompatible with -faltivec.
  4291. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  4292. if (Args.hasArg(options::OPT_faltivec))
  4293. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4294. << "-faltivec";
  4295. if (getToolChain().SupportsProfiling())
  4296. Args.AddLastArg(CmdArgs, options::OPT_pg);
  4297. // -flax-vector-conversions is default.
  4298. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  4299. options::OPT_fno_lax_vector_conversions))
  4300. CmdArgs.push_back("-fno-lax-vector-conversions");
  4301. if (Args.getLastArg(options::OPT_fapple_kext) ||
  4302. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  4303. CmdArgs.push_back("-fapple-kext");
  4304. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  4305. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  4306. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  4307. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  4308. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  4309. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  4310. CmdArgs.push_back("-ftrapv-handler");
  4311. CmdArgs.push_back(A->getValue());
  4312. }
  4313. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  4314. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  4315. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  4316. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  4317. if (A->getOption().matches(options::OPT_fwrapv))
  4318. CmdArgs.push_back("-fwrapv");
  4319. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  4320. options::OPT_fno_strict_overflow)) {
  4321. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  4322. CmdArgs.push_back("-fwrapv");
  4323. }
  4324. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  4325. options::OPT_fno_reroll_loops))
  4326. if (A->getOption().matches(options::OPT_freroll_loops))
  4327. CmdArgs.push_back("-freroll-loops");
  4328. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  4329. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  4330. options::OPT_fno_unroll_loops);
  4331. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  4332. // -stack-protector=0 is default.
  4333. unsigned StackProtectorLevel = 0;
  4334. if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  4335. options::OPT_fstack_protector_all,
  4336. options::OPT_fstack_protector_strong,
  4337. options::OPT_fstack_protector)) {
  4338. if (A->getOption().matches(options::OPT_fstack_protector)) {
  4339. StackProtectorLevel = std::max<unsigned>(
  4340. LangOptions::SSPOn,
  4341. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  4342. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  4343. StackProtectorLevel = LangOptions::SSPStrong;
  4344. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  4345. StackProtectorLevel = LangOptions::SSPReq;
  4346. } else {
  4347. StackProtectorLevel =
  4348. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  4349. }
  4350. if (StackProtectorLevel) {
  4351. CmdArgs.push_back("-stack-protector");
  4352. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  4353. }
  4354. // --param ssp-buffer-size=
  4355. for (const Arg *A : Args.filtered(options::OPT__param)) {
  4356. StringRef Str(A->getValue());
  4357. if (Str.startswith("ssp-buffer-size=")) {
  4358. if (StackProtectorLevel) {
  4359. CmdArgs.push_back("-stack-protector-buffer-size");
  4360. // FIXME: Verify the argument is a valid integer.
  4361. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  4362. }
  4363. A->claim();
  4364. }
  4365. }
  4366. // Translate -mstackrealign
  4367. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  4368. false))
  4369. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  4370. if (Args.hasArg(options::OPT_mstack_alignment)) {
  4371. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  4372. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  4373. }
  4374. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  4375. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  4376. if (!Size.empty())
  4377. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  4378. else
  4379. CmdArgs.push_back("-mstack-probe-size=0");
  4380. }
  4381. switch (getToolChain().getArch()) {
  4382. case llvm::Triple::aarch64:
  4383. case llvm::Triple::aarch64_be:
  4384. case llvm::Triple::arm:
  4385. case llvm::Triple::armeb:
  4386. case llvm::Triple::thumb:
  4387. case llvm::Triple::thumbeb:
  4388. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  4389. break;
  4390. default:
  4391. break;
  4392. }
  4393. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4394. options::OPT_mno_restrict_it)) {
  4395. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4396. CmdArgs.push_back("-backend-option");
  4397. CmdArgs.push_back("-arm-restrict-it");
  4398. } else {
  4399. CmdArgs.push_back("-backend-option");
  4400. CmdArgs.push_back("-arm-no-restrict-it");
  4401. }
  4402. } else if (Triple.isOSWindows() &&
  4403. (Triple.getArch() == llvm::Triple::arm ||
  4404. Triple.getArch() == llvm::Triple::thumb)) {
  4405. // Windows on ARM expects restricted IT blocks
  4406. CmdArgs.push_back("-backend-option");
  4407. CmdArgs.push_back("-arm-restrict-it");
  4408. }
  4409. // Forward -f options with positive and negative forms; we translate
  4410. // these by hand.
  4411. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  4412. StringRef fname = A->getValue();
  4413. if (!llvm::sys::fs::exists(fname))
  4414. D.Diag(diag::err_drv_no_such_file) << fname;
  4415. else
  4416. A->render(Args, CmdArgs);
  4417. }
  4418. // -fbuiltin is default unless -mkernel is used.
  4419. bool UseBuiltins =
  4420. Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  4421. !Args.hasArg(options::OPT_mkernel));
  4422. if (!UseBuiltins)
  4423. CmdArgs.push_back("-fno-builtin");
  4424. // -ffreestanding implies -fno-builtin.
  4425. if (Args.hasArg(options::OPT_ffreestanding))
  4426. UseBuiltins = false;
  4427. // Process the -fno-builtin-* options.
  4428. for (const auto &Arg : Args) {
  4429. const Option &O = Arg->getOption();
  4430. if (!O.matches(options::OPT_fno_builtin_))
  4431. continue;
  4432. Arg->claim();
  4433. // If -fno-builtin is specified, then there's no need to pass the option to
  4434. // the frontend.
  4435. if (!UseBuiltins)
  4436. continue;
  4437. StringRef FuncName = Arg->getValue();
  4438. CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
  4439. }
  4440. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4441. options::OPT_fno_assume_sane_operator_new))
  4442. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4443. // -fblocks=0 is default.
  4444. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  4445. getToolChain().IsBlocksDefault()) ||
  4446. (Args.hasArg(options::OPT_fgnu_runtime) &&
  4447. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  4448. !Args.hasArg(options::OPT_fno_blocks))) {
  4449. CmdArgs.push_back("-fblocks");
  4450. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  4451. !getToolChain().hasBlocksRuntime())
  4452. CmdArgs.push_back("-fblocks-runtime-optional");
  4453. }
  4454. // -fmodules enables the use of precompiled modules (off by default).
  4455. // Users can pass -fno-cxx-modules to turn off modules support for
  4456. // C++/Objective-C++ programs.
  4457. bool HaveModules = false;
  4458. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  4459. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  4460. options::OPT_fno_cxx_modules, true);
  4461. if (AllowedInCXX || !types::isCXX(InputType)) {
  4462. CmdArgs.push_back("-fmodules");
  4463. HaveModules = true;
  4464. }
  4465. }
  4466. // -fmodule-maps enables implicit reading of module map files. By default,
  4467. // this is enabled if we are using precompiled modules.
  4468. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  4469. options::OPT_fno_implicit_module_maps, HaveModules)) {
  4470. CmdArgs.push_back("-fimplicit-module-maps");
  4471. }
  4472. // -fmodules-decluse checks that modules used are declared so (off by
  4473. // default).
  4474. if (Args.hasFlag(options::OPT_fmodules_decluse,
  4475. options::OPT_fno_modules_decluse, false)) {
  4476. CmdArgs.push_back("-fmodules-decluse");
  4477. }
  4478. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  4479. // all #included headers are part of modules.
  4480. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  4481. options::OPT_fno_modules_strict_decluse, false)) {
  4482. CmdArgs.push_back("-fmodules-strict-decluse");
  4483. }
  4484. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  4485. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  4486. options::OPT_fno_implicit_modules)) {
  4487. CmdArgs.push_back("-fno-implicit-modules");
  4488. } else if (HaveModules) {
  4489. // -fmodule-cache-path specifies where our implicitly-built module files
  4490. // should be written.
  4491. SmallString<128> Path;
  4492. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  4493. Path = A->getValue();
  4494. if (C.isForDiagnostics()) {
  4495. // When generating crash reports, we want to emit the modules along with
  4496. // the reproduction sources, so we ignore any provided module path.
  4497. Path = Output.getFilename();
  4498. llvm::sys::path::replace_extension(Path, ".cache");
  4499. llvm::sys::path::append(Path, "modules");
  4500. } else if (Path.empty()) {
  4501. // No module path was provided: use the default.
  4502. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  4503. llvm::sys::path::append(Path, "org.llvm.clang.");
  4504. appendUserToPath(Path);
  4505. llvm::sys::path::append(Path, "ModuleCache");
  4506. }
  4507. const char Arg[] = "-fmodules-cache-path=";
  4508. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  4509. CmdArgs.push_back(Args.MakeArgString(Path));
  4510. }
  4511. // -fmodule-name specifies the module that is currently being built (or
  4512. // used for header checking by -fmodule-maps).
  4513. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
  4514. // -fmodule-map-file can be used to specify files containing module
  4515. // definitions.
  4516. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  4517. // -fmodule-file can be used to specify files containing precompiled modules.
  4518. if (HaveModules)
  4519. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  4520. else
  4521. Args.ClaimAllArgs(options::OPT_fmodule_file);
  4522. // When building modules and generating crashdumps, we need to dump a module
  4523. // dependency VFS alongside the output.
  4524. if (HaveModules && C.isForDiagnostics()) {
  4525. SmallString<128> VFSDir(Output.getFilename());
  4526. llvm::sys::path::replace_extension(VFSDir, ".cache");
  4527. // Add the cache directory as a temp so the crash diagnostics pick it up.
  4528. C.addTempFile(Args.MakeArgString(VFSDir));
  4529. llvm::sys::path::append(VFSDir, "vfs");
  4530. CmdArgs.push_back("-module-dependency-dir");
  4531. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  4532. }
  4533. if (HaveModules)
  4534. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  4535. // Pass through all -fmodules-ignore-macro arguments.
  4536. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  4537. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  4538. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  4539. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  4540. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  4541. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  4542. D.Diag(diag::err_drv_argument_not_allowed_with)
  4543. << A->getAsString(Args) << "-fbuild-session-timestamp";
  4544. llvm::sys::fs::file_status Status;
  4545. if (llvm::sys::fs::status(A->getValue(), Status))
  4546. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  4547. CmdArgs.push_back(Args.MakeArgString(
  4548. "-fbuild-session-timestamp=" +
  4549. Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
  4550. }
  4551. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  4552. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  4553. options::OPT_fbuild_session_file))
  4554. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  4555. Args.AddLastArg(CmdArgs,
  4556. options::OPT_fmodules_validate_once_per_build_session);
  4557. }
  4558. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  4559. // -faccess-control is default.
  4560. if (Args.hasFlag(options::OPT_fno_access_control,
  4561. options::OPT_faccess_control, false))
  4562. CmdArgs.push_back("-fno-access-control");
  4563. // -felide-constructors is the default.
  4564. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4565. options::OPT_felide_constructors, false))
  4566. CmdArgs.push_back("-fno-elide-constructors");
  4567. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  4568. if (KernelOrKext || (types::isCXX(InputType) &&
  4569. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  4570. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  4571. CmdArgs.push_back("-fno-rtti");
  4572. // -fshort-enums=0 is default for all architectures except Hexagon.
  4573. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4574. getToolChain().getArch() == llvm::Triple::hexagon))
  4575. CmdArgs.push_back("-fshort-enums");
  4576. // -fsigned-char is default.
  4577. if (Arg *A = Args.getLastArg(
  4578. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  4579. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  4580. if (A->getOption().matches(options::OPT_funsigned_char) ||
  4581. A->getOption().matches(options::OPT_fno_signed_char)) {
  4582. CmdArgs.push_back("-fno-signed-char");
  4583. }
  4584. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  4585. CmdArgs.push_back("-fno-signed-char");
  4586. }
  4587. // -fuse-cxa-atexit is default.
  4588. if (!Args.hasFlag(
  4589. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  4590. !IsWindowsCygnus && !IsWindowsGNU &&
  4591. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  4592. getToolChain().getArch() != llvm::Triple::hexagon &&
  4593. getToolChain().getArch() != llvm::Triple::xcore &&
  4594. ((getToolChain().getTriple().getVendor() !=
  4595. llvm::Triple::MipsTechnologies) ||
  4596. getToolChain().getTriple().hasEnvironment())) ||
  4597. KernelOrKext)
  4598. CmdArgs.push_back("-fno-use-cxa-atexit");
  4599. // -fms-extensions=0 is default.
  4600. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4601. IsWindowsMSVC))
  4602. CmdArgs.push_back("-fms-extensions");
  4603. // -fno-use-line-directives is default.
  4604. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4605. options::OPT_fno_use_line_directives, false))
  4606. CmdArgs.push_back("-fuse-line-directives");
  4607. // -fms-compatibility=0 is default.
  4608. if (Args.hasFlag(options::OPT_fms_compatibility,
  4609. options::OPT_fno_ms_compatibility,
  4610. (IsWindowsMSVC &&
  4611. Args.hasFlag(options::OPT_fms_extensions,
  4612. options::OPT_fno_ms_extensions, true))))
  4613. CmdArgs.push_back("-fms-compatibility");
  4614. // -fms-compatibility-version=18.00 is default.
  4615. VersionTuple MSVT = visualstudio::getMSVCVersion(
  4616. &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
  4617. if (!MSVT.empty())
  4618. CmdArgs.push_back(
  4619. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4620. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4621. if (ImplyVCPPCXXVer) {
  4622. if (IsMSVC2015Compatible)
  4623. CmdArgs.push_back("-std=c++14");
  4624. else
  4625. CmdArgs.push_back("-std=c++11");
  4626. }
  4627. // -fno-borland-extensions is default.
  4628. if (Args.hasFlag(options::OPT_fborland_extensions,
  4629. options::OPT_fno_borland_extensions, false))
  4630. CmdArgs.push_back("-fborland-extensions");
  4631. // -fno-declspec is default, except for PS4.
  4632. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4633. getToolChain().getTriple().isPS4()))
  4634. CmdArgs.push_back("-fdeclspec");
  4635. else if (Args.hasArg(options::OPT_fno_declspec))
  4636. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  4637. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  4638. // than 19.
  4639. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  4640. options::OPT_fno_threadsafe_statics,
  4641. !IsWindowsMSVC || IsMSVC2015Compatible))
  4642. CmdArgs.push_back("-fno-threadsafe-statics");
  4643. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  4644. // needs it.
  4645. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  4646. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  4647. CmdArgs.push_back("-fdelayed-template-parsing");
  4648. // -fgnu-keywords default varies depending on language; only pass if
  4649. // specified.
  4650. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  4651. options::OPT_fno_gnu_keywords))
  4652. A->render(Args, CmdArgs);
  4653. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  4654. false))
  4655. CmdArgs.push_back("-fgnu89-inline");
  4656. if (Args.hasArg(options::OPT_fno_inline))
  4657. CmdArgs.push_back("-fno-inline");
  4658. if (Args.hasArg(options::OPT_fno_inline_functions))
  4659. CmdArgs.push_back("-fno-inline-functions");
  4660. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  4661. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  4662. // legacy is the default. Except for deployment taget of 10.5,
  4663. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  4664. // gets ignored silently.
  4665. if (objcRuntime.isNonFragile()) {
  4666. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  4667. options::OPT_fno_objc_legacy_dispatch,
  4668. objcRuntime.isLegacyDispatchDefaultForArch(
  4669. getToolChain().getArch()))) {
  4670. if (getToolChain().UseObjCMixedDispatch())
  4671. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  4672. else
  4673. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  4674. }
  4675. }
  4676. // When ObjectiveC legacy runtime is in effect on MacOSX,
  4677. // turn on the option to do Array/Dictionary subscripting
  4678. // by default.
  4679. if (getToolChain().getArch() == llvm::Triple::x86 &&
  4680. getToolChain().getTriple().isMacOSX() &&
  4681. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  4682. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  4683. objcRuntime.isNeXTFamily())
  4684. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  4685. // -fencode-extended-block-signature=1 is default.
  4686. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  4687. CmdArgs.push_back("-fencode-extended-block-signature");
  4688. }
  4689. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  4690. // NOTE: This logic is duplicated in ToolChains.cpp.
  4691. bool ARC = isObjCAutoRefCount(Args);
  4692. if (ARC) {
  4693. getToolChain().CheckObjCARC();
  4694. CmdArgs.push_back("-fobjc-arc");
  4695. // FIXME: It seems like this entire block, and several around it should be
  4696. // wrapped in isObjC, but for now we just use it here as this is where it
  4697. // was being used previously.
  4698. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  4699. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  4700. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  4701. else
  4702. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  4703. }
  4704. // Allow the user to enable full exceptions code emission.
  4705. // We define off for Objective-CC, on for Objective-C++.
  4706. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  4707. options::OPT_fno_objc_arc_exceptions,
  4708. /*default*/ types::isCXX(InputType)))
  4709. CmdArgs.push_back("-fobjc-arc-exceptions");
  4710. }
  4711. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  4712. // rewriter.
  4713. if (rewriteKind != RK_None)
  4714. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  4715. // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
  4716. // takes precedence.
  4717. const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
  4718. if (!GCArg)
  4719. GCArg = Args.getLastArg(options::OPT_fobjc_gc);
  4720. if (GCArg) {
  4721. if (ARC) {
  4722. D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
  4723. } else if (getToolChain().SupportsObjCGC()) {
  4724. GCArg->render(Args, CmdArgs);
  4725. } else {
  4726. // FIXME: We should move this to a hard error.
  4727. D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
  4728. }
  4729. }
  4730. // Pass down -fobjc-weak or -fno-objc-weak if present.
  4731. if (types::isObjC(InputType)) {
  4732. auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
  4733. options::OPT_fno_objc_weak);
  4734. if (!WeakArg) {
  4735. // nothing to do
  4736. } else if (GCArg) {
  4737. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4738. D.Diag(diag::err_objc_weak_with_gc);
  4739. } else if (!objcRuntime.allowsWeak()) {
  4740. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4741. D.Diag(diag::err_objc_weak_unsupported);
  4742. } else {
  4743. WeakArg->render(Args, CmdArgs);
  4744. }
  4745. }
  4746. if (Args.hasFlag(options::OPT_fapplication_extension,
  4747. options::OPT_fno_application_extension, false))
  4748. CmdArgs.push_back("-fapplication-extension");
  4749. // Handle GCC-style exception args.
  4750. if (!C.getDriver().IsCLMode())
  4751. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  4752. CmdArgs);
  4753. if (getToolChain().UseSjLjExceptions(Args))
  4754. CmdArgs.push_back("-fsjlj-exceptions");
  4755. // C++ "sane" operator new.
  4756. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4757. options::OPT_fno_assume_sane_operator_new))
  4758. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4759. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  4760. // most platforms.
  4761. if (Args.hasFlag(options::OPT_fsized_deallocation,
  4762. options::OPT_fno_sized_deallocation, false))
  4763. CmdArgs.push_back("-fsized-deallocation");
  4764. // -fconstant-cfstrings is default, and may be subject to argument translation
  4765. // on Darwin.
  4766. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  4767. options::OPT_fno_constant_cfstrings) ||
  4768. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  4769. options::OPT_mno_constant_cfstrings))
  4770. CmdArgs.push_back("-fno-constant-cfstrings");
  4771. // -fshort-wchar default varies depending on platform; only
  4772. // pass if specified.
  4773. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  4774. options::OPT_fno_short_wchar))
  4775. A->render(Args, CmdArgs);
  4776. // -fno-pascal-strings is default, only pass non-default.
  4777. if (Args.hasFlag(options::OPT_fpascal_strings,
  4778. options::OPT_fno_pascal_strings, false))
  4779. CmdArgs.push_back("-fpascal-strings");
  4780. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  4781. // -fno-pack-struct doesn't apply to -fpack-struct=.
  4782. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  4783. std::string PackStructStr = "-fpack-struct=";
  4784. PackStructStr += A->getValue();
  4785. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  4786. } else if (Args.hasFlag(options::OPT_fpack_struct,
  4787. options::OPT_fno_pack_struct, false)) {
  4788. CmdArgs.push_back("-fpack-struct=1");
  4789. }
  4790. // Handle -fmax-type-align=N and -fno-type-align
  4791. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  4792. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  4793. if (!SkipMaxTypeAlign) {
  4794. std::string MaxTypeAlignStr = "-fmax-type-align=";
  4795. MaxTypeAlignStr += A->getValue();
  4796. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4797. }
  4798. } else if (getToolChain().getTriple().isOSDarwin()) {
  4799. if (!SkipMaxTypeAlign) {
  4800. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  4801. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4802. }
  4803. }
  4804. // -fcommon is the default unless compiling kernel code or the target says so
  4805. bool NoCommonDefault =
  4806. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  4807. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  4808. !NoCommonDefault))
  4809. CmdArgs.push_back("-fno-common");
  4810. // -fsigned-bitfields is default, and clang doesn't yet support
  4811. // -funsigned-bitfields.
  4812. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  4813. options::OPT_funsigned_bitfields))
  4814. D.Diag(diag::warn_drv_clang_unsupported)
  4815. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  4816. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  4817. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  4818. D.Diag(diag::err_drv_clang_unsupported)
  4819. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  4820. // -finput_charset=UTF-8 is default. Reject others
  4821. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  4822. StringRef value = inputCharset->getValue();
  4823. if (value != "UTF-8")
  4824. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  4825. << value;
  4826. }
  4827. // -fexec_charset=UTF-8 is default. Reject others
  4828. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  4829. StringRef value = execCharset->getValue();
  4830. if (value != "UTF-8")
  4831. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  4832. << value;
  4833. }
  4834. // -fcaret-diagnostics is default.
  4835. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  4836. options::OPT_fno_caret_diagnostics, true))
  4837. CmdArgs.push_back("-fno-caret-diagnostics");
  4838. // -fdiagnostics-fixit-info is default, only pass non-default.
  4839. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  4840. options::OPT_fno_diagnostics_fixit_info))
  4841. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  4842. // Enable -fdiagnostics-show-option by default.
  4843. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  4844. options::OPT_fno_diagnostics_show_option))
  4845. CmdArgs.push_back("-fdiagnostics-show-option");
  4846. if (const Arg *A =
  4847. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  4848. CmdArgs.push_back("-fdiagnostics-show-category");
  4849. CmdArgs.push_back(A->getValue());
  4850. }
  4851. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  4852. CmdArgs.push_back("-fdiagnostics-format");
  4853. CmdArgs.push_back(A->getValue());
  4854. }
  4855. if (Arg *A = Args.getLastArg(
  4856. options::OPT_fdiagnostics_show_note_include_stack,
  4857. options::OPT_fno_diagnostics_show_note_include_stack)) {
  4858. if (A->getOption().matches(
  4859. options::OPT_fdiagnostics_show_note_include_stack))
  4860. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  4861. else
  4862. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  4863. }
  4864. // Color diagnostics are the default, unless the terminal doesn't support
  4865. // them.
  4866. // Support both clang's -f[no-]color-diagnostics and gcc's
  4867. // -f[no-]diagnostics-colors[=never|always|auto].
  4868. enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
  4869. for (const auto &Arg : Args) {
  4870. const Option &O = Arg->getOption();
  4871. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  4872. !O.matches(options::OPT_fdiagnostics_color) &&
  4873. !O.matches(options::OPT_fno_color_diagnostics) &&
  4874. !O.matches(options::OPT_fno_diagnostics_color) &&
  4875. !O.matches(options::OPT_fdiagnostics_color_EQ))
  4876. continue;
  4877. Arg->claim();
  4878. if (O.matches(options::OPT_fcolor_diagnostics) ||
  4879. O.matches(options::OPT_fdiagnostics_color)) {
  4880. ShowColors = Colors_On;
  4881. } else if (O.matches(options::OPT_fno_color_diagnostics) ||
  4882. O.matches(options::OPT_fno_diagnostics_color)) {
  4883. ShowColors = Colors_Off;
  4884. } else {
  4885. assert(O.matches(options::OPT_fdiagnostics_color_EQ));
  4886. StringRef value(Arg->getValue());
  4887. if (value == "always")
  4888. ShowColors = Colors_On;
  4889. else if (value == "never")
  4890. ShowColors = Colors_Off;
  4891. else if (value == "auto")
  4892. ShowColors = Colors_Auto;
  4893. else
  4894. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4895. << ("-fdiagnostics-color=" + value).str();
  4896. }
  4897. }
  4898. if (ShowColors == Colors_On ||
  4899. (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
  4900. CmdArgs.push_back("-fcolor-diagnostics");
  4901. if (Args.hasArg(options::OPT_fansi_escape_codes))
  4902. CmdArgs.push_back("-fansi-escape-codes");
  4903. if (!Args.hasFlag(options::OPT_fshow_source_location,
  4904. options::OPT_fno_show_source_location))
  4905. CmdArgs.push_back("-fno-show-source-location");
  4906. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  4907. true))
  4908. CmdArgs.push_back("-fno-show-column");
  4909. if (!Args.hasFlag(options::OPT_fspell_checking,
  4910. options::OPT_fno_spell_checking))
  4911. CmdArgs.push_back("-fno-spell-checking");
  4912. // -fno-asm-blocks is default.
  4913. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  4914. false))
  4915. CmdArgs.push_back("-fasm-blocks");
  4916. // -fgnu-inline-asm is default.
  4917. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  4918. options::OPT_fno_gnu_inline_asm, true))
  4919. CmdArgs.push_back("-fno-gnu-inline-asm");
  4920. // Enable vectorization per default according to the optimization level
  4921. // selected. For optimization levels that want vectorization we use the alias
  4922. // option to simplify the hasFlag logic.
  4923. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  4924. OptSpecifier VectorizeAliasOption =
  4925. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  4926. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  4927. options::OPT_fno_vectorize, EnableVec))
  4928. CmdArgs.push_back("-vectorize-loops");
  4929. // -fslp-vectorize is enabled based on the optimization level selected.
  4930. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  4931. OptSpecifier SLPVectAliasOption =
  4932. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  4933. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  4934. options::OPT_fno_slp_vectorize, EnableSLPVec))
  4935. CmdArgs.push_back("-vectorize-slp");
  4936. // -fno-slp-vectorize-aggressive is default.
  4937. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  4938. options::OPT_fno_slp_vectorize_aggressive, false))
  4939. CmdArgs.push_back("-vectorize-slp-aggressive");
  4940. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  4941. A->render(Args, CmdArgs);
  4942. // -fdollars-in-identifiers default varies depending on platform and
  4943. // language; only pass if specified.
  4944. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  4945. options::OPT_fno_dollars_in_identifiers)) {
  4946. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  4947. CmdArgs.push_back("-fdollars-in-identifiers");
  4948. else
  4949. CmdArgs.push_back("-fno-dollars-in-identifiers");
  4950. }
  4951. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  4952. // practical purposes.
  4953. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  4954. options::OPT_fno_unit_at_a_time)) {
  4955. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  4956. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  4957. }
  4958. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  4959. options::OPT_fno_apple_pragma_pack, false))
  4960. CmdArgs.push_back("-fapple-pragma-pack");
  4961. // le32-specific flags:
  4962. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  4963. // by default.
  4964. if (getToolChain().getArch() == llvm::Triple::le32) {
  4965. CmdArgs.push_back("-fno-math-builtin");
  4966. }
  4967. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  4968. //
  4969. // FIXME: Now that PR4941 has been fixed this can be enabled.
  4970. #if 0
  4971. if (getToolChain().getTriple().isOSDarwin() &&
  4972. (getToolChain().getArch() == llvm::Triple::arm ||
  4973. getToolChain().getArch() == llvm::Triple::thumb)) {
  4974. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  4975. CmdArgs.push_back("-fno-builtin-strcat");
  4976. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  4977. CmdArgs.push_back("-fno-builtin-strcpy");
  4978. }
  4979. #endif
  4980. // Enable rewrite includes if the user's asked for it or if we're generating
  4981. // diagnostics.
  4982. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  4983. // nice to enable this when doing a crashdump for modules as well.
  4984. if (Args.hasFlag(options::OPT_frewrite_includes,
  4985. options::OPT_fno_rewrite_includes, false) ||
  4986. (C.isForDiagnostics() && !HaveModules))
  4987. CmdArgs.push_back("-frewrite-includes");
  4988. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  4989. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  4990. options::OPT_traditional_cpp)) {
  4991. if (isa<PreprocessJobAction>(JA))
  4992. CmdArgs.push_back("-traditional-cpp");
  4993. else
  4994. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  4995. }
  4996. Args.AddLastArg(CmdArgs, options::OPT_dM);
  4997. Args.AddLastArg(CmdArgs, options::OPT_dD);
  4998. // Handle serialized diagnostics.
  4999. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  5000. CmdArgs.push_back("-serialize-diagnostic-file");
  5001. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  5002. }
  5003. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  5004. CmdArgs.push_back("-fretain-comments-from-system-headers");
  5005. // Forward -fcomment-block-commands to -cc1.
  5006. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  5007. // Forward -fparse-all-comments to -cc1.
  5008. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  5009. // Turn -fplugin=name.so into -load name.so
  5010. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  5011. CmdArgs.push_back("-load");
  5012. CmdArgs.push_back(A->getValue());
  5013. A->claim();
  5014. }
  5015. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  5016. // parser.
  5017. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  5018. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  5019. A->claim();
  5020. // We translate this by hand to the -cc1 argument, since nightly test uses
  5021. // it and developers have been trained to spell it with -mllvm.
  5022. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  5023. CmdArgs.push_back("-disable-llvm-optzns");
  5024. } else
  5025. A->render(Args, CmdArgs);
  5026. }
  5027. // With -save-temps, we want to save the unoptimized bitcode output from the
  5028. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  5029. // by the frontend.
  5030. // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
  5031. // has slightly different breakdown between stages.
  5032. // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
  5033. // pristine IR generated by the frontend. Ideally, a new compile action should
  5034. // be added so both IR can be captured.
  5035. if (C.getDriver().isSaveTempsEnabled() &&
  5036. !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
  5037. CmdArgs.push_back("-disable-llvm-passes");
  5038. if (Output.getType() == types::TY_Dependencies) {
  5039. // Handled with other dependency code.
  5040. } else if (Output.isFilename()) {
  5041. CmdArgs.push_back("-o");
  5042. CmdArgs.push_back(Output.getFilename());
  5043. } else {
  5044. assert(Output.isNothing() && "Invalid output.");
  5045. }
  5046. addDashXForInput(Args, Input, CmdArgs);
  5047. if (Input.isFilename())
  5048. CmdArgs.push_back(Input.getFilename());
  5049. else
  5050. Input.getInputArg().renderAsInput(Args, CmdArgs);
  5051. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  5052. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5053. // Optionally embed the -cc1 level arguments into the debug info, for build
  5054. // analysis.
  5055. if (getToolChain().UseDwarfDebugFlags()) {
  5056. ArgStringList OriginalArgs;
  5057. for (const auto &Arg : Args)
  5058. Arg->render(Args, OriginalArgs);
  5059. SmallString<256> Flags;
  5060. Flags += Exec;
  5061. for (const char *OriginalArg : OriginalArgs) {
  5062. SmallString<128> EscapedArg;
  5063. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5064. Flags += " ";
  5065. Flags += EscapedArg;
  5066. }
  5067. CmdArgs.push_back("-dwarf-debug-flags");
  5068. CmdArgs.push_back(Args.MakeArgString(Flags));
  5069. }
  5070. // Add the split debug info name to the command lines here so we
  5071. // can propagate it to the backend.
  5072. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  5073. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  5074. isa<BackendJobAction>(JA));
  5075. const char *SplitDwarfOut;
  5076. if (SplitDwarf) {
  5077. CmdArgs.push_back("-split-dwarf-file");
  5078. SplitDwarfOut = SplitDebugName(Args, Input);
  5079. CmdArgs.push_back(SplitDwarfOut);
  5080. }
  5081. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  5082. // Include them with -fcuda-include-gpubinary.
  5083. if (IsCuda && Inputs.size() > 1)
  5084. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  5085. CmdArgs.push_back("-fcuda-include-gpubinary");
  5086. CmdArgs.push_back(I->getFilename());
  5087. }
  5088. bool WholeProgramVTables =
  5089. Args.hasFlag(options::OPT_fwhole_program_vtables,
  5090. options::OPT_fno_whole_program_vtables, false);
  5091. if (WholeProgramVTables) {
  5092. if (!D.isUsingLTO())
  5093. D.Diag(diag::err_drv_argument_only_allowed_with)
  5094. << "-fwhole-program-vtables"
  5095. << "-flto";
  5096. CmdArgs.push_back("-fwhole-program-vtables");
  5097. }
  5098. // Finally add the compile command to the compilation.
  5099. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5100. Output.getType() == types::TY_Object &&
  5101. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  5102. auto CLCommand =
  5103. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  5104. C.addCommand(llvm::make_unique<FallbackCommand>(
  5105. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  5106. } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5107. isa<PrecompileJobAction>(JA)) {
  5108. // In /fallback builds, run the main compilation even if the pch generation
  5109. // fails, so that the main compilation's fallback to cl.exe runs.
  5110. C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
  5111. CmdArgs, Inputs));
  5112. } else {
  5113. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5114. }
  5115. // Handle the debug info splitting at object creation time if we're
  5116. // creating an object.
  5117. // TODO: Currently only works on linux with newer objcopy.
  5118. if (SplitDwarf && Output.getType() == types::TY_Object)
  5119. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  5120. if (Arg *A = Args.getLastArg(options::OPT_pg))
  5121. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  5122. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  5123. << A->getAsString(Args);
  5124. // Claim some arguments which clang supports automatically.
  5125. // -fpch-preprocess is used with gcc to add a special marker in the output to
  5126. // include the PCH file. Clang's PTH solution is completely transparent, so we
  5127. // do not need to deal with it at all.
  5128. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  5129. // Claim some arguments which clang doesn't support, but we don't
  5130. // care to warn the user about.
  5131. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  5132. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  5133. // Disable warnings for clang -E -emit-llvm foo.c
  5134. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5135. }
  5136. /// Add options related to the Objective-C runtime/ABI.
  5137. ///
  5138. /// Returns true if the runtime is non-fragile.
  5139. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  5140. ArgStringList &cmdArgs,
  5141. RewriteKind rewriteKind) const {
  5142. // Look for the controlling runtime option.
  5143. Arg *runtimeArg =
  5144. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  5145. options::OPT_fobjc_runtime_EQ);
  5146. // Just forward -fobjc-runtime= to the frontend. This supercedes
  5147. // options about fragility.
  5148. if (runtimeArg &&
  5149. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  5150. ObjCRuntime runtime;
  5151. StringRef value = runtimeArg->getValue();
  5152. if (runtime.tryParse(value)) {
  5153. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  5154. << value;
  5155. }
  5156. runtimeArg->render(args, cmdArgs);
  5157. return runtime;
  5158. }
  5159. // Otherwise, we'll need the ABI "version". Version numbers are
  5160. // slightly confusing for historical reasons:
  5161. // 1 - Traditional "fragile" ABI
  5162. // 2 - Non-fragile ABI, version 1
  5163. // 3 - Non-fragile ABI, version 2
  5164. unsigned objcABIVersion = 1;
  5165. // If -fobjc-abi-version= is present, use that to set the version.
  5166. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  5167. StringRef value = abiArg->getValue();
  5168. if (value == "1")
  5169. objcABIVersion = 1;
  5170. else if (value == "2")
  5171. objcABIVersion = 2;
  5172. else if (value == "3")
  5173. objcABIVersion = 3;
  5174. else
  5175. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  5176. } else {
  5177. // Otherwise, determine if we are using the non-fragile ABI.
  5178. bool nonFragileABIIsDefault =
  5179. (rewriteKind == RK_NonFragile ||
  5180. (rewriteKind == RK_None &&
  5181. getToolChain().IsObjCNonFragileABIDefault()));
  5182. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  5183. options::OPT_fno_objc_nonfragile_abi,
  5184. nonFragileABIIsDefault)) {
  5185. // Determine the non-fragile ABI version to use.
  5186. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  5187. unsigned nonFragileABIVersion = 1;
  5188. #else
  5189. unsigned nonFragileABIVersion = 2;
  5190. #endif
  5191. if (Arg *abiArg =
  5192. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  5193. StringRef value = abiArg->getValue();
  5194. if (value == "1")
  5195. nonFragileABIVersion = 1;
  5196. else if (value == "2")
  5197. nonFragileABIVersion = 2;
  5198. else
  5199. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  5200. << value;
  5201. }
  5202. objcABIVersion = 1 + nonFragileABIVersion;
  5203. } else {
  5204. objcABIVersion = 1;
  5205. }
  5206. }
  5207. // We don't actually care about the ABI version other than whether
  5208. // it's non-fragile.
  5209. bool isNonFragile = objcABIVersion != 1;
  5210. // If we have no runtime argument, ask the toolchain for its default runtime.
  5211. // However, the rewriter only really supports the Mac runtime, so assume that.
  5212. ObjCRuntime runtime;
  5213. if (!runtimeArg) {
  5214. switch (rewriteKind) {
  5215. case RK_None:
  5216. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5217. break;
  5218. case RK_Fragile:
  5219. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  5220. break;
  5221. case RK_NonFragile:
  5222. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5223. break;
  5224. }
  5225. // -fnext-runtime
  5226. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  5227. // On Darwin, make this use the default behavior for the toolchain.
  5228. if (getToolChain().getTriple().isOSDarwin()) {
  5229. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5230. // Otherwise, build for a generic macosx port.
  5231. } else {
  5232. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5233. }
  5234. // -fgnu-runtime
  5235. } else {
  5236. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  5237. // Legacy behaviour is to target the gnustep runtime if we are in
  5238. // non-fragile mode or the GCC runtime in fragile mode.
  5239. if (isNonFragile)
  5240. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  5241. else
  5242. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  5243. }
  5244. cmdArgs.push_back(
  5245. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  5246. return runtime;
  5247. }
  5248. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  5249. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  5250. I += HaveDash;
  5251. return !HaveDash;
  5252. }
  5253. namespace {
  5254. struct EHFlags {
  5255. bool Synch = false;
  5256. bool Asynch = false;
  5257. bool NoUnwindC = false;
  5258. };
  5259. } // end anonymous namespace
  5260. /// /EH controls whether to run destructor cleanups when exceptions are
  5261. /// thrown. There are three modifiers:
  5262. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  5263. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  5264. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  5265. /// - c: Assume that extern "C" functions are implicitly nounwind.
  5266. /// The default is /EHs-c-, meaning cleanups are disabled.
  5267. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  5268. EHFlags EH;
  5269. std::vector<std::string> EHArgs =
  5270. Args.getAllArgValues(options::OPT__SLASH_EH);
  5271. for (auto EHVal : EHArgs) {
  5272. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  5273. switch (EHVal[I]) {
  5274. case 'a':
  5275. EH.Asynch = maybeConsumeDash(EHVal, I);
  5276. if (EH.Asynch)
  5277. EH.Synch = false;
  5278. continue;
  5279. case 'c':
  5280. EH.NoUnwindC = maybeConsumeDash(EHVal, I);
  5281. continue;
  5282. case 's':
  5283. EH.Synch = maybeConsumeDash(EHVal, I);
  5284. if (EH.Synch)
  5285. EH.Asynch = false;
  5286. continue;
  5287. default:
  5288. break;
  5289. }
  5290. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  5291. break;
  5292. }
  5293. }
  5294. // The /GX, /GX- flags are only processed if there are not /EH flags.
  5295. // The default is that /GX is not specified.
  5296. if (EHArgs.empty() &&
  5297. Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
  5298. /*default=*/false)) {
  5299. EH.Synch = true;
  5300. EH.NoUnwindC = true;
  5301. }
  5302. return EH;
  5303. }
  5304. void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
  5305. ArgStringList &CmdArgs,
  5306. codegenoptions::DebugInfoKind *DebugInfoKind,
  5307. bool *EmitCodeView) const {
  5308. unsigned RTOptionID = options::OPT__SLASH_MT;
  5309. if (Args.hasArg(options::OPT__SLASH_LDd))
  5310. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  5311. // but defining _DEBUG is sticky.
  5312. RTOptionID = options::OPT__SLASH_MTd;
  5313. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  5314. RTOptionID = A->getOption().getID();
  5315. StringRef FlagForCRT;
  5316. switch (RTOptionID) {
  5317. case options::OPT__SLASH_MD:
  5318. if (Args.hasArg(options::OPT__SLASH_LDd))
  5319. CmdArgs.push_back("-D_DEBUG");
  5320. CmdArgs.push_back("-D_MT");
  5321. CmdArgs.push_back("-D_DLL");
  5322. FlagForCRT = "--dependent-lib=msvcrt";
  5323. break;
  5324. case options::OPT__SLASH_MDd:
  5325. CmdArgs.push_back("-D_DEBUG");
  5326. CmdArgs.push_back("-D_MT");
  5327. CmdArgs.push_back("-D_DLL");
  5328. FlagForCRT = "--dependent-lib=msvcrtd";
  5329. break;
  5330. case options::OPT__SLASH_MT:
  5331. if (Args.hasArg(options::OPT__SLASH_LDd))
  5332. CmdArgs.push_back("-D_DEBUG");
  5333. CmdArgs.push_back("-D_MT");
  5334. CmdArgs.push_back("-flto-visibility-public-std");
  5335. FlagForCRT = "--dependent-lib=libcmt";
  5336. break;
  5337. case options::OPT__SLASH_MTd:
  5338. CmdArgs.push_back("-D_DEBUG");
  5339. CmdArgs.push_back("-D_MT");
  5340. CmdArgs.push_back("-flto-visibility-public-std");
  5341. FlagForCRT = "--dependent-lib=libcmtd";
  5342. break;
  5343. default:
  5344. llvm_unreachable("Unexpected option ID.");
  5345. }
  5346. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  5347. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  5348. } else {
  5349. CmdArgs.push_back(FlagForCRT.data());
  5350. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  5351. // users want. The /Za flag to cl.exe turns this off, but it's not
  5352. // implemented in clang.
  5353. CmdArgs.push_back("--dependent-lib=oldnames");
  5354. }
  5355. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  5356. // would produce interleaved output, so ignore /showIncludes in such cases.
  5357. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  5358. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  5359. A->render(Args, CmdArgs);
  5360. // This controls whether or not we emit RTTI data for polymorphic types.
  5361. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  5362. /*default=*/false))
  5363. CmdArgs.push_back("-fno-rtti-data");
  5364. // Emit CodeView if -Z7 is present.
  5365. *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
  5366. if (*EmitCodeView)
  5367. *DebugInfoKind = codegenoptions::LimitedDebugInfo;
  5368. if (*EmitCodeView)
  5369. CmdArgs.push_back("-gcodeview");
  5370. const Driver &D = getToolChain().getDriver();
  5371. EHFlags EH = parseClangCLEHFlags(D, Args);
  5372. if (EH.Synch || EH.Asynch) {
  5373. if (types::isCXX(InputType))
  5374. CmdArgs.push_back("-fcxx-exceptions");
  5375. CmdArgs.push_back("-fexceptions");
  5376. }
  5377. if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
  5378. CmdArgs.push_back("-fexternc-nounwind");
  5379. // /EP should expand to -E -P.
  5380. if (Args.hasArg(options::OPT__SLASH_EP)) {
  5381. CmdArgs.push_back("-E");
  5382. CmdArgs.push_back("-P");
  5383. }
  5384. unsigned VolatileOptionID;
  5385. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  5386. getToolChain().getArch() == llvm::Triple::x86)
  5387. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  5388. else
  5389. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  5390. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  5391. VolatileOptionID = A->getOption().getID();
  5392. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  5393. CmdArgs.push_back("-fms-volatile");
  5394. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  5395. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  5396. if (MostGeneralArg && BestCaseArg)
  5397. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5398. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  5399. if (MostGeneralArg) {
  5400. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  5401. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  5402. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  5403. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  5404. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  5405. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  5406. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5407. << FirstConflict->getAsString(Args)
  5408. << SecondConflict->getAsString(Args);
  5409. if (SingleArg)
  5410. CmdArgs.push_back("-fms-memptr-rep=single");
  5411. else if (MultipleArg)
  5412. CmdArgs.push_back("-fms-memptr-rep=multiple");
  5413. else
  5414. CmdArgs.push_back("-fms-memptr-rep=virtual");
  5415. }
  5416. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  5417. A->render(Args, CmdArgs);
  5418. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  5419. CmdArgs.push_back("-fdiagnostics-format");
  5420. if (Args.hasArg(options::OPT__SLASH_fallback))
  5421. CmdArgs.push_back("msvc-fallback");
  5422. else
  5423. CmdArgs.push_back("msvc");
  5424. }
  5425. }
  5426. visualstudio::Compiler *Clang::getCLFallback() const {
  5427. if (!CLFallback)
  5428. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  5429. return CLFallback.get();
  5430. }
  5431. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  5432. ArgStringList &CmdArgs) const {
  5433. StringRef CPUName;
  5434. StringRef ABIName;
  5435. const llvm::Triple &Triple = getToolChain().getTriple();
  5436. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  5437. CmdArgs.push_back("-target-abi");
  5438. CmdArgs.push_back(ABIName.data());
  5439. }
  5440. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  5441. const InputInfo &Output, const InputInfoList &Inputs,
  5442. const ArgList &Args,
  5443. const char *LinkingOutput) const {
  5444. ArgStringList CmdArgs;
  5445. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5446. const InputInfo &Input = Inputs[0];
  5447. std::string TripleStr =
  5448. getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
  5449. const llvm::Triple Triple(TripleStr);
  5450. // Don't warn about "clang -w -c foo.s"
  5451. Args.ClaimAllArgs(options::OPT_w);
  5452. // and "clang -emit-llvm -c foo.s"
  5453. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5454. claimNoWarnArgs(Args);
  5455. // Invoke ourselves in -cc1as mode.
  5456. //
  5457. // FIXME: Implement custom jobs for internal actions.
  5458. CmdArgs.push_back("-cc1as");
  5459. // Add the "effective" target triple.
  5460. CmdArgs.push_back("-triple");
  5461. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  5462. // Set the output mode, we currently only expect to be used as a real
  5463. // assembler.
  5464. CmdArgs.push_back("-filetype");
  5465. CmdArgs.push_back("obj");
  5466. // Set the main file name, so that debug info works even with
  5467. // -save-temps or preprocessed assembly.
  5468. CmdArgs.push_back("-main-file-name");
  5469. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  5470. // Add the target cpu
  5471. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  5472. if (!CPU.empty()) {
  5473. CmdArgs.push_back("-target-cpu");
  5474. CmdArgs.push_back(Args.MakeArgString(CPU));
  5475. }
  5476. // Add the target features
  5477. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  5478. // Ignore explicit -force_cpusubtype_ALL option.
  5479. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  5480. // Pass along any -I options so we get proper .include search paths.
  5481. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  5482. // Determine the original source input.
  5483. const Action *SourceAction = &JA;
  5484. while (SourceAction->getKind() != Action::InputClass) {
  5485. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5486. SourceAction = SourceAction->getInputs()[0];
  5487. }
  5488. // Forward -g and handle debug info related flags, assuming we are dealing
  5489. // with an actual assembly file.
  5490. bool WantDebug = false;
  5491. unsigned DwarfVersion = 0;
  5492. Args.ClaimAllArgs(options::OPT_g_Group);
  5493. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  5494. WantDebug = !A->getOption().matches(options::OPT_g0) &&
  5495. !A->getOption().matches(options::OPT_ggdb0);
  5496. if (WantDebug)
  5497. DwarfVersion = DwarfVersionNum(A->getSpelling());
  5498. }
  5499. if (DwarfVersion == 0)
  5500. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  5501. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  5502. if (SourceAction->getType() == types::TY_Asm ||
  5503. SourceAction->getType() == types::TY_PP_Asm) {
  5504. // You might think that it would be ok to set DebugInfoKind outside of
  5505. // the guard for source type, however there is a test which asserts
  5506. // that some assembler invocation receives no -debug-info-kind,
  5507. // and it's not clear whether that test is just overly restrictive.
  5508. DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
  5509. : codegenoptions::NoDebugInfo);
  5510. // Add the -fdebug-compilation-dir flag if needed.
  5511. addDebugCompDirArg(Args, CmdArgs);
  5512. // Set the AT_producer to the clang version when using the integrated
  5513. // assembler on assembly source files.
  5514. CmdArgs.push_back("-dwarf-debug-producer");
  5515. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  5516. // And pass along -I options
  5517. Args.AddAllArgs(CmdArgs, options::OPT_I);
  5518. }
  5519. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  5520. llvm::DebuggerKind::Default);
  5521. // Handle -fPIC et al -- the relocation-model affects the assembler
  5522. // for some targets.
  5523. llvm::Reloc::Model RelocationModel;
  5524. unsigned PICLevel;
  5525. bool IsPIE;
  5526. std::tie(RelocationModel, PICLevel, IsPIE) =
  5527. ParsePICArgs(getToolChain(), Triple, Args);
  5528. const char *RMName = RelocationModelName(RelocationModel);
  5529. if (RMName) {
  5530. CmdArgs.push_back("-mrelocation-model");
  5531. CmdArgs.push_back(RMName);
  5532. }
  5533. // Optionally embed the -cc1as level arguments into the debug info, for build
  5534. // analysis.
  5535. if (getToolChain().UseDwarfDebugFlags()) {
  5536. ArgStringList OriginalArgs;
  5537. for (const auto &Arg : Args)
  5538. Arg->render(Args, OriginalArgs);
  5539. SmallString<256> Flags;
  5540. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5541. Flags += Exec;
  5542. for (const char *OriginalArg : OriginalArgs) {
  5543. SmallString<128> EscapedArg;
  5544. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5545. Flags += " ";
  5546. Flags += EscapedArg;
  5547. }
  5548. CmdArgs.push_back("-dwarf-debug-flags");
  5549. CmdArgs.push_back(Args.MakeArgString(Flags));
  5550. }
  5551. // FIXME: Add -static support, once we have it.
  5552. // Add target specific flags.
  5553. switch (getToolChain().getArch()) {
  5554. default:
  5555. break;
  5556. case llvm::Triple::mips:
  5557. case llvm::Triple::mipsel:
  5558. case llvm::Triple::mips64:
  5559. case llvm::Triple::mips64el:
  5560. AddMIPSTargetArgs(Args, CmdArgs);
  5561. break;
  5562. }
  5563. // Consume all the warning flags. Usually this would be handled more
  5564. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  5565. // doesn't handle that so rather than warning about unused flags that are
  5566. // actually used, we'll lie by omission instead.
  5567. // FIXME: Stop lying and consume only the appropriate driver flags
  5568. Args.ClaimAllArgs(options::OPT_W_Group);
  5569. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  5570. getToolChain().getDriver());
  5571. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  5572. assert(Output.isFilename() && "Unexpected lipo output.");
  5573. CmdArgs.push_back("-o");
  5574. CmdArgs.push_back(Output.getFilename());
  5575. assert(Input.isFilename() && "Invalid input.");
  5576. CmdArgs.push_back(Input.getFilename());
  5577. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5578. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5579. // Handle the debug info splitting at object creation time if we're
  5580. // creating an object.
  5581. // TODO: Currently only works on linux with newer objcopy.
  5582. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  5583. getToolChain().getTriple().isOSLinux())
  5584. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  5585. SplitDebugName(Args, Input));
  5586. }
  5587. void GnuTool::anchor() {}
  5588. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  5589. const InputInfo &Output,
  5590. const InputInfoList &Inputs, const ArgList &Args,
  5591. const char *LinkingOutput) const {
  5592. const Driver &D = getToolChain().getDriver();
  5593. ArgStringList CmdArgs;
  5594. for (const auto &A : Args) {
  5595. if (forwardToGCC(A->getOption())) {
  5596. // It is unfortunate that we have to claim here, as this means
  5597. // we will basically never report anything interesting for
  5598. // platforms using a generic gcc, even if we are just using gcc
  5599. // to get to the assembler.
  5600. A->claim();
  5601. // Don't forward any -g arguments to assembly steps.
  5602. if (isa<AssembleJobAction>(JA) &&
  5603. A->getOption().matches(options::OPT_g_Group))
  5604. continue;
  5605. // Don't forward any -W arguments to assembly and link steps.
  5606. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  5607. A->getOption().matches(options::OPT_W_Group))
  5608. continue;
  5609. A->render(Args, CmdArgs);
  5610. }
  5611. }
  5612. RenderExtraToolArgs(JA, CmdArgs);
  5613. // If using a driver driver, force the arch.
  5614. if (getToolChain().getTriple().isOSDarwin()) {
  5615. CmdArgs.push_back("-arch");
  5616. CmdArgs.push_back(
  5617. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  5618. }
  5619. // Try to force gcc to match the tool chain we want, if we recognize
  5620. // the arch.
  5621. //
  5622. // FIXME: The triple class should directly provide the information we want
  5623. // here.
  5624. switch (getToolChain().getArch()) {
  5625. default:
  5626. break;
  5627. case llvm::Triple::x86:
  5628. case llvm::Triple::ppc:
  5629. CmdArgs.push_back("-m32");
  5630. break;
  5631. case llvm::Triple::x86_64:
  5632. case llvm::Triple::ppc64:
  5633. case llvm::Triple::ppc64le:
  5634. CmdArgs.push_back("-m64");
  5635. break;
  5636. case llvm::Triple::sparcel:
  5637. CmdArgs.push_back("-EL");
  5638. break;
  5639. }
  5640. if (Output.isFilename()) {
  5641. CmdArgs.push_back("-o");
  5642. CmdArgs.push_back(Output.getFilename());
  5643. } else {
  5644. assert(Output.isNothing() && "Unexpected output");
  5645. CmdArgs.push_back("-fsyntax-only");
  5646. }
  5647. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5648. // Only pass -x if gcc will understand it; otherwise hope gcc
  5649. // understands the suffix correctly. The main use case this would go
  5650. // wrong in is for linker inputs if they happened to have an odd
  5651. // suffix; really the only way to get this to happen is a command
  5652. // like '-x foobar a.c' which will treat a.c like a linker input.
  5653. //
  5654. // FIXME: For the linker case specifically, can we safely convert
  5655. // inputs into '-Wl,' options?
  5656. for (const auto &II : Inputs) {
  5657. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5658. if (types::isLLVMIR(II.getType()))
  5659. D.Diag(diag::err_drv_no_linker_llvm_support)
  5660. << getToolChain().getTripleString();
  5661. else if (II.getType() == types::TY_AST)
  5662. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  5663. else if (II.getType() == types::TY_ModuleFile)
  5664. D.Diag(diag::err_drv_no_module_support)
  5665. << getToolChain().getTripleString();
  5666. if (types::canTypeBeUserSpecified(II.getType())) {
  5667. CmdArgs.push_back("-x");
  5668. CmdArgs.push_back(types::getTypeName(II.getType()));
  5669. }
  5670. if (II.isFilename())
  5671. CmdArgs.push_back(II.getFilename());
  5672. else {
  5673. const Arg &A = II.getInputArg();
  5674. // Reverse translate some rewritten options.
  5675. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  5676. CmdArgs.push_back("-lstdc++");
  5677. continue;
  5678. }
  5679. // Don't render as input, we need gcc to do the translations.
  5680. A.render(Args, CmdArgs);
  5681. }
  5682. }
  5683. const std::string customGCCName = D.getCCCGenericGCCName();
  5684. const char *GCCName;
  5685. if (!customGCCName.empty())
  5686. GCCName = customGCCName.c_str();
  5687. else if (D.CCCIsCXX()) {
  5688. GCCName = "g++";
  5689. } else
  5690. GCCName = "gcc";
  5691. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5692. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5693. }
  5694. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  5695. ArgStringList &CmdArgs) const {
  5696. CmdArgs.push_back("-E");
  5697. }
  5698. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  5699. ArgStringList &CmdArgs) const {
  5700. const Driver &D = getToolChain().getDriver();
  5701. switch (JA.getType()) {
  5702. // If -flto, etc. are present then make sure not to force assembly output.
  5703. case types::TY_LLVM_IR:
  5704. case types::TY_LTO_IR:
  5705. case types::TY_LLVM_BC:
  5706. case types::TY_LTO_BC:
  5707. CmdArgs.push_back("-c");
  5708. break;
  5709. // We assume we've got an "integrated" assembler in that gcc will produce an
  5710. // object file itself.
  5711. case types::TY_Object:
  5712. CmdArgs.push_back("-c");
  5713. break;
  5714. case types::TY_PP_Asm:
  5715. CmdArgs.push_back("-S");
  5716. break;
  5717. case types::TY_Nothing:
  5718. CmdArgs.push_back("-fsyntax-only");
  5719. break;
  5720. default:
  5721. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  5722. }
  5723. }
  5724. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  5725. ArgStringList &CmdArgs) const {
  5726. // The types are (hopefully) good enough.
  5727. }
  5728. // Hexagon tools start.
  5729. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  5730. ArgStringList &CmdArgs) const {
  5731. }
  5732. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5733. const InputInfo &Output,
  5734. const InputInfoList &Inputs,
  5735. const ArgList &Args,
  5736. const char *LinkingOutput) const {
  5737. claimNoWarnArgs(Args);
  5738. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5739. const Driver &D = HTC.getDriver();
  5740. ArgStringList CmdArgs;
  5741. std::string MArchString = "-march=hexagon";
  5742. CmdArgs.push_back(Args.MakeArgString(MArchString));
  5743. RenderExtraToolArgs(JA, CmdArgs);
  5744. std::string AsName = "hexagon-llvm-mc";
  5745. std::string MCpuString = "-mcpu=hexagon" +
  5746. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5747. CmdArgs.push_back("-filetype=obj");
  5748. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5749. if (Output.isFilename()) {
  5750. CmdArgs.push_back("-o");
  5751. CmdArgs.push_back(Output.getFilename());
  5752. } else {
  5753. assert(Output.isNothing() && "Unexpected output");
  5754. CmdArgs.push_back("-fsyntax-only");
  5755. }
  5756. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5757. std::string N = llvm::utostr(G.getValue());
  5758. CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
  5759. }
  5760. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5761. // Only pass -x if gcc will understand it; otherwise hope gcc
  5762. // understands the suffix correctly. The main use case this would go
  5763. // wrong in is for linker inputs if they happened to have an odd
  5764. // suffix; really the only way to get this to happen is a command
  5765. // like '-x foobar a.c' which will treat a.c like a linker input.
  5766. //
  5767. // FIXME: For the linker case specifically, can we safely convert
  5768. // inputs into '-Wl,' options?
  5769. for (const auto &II : Inputs) {
  5770. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5771. if (types::isLLVMIR(II.getType()))
  5772. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  5773. << HTC.getTripleString();
  5774. else if (II.getType() == types::TY_AST)
  5775. D.Diag(clang::diag::err_drv_no_ast_support)
  5776. << HTC.getTripleString();
  5777. else if (II.getType() == types::TY_ModuleFile)
  5778. D.Diag(diag::err_drv_no_module_support)
  5779. << HTC.getTripleString();
  5780. if (II.isFilename())
  5781. CmdArgs.push_back(II.getFilename());
  5782. else
  5783. // Don't render as input, we need gcc to do the translations.
  5784. // FIXME: What is this?
  5785. II.getInputArg().render(Args, CmdArgs);
  5786. }
  5787. auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
  5788. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5789. }
  5790. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  5791. ArgStringList &CmdArgs) const {
  5792. }
  5793. static void
  5794. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  5795. const toolchains::HexagonToolChain &HTC,
  5796. const InputInfo &Output, const InputInfoList &Inputs,
  5797. const ArgList &Args, ArgStringList &CmdArgs,
  5798. const char *LinkingOutput) {
  5799. const Driver &D = HTC.getDriver();
  5800. //----------------------------------------------------------------------------
  5801. //
  5802. //----------------------------------------------------------------------------
  5803. bool IsStatic = Args.hasArg(options::OPT_static);
  5804. bool IsShared = Args.hasArg(options::OPT_shared);
  5805. bool IsPIE = Args.hasArg(options::OPT_pie);
  5806. bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
  5807. bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  5808. bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  5809. bool UseG0 = false;
  5810. bool UseShared = IsShared && !IsStatic;
  5811. //----------------------------------------------------------------------------
  5812. // Silence warnings for various options
  5813. //----------------------------------------------------------------------------
  5814. Args.ClaimAllArgs(options::OPT_g_Group);
  5815. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5816. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  5817. // handled somewhere else.
  5818. Args.ClaimAllArgs(options::OPT_static_libgcc);
  5819. //----------------------------------------------------------------------------
  5820. //
  5821. //----------------------------------------------------------------------------
  5822. if (Args.hasArg(options::OPT_s))
  5823. CmdArgs.push_back("-s");
  5824. if (Args.hasArg(options::OPT_r))
  5825. CmdArgs.push_back("-r");
  5826. for (const auto &Opt : HTC.ExtraOpts)
  5827. CmdArgs.push_back(Opt.c_str());
  5828. CmdArgs.push_back("-march=hexagon");
  5829. std::string CpuVer =
  5830. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5831. std::string MCpuString = "-mcpu=hexagon" + CpuVer;
  5832. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5833. if (IsShared) {
  5834. CmdArgs.push_back("-shared");
  5835. // The following should be the default, but doing as hexagon-gcc does.
  5836. CmdArgs.push_back("-call_shared");
  5837. }
  5838. if (IsStatic)
  5839. CmdArgs.push_back("-static");
  5840. if (IsPIE && !IsShared)
  5841. CmdArgs.push_back("-pie");
  5842. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5843. std::string N = llvm::utostr(G.getValue());
  5844. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
  5845. UseG0 = G.getValue() == 0;
  5846. }
  5847. //----------------------------------------------------------------------------
  5848. //
  5849. //----------------------------------------------------------------------------
  5850. CmdArgs.push_back("-o");
  5851. CmdArgs.push_back(Output.getFilename());
  5852. //----------------------------------------------------------------------------
  5853. // moslib
  5854. //----------------------------------------------------------------------------
  5855. std::vector<std::string> OsLibs;
  5856. bool HasStandalone = false;
  5857. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  5858. A->claim();
  5859. OsLibs.emplace_back(A->getValue());
  5860. HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
  5861. }
  5862. if (OsLibs.empty()) {
  5863. OsLibs.push_back("standalone");
  5864. HasStandalone = true;
  5865. }
  5866. //----------------------------------------------------------------------------
  5867. // Start Files
  5868. //----------------------------------------------------------------------------
  5869. const std::string MCpuSuffix = "/" + CpuVer;
  5870. const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
  5871. const std::string RootDir =
  5872. HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
  5873. const std::string StartSubDir =
  5874. "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
  5875. auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
  5876. const char *Name) -> std::string {
  5877. std::string RelName = SubDir + Name;
  5878. std::string P = HTC.GetFilePath(RelName.c_str());
  5879. if (llvm::sys::fs::exists(P))
  5880. return P;
  5881. return RootDir + RelName;
  5882. };
  5883. if (IncStdLib && IncStartFiles) {
  5884. if (!IsShared) {
  5885. if (HasStandalone) {
  5886. std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
  5887. CmdArgs.push_back(Args.MakeArgString(Crt0SA));
  5888. }
  5889. std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
  5890. CmdArgs.push_back(Args.MakeArgString(Crt0));
  5891. }
  5892. std::string Init = UseShared
  5893. ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
  5894. : Find(RootDir, StartSubDir, "/init.o");
  5895. CmdArgs.push_back(Args.MakeArgString(Init));
  5896. }
  5897. //----------------------------------------------------------------------------
  5898. // Library Search Paths
  5899. //----------------------------------------------------------------------------
  5900. const ToolChain::path_list &LibPaths = HTC.getFilePaths();
  5901. for (const auto &LibPath : LibPaths)
  5902. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  5903. //----------------------------------------------------------------------------
  5904. //
  5905. //----------------------------------------------------------------------------
  5906. Args.AddAllArgs(CmdArgs,
  5907. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5908. options::OPT_t, options::OPT_u_Group});
  5909. AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
  5910. //----------------------------------------------------------------------------
  5911. // Libraries
  5912. //----------------------------------------------------------------------------
  5913. if (IncStdLib && IncDefLibs) {
  5914. if (D.CCCIsCXX()) {
  5915. HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
  5916. CmdArgs.push_back("-lm");
  5917. }
  5918. CmdArgs.push_back("--start-group");
  5919. if (!IsShared) {
  5920. for (const std::string &Lib : OsLibs)
  5921. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  5922. CmdArgs.push_back("-lc");
  5923. }
  5924. CmdArgs.push_back("-lgcc");
  5925. CmdArgs.push_back("--end-group");
  5926. }
  5927. //----------------------------------------------------------------------------
  5928. // End files
  5929. //----------------------------------------------------------------------------
  5930. if (IncStdLib && IncStartFiles) {
  5931. std::string Fini = UseShared
  5932. ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
  5933. : Find(RootDir, StartSubDir, "/fini.o");
  5934. CmdArgs.push_back(Args.MakeArgString(Fini));
  5935. }
  5936. }
  5937. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5938. const InputInfo &Output,
  5939. const InputInfoList &Inputs,
  5940. const ArgList &Args,
  5941. const char *LinkingOutput) const {
  5942. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5943. ArgStringList CmdArgs;
  5944. constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
  5945. LinkingOutput);
  5946. std::string Linker = HTC.GetProgramPath("hexagon-link");
  5947. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5948. CmdArgs, Inputs));
  5949. }
  5950. // Hexagon tools end.
  5951. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5952. const InputInfo &Output,
  5953. const InputInfoList &Inputs,
  5954. const ArgList &Args,
  5955. const char *LinkingOutput) const {
  5956. std::string Linker = getToolChain().GetProgramPath(getShortName());
  5957. ArgStringList CmdArgs;
  5958. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  5959. CmdArgs.push_back("-shared");
  5960. CmdArgs.push_back("-o");
  5961. CmdArgs.push_back(Output.getFilename());
  5962. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5963. CmdArgs, Inputs));
  5964. }
  5965. // AMDGPU tools end.
  5966. wasm::Linker::Linker(const ToolChain &TC)
  5967. : GnuTool("wasm::Linker", "lld", TC) {}
  5968. bool wasm::Linker::isLinkJob() const {
  5969. return true;
  5970. }
  5971. bool wasm::Linker::hasIntegratedCPP() const {
  5972. return false;
  5973. }
  5974. void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5975. const InputInfo &Output,
  5976. const InputInfoList &Inputs,
  5977. const ArgList &Args,
  5978. const char *LinkingOutput) const {
  5979. const ToolChain &ToolChain = getToolChain();
  5980. const Driver &D = ToolChain.getDriver();
  5981. const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
  5982. ArgStringList CmdArgs;
  5983. CmdArgs.push_back("-flavor");
  5984. CmdArgs.push_back("ld");
  5985. // Enable garbage collection of unused input sections by default, since code
  5986. // size is of particular importance. This is significantly facilitated by
  5987. // the enabling of -ffunction-sections and -fdata-sections in
  5988. // Clang::ConstructJob.
  5989. if (areOptimizationsEnabled(Args))
  5990. CmdArgs.push_back("--gc-sections");
  5991. if (Args.hasArg(options::OPT_rdynamic))
  5992. CmdArgs.push_back("-export-dynamic");
  5993. if (Args.hasArg(options::OPT_s))
  5994. CmdArgs.push_back("--strip-all");
  5995. if (Args.hasArg(options::OPT_shared))
  5996. CmdArgs.push_back("-shared");
  5997. if (Args.hasArg(options::OPT_static))
  5998. CmdArgs.push_back("-Bstatic");
  5999. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6000. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6001. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6002. if (Args.hasArg(options::OPT_shared))
  6003. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
  6004. else if (Args.hasArg(options::OPT_pie))
  6005. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
  6006. else
  6007. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  6008. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6009. }
  6010. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6011. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6012. if (D.CCCIsCXX())
  6013. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6014. if (Args.hasArg(options::OPT_pthread))
  6015. CmdArgs.push_back("-lpthread");
  6016. CmdArgs.push_back("-lc");
  6017. CmdArgs.push_back("-lcompiler_rt");
  6018. }
  6019. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6020. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  6021. CmdArgs.push_back("-o");
  6022. CmdArgs.push_back(Output.getFilename());
  6023. C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
  6024. }
  6025. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  6026. std::string MArch;
  6027. if (!Arch.empty())
  6028. MArch = Arch;
  6029. else
  6030. MArch = Triple.getArchName();
  6031. MArch = StringRef(MArch).split("+").first.lower();
  6032. // Handle -march=native.
  6033. if (MArch == "native") {
  6034. std::string CPU = llvm::sys::getHostCPUName();
  6035. if (CPU != "generic") {
  6036. // Translate the native cpu into the architecture suffix for that CPU.
  6037. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  6038. // If there is no valid architecture suffix for this CPU we don't know how
  6039. // to handle it, so return no architecture.
  6040. if (Suffix.empty())
  6041. MArch = "";
  6042. else
  6043. MArch = std::string("arm") + Suffix.str();
  6044. }
  6045. }
  6046. return MArch;
  6047. }
  6048. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  6049. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  6050. std::string MArch = getARMArch(Arch, Triple);
  6051. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  6052. // here means an -march=native that we can't handle, so instead return no CPU.
  6053. if (MArch.empty())
  6054. return StringRef();
  6055. // We need to return an empty string here on invalid MArch values as the
  6056. // various places that call this function can't cope with a null result.
  6057. return Triple.getARMCPUForArch(MArch);
  6058. }
  6059. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  6060. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  6061. const llvm::Triple &Triple) {
  6062. // FIXME: Warn on inconsistent use of -mcpu and -march.
  6063. // If we have -mcpu=, use that.
  6064. if (!CPU.empty()) {
  6065. std::string MCPU = StringRef(CPU).split("+").first.lower();
  6066. // Handle -mcpu=native.
  6067. if (MCPU == "native")
  6068. return llvm::sys::getHostCPUName();
  6069. else
  6070. return MCPU;
  6071. }
  6072. return getARMCPUForMArch(Arch, Triple);
  6073. }
  6074. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  6075. /// CPU (or Arch, if CPU is generic).
  6076. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  6077. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  6078. const llvm::Triple &Triple) {
  6079. unsigned ArchKind;
  6080. if (CPU == "generic") {
  6081. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  6082. ArchKind = llvm::ARM::parseArch(ARMArch);
  6083. if (ArchKind == llvm::ARM::AK_INVALID)
  6084. // In case of generic Arch, i.e. "arm",
  6085. // extract arch from default cpu of the Triple
  6086. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  6087. } else {
  6088. // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
  6089. // armv7k triple if it's actually been specified via "-arch armv7k".
  6090. ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
  6091. ? (unsigned)llvm::ARM::AK_ARMV7K
  6092. : llvm::ARM::parseCPUArch(CPU);
  6093. }
  6094. if (ArchKind == llvm::ARM::AK_INVALID)
  6095. return "";
  6096. return llvm::ARM::getSubArch(ArchKind);
  6097. }
  6098. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  6099. const llvm::Triple &Triple) {
  6100. if (Args.hasArg(options::OPT_r))
  6101. return;
  6102. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  6103. // to generate BE-8 executables.
  6104. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  6105. CmdArgs.push_back("--be8");
  6106. }
  6107. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  6108. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  6109. // was first introduced in Release 3. However, other compilers have
  6110. // traditionally allowed it for Release 2 so we should do the same.
  6111. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  6112. .Case("mips1", NanLegacy)
  6113. .Case("mips2", NanLegacy)
  6114. .Case("mips3", NanLegacy)
  6115. .Case("mips4", NanLegacy)
  6116. .Case("mips5", NanLegacy)
  6117. .Case("mips32", NanLegacy)
  6118. .Case("mips32r2", NanLegacy | Nan2008)
  6119. .Case("mips32r3", NanLegacy | Nan2008)
  6120. .Case("mips32r5", NanLegacy | Nan2008)
  6121. .Case("mips32r6", Nan2008)
  6122. .Case("mips64", NanLegacy)
  6123. .Case("mips64r2", NanLegacy | Nan2008)
  6124. .Case("mips64r3", NanLegacy | Nan2008)
  6125. .Case("mips64r5", NanLegacy | Nan2008)
  6126. .Case("mips64r6", Nan2008)
  6127. .Default(NanLegacy);
  6128. }
  6129. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  6130. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  6131. return A && (A->getValue() == StringRef(Value));
  6132. }
  6133. bool mips::isUCLibc(const ArgList &Args) {
  6134. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  6135. return A && A->getOption().matches(options::OPT_muclibc);
  6136. }
  6137. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  6138. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  6139. return llvm::StringSwitch<bool>(NaNArg->getValue())
  6140. .Case("2008", true)
  6141. .Case("legacy", false)
  6142. .Default(false);
  6143. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  6144. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  6145. .Cases("mips32r6", "mips64r6", true)
  6146. .Default(false);
  6147. return false;
  6148. }
  6149. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  6150. StringRef ABIName, mips::FloatABI FloatABI) {
  6151. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  6152. Triple.getVendor() != llvm::Triple::MipsTechnologies)
  6153. return false;
  6154. if (ABIName != "32")
  6155. return false;
  6156. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  6157. // present.
  6158. if (FloatABI == mips::FloatABI::Soft)
  6159. return false;
  6160. return llvm::StringSwitch<bool>(CPUName)
  6161. .Cases("mips2", "mips3", "mips4", "mips5", true)
  6162. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  6163. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  6164. .Default(false);
  6165. }
  6166. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  6167. StringRef CPUName, StringRef ABIName,
  6168. mips::FloatABI FloatABI) {
  6169. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  6170. // FPXX shouldn't be used if -msingle-float is present.
  6171. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  6172. options::OPT_mdouble_float))
  6173. if (A->getOption().matches(options::OPT_msingle_float))
  6174. UseFPXX = false;
  6175. return UseFPXX;
  6176. }
  6177. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  6178. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  6179. // archs which Darwin doesn't use.
  6180. // The matching this routine does is fairly pointless, since it is neither the
  6181. // complete architecture list, nor a reasonable subset. The problem is that
  6182. // historically the driver driver accepts this and also ties its -march=
  6183. // handling to the architecture name, so we need to be careful before removing
  6184. // support for it.
  6185. // This code must be kept in sync with Clang's Darwin specific argument
  6186. // translation.
  6187. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  6188. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  6189. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  6190. .Case("ppc64", llvm::Triple::ppc64)
  6191. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  6192. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  6193. llvm::Triple::x86)
  6194. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  6195. // This is derived from the driver driver.
  6196. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  6197. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  6198. .Cases("armv7s", "xscale", llvm::Triple::arm)
  6199. .Case("arm64", llvm::Triple::aarch64)
  6200. .Case("r600", llvm::Triple::r600)
  6201. .Case("amdgcn", llvm::Triple::amdgcn)
  6202. .Case("nvptx", llvm::Triple::nvptx)
  6203. .Case("nvptx64", llvm::Triple::nvptx64)
  6204. .Case("amdil", llvm::Triple::amdil)
  6205. .Case("spir", llvm::Triple::spir)
  6206. .Default(llvm::Triple::UnknownArch);
  6207. }
  6208. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  6209. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  6210. T.setArch(Arch);
  6211. if (Str == "x86_64h")
  6212. T.setArchName(Str);
  6213. else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
  6214. T.setOS(llvm::Triple::UnknownOS);
  6215. T.setObjectFormat(llvm::Triple::MachO);
  6216. }
  6217. }
  6218. const char *Clang::getBaseInputName(const ArgList &Args,
  6219. const InputInfo &Input) {
  6220. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  6221. }
  6222. const char *Clang::getBaseInputStem(const ArgList &Args,
  6223. const InputInfoList &Inputs) {
  6224. const char *Str = getBaseInputName(Args, Inputs[0]);
  6225. if (const char *End = strrchr(Str, '.'))
  6226. return Args.MakeArgString(std::string(Str, End));
  6227. return Str;
  6228. }
  6229. const char *Clang::getDependencyFileName(const ArgList &Args,
  6230. const InputInfoList &Inputs) {
  6231. // FIXME: Think about this more.
  6232. std::string Res;
  6233. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  6234. std::string Str(OutputOpt->getValue());
  6235. Res = Str.substr(0, Str.rfind('.'));
  6236. } else {
  6237. Res = getBaseInputStem(Args, Inputs);
  6238. }
  6239. return Args.MakeArgString(Res + ".d");
  6240. }
  6241. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6242. const InputInfo &Output,
  6243. const InputInfoList &Inputs,
  6244. const ArgList &Args,
  6245. const char *LinkingOutput) const {
  6246. const ToolChain &ToolChain = getToolChain();
  6247. const Driver &D = ToolChain.getDriver();
  6248. ArgStringList CmdArgs;
  6249. // Silence warning for "clang -g foo.o -o foo"
  6250. Args.ClaimAllArgs(options::OPT_g_Group);
  6251. // and "clang -emit-llvm foo.o -o foo"
  6252. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6253. // and for "clang -w foo.o -o foo". Other warning options are already
  6254. // handled somewhere else.
  6255. Args.ClaimAllArgs(options::OPT_w);
  6256. if (!D.SysRoot.empty())
  6257. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6258. // CloudABI only supports static linkage.
  6259. CmdArgs.push_back("-Bstatic");
  6260. // CloudABI uses Position Independent Executables exclusively.
  6261. CmdArgs.push_back("-pie");
  6262. CmdArgs.push_back("--no-dynamic-linker");
  6263. CmdArgs.push_back("-zrelro");
  6264. CmdArgs.push_back("--eh-frame-hdr");
  6265. CmdArgs.push_back("--gc-sections");
  6266. if (Output.isFilename()) {
  6267. CmdArgs.push_back("-o");
  6268. CmdArgs.push_back(Output.getFilename());
  6269. } else {
  6270. assert(Output.isNothing() && "Invalid output.");
  6271. }
  6272. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6273. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  6274. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  6275. }
  6276. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6277. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6278. Args.AddAllArgs(CmdArgs,
  6279. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  6280. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  6281. if (D.isUsingLTO())
  6282. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  6283. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6284. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6285. if (D.CCCIsCXX())
  6286. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6287. CmdArgs.push_back("-lc");
  6288. CmdArgs.push_back("-lcompiler_rt");
  6289. }
  6290. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6291. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  6292. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  6293. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6294. }
  6295. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6296. const InputInfo &Output,
  6297. const InputInfoList &Inputs,
  6298. const ArgList &Args,
  6299. const char *LinkingOutput) const {
  6300. ArgStringList CmdArgs;
  6301. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  6302. const InputInfo &Input = Inputs[0];
  6303. // Determine the original source input.
  6304. const Action *SourceAction = &JA;
  6305. while (SourceAction->getKind() != Action::InputClass) {
  6306. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  6307. SourceAction = SourceAction->getInputs()[0];
  6308. }
  6309. // If -fno-integrated-as is used add -Q to the darwin assember driver to make
  6310. // sure it runs its system assembler not clang's integrated assembler.
  6311. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  6312. // FIXME: at run-time detect assembler capabilities or rely on version
  6313. // information forwarded by -target-assembler-version.
  6314. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  6315. const llvm::Triple &T(getToolChain().getTriple());
  6316. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  6317. CmdArgs.push_back("-Q");
  6318. }
  6319. // Forward -g, assuming we are dealing with an actual assembly file.
  6320. if (SourceAction->getType() == types::TY_Asm ||
  6321. SourceAction->getType() == types::TY_PP_Asm) {
  6322. if (Args.hasArg(options::OPT_gstabs))
  6323. CmdArgs.push_back("--gstabs");
  6324. else if (Args.hasArg(options::OPT_g_Group))
  6325. CmdArgs.push_back("-g");
  6326. }
  6327. // Derived from asm spec.
  6328. AddMachOArch(Args, CmdArgs);
  6329. // Use -force_cpusubtype_ALL on x86 by default.
  6330. if (getToolChain().getArch() == llvm::Triple::x86 ||
  6331. getToolChain().getArch() == llvm::Triple::x86_64 ||
  6332. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  6333. CmdArgs.push_back("-force_cpusubtype_ALL");
  6334. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  6335. (((Args.hasArg(options::OPT_mkernel) ||
  6336. Args.hasArg(options::OPT_fapple_kext)) &&
  6337. getMachOToolChain().isKernelStatic()) ||
  6338. Args.hasArg(options::OPT_static)))
  6339. CmdArgs.push_back("-static");
  6340. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6341. assert(Output.isFilename() && "Unexpected lipo output.");
  6342. CmdArgs.push_back("-o");
  6343. CmdArgs.push_back(Output.getFilename());
  6344. assert(Input.isFilename() && "Invalid input.");
  6345. CmdArgs.push_back(Input.getFilename());
  6346. // asm_final spec is empty.
  6347. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6348. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6349. }
  6350. void darwin::MachOTool::anchor() {}
  6351. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  6352. ArgStringList &CmdArgs) const {
  6353. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  6354. // Derived from darwin_arch spec.
  6355. CmdArgs.push_back("-arch");
  6356. CmdArgs.push_back(Args.MakeArgString(ArchName));
  6357. // FIXME: Is this needed anymore?
  6358. if (ArchName == "arm")
  6359. CmdArgs.push_back("-force_cpusubtype_ALL");
  6360. }
  6361. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  6362. // We only need to generate a temp path for LTO if we aren't compiling object
  6363. // files. When compiling source files, we run 'dsymutil' after linking. We
  6364. // don't run 'dsymutil' when compiling object files.
  6365. for (const auto &Input : Inputs)
  6366. if (Input.getType() != types::TY_Object)
  6367. return true;
  6368. return false;
  6369. }
  6370. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  6371. ArgStringList &CmdArgs,
  6372. const InputInfoList &Inputs) const {
  6373. const Driver &D = getToolChain().getDriver();
  6374. const toolchains::MachO &MachOTC = getMachOToolChain();
  6375. unsigned Version[5] = {0, 0, 0, 0, 0};
  6376. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  6377. if (!Driver::GetReleaseVersion(A->getValue(), Version))
  6378. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  6379. }
  6380. // Newer linkers support -demangle. Pass it if supported and not disabled by
  6381. // the user.
  6382. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  6383. CmdArgs.push_back("-demangle");
  6384. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  6385. CmdArgs.push_back("-export_dynamic");
  6386. // If we are using App Extension restrictions, pass a flag to the linker
  6387. // telling it that the compiled code has been audited.
  6388. if (Args.hasFlag(options::OPT_fapplication_extension,
  6389. options::OPT_fno_application_extension, false))
  6390. CmdArgs.push_back("-application_extension");
  6391. if (D.isUsingLTO()) {
  6392. // If we are using LTO, then automatically create a temporary file path for
  6393. // the linker to use, so that it's lifetime will extend past a possible
  6394. // dsymutil step.
  6395. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  6396. const char *TmpPath = C.getArgs().MakeArgString(
  6397. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  6398. C.addTempFile(TmpPath);
  6399. CmdArgs.push_back("-object_path_lto");
  6400. CmdArgs.push_back(TmpPath);
  6401. }
  6402. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  6403. // it in clang installed libraries. If not found, the option is not used
  6404. // and 'ld' will use its default mechanism to search for libLTO.dylib.
  6405. if (Version[0] >= 133) {
  6406. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  6407. StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
  6408. SmallString<128> LibLTOPath(P);
  6409. llvm::sys::path::append(LibLTOPath, "lib");
  6410. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  6411. if (llvm::sys::fs::exists(LibLTOPath)) {
  6412. CmdArgs.push_back("-lto_library");
  6413. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  6414. } else {
  6415. D.Diag(diag::warn_drv_lto_libpath);
  6416. }
  6417. }
  6418. }
  6419. // Derived from the "link" spec.
  6420. Args.AddAllArgs(CmdArgs, options::OPT_static);
  6421. if (!Args.hasArg(options::OPT_static))
  6422. CmdArgs.push_back("-dynamic");
  6423. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  6424. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  6425. // here. How do we wish to handle such things?
  6426. }
  6427. if (!Args.hasArg(options::OPT_dynamiclib)) {
  6428. AddMachOArch(Args, CmdArgs);
  6429. // FIXME: Why do this only on this path?
  6430. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  6431. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  6432. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  6433. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  6434. Arg *A;
  6435. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  6436. (A = Args.getLastArg(options::OPT_current__version)) ||
  6437. (A = Args.getLastArg(options::OPT_install__name)))
  6438. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  6439. << "-dynamiclib";
  6440. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  6441. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  6442. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  6443. } else {
  6444. CmdArgs.push_back("-dylib");
  6445. Arg *A;
  6446. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  6447. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  6448. (A = Args.getLastArg(options::OPT_client__name)) ||
  6449. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  6450. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  6451. (A = Args.getLastArg(options::OPT_private__bundle)))
  6452. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  6453. << "-dynamiclib";
  6454. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  6455. "-dylib_compatibility_version");
  6456. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  6457. "-dylib_current_version");
  6458. AddMachOArch(Args, CmdArgs);
  6459. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  6460. "-dylib_install_name");
  6461. }
  6462. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  6463. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  6464. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  6465. if (MachOTC.isTargetIOSBased())
  6466. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  6467. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  6468. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  6469. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  6470. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  6471. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  6472. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  6473. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  6474. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  6475. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  6476. Args.AddAllArgs(CmdArgs, options::OPT_init);
  6477. // Add the deployment target.
  6478. MachOTC.addMinVersionArgs(Args, CmdArgs);
  6479. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  6480. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  6481. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  6482. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  6483. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  6484. if (const Arg *A =
  6485. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  6486. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  6487. if (A->getOption().matches(options::OPT_fpie) ||
  6488. A->getOption().matches(options::OPT_fPIE))
  6489. CmdArgs.push_back("-pie");
  6490. else
  6491. CmdArgs.push_back("-no_pie");
  6492. }
  6493. // for embed-bitcode, use -bitcode_bundle in linker command
  6494. if (C.getDriver().embedBitcodeEnabled() ||
  6495. C.getDriver().embedBitcodeMarkerOnly()) {
  6496. // Check if the toolchain supports bitcode build flow.
  6497. if (MachOTC.SupportsEmbeddedBitcode())
  6498. CmdArgs.push_back("-bitcode_bundle");
  6499. else
  6500. D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
  6501. }
  6502. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  6503. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  6504. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  6505. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  6506. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  6507. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  6508. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  6509. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  6510. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  6511. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  6512. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  6513. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  6514. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  6515. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  6516. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  6517. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  6518. // Give --sysroot= preference, over the Apple specific behavior to also use
  6519. // --isysroot as the syslibroot.
  6520. StringRef sysroot = C.getSysRoot();
  6521. if (sysroot != "") {
  6522. CmdArgs.push_back("-syslibroot");
  6523. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  6524. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  6525. CmdArgs.push_back("-syslibroot");
  6526. CmdArgs.push_back(A->getValue());
  6527. }
  6528. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  6529. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  6530. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  6531. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  6532. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  6533. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  6534. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  6535. Args.AddAllArgs(CmdArgs, options::OPT_y);
  6536. Args.AddLastArg(CmdArgs, options::OPT_w);
  6537. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  6538. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  6539. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  6540. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  6541. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  6542. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  6543. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  6544. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  6545. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  6546. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  6547. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  6548. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  6549. }
  6550. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6551. const InputInfo &Output,
  6552. const InputInfoList &Inputs,
  6553. const ArgList &Args,
  6554. const char *LinkingOutput) const {
  6555. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  6556. // If the number of arguments surpasses the system limits, we will encode the
  6557. // input files in a separate file, shortening the command line. To this end,
  6558. // build a list of input file names that can be passed via a file with the
  6559. // -filelist linker option.
  6560. llvm::opt::ArgStringList InputFileList;
  6561. // The logic here is derived from gcc's behavior; most of which
  6562. // comes from specs (starting with link_command). Consult gcc for
  6563. // more information.
  6564. ArgStringList CmdArgs;
  6565. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  6566. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  6567. options::OPT_ccc_arcmt_migrate)) {
  6568. for (const auto &Arg : Args)
  6569. Arg->claim();
  6570. const char *Exec =
  6571. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  6572. CmdArgs.push_back(Output.getFilename());
  6573. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  6574. return;
  6575. }
  6576. // I'm not sure why this particular decomposition exists in gcc, but
  6577. // we follow suite for ease of comparison.
  6578. AddLinkArgs(C, Args, CmdArgs, Inputs);
  6579. // It seems that the 'e' option is completely ignored for dynamic executables
  6580. // (the default), and with static executables, the last one wins, as expected.
  6581. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  6582. options::OPT_Z_Flag, options::OPT_u_Group,
  6583. options::OPT_e, options::OPT_r});
  6584. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  6585. // members of static archive libraries which implement Objective-C classes or
  6586. // categories.
  6587. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  6588. CmdArgs.push_back("-ObjC");
  6589. CmdArgs.push_back("-o");
  6590. CmdArgs.push_back(Output.getFilename());
  6591. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6592. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  6593. // SafeStack requires its own runtime libraries
  6594. // These libraries should be linked first, to make sure the
  6595. // __safestack_init constructor executes before everything else
  6596. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  6597. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  6598. "libclang_rt.safestack_osx.a",
  6599. /*AlwaysLink=*/true);
  6600. }
  6601. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6602. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6603. // Build the input file for -filelist (list of linker input files) in case we
  6604. // need it later
  6605. for (const auto &II : Inputs) {
  6606. if (!II.isFilename()) {
  6607. // This is a linker input argument.
  6608. // We cannot mix input arguments and file names in a -filelist input, thus
  6609. // we prematurely stop our list (remaining files shall be passed as
  6610. // arguments).
  6611. if (InputFileList.size() > 0)
  6612. break;
  6613. continue;
  6614. }
  6615. InputFileList.push_back(II.getFilename());
  6616. }
  6617. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  6618. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  6619. if (isObjCRuntimeLinked(Args) &&
  6620. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6621. // We use arclite library for both ARC and subscripting support.
  6622. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  6623. CmdArgs.push_back("-framework");
  6624. CmdArgs.push_back("Foundation");
  6625. // Link libobj.
  6626. CmdArgs.push_back("-lobjc");
  6627. }
  6628. if (LinkingOutput) {
  6629. CmdArgs.push_back("-arch_multiple");
  6630. CmdArgs.push_back("-final_output");
  6631. CmdArgs.push_back(LinkingOutput);
  6632. }
  6633. if (Args.hasArg(options::OPT_fnested_functions))
  6634. CmdArgs.push_back("-allow_stack_execute");
  6635. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  6636. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6637. if (getToolChain().getDriver().CCCIsCXX())
  6638. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6639. // link_ssp spec is empty.
  6640. // Let the tool chain choose which runtime library to link.
  6641. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  6642. }
  6643. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6644. // endfile_spec is empty.
  6645. }
  6646. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6647. Args.AddAllArgs(CmdArgs, options::OPT_F);
  6648. // -iframework should be forwarded as -F.
  6649. for (const Arg *A : Args.filtered(options::OPT_iframework))
  6650. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  6651. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6652. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  6653. if (A->getValue() == StringRef("Accelerate")) {
  6654. CmdArgs.push_back("-framework");
  6655. CmdArgs.push_back("Accelerate");
  6656. }
  6657. }
  6658. }
  6659. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6660. std::unique_ptr<Command> Cmd =
  6661. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  6662. Cmd->setInputFileList(std::move(InputFileList));
  6663. C.addCommand(std::move(Cmd));
  6664. }
  6665. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  6666. const InputInfo &Output,
  6667. const InputInfoList &Inputs,
  6668. const ArgList &Args,
  6669. const char *LinkingOutput) const {
  6670. ArgStringList CmdArgs;
  6671. CmdArgs.push_back("-create");
  6672. assert(Output.isFilename() && "Unexpected lipo output.");
  6673. CmdArgs.push_back("-output");
  6674. CmdArgs.push_back(Output.getFilename());
  6675. for (const auto &II : Inputs) {
  6676. assert(II.isFilename() && "Unexpected lipo input.");
  6677. CmdArgs.push_back(II.getFilename());
  6678. }
  6679. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  6680. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6681. }
  6682. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  6683. const InputInfo &Output,
  6684. const InputInfoList &Inputs,
  6685. const ArgList &Args,
  6686. const char *LinkingOutput) const {
  6687. ArgStringList CmdArgs;
  6688. CmdArgs.push_back("-o");
  6689. CmdArgs.push_back(Output.getFilename());
  6690. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6691. const InputInfo &Input = Inputs[0];
  6692. assert(Input.isFilename() && "Unexpected dsymutil input.");
  6693. CmdArgs.push_back(Input.getFilename());
  6694. const char *Exec =
  6695. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  6696. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6697. }
  6698. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  6699. const InputInfo &Output,
  6700. const InputInfoList &Inputs,
  6701. const ArgList &Args,
  6702. const char *LinkingOutput) const {
  6703. ArgStringList CmdArgs;
  6704. CmdArgs.push_back("--verify");
  6705. CmdArgs.push_back("--debug-info");
  6706. CmdArgs.push_back("--eh-frame");
  6707. CmdArgs.push_back("--quiet");
  6708. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6709. const InputInfo &Input = Inputs[0];
  6710. assert(Input.isFilename() && "Unexpected verify input");
  6711. // Grabbing the output of the earlier dsymutil run.
  6712. CmdArgs.push_back(Input.getFilename());
  6713. const char *Exec =
  6714. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  6715. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6716. }
  6717. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6718. const InputInfo &Output,
  6719. const InputInfoList &Inputs,
  6720. const ArgList &Args,
  6721. const char *LinkingOutput) const {
  6722. claimNoWarnArgs(Args);
  6723. ArgStringList CmdArgs;
  6724. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6725. CmdArgs.push_back("-o");
  6726. CmdArgs.push_back(Output.getFilename());
  6727. for (const auto &II : Inputs)
  6728. CmdArgs.push_back(II.getFilename());
  6729. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6730. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6731. }
  6732. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6733. const InputInfo &Output,
  6734. const InputInfoList &Inputs,
  6735. const ArgList &Args,
  6736. const char *LinkingOutput) const {
  6737. ArgStringList CmdArgs;
  6738. // Demangle C++ names in errors
  6739. CmdArgs.push_back("-C");
  6740. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6741. CmdArgs.push_back("-e");
  6742. CmdArgs.push_back("_start");
  6743. }
  6744. if (Args.hasArg(options::OPT_static)) {
  6745. CmdArgs.push_back("-Bstatic");
  6746. CmdArgs.push_back("-dn");
  6747. } else {
  6748. CmdArgs.push_back("-Bdynamic");
  6749. if (Args.hasArg(options::OPT_shared)) {
  6750. CmdArgs.push_back("-shared");
  6751. } else {
  6752. CmdArgs.push_back("--dynamic-linker");
  6753. CmdArgs.push_back(
  6754. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  6755. }
  6756. }
  6757. if (Output.isFilename()) {
  6758. CmdArgs.push_back("-o");
  6759. CmdArgs.push_back(Output.getFilename());
  6760. } else {
  6761. assert(Output.isNothing() && "Invalid output.");
  6762. }
  6763. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6764. if (!Args.hasArg(options::OPT_shared))
  6765. CmdArgs.push_back(
  6766. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  6767. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6768. CmdArgs.push_back(
  6769. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  6770. CmdArgs.push_back(
  6771. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6772. }
  6773. getToolChain().AddFilePathLibArgs(Args, CmdArgs);
  6774. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6775. options::OPT_e, options::OPT_r});
  6776. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6777. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6778. if (getToolChain().getDriver().CCCIsCXX())
  6779. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6780. CmdArgs.push_back("-lgcc_s");
  6781. CmdArgs.push_back("-lc");
  6782. if (!Args.hasArg(options::OPT_shared)) {
  6783. CmdArgs.push_back("-lgcc");
  6784. CmdArgs.push_back("-lm");
  6785. }
  6786. }
  6787. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6788. CmdArgs.push_back(
  6789. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6790. }
  6791. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  6792. getToolChain().addProfileRTLibs(Args, CmdArgs);
  6793. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6794. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6795. }
  6796. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6797. const InputInfo &Output,
  6798. const InputInfoList &Inputs,
  6799. const ArgList &Args,
  6800. const char *LinkingOutput) const {
  6801. claimNoWarnArgs(Args);
  6802. ArgStringList CmdArgs;
  6803. switch (getToolChain().getArch()) {
  6804. case llvm::Triple::x86:
  6805. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  6806. // instruct as in the base system to assemble 32-bit code.
  6807. CmdArgs.push_back("--32");
  6808. break;
  6809. case llvm::Triple::ppc:
  6810. CmdArgs.push_back("-mppc");
  6811. CmdArgs.push_back("-many");
  6812. break;
  6813. case llvm::Triple::sparc:
  6814. case llvm::Triple::sparcel: {
  6815. CmdArgs.push_back("-32");
  6816. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6817. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6818. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6819. break;
  6820. }
  6821. case llvm::Triple::sparcv9: {
  6822. CmdArgs.push_back("-64");
  6823. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6824. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6825. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6826. break;
  6827. }
  6828. case llvm::Triple::mips64:
  6829. case llvm::Triple::mips64el: {
  6830. StringRef CPUName;
  6831. StringRef ABIName;
  6832. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6833. CmdArgs.push_back("-mabi");
  6834. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6835. if (getToolChain().getArch() == llvm::Triple::mips64)
  6836. CmdArgs.push_back("-EB");
  6837. else
  6838. CmdArgs.push_back("-EL");
  6839. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6840. break;
  6841. }
  6842. default:
  6843. break;
  6844. }
  6845. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6846. CmdArgs.push_back("-o");
  6847. CmdArgs.push_back(Output.getFilename());
  6848. for (const auto &II : Inputs)
  6849. CmdArgs.push_back(II.getFilename());
  6850. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6851. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6852. }
  6853. void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6854. const InputInfo &Output,
  6855. const InputInfoList &Inputs,
  6856. const ArgList &Args,
  6857. const char *LinkingOutput) const {
  6858. const Driver &D = getToolChain().getDriver();
  6859. ArgStringList CmdArgs;
  6860. // Silence warning for "clang -g foo.o -o foo"
  6861. Args.ClaimAllArgs(options::OPT_g_Group);
  6862. // and "clang -emit-llvm foo.o -o foo"
  6863. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6864. // and for "clang -w foo.o -o foo". Other warning options are already
  6865. // handled somewhere else.
  6866. Args.ClaimAllArgs(options::OPT_w);
  6867. if (getToolChain().getArch() == llvm::Triple::mips64)
  6868. CmdArgs.push_back("-EB");
  6869. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  6870. CmdArgs.push_back("-EL");
  6871. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6872. CmdArgs.push_back("-e");
  6873. CmdArgs.push_back("__start");
  6874. }
  6875. if (Args.hasArg(options::OPT_static)) {
  6876. CmdArgs.push_back("-Bstatic");
  6877. } else {
  6878. if (Args.hasArg(options::OPT_rdynamic))
  6879. CmdArgs.push_back("-export-dynamic");
  6880. CmdArgs.push_back("--eh-frame-hdr");
  6881. CmdArgs.push_back("-Bdynamic");
  6882. if (Args.hasArg(options::OPT_shared)) {
  6883. CmdArgs.push_back("-shared");
  6884. } else {
  6885. CmdArgs.push_back("-dynamic-linker");
  6886. CmdArgs.push_back("/usr/libexec/ld.so");
  6887. }
  6888. }
  6889. if (Args.hasArg(options::OPT_nopie))
  6890. CmdArgs.push_back("-nopie");
  6891. if (Output.isFilename()) {
  6892. CmdArgs.push_back("-o");
  6893. CmdArgs.push_back(Output.getFilename());
  6894. } else {
  6895. assert(Output.isNothing() && "Invalid output.");
  6896. }
  6897. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6898. if (!Args.hasArg(options::OPT_shared)) {
  6899. if (Args.hasArg(options::OPT_pg))
  6900. CmdArgs.push_back(
  6901. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6902. else
  6903. CmdArgs.push_back(
  6904. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6905. CmdArgs.push_back(
  6906. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6907. } else {
  6908. CmdArgs.push_back(
  6909. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6910. }
  6911. }
  6912. std::string Triple = getToolChain().getTripleString();
  6913. if (Triple.substr(0, 6) == "x86_64")
  6914. Triple.replace(0, 6, "amd64");
  6915. CmdArgs.push_back(
  6916. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  6917. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6918. options::OPT_e, options::OPT_s, options::OPT_t,
  6919. options::OPT_Z_Flag, options::OPT_r});
  6920. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6921. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6922. if (D.CCCIsCXX()) {
  6923. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6924. if (Args.hasArg(options::OPT_pg))
  6925. CmdArgs.push_back("-lm_p");
  6926. else
  6927. CmdArgs.push_back("-lm");
  6928. }
  6929. // FIXME: For some reason GCC passes -lgcc before adding
  6930. // the default system libraries. Just mimic this for now.
  6931. CmdArgs.push_back("-lgcc");
  6932. if (Args.hasArg(options::OPT_pthread)) {
  6933. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6934. CmdArgs.push_back("-lpthread_p");
  6935. else
  6936. CmdArgs.push_back("-lpthread");
  6937. }
  6938. if (!Args.hasArg(options::OPT_shared)) {
  6939. if (Args.hasArg(options::OPT_pg))
  6940. CmdArgs.push_back("-lc_p");
  6941. else
  6942. CmdArgs.push_back("-lc");
  6943. }
  6944. CmdArgs.push_back("-lgcc");
  6945. }
  6946. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6947. if (!Args.hasArg(options::OPT_shared))
  6948. CmdArgs.push_back(
  6949. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6950. else
  6951. CmdArgs.push_back(
  6952. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6953. }
  6954. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6955. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6956. }
  6957. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6958. const InputInfo &Output,
  6959. const InputInfoList &Inputs,
  6960. const ArgList &Args,
  6961. const char *LinkingOutput) const {
  6962. claimNoWarnArgs(Args);
  6963. ArgStringList CmdArgs;
  6964. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6965. CmdArgs.push_back("-o");
  6966. CmdArgs.push_back(Output.getFilename());
  6967. for (const auto &II : Inputs)
  6968. CmdArgs.push_back(II.getFilename());
  6969. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6970. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6971. }
  6972. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6973. const InputInfo &Output,
  6974. const InputInfoList &Inputs,
  6975. const ArgList &Args,
  6976. const char *LinkingOutput) const {
  6977. const Driver &D = getToolChain().getDriver();
  6978. ArgStringList CmdArgs;
  6979. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6980. CmdArgs.push_back("-e");
  6981. CmdArgs.push_back("__start");
  6982. }
  6983. if (Args.hasArg(options::OPT_static)) {
  6984. CmdArgs.push_back("-Bstatic");
  6985. } else {
  6986. if (Args.hasArg(options::OPT_rdynamic))
  6987. CmdArgs.push_back("-export-dynamic");
  6988. CmdArgs.push_back("--eh-frame-hdr");
  6989. CmdArgs.push_back("-Bdynamic");
  6990. if (Args.hasArg(options::OPT_shared)) {
  6991. CmdArgs.push_back("-shared");
  6992. } else {
  6993. CmdArgs.push_back("-dynamic-linker");
  6994. CmdArgs.push_back("/usr/libexec/ld.so");
  6995. }
  6996. }
  6997. if (Output.isFilename()) {
  6998. CmdArgs.push_back("-o");
  6999. CmdArgs.push_back(Output.getFilename());
  7000. } else {
  7001. assert(Output.isNothing() && "Invalid output.");
  7002. }
  7003. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7004. if (!Args.hasArg(options::OPT_shared)) {
  7005. if (Args.hasArg(options::OPT_pg))
  7006. CmdArgs.push_back(
  7007. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  7008. else
  7009. CmdArgs.push_back(
  7010. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7011. CmdArgs.push_back(
  7012. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7013. } else {
  7014. CmdArgs.push_back(
  7015. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7016. }
  7017. }
  7018. Args.AddAllArgs(CmdArgs,
  7019. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7020. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7021. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7022. if (D.CCCIsCXX()) {
  7023. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7024. if (Args.hasArg(options::OPT_pg))
  7025. CmdArgs.push_back("-lm_p");
  7026. else
  7027. CmdArgs.push_back("-lm");
  7028. }
  7029. if (Args.hasArg(options::OPT_pthread)) {
  7030. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  7031. CmdArgs.push_back("-lpthread_p");
  7032. else
  7033. CmdArgs.push_back("-lpthread");
  7034. }
  7035. if (!Args.hasArg(options::OPT_shared)) {
  7036. if (Args.hasArg(options::OPT_pg))
  7037. CmdArgs.push_back("-lc_p");
  7038. else
  7039. CmdArgs.push_back("-lc");
  7040. }
  7041. StringRef MyArch;
  7042. switch (getToolChain().getArch()) {
  7043. case llvm::Triple::arm:
  7044. MyArch = "arm";
  7045. break;
  7046. case llvm::Triple::x86:
  7047. MyArch = "i386";
  7048. break;
  7049. case llvm::Triple::x86_64:
  7050. MyArch = "amd64";
  7051. break;
  7052. default:
  7053. llvm_unreachable("Unsupported architecture");
  7054. }
  7055. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  7056. }
  7057. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7058. if (!Args.hasArg(options::OPT_shared))
  7059. CmdArgs.push_back(
  7060. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7061. else
  7062. CmdArgs.push_back(
  7063. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7064. }
  7065. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7066. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7067. }
  7068. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7069. const InputInfo &Output,
  7070. const InputInfoList &Inputs,
  7071. const ArgList &Args,
  7072. const char *LinkingOutput) const {
  7073. claimNoWarnArgs(Args);
  7074. ArgStringList CmdArgs;
  7075. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  7076. // instruct as in the base system to assemble 32-bit code.
  7077. switch (getToolChain().getArch()) {
  7078. default:
  7079. break;
  7080. case llvm::Triple::x86:
  7081. CmdArgs.push_back("--32");
  7082. break;
  7083. case llvm::Triple::ppc:
  7084. CmdArgs.push_back("-a32");
  7085. break;
  7086. case llvm::Triple::mips:
  7087. case llvm::Triple::mipsel:
  7088. case llvm::Triple::mips64:
  7089. case llvm::Triple::mips64el: {
  7090. StringRef CPUName;
  7091. StringRef ABIName;
  7092. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7093. CmdArgs.push_back("-march");
  7094. CmdArgs.push_back(CPUName.data());
  7095. CmdArgs.push_back("-mabi");
  7096. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7097. if (getToolChain().getArch() == llvm::Triple::mips ||
  7098. getToolChain().getArch() == llvm::Triple::mips64)
  7099. CmdArgs.push_back("-EB");
  7100. else
  7101. CmdArgs.push_back("-EL");
  7102. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  7103. StringRef v = A->getValue();
  7104. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  7105. A->claim();
  7106. }
  7107. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7108. break;
  7109. }
  7110. case llvm::Triple::arm:
  7111. case llvm::Triple::armeb:
  7112. case llvm::Triple::thumb:
  7113. case llvm::Triple::thumbeb: {
  7114. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  7115. if (ABI == arm::FloatABI::Hard)
  7116. CmdArgs.push_back("-mfpu=vfp");
  7117. else
  7118. CmdArgs.push_back("-mfpu=softvfp");
  7119. switch (getToolChain().getTriple().getEnvironment()) {
  7120. case llvm::Triple::GNUEABIHF:
  7121. case llvm::Triple::GNUEABI:
  7122. case llvm::Triple::EABI:
  7123. CmdArgs.push_back("-meabi=5");
  7124. break;
  7125. default:
  7126. CmdArgs.push_back("-matpcs");
  7127. }
  7128. break;
  7129. }
  7130. case llvm::Triple::sparc:
  7131. case llvm::Triple::sparcel:
  7132. case llvm::Triple::sparcv9: {
  7133. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7134. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7135. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7136. break;
  7137. }
  7138. }
  7139. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7140. CmdArgs.push_back("-o");
  7141. CmdArgs.push_back(Output.getFilename());
  7142. for (const auto &II : Inputs)
  7143. CmdArgs.push_back(II.getFilename());
  7144. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7145. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7146. }
  7147. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7148. const InputInfo &Output,
  7149. const InputInfoList &Inputs,
  7150. const ArgList &Args,
  7151. const char *LinkingOutput) const {
  7152. const toolchains::FreeBSD &ToolChain =
  7153. static_cast<const toolchains::FreeBSD &>(getToolChain());
  7154. const Driver &D = ToolChain.getDriver();
  7155. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7156. const bool IsPIE =
  7157. !Args.hasArg(options::OPT_shared) &&
  7158. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7159. ArgStringList CmdArgs;
  7160. // Silence warning for "clang -g foo.o -o foo"
  7161. Args.ClaimAllArgs(options::OPT_g_Group);
  7162. // and "clang -emit-llvm foo.o -o foo"
  7163. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7164. // and for "clang -w foo.o -o foo". Other warning options are already
  7165. // handled somewhere else.
  7166. Args.ClaimAllArgs(options::OPT_w);
  7167. if (!D.SysRoot.empty())
  7168. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7169. if (IsPIE)
  7170. CmdArgs.push_back("-pie");
  7171. CmdArgs.push_back("--eh-frame-hdr");
  7172. if (Args.hasArg(options::OPT_static)) {
  7173. CmdArgs.push_back("-Bstatic");
  7174. } else {
  7175. if (Args.hasArg(options::OPT_rdynamic))
  7176. CmdArgs.push_back("-export-dynamic");
  7177. if (Args.hasArg(options::OPT_shared)) {
  7178. CmdArgs.push_back("-Bshareable");
  7179. } else {
  7180. CmdArgs.push_back("-dynamic-linker");
  7181. CmdArgs.push_back("/libexec/ld-elf.so.1");
  7182. }
  7183. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  7184. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  7185. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  7186. CmdArgs.push_back("--hash-style=both");
  7187. }
  7188. }
  7189. CmdArgs.push_back("--enable-new-dtags");
  7190. }
  7191. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  7192. // instruct ld in the base system to link 32-bit code.
  7193. if (Arch == llvm::Triple::x86) {
  7194. CmdArgs.push_back("-m");
  7195. CmdArgs.push_back("elf_i386_fbsd");
  7196. }
  7197. if (Arch == llvm::Triple::ppc) {
  7198. CmdArgs.push_back("-m");
  7199. CmdArgs.push_back("elf32ppc_fbsd");
  7200. }
  7201. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  7202. if (ToolChain.getArch() == llvm::Triple::mips ||
  7203. ToolChain.getArch() == llvm::Triple::mipsel ||
  7204. ToolChain.getArch() == llvm::Triple::mips64 ||
  7205. ToolChain.getArch() == llvm::Triple::mips64el) {
  7206. StringRef v = A->getValue();
  7207. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  7208. A->claim();
  7209. }
  7210. }
  7211. if (Output.isFilename()) {
  7212. CmdArgs.push_back("-o");
  7213. CmdArgs.push_back(Output.getFilename());
  7214. } else {
  7215. assert(Output.isNothing() && "Invalid output.");
  7216. }
  7217. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7218. const char *crt1 = nullptr;
  7219. if (!Args.hasArg(options::OPT_shared)) {
  7220. if (Args.hasArg(options::OPT_pg))
  7221. crt1 = "gcrt1.o";
  7222. else if (IsPIE)
  7223. crt1 = "Scrt1.o";
  7224. else
  7225. crt1 = "crt1.o";
  7226. }
  7227. if (crt1)
  7228. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  7229. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7230. const char *crtbegin = nullptr;
  7231. if (Args.hasArg(options::OPT_static))
  7232. crtbegin = "crtbeginT.o";
  7233. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  7234. crtbegin = "crtbeginS.o";
  7235. else
  7236. crtbegin = "crtbegin.o";
  7237. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7238. }
  7239. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7240. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7241. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7242. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7243. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7244. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7245. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7246. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7247. if (D.isUsingLTO())
  7248. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  7249. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7250. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7251. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7252. addOpenMPRuntime(CmdArgs, ToolChain, Args);
  7253. if (D.CCCIsCXX()) {
  7254. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7255. if (Args.hasArg(options::OPT_pg))
  7256. CmdArgs.push_back("-lm_p");
  7257. else
  7258. CmdArgs.push_back("-lm");
  7259. }
  7260. if (NeedsSanitizerDeps)
  7261. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7262. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  7263. // the default system libraries. Just mimic this for now.
  7264. if (Args.hasArg(options::OPT_pg))
  7265. CmdArgs.push_back("-lgcc_p");
  7266. else
  7267. CmdArgs.push_back("-lgcc");
  7268. if (Args.hasArg(options::OPT_static)) {
  7269. CmdArgs.push_back("-lgcc_eh");
  7270. } else if (Args.hasArg(options::OPT_pg)) {
  7271. CmdArgs.push_back("-lgcc_eh_p");
  7272. } else {
  7273. CmdArgs.push_back("--as-needed");
  7274. CmdArgs.push_back("-lgcc_s");
  7275. CmdArgs.push_back("--no-as-needed");
  7276. }
  7277. if (Args.hasArg(options::OPT_pthread)) {
  7278. if (Args.hasArg(options::OPT_pg))
  7279. CmdArgs.push_back("-lpthread_p");
  7280. else
  7281. CmdArgs.push_back("-lpthread");
  7282. }
  7283. if (Args.hasArg(options::OPT_pg)) {
  7284. if (Args.hasArg(options::OPT_shared))
  7285. CmdArgs.push_back("-lc");
  7286. else
  7287. CmdArgs.push_back("-lc_p");
  7288. CmdArgs.push_back("-lgcc_p");
  7289. } else {
  7290. CmdArgs.push_back("-lc");
  7291. CmdArgs.push_back("-lgcc");
  7292. }
  7293. if (Args.hasArg(options::OPT_static)) {
  7294. CmdArgs.push_back("-lgcc_eh");
  7295. } else if (Args.hasArg(options::OPT_pg)) {
  7296. CmdArgs.push_back("-lgcc_eh_p");
  7297. } else {
  7298. CmdArgs.push_back("--as-needed");
  7299. CmdArgs.push_back("-lgcc_s");
  7300. CmdArgs.push_back("--no-as-needed");
  7301. }
  7302. }
  7303. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7304. if (Args.hasArg(options::OPT_shared) || IsPIE)
  7305. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  7306. else
  7307. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  7308. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7309. }
  7310. ToolChain.addProfileRTLibs(Args, CmdArgs);
  7311. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7312. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7313. }
  7314. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7315. const InputInfo &Output,
  7316. const InputInfoList &Inputs,
  7317. const ArgList &Args,
  7318. const char *LinkingOutput) const {
  7319. claimNoWarnArgs(Args);
  7320. ArgStringList CmdArgs;
  7321. // GNU as needs different flags for creating the correct output format
  7322. // on architectures with different ABIs or optional feature sets.
  7323. switch (getToolChain().getArch()) {
  7324. case llvm::Triple::x86:
  7325. CmdArgs.push_back("--32");
  7326. break;
  7327. case llvm::Triple::arm:
  7328. case llvm::Triple::armeb:
  7329. case llvm::Triple::thumb:
  7330. case llvm::Triple::thumbeb: {
  7331. StringRef MArch, MCPU;
  7332. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  7333. std::string Arch =
  7334. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  7335. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  7336. break;
  7337. }
  7338. case llvm::Triple::mips:
  7339. case llvm::Triple::mipsel:
  7340. case llvm::Triple::mips64:
  7341. case llvm::Triple::mips64el: {
  7342. StringRef CPUName;
  7343. StringRef ABIName;
  7344. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7345. CmdArgs.push_back("-march");
  7346. CmdArgs.push_back(CPUName.data());
  7347. CmdArgs.push_back("-mabi");
  7348. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7349. if (getToolChain().getArch() == llvm::Triple::mips ||
  7350. getToolChain().getArch() == llvm::Triple::mips64)
  7351. CmdArgs.push_back("-EB");
  7352. else
  7353. CmdArgs.push_back("-EL");
  7354. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7355. break;
  7356. }
  7357. case llvm::Triple::sparc:
  7358. case llvm::Triple::sparcel: {
  7359. CmdArgs.push_back("-32");
  7360. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7361. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7362. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7363. break;
  7364. }
  7365. case llvm::Triple::sparcv9: {
  7366. CmdArgs.push_back("-64");
  7367. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7368. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7369. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7370. break;
  7371. }
  7372. default:
  7373. break;
  7374. }
  7375. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7376. CmdArgs.push_back("-o");
  7377. CmdArgs.push_back(Output.getFilename());
  7378. for (const auto &II : Inputs)
  7379. CmdArgs.push_back(II.getFilename());
  7380. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  7381. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7382. }
  7383. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7384. const InputInfo &Output,
  7385. const InputInfoList &Inputs,
  7386. const ArgList &Args,
  7387. const char *LinkingOutput) const {
  7388. const Driver &D = getToolChain().getDriver();
  7389. ArgStringList CmdArgs;
  7390. if (!D.SysRoot.empty())
  7391. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7392. CmdArgs.push_back("--eh-frame-hdr");
  7393. if (Args.hasArg(options::OPT_static)) {
  7394. CmdArgs.push_back("-Bstatic");
  7395. } else {
  7396. if (Args.hasArg(options::OPT_rdynamic))
  7397. CmdArgs.push_back("-export-dynamic");
  7398. if (Args.hasArg(options::OPT_shared)) {
  7399. CmdArgs.push_back("-Bshareable");
  7400. } else {
  7401. CmdArgs.push_back("-dynamic-linker");
  7402. CmdArgs.push_back("/libexec/ld.elf_so");
  7403. }
  7404. }
  7405. // Many NetBSD architectures support more than one ABI.
  7406. // Determine the correct emulation for ld.
  7407. switch (getToolChain().getArch()) {
  7408. case llvm::Triple::x86:
  7409. CmdArgs.push_back("-m");
  7410. CmdArgs.push_back("elf_i386");
  7411. break;
  7412. case llvm::Triple::arm:
  7413. case llvm::Triple::thumb:
  7414. CmdArgs.push_back("-m");
  7415. switch (getToolChain().getTriple().getEnvironment()) {
  7416. case llvm::Triple::EABI:
  7417. case llvm::Triple::GNUEABI:
  7418. CmdArgs.push_back("armelf_nbsd_eabi");
  7419. break;
  7420. case llvm::Triple::EABIHF:
  7421. case llvm::Triple::GNUEABIHF:
  7422. CmdArgs.push_back("armelf_nbsd_eabihf");
  7423. break;
  7424. default:
  7425. CmdArgs.push_back("armelf_nbsd");
  7426. break;
  7427. }
  7428. break;
  7429. case llvm::Triple::armeb:
  7430. case llvm::Triple::thumbeb:
  7431. arm::appendEBLinkFlags(
  7432. Args, CmdArgs,
  7433. llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
  7434. CmdArgs.push_back("-m");
  7435. switch (getToolChain().getTriple().getEnvironment()) {
  7436. case llvm::Triple::EABI:
  7437. case llvm::Triple::GNUEABI:
  7438. CmdArgs.push_back("armelfb_nbsd_eabi");
  7439. break;
  7440. case llvm::Triple::EABIHF:
  7441. case llvm::Triple::GNUEABIHF:
  7442. CmdArgs.push_back("armelfb_nbsd_eabihf");
  7443. break;
  7444. default:
  7445. CmdArgs.push_back("armelfb_nbsd");
  7446. break;
  7447. }
  7448. break;
  7449. case llvm::Triple::mips64:
  7450. case llvm::Triple::mips64el:
  7451. if (mips::hasMipsAbiArg(Args, "32")) {
  7452. CmdArgs.push_back("-m");
  7453. if (getToolChain().getArch() == llvm::Triple::mips64)
  7454. CmdArgs.push_back("elf32btsmip");
  7455. else
  7456. CmdArgs.push_back("elf32ltsmip");
  7457. } else if (mips::hasMipsAbiArg(Args, "64")) {
  7458. CmdArgs.push_back("-m");
  7459. if (getToolChain().getArch() == llvm::Triple::mips64)
  7460. CmdArgs.push_back("elf64btsmip");
  7461. else
  7462. CmdArgs.push_back("elf64ltsmip");
  7463. }
  7464. break;
  7465. case llvm::Triple::ppc:
  7466. CmdArgs.push_back("-m");
  7467. CmdArgs.push_back("elf32ppc_nbsd");
  7468. break;
  7469. case llvm::Triple::ppc64:
  7470. case llvm::Triple::ppc64le:
  7471. CmdArgs.push_back("-m");
  7472. CmdArgs.push_back("elf64ppc");
  7473. break;
  7474. case llvm::Triple::sparc:
  7475. CmdArgs.push_back("-m");
  7476. CmdArgs.push_back("elf32_sparc");
  7477. break;
  7478. case llvm::Triple::sparcv9:
  7479. CmdArgs.push_back("-m");
  7480. CmdArgs.push_back("elf64_sparc");
  7481. break;
  7482. default:
  7483. break;
  7484. }
  7485. if (Output.isFilename()) {
  7486. CmdArgs.push_back("-o");
  7487. CmdArgs.push_back(Output.getFilename());
  7488. } else {
  7489. assert(Output.isNothing() && "Invalid output.");
  7490. }
  7491. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7492. if (!Args.hasArg(options::OPT_shared)) {
  7493. CmdArgs.push_back(
  7494. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7495. CmdArgs.push_back(
  7496. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7497. CmdArgs.push_back(
  7498. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7499. } else {
  7500. CmdArgs.push_back(
  7501. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7502. CmdArgs.push_back(
  7503. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7504. }
  7505. }
  7506. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7507. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7508. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7509. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7510. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7511. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7512. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7513. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7514. unsigned Major, Minor, Micro;
  7515. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  7516. bool useLibgcc = true;
  7517. if (Major >= 7 || Major == 0) {
  7518. switch (getToolChain().getArch()) {
  7519. case llvm::Triple::aarch64:
  7520. case llvm::Triple::arm:
  7521. case llvm::Triple::armeb:
  7522. case llvm::Triple::thumb:
  7523. case llvm::Triple::thumbeb:
  7524. case llvm::Triple::ppc:
  7525. case llvm::Triple::ppc64:
  7526. case llvm::Triple::ppc64le:
  7527. case llvm::Triple::sparc:
  7528. case llvm::Triple::sparcv9:
  7529. case llvm::Triple::x86:
  7530. case llvm::Triple::x86_64:
  7531. useLibgcc = false;
  7532. break;
  7533. default:
  7534. break;
  7535. }
  7536. }
  7537. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7538. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  7539. if (D.CCCIsCXX()) {
  7540. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7541. CmdArgs.push_back("-lm");
  7542. }
  7543. if (Args.hasArg(options::OPT_pthread))
  7544. CmdArgs.push_back("-lpthread");
  7545. CmdArgs.push_back("-lc");
  7546. if (useLibgcc) {
  7547. if (Args.hasArg(options::OPT_static)) {
  7548. // libgcc_eh depends on libc, so resolve as much as possible,
  7549. // pull in any new requirements from libc and then get the rest
  7550. // of libgcc.
  7551. CmdArgs.push_back("-lgcc_eh");
  7552. CmdArgs.push_back("-lc");
  7553. CmdArgs.push_back("-lgcc");
  7554. } else {
  7555. CmdArgs.push_back("-lgcc");
  7556. CmdArgs.push_back("--as-needed");
  7557. CmdArgs.push_back("-lgcc_s");
  7558. CmdArgs.push_back("--no-as-needed");
  7559. }
  7560. }
  7561. }
  7562. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7563. if (!Args.hasArg(options::OPT_shared))
  7564. CmdArgs.push_back(
  7565. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7566. else
  7567. CmdArgs.push_back(
  7568. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7569. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7570. }
  7571. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7572. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7573. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7574. }
  7575. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7576. const InputInfo &Output,
  7577. const InputInfoList &Inputs,
  7578. const ArgList &Args,
  7579. const char *LinkingOutput) const {
  7580. claimNoWarnArgs(Args);
  7581. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7582. llvm::Triple Triple = llvm::Triple(TripleStr);
  7583. ArgStringList CmdArgs;
  7584. llvm::Reloc::Model RelocationModel;
  7585. unsigned PICLevel;
  7586. bool IsPIE;
  7587. std::tie(RelocationModel, PICLevel, IsPIE) =
  7588. ParsePICArgs(getToolChain(), Triple, Args);
  7589. switch (getToolChain().getArch()) {
  7590. default:
  7591. break;
  7592. // Add --32/--64 to make sure we get the format we want.
  7593. // This is incomplete
  7594. case llvm::Triple::x86:
  7595. CmdArgs.push_back("--32");
  7596. break;
  7597. case llvm::Triple::x86_64:
  7598. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7599. CmdArgs.push_back("--x32");
  7600. else
  7601. CmdArgs.push_back("--64");
  7602. break;
  7603. case llvm::Triple::ppc:
  7604. CmdArgs.push_back("-a32");
  7605. CmdArgs.push_back("-mppc");
  7606. CmdArgs.push_back("-many");
  7607. break;
  7608. case llvm::Triple::ppc64:
  7609. CmdArgs.push_back("-a64");
  7610. CmdArgs.push_back("-mppc64");
  7611. CmdArgs.push_back("-many");
  7612. break;
  7613. case llvm::Triple::ppc64le:
  7614. CmdArgs.push_back("-a64");
  7615. CmdArgs.push_back("-mppc64");
  7616. CmdArgs.push_back("-many");
  7617. CmdArgs.push_back("-mlittle-endian");
  7618. break;
  7619. case llvm::Triple::sparc:
  7620. case llvm::Triple::sparcel: {
  7621. CmdArgs.push_back("-32");
  7622. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7623. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7624. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7625. break;
  7626. }
  7627. case llvm::Triple::sparcv9: {
  7628. CmdArgs.push_back("-64");
  7629. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7630. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7631. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7632. break;
  7633. }
  7634. case llvm::Triple::arm:
  7635. case llvm::Triple::armeb:
  7636. case llvm::Triple::thumb:
  7637. case llvm::Triple::thumbeb: {
  7638. const llvm::Triple &Triple2 = getToolChain().getTriple();
  7639. switch (Triple2.getSubArch()) {
  7640. case llvm::Triple::ARMSubArch_v7:
  7641. CmdArgs.push_back("-mfpu=neon");
  7642. break;
  7643. case llvm::Triple::ARMSubArch_v8:
  7644. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  7645. break;
  7646. default:
  7647. break;
  7648. }
  7649. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  7650. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  7651. case arm::FloatABI::Soft:
  7652. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  7653. break;
  7654. case arm::FloatABI::SoftFP:
  7655. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  7656. break;
  7657. case arm::FloatABI::Hard:
  7658. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  7659. break;
  7660. }
  7661. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  7662. // FIXME: remove krait check when GNU tools support krait cpu
  7663. // for now replace it with -mcpu=cortex-a15 to avoid a lower
  7664. // march from being picked in the absence of a cpu flag.
  7665. Arg *A;
  7666. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  7667. StringRef(A->getValue()).lower() == "krait")
  7668. CmdArgs.push_back("-mcpu=cortex-a15");
  7669. else
  7670. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  7671. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  7672. break;
  7673. }
  7674. case llvm::Triple::mips:
  7675. case llvm::Triple::mipsel:
  7676. case llvm::Triple::mips64:
  7677. case llvm::Triple::mips64el: {
  7678. StringRef CPUName;
  7679. StringRef ABIName;
  7680. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7681. ABIName = getGnuCompatibleMipsABIName(ABIName);
  7682. CmdArgs.push_back("-march");
  7683. CmdArgs.push_back(CPUName.data());
  7684. CmdArgs.push_back("-mabi");
  7685. CmdArgs.push_back(ABIName.data());
  7686. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  7687. // or -mshared (not implemented) is in effect.
  7688. if (RelocationModel == llvm::Reloc::Static)
  7689. CmdArgs.push_back("-mno-shared");
  7690. // LLVM doesn't support -mplt yet and acts as if it is always given.
  7691. // However, -mplt has no effect with the N64 ABI.
  7692. CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
  7693. if (getToolChain().getArch() == llvm::Triple::mips ||
  7694. getToolChain().getArch() == llvm::Triple::mips64)
  7695. CmdArgs.push_back("-EB");
  7696. else
  7697. CmdArgs.push_back("-EL");
  7698. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  7699. if (StringRef(A->getValue()) == "2008")
  7700. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  7701. }
  7702. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  7703. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  7704. options::OPT_mfp64)) {
  7705. A->claim();
  7706. A->render(Args, CmdArgs);
  7707. } else if (mips::shouldUseFPXX(
  7708. Args, getToolChain().getTriple(), CPUName, ABIName,
  7709. getMipsFloatABI(getToolChain().getDriver(), Args)))
  7710. CmdArgs.push_back("-mfpxx");
  7711. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  7712. // -mno-mips16 is actually -no-mips16.
  7713. if (Arg *A =
  7714. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  7715. if (A->getOption().matches(options::OPT_mips16)) {
  7716. A->claim();
  7717. A->render(Args, CmdArgs);
  7718. } else {
  7719. A->claim();
  7720. CmdArgs.push_back("-no-mips16");
  7721. }
  7722. }
  7723. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  7724. options::OPT_mno_micromips);
  7725. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  7726. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  7727. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  7728. // Do not use AddLastArg because not all versions of MIPS assembler
  7729. // support -mmsa / -mno-msa options.
  7730. if (A->getOption().matches(options::OPT_mmsa))
  7731. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  7732. }
  7733. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  7734. options::OPT_msoft_float);
  7735. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  7736. options::OPT_msingle_float);
  7737. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  7738. options::OPT_mno_odd_spreg);
  7739. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7740. break;
  7741. }
  7742. case llvm::Triple::systemz: {
  7743. // Always pass an -march option, since our default of z10 is later
  7744. // than the GNU assembler's default.
  7745. StringRef CPUName = getSystemZTargetCPU(Args);
  7746. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  7747. break;
  7748. }
  7749. }
  7750. Args.AddAllArgs(CmdArgs, options::OPT_I);
  7751. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7752. CmdArgs.push_back("-o");
  7753. CmdArgs.push_back(Output.getFilename());
  7754. for (const auto &II : Inputs)
  7755. CmdArgs.push_back(II.getFilename());
  7756. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7757. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7758. // Handle the debug info splitting at object creation time if we're
  7759. // creating an object.
  7760. // TODO: Currently only works on linux with newer objcopy.
  7761. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  7762. getToolChain().getTriple().isOSLinux())
  7763. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  7764. SplitDebugName(Args, Inputs[0]));
  7765. }
  7766. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  7767. ArgStringList &CmdArgs, const ArgList &Args) {
  7768. bool isAndroid = Triple.isAndroid();
  7769. bool isCygMing = Triple.isOSCygMing();
  7770. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  7771. Args.hasArg(options::OPT_static);
  7772. if (!D.CCCIsCXX())
  7773. CmdArgs.push_back("-lgcc");
  7774. if (StaticLibgcc || isAndroid) {
  7775. if (D.CCCIsCXX())
  7776. CmdArgs.push_back("-lgcc");
  7777. } else {
  7778. if (!D.CCCIsCXX() && !isCygMing)
  7779. CmdArgs.push_back("--as-needed");
  7780. CmdArgs.push_back("-lgcc_s");
  7781. if (!D.CCCIsCXX() && !isCygMing)
  7782. CmdArgs.push_back("--no-as-needed");
  7783. }
  7784. if (StaticLibgcc && !isAndroid)
  7785. CmdArgs.push_back("-lgcc_eh");
  7786. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  7787. CmdArgs.push_back("-lgcc");
  7788. // According to Android ABI, we have to link with libdl if we are
  7789. // linking with non-static libgcc.
  7790. //
  7791. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  7792. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  7793. if (isAndroid && !StaticLibgcc)
  7794. CmdArgs.push_back("-ldl");
  7795. }
  7796. static std::string getLinuxDynamicLinker(const ArgList &Args,
  7797. const toolchains::Linux &ToolChain) {
  7798. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7799. if (ToolChain.getTriple().isAndroid()) {
  7800. if (ToolChain.getTriple().isArch64Bit())
  7801. return "/system/bin/linker64";
  7802. else
  7803. return "/system/bin/linker";
  7804. } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
  7805. Arch == llvm::Triple::sparcel)
  7806. return "/lib/ld-linux.so.2";
  7807. else if (Arch == llvm::Triple::aarch64)
  7808. return "/lib/ld-linux-aarch64.so.1";
  7809. else if (Arch == llvm::Triple::aarch64_be)
  7810. return "/lib/ld-linux-aarch64_be.so.1";
  7811. else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
  7812. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7813. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7814. return "/lib/ld-linux-armhf.so.3";
  7815. else
  7816. return "/lib/ld-linux.so.3";
  7817. } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
  7818. // TODO: check which dynamic linker name.
  7819. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7820. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7821. return "/lib/ld-linux-armhf.so.3";
  7822. else
  7823. return "/lib/ld-linux.so.3";
  7824. } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
  7825. Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
  7826. std::string LibDir =
  7827. "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
  7828. StringRef LibName;
  7829. bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
  7830. if (mips::isUCLibc(Args))
  7831. LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
  7832. else if (!ToolChain.getTriple().hasEnvironment()) {
  7833. bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
  7834. (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
  7835. LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
  7836. } else
  7837. LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
  7838. return (LibDir + "/" + LibName).str();
  7839. } else if (Arch == llvm::Triple::ppc)
  7840. return "/lib/ld.so.1";
  7841. else if (Arch == llvm::Triple::ppc64) {
  7842. if (ppc::hasPPCAbiArg(Args, "elfv2"))
  7843. return "/lib64/ld64.so.2";
  7844. return "/lib64/ld64.so.1";
  7845. } else if (Arch == llvm::Triple::ppc64le) {
  7846. if (ppc::hasPPCAbiArg(Args, "elfv1"))
  7847. return "/lib64/ld64.so.1";
  7848. return "/lib64/ld64.so.2";
  7849. } else if (Arch == llvm::Triple::systemz)
  7850. return "/lib/ld64.so.1";
  7851. else if (Arch == llvm::Triple::sparcv9)
  7852. return "/lib64/ld-linux.so.2";
  7853. else if (Arch == llvm::Triple::x86_64 &&
  7854. ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7855. return "/libx32/ld-linux-x32.so.2";
  7856. else
  7857. return "/lib64/ld-linux-x86-64.so.2";
  7858. }
  7859. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  7860. ArgStringList &CmdArgs, const ArgList &Args) {
  7861. // Make use of compiler-rt if --rtlib option is used
  7862. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  7863. switch (RLT) {
  7864. case ToolChain::RLT_CompilerRT:
  7865. switch (TC.getTriple().getOS()) {
  7866. default:
  7867. llvm_unreachable("unsupported OS");
  7868. case llvm::Triple::Win32:
  7869. case llvm::Triple::Linux:
  7870. addClangRT(TC, Args, CmdArgs);
  7871. break;
  7872. }
  7873. break;
  7874. case ToolChain::RLT_Libgcc:
  7875. // Make sure libgcc is not used under MSVC environment by default
  7876. if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
  7877. // Issue error diagnostic if libgcc is explicitly specified
  7878. // through command line as --rtlib option argument.
  7879. if (Args.hasArg(options::OPT_rtlib_EQ)) {
  7880. TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
  7881. << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
  7882. }
  7883. } else
  7884. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  7885. break;
  7886. }
  7887. }
  7888. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  7889. switch (T.getArch()) {
  7890. case llvm::Triple::x86:
  7891. return "elf_i386";
  7892. case llvm::Triple::aarch64:
  7893. return "aarch64linux";
  7894. case llvm::Triple::aarch64_be:
  7895. return "aarch64_be_linux";
  7896. case llvm::Triple::arm:
  7897. case llvm::Triple::thumb:
  7898. return "armelf_linux_eabi";
  7899. case llvm::Triple::armeb:
  7900. case llvm::Triple::thumbeb:
  7901. return "armebelf_linux_eabi"; /* TODO: check which NAME. */
  7902. case llvm::Triple::ppc:
  7903. return "elf32ppclinux";
  7904. case llvm::Triple::ppc64:
  7905. return "elf64ppc";
  7906. case llvm::Triple::ppc64le:
  7907. return "elf64lppc";
  7908. case llvm::Triple::sparc:
  7909. case llvm::Triple::sparcel:
  7910. return "elf32_sparc";
  7911. case llvm::Triple::sparcv9:
  7912. return "elf64_sparc";
  7913. case llvm::Triple::mips:
  7914. return "elf32btsmip";
  7915. case llvm::Triple::mipsel:
  7916. return "elf32ltsmip";
  7917. case llvm::Triple::mips64:
  7918. if (mips::hasMipsAbiArg(Args, "n32"))
  7919. return "elf32btsmipn32";
  7920. return "elf64btsmip";
  7921. case llvm::Triple::mips64el:
  7922. if (mips::hasMipsAbiArg(Args, "n32"))
  7923. return "elf32ltsmipn32";
  7924. return "elf64ltsmip";
  7925. case llvm::Triple::systemz:
  7926. return "elf64_s390";
  7927. case llvm::Triple::x86_64:
  7928. if (T.getEnvironment() == llvm::Triple::GNUX32)
  7929. return "elf32_x86_64";
  7930. return "elf_x86_64";
  7931. default:
  7932. llvm_unreachable("Unexpected arch");
  7933. }
  7934. }
  7935. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7936. const InputInfo &Output,
  7937. const InputInfoList &Inputs,
  7938. const ArgList &Args,
  7939. const char *LinkingOutput) const {
  7940. const toolchains::Linux &ToolChain =
  7941. static_cast<const toolchains::Linux &>(getToolChain());
  7942. const Driver &D = ToolChain.getDriver();
  7943. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7944. llvm::Triple Triple = llvm::Triple(TripleStr);
  7945. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7946. const bool isAndroid = ToolChain.getTriple().isAndroid();
  7947. const bool IsPIE =
  7948. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  7949. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7950. const bool HasCRTBeginEndFiles =
  7951. ToolChain.getTriple().hasEnvironment() ||
  7952. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  7953. ArgStringList CmdArgs;
  7954. // Silence warning for "clang -g foo.o -o foo"
  7955. Args.ClaimAllArgs(options::OPT_g_Group);
  7956. // and "clang -emit-llvm foo.o -o foo"
  7957. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7958. // and for "clang -w foo.o -o foo". Other warning options are already
  7959. // handled somewhere else.
  7960. Args.ClaimAllArgs(options::OPT_w);
  7961. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  7962. if (llvm::sys::path::filename(Exec) == "lld") {
  7963. CmdArgs.push_back("-flavor");
  7964. CmdArgs.push_back("old-gnu");
  7965. CmdArgs.push_back("-target");
  7966. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  7967. }
  7968. if (!D.SysRoot.empty())
  7969. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7970. if (IsPIE)
  7971. CmdArgs.push_back("-pie");
  7972. if (Args.hasArg(options::OPT_rdynamic))
  7973. CmdArgs.push_back("-export-dynamic");
  7974. if (Args.hasArg(options::OPT_s))
  7975. CmdArgs.push_back("-s");
  7976. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  7977. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  7978. for (const auto &Opt : ToolChain.ExtraOpts)
  7979. CmdArgs.push_back(Opt.c_str());
  7980. if (!Args.hasArg(options::OPT_static)) {
  7981. CmdArgs.push_back("--eh-frame-hdr");
  7982. }
  7983. CmdArgs.push_back("-m");
  7984. CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
  7985. if (Args.hasArg(options::OPT_static)) {
  7986. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7987. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  7988. CmdArgs.push_back("-Bstatic");
  7989. else
  7990. CmdArgs.push_back("-static");
  7991. } else if (Args.hasArg(options::OPT_shared)) {
  7992. CmdArgs.push_back("-shared");
  7993. }
  7994. if (!Args.hasArg(options::OPT_static)) {
  7995. if (Args.hasArg(options::OPT_rdynamic))
  7996. CmdArgs.push_back("-export-dynamic");
  7997. if (!Args.hasArg(options::OPT_shared)) {
  7998. const std::string Loader =
  7999. D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain);
  8000. CmdArgs.push_back("-dynamic-linker");
  8001. CmdArgs.push_back(Args.MakeArgString(Loader));
  8002. }
  8003. }
  8004. CmdArgs.push_back("-o");
  8005. CmdArgs.push_back(Output.getFilename());
  8006. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8007. if (!isAndroid) {
  8008. const char *crt1 = nullptr;
  8009. if (!Args.hasArg(options::OPT_shared)) {
  8010. if (Args.hasArg(options::OPT_pg))
  8011. crt1 = "gcrt1.o";
  8012. else if (IsPIE)
  8013. crt1 = "Scrt1.o";
  8014. else
  8015. crt1 = "crt1.o";
  8016. }
  8017. if (crt1)
  8018. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  8019. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8020. }
  8021. const char *crtbegin;
  8022. if (Args.hasArg(options::OPT_static))
  8023. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  8024. else if (Args.hasArg(options::OPT_shared))
  8025. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  8026. else if (IsPIE)
  8027. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  8028. else
  8029. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  8030. if (HasCRTBeginEndFiles)
  8031. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8032. // Add crtfastmath.o if available and fast math is enabled.
  8033. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8034. }
  8035. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8036. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8037. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8038. if (D.isUsingLTO())
  8039. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  8040. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8041. CmdArgs.push_back("--no-demangle");
  8042. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  8043. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8044. // The profile runtime also needs access to system libraries.
  8045. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8046. if (D.CCCIsCXX() &&
  8047. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8048. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8049. !Args.hasArg(options::OPT_static);
  8050. if (OnlyLibstdcxxStatic)
  8051. CmdArgs.push_back("-Bstatic");
  8052. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8053. if (OnlyLibstdcxxStatic)
  8054. CmdArgs.push_back("-Bdynamic");
  8055. CmdArgs.push_back("-lm");
  8056. }
  8057. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  8058. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  8059. if (!Args.hasArg(options::OPT_nostdlib)) {
  8060. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8061. if (Args.hasArg(options::OPT_static))
  8062. CmdArgs.push_back("--start-group");
  8063. if (NeedsSanitizerDeps)
  8064. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  8065. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  8066. Args.hasArg(options::OPT_pthreads);
  8067. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8068. options::OPT_fno_openmp, false)) {
  8069. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  8070. // FIXME: Does this really make sense for all GNU toolchains?
  8071. WantPthread = true;
  8072. // Also link the particular OpenMP runtimes.
  8073. switch (getOpenMPRuntime(ToolChain, Args)) {
  8074. case OMPRT_OMP:
  8075. CmdArgs.push_back("-lomp");
  8076. break;
  8077. case OMPRT_GOMP:
  8078. CmdArgs.push_back("-lgomp");
  8079. // FIXME: Exclude this for platforms with libgomp that don't require
  8080. // librt. Most modern Linux platforms require it, but some may not.
  8081. CmdArgs.push_back("-lrt");
  8082. break;
  8083. case OMPRT_IOMP5:
  8084. CmdArgs.push_back("-liomp5");
  8085. break;
  8086. case OMPRT_Unknown:
  8087. // Already diagnosed.
  8088. break;
  8089. }
  8090. }
  8091. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8092. if (WantPthread && !isAndroid)
  8093. CmdArgs.push_back("-lpthread");
  8094. if (Args.hasArg(options::OPT_fsplit_stack))
  8095. CmdArgs.push_back("--wrap=pthread_create");
  8096. CmdArgs.push_back("-lc");
  8097. if (Args.hasArg(options::OPT_static))
  8098. CmdArgs.push_back("--end-group");
  8099. else
  8100. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8101. }
  8102. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8103. const char *crtend;
  8104. if (Args.hasArg(options::OPT_shared))
  8105. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  8106. else if (IsPIE)
  8107. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  8108. else
  8109. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  8110. if (HasCRTBeginEndFiles)
  8111. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8112. if (!isAndroid)
  8113. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8114. }
  8115. }
  8116. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8117. }
  8118. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  8119. // for the various SFI requirements like register masking. The assembly tool
  8120. // inserts the file containing the macros as an input into all the assembly
  8121. // jobs.
  8122. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  8123. const InputInfo &Output,
  8124. const InputInfoList &Inputs,
  8125. const ArgList &Args,
  8126. const char *LinkingOutput) const {
  8127. const toolchains::NaClToolChain &ToolChain =
  8128. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  8129. InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
  8130. "nacl-arm-macros.s");
  8131. InputInfoList NewInputs;
  8132. NewInputs.push_back(NaClMacros);
  8133. NewInputs.append(Inputs.begin(), Inputs.end());
  8134. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  8135. LinkingOutput);
  8136. }
  8137. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  8138. // we use static by default, do not yet support sanitizers or LTO, and a few
  8139. // others. Eventually we can support more of that and hopefully migrate back
  8140. // to gnutools::Linker.
  8141. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8142. const InputInfo &Output,
  8143. const InputInfoList &Inputs,
  8144. const ArgList &Args,
  8145. const char *LinkingOutput) const {
  8146. const toolchains::NaClToolChain &ToolChain =
  8147. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  8148. const Driver &D = ToolChain.getDriver();
  8149. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  8150. const bool IsStatic =
  8151. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  8152. ArgStringList CmdArgs;
  8153. // Silence warning for "clang -g foo.o -o foo"
  8154. Args.ClaimAllArgs(options::OPT_g_Group);
  8155. // and "clang -emit-llvm foo.o -o foo"
  8156. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8157. // and for "clang -w foo.o -o foo". Other warning options are already
  8158. // handled somewhere else.
  8159. Args.ClaimAllArgs(options::OPT_w);
  8160. if (!D.SysRoot.empty())
  8161. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8162. if (Args.hasArg(options::OPT_rdynamic))
  8163. CmdArgs.push_back("-export-dynamic");
  8164. if (Args.hasArg(options::OPT_s))
  8165. CmdArgs.push_back("-s");
  8166. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  8167. // from there is --build-id, which we do want.
  8168. CmdArgs.push_back("--build-id");
  8169. if (!IsStatic)
  8170. CmdArgs.push_back("--eh-frame-hdr");
  8171. CmdArgs.push_back("-m");
  8172. if (Arch == llvm::Triple::x86)
  8173. CmdArgs.push_back("elf_i386_nacl");
  8174. else if (Arch == llvm::Triple::arm)
  8175. CmdArgs.push_back("armelf_nacl");
  8176. else if (Arch == llvm::Triple::x86_64)
  8177. CmdArgs.push_back("elf_x86_64_nacl");
  8178. else if (Arch == llvm::Triple::mipsel)
  8179. CmdArgs.push_back("mipselelf_nacl");
  8180. else
  8181. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  8182. << "Native Client";
  8183. if (IsStatic)
  8184. CmdArgs.push_back("-static");
  8185. else if (Args.hasArg(options::OPT_shared))
  8186. CmdArgs.push_back("-shared");
  8187. CmdArgs.push_back("-o");
  8188. CmdArgs.push_back(Output.getFilename());
  8189. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8190. if (!Args.hasArg(options::OPT_shared))
  8191. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  8192. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8193. const char *crtbegin;
  8194. if (IsStatic)
  8195. crtbegin = "crtbeginT.o";
  8196. else if (Args.hasArg(options::OPT_shared))
  8197. crtbegin = "crtbeginS.o";
  8198. else
  8199. crtbegin = "crtbegin.o";
  8200. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8201. }
  8202. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8203. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8204. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8205. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8206. CmdArgs.push_back("--no-demangle");
  8207. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8208. if (D.CCCIsCXX() &&
  8209. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8210. bool OnlyLibstdcxxStatic =
  8211. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  8212. if (OnlyLibstdcxxStatic)
  8213. CmdArgs.push_back("-Bstatic");
  8214. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8215. if (OnlyLibstdcxxStatic)
  8216. CmdArgs.push_back("-Bdynamic");
  8217. CmdArgs.push_back("-lm");
  8218. }
  8219. if (!Args.hasArg(options::OPT_nostdlib)) {
  8220. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8221. // Always use groups, since it has no effect on dynamic libraries.
  8222. CmdArgs.push_back("--start-group");
  8223. CmdArgs.push_back("-lc");
  8224. // NaCl's libc++ currently requires libpthread, so just always include it
  8225. // in the group for C++.
  8226. if (Args.hasArg(options::OPT_pthread) ||
  8227. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  8228. // Gold, used by Mips, handles nested groups differently than ld, and
  8229. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  8230. // which is not a desired behaviour here.
  8231. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  8232. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8233. CmdArgs.push_back("-lnacl");
  8234. CmdArgs.push_back("-lpthread");
  8235. }
  8236. CmdArgs.push_back("-lgcc");
  8237. CmdArgs.push_back("--as-needed");
  8238. if (IsStatic)
  8239. CmdArgs.push_back("-lgcc_eh");
  8240. else
  8241. CmdArgs.push_back("-lgcc_s");
  8242. CmdArgs.push_back("--no-as-needed");
  8243. // Mips needs to create and use pnacl_legacy library that contains
  8244. // definitions from bitcode/pnaclmm.c and definitions for
  8245. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  8246. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8247. CmdArgs.push_back("-lpnacl_legacy");
  8248. CmdArgs.push_back("--end-group");
  8249. }
  8250. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8251. const char *crtend;
  8252. if (Args.hasArg(options::OPT_shared))
  8253. crtend = "crtendS.o";
  8254. else
  8255. crtend = "crtend.o";
  8256. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8257. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8258. }
  8259. }
  8260. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8261. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8262. }
  8263. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8264. const InputInfo &Output,
  8265. const InputInfoList &Inputs,
  8266. const ArgList &Args,
  8267. const char *LinkingOutput) const {
  8268. claimNoWarnArgs(Args);
  8269. ArgStringList CmdArgs;
  8270. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8271. CmdArgs.push_back("-o");
  8272. CmdArgs.push_back(Output.getFilename());
  8273. for (const auto &II : Inputs)
  8274. CmdArgs.push_back(II.getFilename());
  8275. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8276. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8277. }
  8278. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8279. const InputInfo &Output,
  8280. const InputInfoList &Inputs,
  8281. const ArgList &Args,
  8282. const char *LinkingOutput) const {
  8283. const Driver &D = getToolChain().getDriver();
  8284. ArgStringList CmdArgs;
  8285. if (Output.isFilename()) {
  8286. CmdArgs.push_back("-o");
  8287. CmdArgs.push_back(Output.getFilename());
  8288. } else {
  8289. assert(Output.isNothing() && "Invalid output.");
  8290. }
  8291. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8292. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8293. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8294. CmdArgs.push_back(
  8295. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8296. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8297. }
  8298. Args.AddAllArgs(CmdArgs,
  8299. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8300. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8301. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8302. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8303. if (D.CCCIsCXX()) {
  8304. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8305. CmdArgs.push_back("-lm");
  8306. }
  8307. }
  8308. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8309. if (Args.hasArg(options::OPT_pthread))
  8310. CmdArgs.push_back("-lpthread");
  8311. CmdArgs.push_back("-lc");
  8312. CmdArgs.push_back("-lCompilerRT-Generic");
  8313. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  8314. CmdArgs.push_back(
  8315. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8316. }
  8317. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8318. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8319. }
  8320. /// DragonFly Tools
  8321. // For now, DragonFly Assemble does just about the same as for
  8322. // FreeBSD, but this may change soon.
  8323. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8324. const InputInfo &Output,
  8325. const InputInfoList &Inputs,
  8326. const ArgList &Args,
  8327. const char *LinkingOutput) const {
  8328. claimNoWarnArgs(Args);
  8329. ArgStringList CmdArgs;
  8330. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8331. // instruct as in the base system to assemble 32-bit code.
  8332. if (getToolChain().getArch() == llvm::Triple::x86)
  8333. CmdArgs.push_back("--32");
  8334. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8335. CmdArgs.push_back("-o");
  8336. CmdArgs.push_back(Output.getFilename());
  8337. for (const auto &II : Inputs)
  8338. CmdArgs.push_back(II.getFilename());
  8339. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8340. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8341. }
  8342. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8343. const InputInfo &Output,
  8344. const InputInfoList &Inputs,
  8345. const ArgList &Args,
  8346. const char *LinkingOutput) const {
  8347. const Driver &D = getToolChain().getDriver();
  8348. ArgStringList CmdArgs;
  8349. if (!D.SysRoot.empty())
  8350. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8351. CmdArgs.push_back("--eh-frame-hdr");
  8352. if (Args.hasArg(options::OPT_static)) {
  8353. CmdArgs.push_back("-Bstatic");
  8354. } else {
  8355. if (Args.hasArg(options::OPT_rdynamic))
  8356. CmdArgs.push_back("-export-dynamic");
  8357. if (Args.hasArg(options::OPT_shared))
  8358. CmdArgs.push_back("-Bshareable");
  8359. else {
  8360. CmdArgs.push_back("-dynamic-linker");
  8361. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  8362. }
  8363. CmdArgs.push_back("--hash-style=gnu");
  8364. CmdArgs.push_back("--enable-new-dtags");
  8365. }
  8366. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8367. // instruct ld in the base system to link 32-bit code.
  8368. if (getToolChain().getArch() == llvm::Triple::x86) {
  8369. CmdArgs.push_back("-m");
  8370. CmdArgs.push_back("elf_i386");
  8371. }
  8372. if (Output.isFilename()) {
  8373. CmdArgs.push_back("-o");
  8374. CmdArgs.push_back(Output.getFilename());
  8375. } else {
  8376. assert(Output.isNothing() && "Invalid output.");
  8377. }
  8378. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8379. if (!Args.hasArg(options::OPT_shared)) {
  8380. if (Args.hasArg(options::OPT_pg))
  8381. CmdArgs.push_back(
  8382. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  8383. else {
  8384. if (Args.hasArg(options::OPT_pie))
  8385. CmdArgs.push_back(
  8386. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  8387. else
  8388. CmdArgs.push_back(
  8389. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8390. }
  8391. }
  8392. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8393. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8394. CmdArgs.push_back(
  8395. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  8396. else
  8397. CmdArgs.push_back(
  8398. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8399. }
  8400. Args.AddAllArgs(CmdArgs,
  8401. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8402. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8403. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8404. CmdArgs.push_back("-L/usr/lib/gcc50");
  8405. if (!Args.hasArg(options::OPT_static)) {
  8406. CmdArgs.push_back("-rpath");
  8407. CmdArgs.push_back("/usr/lib/gcc50");
  8408. }
  8409. if (D.CCCIsCXX()) {
  8410. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8411. CmdArgs.push_back("-lm");
  8412. }
  8413. if (Args.hasArg(options::OPT_pthread))
  8414. CmdArgs.push_back("-lpthread");
  8415. if (!Args.hasArg(options::OPT_nolibc)) {
  8416. CmdArgs.push_back("-lc");
  8417. }
  8418. if (Args.hasArg(options::OPT_static) ||
  8419. Args.hasArg(options::OPT_static_libgcc)) {
  8420. CmdArgs.push_back("-lgcc");
  8421. CmdArgs.push_back("-lgcc_eh");
  8422. } else {
  8423. if (Args.hasArg(options::OPT_shared_libgcc)) {
  8424. CmdArgs.push_back("-lgcc_pic");
  8425. if (!Args.hasArg(options::OPT_shared))
  8426. CmdArgs.push_back("-lgcc");
  8427. } else {
  8428. CmdArgs.push_back("-lgcc");
  8429. CmdArgs.push_back("--as-needed");
  8430. CmdArgs.push_back("-lgcc_pic");
  8431. CmdArgs.push_back("--no-as-needed");
  8432. }
  8433. }
  8434. }
  8435. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8436. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8437. CmdArgs.push_back(
  8438. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  8439. else
  8440. CmdArgs.push_back(
  8441. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8442. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8443. }
  8444. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8445. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8446. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8447. }
  8448. // Try to find Exe from a Visual Studio distribution. This first tries to find
  8449. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  8450. // making sure that whatever executable that's found is not a same-named exe
  8451. // from clang itself to prevent clang from falling back to itself.
  8452. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  8453. const char *Exe,
  8454. const char *ClangProgramPath) {
  8455. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8456. std::string visualStudioBinDir;
  8457. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  8458. visualStudioBinDir)) {
  8459. SmallString<128> FilePath(visualStudioBinDir);
  8460. llvm::sys::path::append(FilePath, Exe);
  8461. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  8462. return FilePath.str();
  8463. }
  8464. return Exe;
  8465. }
  8466. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8467. const InputInfo &Output,
  8468. const InputInfoList &Inputs,
  8469. const ArgList &Args,
  8470. const char *LinkingOutput) const {
  8471. ArgStringList CmdArgs;
  8472. const ToolChain &TC = getToolChain();
  8473. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  8474. if (Output.isFilename())
  8475. CmdArgs.push_back(
  8476. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  8477. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
  8478. !C.getDriver().IsCLMode())
  8479. CmdArgs.push_back("-defaultlib:libcmt");
  8480. if (!llvm::sys::Process::GetEnv("LIB")) {
  8481. // If the VC environment hasn't been configured (perhaps because the user
  8482. // did not run vcvarsall), try to build a consistent link environment. If
  8483. // the environment variable is set however, assume the user knows what
  8484. // they're doing.
  8485. std::string VisualStudioDir;
  8486. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8487. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  8488. SmallString<128> LibDir(VisualStudioDir);
  8489. llvm::sys::path::append(LibDir, "VC", "lib");
  8490. switch (MSVC.getArch()) {
  8491. case llvm::Triple::x86:
  8492. // x86 just puts the libraries directly in lib
  8493. break;
  8494. case llvm::Triple::x86_64:
  8495. llvm::sys::path::append(LibDir, "amd64");
  8496. break;
  8497. case llvm::Triple::arm:
  8498. llvm::sys::path::append(LibDir, "arm");
  8499. break;
  8500. default:
  8501. break;
  8502. }
  8503. CmdArgs.push_back(
  8504. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  8505. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  8506. std::string UniversalCRTLibPath;
  8507. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  8508. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8509. UniversalCRTLibPath.c_str()));
  8510. }
  8511. }
  8512. std::string WindowsSdkLibPath;
  8513. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  8514. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8515. WindowsSdkLibPath.c_str()));
  8516. }
  8517. CmdArgs.push_back("-nologo");
  8518. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
  8519. CmdArgs.push_back("-debug");
  8520. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  8521. options::OPT_shared);
  8522. if (DLL) {
  8523. CmdArgs.push_back(Args.MakeArgString("-dll"));
  8524. SmallString<128> ImplibName(Output.getFilename());
  8525. llvm::sys::path::replace_extension(ImplibName, "lib");
  8526. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  8527. }
  8528. if (TC.getSanitizerArgs().needsAsanRt()) {
  8529. CmdArgs.push_back(Args.MakeArgString("-debug"));
  8530. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  8531. if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  8532. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  8533. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8534. // Make sure the dynamic runtime thunk is not optimized out at link time
  8535. // to ensure proper SEH handling.
  8536. CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
  8537. } else if (DLL) {
  8538. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  8539. } else {
  8540. for (const auto &Lib : {"asan", "asan_cxx"})
  8541. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8542. }
  8543. }
  8544. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  8545. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8546. options::OPT_fno_openmp, false)) {
  8547. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  8548. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  8549. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8550. TC.getDriver().Dir + "/../lib"));
  8551. switch (getOpenMPRuntime(getToolChain(), Args)) {
  8552. case OMPRT_OMP:
  8553. CmdArgs.push_back("-defaultlib:libomp.lib");
  8554. break;
  8555. case OMPRT_IOMP5:
  8556. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  8557. break;
  8558. case OMPRT_GOMP:
  8559. break;
  8560. case OMPRT_Unknown:
  8561. // Already diagnosed.
  8562. break;
  8563. }
  8564. }
  8565. // Add compiler-rt lib in case if it was explicitly
  8566. // specified as an argument for --rtlib option.
  8567. if (!Args.hasArg(options::OPT_nostdlib)) {
  8568. AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
  8569. }
  8570. // Add filenames, libraries, and other linker inputs.
  8571. for (const auto &Input : Inputs) {
  8572. if (Input.isFilename()) {
  8573. CmdArgs.push_back(Input.getFilename());
  8574. continue;
  8575. }
  8576. const Arg &A = Input.getInputArg();
  8577. // Render -l options differently for the MSVC linker.
  8578. if (A.getOption().matches(options::OPT_l)) {
  8579. StringRef Lib = A.getValue();
  8580. const char *LinkLibArg;
  8581. if (Lib.endswith(".lib"))
  8582. LinkLibArg = Args.MakeArgString(Lib);
  8583. else
  8584. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  8585. CmdArgs.push_back(LinkLibArg);
  8586. continue;
  8587. }
  8588. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  8589. // or -L. Render it, even if MSVC doesn't understand it.
  8590. A.renderAsInput(Args, CmdArgs);
  8591. }
  8592. TC.addProfileRTLibs(Args, CmdArgs);
  8593. // We need to special case some linker paths. In the case of lld, we need to
  8594. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  8595. // linker, we need to use a special search algorithm.
  8596. llvm::SmallString<128> linkPath;
  8597. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  8598. if (Linker.equals_lower("lld"))
  8599. Linker = "lld-link";
  8600. if (Linker.equals_lower("link")) {
  8601. // If we're using the MSVC linker, it's not sufficient to just use link
  8602. // from the program PATH, because other environments like GnuWin32 install
  8603. // their own link.exe which may come first.
  8604. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  8605. C.getDriver().getClangProgramPath());
  8606. } else {
  8607. linkPath = Linker;
  8608. llvm::sys::path::replace_extension(linkPath, "exe");
  8609. linkPath = TC.GetProgramPath(linkPath.c_str());
  8610. }
  8611. const char *Exec = Args.MakeArgString(linkPath);
  8612. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8613. }
  8614. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8615. const InputInfo &Output,
  8616. const InputInfoList &Inputs,
  8617. const ArgList &Args,
  8618. const char *LinkingOutput) const {
  8619. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  8620. }
  8621. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  8622. Compilation &C, const JobAction &JA, const InputInfo &Output,
  8623. const InputInfoList &Inputs, const ArgList &Args,
  8624. const char *LinkingOutput) const {
  8625. ArgStringList CmdArgs;
  8626. CmdArgs.push_back("/nologo");
  8627. CmdArgs.push_back("/c"); // Compile only.
  8628. CmdArgs.push_back("/W0"); // No warnings.
  8629. // The goal is to be able to invoke this tool correctly based on
  8630. // any flag accepted by clang-cl.
  8631. // These are spelled the same way in clang and cl.exe,.
  8632. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  8633. // Optimization level.
  8634. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  8635. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  8636. : "/Oi-");
  8637. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  8638. if (A->getOption().getID() == options::OPT_O0) {
  8639. CmdArgs.push_back("/Od");
  8640. } else {
  8641. CmdArgs.push_back("/Og");
  8642. StringRef OptLevel = A->getValue();
  8643. if (OptLevel == "s" || OptLevel == "z")
  8644. CmdArgs.push_back("/Os");
  8645. else
  8646. CmdArgs.push_back("/Ot");
  8647. CmdArgs.push_back("/Ob2");
  8648. }
  8649. }
  8650. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  8651. options::OPT_fno_omit_frame_pointer))
  8652. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  8653. ? "/Oy"
  8654. : "/Oy-");
  8655. if (!Args.hasArg(options::OPT_fwritable_strings))
  8656. CmdArgs.push_back("/GF");
  8657. // Flags for which clang-cl has an alias.
  8658. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  8659. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  8660. /*default=*/false))
  8661. CmdArgs.push_back("/GR-");
  8662. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  8663. options::OPT_fno_function_sections))
  8664. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  8665. ? "/Gy"
  8666. : "/Gy-");
  8667. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  8668. options::OPT_fno_data_sections))
  8669. CmdArgs.push_back(
  8670. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  8671. if (Args.hasArg(options::OPT_fsyntax_only))
  8672. CmdArgs.push_back("/Zs");
  8673. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  8674. options::OPT__SLASH_Z7))
  8675. CmdArgs.push_back("/Z7");
  8676. std::vector<std::string> Includes =
  8677. Args.getAllArgValues(options::OPT_include);
  8678. for (const auto &Include : Includes)
  8679. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  8680. // Flags that can simply be passed through.
  8681. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  8682. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  8683. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
  8684. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
  8685. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  8686. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  8687. // The order of these flags is relevant, so pick the last one.
  8688. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  8689. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  8690. A->render(Args, CmdArgs);
  8691. // Pass through all unknown arguments so that the fallback command can see
  8692. // them too.
  8693. Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
  8694. // Input filename.
  8695. assert(Inputs.size() == 1);
  8696. const InputInfo &II = Inputs[0];
  8697. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  8698. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  8699. if (II.isFilename())
  8700. CmdArgs.push_back(II.getFilename());
  8701. else
  8702. II.getInputArg().renderAsInput(Args, CmdArgs);
  8703. // Output filename.
  8704. assert(Output.getType() == types::TY_Object);
  8705. const char *Fo =
  8706. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  8707. CmdArgs.push_back(Fo);
  8708. const Driver &D = getToolChain().getDriver();
  8709. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  8710. D.getClangProgramPath());
  8711. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8712. CmdArgs, Inputs);
  8713. }
  8714. /// MinGW Tools
  8715. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8716. const InputInfo &Output,
  8717. const InputInfoList &Inputs,
  8718. const ArgList &Args,
  8719. const char *LinkingOutput) const {
  8720. claimNoWarnArgs(Args);
  8721. ArgStringList CmdArgs;
  8722. if (getToolChain().getArch() == llvm::Triple::x86) {
  8723. CmdArgs.push_back("--32");
  8724. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  8725. CmdArgs.push_back("--64");
  8726. }
  8727. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8728. CmdArgs.push_back("-o");
  8729. CmdArgs.push_back(Output.getFilename());
  8730. for (const auto &II : Inputs)
  8731. CmdArgs.push_back(II.getFilename());
  8732. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8733. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8734. if (Args.hasArg(options::OPT_gsplit_dwarf))
  8735. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8736. SplitDebugName(Args, Inputs[0]));
  8737. }
  8738. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  8739. ArgStringList &CmdArgs) const {
  8740. if (Args.hasArg(options::OPT_mthreads))
  8741. CmdArgs.push_back("-lmingwthrd");
  8742. CmdArgs.push_back("-lmingw32");
  8743. // Make use of compiler-rt if --rtlib option is used
  8744. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  8745. if (RLT == ToolChain::RLT_Libgcc) {
  8746. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  8747. Args.hasArg(options::OPT_static);
  8748. bool Shared = Args.hasArg(options::OPT_shared);
  8749. bool CXX = getToolChain().getDriver().CCCIsCXX();
  8750. if (Static || (!CXX && !Shared)) {
  8751. CmdArgs.push_back("-lgcc");
  8752. CmdArgs.push_back("-lgcc_eh");
  8753. } else {
  8754. CmdArgs.push_back("-lgcc_s");
  8755. CmdArgs.push_back("-lgcc");
  8756. }
  8757. } else {
  8758. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  8759. }
  8760. CmdArgs.push_back("-lmoldname");
  8761. CmdArgs.push_back("-lmingwex");
  8762. CmdArgs.push_back("-lmsvcrt");
  8763. }
  8764. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8765. const InputInfo &Output,
  8766. const InputInfoList &Inputs,
  8767. const ArgList &Args,
  8768. const char *LinkingOutput) const {
  8769. const ToolChain &TC = getToolChain();
  8770. const Driver &D = TC.getDriver();
  8771. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  8772. ArgStringList CmdArgs;
  8773. // Silence warning for "clang -g foo.o -o foo"
  8774. Args.ClaimAllArgs(options::OPT_g_Group);
  8775. // and "clang -emit-llvm foo.o -o foo"
  8776. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8777. // and for "clang -w foo.o -o foo". Other warning options are already
  8778. // handled somewhere else.
  8779. Args.ClaimAllArgs(options::OPT_w);
  8780. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  8781. if (LinkerName.equals_lower("lld")) {
  8782. CmdArgs.push_back("-flavor");
  8783. CmdArgs.push_back("gnu");
  8784. } else if (!LinkerName.equals_lower("ld")) {
  8785. D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
  8786. }
  8787. if (!D.SysRoot.empty())
  8788. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8789. if (Args.hasArg(options::OPT_s))
  8790. CmdArgs.push_back("-s");
  8791. CmdArgs.push_back("-m");
  8792. if (TC.getArch() == llvm::Triple::x86)
  8793. CmdArgs.push_back("i386pe");
  8794. if (TC.getArch() == llvm::Triple::x86_64)
  8795. CmdArgs.push_back("i386pep");
  8796. if (TC.getArch() == llvm::Triple::arm)
  8797. CmdArgs.push_back("thumb2pe");
  8798. if (Args.hasArg(options::OPT_mwindows)) {
  8799. CmdArgs.push_back("--subsystem");
  8800. CmdArgs.push_back("windows");
  8801. } else if (Args.hasArg(options::OPT_mconsole)) {
  8802. CmdArgs.push_back("--subsystem");
  8803. CmdArgs.push_back("console");
  8804. }
  8805. if (Args.hasArg(options::OPT_static))
  8806. CmdArgs.push_back("-Bstatic");
  8807. else {
  8808. if (Args.hasArg(options::OPT_mdll))
  8809. CmdArgs.push_back("--dll");
  8810. else if (Args.hasArg(options::OPT_shared))
  8811. CmdArgs.push_back("--shared");
  8812. CmdArgs.push_back("-Bdynamic");
  8813. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  8814. CmdArgs.push_back("-e");
  8815. if (TC.getArch() == llvm::Triple::x86)
  8816. CmdArgs.push_back("_DllMainCRTStartup@12");
  8817. else
  8818. CmdArgs.push_back("DllMainCRTStartup");
  8819. CmdArgs.push_back("--enable-auto-image-base");
  8820. }
  8821. }
  8822. CmdArgs.push_back("-o");
  8823. CmdArgs.push_back(Output.getFilename());
  8824. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8825. // FIXME: add -N, -n flags
  8826. Args.AddLastArg(CmdArgs, options::OPT_r);
  8827. Args.AddLastArg(CmdArgs, options::OPT_s);
  8828. Args.AddLastArg(CmdArgs, options::OPT_t);
  8829. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  8830. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  8831. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8832. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  8833. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  8834. } else {
  8835. if (Args.hasArg(options::OPT_municode))
  8836. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  8837. else
  8838. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  8839. }
  8840. if (Args.hasArg(options::OPT_pg))
  8841. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  8842. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8843. }
  8844. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8845. TC.AddFilePathLibArgs(Args, CmdArgs);
  8846. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8847. // TODO: Add ASan stuff here
  8848. // TODO: Add profile stuff here
  8849. if (D.CCCIsCXX() &&
  8850. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8851. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8852. !Args.hasArg(options::OPT_static);
  8853. if (OnlyLibstdcxxStatic)
  8854. CmdArgs.push_back("-Bstatic");
  8855. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8856. if (OnlyLibstdcxxStatic)
  8857. CmdArgs.push_back("-Bdynamic");
  8858. }
  8859. if (!Args.hasArg(options::OPT_nostdlib)) {
  8860. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8861. if (Args.hasArg(options::OPT_static))
  8862. CmdArgs.push_back("--start-group");
  8863. if (Args.hasArg(options::OPT_fstack_protector) ||
  8864. Args.hasArg(options::OPT_fstack_protector_strong) ||
  8865. Args.hasArg(options::OPT_fstack_protector_all)) {
  8866. CmdArgs.push_back("-lssp_nonshared");
  8867. CmdArgs.push_back("-lssp");
  8868. }
  8869. if (Args.hasArg(options::OPT_fopenmp))
  8870. CmdArgs.push_back("-lgomp");
  8871. AddLibGCC(Args, CmdArgs);
  8872. if (Args.hasArg(options::OPT_pg))
  8873. CmdArgs.push_back("-lgmon");
  8874. if (Args.hasArg(options::OPT_pthread))
  8875. CmdArgs.push_back("-lpthread");
  8876. // add system libraries
  8877. if (Args.hasArg(options::OPT_mwindows)) {
  8878. CmdArgs.push_back("-lgdi32");
  8879. CmdArgs.push_back("-lcomdlg32");
  8880. }
  8881. CmdArgs.push_back("-ladvapi32");
  8882. CmdArgs.push_back("-lshell32");
  8883. CmdArgs.push_back("-luser32");
  8884. CmdArgs.push_back("-lkernel32");
  8885. if (Args.hasArg(options::OPT_static))
  8886. CmdArgs.push_back("--end-group");
  8887. else if (!LinkerName.equals_lower("lld"))
  8888. AddLibGCC(Args, CmdArgs);
  8889. }
  8890. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8891. // Add crtfastmath.o if available and fast math is enabled.
  8892. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8893. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8894. }
  8895. }
  8896. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  8897. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8898. }
  8899. /// XCore Tools
  8900. // We pass assemble and link construction to the xcc tool.
  8901. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8902. const InputInfo &Output,
  8903. const InputInfoList &Inputs,
  8904. const ArgList &Args,
  8905. const char *LinkingOutput) const {
  8906. claimNoWarnArgs(Args);
  8907. ArgStringList CmdArgs;
  8908. CmdArgs.push_back("-o");
  8909. CmdArgs.push_back(Output.getFilename());
  8910. CmdArgs.push_back("-c");
  8911. if (Args.hasArg(options::OPT_v))
  8912. CmdArgs.push_back("-v");
  8913. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  8914. if (!A->getOption().matches(options::OPT_g0))
  8915. CmdArgs.push_back("-g");
  8916. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  8917. false))
  8918. CmdArgs.push_back("-fverbose-asm");
  8919. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8920. for (const auto &II : Inputs)
  8921. CmdArgs.push_back(II.getFilename());
  8922. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8923. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8924. }
  8925. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8926. const InputInfo &Output,
  8927. const InputInfoList &Inputs,
  8928. const ArgList &Args,
  8929. const char *LinkingOutput) const {
  8930. ArgStringList CmdArgs;
  8931. if (Output.isFilename()) {
  8932. CmdArgs.push_back("-o");
  8933. CmdArgs.push_back(Output.getFilename());
  8934. } else {
  8935. assert(Output.isNothing() && "Invalid output.");
  8936. }
  8937. if (Args.hasArg(options::OPT_v))
  8938. CmdArgs.push_back("-v");
  8939. // Pass -fexceptions through to the linker if it was present.
  8940. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  8941. false))
  8942. CmdArgs.push_back("-fexceptions");
  8943. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8944. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8945. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8946. }
  8947. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8948. const InputInfo &Output,
  8949. const InputInfoList &Inputs,
  8950. const ArgList &Args,
  8951. const char *LinkingOutput) const {
  8952. claimNoWarnArgs(Args);
  8953. const auto &TC =
  8954. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8955. ArgStringList CmdArgs;
  8956. const char *Exec;
  8957. switch (TC.getArch()) {
  8958. default:
  8959. llvm_unreachable("unsupported architecture");
  8960. case llvm::Triple::arm:
  8961. case llvm::Triple::thumb:
  8962. break;
  8963. case llvm::Triple::x86:
  8964. CmdArgs.push_back("--32");
  8965. break;
  8966. case llvm::Triple::x86_64:
  8967. CmdArgs.push_back("--64");
  8968. break;
  8969. }
  8970. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8971. CmdArgs.push_back("-o");
  8972. CmdArgs.push_back(Output.getFilename());
  8973. for (const auto &Input : Inputs)
  8974. CmdArgs.push_back(Input.getFilename());
  8975. const std::string Assembler = TC.GetProgramPath("as");
  8976. Exec = Args.MakeArgString(Assembler);
  8977. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8978. }
  8979. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8980. const InputInfo &Output,
  8981. const InputInfoList &Inputs,
  8982. const ArgList &Args,
  8983. const char *LinkingOutput) const {
  8984. const auto &TC =
  8985. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8986. const llvm::Triple &T = TC.getTriple();
  8987. const Driver &D = TC.getDriver();
  8988. SmallString<128> EntryPoint;
  8989. ArgStringList CmdArgs;
  8990. const char *Exec;
  8991. // Silence warning for "clang -g foo.o -o foo"
  8992. Args.ClaimAllArgs(options::OPT_g_Group);
  8993. // and "clang -emit-llvm foo.o -o foo"
  8994. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8995. // and for "clang -w foo.o -o foo"
  8996. Args.ClaimAllArgs(options::OPT_w);
  8997. // Other warning options are already handled somewhere else.
  8998. if (!D.SysRoot.empty())
  8999. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9000. if (Args.hasArg(options::OPT_pie))
  9001. CmdArgs.push_back("-pie");
  9002. if (Args.hasArg(options::OPT_rdynamic))
  9003. CmdArgs.push_back("-export-dynamic");
  9004. if (Args.hasArg(options::OPT_s))
  9005. CmdArgs.push_back("--strip-all");
  9006. CmdArgs.push_back("-m");
  9007. switch (TC.getArch()) {
  9008. default:
  9009. llvm_unreachable("unsupported architecture");
  9010. case llvm::Triple::arm:
  9011. case llvm::Triple::thumb:
  9012. // FIXME: this is incorrect for WinCE
  9013. CmdArgs.push_back("thumb2pe");
  9014. break;
  9015. case llvm::Triple::x86:
  9016. CmdArgs.push_back("i386pe");
  9017. EntryPoint.append("_");
  9018. break;
  9019. case llvm::Triple::x86_64:
  9020. CmdArgs.push_back("i386pep");
  9021. break;
  9022. }
  9023. if (Args.hasArg(options::OPT_shared)) {
  9024. switch (T.getArch()) {
  9025. default:
  9026. llvm_unreachable("unsupported architecture");
  9027. case llvm::Triple::arm:
  9028. case llvm::Triple::thumb:
  9029. case llvm::Triple::x86_64:
  9030. EntryPoint.append("_DllMainCRTStartup");
  9031. break;
  9032. case llvm::Triple::x86:
  9033. EntryPoint.append("_DllMainCRTStartup@12");
  9034. break;
  9035. }
  9036. CmdArgs.push_back("-shared");
  9037. CmdArgs.push_back("-Bdynamic");
  9038. CmdArgs.push_back("--enable-auto-image-base");
  9039. CmdArgs.push_back("--entry");
  9040. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  9041. } else {
  9042. EntryPoint.append("mainCRTStartup");
  9043. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  9044. : "-Bdynamic");
  9045. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9046. CmdArgs.push_back("--entry");
  9047. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  9048. }
  9049. // FIXME: handle subsystem
  9050. }
  9051. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  9052. CmdArgs.push_back("--allow-multiple-definition");
  9053. CmdArgs.push_back("-o");
  9054. CmdArgs.push_back(Output.getFilename());
  9055. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  9056. SmallString<261> ImpLib(Output.getFilename());
  9057. llvm::sys::path::replace_extension(ImpLib, ".lib");
  9058. CmdArgs.push_back("--out-implib");
  9059. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  9060. }
  9061. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9062. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  9063. const char *CRTBegin;
  9064. CRTBegin =
  9065. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  9066. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  9067. }
  9068. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9069. TC.AddFilePathLibArgs(Args, CmdArgs);
  9070. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  9071. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  9072. !Args.hasArg(options::OPT_nodefaultlibs)) {
  9073. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  9074. !Args.hasArg(options::OPT_static);
  9075. if (StaticCXX)
  9076. CmdArgs.push_back("-Bstatic");
  9077. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  9078. if (StaticCXX)
  9079. CmdArgs.push_back("-Bdynamic");
  9080. }
  9081. if (!Args.hasArg(options::OPT_nostdlib)) {
  9082. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  9083. // TODO handle /MT[d] /MD[d]
  9084. CmdArgs.push_back("-lmsvcrt");
  9085. AddRunTimeLibs(TC, D, CmdArgs, Args);
  9086. }
  9087. }
  9088. if (TC.getSanitizerArgs().needsAsanRt()) {
  9089. // TODO handle /MT[d] /MD[d]
  9090. if (Args.hasArg(options::OPT_shared)) {
  9091. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  9092. } else {
  9093. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  9094. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  9095. // Make sure the dynamic runtime thunk is not optimized out at link time
  9096. // to ensure proper SEH handling.
  9097. CmdArgs.push_back(Args.MakeArgString("--undefined"));
  9098. CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
  9099. ? "___asan_seh_interceptor"
  9100. : "__asan_seh_interceptor"));
  9101. }
  9102. }
  9103. Exec = Args.MakeArgString(TC.GetLinkerPath());
  9104. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9105. }
  9106. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  9107. const InputInfo &Output,
  9108. const InputInfoList &Inputs,
  9109. const ArgList &Args,
  9110. const char *LinkingOutput) const {
  9111. ArgStringList CmdArgs;
  9112. assert(Inputs.size() == 1);
  9113. const InputInfo &II = Inputs[0];
  9114. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
  9115. II.getType() == types::TY_PP_CXX);
  9116. if (JA.getKind() == Action::PreprocessJobClass) {
  9117. Args.ClaimAllArgs();
  9118. CmdArgs.push_back("-E");
  9119. } else {
  9120. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  9121. CmdArgs.push_back("-S");
  9122. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  9123. }
  9124. CmdArgs.push_back("-DMYRIAD2");
  9125. // Append all -I, -iquote, -isystem paths, defines/undefines,
  9126. // 'f' flags, optimize flags, and warning options.
  9127. // These are spelled the same way in clang and moviCompile.
  9128. Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
  9129. options::OPT_std_EQ, options::OPT_D, options::OPT_U,
  9130. options::OPT_f_Group, options::OPT_f_clang_Group,
  9131. options::OPT_g_Group, options::OPT_M_Group,
  9132. options::OPT_O_Group, options::OPT_W_Group,
  9133. options::OPT_mcpu_EQ});
  9134. // If we're producing a dependency file, and assembly is the final action,
  9135. // then the name of the target in the dependency file should be the '.o'
  9136. // file, not the '.s' file produced by this step. For example, instead of
  9137. // /tmp/mumble.s: mumble.c .../someheader.h
  9138. // the filename on the lefthand side should be "mumble.o"
  9139. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  9140. C.getActions().size() == 1 &&
  9141. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  9142. Arg *A = Args.getLastArg(options::OPT_o);
  9143. if (A) {
  9144. CmdArgs.push_back("-MT");
  9145. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  9146. }
  9147. }
  9148. CmdArgs.push_back(II.getFilename());
  9149. CmdArgs.push_back("-o");
  9150. CmdArgs.push_back(Output.getFilename());
  9151. std::string Exec =
  9152. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  9153. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9154. CmdArgs, Inputs));
  9155. }
  9156. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9157. const InputInfo &Output,
  9158. const InputInfoList &Inputs,
  9159. const ArgList &Args,
  9160. const char *LinkingOutput) const {
  9161. ArgStringList CmdArgs;
  9162. assert(Inputs.size() == 1);
  9163. const InputInfo &II = Inputs[0];
  9164. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  9165. assert(Output.getType() == types::TY_Object);
  9166. CmdArgs.push_back("-no6thSlotCompression");
  9167. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  9168. if (CPUArg)
  9169. CmdArgs.push_back(
  9170. Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
  9171. CmdArgs.push_back("-noSPrefixing");
  9172. CmdArgs.push_back("-a"); // Mystery option.
  9173. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9174. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  9175. A->claim();
  9176. CmdArgs.push_back(
  9177. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  9178. }
  9179. CmdArgs.push_back("-elf"); // Output format.
  9180. CmdArgs.push_back(II.getFilename());
  9181. CmdArgs.push_back(
  9182. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  9183. std::string Exec =
  9184. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  9185. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9186. CmdArgs, Inputs));
  9187. }
  9188. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9189. const InputInfo &Output,
  9190. const InputInfoList &Inputs,
  9191. const ArgList &Args,
  9192. const char *LinkingOutput) const {
  9193. const auto &TC =
  9194. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  9195. const llvm::Triple &T = TC.getTriple();
  9196. ArgStringList CmdArgs;
  9197. bool UseStartfiles =
  9198. !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
  9199. bool UseDefaultLibs =
  9200. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  9201. if (T.getArch() == llvm::Triple::sparc)
  9202. CmdArgs.push_back("-EB");
  9203. else // SHAVE assumes little-endian, and sparcel is expressly so.
  9204. CmdArgs.push_back("-EL");
  9205. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  9206. // but we never pass through a --sysroot option and various other bits.
  9207. // For example, there are no sanitizers (yet) nor gold linker.
  9208. // Eat some arguments that may be present but have no effect.
  9209. Args.ClaimAllArgs(options::OPT_g_Group);
  9210. Args.ClaimAllArgs(options::OPT_w);
  9211. Args.ClaimAllArgs(options::OPT_static_libgcc);
  9212. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  9213. CmdArgs.push_back("-s");
  9214. CmdArgs.push_back("-o");
  9215. CmdArgs.push_back(Output.getFilename());
  9216. if (UseStartfiles) {
  9217. // If you want startfiles, it means you want the builtin crti and crtbegin,
  9218. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  9219. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
  9220. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  9221. }
  9222. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  9223. options::OPT_e, options::OPT_s, options::OPT_t,
  9224. options::OPT_Z_Flag, options::OPT_r});
  9225. TC.AddFilePathLibArgs(Args, CmdArgs);
  9226. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  9227. if (UseDefaultLibs) {
  9228. if (C.getDriver().CCCIsCXX())
  9229. CmdArgs.push_back("-lstdc++");
  9230. if (T.getOS() == llvm::Triple::RTEMS) {
  9231. CmdArgs.push_back("--start-group");
  9232. CmdArgs.push_back("-lc");
  9233. // You must provide your own "-L" option to enable finding these.
  9234. CmdArgs.push_back("-lrtemscpu");
  9235. CmdArgs.push_back("-lrtemsbsp");
  9236. CmdArgs.push_back("--end-group");
  9237. } else {
  9238. CmdArgs.push_back("-lc");
  9239. }
  9240. CmdArgs.push_back("-lgcc");
  9241. }
  9242. if (UseStartfiles) {
  9243. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  9244. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
  9245. }
  9246. std::string Exec =
  9247. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  9248. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9249. CmdArgs, Inputs));
  9250. }
  9251. void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
  9252. const InputInfo &Output,
  9253. const InputInfoList &Inputs,
  9254. const ArgList &Args,
  9255. const char *LinkingOutput) const {
  9256. claimNoWarnArgs(Args);
  9257. ArgStringList CmdArgs;
  9258. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9259. CmdArgs.push_back("-o");
  9260. CmdArgs.push_back(Output.getFilename());
  9261. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  9262. const InputInfo &Input = Inputs[0];
  9263. assert(Input.isFilename() && "Invalid input.");
  9264. CmdArgs.push_back(Input.getFilename());
  9265. const char *Exec =
  9266. Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
  9267. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9268. }
  9269. static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
  9270. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  9271. if (SanArgs.needsUbsanRt()) {
  9272. CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
  9273. }
  9274. if (SanArgs.needsAsanRt()) {
  9275. CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
  9276. }
  9277. }
  9278. static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
  9279. const JobAction &JA, const InputInfo &Output,
  9280. const InputInfoList &Inputs,
  9281. const ArgList &Args,
  9282. const char *LinkingOutput) {
  9283. const toolchains::FreeBSD &ToolChain =
  9284. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9285. const Driver &D = ToolChain.getDriver();
  9286. ArgStringList CmdArgs;
  9287. // Silence warning for "clang -g foo.o -o foo"
  9288. Args.ClaimAllArgs(options::OPT_g_Group);
  9289. // and "clang -emit-llvm foo.o -o foo"
  9290. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9291. // and for "clang -w foo.o -o foo". Other warning options are already
  9292. // handled somewhere else.
  9293. Args.ClaimAllArgs(options::OPT_w);
  9294. if (!D.SysRoot.empty())
  9295. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9296. if (Args.hasArg(options::OPT_pie))
  9297. CmdArgs.push_back("-pie");
  9298. if (Args.hasArg(options::OPT_rdynamic))
  9299. CmdArgs.push_back("-export-dynamic");
  9300. if (Args.hasArg(options::OPT_shared))
  9301. CmdArgs.push_back("--oformat=so");
  9302. if (Output.isFilename()) {
  9303. CmdArgs.push_back("-o");
  9304. CmdArgs.push_back(Output.getFilename());
  9305. } else {
  9306. assert(Output.isNothing() && "Invalid output.");
  9307. }
  9308. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9309. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9310. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9311. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9312. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9313. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9314. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9315. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9316. CmdArgs.push_back("--no-demangle");
  9317. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9318. if (Args.hasArg(options::OPT_pthread)) {
  9319. CmdArgs.push_back("-lpthread");
  9320. }
  9321. const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  9322. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9323. }
  9324. static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
  9325. const JobAction &JA, const InputInfo &Output,
  9326. const InputInfoList &Inputs,
  9327. const ArgList &Args,
  9328. const char *LinkingOutput) {
  9329. const toolchains::FreeBSD &ToolChain =
  9330. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9331. const Driver &D = ToolChain.getDriver();
  9332. ArgStringList CmdArgs;
  9333. // Silence warning for "clang -g foo.o -o foo"
  9334. Args.ClaimAllArgs(options::OPT_g_Group);
  9335. // and "clang -emit-llvm foo.o -o foo"
  9336. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9337. // and for "clang -w foo.o -o foo". Other warning options are already
  9338. // handled somewhere else.
  9339. Args.ClaimAllArgs(options::OPT_w);
  9340. if (!D.SysRoot.empty())
  9341. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9342. if (Args.hasArg(options::OPT_pie))
  9343. CmdArgs.push_back("-pie");
  9344. if (Args.hasArg(options::OPT_static)) {
  9345. CmdArgs.push_back("-Bstatic");
  9346. } else {
  9347. if (Args.hasArg(options::OPT_rdynamic))
  9348. CmdArgs.push_back("-export-dynamic");
  9349. CmdArgs.push_back("--eh-frame-hdr");
  9350. if (Args.hasArg(options::OPT_shared)) {
  9351. CmdArgs.push_back("-Bshareable");
  9352. } else {
  9353. CmdArgs.push_back("-dynamic-linker");
  9354. CmdArgs.push_back("/libexec/ld-elf.so.1");
  9355. }
  9356. CmdArgs.push_back("--enable-new-dtags");
  9357. }
  9358. if (Output.isFilename()) {
  9359. CmdArgs.push_back("-o");
  9360. CmdArgs.push_back(Output.getFilename());
  9361. } else {
  9362. assert(Output.isNothing() && "Invalid output.");
  9363. }
  9364. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9365. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9366. const char *crt1 = nullptr;
  9367. if (!Args.hasArg(options::OPT_shared)) {
  9368. if (Args.hasArg(options::OPT_pg))
  9369. crt1 = "gcrt1.o";
  9370. else if (Args.hasArg(options::OPT_pie))
  9371. crt1 = "Scrt1.o";
  9372. else
  9373. crt1 = "crt1.o";
  9374. }
  9375. if (crt1)
  9376. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  9377. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  9378. const char *crtbegin = nullptr;
  9379. if (Args.hasArg(options::OPT_static))
  9380. crtbegin = "crtbeginT.o";
  9381. else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9382. crtbegin = "crtbeginS.o";
  9383. else
  9384. crtbegin = "crtbegin.o";
  9385. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  9386. }
  9387. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9388. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  9389. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9390. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9391. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9392. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9393. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9394. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9395. CmdArgs.push_back("--no-demangle");
  9396. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9397. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9398. // For PS4, we always want to pass libm, libstdc++ and libkernel
  9399. // libraries for both C and C++ compilations.
  9400. CmdArgs.push_back("-lkernel");
  9401. if (D.CCCIsCXX()) {
  9402. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  9403. if (Args.hasArg(options::OPT_pg))
  9404. CmdArgs.push_back("-lm_p");
  9405. else
  9406. CmdArgs.push_back("-lm");
  9407. }
  9408. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  9409. // the default system libraries. Just mimic this for now.
  9410. if (Args.hasArg(options::OPT_pg))
  9411. CmdArgs.push_back("-lgcc_p");
  9412. else
  9413. CmdArgs.push_back("-lcompiler_rt");
  9414. if (Args.hasArg(options::OPT_static)) {
  9415. CmdArgs.push_back("-lstdc++");
  9416. } else if (Args.hasArg(options::OPT_pg)) {
  9417. CmdArgs.push_back("-lgcc_eh_p");
  9418. } else {
  9419. CmdArgs.push_back("--as-needed");
  9420. CmdArgs.push_back("-lstdc++");
  9421. CmdArgs.push_back("--no-as-needed");
  9422. }
  9423. if (Args.hasArg(options::OPT_pthread)) {
  9424. if (Args.hasArg(options::OPT_pg))
  9425. CmdArgs.push_back("-lpthread_p");
  9426. else
  9427. CmdArgs.push_back("-lpthread");
  9428. }
  9429. if (Args.hasArg(options::OPT_pg)) {
  9430. if (Args.hasArg(options::OPT_shared))
  9431. CmdArgs.push_back("-lc");
  9432. else {
  9433. if (Args.hasArg(options::OPT_static)) {
  9434. CmdArgs.push_back("--start-group");
  9435. CmdArgs.push_back("-lc_p");
  9436. CmdArgs.push_back("-lpthread_p");
  9437. CmdArgs.push_back("--end-group");
  9438. } else {
  9439. CmdArgs.push_back("-lc_p");
  9440. }
  9441. }
  9442. CmdArgs.push_back("-lgcc_p");
  9443. } else {
  9444. if (Args.hasArg(options::OPT_static)) {
  9445. CmdArgs.push_back("--start-group");
  9446. CmdArgs.push_back("-lc");
  9447. CmdArgs.push_back("-lpthread");
  9448. CmdArgs.push_back("--end-group");
  9449. } else {
  9450. CmdArgs.push_back("-lc");
  9451. }
  9452. CmdArgs.push_back("-lcompiler_rt");
  9453. }
  9454. if (Args.hasArg(options::OPT_static)) {
  9455. CmdArgs.push_back("-lstdc++");
  9456. } else if (Args.hasArg(options::OPT_pg)) {
  9457. CmdArgs.push_back("-lgcc_eh_p");
  9458. } else {
  9459. CmdArgs.push_back("--as-needed");
  9460. CmdArgs.push_back("-lstdc++");
  9461. CmdArgs.push_back("--no-as-needed");
  9462. }
  9463. }
  9464. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9465. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9466. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  9467. else
  9468. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  9469. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  9470. }
  9471. const char *Exec =
  9472. #ifdef LLVM_ON_WIN32
  9473. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
  9474. #else
  9475. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  9476. #endif
  9477. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9478. }
  9479. void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
  9480. const InputInfo &Output,
  9481. const InputInfoList &Inputs,
  9482. const ArgList &Args,
  9483. const char *LinkingOutput) const {
  9484. const toolchains::FreeBSD &ToolChain =
  9485. static_cast<const toolchains::FreeBSD &>(getToolChain());
  9486. const Driver &D = ToolChain.getDriver();
  9487. bool PS4Linker;
  9488. StringRef LinkerOptName;
  9489. if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  9490. LinkerOptName = A->getValue();
  9491. if (LinkerOptName != "ps4" && LinkerOptName != "gold")
  9492. D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
  9493. }
  9494. if (LinkerOptName == "gold")
  9495. PS4Linker = false;
  9496. else if (LinkerOptName == "ps4")
  9497. PS4Linker = true;
  9498. else
  9499. PS4Linker = !Args.hasArg(options::OPT_shared);
  9500. if (PS4Linker)
  9501. ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9502. else
  9503. ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9504. }
  9505. void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9506. const InputInfo &Output,
  9507. const InputInfoList &Inputs,
  9508. const ArgList &Args,
  9509. const char *LinkingOutput) const {
  9510. const auto &TC =
  9511. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  9512. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  9513. std::vector<std::string> gpu_archs =
  9514. Args.getAllArgValues(options::OPT_march_EQ);
  9515. assert(gpu_archs.size() == 1 && "Exactly one GPU Arch required for ptxas.");
  9516. const std::string& gpu_arch = gpu_archs[0];
  9517. ArgStringList CmdArgs;
  9518. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
  9519. if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
  9520. options::OPT_no_cuda_noopt_device_debug, false)) {
  9521. // ptxas does not accept -g option if optimization is enabled, so
  9522. // we ignore the compiler's -O* options if we want debug info.
  9523. CmdArgs.push_back("-g");
  9524. CmdArgs.push_back("--dont-merge-basicblocks");
  9525. CmdArgs.push_back("--return-at-end");
  9526. } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  9527. // Map the -O we received to -O{0,1,2,3}.
  9528. //
  9529. // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
  9530. // default, so it may correspond more closely to the spirit of clang -O2.
  9531. // -O3 seems like the least-bad option when -Osomething is specified to
  9532. // clang but it isn't handled below.
  9533. StringRef OOpt = "3";
  9534. if (A->getOption().matches(options::OPT_O4) ||
  9535. A->getOption().matches(options::OPT_Ofast))
  9536. OOpt = "3";
  9537. else if (A->getOption().matches(options::OPT_O0))
  9538. OOpt = "0";
  9539. else if (A->getOption().matches(options::OPT_O)) {
  9540. // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
  9541. OOpt = llvm::StringSwitch<const char *>(A->getValue())
  9542. .Case("1", "1")
  9543. .Case("2", "2")
  9544. .Case("3", "3")
  9545. .Case("s", "2")
  9546. .Case("z", "2")
  9547. .Default("2");
  9548. }
  9549. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
  9550. } else {
  9551. // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
  9552. // to no optimizations, but ptxas's default is -O3.
  9553. CmdArgs.push_back("-O0");
  9554. }
  9555. CmdArgs.push_back("--gpu-name");
  9556. CmdArgs.push_back(Args.MakeArgString(gpu_arch));
  9557. CmdArgs.push_back("--output-file");
  9558. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  9559. for (const auto& II : Inputs)
  9560. CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
  9561. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
  9562. CmdArgs.push_back(Args.MakeArgString(A));
  9563. const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
  9564. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9565. }
  9566. // All inputs to this linker must be from CudaDeviceActions, as we need to look
  9567. // at the Inputs' Actions in order to figure out which GPU architecture they
  9568. // correspond to.
  9569. void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9570. const InputInfo &Output,
  9571. const InputInfoList &Inputs,
  9572. const ArgList &Args,
  9573. const char *LinkingOutput) const {
  9574. const auto &TC =
  9575. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  9576. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  9577. ArgStringList CmdArgs;
  9578. CmdArgs.push_back("--cuda");
  9579. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
  9580. CmdArgs.push_back(Args.MakeArgString("--create"));
  9581. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  9582. for (const auto& II : Inputs) {
  9583. auto* A = cast<const CudaDeviceAction>(II.getAction());
  9584. // We need to pass an Arch of the form "sm_XX" for cubin files and
  9585. // "compute_XX" for ptx.
  9586. const char *Arch = (II.getType() == types::TY_PP_Asm)
  9587. ? A->getComputeArchName()
  9588. : A->getGpuArchName();
  9589. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
  9590. Arch + ",file=" + II.getFilename()));
  9591. }
  9592. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
  9593. CmdArgs.push_back(Args.MakeArgString(A));
  9594. const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
  9595. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9596. }