Tools.cpp 405 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126
  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. DefMips32CPU = "mips32";
  1065. DefMips64CPU = "mips64r6";
  1066. }
  1067. // MIPS3 is the default for mips64*-unknown-openbsd.
  1068. if (Triple.getOS() == llvm::Triple::OpenBSD)
  1069. DefMips64CPU = "mips3";
  1070. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  1071. CPUName = A->getValue();
  1072. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1073. ABIName = A->getValue();
  1074. // Convert a GNU style Mips ABI name to the name
  1075. // accepted by LLVM Mips backend.
  1076. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  1077. .Case("32", "o32")
  1078. .Case("64", "n64")
  1079. .Default(ABIName);
  1080. }
  1081. // Setup default CPU and ABI names.
  1082. if (CPUName.empty() && ABIName.empty()) {
  1083. switch (Triple.getArch()) {
  1084. default:
  1085. llvm_unreachable("Unexpected triple arch name");
  1086. case llvm::Triple::mips:
  1087. case llvm::Triple::mipsel:
  1088. CPUName = DefMips32CPU;
  1089. break;
  1090. case llvm::Triple::mips64:
  1091. case llvm::Triple::mips64el:
  1092. CPUName = DefMips64CPU;
  1093. break;
  1094. }
  1095. }
  1096. if (ABIName.empty() &&
  1097. (Triple.getVendor() == llvm::Triple::MipsTechnologies ||
  1098. Triple.getVendor() == llvm::Triple::ImaginationTechnologies)) {
  1099. ABIName = llvm::StringSwitch<const char *>(CPUName)
  1100. .Case("mips1", "o32")
  1101. .Case("mips2", "o32")
  1102. .Case("mips3", "n64")
  1103. .Case("mips4", "n64")
  1104. .Case("mips5", "n64")
  1105. .Case("mips32", "o32")
  1106. .Case("mips32r2", "o32")
  1107. .Case("mips32r3", "o32")
  1108. .Case("mips32r5", "o32")
  1109. .Case("mips32r6", "o32")
  1110. .Case("mips64", "n64")
  1111. .Case("mips64r2", "n64")
  1112. .Case("mips64r3", "n64")
  1113. .Case("mips64r5", "n64")
  1114. .Case("mips64r6", "n64")
  1115. .Case("octeon", "n64")
  1116. .Case("p5600", "o32")
  1117. .Default("");
  1118. }
  1119. if (ABIName.empty()) {
  1120. // Deduce ABI name from the target triple.
  1121. if (Triple.getArch() == llvm::Triple::mips ||
  1122. Triple.getArch() == llvm::Triple::mipsel)
  1123. ABIName = "o32";
  1124. else
  1125. ABIName = "n64";
  1126. }
  1127. if (CPUName.empty()) {
  1128. // Deduce CPU name from ABI name.
  1129. CPUName = llvm::StringSwitch<const char *>(ABIName)
  1130. .Case("o32", DefMips32CPU)
  1131. .Cases("n32", "n64", DefMips64CPU)
  1132. .Default("");
  1133. }
  1134. // FIXME: Warn on inconsistent use of -march and -mabi.
  1135. }
  1136. std::string mips::getMipsABILibSuffix(const ArgList &Args,
  1137. const llvm::Triple &Triple) {
  1138. StringRef CPUName, ABIName;
  1139. tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1140. return llvm::StringSwitch<std::string>(ABIName)
  1141. .Case("o32", "")
  1142. .Case("n32", "32")
  1143. .Case("n64", "64");
  1144. }
  1145. // Convert ABI name to the GNU tools acceptable variant.
  1146. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  1147. return llvm::StringSwitch<llvm::StringRef>(ABI)
  1148. .Case("o32", "32")
  1149. .Case("n64", "64")
  1150. .Default(ABI);
  1151. }
  1152. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  1153. // and -mfloat-abi=.
  1154. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  1155. mips::FloatABI ABI = mips::FloatABI::Invalid;
  1156. if (Arg *A =
  1157. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1158. options::OPT_mfloat_abi_EQ)) {
  1159. if (A->getOption().matches(options::OPT_msoft_float))
  1160. ABI = mips::FloatABI::Soft;
  1161. else if (A->getOption().matches(options::OPT_mhard_float))
  1162. ABI = mips::FloatABI::Hard;
  1163. else {
  1164. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  1165. .Case("soft", mips::FloatABI::Soft)
  1166. .Case("hard", mips::FloatABI::Hard)
  1167. .Default(mips::FloatABI::Invalid);
  1168. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1169. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1170. ABI = mips::FloatABI::Hard;
  1171. }
  1172. }
  1173. }
  1174. // If unspecified, choose the default based on the platform.
  1175. if (ABI == mips::FloatABI::Invalid) {
  1176. // Assume "hard", because it's a default value used by gcc.
  1177. // When we start to recognize specific target MIPS processors,
  1178. // we will be able to select the default more correctly.
  1179. ABI = mips::FloatABI::Hard;
  1180. }
  1181. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  1182. return ABI;
  1183. }
  1184. static void AddTargetFeature(const ArgList &Args,
  1185. std::vector<const char *> &Features,
  1186. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1187. StringRef FeatureName) {
  1188. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1189. if (A->getOption().matches(OnOpt))
  1190. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1191. else
  1192. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1193. }
  1194. }
  1195. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1196. const ArgList &Args,
  1197. std::vector<const char *> &Features) {
  1198. StringRef CPUName;
  1199. StringRef ABIName;
  1200. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1201. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1202. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1203. options::OPT_mabicalls, "noabicalls");
  1204. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1205. if (FloatABI == mips::FloatABI::Soft) {
  1206. // FIXME: Note, this is a hack. We need to pass the selected float
  1207. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1208. // Now it is the only method.
  1209. Features.push_back("+soft-float");
  1210. }
  1211. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1212. StringRef Val = StringRef(A->getValue());
  1213. if (Val == "2008") {
  1214. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1215. Features.push_back("+nan2008");
  1216. else {
  1217. Features.push_back("-nan2008");
  1218. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1219. }
  1220. } else if (Val == "legacy") {
  1221. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1222. Features.push_back("-nan2008");
  1223. else {
  1224. Features.push_back("+nan2008");
  1225. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1226. }
  1227. } else
  1228. D.Diag(diag::err_drv_unsupported_option_argument)
  1229. << A->getOption().getName() << Val;
  1230. }
  1231. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1232. options::OPT_mdouble_float, "single-float");
  1233. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1234. "mips16");
  1235. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1236. options::OPT_mno_micromips, "micromips");
  1237. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1238. "dsp");
  1239. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1240. "dspr2");
  1241. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1242. "msa");
  1243. // Add the last -mfp32/-mfpxx/-mfp64, if none are given and the ABI is O32
  1244. // pass -mfpxx, or if none are given and fp64a is default, pass fp64 and
  1245. // nooddspreg.
  1246. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1247. options::OPT_mfp64)) {
  1248. if (A->getOption().matches(options::OPT_mfp32))
  1249. Features.push_back(Args.MakeArgString("-fp64"));
  1250. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1251. Features.push_back(Args.MakeArgString("+fpxx"));
  1252. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1253. } else
  1254. Features.push_back(Args.MakeArgString("+fp64"));
  1255. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1256. Features.push_back(Args.MakeArgString("+fpxx"));
  1257. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1258. } else if (mips::isFP64ADefault(Triple, CPUName)) {
  1259. Features.push_back(Args.MakeArgString("+fp64"));
  1260. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1261. }
  1262. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1263. options::OPT_modd_spreg, "nooddspreg");
  1264. }
  1265. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1266. ArgStringList &CmdArgs) const {
  1267. const Driver &D = getToolChain().getDriver();
  1268. StringRef CPUName;
  1269. StringRef ABIName;
  1270. const llvm::Triple &Triple = getToolChain().getTriple();
  1271. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1272. CmdArgs.push_back("-target-abi");
  1273. CmdArgs.push_back(ABIName.data());
  1274. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1275. if (ABI == mips::FloatABI::Soft) {
  1276. // Floating point operations and argument passing are soft.
  1277. CmdArgs.push_back("-msoft-float");
  1278. CmdArgs.push_back("-mfloat-abi");
  1279. CmdArgs.push_back("soft");
  1280. } else {
  1281. // Floating point operations and argument passing are hard.
  1282. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1283. CmdArgs.push_back("-mfloat-abi");
  1284. CmdArgs.push_back("hard");
  1285. }
  1286. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1287. if (A->getOption().matches(options::OPT_mxgot)) {
  1288. CmdArgs.push_back("-mllvm");
  1289. CmdArgs.push_back("-mxgot");
  1290. }
  1291. }
  1292. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1293. options::OPT_mno_ldc1_sdc1)) {
  1294. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1295. CmdArgs.push_back("-mllvm");
  1296. CmdArgs.push_back("-mno-ldc1-sdc1");
  1297. }
  1298. }
  1299. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1300. options::OPT_mno_check_zero_division)) {
  1301. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1302. CmdArgs.push_back("-mllvm");
  1303. CmdArgs.push_back("-mno-check-zero-division");
  1304. }
  1305. }
  1306. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1307. StringRef v = A->getValue();
  1308. CmdArgs.push_back("-mllvm");
  1309. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1310. A->claim();
  1311. }
  1312. if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
  1313. StringRef Val = StringRef(A->getValue());
  1314. if (mips::hasCompactBranches(CPUName)) {
  1315. if (Val == "never" || Val == "always" || Val == "optimal") {
  1316. CmdArgs.push_back("-mllvm");
  1317. CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
  1318. } else
  1319. D.Diag(diag::err_drv_unsupported_option_argument)
  1320. << A->getOption().getName() << Val;
  1321. } else
  1322. D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
  1323. }
  1324. }
  1325. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1326. static std::string getPPCTargetCPU(const ArgList &Args) {
  1327. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1328. StringRef CPUName = A->getValue();
  1329. if (CPUName == "native") {
  1330. std::string CPU = llvm::sys::getHostCPUName();
  1331. if (!CPU.empty() && CPU != "generic")
  1332. return CPU;
  1333. else
  1334. return "";
  1335. }
  1336. return llvm::StringSwitch<const char *>(CPUName)
  1337. .Case("common", "generic")
  1338. .Case("440", "440")
  1339. .Case("440fp", "440")
  1340. .Case("450", "450")
  1341. .Case("601", "601")
  1342. .Case("602", "602")
  1343. .Case("603", "603")
  1344. .Case("603e", "603e")
  1345. .Case("603ev", "603ev")
  1346. .Case("604", "604")
  1347. .Case("604e", "604e")
  1348. .Case("620", "620")
  1349. .Case("630", "pwr3")
  1350. .Case("G3", "g3")
  1351. .Case("7400", "7400")
  1352. .Case("G4", "g4")
  1353. .Case("7450", "7450")
  1354. .Case("G4+", "g4+")
  1355. .Case("750", "750")
  1356. .Case("970", "970")
  1357. .Case("G5", "g5")
  1358. .Case("a2", "a2")
  1359. .Case("a2q", "a2q")
  1360. .Case("e500mc", "e500mc")
  1361. .Case("e5500", "e5500")
  1362. .Case("power3", "pwr3")
  1363. .Case("power4", "pwr4")
  1364. .Case("power5", "pwr5")
  1365. .Case("power5x", "pwr5x")
  1366. .Case("power6", "pwr6")
  1367. .Case("power6x", "pwr6x")
  1368. .Case("power7", "pwr7")
  1369. .Case("power8", "pwr8")
  1370. .Case("power9", "pwr9")
  1371. .Case("pwr3", "pwr3")
  1372. .Case("pwr4", "pwr4")
  1373. .Case("pwr5", "pwr5")
  1374. .Case("pwr5x", "pwr5x")
  1375. .Case("pwr6", "pwr6")
  1376. .Case("pwr6x", "pwr6x")
  1377. .Case("pwr7", "pwr7")
  1378. .Case("pwr8", "pwr8")
  1379. .Case("pwr9", "pwr9")
  1380. .Case("powerpc", "ppc")
  1381. .Case("powerpc64", "ppc64")
  1382. .Case("powerpc64le", "ppc64le")
  1383. .Default("");
  1384. }
  1385. return "";
  1386. }
  1387. static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1388. const ArgList &Args,
  1389. std::vector<const char *> &Features) {
  1390. handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
  1391. ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
  1392. if (FloatABI == ppc::FloatABI::Soft &&
  1393. !(Triple.getArch() == llvm::Triple::ppc64 ||
  1394. Triple.getArch() == llvm::Triple::ppc64le))
  1395. Features.push_back("+soft-float");
  1396. else if (FloatABI == ppc::FloatABI::Soft &&
  1397. (Triple.getArch() == llvm::Triple::ppc64 ||
  1398. Triple.getArch() == llvm::Triple::ppc64le))
  1399. D.Diag(diag::err_drv_invalid_mfloat_abi)
  1400. << "soft float is not supported for ppc64";
  1401. // Altivec is a bit weird, allow overriding of the Altivec feature here.
  1402. AddTargetFeature(Args, Features, options::OPT_faltivec,
  1403. options::OPT_fno_altivec, "altivec");
  1404. }
  1405. ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
  1406. ppc::FloatABI ABI = ppc::FloatABI::Invalid;
  1407. if (Arg *A =
  1408. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1409. options::OPT_mfloat_abi_EQ)) {
  1410. if (A->getOption().matches(options::OPT_msoft_float))
  1411. ABI = ppc::FloatABI::Soft;
  1412. else if (A->getOption().matches(options::OPT_mhard_float))
  1413. ABI = ppc::FloatABI::Hard;
  1414. else {
  1415. ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
  1416. .Case("soft", ppc::FloatABI::Soft)
  1417. .Case("hard", ppc::FloatABI::Hard)
  1418. .Default(ppc::FloatABI::Invalid);
  1419. if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1420. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1421. ABI = ppc::FloatABI::Hard;
  1422. }
  1423. }
  1424. }
  1425. // If unspecified, choose the default based on the platform.
  1426. if (ABI == ppc::FloatABI::Invalid) {
  1427. ABI = ppc::FloatABI::Hard;
  1428. }
  1429. return ABI;
  1430. }
  1431. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1432. ArgStringList &CmdArgs) const {
  1433. // Select the ABI to use.
  1434. const char *ABIName = nullptr;
  1435. if (getToolChain().getTriple().isOSLinux())
  1436. switch (getToolChain().getArch()) {
  1437. case llvm::Triple::ppc64: {
  1438. // When targeting a processor that supports QPX, or if QPX is
  1439. // specifically enabled, default to using the ABI that supports QPX (so
  1440. // long as it is not specifically disabled).
  1441. bool HasQPX = false;
  1442. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1443. HasQPX = A->getValue() == StringRef("a2q");
  1444. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1445. if (HasQPX) {
  1446. ABIName = "elfv1-qpx";
  1447. break;
  1448. }
  1449. ABIName = "elfv1";
  1450. break;
  1451. }
  1452. case llvm::Triple::ppc64le:
  1453. ABIName = "elfv2";
  1454. break;
  1455. default:
  1456. break;
  1457. }
  1458. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1459. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1460. // the option if given as we don't have backend support for any targets
  1461. // that don't use the altivec abi.
  1462. if (StringRef(A->getValue()) != "altivec")
  1463. ABIName = A->getValue();
  1464. ppc::FloatABI FloatABI =
  1465. ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
  1466. if (FloatABI == ppc::FloatABI::Soft) {
  1467. // Floating point operations and argument passing are soft.
  1468. CmdArgs.push_back("-msoft-float");
  1469. CmdArgs.push_back("-mfloat-abi");
  1470. CmdArgs.push_back("soft");
  1471. } else {
  1472. // Floating point operations and argument passing are hard.
  1473. assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
  1474. CmdArgs.push_back("-mfloat-abi");
  1475. CmdArgs.push_back("hard");
  1476. }
  1477. if (ABIName) {
  1478. CmdArgs.push_back("-target-abi");
  1479. CmdArgs.push_back(ABIName);
  1480. }
  1481. }
  1482. bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  1483. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  1484. return A && (A->getValue() == StringRef(Value));
  1485. }
  1486. /// Get the (LLVM) name of the R600 gpu we are targeting.
  1487. static std::string getR600TargetGPU(const ArgList &Args) {
  1488. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1489. const char *GPUName = A->getValue();
  1490. return llvm::StringSwitch<const char *>(GPUName)
  1491. .Cases("rv630", "rv635", "r600")
  1492. .Cases("rv610", "rv620", "rs780", "rs880")
  1493. .Case("rv740", "rv770")
  1494. .Case("palm", "cedar")
  1495. .Cases("sumo", "sumo2", "sumo")
  1496. .Case("hemlock", "cypress")
  1497. .Case("aruba", "cayman")
  1498. .Default(GPUName);
  1499. }
  1500. return "";
  1501. }
  1502. static std::string getLanaiTargetCPU(const ArgList &Args) {
  1503. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1504. return A->getValue();
  1505. }
  1506. return "";
  1507. }
  1508. sparc::FloatABI sparc::getSparcFloatABI(const Driver &D,
  1509. const ArgList &Args) {
  1510. sparc::FloatABI ABI = sparc::FloatABI::Invalid;
  1511. if (Arg *A =
  1512. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1513. options::OPT_mfloat_abi_EQ)) {
  1514. if (A->getOption().matches(options::OPT_msoft_float))
  1515. ABI = sparc::FloatABI::Soft;
  1516. else if (A->getOption().matches(options::OPT_mhard_float))
  1517. ABI = sparc::FloatABI::Hard;
  1518. else {
  1519. ABI = llvm::StringSwitch<sparc::FloatABI>(A->getValue())
  1520. .Case("soft", sparc::FloatABI::Soft)
  1521. .Case("hard", sparc::FloatABI::Hard)
  1522. .Default(sparc::FloatABI::Invalid);
  1523. if (ABI == sparc::FloatABI::Invalid &&
  1524. !StringRef(A->getValue()).empty()) {
  1525. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1526. ABI = sparc::FloatABI::Hard;
  1527. }
  1528. }
  1529. }
  1530. // If unspecified, choose the default based on the platform.
  1531. // Only the hard-float ABI on Sparc is standardized, and it is the
  1532. // default. GCC also supports a nonstandard soft-float ABI mode, also
  1533. // implemented in LLVM. However as this is not standard we set the default
  1534. // to be hard-float.
  1535. if (ABI == sparc::FloatABI::Invalid) {
  1536. ABI = sparc::FloatABI::Hard;
  1537. }
  1538. return ABI;
  1539. }
  1540. static void getSparcTargetFeatures(const Driver &D, const ArgList &Args,
  1541. std::vector<const char *> &Features) {
  1542. sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
  1543. if (FloatABI == sparc::FloatABI::Soft)
  1544. Features.push_back("+soft-float");
  1545. }
  1546. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1547. ArgStringList &CmdArgs) const {
  1548. //const Driver &D = getToolChain().getDriver();
  1549. std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
  1550. sparc::FloatABI FloatABI =
  1551. sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
  1552. if (FloatABI == sparc::FloatABI::Soft) {
  1553. // Floating point operations and argument passing are soft.
  1554. CmdArgs.push_back("-msoft-float");
  1555. CmdArgs.push_back("-mfloat-abi");
  1556. CmdArgs.push_back("soft");
  1557. } else {
  1558. // Floating point operations and argument passing are hard.
  1559. assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
  1560. CmdArgs.push_back("-mfloat-abi");
  1561. CmdArgs.push_back("hard");
  1562. }
  1563. }
  1564. void Clang::AddSystemZTargetArgs(const ArgList &Args,
  1565. ArgStringList &CmdArgs) const {
  1566. if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
  1567. CmdArgs.push_back("-mbackchain");
  1568. }
  1569. static const char *getSystemZTargetCPU(const ArgList &Args) {
  1570. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1571. return A->getValue();
  1572. return "z10";
  1573. }
  1574. static void getSystemZTargetFeatures(const ArgList &Args,
  1575. std::vector<const char *> &Features) {
  1576. // -m(no-)htm overrides use of the transactional-execution facility.
  1577. if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
  1578. if (A->getOption().matches(options::OPT_mhtm))
  1579. Features.push_back("+transactional-execution");
  1580. else
  1581. Features.push_back("-transactional-execution");
  1582. }
  1583. // -m(no-)vx overrides use of the vector facility.
  1584. if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
  1585. if (A->getOption().matches(options::OPT_mvx))
  1586. Features.push_back("+vector");
  1587. else
  1588. Features.push_back("-vector");
  1589. }
  1590. }
  1591. static const char *getX86TargetCPU(const ArgList &Args,
  1592. const llvm::Triple &Triple) {
  1593. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1594. if (StringRef(A->getValue()) != "native") {
  1595. if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
  1596. return "core-avx2";
  1597. return A->getValue();
  1598. }
  1599. // FIXME: Reject attempts to use -march=native unless the target matches
  1600. // the host.
  1601. //
  1602. // FIXME: We should also incorporate the detected target features for use
  1603. // with -native.
  1604. std::string CPU = llvm::sys::getHostCPUName();
  1605. if (!CPU.empty() && CPU != "generic")
  1606. return Args.MakeArgString(CPU);
  1607. }
  1608. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1609. // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
  1610. StringRef Arch = A->getValue();
  1611. const char *CPU;
  1612. if (Triple.getArch() == llvm::Triple::x86) {
  1613. CPU = llvm::StringSwitch<const char *>(Arch)
  1614. .Case("IA32", "i386")
  1615. .Case("SSE", "pentium3")
  1616. .Case("SSE2", "pentium4")
  1617. .Case("AVX", "sandybridge")
  1618. .Case("AVX2", "haswell")
  1619. .Default(nullptr);
  1620. } else {
  1621. CPU = llvm::StringSwitch<const char *>(Arch)
  1622. .Case("AVX", "sandybridge")
  1623. .Case("AVX2", "haswell")
  1624. .Default(nullptr);
  1625. }
  1626. if (CPU)
  1627. return CPU;
  1628. }
  1629. // Select the default CPU if none was given (or detection failed).
  1630. if (Triple.getArch() != llvm::Triple::x86_64 &&
  1631. Triple.getArch() != llvm::Triple::x86)
  1632. return nullptr; // This routine is only handling x86 targets.
  1633. bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
  1634. // FIXME: Need target hooks.
  1635. if (Triple.isOSDarwin()) {
  1636. if (Triple.getArchName() == "x86_64h")
  1637. return "core-avx2";
  1638. return Is64Bit ? "core2" : "yonah";
  1639. }
  1640. // Set up default CPU name for PS4 compilers.
  1641. if (Triple.isPS4CPU())
  1642. return "btver2";
  1643. // On Android use targets compatible with gcc
  1644. if (Triple.isAndroid())
  1645. return Is64Bit ? "x86-64" : "i686";
  1646. // Everything else goes to x86-64 in 64-bit mode.
  1647. if (Is64Bit)
  1648. return "x86-64";
  1649. switch (Triple.getOS()) {
  1650. case llvm::Triple::FreeBSD:
  1651. case llvm::Triple::NetBSD:
  1652. case llvm::Triple::OpenBSD:
  1653. return "i486";
  1654. case llvm::Triple::Haiku:
  1655. return "i586";
  1656. case llvm::Triple::Bitrig:
  1657. return "i686";
  1658. default:
  1659. // Fallback to p4.
  1660. return "pentium4";
  1661. }
  1662. }
  1663. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  1664. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  1665. // If we have -mcpu=, use that.
  1666. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1667. StringRef CPU = A->getValue();
  1668. #ifdef __wasm__
  1669. // Handle "native" by examining the host. "native" isn't meaningful when
  1670. // cross compiling, so only support this when the host is also WebAssembly.
  1671. if (CPU == "native")
  1672. return llvm::sys::getHostCPUName();
  1673. #endif
  1674. return CPU;
  1675. }
  1676. return "generic";
  1677. }
  1678. static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
  1679. bool FromAs = false) {
  1680. switch (T.getArch()) {
  1681. default:
  1682. return "";
  1683. case llvm::Triple::aarch64:
  1684. case llvm::Triple::aarch64_be:
  1685. return getAArch64TargetCPU(Args);
  1686. case llvm::Triple::arm:
  1687. case llvm::Triple::armeb:
  1688. case llvm::Triple::thumb:
  1689. case llvm::Triple::thumbeb: {
  1690. StringRef MArch, MCPU;
  1691. getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  1692. return arm::getARMTargetCPU(MCPU, MArch, T);
  1693. }
  1694. case llvm::Triple::mips:
  1695. case llvm::Triple::mipsel:
  1696. case llvm::Triple::mips64:
  1697. case llvm::Triple::mips64el: {
  1698. StringRef CPUName;
  1699. StringRef ABIName;
  1700. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  1701. return CPUName;
  1702. }
  1703. case llvm::Triple::nvptx:
  1704. case llvm::Triple::nvptx64:
  1705. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1706. return A->getValue();
  1707. return "";
  1708. case llvm::Triple::ppc:
  1709. case llvm::Triple::ppc64:
  1710. case llvm::Triple::ppc64le: {
  1711. std::string TargetCPUName = getPPCTargetCPU(Args);
  1712. // LLVM may default to generating code for the native CPU,
  1713. // but, like gcc, we default to a more generic option for
  1714. // each architecture. (except on Darwin)
  1715. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  1716. if (T.getArch() == llvm::Triple::ppc64)
  1717. TargetCPUName = "ppc64";
  1718. else if (T.getArch() == llvm::Triple::ppc64le)
  1719. TargetCPUName = "ppc64le";
  1720. else
  1721. TargetCPUName = "ppc";
  1722. }
  1723. return TargetCPUName;
  1724. }
  1725. case llvm::Triple::sparc:
  1726. case llvm::Triple::sparcel:
  1727. case llvm::Triple::sparcv9:
  1728. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1729. return A->getValue();
  1730. return "";
  1731. case llvm::Triple::x86:
  1732. case llvm::Triple::x86_64:
  1733. return getX86TargetCPU(Args, T);
  1734. case llvm::Triple::hexagon:
  1735. return "hexagon" +
  1736. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  1737. case llvm::Triple::lanai:
  1738. return getLanaiTargetCPU(Args);
  1739. case llvm::Triple::systemz:
  1740. return getSystemZTargetCPU(Args);
  1741. case llvm::Triple::r600:
  1742. case llvm::Triple::amdgcn:
  1743. return getR600TargetGPU(Args);
  1744. case llvm::Triple::wasm32:
  1745. case llvm::Triple::wasm64:
  1746. return getWebAssemblyTargetCPU(Args);
  1747. }
  1748. }
  1749. static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  1750. ArgStringList &CmdArgs, bool IsThinLTO) {
  1751. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  1752. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  1753. // forward.
  1754. CmdArgs.push_back("-plugin");
  1755. std::string Plugin =
  1756. ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
  1757. CmdArgs.push_back(Args.MakeArgString(Plugin));
  1758. // Try to pass driver level flags relevant to LTO code generation down to
  1759. // the plugin.
  1760. // Handle flags for selecting CPU variants.
  1761. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  1762. if (!CPU.empty())
  1763. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  1764. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  1765. StringRef OOpt;
  1766. if (A->getOption().matches(options::OPT_O4) ||
  1767. A->getOption().matches(options::OPT_Ofast))
  1768. OOpt = "3";
  1769. else if (A->getOption().matches(options::OPT_O))
  1770. OOpt = A->getValue();
  1771. else if (A->getOption().matches(options::OPT_O0))
  1772. OOpt = "0";
  1773. if (!OOpt.empty())
  1774. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
  1775. }
  1776. if (IsThinLTO)
  1777. CmdArgs.push_back("-plugin-opt=thinlto");
  1778. // If an explicit debugger tuning argument appeared, pass it along.
  1779. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  1780. options::OPT_ggdbN_Group)) {
  1781. if (A->getOption().matches(options::OPT_glldb))
  1782. CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
  1783. else if (A->getOption().matches(options::OPT_gsce))
  1784. CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
  1785. else
  1786. CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
  1787. }
  1788. }
  1789. /// This is a helper function for validating the optional refinement step
  1790. /// parameter in reciprocal argument strings. Return false if there is an error
  1791. /// parsing the refinement step. Otherwise, return true and set the Position
  1792. /// of the refinement step in the input string.
  1793. static bool getRefinementStep(StringRef In, const Driver &D,
  1794. const Arg &A, size_t &Position) {
  1795. const char RefinementStepToken = ':';
  1796. Position = In.find(RefinementStepToken);
  1797. if (Position != StringRef::npos) {
  1798. StringRef Option = A.getOption().getName();
  1799. StringRef RefStep = In.substr(Position + 1);
  1800. // Allow exactly one numeric character for the additional refinement
  1801. // step parameter. This is reasonable for all currently-supported
  1802. // operations and architectures because we would expect that a larger value
  1803. // of refinement steps would cause the estimate "optimization" to
  1804. // under-perform the native operation. Also, if the estimate does not
  1805. // converge quickly, it probably will not ever converge, so further
  1806. // refinement steps will not produce a better answer.
  1807. if (RefStep.size() != 1) {
  1808. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1809. return false;
  1810. }
  1811. char RefStepChar = RefStep[0];
  1812. if (RefStepChar < '0' || RefStepChar > '9') {
  1813. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1814. return false;
  1815. }
  1816. }
  1817. return true;
  1818. }
  1819. /// The -mrecip flag requires processing of many optional parameters.
  1820. static void ParseMRecip(const Driver &D, const ArgList &Args,
  1821. ArgStringList &OutStrings) {
  1822. StringRef DisabledPrefixIn = "!";
  1823. StringRef DisabledPrefixOut = "!";
  1824. StringRef EnabledPrefixOut = "";
  1825. StringRef Out = "-mrecip=";
  1826. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  1827. if (!A)
  1828. return;
  1829. unsigned NumOptions = A->getNumValues();
  1830. if (NumOptions == 0) {
  1831. // No option is the same as "all".
  1832. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  1833. return;
  1834. }
  1835. // Pass through "all", "none", or "default" with an optional refinement step.
  1836. if (NumOptions == 1) {
  1837. StringRef Val = A->getValue(0);
  1838. size_t RefStepLoc;
  1839. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  1840. return;
  1841. StringRef ValBase = Val.slice(0, RefStepLoc);
  1842. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  1843. OutStrings.push_back(Args.MakeArgString(Out + Val));
  1844. return;
  1845. }
  1846. }
  1847. // Each reciprocal type may be enabled or disabled individually.
  1848. // Check each input value for validity, concatenate them all back together,
  1849. // and pass through.
  1850. llvm::StringMap<bool> OptionStrings;
  1851. OptionStrings.insert(std::make_pair("divd", false));
  1852. OptionStrings.insert(std::make_pair("divf", false));
  1853. OptionStrings.insert(std::make_pair("vec-divd", false));
  1854. OptionStrings.insert(std::make_pair("vec-divf", false));
  1855. OptionStrings.insert(std::make_pair("sqrtd", false));
  1856. OptionStrings.insert(std::make_pair("sqrtf", false));
  1857. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  1858. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  1859. for (unsigned i = 0; i != NumOptions; ++i) {
  1860. StringRef Val = A->getValue(i);
  1861. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  1862. // Ignore the disablement token for string matching.
  1863. if (IsDisabled)
  1864. Val = Val.substr(1);
  1865. size_t RefStep;
  1866. if (!getRefinementStep(Val, D, *A, RefStep))
  1867. return;
  1868. StringRef ValBase = Val.slice(0, RefStep);
  1869. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  1870. if (OptionIter == OptionStrings.end()) {
  1871. // Try again specifying float suffix.
  1872. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  1873. if (OptionIter == OptionStrings.end()) {
  1874. // The input name did not match any known option string.
  1875. D.Diag(diag::err_drv_unknown_argument) << Val;
  1876. return;
  1877. }
  1878. // The option was specified without a float or double suffix.
  1879. // Make sure that the double entry was not already specified.
  1880. // The float entry will be checked below.
  1881. if (OptionStrings[ValBase.str() + 'd']) {
  1882. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1883. return;
  1884. }
  1885. }
  1886. if (OptionIter->second == true) {
  1887. // Duplicate option specified.
  1888. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1889. return;
  1890. }
  1891. // Mark the matched option as found. Do not allow duplicate specifiers.
  1892. OptionIter->second = true;
  1893. // If the precision was not specified, also mark the double entry as found.
  1894. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  1895. OptionStrings[ValBase.str() + 'd'] = true;
  1896. // Build the output string.
  1897. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  1898. Out = Args.MakeArgString(Out + Prefix + Val);
  1899. if (i != NumOptions - 1)
  1900. Out = Args.MakeArgString(Out + ",");
  1901. }
  1902. OutStrings.push_back(Args.MakeArgString(Out));
  1903. }
  1904. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1905. const ArgList &Args,
  1906. std::vector<const char *> &Features) {
  1907. // If -march=native, autodetect the feature list.
  1908. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1909. if (StringRef(A->getValue()) == "native") {
  1910. llvm::StringMap<bool> HostFeatures;
  1911. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  1912. for (auto &F : HostFeatures)
  1913. Features.push_back(
  1914. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  1915. }
  1916. }
  1917. if (Triple.getArchName() == "x86_64h") {
  1918. // x86_64h implies quite a few of the more modern subtarget features
  1919. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  1920. Features.push_back("-rdrnd");
  1921. Features.push_back("-aes");
  1922. Features.push_back("-pclmul");
  1923. Features.push_back("-rtm");
  1924. Features.push_back("-hle");
  1925. Features.push_back("-fsgsbase");
  1926. }
  1927. const llvm::Triple::ArchType ArchType = Triple.getArch();
  1928. // Add features to be compatible with gcc for Android.
  1929. if (Triple.isAndroid()) {
  1930. if (ArchType == llvm::Triple::x86_64) {
  1931. Features.push_back("+sse4.2");
  1932. Features.push_back("+popcnt");
  1933. } else
  1934. Features.push_back("+ssse3");
  1935. }
  1936. // Set features according to the -arch flag on MSVC.
  1937. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1938. StringRef Arch = A->getValue();
  1939. bool ArchUsed = false;
  1940. // First, look for flags that are shared in x86 and x86-64.
  1941. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  1942. if (Arch == "AVX" || Arch == "AVX2") {
  1943. ArchUsed = true;
  1944. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1945. }
  1946. }
  1947. // Then, look for x86-specific flags.
  1948. if (ArchType == llvm::Triple::x86) {
  1949. if (Arch == "IA32") {
  1950. ArchUsed = true;
  1951. } else if (Arch == "SSE" || Arch == "SSE2") {
  1952. ArchUsed = true;
  1953. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1954. }
  1955. }
  1956. if (!ArchUsed)
  1957. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  1958. }
  1959. // Now add any that the user explicitly requested on the command line,
  1960. // which may override the defaults.
  1961. handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
  1962. }
  1963. void Clang::AddX86TargetArgs(const ArgList &Args,
  1964. ArgStringList &CmdArgs) const {
  1965. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1966. Args.hasArg(options::OPT_mkernel) ||
  1967. Args.hasArg(options::OPT_fapple_kext))
  1968. CmdArgs.push_back("-disable-red-zone");
  1969. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1970. // that to be overridden with -mno-soft-float.
  1971. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1972. Args.hasArg(options::OPT_fapple_kext));
  1973. if (Arg *A = Args.getLastArg(
  1974. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1975. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1976. const Option &O = A->getOption();
  1977. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1978. O.matches(options::OPT_msoft_float));
  1979. }
  1980. if (NoImplicitFloat)
  1981. CmdArgs.push_back("-no-implicit-float");
  1982. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1983. StringRef Value = A->getValue();
  1984. if (Value == "intel" || Value == "att") {
  1985. CmdArgs.push_back("-mllvm");
  1986. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1987. } else {
  1988. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  1989. << A->getOption().getName() << Value;
  1990. }
  1991. }
  1992. // Set flags to support MCU ABI.
  1993. if (Args.hasArg(options::OPT_miamcu)) {
  1994. CmdArgs.push_back("-mfloat-abi");
  1995. CmdArgs.push_back("soft");
  1996. CmdArgs.push_back("-mstack-alignment=4");
  1997. }
  1998. }
  1999. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  2000. ArgStringList &CmdArgs) const {
  2001. CmdArgs.push_back("-mqdsp6-compat");
  2002. CmdArgs.push_back("-Wreturn-type");
  2003. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  2004. std::string N = llvm::utostr(G.getValue());
  2005. std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
  2006. CmdArgs.push_back("-mllvm");
  2007. CmdArgs.push_back(Args.MakeArgString(Opt));
  2008. }
  2009. if (!Args.hasArg(options::OPT_fno_short_enums))
  2010. CmdArgs.push_back("-fshort-enums");
  2011. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  2012. CmdArgs.push_back("-mllvm");
  2013. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  2014. }
  2015. CmdArgs.push_back("-mllvm");
  2016. CmdArgs.push_back("-machine-sink-split=0");
  2017. }
  2018. void Clang::AddLanaiTargetArgs(const ArgList &Args,
  2019. ArgStringList &CmdArgs) const {
  2020. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  2021. StringRef CPUName = A->getValue();
  2022. CmdArgs.push_back("-target-cpu");
  2023. CmdArgs.push_back(Args.MakeArgString(CPUName));
  2024. }
  2025. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  2026. StringRef Value = A->getValue();
  2027. // Only support mregparm=4 to support old usage. Report error for all other
  2028. // cases.
  2029. int Mregparm;
  2030. if (Value.getAsInteger(10, Mregparm)) {
  2031. if (Mregparm != 4) {
  2032. getToolChain().getDriver().Diag(
  2033. diag::err_drv_unsupported_option_argument)
  2034. << A->getOption().getName() << Value;
  2035. }
  2036. }
  2037. }
  2038. }
  2039. void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
  2040. ArgStringList &CmdArgs) const {
  2041. // Default to "hidden" visibility.
  2042. if (!Args.hasArg(options::OPT_fvisibility_EQ,
  2043. options::OPT_fvisibility_ms_compat)) {
  2044. CmdArgs.push_back("-fvisibility");
  2045. CmdArgs.push_back("hidden");
  2046. }
  2047. }
  2048. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  2049. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  2050. std::vector<const char *> &Features) {
  2051. SmallVector<StringRef, 8> Split;
  2052. text.split(Split, StringRef("+"), -1, false);
  2053. for (StringRef Feature : Split) {
  2054. const char *result = llvm::StringSwitch<const char *>(Feature)
  2055. .Case("fp", "+fp-armv8")
  2056. .Case("simd", "+neon")
  2057. .Case("crc", "+crc")
  2058. .Case("crypto", "+crypto")
  2059. .Case("fp16", "+fullfp16")
  2060. .Case("profile", "+spe")
  2061. .Case("ras", "+ras")
  2062. .Case("nofp", "-fp-armv8")
  2063. .Case("nosimd", "-neon")
  2064. .Case("nocrc", "-crc")
  2065. .Case("nocrypto", "-crypto")
  2066. .Case("nofp16", "-fullfp16")
  2067. .Case("noprofile", "-spe")
  2068. .Case("noras", "-ras")
  2069. .Default(nullptr);
  2070. if (result)
  2071. Features.push_back(result);
  2072. else if (Feature == "neon" || Feature == "noneon")
  2073. D.Diag(diag::err_drv_no_neon_modifier);
  2074. else
  2075. return false;
  2076. }
  2077. return true;
  2078. }
  2079. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  2080. // decode CPU and feature.
  2081. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  2082. std::vector<const char *> &Features) {
  2083. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  2084. CPU = Split.first;
  2085. if (CPU == "cortex-a53" || CPU == "cortex-a57" ||
  2086. CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1" ||
  2087. CPU == "kryo" || CPU == "cortex-a73") {
  2088. Features.push_back("+neon");
  2089. Features.push_back("+crc");
  2090. Features.push_back("+crypto");
  2091. } else if (CPU == "cyclone") {
  2092. Features.push_back("+neon");
  2093. Features.push_back("+crypto");
  2094. } else if (CPU == "generic") {
  2095. Features.push_back("+neon");
  2096. } else {
  2097. return false;
  2098. }
  2099. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  2100. return false;
  2101. return true;
  2102. }
  2103. static bool
  2104. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  2105. const ArgList &Args,
  2106. std::vector<const char *> &Features) {
  2107. std::string MarchLowerCase = March.lower();
  2108. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  2109. if (Split.first == "armv8-a" || Split.first == "armv8a") {
  2110. // ok, no additional features.
  2111. } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
  2112. Features.push_back("+v8.1a");
  2113. } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
  2114. Features.push_back("+v8.2a");
  2115. } else {
  2116. return false;
  2117. }
  2118. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  2119. return false;
  2120. return true;
  2121. }
  2122. static bool
  2123. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2124. const ArgList &Args,
  2125. std::vector<const char *> &Features) {
  2126. StringRef CPU;
  2127. std::string McpuLowerCase = Mcpu.lower();
  2128. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  2129. return false;
  2130. return true;
  2131. }
  2132. static bool
  2133. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  2134. const ArgList &Args,
  2135. std::vector<const char *> &Features) {
  2136. std::string MtuneLowerCase = Mtune.lower();
  2137. // Handle CPU name is 'native'.
  2138. if (MtuneLowerCase == "native")
  2139. MtuneLowerCase = llvm::sys::getHostCPUName();
  2140. if (MtuneLowerCase == "cyclone") {
  2141. Features.push_back("+zcm");
  2142. Features.push_back("+zcz");
  2143. }
  2144. return true;
  2145. }
  2146. static bool
  2147. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  2148. const ArgList &Args,
  2149. std::vector<const char *> &Features) {
  2150. StringRef CPU;
  2151. std::vector<const char *> DecodedFeature;
  2152. std::string McpuLowerCase = Mcpu.lower();
  2153. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  2154. return false;
  2155. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  2156. }
  2157. static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
  2158. std::vector<const char *> &Features) {
  2159. Arg *A;
  2160. bool success = true;
  2161. // Enable NEON by default.
  2162. Features.push_back("+neon");
  2163. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  2164. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  2165. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2166. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2167. else if (Args.hasArg(options::OPT_arch))
  2168. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
  2169. Features);
  2170. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  2171. success =
  2172. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  2173. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  2174. success =
  2175. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  2176. else if (Args.hasArg(options::OPT_arch))
  2177. success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
  2178. Args, Features);
  2179. if (!success)
  2180. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  2181. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  2182. Features.push_back("-fp-armv8");
  2183. Features.push_back("-crypto");
  2184. Features.push_back("-neon");
  2185. }
  2186. // En/disable crc
  2187. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  2188. if (A->getOption().matches(options::OPT_mcrc))
  2189. Features.push_back("+crc");
  2190. else
  2191. Features.push_back("-crc");
  2192. }
  2193. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  2194. options::OPT_munaligned_access))
  2195. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  2196. Features.push_back("+strict-align");
  2197. if (Args.hasArg(options::OPT_ffixed_x18))
  2198. Features.push_back("+reserve-x18");
  2199. }
  2200. static void getHexagonTargetFeatures(const ArgList &Args,
  2201. std::vector<const char *> &Features) {
  2202. bool HasHVX = false, HasHVXD = false;
  2203. // FIXME: This should be able to use handleTargetFeaturesGroup except it is
  2204. // doing dependent option handling here rather than in initFeatureMap or a
  2205. // similar handler.
  2206. for (auto &A : Args) {
  2207. auto &Opt = A->getOption();
  2208. if (Opt.matches(options::OPT_mhexagon_hvx))
  2209. HasHVX = true;
  2210. else if (Opt.matches(options::OPT_mno_hexagon_hvx))
  2211. HasHVXD = HasHVX = false;
  2212. else if (Opt.matches(options::OPT_mhexagon_hvx_double))
  2213. HasHVXD = HasHVX = true;
  2214. else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
  2215. HasHVXD = false;
  2216. else
  2217. continue;
  2218. A->claim();
  2219. }
  2220. Features.push_back(HasHVX ? "+hvx" : "-hvx");
  2221. Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
  2222. }
  2223. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  2224. std::vector<const char *> &Features) {
  2225. handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
  2226. }
  2227. static void getAMDGPUTargetFeatures(const Driver &D, const ArgList &Args,
  2228. std::vector<const char *> &Features) {
  2229. if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi)) {
  2230. StringRef value = dAbi->getValue();
  2231. if (value == "1.0") {
  2232. Features.push_back("+amdgpu-debugger-insert-nops");
  2233. Features.push_back("+amdgpu-debugger-reserve-regs");
  2234. Features.push_back("+amdgpu-debugger-emit-prologue");
  2235. } else {
  2236. D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
  2237. }
  2238. }
  2239. handleTargetFeaturesGroup(
  2240. Args, Features, options::OPT_m_amdgpu_Features_Group);
  2241. }
  2242. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  2243. const ArgList &Args, ArgStringList &CmdArgs,
  2244. bool ForAS) {
  2245. const Driver &D = TC.getDriver();
  2246. std::vector<const char *> Features;
  2247. switch (Triple.getArch()) {
  2248. default:
  2249. break;
  2250. case llvm::Triple::mips:
  2251. case llvm::Triple::mipsel:
  2252. case llvm::Triple::mips64:
  2253. case llvm::Triple::mips64el:
  2254. getMIPSTargetFeatures(D, Triple, Args, Features);
  2255. break;
  2256. case llvm::Triple::arm:
  2257. case llvm::Triple::armeb:
  2258. case llvm::Triple::thumb:
  2259. case llvm::Triple::thumbeb:
  2260. getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
  2261. break;
  2262. case llvm::Triple::ppc:
  2263. case llvm::Triple::ppc64:
  2264. case llvm::Triple::ppc64le:
  2265. getPPCTargetFeatures(D, Triple, Args, Features);
  2266. break;
  2267. case llvm::Triple::systemz:
  2268. getSystemZTargetFeatures(Args, Features);
  2269. break;
  2270. case llvm::Triple::aarch64:
  2271. case llvm::Triple::aarch64_be:
  2272. getAArch64TargetFeatures(D, Args, Features);
  2273. break;
  2274. case llvm::Triple::x86:
  2275. case llvm::Triple::x86_64:
  2276. getX86TargetFeatures(D, Triple, Args, Features);
  2277. break;
  2278. case llvm::Triple::hexagon:
  2279. getHexagonTargetFeatures(Args, Features);
  2280. break;
  2281. case llvm::Triple::wasm32:
  2282. case llvm::Triple::wasm64:
  2283. getWebAssemblyTargetFeatures(Args, Features);
  2284. break;
  2285. case llvm::Triple::sparc:
  2286. case llvm::Triple::sparcel:
  2287. case llvm::Triple::sparcv9:
  2288. getSparcTargetFeatures(D, Args, Features);
  2289. break;
  2290. case llvm::Triple::r600:
  2291. case llvm::Triple::amdgcn:
  2292. getAMDGPUTargetFeatures(D, Args, Features);
  2293. break;
  2294. }
  2295. // Find the last of each feature.
  2296. llvm::StringMap<unsigned> LastOpt;
  2297. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2298. const char *Name = Features[I];
  2299. assert(Name[0] == '-' || Name[0] == '+');
  2300. LastOpt[Name + 1] = I;
  2301. }
  2302. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2303. // If this feature was overridden, ignore it.
  2304. const char *Name = Features[I];
  2305. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
  2306. assert(LastI != LastOpt.end());
  2307. unsigned Last = LastI->second;
  2308. if (Last != I)
  2309. continue;
  2310. CmdArgs.push_back("-target-feature");
  2311. CmdArgs.push_back(Name);
  2312. }
  2313. }
  2314. static bool
  2315. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  2316. const llvm::Triple &Triple) {
  2317. // We use the zero-cost exception tables for Objective-C if the non-fragile
  2318. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  2319. // later.
  2320. if (runtime.isNonFragile())
  2321. return true;
  2322. if (!Triple.isMacOSX())
  2323. return false;
  2324. return (!Triple.isMacOSXVersionLT(10, 5) &&
  2325. (Triple.getArch() == llvm::Triple::x86_64 ||
  2326. Triple.getArch() == llvm::Triple::arm));
  2327. }
  2328. /// Adds exception related arguments to the driver command arguments. There's a
  2329. /// master flag, -fexceptions and also language specific flags to enable/disable
  2330. /// C++ and Objective-C exceptions. This makes it possible to for example
  2331. /// disable C++ exceptions but enable Objective-C exceptions.
  2332. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  2333. const ToolChain &TC, bool KernelOrKext,
  2334. const ObjCRuntime &objcRuntime,
  2335. ArgStringList &CmdArgs) {
  2336. const Driver &D = TC.getDriver();
  2337. const llvm::Triple &Triple = TC.getTriple();
  2338. if (KernelOrKext) {
  2339. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  2340. // arguments now to avoid warnings about unused arguments.
  2341. Args.ClaimAllArgs(options::OPT_fexceptions);
  2342. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  2343. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  2344. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  2345. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  2346. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  2347. return;
  2348. }
  2349. // See if the user explicitly enabled exceptions.
  2350. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2351. false);
  2352. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  2353. // is not necessarily sensible, but follows GCC.
  2354. if (types::isObjC(InputType) &&
  2355. Args.hasFlag(options::OPT_fobjc_exceptions,
  2356. options::OPT_fno_objc_exceptions, true)) {
  2357. CmdArgs.push_back("-fobjc-exceptions");
  2358. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  2359. }
  2360. if (types::isCXX(InputType)) {
  2361. // Disable C++ EH by default on XCore and PS4.
  2362. bool CXXExceptionsEnabled =
  2363. Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
  2364. Arg *ExceptionArg = Args.getLastArg(
  2365. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  2366. options::OPT_fexceptions, options::OPT_fno_exceptions);
  2367. if (ExceptionArg)
  2368. CXXExceptionsEnabled =
  2369. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  2370. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  2371. if (CXXExceptionsEnabled) {
  2372. if (Triple.isPS4CPU()) {
  2373. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  2374. assert(ExceptionArg &&
  2375. "On the PS4 exceptions should only be enabled if passing "
  2376. "an argument");
  2377. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  2378. const Arg *RTTIArg = TC.getRTTIArg();
  2379. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  2380. D.Diag(diag::err_drv_argument_not_allowed_with)
  2381. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2382. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2383. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2384. } else
  2385. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2386. CmdArgs.push_back("-fcxx-exceptions");
  2387. EH = true;
  2388. }
  2389. }
  2390. if (EH)
  2391. CmdArgs.push_back("-fexceptions");
  2392. }
  2393. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2394. bool Default = true;
  2395. if (TC.getTriple().isOSDarwin()) {
  2396. // The native darwin assembler doesn't support the linker_option directives,
  2397. // so we disable them if we think the .s file will be passed to it.
  2398. Default = TC.useIntegratedAs();
  2399. }
  2400. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2401. Default);
  2402. }
  2403. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2404. const ToolChain &TC) {
  2405. bool UseDwarfDirectory =
  2406. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2407. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2408. return !UseDwarfDirectory;
  2409. }
  2410. /// \brief Check whether the given input tree contains any compilation actions.
  2411. static bool ContainsCompileAction(const Action *A) {
  2412. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2413. return true;
  2414. for (const auto &AI : A->inputs())
  2415. if (ContainsCompileAction(AI))
  2416. return true;
  2417. return false;
  2418. }
  2419. /// \brief Check if -relax-all should be passed to the internal assembler.
  2420. /// This is done by default when compiling non-assembler source with -O0.
  2421. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2422. bool RelaxDefault = true;
  2423. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2424. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2425. if (RelaxDefault) {
  2426. RelaxDefault = false;
  2427. for (const auto &Act : C.getActions()) {
  2428. if (ContainsCompileAction(Act)) {
  2429. RelaxDefault = true;
  2430. break;
  2431. }
  2432. }
  2433. }
  2434. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2435. RelaxDefault);
  2436. }
  2437. // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
  2438. // to the corresponding DebugInfoKind.
  2439. static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
  2440. assert(A.getOption().matches(options::OPT_gN_Group) &&
  2441. "Not a -g option that specifies a debug-info level");
  2442. if (A.getOption().matches(options::OPT_g0) ||
  2443. A.getOption().matches(options::OPT_ggdb0))
  2444. return codegenoptions::NoDebugInfo;
  2445. if (A.getOption().matches(options::OPT_gline_tables_only) ||
  2446. A.getOption().matches(options::OPT_ggdb1))
  2447. return codegenoptions::DebugLineTablesOnly;
  2448. return codegenoptions::LimitedDebugInfo;
  2449. }
  2450. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2451. // on mismatch. The StringRef input (rather than an Arg) allows
  2452. // for use by the "-Xassembler" option parser.
  2453. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2454. return llvm::StringSwitch<unsigned>(ArgValue)
  2455. .Case("-gdwarf-2", 2)
  2456. .Case("-gdwarf-3", 3)
  2457. .Case("-gdwarf-4", 4)
  2458. .Case("-gdwarf-5", 5)
  2459. .Default(0);
  2460. }
  2461. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2462. codegenoptions::DebugInfoKind DebugInfoKind,
  2463. unsigned DwarfVersion,
  2464. llvm::DebuggerKind DebuggerTuning) {
  2465. switch (DebugInfoKind) {
  2466. case codegenoptions::DebugLineTablesOnly:
  2467. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2468. break;
  2469. case codegenoptions::LimitedDebugInfo:
  2470. CmdArgs.push_back("-debug-info-kind=limited");
  2471. break;
  2472. case codegenoptions::FullDebugInfo:
  2473. CmdArgs.push_back("-debug-info-kind=standalone");
  2474. break;
  2475. default:
  2476. break;
  2477. }
  2478. if (DwarfVersion > 0)
  2479. CmdArgs.push_back(
  2480. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2481. switch (DebuggerTuning) {
  2482. case llvm::DebuggerKind::GDB:
  2483. CmdArgs.push_back("-debugger-tuning=gdb");
  2484. break;
  2485. case llvm::DebuggerKind::LLDB:
  2486. CmdArgs.push_back("-debugger-tuning=lldb");
  2487. break;
  2488. case llvm::DebuggerKind::SCE:
  2489. CmdArgs.push_back("-debugger-tuning=sce");
  2490. break;
  2491. default:
  2492. break;
  2493. }
  2494. }
  2495. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2496. const ArgList &Args,
  2497. ArgStringList &CmdArgs,
  2498. const Driver &D) {
  2499. if (UseRelaxAll(C, Args))
  2500. CmdArgs.push_back("-mrelax-all");
  2501. // Only default to -mincremental-linker-compatible if we think we are
  2502. // targeting the MSVC linker.
  2503. bool DefaultIncrementalLinkerCompatible =
  2504. C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
  2505. if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
  2506. options::OPT_mno_incremental_linker_compatible,
  2507. DefaultIncrementalLinkerCompatible))
  2508. CmdArgs.push_back("-mincremental-linker-compatible");
  2509. // When passing -I arguments to the assembler we sometimes need to
  2510. // unconditionally take the next argument. For example, when parsing
  2511. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2512. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2513. // arg after parsing the '-I' arg.
  2514. bool TakeNextArg = false;
  2515. // When using an integrated assembler, translate -Wa, and -Xassembler
  2516. // options.
  2517. bool CompressDebugSections = false;
  2518. bool UseRelaxRelocations = false;
  2519. const char *MipsTargetFeature = nullptr;
  2520. for (const Arg *A :
  2521. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2522. A->claim();
  2523. for (StringRef Value : A->getValues()) {
  2524. if (TakeNextArg) {
  2525. CmdArgs.push_back(Value.data());
  2526. TakeNextArg = false;
  2527. continue;
  2528. }
  2529. switch (C.getDefaultToolChain().getArch()) {
  2530. default:
  2531. break;
  2532. case llvm::Triple::mips:
  2533. case llvm::Triple::mipsel:
  2534. case llvm::Triple::mips64:
  2535. case llvm::Triple::mips64el:
  2536. if (Value == "--trap") {
  2537. CmdArgs.push_back("-target-feature");
  2538. CmdArgs.push_back("+use-tcc-in-div");
  2539. continue;
  2540. }
  2541. if (Value == "--break") {
  2542. CmdArgs.push_back("-target-feature");
  2543. CmdArgs.push_back("-use-tcc-in-div");
  2544. continue;
  2545. }
  2546. if (Value.startswith("-msoft-float")) {
  2547. CmdArgs.push_back("-target-feature");
  2548. CmdArgs.push_back("+soft-float");
  2549. continue;
  2550. }
  2551. if (Value.startswith("-mhard-float")) {
  2552. CmdArgs.push_back("-target-feature");
  2553. CmdArgs.push_back("-soft-float");
  2554. continue;
  2555. }
  2556. MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
  2557. .Case("-mips1", "+mips1")
  2558. .Case("-mips2", "+mips2")
  2559. .Case("-mips3", "+mips3")
  2560. .Case("-mips4", "+mips4")
  2561. .Case("-mips5", "+mips5")
  2562. .Case("-mips32", "+mips32")
  2563. .Case("-mips32r2", "+mips32r2")
  2564. .Case("-mips32r3", "+mips32r3")
  2565. .Case("-mips32r5", "+mips32r5")
  2566. .Case("-mips32r6", "+mips32r6")
  2567. .Case("-mips64", "+mips64")
  2568. .Case("-mips64r2", "+mips64r2")
  2569. .Case("-mips64r3", "+mips64r3")
  2570. .Case("-mips64r5", "+mips64r5")
  2571. .Case("-mips64r6", "+mips64r6")
  2572. .Default(nullptr);
  2573. if (MipsTargetFeature)
  2574. continue;
  2575. }
  2576. if (Value == "-force_cpusubtype_ALL") {
  2577. // Do nothing, this is the default and we don't support anything else.
  2578. } else if (Value == "-L") {
  2579. CmdArgs.push_back("-msave-temp-labels");
  2580. } else if (Value == "--fatal-warnings") {
  2581. CmdArgs.push_back("-massembler-fatal-warnings");
  2582. } else if (Value == "--noexecstack") {
  2583. CmdArgs.push_back("-mnoexecstack");
  2584. } else if (Value == "-compress-debug-sections" ||
  2585. Value == "--compress-debug-sections") {
  2586. CompressDebugSections = true;
  2587. } else if (Value == "-nocompress-debug-sections" ||
  2588. Value == "--nocompress-debug-sections") {
  2589. CompressDebugSections = false;
  2590. } else if (Value == "-mrelax-relocations=yes" ||
  2591. Value == "--mrelax-relocations=yes") {
  2592. UseRelaxRelocations = true;
  2593. } else if (Value == "-mrelax-relocations=no" ||
  2594. Value == "--mrelax-relocations=no") {
  2595. UseRelaxRelocations = false;
  2596. } else if (Value.startswith("-I")) {
  2597. CmdArgs.push_back(Value.data());
  2598. // We need to consume the next argument if the current arg is a plain
  2599. // -I. The next arg will be the include directory.
  2600. if (Value == "-I")
  2601. TakeNextArg = true;
  2602. } else if (Value.startswith("-gdwarf-")) {
  2603. // "-gdwarf-N" options are not cc1as options.
  2604. unsigned DwarfVersion = DwarfVersionNum(Value);
  2605. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2606. CmdArgs.push_back(Value.data());
  2607. } else {
  2608. RenderDebugEnablingArgs(Args, CmdArgs,
  2609. codegenoptions::LimitedDebugInfo,
  2610. DwarfVersion, llvm::DebuggerKind::Default);
  2611. }
  2612. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2613. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2614. // Do nothing, we'll validate it later.
  2615. } else {
  2616. D.Diag(diag::err_drv_unsupported_option_argument)
  2617. << A->getOption().getName() << Value;
  2618. }
  2619. }
  2620. }
  2621. if (CompressDebugSections) {
  2622. if (llvm::zlib::isAvailable())
  2623. CmdArgs.push_back("-compress-debug-sections");
  2624. else
  2625. D.Diag(diag::warn_debug_compression_unavailable);
  2626. }
  2627. if (UseRelaxRelocations)
  2628. CmdArgs.push_back("--mrelax-relocations");
  2629. if (MipsTargetFeature != nullptr) {
  2630. CmdArgs.push_back("-target-feature");
  2631. CmdArgs.push_back(MipsTargetFeature);
  2632. }
  2633. }
  2634. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2635. // FIXME: Make sure we can also emit shared objects if they're requested
  2636. // and available, check for possible errors, etc.
  2637. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2638. ArgStringList &CmdArgs) {
  2639. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  2640. }
  2641. namespace {
  2642. enum OpenMPRuntimeKind {
  2643. /// An unknown OpenMP runtime. We can't generate effective OpenMP code
  2644. /// without knowing what runtime to target.
  2645. OMPRT_Unknown,
  2646. /// The LLVM OpenMP runtime. When completed and integrated, this will become
  2647. /// the default for Clang.
  2648. OMPRT_OMP,
  2649. /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
  2650. /// this runtime but can swallow the pragmas, and find and link against the
  2651. /// runtime library itself.
  2652. OMPRT_GOMP,
  2653. /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
  2654. /// OpenMP runtime. We support this mode for users with existing dependencies
  2655. /// on this runtime library name.
  2656. OMPRT_IOMP5
  2657. };
  2658. }
  2659. /// Compute the desired OpenMP runtime from the flag provided.
  2660. static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
  2661. const ArgList &Args) {
  2662. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  2663. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  2664. if (A)
  2665. RuntimeName = A->getValue();
  2666. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  2667. .Case("libomp", OMPRT_OMP)
  2668. .Case("libgomp", OMPRT_GOMP)
  2669. .Case("libiomp5", OMPRT_IOMP5)
  2670. .Default(OMPRT_Unknown);
  2671. if (RT == OMPRT_Unknown) {
  2672. if (A)
  2673. TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2674. << A->getOption().getName() << A->getValue();
  2675. else
  2676. // FIXME: We could use a nicer diagnostic here.
  2677. TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  2678. }
  2679. return RT;
  2680. }
  2681. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2682. const ArgList &Args) {
  2683. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2684. options::OPT_fno_openmp, false))
  2685. return;
  2686. switch (getOpenMPRuntime(TC, Args)) {
  2687. case OMPRT_OMP:
  2688. CmdArgs.push_back("-lomp");
  2689. break;
  2690. case OMPRT_GOMP:
  2691. CmdArgs.push_back("-lgomp");
  2692. break;
  2693. case OMPRT_IOMP5:
  2694. CmdArgs.push_back("-liomp5");
  2695. break;
  2696. case OMPRT_Unknown:
  2697. // Already diagnosed.
  2698. break;
  2699. }
  2700. }
  2701. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2702. ArgStringList &CmdArgs, StringRef Sanitizer,
  2703. bool IsShared, bool IsWhole) {
  2704. // Wrap any static runtimes that must be forced into executable in
  2705. // whole-archive.
  2706. if (IsWhole) CmdArgs.push_back("-whole-archive");
  2707. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
  2708. if (IsWhole) CmdArgs.push_back("-no-whole-archive");
  2709. }
  2710. // Tries to use a file with the list of dynamic symbols that need to be exported
  2711. // from the runtime library. Returns true if the file was found.
  2712. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2713. ArgStringList &CmdArgs,
  2714. StringRef Sanitizer) {
  2715. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2716. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2717. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2718. return true;
  2719. }
  2720. return false;
  2721. }
  2722. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2723. ArgStringList &CmdArgs) {
  2724. // Force linking against the system libraries sanitizers depends on
  2725. // (see PR15823 why this is necessary).
  2726. CmdArgs.push_back("--no-as-needed");
  2727. CmdArgs.push_back("-lpthread");
  2728. CmdArgs.push_back("-lrt");
  2729. CmdArgs.push_back("-lm");
  2730. // There's no libdl on FreeBSD.
  2731. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  2732. CmdArgs.push_back("-ldl");
  2733. }
  2734. static void
  2735. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2736. SmallVectorImpl<StringRef> &SharedRuntimes,
  2737. SmallVectorImpl<StringRef> &StaticRuntimes,
  2738. SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
  2739. SmallVectorImpl<StringRef> &HelperStaticRuntimes,
  2740. SmallVectorImpl<StringRef> &RequiredSymbols) {
  2741. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2742. // Collect shared runtimes.
  2743. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2744. SharedRuntimes.push_back("asan");
  2745. }
  2746. // The stats_client library is also statically linked into DSOs.
  2747. if (SanArgs.needsStatsRt())
  2748. StaticRuntimes.push_back("stats_client");
  2749. // Collect static runtimes.
  2750. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2751. // Don't link static runtimes into DSOs or if compiling for Android.
  2752. return;
  2753. }
  2754. if (SanArgs.needsAsanRt()) {
  2755. if (SanArgs.needsSharedAsanRt()) {
  2756. HelperStaticRuntimes.push_back("asan-preinit");
  2757. } else {
  2758. StaticRuntimes.push_back("asan");
  2759. if (SanArgs.linkCXXRuntimes())
  2760. StaticRuntimes.push_back("asan_cxx");
  2761. }
  2762. }
  2763. if (SanArgs.needsDfsanRt())
  2764. StaticRuntimes.push_back("dfsan");
  2765. if (SanArgs.needsLsanRt())
  2766. StaticRuntimes.push_back("lsan");
  2767. if (SanArgs.needsMsanRt()) {
  2768. StaticRuntimes.push_back("msan");
  2769. if (SanArgs.linkCXXRuntimes())
  2770. StaticRuntimes.push_back("msan_cxx");
  2771. }
  2772. if (SanArgs.needsTsanRt()) {
  2773. StaticRuntimes.push_back("tsan");
  2774. if (SanArgs.linkCXXRuntimes())
  2775. StaticRuntimes.push_back("tsan_cxx");
  2776. }
  2777. if (SanArgs.needsUbsanRt()) {
  2778. StaticRuntimes.push_back("ubsan_standalone");
  2779. if (SanArgs.linkCXXRuntimes())
  2780. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2781. }
  2782. if (SanArgs.needsSafeStackRt())
  2783. StaticRuntimes.push_back("safestack");
  2784. if (SanArgs.needsCfiRt())
  2785. StaticRuntimes.push_back("cfi");
  2786. if (SanArgs.needsCfiDiagRt()) {
  2787. StaticRuntimes.push_back("cfi_diag");
  2788. if (SanArgs.linkCXXRuntimes())
  2789. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2790. }
  2791. if (SanArgs.needsStatsRt()) {
  2792. NonWholeStaticRuntimes.push_back("stats");
  2793. RequiredSymbols.push_back("__sanitizer_stats_register");
  2794. }
  2795. if (SanArgs.needsEsanRt())
  2796. StaticRuntimes.push_back("esan");
  2797. }
  2798. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  2799. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  2800. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2801. ArgStringList &CmdArgs) {
  2802. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  2803. NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
  2804. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  2805. NonWholeStaticRuntimes, HelperStaticRuntimes,
  2806. RequiredSymbols);
  2807. for (auto RT : SharedRuntimes)
  2808. addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
  2809. for (auto RT : HelperStaticRuntimes)
  2810. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2811. bool AddExportDynamic = false;
  2812. for (auto RT : StaticRuntimes) {
  2813. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2814. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2815. }
  2816. for (auto RT : NonWholeStaticRuntimes) {
  2817. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
  2818. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2819. }
  2820. for (auto S : RequiredSymbols) {
  2821. CmdArgs.push_back("-u");
  2822. CmdArgs.push_back(Args.MakeArgString(S));
  2823. }
  2824. // If there is a static runtime with no dynamic list, force all the symbols
  2825. // to be dynamic to be sure we export sanitizer interface functions.
  2826. if (AddExportDynamic)
  2827. CmdArgs.push_back("-export-dynamic");
  2828. return !StaticRuntimes.empty();
  2829. }
  2830. static bool areOptimizationsEnabled(const ArgList &Args) {
  2831. // Find the last -O arg and see if it is non-zero.
  2832. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2833. return !A->getOption().matches(options::OPT_O0);
  2834. // Defaults to -O0.
  2835. return false;
  2836. }
  2837. static bool shouldUseFramePointerForTarget(const ArgList &Args,
  2838. const llvm::Triple &Triple) {
  2839. switch (Triple.getArch()) {
  2840. case llvm::Triple::xcore:
  2841. case llvm::Triple::wasm32:
  2842. case llvm::Triple::wasm64:
  2843. // XCore never wants frame pointers, regardless of OS.
  2844. // WebAssembly never wants frame pointers.
  2845. return false;
  2846. default:
  2847. break;
  2848. }
  2849. if (Triple.isOSLinux()) {
  2850. switch (Triple.getArch()) {
  2851. // Don't use a frame pointer on linux if optimizing for certain targets.
  2852. case llvm::Triple::mips64:
  2853. case llvm::Triple::mips64el:
  2854. case llvm::Triple::mips:
  2855. case llvm::Triple::mipsel:
  2856. case llvm::Triple::systemz:
  2857. case llvm::Triple::x86:
  2858. case llvm::Triple::x86_64:
  2859. return !areOptimizationsEnabled(Args);
  2860. default:
  2861. return true;
  2862. }
  2863. }
  2864. if (Triple.isOSWindows()) {
  2865. switch (Triple.getArch()) {
  2866. case llvm::Triple::x86:
  2867. return !areOptimizationsEnabled(Args);
  2868. case llvm::Triple::x86_64:
  2869. return Triple.isOSBinFormatMachO();
  2870. case llvm::Triple::arm:
  2871. case llvm::Triple::thumb:
  2872. // Windows on ARM builds with FPO disabled to aid fast stack walking
  2873. return true;
  2874. default:
  2875. // All other supported Windows ISAs use xdata unwind information, so frame
  2876. // pointers are not generally useful.
  2877. return false;
  2878. }
  2879. }
  2880. return true;
  2881. }
  2882. static bool shouldUseFramePointer(const ArgList &Args,
  2883. const llvm::Triple &Triple) {
  2884. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  2885. options::OPT_fomit_frame_pointer))
  2886. return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  2887. if (Args.hasArg(options::OPT_pg))
  2888. return true;
  2889. return shouldUseFramePointerForTarget(Args, Triple);
  2890. }
  2891. static bool shouldUseLeafFramePointer(const ArgList &Args,
  2892. const llvm::Triple &Triple) {
  2893. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  2894. options::OPT_momit_leaf_frame_pointer))
  2895. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
  2896. if (Args.hasArg(options::OPT_pg))
  2897. return true;
  2898. if (Triple.isPS4CPU())
  2899. return false;
  2900. return shouldUseFramePointerForTarget(Args, Triple);
  2901. }
  2902. /// Add a CC1 option to specify the debug compilation directory.
  2903. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  2904. SmallString<128> cwd;
  2905. if (!llvm::sys::fs::current_path(cwd)) {
  2906. CmdArgs.push_back("-fdebug-compilation-dir");
  2907. CmdArgs.push_back(Args.MakeArgString(cwd));
  2908. }
  2909. }
  2910. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  2911. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  2912. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  2913. SmallString<128> T(FinalOutput->getValue());
  2914. llvm::sys::path::replace_extension(T, "dwo");
  2915. return Args.MakeArgString(T);
  2916. } else {
  2917. // Use the compilation dir.
  2918. SmallString<128> T(
  2919. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  2920. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  2921. llvm::sys::path::replace_extension(F, "dwo");
  2922. T += F;
  2923. return Args.MakeArgString(F);
  2924. }
  2925. }
  2926. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  2927. const JobAction &JA, const ArgList &Args,
  2928. const InputInfo &Output, const char *OutFile) {
  2929. ArgStringList ExtractArgs;
  2930. ExtractArgs.push_back("--extract-dwo");
  2931. ArgStringList StripArgs;
  2932. StripArgs.push_back("--strip-dwo");
  2933. // Grabbing the output of the earlier compile step.
  2934. StripArgs.push_back(Output.getFilename());
  2935. ExtractArgs.push_back(Output.getFilename());
  2936. ExtractArgs.push_back(OutFile);
  2937. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  2938. InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
  2939. // First extract the dwo sections.
  2940. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  2941. // Then remove them from the original .o file.
  2942. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  2943. }
  2944. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  2945. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  2946. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  2947. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  2948. if (A->getOption().matches(options::OPT_O4) ||
  2949. A->getOption().matches(options::OPT_Ofast))
  2950. return true;
  2951. if (A->getOption().matches(options::OPT_O0))
  2952. return false;
  2953. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  2954. // Vectorize -Os.
  2955. StringRef S(A->getValue());
  2956. if (S == "s")
  2957. return true;
  2958. // Don't vectorize -Oz, unless it's the slp vectorizer.
  2959. if (S == "z")
  2960. return isSlpVec;
  2961. unsigned OptLevel = 0;
  2962. if (S.getAsInteger(10, OptLevel))
  2963. return false;
  2964. return OptLevel > 1;
  2965. }
  2966. return false;
  2967. }
  2968. /// Add -x lang to \p CmdArgs for \p Input.
  2969. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  2970. ArgStringList &CmdArgs) {
  2971. // When using -verify-pch, we don't want to provide the type
  2972. // 'precompiled-header' if it was inferred from the file extension
  2973. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  2974. return;
  2975. CmdArgs.push_back("-x");
  2976. if (Args.hasArg(options::OPT_rewrite_objc))
  2977. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  2978. else
  2979. CmdArgs.push_back(types::getTypeName(Input.getType()));
  2980. }
  2981. static VersionTuple getMSCompatibilityVersion(unsigned Version) {
  2982. if (Version < 100)
  2983. return VersionTuple(Version);
  2984. if (Version < 10000)
  2985. return VersionTuple(Version / 100, Version % 100);
  2986. unsigned Build = 0, Factor = 1;
  2987. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  2988. Build = Build + (Version % 10) * Factor;
  2989. return VersionTuple(Version / 100, Version % 100, Build);
  2990. }
  2991. // Claim options we don't want to warn if they are unused. We do this for
  2992. // options that build systems might add but are unused when assembling or only
  2993. // running the preprocessor for example.
  2994. static void claimNoWarnArgs(const ArgList &Args) {
  2995. // Don't warn about unused -f(no-)?lto. This can happen when we're
  2996. // preprocessing, precompiling or assembling.
  2997. Args.ClaimAllArgs(options::OPT_flto_EQ);
  2998. Args.ClaimAllArgs(options::OPT_flto);
  2999. Args.ClaimAllArgs(options::OPT_fno_lto);
  3000. }
  3001. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  3002. #ifdef LLVM_ON_UNIX
  3003. const char *Username = getenv("LOGNAME");
  3004. #else
  3005. const char *Username = getenv("USERNAME");
  3006. #endif
  3007. if (Username) {
  3008. // Validate that LoginName can be used in a path, and get its length.
  3009. size_t Len = 0;
  3010. for (const char *P = Username; *P; ++P, ++Len) {
  3011. if (!isAlphanumeric(*P) && *P != '_') {
  3012. Username = nullptr;
  3013. break;
  3014. }
  3015. }
  3016. if (Username && Len > 0) {
  3017. Result.append(Username, Username + Len);
  3018. return;
  3019. }
  3020. }
  3021. // Fallback to user id.
  3022. #ifdef LLVM_ON_UNIX
  3023. std::string UID = llvm::utostr(getuid());
  3024. #else
  3025. // FIXME: Windows seems to have an 'SID' that might work.
  3026. std::string UID = "9999";
  3027. #endif
  3028. Result.append(UID.begin(), UID.end());
  3029. }
  3030. VersionTuple visualstudio::getMSVCVersion(const Driver *D, const ToolChain &TC,
  3031. const llvm::Triple &Triple,
  3032. const llvm::opt::ArgList &Args,
  3033. bool IsWindowsMSVC) {
  3034. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  3035. IsWindowsMSVC) ||
  3036. Args.hasArg(options::OPT_fmsc_version) ||
  3037. Args.hasArg(options::OPT_fms_compatibility_version)) {
  3038. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  3039. const Arg *MSCompatibilityVersion =
  3040. Args.getLastArg(options::OPT_fms_compatibility_version);
  3041. if (MSCVersion && MSCompatibilityVersion) {
  3042. if (D)
  3043. D->Diag(diag::err_drv_argument_not_allowed_with)
  3044. << MSCVersion->getAsString(Args)
  3045. << MSCompatibilityVersion->getAsString(Args);
  3046. return VersionTuple();
  3047. }
  3048. if (MSCompatibilityVersion) {
  3049. VersionTuple MSVT;
  3050. if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
  3051. D->Diag(diag::err_drv_invalid_value)
  3052. << MSCompatibilityVersion->getAsString(Args)
  3053. << MSCompatibilityVersion->getValue();
  3054. return MSVT;
  3055. }
  3056. if (MSCVersion) {
  3057. unsigned Version = 0;
  3058. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
  3059. D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
  3060. << MSCVersion->getValue();
  3061. return getMSCompatibilityVersion(Version);
  3062. }
  3063. unsigned Major, Minor, Micro;
  3064. Triple.getEnvironmentVersion(Major, Minor, Micro);
  3065. if (Major || Minor || Micro)
  3066. return VersionTuple(Major, Minor, Micro);
  3067. if (IsWindowsMSVC) {
  3068. VersionTuple MSVT = TC.getMSVCVersionFromExe();
  3069. if (!MSVT.empty())
  3070. return MSVT;
  3071. // FIXME: Consider bumping this to 19 (MSVC2015) soon.
  3072. return VersionTuple(18);
  3073. }
  3074. }
  3075. return VersionTuple();
  3076. }
  3077. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  3078. const InputInfo &Output, const ArgList &Args,
  3079. ArgStringList &CmdArgs) {
  3080. auto *ProfileGenerateArg = Args.getLastArg(
  3081. options::OPT_fprofile_instr_generate,
  3082. options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
  3083. options::OPT_fprofile_generate_EQ,
  3084. options::OPT_fno_profile_instr_generate);
  3085. if (ProfileGenerateArg &&
  3086. ProfileGenerateArg->getOption().matches(
  3087. options::OPT_fno_profile_instr_generate))
  3088. ProfileGenerateArg = nullptr;
  3089. auto *ProfileUseArg = Args.getLastArg(
  3090. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  3091. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  3092. options::OPT_fno_profile_instr_use);
  3093. if (ProfileUseArg &&
  3094. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  3095. ProfileUseArg = nullptr;
  3096. if (ProfileGenerateArg && ProfileUseArg)
  3097. D.Diag(diag::err_drv_argument_not_allowed_with)
  3098. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  3099. if (ProfileGenerateArg) {
  3100. if (ProfileGenerateArg->getOption().matches(
  3101. options::OPT_fprofile_instr_generate_EQ))
  3102. CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
  3103. ProfileGenerateArg->getValue()));
  3104. else if (ProfileGenerateArg->getOption().matches(
  3105. options::OPT_fprofile_generate_EQ)) {
  3106. SmallString<128> Path(ProfileGenerateArg->getValue());
  3107. llvm::sys::path::append(Path, "default.profraw");
  3108. CmdArgs.push_back(
  3109. Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
  3110. }
  3111. // The default is to use Clang Instrumentation.
  3112. CmdArgs.push_back("-fprofile-instrument=clang");
  3113. }
  3114. if (ProfileUseArg) {
  3115. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  3116. CmdArgs.push_back(Args.MakeArgString(
  3117. Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
  3118. else if ((ProfileUseArg->getOption().matches(
  3119. options::OPT_fprofile_use_EQ) ||
  3120. ProfileUseArg->getOption().matches(
  3121. options::OPT_fprofile_instr_use))) {
  3122. SmallString<128> Path(
  3123. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  3124. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  3125. llvm::sys::path::append(Path, "default.profdata");
  3126. CmdArgs.push_back(
  3127. Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
  3128. }
  3129. }
  3130. if (Args.hasArg(options::OPT_ftest_coverage) ||
  3131. Args.hasArg(options::OPT_coverage))
  3132. CmdArgs.push_back("-femit-coverage-notes");
  3133. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3134. false) ||
  3135. Args.hasArg(options::OPT_coverage))
  3136. CmdArgs.push_back("-femit-coverage-data");
  3137. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3138. options::OPT_fno_coverage_mapping, false) &&
  3139. !ProfileGenerateArg)
  3140. D.Diag(diag::err_drv_argument_only_allowed_with)
  3141. << "-fcoverage-mapping"
  3142. << "-fprofile-instr-generate";
  3143. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  3144. options::OPT_fno_coverage_mapping, false))
  3145. CmdArgs.push_back("-fcoverage-mapping");
  3146. if (C.getArgs().hasArg(options::OPT_c) ||
  3147. C.getArgs().hasArg(options::OPT_S)) {
  3148. if (Output.isFilename()) {
  3149. CmdArgs.push_back("-coverage-file");
  3150. SmallString<128> CoverageFilename;
  3151. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
  3152. CoverageFilename = FinalOutput->getValue();
  3153. } else {
  3154. CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
  3155. }
  3156. if (llvm::sys::path::is_relative(CoverageFilename)) {
  3157. SmallString<128> Pwd;
  3158. if (!llvm::sys::fs::current_path(Pwd)) {
  3159. llvm::sys::path::append(Pwd, CoverageFilename);
  3160. CoverageFilename.swap(Pwd);
  3161. }
  3162. }
  3163. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  3164. }
  3165. }
  3166. }
  3167. static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
  3168. ArgStringList &CmdArgs) {
  3169. if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  3170. false) ||
  3171. Args.hasFlag(options::OPT_fprofile_generate,
  3172. options::OPT_fno_profile_instr_generate, false) ||
  3173. Args.hasFlag(options::OPT_fprofile_generate_EQ,
  3174. options::OPT_fno_profile_instr_generate, false) ||
  3175. Args.hasFlag(options::OPT_fprofile_instr_generate,
  3176. options::OPT_fno_profile_instr_generate, false) ||
  3177. Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
  3178. options::OPT_fno_profile_instr_generate, false) ||
  3179. Args.hasArg(options::OPT_fcreate_profile) ||
  3180. Args.hasArg(options::OPT_coverage)))
  3181. CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
  3182. }
  3183. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  3184. /// smooshes them together with platform defaults, to decide whether
  3185. /// this compile should be using PIC mode or not. Returns a tuple of
  3186. /// (RelocationModel, PICLevel, IsPIE).
  3187. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  3188. ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
  3189. const ArgList &Args) {
  3190. // FIXME: why does this code...and so much everywhere else, use both
  3191. // ToolChain.getTriple() and Triple?
  3192. bool PIE = ToolChain.isPIEDefault();
  3193. bool PIC = PIE || ToolChain.isPICDefault();
  3194. // The Darwin/MachO default to use PIC does not apply when using -static.
  3195. if (ToolChain.getTriple().isOSBinFormatMachO() &&
  3196. Args.hasArg(options::OPT_static))
  3197. PIE = PIC = false;
  3198. bool IsPICLevelTwo = PIC;
  3199. bool KernelOrKext =
  3200. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3201. // Android-specific defaults for PIC/PIE
  3202. if (ToolChain.getTriple().isAndroid()) {
  3203. switch (ToolChain.getArch()) {
  3204. case llvm::Triple::arm:
  3205. case llvm::Triple::armeb:
  3206. case llvm::Triple::thumb:
  3207. case llvm::Triple::thumbeb:
  3208. case llvm::Triple::aarch64:
  3209. case llvm::Triple::mips:
  3210. case llvm::Triple::mipsel:
  3211. case llvm::Triple::mips64:
  3212. case llvm::Triple::mips64el:
  3213. PIC = true; // "-fpic"
  3214. break;
  3215. case llvm::Triple::x86:
  3216. case llvm::Triple::x86_64:
  3217. PIC = true; // "-fPIC"
  3218. IsPICLevelTwo = true;
  3219. break;
  3220. default:
  3221. break;
  3222. }
  3223. }
  3224. // OpenBSD-specific defaults for PIE
  3225. if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
  3226. switch (ToolChain.getArch()) {
  3227. case llvm::Triple::mips64:
  3228. case llvm::Triple::mips64el:
  3229. case llvm::Triple::sparcel:
  3230. case llvm::Triple::x86:
  3231. case llvm::Triple::x86_64:
  3232. IsPICLevelTwo = false; // "-fpie"
  3233. break;
  3234. case llvm::Triple::ppc:
  3235. case llvm::Triple::sparc:
  3236. case llvm::Triple::sparcv9:
  3237. IsPICLevelTwo = true; // "-fPIE"
  3238. break;
  3239. default:
  3240. break;
  3241. }
  3242. }
  3243. // The last argument relating to either PIC or PIE wins, and no
  3244. // other argument is used. If the last argument is any flavor of the
  3245. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  3246. // option implicitly enables PIC at the same level.
  3247. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  3248. options::OPT_fpic, options::OPT_fno_pic,
  3249. options::OPT_fPIE, options::OPT_fno_PIE,
  3250. options::OPT_fpie, options::OPT_fno_pie);
  3251. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  3252. // is forced, then neither PIC nor PIE flags will have no effect.
  3253. if (!ToolChain.isPICDefaultForced()) {
  3254. if (LastPICArg) {
  3255. Option O = LastPICArg->getOption();
  3256. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  3257. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  3258. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  3259. PIC =
  3260. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  3261. IsPICLevelTwo =
  3262. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  3263. } else {
  3264. PIE = PIC = false;
  3265. if (Triple.isPS4CPU()) {
  3266. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  3267. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  3268. if (Model != "kernel") {
  3269. PIC = true;
  3270. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  3271. << LastPICArg->getSpelling();
  3272. }
  3273. }
  3274. }
  3275. }
  3276. }
  3277. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  3278. // PIC level would've been set to level 1, force it back to level 2 PIC
  3279. // instead.
  3280. if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
  3281. IsPICLevelTwo |= ToolChain.isPICDefault();
  3282. // This kernel flags are a trump-card: they will disable PIC/PIE
  3283. // generation, independent of the argument order.
  3284. if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  3285. !Triple.isWatchOS()))
  3286. PIC = PIE = false;
  3287. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  3288. // This is a very special mode. It trumps the other modes, almost no one
  3289. // uses it, and it isn't even valid on any OS but Darwin.
  3290. if (!ToolChain.getTriple().isOSDarwin())
  3291. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3292. << A->getSpelling() << ToolChain.getTriple().str();
  3293. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  3294. // Only a forced PIC mode can cause the actual compile to have PIC defines
  3295. // etc., no flags are sufficient. This behavior was selected to closely
  3296. // match that of llvm-gcc and Apple GCC before that.
  3297. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  3298. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
  3299. }
  3300. if (PIC)
  3301. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
  3302. return std::make_tuple(llvm::Reloc::Static, 0, false);
  3303. }
  3304. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  3305. switch (Model) {
  3306. case llvm::Reloc::Static:
  3307. return "static";
  3308. case llvm::Reloc::PIC_:
  3309. return "pic";
  3310. case llvm::Reloc::DynamicNoPIC:
  3311. return "dynamic-no-pic";
  3312. }
  3313. llvm_unreachable("Unknown Reloc::Model kind");
  3314. }
  3315. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  3316. ArgStringList &CmdArgs) {
  3317. llvm::Reloc::Model RelocationModel;
  3318. unsigned PICLevel;
  3319. bool IsPIE;
  3320. std::tie(RelocationModel, PICLevel, IsPIE) =
  3321. ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
  3322. if (RelocationModel != llvm::Reloc::Static)
  3323. CmdArgs.push_back("-KPIC");
  3324. }
  3325. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  3326. const InputInfo &Output, const InputInfoList &Inputs,
  3327. const ArgList &Args, const char *LinkingOutput) const {
  3328. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  3329. const llvm::Triple Triple(TripleStr);
  3330. bool KernelOrKext =
  3331. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3332. const Driver &D = getToolChain().getDriver();
  3333. ArgStringList CmdArgs;
  3334. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  3335. bool IsWindowsCygnus =
  3336. getToolChain().getTriple().isWindowsCygwinEnvironment();
  3337. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  3338. bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
  3339. // Check number of inputs for sanity. We need at least one input.
  3340. assert(Inputs.size() >= 1 && "Must have at least one input.");
  3341. const InputInfo &Input = Inputs[0];
  3342. // CUDA compilation may have multiple inputs (source file + results of
  3343. // device-side compilations). All other jobs are expected to have exactly one
  3344. // input.
  3345. bool IsCuda = types::isCuda(Input.getType());
  3346. assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
  3347. // Invoke ourselves in -cc1 mode.
  3348. //
  3349. // FIXME: Implement custom jobs for internal actions.
  3350. CmdArgs.push_back("-cc1");
  3351. // Add the "effective" target triple.
  3352. CmdArgs.push_back("-triple");
  3353. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  3354. const ToolChain *AuxToolChain = nullptr;
  3355. if (IsCuda) {
  3356. // FIXME: We need a (better) way to pass information about
  3357. // particular compilation pass we're constructing here. For now we
  3358. // can check which toolchain we're using and pick the other one to
  3359. // extract the triple.
  3360. if (&getToolChain() == C.getSingleOffloadToolChain<Action::OFK_Cuda>())
  3361. AuxToolChain = C.getOffloadingHostToolChain();
  3362. else if (&getToolChain() == C.getOffloadingHostToolChain())
  3363. AuxToolChain = C.getSingleOffloadToolChain<Action::OFK_Cuda>();
  3364. else
  3365. llvm_unreachable("Can't figure out CUDA compilation mode.");
  3366. assert(AuxToolChain != nullptr && "No aux toolchain.");
  3367. CmdArgs.push_back("-aux-triple");
  3368. CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
  3369. }
  3370. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  3371. Triple.getArch() == llvm::Triple::thumb)) {
  3372. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  3373. unsigned Version;
  3374. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  3375. if (Version < 7)
  3376. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  3377. << TripleStr;
  3378. }
  3379. // Push all default warning arguments that are specific to
  3380. // the given target. These come before user provided warning options
  3381. // are provided.
  3382. getToolChain().addClangWarningOptions(CmdArgs);
  3383. // Select the appropriate action.
  3384. RewriteKind rewriteKind = RK_None;
  3385. if (isa<AnalyzeJobAction>(JA)) {
  3386. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  3387. CmdArgs.push_back("-analyze");
  3388. } else if (isa<MigrateJobAction>(JA)) {
  3389. CmdArgs.push_back("-migrate");
  3390. } else if (isa<PreprocessJobAction>(JA)) {
  3391. if (Output.getType() == types::TY_Dependencies)
  3392. CmdArgs.push_back("-Eonly");
  3393. else {
  3394. CmdArgs.push_back("-E");
  3395. if (Args.hasArg(options::OPT_rewrite_objc) &&
  3396. !Args.hasArg(options::OPT_g_Group))
  3397. CmdArgs.push_back("-P");
  3398. }
  3399. } else if (isa<AssembleJobAction>(JA)) {
  3400. CmdArgs.push_back("-emit-obj");
  3401. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  3402. // Also ignore explicit -force_cpusubtype_ALL option.
  3403. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  3404. } else if (isa<PrecompileJobAction>(JA)) {
  3405. // Use PCH if the user requested it.
  3406. bool UsePCH = D.CCCUsePCH;
  3407. if (JA.getType() == types::TY_Nothing)
  3408. CmdArgs.push_back("-fsyntax-only");
  3409. else if (UsePCH)
  3410. CmdArgs.push_back("-emit-pch");
  3411. else
  3412. CmdArgs.push_back("-emit-pth");
  3413. } else if (isa<VerifyPCHJobAction>(JA)) {
  3414. CmdArgs.push_back("-verify-pch");
  3415. } else {
  3416. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  3417. "Invalid action for clang tool.");
  3418. if (JA.getType() == types::TY_Nothing) {
  3419. CmdArgs.push_back("-fsyntax-only");
  3420. } else if (JA.getType() == types::TY_LLVM_IR ||
  3421. JA.getType() == types::TY_LTO_IR) {
  3422. CmdArgs.push_back("-emit-llvm");
  3423. } else if (JA.getType() == types::TY_LLVM_BC ||
  3424. JA.getType() == types::TY_LTO_BC) {
  3425. CmdArgs.push_back("-emit-llvm-bc");
  3426. } else if (JA.getType() == types::TY_PP_Asm) {
  3427. CmdArgs.push_back("-S");
  3428. } else if (JA.getType() == types::TY_AST) {
  3429. CmdArgs.push_back("-emit-pch");
  3430. } else if (JA.getType() == types::TY_ModuleFile) {
  3431. CmdArgs.push_back("-module-file-info");
  3432. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3433. CmdArgs.push_back("-rewrite-objc");
  3434. rewriteKind = RK_NonFragile;
  3435. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3436. CmdArgs.push_back("-rewrite-objc");
  3437. rewriteKind = RK_Fragile;
  3438. } else {
  3439. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3440. }
  3441. // Preserve use-list order by default when emitting bitcode, so that
  3442. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3443. // same result as running passes here. For LTO, we don't need to preserve
  3444. // the use-list order, since serialization to bitcode is part of the flow.
  3445. if (JA.getType() == types::TY_LLVM_BC)
  3446. CmdArgs.push_back("-emit-llvm-uselists");
  3447. if (D.isUsingLTO())
  3448. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3449. }
  3450. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  3451. if (!types::isLLVMIR(Input.getType()))
  3452. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3453. << "-x ir";
  3454. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  3455. }
  3456. // Embed-bitcode option.
  3457. if (C.getDriver().embedBitcodeEnabled() &&
  3458. (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
  3459. // Add flags implied by -fembed-bitcode.
  3460. Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
  3461. // Disable all llvm IR level optimizations.
  3462. CmdArgs.push_back("-disable-llvm-optzns");
  3463. }
  3464. if (C.getDriver().embedBitcodeMarkerOnly())
  3465. CmdArgs.push_back("-fembed-bitcode=marker");
  3466. // We normally speed up the clang process a bit by skipping destructors at
  3467. // exit, but when we're generating diagnostics we can rely on some of the
  3468. // cleanup.
  3469. if (!C.isForDiagnostics())
  3470. CmdArgs.push_back("-disable-free");
  3471. // Disable the verification pass in -asserts builds.
  3472. #ifdef NDEBUG
  3473. CmdArgs.push_back("-disable-llvm-verifier");
  3474. // Discard LLVM value names in -asserts builds.
  3475. CmdArgs.push_back("-discard-value-names");
  3476. #endif
  3477. // Set the main file name, so that debug info works even with
  3478. // -save-temps.
  3479. CmdArgs.push_back("-main-file-name");
  3480. CmdArgs.push_back(getBaseInputName(Args, Input));
  3481. // Some flags which affect the language (via preprocessor
  3482. // defines).
  3483. if (Args.hasArg(options::OPT_static))
  3484. CmdArgs.push_back("-static-define");
  3485. if (isa<AnalyzeJobAction>(JA)) {
  3486. // Enable region store model by default.
  3487. CmdArgs.push_back("-analyzer-store=region");
  3488. // Treat blocks as analysis entry points.
  3489. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  3490. CmdArgs.push_back("-analyzer-eagerly-assume");
  3491. // Add default argument set.
  3492. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  3493. CmdArgs.push_back("-analyzer-checker=core");
  3494. if (!IsWindowsMSVC) {
  3495. CmdArgs.push_back("-analyzer-checker=unix");
  3496. } else {
  3497. // Enable "unix" checkers that also work on Windows.
  3498. CmdArgs.push_back("-analyzer-checker=unix.API");
  3499. CmdArgs.push_back("-analyzer-checker=unix.Malloc");
  3500. CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
  3501. CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
  3502. CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
  3503. CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
  3504. }
  3505. // Disable some unix checkers for PS4.
  3506. if (IsPS4CPU) {
  3507. CmdArgs.push_back("-analyzer-disable-checker=unix.API");
  3508. CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
  3509. }
  3510. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  3511. CmdArgs.push_back("-analyzer-checker=osx");
  3512. CmdArgs.push_back("-analyzer-checker=deadcode");
  3513. if (types::isCXX(Input.getType()))
  3514. CmdArgs.push_back("-analyzer-checker=cplusplus");
  3515. if (!IsPS4CPU) {
  3516. CmdArgs.push_back(
  3517. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  3518. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  3519. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  3520. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  3521. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  3522. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  3523. }
  3524. // Default nullability checks.
  3525. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  3526. CmdArgs.push_back(
  3527. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  3528. }
  3529. // Set the output format. The default is plist, for (lame) historical
  3530. // reasons.
  3531. CmdArgs.push_back("-analyzer-output");
  3532. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  3533. CmdArgs.push_back(A->getValue());
  3534. else
  3535. CmdArgs.push_back("plist");
  3536. // Disable the presentation of standard compiler warnings when
  3537. // using --analyze. We only want to show static analyzer diagnostics
  3538. // or frontend errors.
  3539. CmdArgs.push_back("-w");
  3540. // Add -Xanalyzer arguments when running as analyzer.
  3541. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  3542. }
  3543. CheckCodeGenerationOptions(D, Args);
  3544. llvm::Reloc::Model RelocationModel;
  3545. unsigned PICLevel;
  3546. bool IsPIE;
  3547. std::tie(RelocationModel, PICLevel, IsPIE) =
  3548. ParsePICArgs(getToolChain(), Triple, Args);
  3549. const char *RMName = RelocationModelName(RelocationModel);
  3550. if (RMName) {
  3551. CmdArgs.push_back("-mrelocation-model");
  3552. CmdArgs.push_back(RMName);
  3553. }
  3554. if (PICLevel > 0) {
  3555. CmdArgs.push_back("-pic-level");
  3556. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3557. if (IsPIE) {
  3558. CmdArgs.push_back("-pie-level");
  3559. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3560. }
  3561. }
  3562. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3563. CmdArgs.push_back("-meabi");
  3564. CmdArgs.push_back(A->getValue());
  3565. }
  3566. CmdArgs.push_back("-mthread-model");
  3567. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  3568. CmdArgs.push_back(A->getValue());
  3569. else
  3570. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3571. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3572. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3573. options::OPT_fno_merge_all_constants))
  3574. CmdArgs.push_back("-fno-merge-all-constants");
  3575. // LLVM Code Generator Options.
  3576. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3577. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3578. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3579. options::OPT_frewrite_map_file_EQ)) {
  3580. CmdArgs.push_back("-frewrite-map-file");
  3581. CmdArgs.push_back(A->getValue());
  3582. A->claim();
  3583. }
  3584. }
  3585. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3586. StringRef v = A->getValue();
  3587. CmdArgs.push_back("-mllvm");
  3588. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3589. A->claim();
  3590. }
  3591. if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
  3592. true))
  3593. CmdArgs.push_back("-fno-jump-tables");
  3594. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3595. CmdArgs.push_back("-mregparm");
  3596. CmdArgs.push_back(A->getValue());
  3597. }
  3598. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3599. options::OPT_freg_struct_return)) {
  3600. if (getToolChain().getArch() != llvm::Triple::x86) {
  3601. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3602. << A->getSpelling() << getToolChain().getTriple().str();
  3603. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3604. CmdArgs.push_back("-fpcc-struct-return");
  3605. } else {
  3606. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3607. CmdArgs.push_back("-freg-struct-return");
  3608. }
  3609. }
  3610. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3611. CmdArgs.push_back("-fdefault-calling-conv=stdcall");
  3612. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  3613. CmdArgs.push_back("-mdisable-fp-elim");
  3614. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3615. options::OPT_fno_zero_initialized_in_bss))
  3616. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3617. bool OFastEnabled = isOptimizationLevelFast(Args);
  3618. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3619. // enabled. This alias option is being used to simplify the hasFlag logic.
  3620. OptSpecifier StrictAliasingAliasOption =
  3621. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3622. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3623. // doesn't do any TBAA.
  3624. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  3625. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3626. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3627. CmdArgs.push_back("-relaxed-aliasing");
  3628. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3629. options::OPT_fno_struct_path_tbaa))
  3630. CmdArgs.push_back("-no-struct-path-tbaa");
  3631. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3632. false))
  3633. CmdArgs.push_back("-fstrict-enums");
  3634. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3635. options::OPT_fno_strict_vtable_pointers,
  3636. false))
  3637. CmdArgs.push_back("-fstrict-vtable-pointers");
  3638. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3639. options::OPT_fno_optimize_sibling_calls))
  3640. CmdArgs.push_back("-mdisable-tail-calls");
  3641. // Handle segmented stacks.
  3642. if (Args.hasArg(options::OPT_fsplit_stack))
  3643. CmdArgs.push_back("-split-stacks");
  3644. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  3645. // This alias option is being used to simplify the getLastArg logic.
  3646. OptSpecifier FastMathAliasOption =
  3647. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  3648. // Handle various floating point optimization flags, mapping them to the
  3649. // appropriate LLVM code generation flags. The pattern for all of these is to
  3650. // default off the codegen optimizations, and if any flag enables them and no
  3651. // flag disables them after the flag enabling them, enable the codegen
  3652. // optimization. This is complicated by several "umbrella" flags.
  3653. if (Arg *A = Args.getLastArg(
  3654. options::OPT_ffast_math, FastMathAliasOption,
  3655. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3656. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  3657. options::OPT_fno_honor_infinities))
  3658. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3659. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3660. A->getOption().getID() != options::OPT_fhonor_infinities)
  3661. CmdArgs.push_back("-menable-no-infs");
  3662. if (Arg *A = Args.getLastArg(
  3663. options::OPT_ffast_math, FastMathAliasOption,
  3664. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3665. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  3666. options::OPT_fno_honor_nans))
  3667. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3668. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3669. A->getOption().getID() != options::OPT_fhonor_nans)
  3670. CmdArgs.push_back("-menable-no-nans");
  3671. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  3672. bool MathErrno = getToolChain().IsMathErrnoDefault();
  3673. if (Arg *A =
  3674. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3675. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  3676. options::OPT_fno_math_errno)) {
  3677. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  3678. // However, turning *off* -ffast_math merely restores the toolchain default
  3679. // (which may be false).
  3680. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  3681. A->getOption().getID() == options::OPT_ffast_math ||
  3682. A->getOption().getID() == options::OPT_Ofast)
  3683. MathErrno = false;
  3684. else if (A->getOption().getID() == options::OPT_fmath_errno)
  3685. MathErrno = true;
  3686. }
  3687. if (MathErrno)
  3688. CmdArgs.push_back("-fmath-errno");
  3689. // There are several flags which require disabling very specific
  3690. // optimizations. Any of these being disabled forces us to turn off the
  3691. // entire set of LLVM optimizations, so collect them through all the flag
  3692. // madness.
  3693. bool AssociativeMath = false;
  3694. if (Arg *A = Args.getLastArg(
  3695. options::OPT_ffast_math, FastMathAliasOption,
  3696. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3697. options::OPT_fno_unsafe_math_optimizations,
  3698. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  3699. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3700. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3701. A->getOption().getID() != options::OPT_fno_associative_math)
  3702. AssociativeMath = true;
  3703. bool ReciprocalMath = false;
  3704. if (Arg *A = Args.getLastArg(
  3705. options::OPT_ffast_math, FastMathAliasOption,
  3706. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3707. options::OPT_fno_unsafe_math_optimizations,
  3708. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  3709. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3710. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3711. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  3712. ReciprocalMath = true;
  3713. bool SignedZeros = true;
  3714. if (Arg *A = Args.getLastArg(
  3715. options::OPT_ffast_math, FastMathAliasOption,
  3716. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3717. options::OPT_fno_unsafe_math_optimizations,
  3718. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  3719. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3720. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3721. A->getOption().getID() != options::OPT_fsigned_zeros)
  3722. SignedZeros = false;
  3723. bool TrappingMath = true;
  3724. if (Arg *A = Args.getLastArg(
  3725. options::OPT_ffast_math, FastMathAliasOption,
  3726. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3727. options::OPT_fno_unsafe_math_optimizations,
  3728. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  3729. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3730. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3731. A->getOption().getID() != options::OPT_ftrapping_math)
  3732. TrappingMath = false;
  3733. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  3734. !TrappingMath)
  3735. CmdArgs.push_back("-menable-unsafe-fp-math");
  3736. if (!SignedZeros)
  3737. CmdArgs.push_back("-fno-signed-zeros");
  3738. if (ReciprocalMath)
  3739. CmdArgs.push_back("-freciprocal-math");
  3740. // Validate and pass through -fp-contract option.
  3741. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3742. options::OPT_fno_fast_math,
  3743. options::OPT_ffp_contract)) {
  3744. if (A->getOption().getID() == options::OPT_ffp_contract) {
  3745. StringRef Val = A->getValue();
  3746. if (Val == "fast" || Val == "on" || Val == "off") {
  3747. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  3748. } else {
  3749. D.Diag(diag::err_drv_unsupported_option_argument)
  3750. << A->getOption().getName() << Val;
  3751. }
  3752. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  3753. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  3754. // If fast-math is set then set the fp-contract mode to fast.
  3755. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  3756. }
  3757. }
  3758. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  3759. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  3760. // and if we find them, tell the frontend to provide the appropriate
  3761. // preprocessor macros. This is distinct from enabling any optimizations as
  3762. // these options induce language changes which must survive serialization
  3763. // and deserialization, etc.
  3764. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3765. options::OPT_fno_fast_math))
  3766. if (!A->getOption().matches(options::OPT_fno_fast_math))
  3767. CmdArgs.push_back("-ffast-math");
  3768. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  3769. options::OPT_fno_fast_math))
  3770. if (A->getOption().matches(options::OPT_ffinite_math_only))
  3771. CmdArgs.push_back("-ffinite-math-only");
  3772. // Decide whether to use verbose asm. Verbose assembly is the default on
  3773. // toolchains which have the integrated assembler on by default.
  3774. bool IsIntegratedAssemblerDefault =
  3775. getToolChain().IsIntegratedAssemblerDefault();
  3776. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3777. IsIntegratedAssemblerDefault) ||
  3778. Args.hasArg(options::OPT_dA))
  3779. CmdArgs.push_back("-masm-verbose");
  3780. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  3781. IsIntegratedAssemblerDefault))
  3782. CmdArgs.push_back("-no-integrated-as");
  3783. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3784. CmdArgs.push_back("-mdebug-pass");
  3785. CmdArgs.push_back("Structure");
  3786. }
  3787. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3788. CmdArgs.push_back("-mdebug-pass");
  3789. CmdArgs.push_back("Arguments");
  3790. }
  3791. // Enable -mconstructor-aliases except on darwin, where we have to work around
  3792. // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
  3793. // aliases aren't supported.
  3794. if (!getToolChain().getTriple().isOSDarwin() &&
  3795. !getToolChain().getTriple().isNVPTX())
  3796. CmdArgs.push_back("-mconstructor-aliases");
  3797. // Darwin's kernel doesn't support guard variables; just die if we
  3798. // try to use them.
  3799. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  3800. CmdArgs.push_back("-fforbid-guard-variables");
  3801. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  3802. false)) {
  3803. CmdArgs.push_back("-mms-bitfields");
  3804. }
  3805. // This is a coarse approximation of what llvm-gcc actually does, both
  3806. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3807. // complicated ways.
  3808. bool AsynchronousUnwindTables =
  3809. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3810. options::OPT_fno_asynchronous_unwind_tables,
  3811. (getToolChain().IsUnwindTablesDefault() ||
  3812. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  3813. !KernelOrKext);
  3814. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3815. AsynchronousUnwindTables))
  3816. CmdArgs.push_back("-munwind-tables");
  3817. getToolChain().addClangTargetOptions(Args, CmdArgs);
  3818. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  3819. CmdArgs.push_back("-mlimit-float-precision");
  3820. CmdArgs.push_back(A->getValue());
  3821. }
  3822. // FIXME: Handle -mtune=.
  3823. (void)Args.hasArg(options::OPT_mtune_EQ);
  3824. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3825. CmdArgs.push_back("-mcode-model");
  3826. CmdArgs.push_back(A->getValue());
  3827. }
  3828. // Add the target cpu
  3829. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3830. if (!CPU.empty()) {
  3831. CmdArgs.push_back("-target-cpu");
  3832. CmdArgs.push_back(Args.MakeArgString(CPU));
  3833. }
  3834. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  3835. CmdArgs.push_back("-mfpmath");
  3836. CmdArgs.push_back(A->getValue());
  3837. }
  3838. // Add the target features
  3839. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  3840. // Add target specific flags.
  3841. switch (getToolChain().getArch()) {
  3842. default:
  3843. break;
  3844. case llvm::Triple::arm:
  3845. case llvm::Triple::armeb:
  3846. case llvm::Triple::thumb:
  3847. case llvm::Triple::thumbeb:
  3848. // Use the effective triple, which takes into account the deployment target.
  3849. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  3850. break;
  3851. case llvm::Triple::aarch64:
  3852. case llvm::Triple::aarch64_be:
  3853. AddAArch64TargetArgs(Args, CmdArgs);
  3854. break;
  3855. case llvm::Triple::mips:
  3856. case llvm::Triple::mipsel:
  3857. case llvm::Triple::mips64:
  3858. case llvm::Triple::mips64el:
  3859. AddMIPSTargetArgs(Args, CmdArgs);
  3860. break;
  3861. case llvm::Triple::ppc:
  3862. case llvm::Triple::ppc64:
  3863. case llvm::Triple::ppc64le:
  3864. AddPPCTargetArgs(Args, CmdArgs);
  3865. break;
  3866. case llvm::Triple::sparc:
  3867. case llvm::Triple::sparcel:
  3868. case llvm::Triple::sparcv9:
  3869. AddSparcTargetArgs(Args, CmdArgs);
  3870. break;
  3871. case llvm::Triple::systemz:
  3872. AddSystemZTargetArgs(Args, CmdArgs);
  3873. break;
  3874. case llvm::Triple::x86:
  3875. case llvm::Triple::x86_64:
  3876. AddX86TargetArgs(Args, CmdArgs);
  3877. break;
  3878. case llvm::Triple::lanai:
  3879. AddLanaiTargetArgs(Args, CmdArgs);
  3880. break;
  3881. case llvm::Triple::hexagon:
  3882. AddHexagonTargetArgs(Args, CmdArgs);
  3883. break;
  3884. case llvm::Triple::wasm32:
  3885. case llvm::Triple::wasm64:
  3886. AddWebAssemblyTargetArgs(Args, CmdArgs);
  3887. break;
  3888. }
  3889. // The 'g' groups options involve a somewhat intricate sequence of decisions
  3890. // about what to pass from the driver to the frontend, but by the time they
  3891. // reach cc1 they've been factored into three well-defined orthogonal choices:
  3892. // * what level of debug info to generate
  3893. // * what dwarf version to write
  3894. // * what debugger tuning to use
  3895. // This avoids having to monkey around further in cc1 other than to disable
  3896. // codeview if not running in a Windows environment. Perhaps even that
  3897. // decision should be made in the driver as well though.
  3898. unsigned DwarfVersion = 0;
  3899. llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
  3900. // These two are potentially updated by AddClangCLArgs.
  3901. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  3902. bool EmitCodeView = false;
  3903. // Add clang-cl arguments.
  3904. types::ID InputType = Input.getType();
  3905. if (getToolChain().getDriver().IsCLMode())
  3906. AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
  3907. // Pass the linker version in use.
  3908. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  3909. CmdArgs.push_back("-target-linker-version");
  3910. CmdArgs.push_back(A->getValue());
  3911. }
  3912. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  3913. CmdArgs.push_back("-momit-leaf-frame-pointer");
  3914. // Explicitly error on some things we know we don't support and can't just
  3915. // ignore.
  3916. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  3917. Arg *Unsupported;
  3918. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  3919. getToolChain().getArch() == llvm::Triple::x86) {
  3920. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  3921. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  3922. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  3923. << Unsupported->getOption().getName();
  3924. }
  3925. }
  3926. Args.AddAllArgs(CmdArgs, options::OPT_v);
  3927. Args.AddLastArg(CmdArgs, options::OPT_H);
  3928. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  3929. CmdArgs.push_back("-header-include-file");
  3930. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  3931. : "-");
  3932. }
  3933. Args.AddLastArg(CmdArgs, options::OPT_P);
  3934. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  3935. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  3936. CmdArgs.push_back("-diagnostic-log-file");
  3937. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  3938. : "-");
  3939. }
  3940. Args.ClaimAllArgs(options::OPT_g_Group);
  3941. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  3942. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  3943. // If the last option explicitly specified a debug-info level, use it.
  3944. if (A->getOption().matches(options::OPT_gN_Group)) {
  3945. DebugInfoKind = DebugLevelToInfoKind(*A);
  3946. // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
  3947. // But -gsplit-dwarf is not a g_group option, hence we have to check the
  3948. // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
  3949. if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
  3950. A->getIndex() > SplitDwarfArg->getIndex())
  3951. SplitDwarfArg = nullptr;
  3952. } else
  3953. // For any other 'g' option, use Limited.
  3954. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3955. }
  3956. // If a debugger tuning argument appeared, remember it.
  3957. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  3958. options::OPT_ggdbN_Group)) {
  3959. if (A->getOption().matches(options::OPT_glldb))
  3960. DebuggerTuning = llvm::DebuggerKind::LLDB;
  3961. else if (A->getOption().matches(options::OPT_gsce))
  3962. DebuggerTuning = llvm::DebuggerKind::SCE;
  3963. else
  3964. DebuggerTuning = llvm::DebuggerKind::GDB;
  3965. }
  3966. // If a -gdwarf argument appeared, remember it.
  3967. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  3968. options::OPT_gdwarf_4, options::OPT_gdwarf_5))
  3969. DwarfVersion = DwarfVersionNum(A->getSpelling());
  3970. // Forward -gcodeview.
  3971. // 'EmitCodeView might have been set by CL-compatibility argument parsing.
  3972. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  3973. // DwarfVersion remains at 0 if no explicit choice was made.
  3974. CmdArgs.push_back("-gcodeview");
  3975. } else if (DwarfVersion == 0 &&
  3976. DebugInfoKind != codegenoptions::NoDebugInfo) {
  3977. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  3978. }
  3979. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  3980. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  3981. // PS4 defaults to no column info
  3982. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  3983. /*Default=*/ !IsPS4CPU))
  3984. CmdArgs.push_back("-dwarf-column-info");
  3985. // FIXME: Move backend command line options to the module.
  3986. if (Args.hasArg(options::OPT_gmodules)) {
  3987. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3988. CmdArgs.push_back("-dwarf-ext-refs");
  3989. CmdArgs.push_back("-fmodule-format=obj");
  3990. }
  3991. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  3992. // splitting and extraction.
  3993. // FIXME: Currently only works on Linux.
  3994. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  3995. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3996. CmdArgs.push_back("-backend-option");
  3997. CmdArgs.push_back("-split-dwarf=Enable");
  3998. }
  3999. // After we've dealt with all combinations of things that could
  4000. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  4001. // figure out if we need to "upgrade" it to standalone debug info.
  4002. // We parse these two '-f' options whether or not they will be used,
  4003. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  4004. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  4005. options::OPT_fno_standalone_debug,
  4006. getToolChain().GetDefaultStandaloneDebug());
  4007. if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
  4008. DebugInfoKind = codegenoptions::FullDebugInfo;
  4009. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  4010. DebuggerTuning);
  4011. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  4012. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  4013. CmdArgs.push_back("-backend-option");
  4014. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  4015. }
  4016. // -gdwarf-aranges turns on the emission of the aranges section in the
  4017. // backend.
  4018. // Always enabled on the PS4.
  4019. if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
  4020. CmdArgs.push_back("-backend-option");
  4021. CmdArgs.push_back("-generate-arange-section");
  4022. }
  4023. if (Args.hasFlag(options::OPT_fdebug_types_section,
  4024. options::OPT_fno_debug_types_section, false)) {
  4025. CmdArgs.push_back("-backend-option");
  4026. CmdArgs.push_back("-generate-type-units");
  4027. }
  4028. // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
  4029. // default.
  4030. bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
  4031. Triple.getArch() == llvm::Triple::wasm32 ||
  4032. Triple.getArch() == llvm::Triple::wasm64;
  4033. if (Args.hasFlag(options::OPT_ffunction_sections,
  4034. options::OPT_fno_function_sections, UseSeparateSections)) {
  4035. CmdArgs.push_back("-ffunction-sections");
  4036. }
  4037. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  4038. UseSeparateSections)) {
  4039. CmdArgs.push_back("-fdata-sections");
  4040. }
  4041. if (!Args.hasFlag(options::OPT_funique_section_names,
  4042. options::OPT_fno_unique_section_names, true))
  4043. CmdArgs.push_back("-fno-unique-section-names");
  4044. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  4045. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  4046. // Add runtime flag for PS4 when PGO or Coverage are enabled.
  4047. if (getToolChain().getTriple().isPS4CPU())
  4048. addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
  4049. // Pass options for controlling the default header search paths.
  4050. if (Args.hasArg(options::OPT_nostdinc)) {
  4051. CmdArgs.push_back("-nostdsysteminc");
  4052. CmdArgs.push_back("-nobuiltininc");
  4053. } else {
  4054. if (Args.hasArg(options::OPT_nostdlibinc))
  4055. CmdArgs.push_back("-nostdsysteminc");
  4056. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  4057. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  4058. }
  4059. // Pass the path to compiler resource files.
  4060. CmdArgs.push_back("-resource-dir");
  4061. CmdArgs.push_back(D.ResourceDir.c_str());
  4062. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  4063. bool ARCMTEnabled = false;
  4064. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  4065. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  4066. options::OPT_ccc_arcmt_modify,
  4067. options::OPT_ccc_arcmt_migrate)) {
  4068. ARCMTEnabled = true;
  4069. switch (A->getOption().getID()) {
  4070. default:
  4071. llvm_unreachable("missed a case");
  4072. case options::OPT_ccc_arcmt_check:
  4073. CmdArgs.push_back("-arcmt-check");
  4074. break;
  4075. case options::OPT_ccc_arcmt_modify:
  4076. CmdArgs.push_back("-arcmt-modify");
  4077. break;
  4078. case options::OPT_ccc_arcmt_migrate:
  4079. CmdArgs.push_back("-arcmt-migrate");
  4080. CmdArgs.push_back("-mt-migrate-directory");
  4081. CmdArgs.push_back(A->getValue());
  4082. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  4083. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  4084. break;
  4085. }
  4086. }
  4087. } else {
  4088. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  4089. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  4090. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  4091. }
  4092. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  4093. if (ARCMTEnabled) {
  4094. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4095. << "-ccc-arcmt-migrate";
  4096. }
  4097. CmdArgs.push_back("-mt-migrate-directory");
  4098. CmdArgs.push_back(A->getValue());
  4099. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  4100. options::OPT_objcmt_migrate_subscripting,
  4101. options::OPT_objcmt_migrate_property)) {
  4102. // None specified, means enable them all.
  4103. CmdArgs.push_back("-objcmt-migrate-literals");
  4104. CmdArgs.push_back("-objcmt-migrate-subscripting");
  4105. CmdArgs.push_back("-objcmt-migrate-property");
  4106. } else {
  4107. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4108. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4109. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4110. }
  4111. } else {
  4112. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  4113. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  4114. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  4115. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  4116. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  4117. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  4118. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  4119. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  4120. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  4121. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  4122. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  4123. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  4124. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  4125. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  4126. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  4127. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  4128. }
  4129. // Add preprocessing options like -I, -D, etc. if we are using the
  4130. // preprocessor.
  4131. //
  4132. // FIXME: Support -fpreprocessed
  4133. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  4134. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
  4135. AuxToolChain);
  4136. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  4137. // that "The compiler can only warn and ignore the option if not recognized".
  4138. // When building with ccache, it will pass -D options to clang even on
  4139. // preprocessed inputs and configure concludes that -fPIC is not supported.
  4140. Args.ClaimAllArgs(options::OPT_D);
  4141. // Manually translate -O4 to -O3; let clang reject others.
  4142. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  4143. if (A->getOption().matches(options::OPT_O4)) {
  4144. CmdArgs.push_back("-O3");
  4145. D.Diag(diag::warn_O4_is_O3);
  4146. } else {
  4147. A->render(Args, CmdArgs);
  4148. }
  4149. }
  4150. // Warn about ignored options to clang.
  4151. for (const Arg *A :
  4152. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  4153. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  4154. A->claim();
  4155. }
  4156. claimNoWarnArgs(Args);
  4157. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  4158. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  4159. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  4160. CmdArgs.push_back("-pedantic");
  4161. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  4162. Args.AddLastArg(CmdArgs, options::OPT_w);
  4163. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  4164. // (-ansi is equivalent to -std=c89 or -std=c++98).
  4165. //
  4166. // If a std is supplied, only add -trigraphs if it follows the
  4167. // option.
  4168. bool ImplyVCPPCXXVer = false;
  4169. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  4170. if (Std->getOption().matches(options::OPT_ansi))
  4171. if (types::isCXX(InputType))
  4172. CmdArgs.push_back("-std=c++98");
  4173. else
  4174. CmdArgs.push_back("-std=c89");
  4175. else
  4176. Std->render(Args, CmdArgs);
  4177. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  4178. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  4179. options::OPT_ftrigraphs,
  4180. options::OPT_fno_trigraphs))
  4181. if (A != Std)
  4182. A->render(Args, CmdArgs);
  4183. } else {
  4184. // Honor -std-default.
  4185. //
  4186. // FIXME: Clang doesn't correctly handle -std= when the input language
  4187. // doesn't match. For the time being just ignore this for C++ inputs;
  4188. // eventually we want to do all the standard defaulting here instead of
  4189. // splitting it between the driver and clang -cc1.
  4190. if (!types::isCXX(InputType))
  4191. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  4192. /*Joined=*/true);
  4193. else if (IsWindowsMSVC)
  4194. ImplyVCPPCXXVer = true;
  4195. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  4196. options::OPT_fno_trigraphs);
  4197. }
  4198. // GCC's behavior for -Wwrite-strings is a bit strange:
  4199. // * In C, this "warning flag" changes the types of string literals from
  4200. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  4201. // for the discarded qualifier.
  4202. // * In C++, this is just a normal warning flag.
  4203. //
  4204. // Implementing this warning correctly in C is hard, so we follow GCC's
  4205. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  4206. // a non-const char* in C, rather than using this crude hack.
  4207. if (!types::isCXX(InputType)) {
  4208. // FIXME: This should behave just like a warning flag, and thus should also
  4209. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  4210. Arg *WriteStrings =
  4211. Args.getLastArg(options::OPT_Wwrite_strings,
  4212. options::OPT_Wno_write_strings, options::OPT_w);
  4213. if (WriteStrings &&
  4214. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  4215. CmdArgs.push_back("-fconst-strings");
  4216. }
  4217. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  4218. // during C++ compilation, which it is by default. GCC keeps this define even
  4219. // in the presence of '-w', match this behavior bug-for-bug.
  4220. if (types::isCXX(InputType) &&
  4221. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  4222. true)) {
  4223. CmdArgs.push_back("-fdeprecated-macro");
  4224. }
  4225. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  4226. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  4227. if (Asm->getOption().matches(options::OPT_fasm))
  4228. CmdArgs.push_back("-fgnu-keywords");
  4229. else
  4230. CmdArgs.push_back("-fno-gnu-keywords");
  4231. }
  4232. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  4233. CmdArgs.push_back("-fno-dwarf-directory-asm");
  4234. if (ShouldDisableAutolink(Args, getToolChain()))
  4235. CmdArgs.push_back("-fno-autolink");
  4236. // Add in -fdebug-compilation-dir if necessary.
  4237. addDebugCompDirArg(Args, CmdArgs);
  4238. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  4239. StringRef Map = A->getValue();
  4240. if (Map.find('=') == StringRef::npos)
  4241. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  4242. else
  4243. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  4244. A->claim();
  4245. }
  4246. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  4247. options::OPT_ftemplate_depth_EQ)) {
  4248. CmdArgs.push_back("-ftemplate-depth");
  4249. CmdArgs.push_back(A->getValue());
  4250. }
  4251. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  4252. CmdArgs.push_back("-foperator-arrow-depth");
  4253. CmdArgs.push_back(A->getValue());
  4254. }
  4255. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  4256. CmdArgs.push_back("-fconstexpr-depth");
  4257. CmdArgs.push_back(A->getValue());
  4258. }
  4259. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  4260. CmdArgs.push_back("-fconstexpr-steps");
  4261. CmdArgs.push_back(A->getValue());
  4262. }
  4263. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  4264. CmdArgs.push_back("-fbracket-depth");
  4265. CmdArgs.push_back(A->getValue());
  4266. }
  4267. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  4268. options::OPT_Wlarge_by_value_copy_def)) {
  4269. if (A->getNumValues()) {
  4270. StringRef bytes = A->getValue();
  4271. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  4272. } else
  4273. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  4274. }
  4275. if (Args.hasArg(options::OPT_relocatable_pch))
  4276. CmdArgs.push_back("-relocatable-pch");
  4277. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  4278. CmdArgs.push_back("-fconstant-string-class");
  4279. CmdArgs.push_back(A->getValue());
  4280. }
  4281. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  4282. CmdArgs.push_back("-ftabstop");
  4283. CmdArgs.push_back(A->getValue());
  4284. }
  4285. CmdArgs.push_back("-ferror-limit");
  4286. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  4287. CmdArgs.push_back(A->getValue());
  4288. else
  4289. CmdArgs.push_back("19");
  4290. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  4291. CmdArgs.push_back("-fmacro-backtrace-limit");
  4292. CmdArgs.push_back(A->getValue());
  4293. }
  4294. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  4295. CmdArgs.push_back("-ftemplate-backtrace-limit");
  4296. CmdArgs.push_back(A->getValue());
  4297. }
  4298. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  4299. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  4300. CmdArgs.push_back(A->getValue());
  4301. }
  4302. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  4303. CmdArgs.push_back("-fspell-checking-limit");
  4304. CmdArgs.push_back(A->getValue());
  4305. }
  4306. // Pass -fmessage-length=.
  4307. CmdArgs.push_back("-fmessage-length");
  4308. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  4309. CmdArgs.push_back(A->getValue());
  4310. } else {
  4311. // If -fmessage-length=N was not specified, determine whether this is a
  4312. // terminal and, if so, implicitly define -fmessage-length appropriately.
  4313. unsigned N = llvm::sys::Process::StandardErrColumns();
  4314. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  4315. }
  4316. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  4317. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  4318. options::OPT_fvisibility_ms_compat)) {
  4319. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  4320. CmdArgs.push_back("-fvisibility");
  4321. CmdArgs.push_back(A->getValue());
  4322. } else {
  4323. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  4324. CmdArgs.push_back("-fvisibility");
  4325. CmdArgs.push_back("hidden");
  4326. CmdArgs.push_back("-ftype-visibility");
  4327. CmdArgs.push_back("default");
  4328. }
  4329. }
  4330. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  4331. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  4332. // -fhosted is default.
  4333. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  4334. KernelOrKext)
  4335. CmdArgs.push_back("-ffreestanding");
  4336. // Forward -f (flag) options which we can pass directly.
  4337. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  4338. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  4339. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  4340. // Emulated TLS is enabled by default on Android, and can be enabled manually
  4341. // with -femulated-tls.
  4342. bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
  4343. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  4344. EmulatedTLSDefault))
  4345. CmdArgs.push_back("-femulated-tls");
  4346. // AltiVec-like language extensions aren't relevant for assembling.
  4347. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  4348. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  4349. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  4350. }
  4351. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  4352. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  4353. // Forward flags for OpenMP
  4354. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  4355. options::OPT_fno_openmp, false)) {
  4356. switch (getOpenMPRuntime(getToolChain(), Args)) {
  4357. case OMPRT_OMP:
  4358. case OMPRT_IOMP5:
  4359. // Clang can generate useful OpenMP code for these two runtime libraries.
  4360. CmdArgs.push_back("-fopenmp");
  4361. // If no option regarding the use of TLS in OpenMP codegeneration is
  4362. // given, decide a default based on the target. Otherwise rely on the
  4363. // options and pass the right information to the frontend.
  4364. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  4365. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  4366. CmdArgs.push_back("-fnoopenmp-use-tls");
  4367. Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
  4368. break;
  4369. default:
  4370. // By default, if Clang doesn't know how to generate useful OpenMP code
  4371. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  4372. // down to the actual compilation.
  4373. // FIXME: It would be better to have a mode which *only* omits IR
  4374. // generation based on the OpenMP support so that we get consistent
  4375. // semantic analysis, etc.
  4376. break;
  4377. }
  4378. }
  4379. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  4380. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  4381. // Report an error for -faltivec on anything other than PowerPC.
  4382. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  4383. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  4384. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  4385. Arch == llvm::Triple::ppc64le))
  4386. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  4387. << "ppc/ppc64/ppc64le";
  4388. }
  4389. // -fzvector is incompatible with -faltivec.
  4390. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  4391. if (Args.hasArg(options::OPT_faltivec))
  4392. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4393. << "-faltivec";
  4394. if (getToolChain().SupportsProfiling())
  4395. Args.AddLastArg(CmdArgs, options::OPT_pg);
  4396. // -flax-vector-conversions is default.
  4397. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  4398. options::OPT_fno_lax_vector_conversions))
  4399. CmdArgs.push_back("-fno-lax-vector-conversions");
  4400. if (Args.getLastArg(options::OPT_fapple_kext) ||
  4401. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  4402. CmdArgs.push_back("-fapple-kext");
  4403. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  4404. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  4405. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  4406. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  4407. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  4408. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  4409. CmdArgs.push_back("-ftrapv-handler");
  4410. CmdArgs.push_back(A->getValue());
  4411. }
  4412. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  4413. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  4414. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  4415. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  4416. if (A->getOption().matches(options::OPT_fwrapv))
  4417. CmdArgs.push_back("-fwrapv");
  4418. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  4419. options::OPT_fno_strict_overflow)) {
  4420. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  4421. CmdArgs.push_back("-fwrapv");
  4422. }
  4423. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  4424. options::OPT_fno_reroll_loops))
  4425. if (A->getOption().matches(options::OPT_freroll_loops))
  4426. CmdArgs.push_back("-freroll-loops");
  4427. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  4428. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  4429. options::OPT_fno_unroll_loops);
  4430. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  4431. // -stack-protector=0 is default.
  4432. unsigned StackProtectorLevel = 0;
  4433. if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  4434. options::OPT_fstack_protector_all,
  4435. options::OPT_fstack_protector_strong,
  4436. options::OPT_fstack_protector)) {
  4437. if (A->getOption().matches(options::OPT_fstack_protector)) {
  4438. StackProtectorLevel = std::max<unsigned>(
  4439. LangOptions::SSPOn,
  4440. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  4441. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  4442. StackProtectorLevel = LangOptions::SSPStrong;
  4443. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  4444. StackProtectorLevel = LangOptions::SSPReq;
  4445. } else {
  4446. StackProtectorLevel =
  4447. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  4448. }
  4449. if (StackProtectorLevel) {
  4450. CmdArgs.push_back("-stack-protector");
  4451. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  4452. }
  4453. // --param ssp-buffer-size=
  4454. for (const Arg *A : Args.filtered(options::OPT__param)) {
  4455. StringRef Str(A->getValue());
  4456. if (Str.startswith("ssp-buffer-size=")) {
  4457. if (StackProtectorLevel) {
  4458. CmdArgs.push_back("-stack-protector-buffer-size");
  4459. // FIXME: Verify the argument is a valid integer.
  4460. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  4461. }
  4462. A->claim();
  4463. }
  4464. }
  4465. // Translate -mstackrealign
  4466. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  4467. false))
  4468. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  4469. if (Args.hasArg(options::OPT_mstack_alignment)) {
  4470. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  4471. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  4472. }
  4473. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  4474. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  4475. if (!Size.empty())
  4476. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  4477. else
  4478. CmdArgs.push_back("-mstack-probe-size=0");
  4479. }
  4480. switch (getToolChain().getArch()) {
  4481. case llvm::Triple::aarch64:
  4482. case llvm::Triple::aarch64_be:
  4483. case llvm::Triple::arm:
  4484. case llvm::Triple::armeb:
  4485. case llvm::Triple::thumb:
  4486. case llvm::Triple::thumbeb:
  4487. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  4488. break;
  4489. default:
  4490. break;
  4491. }
  4492. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4493. options::OPT_mno_restrict_it)) {
  4494. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4495. CmdArgs.push_back("-backend-option");
  4496. CmdArgs.push_back("-arm-restrict-it");
  4497. } else {
  4498. CmdArgs.push_back("-backend-option");
  4499. CmdArgs.push_back("-arm-no-restrict-it");
  4500. }
  4501. } else if (Triple.isOSWindows() &&
  4502. (Triple.getArch() == llvm::Triple::arm ||
  4503. Triple.getArch() == llvm::Triple::thumb)) {
  4504. // Windows on ARM expects restricted IT blocks
  4505. CmdArgs.push_back("-backend-option");
  4506. CmdArgs.push_back("-arm-restrict-it");
  4507. }
  4508. // Forward -f options with positive and negative forms; we translate
  4509. // these by hand.
  4510. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  4511. StringRef fname = A->getValue();
  4512. if (!llvm::sys::fs::exists(fname))
  4513. D.Diag(diag::err_drv_no_such_file) << fname;
  4514. else
  4515. A->render(Args, CmdArgs);
  4516. }
  4517. // -fbuiltin is default unless -mkernel is used.
  4518. bool UseBuiltins =
  4519. Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  4520. !Args.hasArg(options::OPT_mkernel));
  4521. if (!UseBuiltins)
  4522. CmdArgs.push_back("-fno-builtin");
  4523. // -ffreestanding implies -fno-builtin.
  4524. if (Args.hasArg(options::OPT_ffreestanding))
  4525. UseBuiltins = false;
  4526. // Process the -fno-builtin-* options.
  4527. for (const auto &Arg : Args) {
  4528. const Option &O = Arg->getOption();
  4529. if (!O.matches(options::OPT_fno_builtin_))
  4530. continue;
  4531. Arg->claim();
  4532. // If -fno-builtin is specified, then there's no need to pass the option to
  4533. // the frontend.
  4534. if (!UseBuiltins)
  4535. continue;
  4536. StringRef FuncName = Arg->getValue();
  4537. CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
  4538. }
  4539. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4540. options::OPT_fno_assume_sane_operator_new))
  4541. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4542. // -fblocks=0 is default.
  4543. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  4544. getToolChain().IsBlocksDefault()) ||
  4545. (Args.hasArg(options::OPT_fgnu_runtime) &&
  4546. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  4547. !Args.hasArg(options::OPT_fno_blocks))) {
  4548. CmdArgs.push_back("-fblocks");
  4549. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  4550. !getToolChain().hasBlocksRuntime())
  4551. CmdArgs.push_back("-fblocks-runtime-optional");
  4552. }
  4553. // -fmodules enables the use of precompiled modules (off by default).
  4554. // Users can pass -fno-cxx-modules to turn off modules support for
  4555. // C++/Objective-C++ programs.
  4556. bool HaveModules = false;
  4557. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  4558. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  4559. options::OPT_fno_cxx_modules, true);
  4560. if (AllowedInCXX || !types::isCXX(InputType)) {
  4561. CmdArgs.push_back("-fmodules");
  4562. HaveModules = true;
  4563. }
  4564. }
  4565. // -fmodule-maps enables implicit reading of module map files. By default,
  4566. // this is enabled if we are using precompiled modules.
  4567. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  4568. options::OPT_fno_implicit_module_maps, HaveModules)) {
  4569. CmdArgs.push_back("-fimplicit-module-maps");
  4570. }
  4571. // -fmodules-decluse checks that modules used are declared so (off by
  4572. // default).
  4573. if (Args.hasFlag(options::OPT_fmodules_decluse,
  4574. options::OPT_fno_modules_decluse, false)) {
  4575. CmdArgs.push_back("-fmodules-decluse");
  4576. }
  4577. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  4578. // all #included headers are part of modules.
  4579. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  4580. options::OPT_fno_modules_strict_decluse, false)) {
  4581. CmdArgs.push_back("-fmodules-strict-decluse");
  4582. }
  4583. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  4584. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  4585. options::OPT_fno_implicit_modules)) {
  4586. CmdArgs.push_back("-fno-implicit-modules");
  4587. } else if (HaveModules) {
  4588. // -fmodule-cache-path specifies where our implicitly-built module files
  4589. // should be written.
  4590. SmallString<128> Path;
  4591. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  4592. Path = A->getValue();
  4593. if (C.isForDiagnostics()) {
  4594. // When generating crash reports, we want to emit the modules along with
  4595. // the reproduction sources, so we ignore any provided module path.
  4596. Path = Output.getFilename();
  4597. llvm::sys::path::replace_extension(Path, ".cache");
  4598. llvm::sys::path::append(Path, "modules");
  4599. } else if (Path.empty()) {
  4600. // No module path was provided: use the default.
  4601. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  4602. llvm::sys::path::append(Path, "org.llvm.clang.");
  4603. appendUserToPath(Path);
  4604. llvm::sys::path::append(Path, "ModuleCache");
  4605. }
  4606. const char Arg[] = "-fmodules-cache-path=";
  4607. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  4608. CmdArgs.push_back(Args.MakeArgString(Path));
  4609. }
  4610. // -fmodule-name specifies the module that is currently being built (or
  4611. // used for header checking by -fmodule-maps).
  4612. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
  4613. // -fmodule-map-file can be used to specify files containing module
  4614. // definitions.
  4615. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  4616. // -fmodule-file can be used to specify files containing precompiled modules.
  4617. if (HaveModules)
  4618. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  4619. else
  4620. Args.ClaimAllArgs(options::OPT_fmodule_file);
  4621. // When building modules and generating crashdumps, we need to dump a module
  4622. // dependency VFS alongside the output.
  4623. if (HaveModules && C.isForDiagnostics()) {
  4624. SmallString<128> VFSDir(Output.getFilename());
  4625. llvm::sys::path::replace_extension(VFSDir, ".cache");
  4626. // Add the cache directory as a temp so the crash diagnostics pick it up.
  4627. C.addTempFile(Args.MakeArgString(VFSDir));
  4628. llvm::sys::path::append(VFSDir, "vfs");
  4629. CmdArgs.push_back("-module-dependency-dir");
  4630. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  4631. }
  4632. if (HaveModules)
  4633. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  4634. // Pass through all -fmodules-ignore-macro arguments.
  4635. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  4636. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  4637. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  4638. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  4639. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  4640. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  4641. D.Diag(diag::err_drv_argument_not_allowed_with)
  4642. << A->getAsString(Args) << "-fbuild-session-timestamp";
  4643. llvm::sys::fs::file_status Status;
  4644. if (llvm::sys::fs::status(A->getValue(), Status))
  4645. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  4646. CmdArgs.push_back(Args.MakeArgString(
  4647. "-fbuild-session-timestamp=" +
  4648. Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
  4649. }
  4650. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  4651. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  4652. options::OPT_fbuild_session_file))
  4653. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  4654. Args.AddLastArg(CmdArgs,
  4655. options::OPT_fmodules_validate_once_per_build_session);
  4656. }
  4657. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  4658. // -faccess-control is default.
  4659. if (Args.hasFlag(options::OPT_fno_access_control,
  4660. options::OPT_faccess_control, false))
  4661. CmdArgs.push_back("-fno-access-control");
  4662. // -felide-constructors is the default.
  4663. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4664. options::OPT_felide_constructors, false))
  4665. CmdArgs.push_back("-fno-elide-constructors");
  4666. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  4667. if (KernelOrKext || (types::isCXX(InputType) &&
  4668. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  4669. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  4670. CmdArgs.push_back("-fno-rtti");
  4671. // -fshort-enums=0 is default for all architectures except Hexagon.
  4672. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4673. getToolChain().getArch() == llvm::Triple::hexagon))
  4674. CmdArgs.push_back("-fshort-enums");
  4675. // -fsigned-char is default.
  4676. if (Arg *A = Args.getLastArg(
  4677. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  4678. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  4679. if (A->getOption().matches(options::OPT_funsigned_char) ||
  4680. A->getOption().matches(options::OPT_fno_signed_char)) {
  4681. CmdArgs.push_back("-fno-signed-char");
  4682. }
  4683. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  4684. CmdArgs.push_back("-fno-signed-char");
  4685. }
  4686. // -fuse-cxa-atexit is default.
  4687. if (!Args.hasFlag(
  4688. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  4689. !IsWindowsCygnus && !IsWindowsGNU &&
  4690. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  4691. getToolChain().getArch() != llvm::Triple::hexagon &&
  4692. getToolChain().getArch() != llvm::Triple::xcore &&
  4693. ((getToolChain().getTriple().getVendor() !=
  4694. llvm::Triple::MipsTechnologies) ||
  4695. getToolChain().getTriple().hasEnvironment())) ||
  4696. KernelOrKext)
  4697. CmdArgs.push_back("-fno-use-cxa-atexit");
  4698. // -fms-extensions=0 is default.
  4699. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4700. IsWindowsMSVC))
  4701. CmdArgs.push_back("-fms-extensions");
  4702. // -fno-use-line-directives is default.
  4703. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4704. options::OPT_fno_use_line_directives, false))
  4705. CmdArgs.push_back("-fuse-line-directives");
  4706. // -fms-compatibility=0 is default.
  4707. if (Args.hasFlag(options::OPT_fms_compatibility,
  4708. options::OPT_fno_ms_compatibility,
  4709. (IsWindowsMSVC &&
  4710. Args.hasFlag(options::OPT_fms_extensions,
  4711. options::OPT_fno_ms_extensions, true))))
  4712. CmdArgs.push_back("-fms-compatibility");
  4713. // -fms-compatibility-version=18.00 is default.
  4714. VersionTuple MSVT = visualstudio::getMSVCVersion(
  4715. &D, getToolChain(), getToolChain().getTriple(), Args, IsWindowsMSVC);
  4716. if (!MSVT.empty())
  4717. CmdArgs.push_back(
  4718. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4719. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4720. if (ImplyVCPPCXXVer) {
  4721. if (IsMSVC2015Compatible)
  4722. CmdArgs.push_back("-std=c++14");
  4723. else
  4724. CmdArgs.push_back("-std=c++11");
  4725. }
  4726. // -fno-borland-extensions is default.
  4727. if (Args.hasFlag(options::OPT_fborland_extensions,
  4728. options::OPT_fno_borland_extensions, false))
  4729. CmdArgs.push_back("-fborland-extensions");
  4730. // -fno-declspec is default, except for PS4.
  4731. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4732. getToolChain().getTriple().isPS4()))
  4733. CmdArgs.push_back("-fdeclspec");
  4734. else if (Args.hasArg(options::OPT_fno_declspec))
  4735. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  4736. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  4737. // than 19.
  4738. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  4739. options::OPT_fno_threadsafe_statics,
  4740. !IsWindowsMSVC || IsMSVC2015Compatible))
  4741. CmdArgs.push_back("-fno-threadsafe-statics");
  4742. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  4743. // needs it.
  4744. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  4745. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  4746. CmdArgs.push_back("-fdelayed-template-parsing");
  4747. // -fgnu-keywords default varies depending on language; only pass if
  4748. // specified.
  4749. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  4750. options::OPT_fno_gnu_keywords))
  4751. A->render(Args, CmdArgs);
  4752. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  4753. false))
  4754. CmdArgs.push_back("-fgnu89-inline");
  4755. if (Args.hasArg(options::OPT_fno_inline))
  4756. CmdArgs.push_back("-fno-inline");
  4757. if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
  4758. options::OPT_fno_inline_functions))
  4759. InlineArg->render(Args, CmdArgs);
  4760. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  4761. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  4762. // legacy is the default. Except for deployment taget of 10.5,
  4763. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  4764. // gets ignored silently.
  4765. if (objcRuntime.isNonFragile()) {
  4766. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  4767. options::OPT_fno_objc_legacy_dispatch,
  4768. objcRuntime.isLegacyDispatchDefaultForArch(
  4769. getToolChain().getArch()))) {
  4770. if (getToolChain().UseObjCMixedDispatch())
  4771. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  4772. else
  4773. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  4774. }
  4775. }
  4776. // When ObjectiveC legacy runtime is in effect on MacOSX,
  4777. // turn on the option to do Array/Dictionary subscripting
  4778. // by default.
  4779. if (getToolChain().getArch() == llvm::Triple::x86 &&
  4780. getToolChain().getTriple().isMacOSX() &&
  4781. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  4782. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  4783. objcRuntime.isNeXTFamily())
  4784. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  4785. // -fencode-extended-block-signature=1 is default.
  4786. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  4787. CmdArgs.push_back("-fencode-extended-block-signature");
  4788. }
  4789. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  4790. // NOTE: This logic is duplicated in ToolChains.cpp.
  4791. bool ARC = isObjCAutoRefCount(Args);
  4792. if (ARC) {
  4793. getToolChain().CheckObjCARC();
  4794. CmdArgs.push_back("-fobjc-arc");
  4795. // FIXME: It seems like this entire block, and several around it should be
  4796. // wrapped in isObjC, but for now we just use it here as this is where it
  4797. // was being used previously.
  4798. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  4799. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  4800. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  4801. else
  4802. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  4803. }
  4804. // Allow the user to enable full exceptions code emission.
  4805. // We define off for Objective-CC, on for Objective-C++.
  4806. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  4807. options::OPT_fno_objc_arc_exceptions,
  4808. /*default*/ types::isCXX(InputType)))
  4809. CmdArgs.push_back("-fobjc-arc-exceptions");
  4810. }
  4811. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  4812. // rewriter.
  4813. if (rewriteKind != RK_None)
  4814. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  4815. // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
  4816. // takes precedence.
  4817. const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
  4818. if (!GCArg)
  4819. GCArg = Args.getLastArg(options::OPT_fobjc_gc);
  4820. if (GCArg) {
  4821. if (ARC) {
  4822. D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
  4823. } else if (getToolChain().SupportsObjCGC()) {
  4824. GCArg->render(Args, CmdArgs);
  4825. } else {
  4826. // FIXME: We should move this to a hard error.
  4827. D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
  4828. }
  4829. }
  4830. // Pass down -fobjc-weak or -fno-objc-weak if present.
  4831. if (types::isObjC(InputType)) {
  4832. auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
  4833. options::OPT_fno_objc_weak);
  4834. if (!WeakArg) {
  4835. // nothing to do
  4836. } else if (GCArg) {
  4837. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4838. D.Diag(diag::err_objc_weak_with_gc);
  4839. } else if (!objcRuntime.allowsWeak()) {
  4840. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4841. D.Diag(diag::err_objc_weak_unsupported);
  4842. } else {
  4843. WeakArg->render(Args, CmdArgs);
  4844. }
  4845. }
  4846. if (Args.hasFlag(options::OPT_fapplication_extension,
  4847. options::OPT_fno_application_extension, false))
  4848. CmdArgs.push_back("-fapplication-extension");
  4849. // Handle GCC-style exception args.
  4850. if (!C.getDriver().IsCLMode())
  4851. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  4852. CmdArgs);
  4853. if (Args.hasArg(options::OPT_fsjlj_exceptions) ||
  4854. getToolChain().UseSjLjExceptions(Args))
  4855. CmdArgs.push_back("-fsjlj-exceptions");
  4856. // C++ "sane" operator new.
  4857. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4858. options::OPT_fno_assume_sane_operator_new))
  4859. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4860. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  4861. // most platforms.
  4862. if (Args.hasFlag(options::OPT_fsized_deallocation,
  4863. options::OPT_fno_sized_deallocation, false))
  4864. CmdArgs.push_back("-fsized-deallocation");
  4865. // -fconstant-cfstrings is default, and may be subject to argument translation
  4866. // on Darwin.
  4867. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  4868. options::OPT_fno_constant_cfstrings) ||
  4869. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  4870. options::OPT_mno_constant_cfstrings))
  4871. CmdArgs.push_back("-fno-constant-cfstrings");
  4872. // -fshort-wchar default varies depending on platform; only
  4873. // pass if specified.
  4874. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  4875. options::OPT_fno_short_wchar))
  4876. A->render(Args, CmdArgs);
  4877. // -fno-pascal-strings is default, only pass non-default.
  4878. if (Args.hasFlag(options::OPT_fpascal_strings,
  4879. options::OPT_fno_pascal_strings, false))
  4880. CmdArgs.push_back("-fpascal-strings");
  4881. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  4882. // -fno-pack-struct doesn't apply to -fpack-struct=.
  4883. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  4884. std::string PackStructStr = "-fpack-struct=";
  4885. PackStructStr += A->getValue();
  4886. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  4887. } else if (Args.hasFlag(options::OPT_fpack_struct,
  4888. options::OPT_fno_pack_struct, false)) {
  4889. CmdArgs.push_back("-fpack-struct=1");
  4890. }
  4891. // Handle -fmax-type-align=N and -fno-type-align
  4892. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  4893. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  4894. if (!SkipMaxTypeAlign) {
  4895. std::string MaxTypeAlignStr = "-fmax-type-align=";
  4896. MaxTypeAlignStr += A->getValue();
  4897. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4898. }
  4899. } else if (getToolChain().getTriple().isOSDarwin()) {
  4900. if (!SkipMaxTypeAlign) {
  4901. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  4902. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4903. }
  4904. }
  4905. // -fcommon is the default unless compiling kernel code or the target says so
  4906. bool NoCommonDefault =
  4907. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  4908. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  4909. !NoCommonDefault))
  4910. CmdArgs.push_back("-fno-common");
  4911. // -fsigned-bitfields is default, and clang doesn't yet support
  4912. // -funsigned-bitfields.
  4913. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  4914. options::OPT_funsigned_bitfields))
  4915. D.Diag(diag::warn_drv_clang_unsupported)
  4916. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  4917. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  4918. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  4919. D.Diag(diag::err_drv_clang_unsupported)
  4920. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  4921. // -finput_charset=UTF-8 is default. Reject others
  4922. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  4923. StringRef value = inputCharset->getValue();
  4924. if (value != "UTF-8")
  4925. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  4926. << value;
  4927. }
  4928. // -fexec_charset=UTF-8 is default. Reject others
  4929. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  4930. StringRef value = execCharset->getValue();
  4931. if (value != "UTF-8")
  4932. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  4933. << value;
  4934. }
  4935. // -fcaret-diagnostics is default.
  4936. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  4937. options::OPT_fno_caret_diagnostics, true))
  4938. CmdArgs.push_back("-fno-caret-diagnostics");
  4939. // -fdiagnostics-fixit-info is default, only pass non-default.
  4940. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  4941. options::OPT_fno_diagnostics_fixit_info))
  4942. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  4943. // Enable -fdiagnostics-show-option by default.
  4944. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  4945. options::OPT_fno_diagnostics_show_option))
  4946. CmdArgs.push_back("-fdiagnostics-show-option");
  4947. if (const Arg *A =
  4948. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  4949. CmdArgs.push_back("-fdiagnostics-show-category");
  4950. CmdArgs.push_back(A->getValue());
  4951. }
  4952. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  4953. CmdArgs.push_back("-fdiagnostics-format");
  4954. CmdArgs.push_back(A->getValue());
  4955. }
  4956. if (Arg *A = Args.getLastArg(
  4957. options::OPT_fdiagnostics_show_note_include_stack,
  4958. options::OPT_fno_diagnostics_show_note_include_stack)) {
  4959. if (A->getOption().matches(
  4960. options::OPT_fdiagnostics_show_note_include_stack))
  4961. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  4962. else
  4963. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  4964. }
  4965. // Color diagnostics are parsed by the driver directly from argv
  4966. // and later re-parsed to construct this job; claim any possible
  4967. // color diagnostic here to avoid warn_drv_unused_argument and
  4968. // diagnose bad OPT_fdiagnostics_color_EQ values.
  4969. for (Arg *A : Args) {
  4970. const Option &O = A->getOption();
  4971. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  4972. !O.matches(options::OPT_fdiagnostics_color) &&
  4973. !O.matches(options::OPT_fno_color_diagnostics) &&
  4974. !O.matches(options::OPT_fno_diagnostics_color) &&
  4975. !O.matches(options::OPT_fdiagnostics_color_EQ))
  4976. continue;
  4977. if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
  4978. StringRef Value(A->getValue());
  4979. if (Value != "always" && Value != "never" && Value != "auto")
  4980. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4981. << ("-fdiagnostics-color=" + Value).str();
  4982. }
  4983. A->claim();
  4984. }
  4985. if (D.getDiags().getDiagnosticOptions().ShowColors)
  4986. CmdArgs.push_back("-fcolor-diagnostics");
  4987. if (Args.hasArg(options::OPT_fansi_escape_codes))
  4988. CmdArgs.push_back("-fansi-escape-codes");
  4989. if (!Args.hasFlag(options::OPT_fshow_source_location,
  4990. options::OPT_fno_show_source_location))
  4991. CmdArgs.push_back("-fno-show-source-location");
  4992. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  4993. true))
  4994. CmdArgs.push_back("-fno-show-column");
  4995. if (!Args.hasFlag(options::OPT_fspell_checking,
  4996. options::OPT_fno_spell_checking))
  4997. CmdArgs.push_back("-fno-spell-checking");
  4998. // -fno-asm-blocks is default.
  4999. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  5000. false))
  5001. CmdArgs.push_back("-fasm-blocks");
  5002. // -fgnu-inline-asm is default.
  5003. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  5004. options::OPT_fno_gnu_inline_asm, true))
  5005. CmdArgs.push_back("-fno-gnu-inline-asm");
  5006. // Enable vectorization per default according to the optimization level
  5007. // selected. For optimization levels that want vectorization we use the alias
  5008. // option to simplify the hasFlag logic.
  5009. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  5010. OptSpecifier VectorizeAliasOption =
  5011. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  5012. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  5013. options::OPT_fno_vectorize, EnableVec))
  5014. CmdArgs.push_back("-vectorize-loops");
  5015. // -fslp-vectorize is enabled based on the optimization level selected.
  5016. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  5017. OptSpecifier SLPVectAliasOption =
  5018. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  5019. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  5020. options::OPT_fno_slp_vectorize, EnableSLPVec))
  5021. CmdArgs.push_back("-vectorize-slp");
  5022. // -fno-slp-vectorize-aggressive is default.
  5023. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  5024. options::OPT_fno_slp_vectorize_aggressive, false))
  5025. CmdArgs.push_back("-vectorize-slp-aggressive");
  5026. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  5027. A->render(Args, CmdArgs);
  5028. if (Arg *A = Args.getLastArg(
  5029. options::OPT_fsanitize_undefined_strip_path_components_EQ))
  5030. A->render(Args, CmdArgs);
  5031. // -fdollars-in-identifiers default varies depending on platform and
  5032. // language; only pass if specified.
  5033. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  5034. options::OPT_fno_dollars_in_identifiers)) {
  5035. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  5036. CmdArgs.push_back("-fdollars-in-identifiers");
  5037. else
  5038. CmdArgs.push_back("-fno-dollars-in-identifiers");
  5039. }
  5040. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  5041. // practical purposes.
  5042. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  5043. options::OPT_fno_unit_at_a_time)) {
  5044. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  5045. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  5046. }
  5047. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  5048. options::OPT_fno_apple_pragma_pack, false))
  5049. CmdArgs.push_back("-fapple-pragma-pack");
  5050. // le32-specific flags:
  5051. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  5052. // by default.
  5053. if (getToolChain().getArch() == llvm::Triple::le32) {
  5054. CmdArgs.push_back("-fno-math-builtin");
  5055. }
  5056. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  5057. //
  5058. // FIXME: Now that PR4941 has been fixed this can be enabled.
  5059. #if 0
  5060. if (getToolChain().getTriple().isOSDarwin() &&
  5061. (getToolChain().getArch() == llvm::Triple::arm ||
  5062. getToolChain().getArch() == llvm::Triple::thumb)) {
  5063. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  5064. CmdArgs.push_back("-fno-builtin-strcat");
  5065. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  5066. CmdArgs.push_back("-fno-builtin-strcpy");
  5067. }
  5068. #endif
  5069. // Enable rewrite includes if the user's asked for it or if we're generating
  5070. // diagnostics.
  5071. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  5072. // nice to enable this when doing a crashdump for modules as well.
  5073. if (Args.hasFlag(options::OPT_frewrite_includes,
  5074. options::OPT_fno_rewrite_includes, false) ||
  5075. (C.isForDiagnostics() && !HaveModules))
  5076. CmdArgs.push_back("-frewrite-includes");
  5077. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  5078. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  5079. options::OPT_traditional_cpp)) {
  5080. if (isa<PreprocessJobAction>(JA))
  5081. CmdArgs.push_back("-traditional-cpp");
  5082. else
  5083. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  5084. }
  5085. Args.AddLastArg(CmdArgs, options::OPT_dM);
  5086. Args.AddLastArg(CmdArgs, options::OPT_dD);
  5087. // Handle serialized diagnostics.
  5088. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  5089. CmdArgs.push_back("-serialize-diagnostic-file");
  5090. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  5091. }
  5092. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  5093. CmdArgs.push_back("-fretain-comments-from-system-headers");
  5094. // Forward -fcomment-block-commands to -cc1.
  5095. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  5096. // Forward -fparse-all-comments to -cc1.
  5097. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  5098. // Turn -fplugin=name.so into -load name.so
  5099. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  5100. CmdArgs.push_back("-load");
  5101. CmdArgs.push_back(A->getValue());
  5102. A->claim();
  5103. }
  5104. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  5105. // parser.
  5106. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  5107. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  5108. A->claim();
  5109. // We translate this by hand to the -cc1 argument, since nightly test uses
  5110. // it and developers have been trained to spell it with -mllvm.
  5111. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  5112. CmdArgs.push_back("-disable-llvm-optzns");
  5113. } else
  5114. A->render(Args, CmdArgs);
  5115. }
  5116. // With -save-temps, we want to save the unoptimized bitcode output from the
  5117. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  5118. // by the frontend.
  5119. // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
  5120. // has slightly different breakdown between stages.
  5121. // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
  5122. // pristine IR generated by the frontend. Ideally, a new compile action should
  5123. // be added so both IR can be captured.
  5124. if (C.getDriver().isSaveTempsEnabled() &&
  5125. !C.getDriver().embedBitcodeEnabled() && isa<CompileJobAction>(JA))
  5126. CmdArgs.push_back("-disable-llvm-passes");
  5127. if (Output.getType() == types::TY_Dependencies) {
  5128. // Handled with other dependency code.
  5129. } else if (Output.isFilename()) {
  5130. CmdArgs.push_back("-o");
  5131. CmdArgs.push_back(Output.getFilename());
  5132. } else {
  5133. assert(Output.isNothing() && "Invalid output.");
  5134. }
  5135. addDashXForInput(Args, Input, CmdArgs);
  5136. if (Input.isFilename())
  5137. CmdArgs.push_back(Input.getFilename());
  5138. else
  5139. Input.getInputArg().renderAsInput(Args, CmdArgs);
  5140. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  5141. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5142. // Optionally embed the -cc1 level arguments into the debug info, for build
  5143. // analysis.
  5144. if (getToolChain().UseDwarfDebugFlags()) {
  5145. ArgStringList OriginalArgs;
  5146. for (const auto &Arg : Args)
  5147. Arg->render(Args, OriginalArgs);
  5148. SmallString<256> Flags;
  5149. Flags += Exec;
  5150. for (const char *OriginalArg : OriginalArgs) {
  5151. SmallString<128> EscapedArg;
  5152. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5153. Flags += " ";
  5154. Flags += EscapedArg;
  5155. }
  5156. CmdArgs.push_back("-dwarf-debug-flags");
  5157. CmdArgs.push_back(Args.MakeArgString(Flags));
  5158. }
  5159. // Add the split debug info name to the command lines here so we
  5160. // can propagate it to the backend.
  5161. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  5162. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  5163. isa<BackendJobAction>(JA));
  5164. const char *SplitDwarfOut;
  5165. if (SplitDwarf) {
  5166. CmdArgs.push_back("-split-dwarf-file");
  5167. SplitDwarfOut = SplitDebugName(Args, Input);
  5168. CmdArgs.push_back(SplitDwarfOut);
  5169. }
  5170. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  5171. // Include them with -fcuda-include-gpubinary.
  5172. if (IsCuda && Inputs.size() > 1)
  5173. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  5174. CmdArgs.push_back("-fcuda-include-gpubinary");
  5175. CmdArgs.push_back(I->getFilename());
  5176. }
  5177. bool WholeProgramVTables =
  5178. Args.hasFlag(options::OPT_fwhole_program_vtables,
  5179. options::OPT_fno_whole_program_vtables, false);
  5180. if (WholeProgramVTables) {
  5181. if (!D.isUsingLTO())
  5182. D.Diag(diag::err_drv_argument_only_allowed_with)
  5183. << "-fwhole-program-vtables"
  5184. << "-flto";
  5185. CmdArgs.push_back("-fwhole-program-vtables");
  5186. }
  5187. // Finally add the compile command to the compilation.
  5188. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5189. Output.getType() == types::TY_Object &&
  5190. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  5191. auto CLCommand =
  5192. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  5193. C.addCommand(llvm::make_unique<FallbackCommand>(
  5194. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  5195. } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
  5196. isa<PrecompileJobAction>(JA)) {
  5197. // In /fallback builds, run the main compilation even if the pch generation
  5198. // fails, so that the main compilation's fallback to cl.exe runs.
  5199. C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
  5200. CmdArgs, Inputs));
  5201. } else {
  5202. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5203. }
  5204. // Handle the debug info splitting at object creation time if we're
  5205. // creating an object.
  5206. // TODO: Currently only works on linux with newer objcopy.
  5207. if (SplitDwarf && Output.getType() == types::TY_Object)
  5208. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  5209. if (Arg *A = Args.getLastArg(options::OPT_pg))
  5210. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  5211. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  5212. << A->getAsString(Args);
  5213. // Claim some arguments which clang supports automatically.
  5214. // -fpch-preprocess is used with gcc to add a special marker in the output to
  5215. // include the PCH file. Clang's PTH solution is completely transparent, so we
  5216. // do not need to deal with it at all.
  5217. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  5218. // Claim some arguments which clang doesn't support, but we don't
  5219. // care to warn the user about.
  5220. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  5221. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  5222. // Disable warnings for clang -E -emit-llvm foo.c
  5223. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5224. }
  5225. /// Add options related to the Objective-C runtime/ABI.
  5226. ///
  5227. /// Returns true if the runtime is non-fragile.
  5228. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  5229. ArgStringList &cmdArgs,
  5230. RewriteKind rewriteKind) const {
  5231. // Look for the controlling runtime option.
  5232. Arg *runtimeArg =
  5233. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  5234. options::OPT_fobjc_runtime_EQ);
  5235. // Just forward -fobjc-runtime= to the frontend. This supercedes
  5236. // options about fragility.
  5237. if (runtimeArg &&
  5238. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  5239. ObjCRuntime runtime;
  5240. StringRef value = runtimeArg->getValue();
  5241. if (runtime.tryParse(value)) {
  5242. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  5243. << value;
  5244. }
  5245. runtimeArg->render(args, cmdArgs);
  5246. return runtime;
  5247. }
  5248. // Otherwise, we'll need the ABI "version". Version numbers are
  5249. // slightly confusing for historical reasons:
  5250. // 1 - Traditional "fragile" ABI
  5251. // 2 - Non-fragile ABI, version 1
  5252. // 3 - Non-fragile ABI, version 2
  5253. unsigned objcABIVersion = 1;
  5254. // If -fobjc-abi-version= is present, use that to set the version.
  5255. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  5256. StringRef value = abiArg->getValue();
  5257. if (value == "1")
  5258. objcABIVersion = 1;
  5259. else if (value == "2")
  5260. objcABIVersion = 2;
  5261. else if (value == "3")
  5262. objcABIVersion = 3;
  5263. else
  5264. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  5265. } else {
  5266. // Otherwise, determine if we are using the non-fragile ABI.
  5267. bool nonFragileABIIsDefault =
  5268. (rewriteKind == RK_NonFragile ||
  5269. (rewriteKind == RK_None &&
  5270. getToolChain().IsObjCNonFragileABIDefault()));
  5271. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  5272. options::OPT_fno_objc_nonfragile_abi,
  5273. nonFragileABIIsDefault)) {
  5274. // Determine the non-fragile ABI version to use.
  5275. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  5276. unsigned nonFragileABIVersion = 1;
  5277. #else
  5278. unsigned nonFragileABIVersion = 2;
  5279. #endif
  5280. if (Arg *abiArg =
  5281. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  5282. StringRef value = abiArg->getValue();
  5283. if (value == "1")
  5284. nonFragileABIVersion = 1;
  5285. else if (value == "2")
  5286. nonFragileABIVersion = 2;
  5287. else
  5288. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  5289. << value;
  5290. }
  5291. objcABIVersion = 1 + nonFragileABIVersion;
  5292. } else {
  5293. objcABIVersion = 1;
  5294. }
  5295. }
  5296. // We don't actually care about the ABI version other than whether
  5297. // it's non-fragile.
  5298. bool isNonFragile = objcABIVersion != 1;
  5299. // If we have no runtime argument, ask the toolchain for its default runtime.
  5300. // However, the rewriter only really supports the Mac runtime, so assume that.
  5301. ObjCRuntime runtime;
  5302. if (!runtimeArg) {
  5303. switch (rewriteKind) {
  5304. case RK_None:
  5305. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5306. break;
  5307. case RK_Fragile:
  5308. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  5309. break;
  5310. case RK_NonFragile:
  5311. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5312. break;
  5313. }
  5314. // -fnext-runtime
  5315. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  5316. // On Darwin, make this use the default behavior for the toolchain.
  5317. if (getToolChain().getTriple().isOSDarwin()) {
  5318. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5319. // Otherwise, build for a generic macosx port.
  5320. } else {
  5321. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5322. }
  5323. // -fgnu-runtime
  5324. } else {
  5325. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  5326. // Legacy behaviour is to target the gnustep runtime if we are in
  5327. // non-fragile mode or the GCC runtime in fragile mode.
  5328. if (isNonFragile)
  5329. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  5330. else
  5331. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  5332. }
  5333. cmdArgs.push_back(
  5334. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  5335. return runtime;
  5336. }
  5337. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  5338. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  5339. I += HaveDash;
  5340. return !HaveDash;
  5341. }
  5342. namespace {
  5343. struct EHFlags {
  5344. bool Synch = false;
  5345. bool Asynch = false;
  5346. bool NoUnwindC = false;
  5347. };
  5348. } // end anonymous namespace
  5349. /// /EH controls whether to run destructor cleanups when exceptions are
  5350. /// thrown. There are three modifiers:
  5351. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  5352. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  5353. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  5354. /// - c: Assume that extern "C" functions are implicitly nounwind.
  5355. /// The default is /EHs-c-, meaning cleanups are disabled.
  5356. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  5357. EHFlags EH;
  5358. std::vector<std::string> EHArgs =
  5359. Args.getAllArgValues(options::OPT__SLASH_EH);
  5360. for (auto EHVal : EHArgs) {
  5361. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  5362. switch (EHVal[I]) {
  5363. case 'a':
  5364. EH.Asynch = maybeConsumeDash(EHVal, I);
  5365. if (EH.Asynch)
  5366. EH.Synch = false;
  5367. continue;
  5368. case 'c':
  5369. EH.NoUnwindC = maybeConsumeDash(EHVal, I);
  5370. continue;
  5371. case 's':
  5372. EH.Synch = maybeConsumeDash(EHVal, I);
  5373. if (EH.Synch)
  5374. EH.Asynch = false;
  5375. continue;
  5376. default:
  5377. break;
  5378. }
  5379. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  5380. break;
  5381. }
  5382. }
  5383. // The /GX, /GX- flags are only processed if there are not /EH flags.
  5384. // The default is that /GX is not specified.
  5385. if (EHArgs.empty() &&
  5386. Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
  5387. /*default=*/false)) {
  5388. EH.Synch = true;
  5389. EH.NoUnwindC = true;
  5390. }
  5391. return EH;
  5392. }
  5393. void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
  5394. ArgStringList &CmdArgs,
  5395. codegenoptions::DebugInfoKind *DebugInfoKind,
  5396. bool *EmitCodeView) const {
  5397. unsigned RTOptionID = options::OPT__SLASH_MT;
  5398. if (Args.hasArg(options::OPT__SLASH_LDd))
  5399. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  5400. // but defining _DEBUG is sticky.
  5401. RTOptionID = options::OPT__SLASH_MTd;
  5402. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  5403. RTOptionID = A->getOption().getID();
  5404. StringRef FlagForCRT;
  5405. switch (RTOptionID) {
  5406. case options::OPT__SLASH_MD:
  5407. if (Args.hasArg(options::OPT__SLASH_LDd))
  5408. CmdArgs.push_back("-D_DEBUG");
  5409. CmdArgs.push_back("-D_MT");
  5410. CmdArgs.push_back("-D_DLL");
  5411. FlagForCRT = "--dependent-lib=msvcrt";
  5412. break;
  5413. case options::OPT__SLASH_MDd:
  5414. CmdArgs.push_back("-D_DEBUG");
  5415. CmdArgs.push_back("-D_MT");
  5416. CmdArgs.push_back("-D_DLL");
  5417. FlagForCRT = "--dependent-lib=msvcrtd";
  5418. break;
  5419. case options::OPT__SLASH_MT:
  5420. if (Args.hasArg(options::OPT__SLASH_LDd))
  5421. CmdArgs.push_back("-D_DEBUG");
  5422. CmdArgs.push_back("-D_MT");
  5423. CmdArgs.push_back("-flto-visibility-public-std");
  5424. FlagForCRT = "--dependent-lib=libcmt";
  5425. break;
  5426. case options::OPT__SLASH_MTd:
  5427. CmdArgs.push_back("-D_DEBUG");
  5428. CmdArgs.push_back("-D_MT");
  5429. CmdArgs.push_back("-flto-visibility-public-std");
  5430. FlagForCRT = "--dependent-lib=libcmtd";
  5431. break;
  5432. default:
  5433. llvm_unreachable("Unexpected option ID.");
  5434. }
  5435. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  5436. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  5437. } else {
  5438. CmdArgs.push_back(FlagForCRT.data());
  5439. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  5440. // users want. The /Za flag to cl.exe turns this off, but it's not
  5441. // implemented in clang.
  5442. CmdArgs.push_back("--dependent-lib=oldnames");
  5443. }
  5444. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  5445. // would produce interleaved output, so ignore /showIncludes in such cases.
  5446. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  5447. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  5448. A->render(Args, CmdArgs);
  5449. // This controls whether or not we emit RTTI data for polymorphic types.
  5450. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  5451. /*default=*/false))
  5452. CmdArgs.push_back("-fno-rtti-data");
  5453. // Emit CodeView if -Z7 is present.
  5454. *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
  5455. if (*EmitCodeView)
  5456. *DebugInfoKind = codegenoptions::LimitedDebugInfo;
  5457. if (*EmitCodeView)
  5458. CmdArgs.push_back("-gcodeview");
  5459. const Driver &D = getToolChain().getDriver();
  5460. EHFlags EH = parseClangCLEHFlags(D, Args);
  5461. if (EH.Synch || EH.Asynch) {
  5462. if (types::isCXX(InputType))
  5463. CmdArgs.push_back("-fcxx-exceptions");
  5464. CmdArgs.push_back("-fexceptions");
  5465. }
  5466. if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
  5467. CmdArgs.push_back("-fexternc-nounwind");
  5468. // /EP should expand to -E -P.
  5469. if (Args.hasArg(options::OPT__SLASH_EP)) {
  5470. CmdArgs.push_back("-E");
  5471. CmdArgs.push_back("-P");
  5472. }
  5473. unsigned VolatileOptionID;
  5474. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  5475. getToolChain().getArch() == llvm::Triple::x86)
  5476. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  5477. else
  5478. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  5479. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  5480. VolatileOptionID = A->getOption().getID();
  5481. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  5482. CmdArgs.push_back("-fms-volatile");
  5483. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  5484. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  5485. if (MostGeneralArg && BestCaseArg)
  5486. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5487. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  5488. if (MostGeneralArg) {
  5489. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  5490. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  5491. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  5492. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  5493. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  5494. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  5495. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5496. << FirstConflict->getAsString(Args)
  5497. << SecondConflict->getAsString(Args);
  5498. if (SingleArg)
  5499. CmdArgs.push_back("-fms-memptr-rep=single");
  5500. else if (MultipleArg)
  5501. CmdArgs.push_back("-fms-memptr-rep=multiple");
  5502. else
  5503. CmdArgs.push_back("-fms-memptr-rep=virtual");
  5504. }
  5505. if (Args.getLastArg(options::OPT__SLASH_Gd))
  5506. CmdArgs.push_back("-fdefault-calling-conv=cdecl");
  5507. else if (Args.getLastArg(options::OPT__SLASH_Gr))
  5508. CmdArgs.push_back("-fdefault-calling-conv=fastcall");
  5509. else if (Args.getLastArg(options::OPT__SLASH_Gz))
  5510. CmdArgs.push_back("-fdefault-calling-conv=stdcall");
  5511. else if (Args.getLastArg(options::OPT__SLASH_Gv))
  5512. CmdArgs.push_back("-fdefault-calling-conv=vectorcall");
  5513. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  5514. A->render(Args, CmdArgs);
  5515. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  5516. CmdArgs.push_back("-fdiagnostics-format");
  5517. if (Args.hasArg(options::OPT__SLASH_fallback))
  5518. CmdArgs.push_back("msvc-fallback");
  5519. else
  5520. CmdArgs.push_back("msvc");
  5521. }
  5522. }
  5523. visualstudio::Compiler *Clang::getCLFallback() const {
  5524. if (!CLFallback)
  5525. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  5526. return CLFallback.get();
  5527. }
  5528. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  5529. ArgStringList &CmdArgs) const {
  5530. StringRef CPUName;
  5531. StringRef ABIName;
  5532. const llvm::Triple &Triple = getToolChain().getTriple();
  5533. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  5534. CmdArgs.push_back("-target-abi");
  5535. CmdArgs.push_back(ABIName.data());
  5536. }
  5537. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  5538. const InputInfo &Output, const InputInfoList &Inputs,
  5539. const ArgList &Args,
  5540. const char *LinkingOutput) const {
  5541. ArgStringList CmdArgs;
  5542. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5543. const InputInfo &Input = Inputs[0];
  5544. std::string TripleStr =
  5545. getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
  5546. const llvm::Triple Triple(TripleStr);
  5547. // Don't warn about "clang -w -c foo.s"
  5548. Args.ClaimAllArgs(options::OPT_w);
  5549. // and "clang -emit-llvm -c foo.s"
  5550. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5551. claimNoWarnArgs(Args);
  5552. // Invoke ourselves in -cc1as mode.
  5553. //
  5554. // FIXME: Implement custom jobs for internal actions.
  5555. CmdArgs.push_back("-cc1as");
  5556. // Add the "effective" target triple.
  5557. CmdArgs.push_back("-triple");
  5558. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  5559. // Set the output mode, we currently only expect to be used as a real
  5560. // assembler.
  5561. CmdArgs.push_back("-filetype");
  5562. CmdArgs.push_back("obj");
  5563. // Set the main file name, so that debug info works even with
  5564. // -save-temps or preprocessed assembly.
  5565. CmdArgs.push_back("-main-file-name");
  5566. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  5567. // Add the target cpu
  5568. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  5569. if (!CPU.empty()) {
  5570. CmdArgs.push_back("-target-cpu");
  5571. CmdArgs.push_back(Args.MakeArgString(CPU));
  5572. }
  5573. // Add the target features
  5574. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  5575. // Ignore explicit -force_cpusubtype_ALL option.
  5576. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  5577. // Pass along any -I options so we get proper .include search paths.
  5578. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  5579. // Determine the original source input.
  5580. const Action *SourceAction = &JA;
  5581. while (SourceAction->getKind() != Action::InputClass) {
  5582. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5583. SourceAction = SourceAction->getInputs()[0];
  5584. }
  5585. // Forward -g and handle debug info related flags, assuming we are dealing
  5586. // with an actual assembly file.
  5587. bool WantDebug = false;
  5588. unsigned DwarfVersion = 0;
  5589. Args.ClaimAllArgs(options::OPT_g_Group);
  5590. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  5591. WantDebug = !A->getOption().matches(options::OPT_g0) &&
  5592. !A->getOption().matches(options::OPT_ggdb0);
  5593. if (WantDebug)
  5594. DwarfVersion = DwarfVersionNum(A->getSpelling());
  5595. }
  5596. if (DwarfVersion == 0)
  5597. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  5598. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  5599. if (SourceAction->getType() == types::TY_Asm ||
  5600. SourceAction->getType() == types::TY_PP_Asm) {
  5601. // You might think that it would be ok to set DebugInfoKind outside of
  5602. // the guard for source type, however there is a test which asserts
  5603. // that some assembler invocation receives no -debug-info-kind,
  5604. // and it's not clear whether that test is just overly restrictive.
  5605. DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
  5606. : codegenoptions::NoDebugInfo);
  5607. // Add the -fdebug-compilation-dir flag if needed.
  5608. addDebugCompDirArg(Args, CmdArgs);
  5609. // Set the AT_producer to the clang version when using the integrated
  5610. // assembler on assembly source files.
  5611. CmdArgs.push_back("-dwarf-debug-producer");
  5612. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  5613. // And pass along -I options
  5614. Args.AddAllArgs(CmdArgs, options::OPT_I);
  5615. }
  5616. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  5617. llvm::DebuggerKind::Default);
  5618. // Handle -fPIC et al -- the relocation-model affects the assembler
  5619. // for some targets.
  5620. llvm::Reloc::Model RelocationModel;
  5621. unsigned PICLevel;
  5622. bool IsPIE;
  5623. std::tie(RelocationModel, PICLevel, IsPIE) =
  5624. ParsePICArgs(getToolChain(), Triple, Args);
  5625. const char *RMName = RelocationModelName(RelocationModel);
  5626. if (RMName) {
  5627. CmdArgs.push_back("-mrelocation-model");
  5628. CmdArgs.push_back(RMName);
  5629. }
  5630. // Optionally embed the -cc1as level arguments into the debug info, for build
  5631. // analysis.
  5632. if (getToolChain().UseDwarfDebugFlags()) {
  5633. ArgStringList OriginalArgs;
  5634. for (const auto &Arg : Args)
  5635. Arg->render(Args, OriginalArgs);
  5636. SmallString<256> Flags;
  5637. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5638. Flags += Exec;
  5639. for (const char *OriginalArg : OriginalArgs) {
  5640. SmallString<128> EscapedArg;
  5641. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5642. Flags += " ";
  5643. Flags += EscapedArg;
  5644. }
  5645. CmdArgs.push_back("-dwarf-debug-flags");
  5646. CmdArgs.push_back(Args.MakeArgString(Flags));
  5647. }
  5648. // FIXME: Add -static support, once we have it.
  5649. // Add target specific flags.
  5650. switch (getToolChain().getArch()) {
  5651. default:
  5652. break;
  5653. case llvm::Triple::mips:
  5654. case llvm::Triple::mipsel:
  5655. case llvm::Triple::mips64:
  5656. case llvm::Triple::mips64el:
  5657. AddMIPSTargetArgs(Args, CmdArgs);
  5658. break;
  5659. }
  5660. // Consume all the warning flags. Usually this would be handled more
  5661. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  5662. // doesn't handle that so rather than warning about unused flags that are
  5663. // actually used, we'll lie by omission instead.
  5664. // FIXME: Stop lying and consume only the appropriate driver flags
  5665. Args.ClaimAllArgs(options::OPT_W_Group);
  5666. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  5667. getToolChain().getDriver());
  5668. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  5669. assert(Output.isFilename() && "Unexpected lipo output.");
  5670. CmdArgs.push_back("-o");
  5671. CmdArgs.push_back(Output.getFilename());
  5672. assert(Input.isFilename() && "Invalid input.");
  5673. CmdArgs.push_back(Input.getFilename());
  5674. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5675. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5676. // Handle the debug info splitting at object creation time if we're
  5677. // creating an object.
  5678. // TODO: Currently only works on linux with newer objcopy.
  5679. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  5680. getToolChain().getTriple().isOSLinux())
  5681. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  5682. SplitDebugName(Args, Input));
  5683. }
  5684. void GnuTool::anchor() {}
  5685. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  5686. const InputInfo &Output,
  5687. const InputInfoList &Inputs, const ArgList &Args,
  5688. const char *LinkingOutput) const {
  5689. const Driver &D = getToolChain().getDriver();
  5690. ArgStringList CmdArgs;
  5691. for (const auto &A : Args) {
  5692. if (forwardToGCC(A->getOption())) {
  5693. // It is unfortunate that we have to claim here, as this means
  5694. // we will basically never report anything interesting for
  5695. // platforms using a generic gcc, even if we are just using gcc
  5696. // to get to the assembler.
  5697. A->claim();
  5698. // Don't forward any -g arguments to assembly steps.
  5699. if (isa<AssembleJobAction>(JA) &&
  5700. A->getOption().matches(options::OPT_g_Group))
  5701. continue;
  5702. // Don't forward any -W arguments to assembly and link steps.
  5703. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  5704. A->getOption().matches(options::OPT_W_Group))
  5705. continue;
  5706. A->render(Args, CmdArgs);
  5707. }
  5708. }
  5709. RenderExtraToolArgs(JA, CmdArgs);
  5710. // If using a driver driver, force the arch.
  5711. if (getToolChain().getTriple().isOSDarwin()) {
  5712. CmdArgs.push_back("-arch");
  5713. CmdArgs.push_back(
  5714. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  5715. }
  5716. // Try to force gcc to match the tool chain we want, if we recognize
  5717. // the arch.
  5718. //
  5719. // FIXME: The triple class should directly provide the information we want
  5720. // here.
  5721. switch (getToolChain().getArch()) {
  5722. default:
  5723. break;
  5724. case llvm::Triple::x86:
  5725. case llvm::Triple::ppc:
  5726. CmdArgs.push_back("-m32");
  5727. break;
  5728. case llvm::Triple::x86_64:
  5729. case llvm::Triple::ppc64:
  5730. case llvm::Triple::ppc64le:
  5731. CmdArgs.push_back("-m64");
  5732. break;
  5733. case llvm::Triple::sparcel:
  5734. CmdArgs.push_back("-EL");
  5735. break;
  5736. }
  5737. if (Output.isFilename()) {
  5738. CmdArgs.push_back("-o");
  5739. CmdArgs.push_back(Output.getFilename());
  5740. } else {
  5741. assert(Output.isNothing() && "Unexpected output");
  5742. CmdArgs.push_back("-fsyntax-only");
  5743. }
  5744. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5745. // Only pass -x if gcc will understand it; otherwise hope gcc
  5746. // understands the suffix correctly. The main use case this would go
  5747. // wrong in is for linker inputs if they happened to have an odd
  5748. // suffix; really the only way to get this to happen is a command
  5749. // like '-x foobar a.c' which will treat a.c like a linker input.
  5750. //
  5751. // FIXME: For the linker case specifically, can we safely convert
  5752. // inputs into '-Wl,' options?
  5753. for (const auto &II : Inputs) {
  5754. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5755. if (types::isLLVMIR(II.getType()))
  5756. D.Diag(diag::err_drv_no_linker_llvm_support)
  5757. << getToolChain().getTripleString();
  5758. else if (II.getType() == types::TY_AST)
  5759. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  5760. else if (II.getType() == types::TY_ModuleFile)
  5761. D.Diag(diag::err_drv_no_module_support)
  5762. << getToolChain().getTripleString();
  5763. if (types::canTypeBeUserSpecified(II.getType())) {
  5764. CmdArgs.push_back("-x");
  5765. CmdArgs.push_back(types::getTypeName(II.getType()));
  5766. }
  5767. if (II.isFilename())
  5768. CmdArgs.push_back(II.getFilename());
  5769. else {
  5770. const Arg &A = II.getInputArg();
  5771. // Reverse translate some rewritten options.
  5772. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  5773. CmdArgs.push_back("-lstdc++");
  5774. continue;
  5775. }
  5776. // Don't render as input, we need gcc to do the translations.
  5777. A.render(Args, CmdArgs);
  5778. }
  5779. }
  5780. const std::string &customGCCName = D.getCCCGenericGCCName();
  5781. const char *GCCName;
  5782. if (!customGCCName.empty())
  5783. GCCName = customGCCName.c_str();
  5784. else if (D.CCCIsCXX()) {
  5785. GCCName = "g++";
  5786. } else
  5787. GCCName = "gcc";
  5788. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5789. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5790. }
  5791. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  5792. ArgStringList &CmdArgs) const {
  5793. CmdArgs.push_back("-E");
  5794. }
  5795. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  5796. ArgStringList &CmdArgs) const {
  5797. const Driver &D = getToolChain().getDriver();
  5798. switch (JA.getType()) {
  5799. // If -flto, etc. are present then make sure not to force assembly output.
  5800. case types::TY_LLVM_IR:
  5801. case types::TY_LTO_IR:
  5802. case types::TY_LLVM_BC:
  5803. case types::TY_LTO_BC:
  5804. CmdArgs.push_back("-c");
  5805. break;
  5806. // We assume we've got an "integrated" assembler in that gcc will produce an
  5807. // object file itself.
  5808. case types::TY_Object:
  5809. CmdArgs.push_back("-c");
  5810. break;
  5811. case types::TY_PP_Asm:
  5812. CmdArgs.push_back("-S");
  5813. break;
  5814. case types::TY_Nothing:
  5815. CmdArgs.push_back("-fsyntax-only");
  5816. break;
  5817. default:
  5818. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  5819. }
  5820. }
  5821. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  5822. ArgStringList &CmdArgs) const {
  5823. // The types are (hopefully) good enough.
  5824. }
  5825. // Hexagon tools start.
  5826. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  5827. ArgStringList &CmdArgs) const {
  5828. }
  5829. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5830. const InputInfo &Output,
  5831. const InputInfoList &Inputs,
  5832. const ArgList &Args,
  5833. const char *LinkingOutput) const {
  5834. claimNoWarnArgs(Args);
  5835. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5836. const Driver &D = HTC.getDriver();
  5837. ArgStringList CmdArgs;
  5838. std::string MArchString = "-march=hexagon";
  5839. CmdArgs.push_back(Args.MakeArgString(MArchString));
  5840. RenderExtraToolArgs(JA, CmdArgs);
  5841. std::string AsName = "hexagon-llvm-mc";
  5842. std::string MCpuString = "-mcpu=hexagon" +
  5843. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5844. CmdArgs.push_back("-filetype=obj");
  5845. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5846. if (Output.isFilename()) {
  5847. CmdArgs.push_back("-o");
  5848. CmdArgs.push_back(Output.getFilename());
  5849. } else {
  5850. assert(Output.isNothing() && "Unexpected output");
  5851. CmdArgs.push_back("-fsyntax-only");
  5852. }
  5853. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5854. std::string N = llvm::utostr(G.getValue());
  5855. CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
  5856. }
  5857. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5858. // Only pass -x if gcc will understand it; otherwise hope gcc
  5859. // understands the suffix correctly. The main use case this would go
  5860. // wrong in is for linker inputs if they happened to have an odd
  5861. // suffix; really the only way to get this to happen is a command
  5862. // like '-x foobar a.c' which will treat a.c like a linker input.
  5863. //
  5864. // FIXME: For the linker case specifically, can we safely convert
  5865. // inputs into '-Wl,' options?
  5866. for (const auto &II : Inputs) {
  5867. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5868. if (types::isLLVMIR(II.getType()))
  5869. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  5870. << HTC.getTripleString();
  5871. else if (II.getType() == types::TY_AST)
  5872. D.Diag(clang::diag::err_drv_no_ast_support)
  5873. << HTC.getTripleString();
  5874. else if (II.getType() == types::TY_ModuleFile)
  5875. D.Diag(diag::err_drv_no_module_support)
  5876. << HTC.getTripleString();
  5877. if (II.isFilename())
  5878. CmdArgs.push_back(II.getFilename());
  5879. else
  5880. // Don't render as input, we need gcc to do the translations.
  5881. // FIXME: What is this?
  5882. II.getInputArg().render(Args, CmdArgs);
  5883. }
  5884. auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
  5885. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5886. }
  5887. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  5888. ArgStringList &CmdArgs) const {
  5889. }
  5890. static void
  5891. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  5892. const toolchains::HexagonToolChain &HTC,
  5893. const InputInfo &Output, const InputInfoList &Inputs,
  5894. const ArgList &Args, ArgStringList &CmdArgs,
  5895. const char *LinkingOutput) {
  5896. const Driver &D = HTC.getDriver();
  5897. //----------------------------------------------------------------------------
  5898. //
  5899. //----------------------------------------------------------------------------
  5900. bool IsStatic = Args.hasArg(options::OPT_static);
  5901. bool IsShared = Args.hasArg(options::OPT_shared);
  5902. bool IsPIE = Args.hasArg(options::OPT_pie);
  5903. bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
  5904. bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  5905. bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  5906. bool UseG0 = false;
  5907. bool UseShared = IsShared && !IsStatic;
  5908. //----------------------------------------------------------------------------
  5909. // Silence warnings for various options
  5910. //----------------------------------------------------------------------------
  5911. Args.ClaimAllArgs(options::OPT_g_Group);
  5912. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5913. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  5914. // handled somewhere else.
  5915. Args.ClaimAllArgs(options::OPT_static_libgcc);
  5916. //----------------------------------------------------------------------------
  5917. //
  5918. //----------------------------------------------------------------------------
  5919. if (Args.hasArg(options::OPT_s))
  5920. CmdArgs.push_back("-s");
  5921. if (Args.hasArg(options::OPT_r))
  5922. CmdArgs.push_back("-r");
  5923. for (const auto &Opt : HTC.ExtraOpts)
  5924. CmdArgs.push_back(Opt.c_str());
  5925. CmdArgs.push_back("-march=hexagon");
  5926. std::string CpuVer =
  5927. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5928. std::string MCpuString = "-mcpu=hexagon" + CpuVer;
  5929. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5930. if (IsShared) {
  5931. CmdArgs.push_back("-shared");
  5932. // The following should be the default, but doing as hexagon-gcc does.
  5933. CmdArgs.push_back("-call_shared");
  5934. }
  5935. if (IsStatic)
  5936. CmdArgs.push_back("-static");
  5937. if (IsPIE && !IsShared)
  5938. CmdArgs.push_back("-pie");
  5939. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5940. std::string N = llvm::utostr(G.getValue());
  5941. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
  5942. UseG0 = G.getValue() == 0;
  5943. }
  5944. //----------------------------------------------------------------------------
  5945. //
  5946. //----------------------------------------------------------------------------
  5947. CmdArgs.push_back("-o");
  5948. CmdArgs.push_back(Output.getFilename());
  5949. //----------------------------------------------------------------------------
  5950. // moslib
  5951. //----------------------------------------------------------------------------
  5952. std::vector<std::string> OsLibs;
  5953. bool HasStandalone = false;
  5954. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  5955. A->claim();
  5956. OsLibs.emplace_back(A->getValue());
  5957. HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
  5958. }
  5959. if (OsLibs.empty()) {
  5960. OsLibs.push_back("standalone");
  5961. HasStandalone = true;
  5962. }
  5963. //----------------------------------------------------------------------------
  5964. // Start Files
  5965. //----------------------------------------------------------------------------
  5966. const std::string MCpuSuffix = "/" + CpuVer;
  5967. const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
  5968. const std::string RootDir =
  5969. HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
  5970. const std::string StartSubDir =
  5971. "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
  5972. auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
  5973. const char *Name) -> std::string {
  5974. std::string RelName = SubDir + Name;
  5975. std::string P = HTC.GetFilePath(RelName.c_str());
  5976. if (llvm::sys::fs::exists(P))
  5977. return P;
  5978. return RootDir + RelName;
  5979. };
  5980. if (IncStdLib && IncStartFiles) {
  5981. if (!IsShared) {
  5982. if (HasStandalone) {
  5983. std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
  5984. CmdArgs.push_back(Args.MakeArgString(Crt0SA));
  5985. }
  5986. std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
  5987. CmdArgs.push_back(Args.MakeArgString(Crt0));
  5988. }
  5989. std::string Init = UseShared
  5990. ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
  5991. : Find(RootDir, StartSubDir, "/init.o");
  5992. CmdArgs.push_back(Args.MakeArgString(Init));
  5993. }
  5994. //----------------------------------------------------------------------------
  5995. // Library Search Paths
  5996. //----------------------------------------------------------------------------
  5997. const ToolChain::path_list &LibPaths = HTC.getFilePaths();
  5998. for (const auto &LibPath : LibPaths)
  5999. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  6000. //----------------------------------------------------------------------------
  6001. //
  6002. //----------------------------------------------------------------------------
  6003. Args.AddAllArgs(CmdArgs,
  6004. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  6005. options::OPT_t, options::OPT_u_Group});
  6006. AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
  6007. //----------------------------------------------------------------------------
  6008. // Libraries
  6009. //----------------------------------------------------------------------------
  6010. if (IncStdLib && IncDefLibs) {
  6011. if (D.CCCIsCXX()) {
  6012. HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
  6013. CmdArgs.push_back("-lm");
  6014. }
  6015. CmdArgs.push_back("--start-group");
  6016. if (!IsShared) {
  6017. for (const std::string &Lib : OsLibs)
  6018. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  6019. CmdArgs.push_back("-lc");
  6020. }
  6021. CmdArgs.push_back("-lgcc");
  6022. CmdArgs.push_back("--end-group");
  6023. }
  6024. //----------------------------------------------------------------------------
  6025. // End files
  6026. //----------------------------------------------------------------------------
  6027. if (IncStdLib && IncStartFiles) {
  6028. std::string Fini = UseShared
  6029. ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
  6030. : Find(RootDir, StartSubDir, "/fini.o");
  6031. CmdArgs.push_back(Args.MakeArgString(Fini));
  6032. }
  6033. }
  6034. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6035. const InputInfo &Output,
  6036. const InputInfoList &Inputs,
  6037. const ArgList &Args,
  6038. const char *LinkingOutput) const {
  6039. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  6040. ArgStringList CmdArgs;
  6041. constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
  6042. LinkingOutput);
  6043. std::string Linker = HTC.GetProgramPath("hexagon-link");
  6044. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  6045. CmdArgs, Inputs));
  6046. }
  6047. // Hexagon tools end.
  6048. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6049. const InputInfo &Output,
  6050. const InputInfoList &Inputs,
  6051. const ArgList &Args,
  6052. const char *LinkingOutput) const {
  6053. std::string Linker = getToolChain().GetProgramPath(getShortName());
  6054. ArgStringList CmdArgs;
  6055. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6056. CmdArgs.push_back("-shared");
  6057. CmdArgs.push_back("-o");
  6058. CmdArgs.push_back(Output.getFilename());
  6059. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  6060. CmdArgs, Inputs));
  6061. }
  6062. // AMDGPU tools end.
  6063. wasm::Linker::Linker(const ToolChain &TC)
  6064. : GnuTool("wasm::Linker", "lld", TC) {}
  6065. bool wasm::Linker::isLinkJob() const {
  6066. return true;
  6067. }
  6068. bool wasm::Linker::hasIntegratedCPP() const {
  6069. return false;
  6070. }
  6071. void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6072. const InputInfo &Output,
  6073. const InputInfoList &Inputs,
  6074. const ArgList &Args,
  6075. const char *LinkingOutput) const {
  6076. const ToolChain &ToolChain = getToolChain();
  6077. const Driver &D = ToolChain.getDriver();
  6078. const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
  6079. ArgStringList CmdArgs;
  6080. CmdArgs.push_back("-flavor");
  6081. CmdArgs.push_back("ld");
  6082. // Enable garbage collection of unused input sections by default, since code
  6083. // size is of particular importance. This is significantly facilitated by
  6084. // the enabling of -ffunction-sections and -fdata-sections in
  6085. // Clang::ConstructJob.
  6086. if (areOptimizationsEnabled(Args))
  6087. CmdArgs.push_back("--gc-sections");
  6088. if (Args.hasArg(options::OPT_rdynamic))
  6089. CmdArgs.push_back("-export-dynamic");
  6090. if (Args.hasArg(options::OPT_s))
  6091. CmdArgs.push_back("--strip-all");
  6092. if (Args.hasArg(options::OPT_shared))
  6093. CmdArgs.push_back("-shared");
  6094. if (Args.hasArg(options::OPT_static))
  6095. CmdArgs.push_back("-Bstatic");
  6096. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6097. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6098. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6099. if (Args.hasArg(options::OPT_shared))
  6100. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("rcrt1.o")));
  6101. else if (Args.hasArg(options::OPT_pie))
  6102. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("Scrt1.o")));
  6103. else
  6104. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  6105. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6106. }
  6107. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6108. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6109. if (D.CCCIsCXX())
  6110. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6111. if (Args.hasArg(options::OPT_pthread))
  6112. CmdArgs.push_back("-lpthread");
  6113. CmdArgs.push_back("-lc");
  6114. CmdArgs.push_back("-lcompiler_rt");
  6115. }
  6116. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6117. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  6118. CmdArgs.push_back("-o");
  6119. CmdArgs.push_back(Output.getFilename());
  6120. C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
  6121. }
  6122. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  6123. std::string MArch;
  6124. if (!Arch.empty())
  6125. MArch = Arch;
  6126. else
  6127. MArch = Triple.getArchName();
  6128. MArch = StringRef(MArch).split("+").first.lower();
  6129. // Handle -march=native.
  6130. if (MArch == "native") {
  6131. std::string CPU = llvm::sys::getHostCPUName();
  6132. if (CPU != "generic") {
  6133. // Translate the native cpu into the architecture suffix for that CPU.
  6134. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  6135. // If there is no valid architecture suffix for this CPU we don't know how
  6136. // to handle it, so return no architecture.
  6137. if (Suffix.empty())
  6138. MArch = "";
  6139. else
  6140. MArch = std::string("arm") + Suffix.str();
  6141. }
  6142. }
  6143. return MArch;
  6144. }
  6145. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  6146. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  6147. std::string MArch = getARMArch(Arch, Triple);
  6148. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  6149. // here means an -march=native that we can't handle, so instead return no CPU.
  6150. if (MArch.empty())
  6151. return StringRef();
  6152. // We need to return an empty string here on invalid MArch values as the
  6153. // various places that call this function can't cope with a null result.
  6154. return Triple.getARMCPUForArch(MArch);
  6155. }
  6156. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  6157. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  6158. const llvm::Triple &Triple) {
  6159. // FIXME: Warn on inconsistent use of -mcpu and -march.
  6160. // If we have -mcpu=, use that.
  6161. if (!CPU.empty()) {
  6162. std::string MCPU = StringRef(CPU).split("+").first.lower();
  6163. // Handle -mcpu=native.
  6164. if (MCPU == "native")
  6165. return llvm::sys::getHostCPUName();
  6166. else
  6167. return MCPU;
  6168. }
  6169. return getARMCPUForMArch(Arch, Triple);
  6170. }
  6171. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  6172. /// CPU (or Arch, if CPU is generic).
  6173. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  6174. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  6175. const llvm::Triple &Triple) {
  6176. unsigned ArchKind;
  6177. if (CPU == "generic") {
  6178. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  6179. ArchKind = llvm::ARM::parseArch(ARMArch);
  6180. if (ArchKind == llvm::ARM::AK_INVALID)
  6181. // In case of generic Arch, i.e. "arm",
  6182. // extract arch from default cpu of the Triple
  6183. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  6184. } else {
  6185. // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
  6186. // armv7k triple if it's actually been specified via "-arch armv7k".
  6187. ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
  6188. ? (unsigned)llvm::ARM::AK_ARMV7K
  6189. : llvm::ARM::parseCPUArch(CPU);
  6190. }
  6191. if (ArchKind == llvm::ARM::AK_INVALID)
  6192. return "";
  6193. return llvm::ARM::getSubArch(ArchKind);
  6194. }
  6195. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  6196. const llvm::Triple &Triple) {
  6197. if (Args.hasArg(options::OPT_r))
  6198. return;
  6199. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  6200. // to generate BE-8 executables.
  6201. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  6202. CmdArgs.push_back("--be8");
  6203. }
  6204. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  6205. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  6206. // was first introduced in Release 3. However, other compilers have
  6207. // traditionally allowed it for Release 2 so we should do the same.
  6208. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  6209. .Case("mips1", NanLegacy)
  6210. .Case("mips2", NanLegacy)
  6211. .Case("mips3", NanLegacy)
  6212. .Case("mips4", NanLegacy)
  6213. .Case("mips5", NanLegacy)
  6214. .Case("mips32", NanLegacy)
  6215. .Case("mips32r2", NanLegacy | Nan2008)
  6216. .Case("mips32r3", NanLegacy | Nan2008)
  6217. .Case("mips32r5", NanLegacy | Nan2008)
  6218. .Case("mips32r6", Nan2008)
  6219. .Case("mips64", NanLegacy)
  6220. .Case("mips64r2", NanLegacy | Nan2008)
  6221. .Case("mips64r3", NanLegacy | Nan2008)
  6222. .Case("mips64r5", NanLegacy | Nan2008)
  6223. .Case("mips64r6", Nan2008)
  6224. .Default(NanLegacy);
  6225. }
  6226. bool mips::hasCompactBranches(StringRef &CPU) {
  6227. // mips32r6 and mips64r6 have compact branches.
  6228. return llvm::StringSwitch<bool>(CPU)
  6229. .Case("mips32r6", true)
  6230. .Case("mips64r6", true)
  6231. .Default(false);
  6232. }
  6233. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  6234. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  6235. return A && (A->getValue() == StringRef(Value));
  6236. }
  6237. bool mips::isUCLibc(const ArgList &Args) {
  6238. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  6239. return A && A->getOption().matches(options::OPT_muclibc);
  6240. }
  6241. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  6242. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  6243. return llvm::StringSwitch<bool>(NaNArg->getValue())
  6244. .Case("2008", true)
  6245. .Case("legacy", false)
  6246. .Default(false);
  6247. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  6248. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  6249. .Cases("mips32r6", "mips64r6", true)
  6250. .Default(false);
  6251. return false;
  6252. }
  6253. bool mips::isFP64ADefault(const llvm::Triple &Triple, StringRef CPUName) {
  6254. if (!Triple.isAndroid())
  6255. return false;
  6256. // Android MIPS32R6 defaults to FP64A.
  6257. return llvm::StringSwitch<bool>(CPUName)
  6258. .Case("mips32r6", true)
  6259. .Default(false);
  6260. }
  6261. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  6262. StringRef ABIName, mips::FloatABI FloatABI) {
  6263. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  6264. Triple.getVendor() != llvm::Triple::MipsTechnologies &&
  6265. !Triple.isAndroid())
  6266. return false;
  6267. if (ABIName != "32")
  6268. return false;
  6269. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  6270. // present.
  6271. if (FloatABI == mips::FloatABI::Soft)
  6272. return false;
  6273. return llvm::StringSwitch<bool>(CPUName)
  6274. .Cases("mips2", "mips3", "mips4", "mips5", true)
  6275. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  6276. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  6277. .Default(false);
  6278. }
  6279. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  6280. StringRef CPUName, StringRef ABIName,
  6281. mips::FloatABI FloatABI) {
  6282. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  6283. // FPXX shouldn't be used if -msingle-float is present.
  6284. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  6285. options::OPT_mdouble_float))
  6286. if (A->getOption().matches(options::OPT_msingle_float))
  6287. UseFPXX = false;
  6288. return UseFPXX;
  6289. }
  6290. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  6291. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  6292. // archs which Darwin doesn't use.
  6293. // The matching this routine does is fairly pointless, since it is neither the
  6294. // complete architecture list, nor a reasonable subset. The problem is that
  6295. // historically the driver driver accepts this and also ties its -march=
  6296. // handling to the architecture name, so we need to be careful before removing
  6297. // support for it.
  6298. // This code must be kept in sync with Clang's Darwin specific argument
  6299. // translation.
  6300. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  6301. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  6302. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  6303. .Case("ppc64", llvm::Triple::ppc64)
  6304. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  6305. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  6306. llvm::Triple::x86)
  6307. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  6308. // This is derived from the driver driver.
  6309. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  6310. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  6311. .Cases("armv7s", "xscale", llvm::Triple::arm)
  6312. .Case("arm64", llvm::Triple::aarch64)
  6313. .Case("r600", llvm::Triple::r600)
  6314. .Case("amdgcn", llvm::Triple::amdgcn)
  6315. .Case("nvptx", llvm::Triple::nvptx)
  6316. .Case("nvptx64", llvm::Triple::nvptx64)
  6317. .Case("amdil", llvm::Triple::amdil)
  6318. .Case("spir", llvm::Triple::spir)
  6319. .Default(llvm::Triple::UnknownArch);
  6320. }
  6321. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  6322. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  6323. T.setArch(Arch);
  6324. if (Str == "x86_64h")
  6325. T.setArchName(Str);
  6326. else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
  6327. T.setOS(llvm::Triple::UnknownOS);
  6328. T.setObjectFormat(llvm::Triple::MachO);
  6329. }
  6330. }
  6331. const char *Clang::getBaseInputName(const ArgList &Args,
  6332. const InputInfo &Input) {
  6333. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  6334. }
  6335. const char *Clang::getBaseInputStem(const ArgList &Args,
  6336. const InputInfoList &Inputs) {
  6337. const char *Str = getBaseInputName(Args, Inputs[0]);
  6338. if (const char *End = strrchr(Str, '.'))
  6339. return Args.MakeArgString(std::string(Str, End));
  6340. return Str;
  6341. }
  6342. const char *Clang::getDependencyFileName(const ArgList &Args,
  6343. const InputInfoList &Inputs) {
  6344. // FIXME: Think about this more.
  6345. std::string Res;
  6346. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  6347. std::string Str(OutputOpt->getValue());
  6348. Res = Str.substr(0, Str.rfind('.'));
  6349. } else {
  6350. Res = getBaseInputStem(Args, Inputs);
  6351. }
  6352. return Args.MakeArgString(Res + ".d");
  6353. }
  6354. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6355. const InputInfo &Output,
  6356. const InputInfoList &Inputs,
  6357. const ArgList &Args,
  6358. const char *LinkingOutput) const {
  6359. const ToolChain &ToolChain = getToolChain();
  6360. const Driver &D = ToolChain.getDriver();
  6361. ArgStringList CmdArgs;
  6362. // Silence warning for "clang -g foo.o -o foo"
  6363. Args.ClaimAllArgs(options::OPT_g_Group);
  6364. // and "clang -emit-llvm foo.o -o foo"
  6365. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6366. // and for "clang -w foo.o -o foo". Other warning options are already
  6367. // handled somewhere else.
  6368. Args.ClaimAllArgs(options::OPT_w);
  6369. if (!D.SysRoot.empty())
  6370. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6371. // CloudABI only supports static linkage.
  6372. CmdArgs.push_back("-Bstatic");
  6373. // CloudABI uses Position Independent Executables exclusively.
  6374. CmdArgs.push_back("-pie");
  6375. CmdArgs.push_back("--no-dynamic-linker");
  6376. CmdArgs.push_back("-zrelro");
  6377. CmdArgs.push_back("--eh-frame-hdr");
  6378. CmdArgs.push_back("--gc-sections");
  6379. if (Output.isFilename()) {
  6380. CmdArgs.push_back("-o");
  6381. CmdArgs.push_back(Output.getFilename());
  6382. } else {
  6383. assert(Output.isNothing() && "Invalid output.");
  6384. }
  6385. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6386. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  6387. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  6388. }
  6389. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6390. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6391. Args.AddAllArgs(CmdArgs,
  6392. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  6393. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  6394. if (D.isUsingLTO())
  6395. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  6396. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6397. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6398. if (D.CCCIsCXX())
  6399. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6400. CmdArgs.push_back("-lc");
  6401. CmdArgs.push_back("-lcompiler_rt");
  6402. }
  6403. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6404. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  6405. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  6406. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6407. }
  6408. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6409. const InputInfo &Output,
  6410. const InputInfoList &Inputs,
  6411. const ArgList &Args,
  6412. const char *LinkingOutput) const {
  6413. ArgStringList CmdArgs;
  6414. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  6415. const InputInfo &Input = Inputs[0];
  6416. // Determine the original source input.
  6417. const Action *SourceAction = &JA;
  6418. while (SourceAction->getKind() != Action::InputClass) {
  6419. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  6420. SourceAction = SourceAction->getInputs()[0];
  6421. }
  6422. // If -fno-integrated-as is used add -Q to the darwin assember driver to make
  6423. // sure it runs its system assembler not clang's integrated assembler.
  6424. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  6425. // FIXME: at run-time detect assembler capabilities or rely on version
  6426. // information forwarded by -target-assembler-version.
  6427. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  6428. const llvm::Triple &T(getToolChain().getTriple());
  6429. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  6430. CmdArgs.push_back("-Q");
  6431. }
  6432. // Forward -g, assuming we are dealing with an actual assembly file.
  6433. if (SourceAction->getType() == types::TY_Asm ||
  6434. SourceAction->getType() == types::TY_PP_Asm) {
  6435. if (Args.hasArg(options::OPT_gstabs))
  6436. CmdArgs.push_back("--gstabs");
  6437. else if (Args.hasArg(options::OPT_g_Group))
  6438. CmdArgs.push_back("-g");
  6439. }
  6440. // Derived from asm spec.
  6441. AddMachOArch(Args, CmdArgs);
  6442. // Use -force_cpusubtype_ALL on x86 by default.
  6443. if (getToolChain().getArch() == llvm::Triple::x86 ||
  6444. getToolChain().getArch() == llvm::Triple::x86_64 ||
  6445. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  6446. CmdArgs.push_back("-force_cpusubtype_ALL");
  6447. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  6448. (((Args.hasArg(options::OPT_mkernel) ||
  6449. Args.hasArg(options::OPT_fapple_kext)) &&
  6450. getMachOToolChain().isKernelStatic()) ||
  6451. Args.hasArg(options::OPT_static)))
  6452. CmdArgs.push_back("-static");
  6453. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6454. assert(Output.isFilename() && "Unexpected lipo output.");
  6455. CmdArgs.push_back("-o");
  6456. CmdArgs.push_back(Output.getFilename());
  6457. assert(Input.isFilename() && "Invalid input.");
  6458. CmdArgs.push_back(Input.getFilename());
  6459. // asm_final spec is empty.
  6460. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6461. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6462. }
  6463. void darwin::MachOTool::anchor() {}
  6464. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  6465. ArgStringList &CmdArgs) const {
  6466. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  6467. // Derived from darwin_arch spec.
  6468. CmdArgs.push_back("-arch");
  6469. CmdArgs.push_back(Args.MakeArgString(ArchName));
  6470. // FIXME: Is this needed anymore?
  6471. if (ArchName == "arm")
  6472. CmdArgs.push_back("-force_cpusubtype_ALL");
  6473. }
  6474. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  6475. // We only need to generate a temp path for LTO if we aren't compiling object
  6476. // files. When compiling source files, we run 'dsymutil' after linking. We
  6477. // don't run 'dsymutil' when compiling object files.
  6478. for (const auto &Input : Inputs)
  6479. if (Input.getType() != types::TY_Object)
  6480. return true;
  6481. return false;
  6482. }
  6483. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  6484. ArgStringList &CmdArgs,
  6485. const InputInfoList &Inputs) const {
  6486. const Driver &D = getToolChain().getDriver();
  6487. const toolchains::MachO &MachOTC = getMachOToolChain();
  6488. unsigned Version[5] = {0, 0, 0, 0, 0};
  6489. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  6490. if (!Driver::GetReleaseVersion(A->getValue(), Version))
  6491. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  6492. }
  6493. // Newer linkers support -demangle. Pass it if supported and not disabled by
  6494. // the user.
  6495. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  6496. CmdArgs.push_back("-demangle");
  6497. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  6498. CmdArgs.push_back("-export_dynamic");
  6499. // If we are using App Extension restrictions, pass a flag to the linker
  6500. // telling it that the compiled code has been audited.
  6501. if (Args.hasFlag(options::OPT_fapplication_extension,
  6502. options::OPT_fno_application_extension, false))
  6503. CmdArgs.push_back("-application_extension");
  6504. if (D.isUsingLTO()) {
  6505. // If we are using LTO, then automatically create a temporary file path for
  6506. // the linker to use, so that it's lifetime will extend past a possible
  6507. // dsymutil step.
  6508. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  6509. const char *TmpPath = C.getArgs().MakeArgString(
  6510. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  6511. C.addTempFile(TmpPath);
  6512. CmdArgs.push_back("-object_path_lto");
  6513. CmdArgs.push_back(TmpPath);
  6514. }
  6515. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  6516. // it in clang installed libraries. If not found, the option is not used
  6517. // and 'ld' will use its default mechanism to search for libLTO.dylib.
  6518. if (Version[0] >= 133) {
  6519. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  6520. StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
  6521. SmallString<128> LibLTOPath(P);
  6522. llvm::sys::path::append(LibLTOPath, "lib");
  6523. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  6524. if (llvm::sys::fs::exists(LibLTOPath)) {
  6525. CmdArgs.push_back("-lto_library");
  6526. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  6527. } else {
  6528. D.Diag(diag::warn_drv_lto_libpath);
  6529. }
  6530. }
  6531. }
  6532. // Derived from the "link" spec.
  6533. Args.AddAllArgs(CmdArgs, options::OPT_static);
  6534. if (!Args.hasArg(options::OPT_static))
  6535. CmdArgs.push_back("-dynamic");
  6536. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  6537. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  6538. // here. How do we wish to handle such things?
  6539. }
  6540. if (!Args.hasArg(options::OPT_dynamiclib)) {
  6541. AddMachOArch(Args, CmdArgs);
  6542. // FIXME: Why do this only on this path?
  6543. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  6544. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  6545. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  6546. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  6547. Arg *A;
  6548. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  6549. (A = Args.getLastArg(options::OPT_current__version)) ||
  6550. (A = Args.getLastArg(options::OPT_install__name)))
  6551. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  6552. << "-dynamiclib";
  6553. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  6554. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  6555. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  6556. } else {
  6557. CmdArgs.push_back("-dylib");
  6558. Arg *A;
  6559. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  6560. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  6561. (A = Args.getLastArg(options::OPT_client__name)) ||
  6562. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  6563. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  6564. (A = Args.getLastArg(options::OPT_private__bundle)))
  6565. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  6566. << "-dynamiclib";
  6567. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  6568. "-dylib_compatibility_version");
  6569. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  6570. "-dylib_current_version");
  6571. AddMachOArch(Args, CmdArgs);
  6572. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  6573. "-dylib_install_name");
  6574. }
  6575. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  6576. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  6577. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  6578. if (MachOTC.isTargetIOSBased())
  6579. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  6580. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  6581. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  6582. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  6583. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  6584. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  6585. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  6586. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  6587. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  6588. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  6589. Args.AddAllArgs(CmdArgs, options::OPT_init);
  6590. // Add the deployment target.
  6591. MachOTC.addMinVersionArgs(Args, CmdArgs);
  6592. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  6593. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  6594. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  6595. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  6596. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  6597. if (const Arg *A =
  6598. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  6599. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  6600. if (A->getOption().matches(options::OPT_fpie) ||
  6601. A->getOption().matches(options::OPT_fPIE))
  6602. CmdArgs.push_back("-pie");
  6603. else
  6604. CmdArgs.push_back("-no_pie");
  6605. }
  6606. // for embed-bitcode, use -bitcode_bundle in linker command
  6607. if (C.getDriver().embedBitcodeEnabled() ||
  6608. C.getDriver().embedBitcodeMarkerOnly()) {
  6609. // Check if the toolchain supports bitcode build flow.
  6610. if (MachOTC.SupportsEmbeddedBitcode())
  6611. CmdArgs.push_back("-bitcode_bundle");
  6612. else
  6613. D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
  6614. }
  6615. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  6616. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  6617. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  6618. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  6619. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  6620. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  6621. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  6622. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  6623. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  6624. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  6625. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  6626. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  6627. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  6628. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  6629. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  6630. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  6631. // Give --sysroot= preference, over the Apple specific behavior to also use
  6632. // --isysroot as the syslibroot.
  6633. StringRef sysroot = C.getSysRoot();
  6634. if (sysroot != "") {
  6635. CmdArgs.push_back("-syslibroot");
  6636. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  6637. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  6638. CmdArgs.push_back("-syslibroot");
  6639. CmdArgs.push_back(A->getValue());
  6640. }
  6641. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  6642. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  6643. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  6644. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  6645. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  6646. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  6647. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  6648. Args.AddAllArgs(CmdArgs, options::OPT_y);
  6649. Args.AddLastArg(CmdArgs, options::OPT_w);
  6650. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  6651. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  6652. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  6653. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  6654. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  6655. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  6656. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  6657. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  6658. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  6659. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  6660. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  6661. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  6662. }
  6663. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6664. const InputInfo &Output,
  6665. const InputInfoList &Inputs,
  6666. const ArgList &Args,
  6667. const char *LinkingOutput) const {
  6668. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  6669. // If the number of arguments surpasses the system limits, we will encode the
  6670. // input files in a separate file, shortening the command line. To this end,
  6671. // build a list of input file names that can be passed via a file with the
  6672. // -filelist linker option.
  6673. llvm::opt::ArgStringList InputFileList;
  6674. // The logic here is derived from gcc's behavior; most of which
  6675. // comes from specs (starting with link_command). Consult gcc for
  6676. // more information.
  6677. ArgStringList CmdArgs;
  6678. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  6679. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  6680. options::OPT_ccc_arcmt_migrate)) {
  6681. for (const auto &Arg : Args)
  6682. Arg->claim();
  6683. const char *Exec =
  6684. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  6685. CmdArgs.push_back(Output.getFilename());
  6686. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  6687. return;
  6688. }
  6689. // I'm not sure why this particular decomposition exists in gcc, but
  6690. // we follow suite for ease of comparison.
  6691. AddLinkArgs(C, Args, CmdArgs, Inputs);
  6692. // It seems that the 'e' option is completely ignored for dynamic executables
  6693. // (the default), and with static executables, the last one wins, as expected.
  6694. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  6695. options::OPT_Z_Flag, options::OPT_u_Group,
  6696. options::OPT_e, options::OPT_r});
  6697. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  6698. // members of static archive libraries which implement Objective-C classes or
  6699. // categories.
  6700. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  6701. CmdArgs.push_back("-ObjC");
  6702. CmdArgs.push_back("-o");
  6703. CmdArgs.push_back(Output.getFilename());
  6704. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6705. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  6706. // SafeStack requires its own runtime libraries
  6707. // These libraries should be linked first, to make sure the
  6708. // __safestack_init constructor executes before everything else
  6709. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  6710. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  6711. "libclang_rt.safestack_osx.a",
  6712. /*AlwaysLink=*/true);
  6713. }
  6714. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6715. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6716. // Build the input file for -filelist (list of linker input files) in case we
  6717. // need it later
  6718. for (const auto &II : Inputs) {
  6719. if (!II.isFilename()) {
  6720. // This is a linker input argument.
  6721. // We cannot mix input arguments and file names in a -filelist input, thus
  6722. // we prematurely stop our list (remaining files shall be passed as
  6723. // arguments).
  6724. if (InputFileList.size() > 0)
  6725. break;
  6726. continue;
  6727. }
  6728. InputFileList.push_back(II.getFilename());
  6729. }
  6730. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  6731. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  6732. if (isObjCRuntimeLinked(Args) &&
  6733. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6734. // We use arclite library for both ARC and subscripting support.
  6735. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  6736. CmdArgs.push_back("-framework");
  6737. CmdArgs.push_back("Foundation");
  6738. // Link libobj.
  6739. CmdArgs.push_back("-lobjc");
  6740. }
  6741. if (LinkingOutput) {
  6742. CmdArgs.push_back("-arch_multiple");
  6743. CmdArgs.push_back("-final_output");
  6744. CmdArgs.push_back(LinkingOutput);
  6745. }
  6746. if (Args.hasArg(options::OPT_fnested_functions))
  6747. CmdArgs.push_back("-allow_stack_execute");
  6748. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  6749. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6750. if (getToolChain().getDriver().CCCIsCXX())
  6751. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6752. // link_ssp spec is empty.
  6753. // Let the tool chain choose which runtime library to link.
  6754. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  6755. }
  6756. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6757. // endfile_spec is empty.
  6758. }
  6759. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6760. Args.AddAllArgs(CmdArgs, options::OPT_F);
  6761. // -iframework should be forwarded as -F.
  6762. for (const Arg *A : Args.filtered(options::OPT_iframework))
  6763. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  6764. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6765. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  6766. if (A->getValue() == StringRef("Accelerate")) {
  6767. CmdArgs.push_back("-framework");
  6768. CmdArgs.push_back("Accelerate");
  6769. }
  6770. }
  6771. }
  6772. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6773. std::unique_ptr<Command> Cmd =
  6774. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  6775. Cmd->setInputFileList(std::move(InputFileList));
  6776. C.addCommand(std::move(Cmd));
  6777. }
  6778. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  6779. const InputInfo &Output,
  6780. const InputInfoList &Inputs,
  6781. const ArgList &Args,
  6782. const char *LinkingOutput) const {
  6783. ArgStringList CmdArgs;
  6784. CmdArgs.push_back("-create");
  6785. assert(Output.isFilename() && "Unexpected lipo output.");
  6786. CmdArgs.push_back("-output");
  6787. CmdArgs.push_back(Output.getFilename());
  6788. for (const auto &II : Inputs) {
  6789. assert(II.isFilename() && "Unexpected lipo input.");
  6790. CmdArgs.push_back(II.getFilename());
  6791. }
  6792. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  6793. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6794. }
  6795. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  6796. const InputInfo &Output,
  6797. const InputInfoList &Inputs,
  6798. const ArgList &Args,
  6799. const char *LinkingOutput) const {
  6800. ArgStringList CmdArgs;
  6801. CmdArgs.push_back("-o");
  6802. CmdArgs.push_back(Output.getFilename());
  6803. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6804. const InputInfo &Input = Inputs[0];
  6805. assert(Input.isFilename() && "Unexpected dsymutil input.");
  6806. CmdArgs.push_back(Input.getFilename());
  6807. const char *Exec =
  6808. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  6809. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6810. }
  6811. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  6812. const InputInfo &Output,
  6813. const InputInfoList &Inputs,
  6814. const ArgList &Args,
  6815. const char *LinkingOutput) const {
  6816. ArgStringList CmdArgs;
  6817. CmdArgs.push_back("--verify");
  6818. CmdArgs.push_back("--debug-info");
  6819. CmdArgs.push_back("--eh-frame");
  6820. CmdArgs.push_back("--quiet");
  6821. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6822. const InputInfo &Input = Inputs[0];
  6823. assert(Input.isFilename() && "Unexpected verify input");
  6824. // Grabbing the output of the earlier dsymutil run.
  6825. CmdArgs.push_back(Input.getFilename());
  6826. const char *Exec =
  6827. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  6828. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6829. }
  6830. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6831. const InputInfo &Output,
  6832. const InputInfoList &Inputs,
  6833. const ArgList &Args,
  6834. const char *LinkingOutput) const {
  6835. claimNoWarnArgs(Args);
  6836. ArgStringList CmdArgs;
  6837. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6838. CmdArgs.push_back("-o");
  6839. CmdArgs.push_back(Output.getFilename());
  6840. for (const auto &II : Inputs)
  6841. CmdArgs.push_back(II.getFilename());
  6842. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6843. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6844. }
  6845. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6846. const InputInfo &Output,
  6847. const InputInfoList &Inputs,
  6848. const ArgList &Args,
  6849. const char *LinkingOutput) const {
  6850. ArgStringList CmdArgs;
  6851. // Demangle C++ names in errors
  6852. CmdArgs.push_back("-C");
  6853. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6854. CmdArgs.push_back("-e");
  6855. CmdArgs.push_back("_start");
  6856. }
  6857. if (Args.hasArg(options::OPT_static)) {
  6858. CmdArgs.push_back("-Bstatic");
  6859. CmdArgs.push_back("-dn");
  6860. } else {
  6861. CmdArgs.push_back("-Bdynamic");
  6862. if (Args.hasArg(options::OPT_shared)) {
  6863. CmdArgs.push_back("-shared");
  6864. } else {
  6865. CmdArgs.push_back("--dynamic-linker");
  6866. CmdArgs.push_back(
  6867. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  6868. }
  6869. }
  6870. if (Output.isFilename()) {
  6871. CmdArgs.push_back("-o");
  6872. CmdArgs.push_back(Output.getFilename());
  6873. } else {
  6874. assert(Output.isNothing() && "Invalid output.");
  6875. }
  6876. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6877. if (!Args.hasArg(options::OPT_shared))
  6878. CmdArgs.push_back(
  6879. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  6880. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6881. CmdArgs.push_back(
  6882. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  6883. CmdArgs.push_back(
  6884. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6885. }
  6886. getToolChain().AddFilePathLibArgs(Args, CmdArgs);
  6887. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6888. options::OPT_e, options::OPT_r});
  6889. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6890. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6891. if (getToolChain().getDriver().CCCIsCXX())
  6892. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6893. CmdArgs.push_back("-lgcc_s");
  6894. CmdArgs.push_back("-lc");
  6895. if (!Args.hasArg(options::OPT_shared)) {
  6896. CmdArgs.push_back("-lgcc");
  6897. CmdArgs.push_back("-lm");
  6898. }
  6899. }
  6900. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6901. CmdArgs.push_back(
  6902. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6903. }
  6904. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  6905. getToolChain().addProfileRTLibs(Args, CmdArgs);
  6906. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6907. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6908. }
  6909. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6910. const InputInfo &Output,
  6911. const InputInfoList &Inputs,
  6912. const ArgList &Args,
  6913. const char *LinkingOutput) const {
  6914. claimNoWarnArgs(Args);
  6915. ArgStringList CmdArgs;
  6916. switch (getToolChain().getArch()) {
  6917. case llvm::Triple::x86:
  6918. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  6919. // instruct as in the base system to assemble 32-bit code.
  6920. CmdArgs.push_back("--32");
  6921. break;
  6922. case llvm::Triple::ppc:
  6923. CmdArgs.push_back("-mppc");
  6924. CmdArgs.push_back("-many");
  6925. break;
  6926. case llvm::Triple::sparc:
  6927. case llvm::Triple::sparcel: {
  6928. CmdArgs.push_back("-32");
  6929. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6930. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6931. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6932. break;
  6933. }
  6934. case llvm::Triple::sparcv9: {
  6935. CmdArgs.push_back("-64");
  6936. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6937. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6938. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6939. break;
  6940. }
  6941. case llvm::Triple::mips64:
  6942. case llvm::Triple::mips64el: {
  6943. StringRef CPUName;
  6944. StringRef ABIName;
  6945. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6946. CmdArgs.push_back("-mabi");
  6947. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6948. if (getToolChain().getArch() == llvm::Triple::mips64)
  6949. CmdArgs.push_back("-EB");
  6950. else
  6951. CmdArgs.push_back("-EL");
  6952. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6953. break;
  6954. }
  6955. default:
  6956. break;
  6957. }
  6958. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6959. CmdArgs.push_back("-o");
  6960. CmdArgs.push_back(Output.getFilename());
  6961. for (const auto &II : Inputs)
  6962. CmdArgs.push_back(II.getFilename());
  6963. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6964. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6965. }
  6966. void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6967. const InputInfo &Output,
  6968. const InputInfoList &Inputs,
  6969. const ArgList &Args,
  6970. const char *LinkingOutput) const {
  6971. const Driver &D = getToolChain().getDriver();
  6972. ArgStringList CmdArgs;
  6973. // Silence warning for "clang -g foo.o -o foo"
  6974. Args.ClaimAllArgs(options::OPT_g_Group);
  6975. // and "clang -emit-llvm foo.o -o foo"
  6976. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6977. // and for "clang -w foo.o -o foo". Other warning options are already
  6978. // handled somewhere else.
  6979. Args.ClaimAllArgs(options::OPT_w);
  6980. if (getToolChain().getArch() == llvm::Triple::mips64)
  6981. CmdArgs.push_back("-EB");
  6982. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  6983. CmdArgs.push_back("-EL");
  6984. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6985. CmdArgs.push_back("-e");
  6986. CmdArgs.push_back("__start");
  6987. }
  6988. if (Args.hasArg(options::OPT_static)) {
  6989. CmdArgs.push_back("-Bstatic");
  6990. } else {
  6991. if (Args.hasArg(options::OPT_rdynamic))
  6992. CmdArgs.push_back("-export-dynamic");
  6993. CmdArgs.push_back("--eh-frame-hdr");
  6994. CmdArgs.push_back("-Bdynamic");
  6995. if (Args.hasArg(options::OPT_shared)) {
  6996. CmdArgs.push_back("-shared");
  6997. } else {
  6998. CmdArgs.push_back("-dynamic-linker");
  6999. CmdArgs.push_back("/usr/libexec/ld.so");
  7000. }
  7001. }
  7002. if (Args.hasArg(options::OPT_nopie))
  7003. CmdArgs.push_back("-nopie");
  7004. if (Output.isFilename()) {
  7005. CmdArgs.push_back("-o");
  7006. CmdArgs.push_back(Output.getFilename());
  7007. } else {
  7008. assert(Output.isNothing() && "Invalid output.");
  7009. }
  7010. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7011. if (!Args.hasArg(options::OPT_shared)) {
  7012. if (Args.hasArg(options::OPT_pg))
  7013. CmdArgs.push_back(
  7014. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  7015. else
  7016. CmdArgs.push_back(
  7017. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7018. CmdArgs.push_back(
  7019. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7020. } else {
  7021. CmdArgs.push_back(
  7022. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7023. }
  7024. }
  7025. std::string Triple = getToolChain().getTripleString();
  7026. if (Triple.substr(0, 6) == "x86_64")
  7027. Triple.replace(0, 6, "amd64");
  7028. CmdArgs.push_back(
  7029. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  7030. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  7031. options::OPT_e, options::OPT_s, options::OPT_t,
  7032. options::OPT_Z_Flag, options::OPT_r});
  7033. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7034. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7035. if (D.CCCIsCXX()) {
  7036. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7037. if (Args.hasArg(options::OPT_pg))
  7038. CmdArgs.push_back("-lm_p");
  7039. else
  7040. CmdArgs.push_back("-lm");
  7041. }
  7042. // FIXME: For some reason GCC passes -lgcc before adding
  7043. // the default system libraries. Just mimic this for now.
  7044. CmdArgs.push_back("-lgcc");
  7045. if (Args.hasArg(options::OPT_pthread)) {
  7046. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  7047. CmdArgs.push_back("-lpthread_p");
  7048. else
  7049. CmdArgs.push_back("-lpthread");
  7050. }
  7051. if (!Args.hasArg(options::OPT_shared)) {
  7052. if (Args.hasArg(options::OPT_pg))
  7053. CmdArgs.push_back("-lc_p");
  7054. else
  7055. CmdArgs.push_back("-lc");
  7056. }
  7057. CmdArgs.push_back("-lgcc");
  7058. }
  7059. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7060. if (!Args.hasArg(options::OPT_shared))
  7061. CmdArgs.push_back(
  7062. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7063. else
  7064. CmdArgs.push_back(
  7065. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7066. }
  7067. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7068. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7069. }
  7070. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7071. const InputInfo &Output,
  7072. const InputInfoList &Inputs,
  7073. const ArgList &Args,
  7074. const char *LinkingOutput) const {
  7075. claimNoWarnArgs(Args);
  7076. ArgStringList CmdArgs;
  7077. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7078. CmdArgs.push_back("-o");
  7079. CmdArgs.push_back(Output.getFilename());
  7080. for (const auto &II : Inputs)
  7081. CmdArgs.push_back(II.getFilename());
  7082. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7083. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7084. }
  7085. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7086. const InputInfo &Output,
  7087. const InputInfoList &Inputs,
  7088. const ArgList &Args,
  7089. const char *LinkingOutput) const {
  7090. const Driver &D = getToolChain().getDriver();
  7091. ArgStringList CmdArgs;
  7092. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  7093. CmdArgs.push_back("-e");
  7094. CmdArgs.push_back("__start");
  7095. }
  7096. if (Args.hasArg(options::OPT_static)) {
  7097. CmdArgs.push_back("-Bstatic");
  7098. } else {
  7099. if (Args.hasArg(options::OPT_rdynamic))
  7100. CmdArgs.push_back("-export-dynamic");
  7101. CmdArgs.push_back("--eh-frame-hdr");
  7102. CmdArgs.push_back("-Bdynamic");
  7103. if (Args.hasArg(options::OPT_shared)) {
  7104. CmdArgs.push_back("-shared");
  7105. } else {
  7106. CmdArgs.push_back("-dynamic-linker");
  7107. CmdArgs.push_back("/usr/libexec/ld.so");
  7108. }
  7109. }
  7110. if (Output.isFilename()) {
  7111. CmdArgs.push_back("-o");
  7112. CmdArgs.push_back(Output.getFilename());
  7113. } else {
  7114. assert(Output.isNothing() && "Invalid output.");
  7115. }
  7116. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7117. if (!Args.hasArg(options::OPT_shared)) {
  7118. if (Args.hasArg(options::OPT_pg))
  7119. CmdArgs.push_back(
  7120. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  7121. else
  7122. CmdArgs.push_back(
  7123. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7124. CmdArgs.push_back(
  7125. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7126. } else {
  7127. CmdArgs.push_back(
  7128. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7129. }
  7130. }
  7131. Args.AddAllArgs(CmdArgs,
  7132. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  7133. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7134. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7135. if (D.CCCIsCXX()) {
  7136. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7137. if (Args.hasArg(options::OPT_pg))
  7138. CmdArgs.push_back("-lm_p");
  7139. else
  7140. CmdArgs.push_back("-lm");
  7141. }
  7142. if (Args.hasArg(options::OPT_pthread)) {
  7143. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  7144. CmdArgs.push_back("-lpthread_p");
  7145. else
  7146. CmdArgs.push_back("-lpthread");
  7147. }
  7148. if (!Args.hasArg(options::OPT_shared)) {
  7149. if (Args.hasArg(options::OPT_pg))
  7150. CmdArgs.push_back("-lc_p");
  7151. else
  7152. CmdArgs.push_back("-lc");
  7153. }
  7154. StringRef MyArch;
  7155. switch (getToolChain().getArch()) {
  7156. case llvm::Triple::arm:
  7157. MyArch = "arm";
  7158. break;
  7159. case llvm::Triple::x86:
  7160. MyArch = "i386";
  7161. break;
  7162. case llvm::Triple::x86_64:
  7163. MyArch = "amd64";
  7164. break;
  7165. default:
  7166. llvm_unreachable("Unsupported architecture");
  7167. }
  7168. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  7169. }
  7170. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7171. if (!Args.hasArg(options::OPT_shared))
  7172. CmdArgs.push_back(
  7173. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7174. else
  7175. CmdArgs.push_back(
  7176. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7177. }
  7178. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7179. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7180. }
  7181. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7182. const InputInfo &Output,
  7183. const InputInfoList &Inputs,
  7184. const ArgList &Args,
  7185. const char *LinkingOutput) const {
  7186. claimNoWarnArgs(Args);
  7187. ArgStringList CmdArgs;
  7188. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  7189. // instruct as in the base system to assemble 32-bit code.
  7190. switch (getToolChain().getArch()) {
  7191. default:
  7192. break;
  7193. case llvm::Triple::x86:
  7194. CmdArgs.push_back("--32");
  7195. break;
  7196. case llvm::Triple::ppc:
  7197. CmdArgs.push_back("-a32");
  7198. break;
  7199. case llvm::Triple::mips:
  7200. case llvm::Triple::mipsel:
  7201. case llvm::Triple::mips64:
  7202. case llvm::Triple::mips64el: {
  7203. StringRef CPUName;
  7204. StringRef ABIName;
  7205. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7206. CmdArgs.push_back("-march");
  7207. CmdArgs.push_back(CPUName.data());
  7208. CmdArgs.push_back("-mabi");
  7209. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7210. if (getToolChain().getArch() == llvm::Triple::mips ||
  7211. getToolChain().getArch() == llvm::Triple::mips64)
  7212. CmdArgs.push_back("-EB");
  7213. else
  7214. CmdArgs.push_back("-EL");
  7215. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  7216. StringRef v = A->getValue();
  7217. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  7218. A->claim();
  7219. }
  7220. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7221. break;
  7222. }
  7223. case llvm::Triple::arm:
  7224. case llvm::Triple::armeb:
  7225. case llvm::Triple::thumb:
  7226. case llvm::Triple::thumbeb: {
  7227. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  7228. if (ABI == arm::FloatABI::Hard)
  7229. CmdArgs.push_back("-mfpu=vfp");
  7230. else
  7231. CmdArgs.push_back("-mfpu=softvfp");
  7232. switch (getToolChain().getTriple().getEnvironment()) {
  7233. case llvm::Triple::GNUEABIHF:
  7234. case llvm::Triple::GNUEABI:
  7235. case llvm::Triple::EABI:
  7236. CmdArgs.push_back("-meabi=5");
  7237. break;
  7238. default:
  7239. CmdArgs.push_back("-matpcs");
  7240. }
  7241. break;
  7242. }
  7243. case llvm::Triple::sparc:
  7244. case llvm::Triple::sparcel:
  7245. case llvm::Triple::sparcv9: {
  7246. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7247. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7248. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7249. break;
  7250. }
  7251. }
  7252. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7253. CmdArgs.push_back("-o");
  7254. CmdArgs.push_back(Output.getFilename());
  7255. for (const auto &II : Inputs)
  7256. CmdArgs.push_back(II.getFilename());
  7257. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7258. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7259. }
  7260. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7261. const InputInfo &Output,
  7262. const InputInfoList &Inputs,
  7263. const ArgList &Args,
  7264. const char *LinkingOutput) const {
  7265. const toolchains::FreeBSD &ToolChain =
  7266. static_cast<const toolchains::FreeBSD &>(getToolChain());
  7267. const Driver &D = ToolChain.getDriver();
  7268. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7269. const bool IsPIE =
  7270. !Args.hasArg(options::OPT_shared) &&
  7271. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7272. ArgStringList CmdArgs;
  7273. // Silence warning for "clang -g foo.o -o foo"
  7274. Args.ClaimAllArgs(options::OPT_g_Group);
  7275. // and "clang -emit-llvm foo.o -o foo"
  7276. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7277. // and for "clang -w foo.o -o foo". Other warning options are already
  7278. // handled somewhere else.
  7279. Args.ClaimAllArgs(options::OPT_w);
  7280. if (!D.SysRoot.empty())
  7281. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7282. if (IsPIE)
  7283. CmdArgs.push_back("-pie");
  7284. CmdArgs.push_back("--eh-frame-hdr");
  7285. if (Args.hasArg(options::OPT_static)) {
  7286. CmdArgs.push_back("-Bstatic");
  7287. } else {
  7288. if (Args.hasArg(options::OPT_rdynamic))
  7289. CmdArgs.push_back("-export-dynamic");
  7290. if (Args.hasArg(options::OPT_shared)) {
  7291. CmdArgs.push_back("-Bshareable");
  7292. } else {
  7293. CmdArgs.push_back("-dynamic-linker");
  7294. CmdArgs.push_back("/libexec/ld-elf.so.1");
  7295. }
  7296. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  7297. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  7298. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  7299. CmdArgs.push_back("--hash-style=both");
  7300. }
  7301. }
  7302. CmdArgs.push_back("--enable-new-dtags");
  7303. }
  7304. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  7305. // instruct ld in the base system to link 32-bit code.
  7306. if (Arch == llvm::Triple::x86) {
  7307. CmdArgs.push_back("-m");
  7308. CmdArgs.push_back("elf_i386_fbsd");
  7309. }
  7310. if (Arch == llvm::Triple::ppc) {
  7311. CmdArgs.push_back("-m");
  7312. CmdArgs.push_back("elf32ppc_fbsd");
  7313. }
  7314. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  7315. if (ToolChain.getArch() == llvm::Triple::mips ||
  7316. ToolChain.getArch() == llvm::Triple::mipsel ||
  7317. ToolChain.getArch() == llvm::Triple::mips64 ||
  7318. ToolChain.getArch() == llvm::Triple::mips64el) {
  7319. StringRef v = A->getValue();
  7320. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  7321. A->claim();
  7322. }
  7323. }
  7324. if (Output.isFilename()) {
  7325. CmdArgs.push_back("-o");
  7326. CmdArgs.push_back(Output.getFilename());
  7327. } else {
  7328. assert(Output.isNothing() && "Invalid output.");
  7329. }
  7330. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7331. const char *crt1 = nullptr;
  7332. if (!Args.hasArg(options::OPT_shared)) {
  7333. if (Args.hasArg(options::OPT_pg))
  7334. crt1 = "gcrt1.o";
  7335. else if (IsPIE)
  7336. crt1 = "Scrt1.o";
  7337. else
  7338. crt1 = "crt1.o";
  7339. }
  7340. if (crt1)
  7341. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  7342. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7343. const char *crtbegin = nullptr;
  7344. if (Args.hasArg(options::OPT_static))
  7345. crtbegin = "crtbeginT.o";
  7346. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  7347. crtbegin = "crtbeginS.o";
  7348. else
  7349. crtbegin = "crtbegin.o";
  7350. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7351. }
  7352. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7353. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7354. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7355. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7356. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7357. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7358. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7359. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7360. if (D.isUsingLTO())
  7361. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  7362. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7363. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7364. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7365. addOpenMPRuntime(CmdArgs, ToolChain, Args);
  7366. if (D.CCCIsCXX()) {
  7367. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7368. if (Args.hasArg(options::OPT_pg))
  7369. CmdArgs.push_back("-lm_p");
  7370. else
  7371. CmdArgs.push_back("-lm");
  7372. }
  7373. if (NeedsSanitizerDeps)
  7374. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7375. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  7376. // the default system libraries. Just mimic this for now.
  7377. if (Args.hasArg(options::OPT_pg))
  7378. CmdArgs.push_back("-lgcc_p");
  7379. else
  7380. CmdArgs.push_back("-lgcc");
  7381. if (Args.hasArg(options::OPT_static)) {
  7382. CmdArgs.push_back("-lgcc_eh");
  7383. } else if (Args.hasArg(options::OPT_pg)) {
  7384. CmdArgs.push_back("-lgcc_eh_p");
  7385. } else {
  7386. CmdArgs.push_back("--as-needed");
  7387. CmdArgs.push_back("-lgcc_s");
  7388. CmdArgs.push_back("--no-as-needed");
  7389. }
  7390. if (Args.hasArg(options::OPT_pthread)) {
  7391. if (Args.hasArg(options::OPT_pg))
  7392. CmdArgs.push_back("-lpthread_p");
  7393. else
  7394. CmdArgs.push_back("-lpthread");
  7395. }
  7396. if (Args.hasArg(options::OPT_pg)) {
  7397. if (Args.hasArg(options::OPT_shared))
  7398. CmdArgs.push_back("-lc");
  7399. else
  7400. CmdArgs.push_back("-lc_p");
  7401. CmdArgs.push_back("-lgcc_p");
  7402. } else {
  7403. CmdArgs.push_back("-lc");
  7404. CmdArgs.push_back("-lgcc");
  7405. }
  7406. if (Args.hasArg(options::OPT_static)) {
  7407. CmdArgs.push_back("-lgcc_eh");
  7408. } else if (Args.hasArg(options::OPT_pg)) {
  7409. CmdArgs.push_back("-lgcc_eh_p");
  7410. } else {
  7411. CmdArgs.push_back("--as-needed");
  7412. CmdArgs.push_back("-lgcc_s");
  7413. CmdArgs.push_back("--no-as-needed");
  7414. }
  7415. }
  7416. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7417. if (Args.hasArg(options::OPT_shared) || IsPIE)
  7418. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  7419. else
  7420. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  7421. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7422. }
  7423. ToolChain.addProfileRTLibs(Args, CmdArgs);
  7424. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7425. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7426. }
  7427. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7428. const InputInfo &Output,
  7429. const InputInfoList &Inputs,
  7430. const ArgList &Args,
  7431. const char *LinkingOutput) const {
  7432. claimNoWarnArgs(Args);
  7433. ArgStringList CmdArgs;
  7434. // GNU as needs different flags for creating the correct output format
  7435. // on architectures with different ABIs or optional feature sets.
  7436. switch (getToolChain().getArch()) {
  7437. case llvm::Triple::x86:
  7438. CmdArgs.push_back("--32");
  7439. break;
  7440. case llvm::Triple::arm:
  7441. case llvm::Triple::armeb:
  7442. case llvm::Triple::thumb:
  7443. case llvm::Triple::thumbeb: {
  7444. StringRef MArch, MCPU;
  7445. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  7446. std::string Arch =
  7447. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  7448. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  7449. break;
  7450. }
  7451. case llvm::Triple::mips:
  7452. case llvm::Triple::mipsel:
  7453. case llvm::Triple::mips64:
  7454. case llvm::Triple::mips64el: {
  7455. StringRef CPUName;
  7456. StringRef ABIName;
  7457. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7458. CmdArgs.push_back("-march");
  7459. CmdArgs.push_back(CPUName.data());
  7460. CmdArgs.push_back("-mabi");
  7461. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7462. if (getToolChain().getArch() == llvm::Triple::mips ||
  7463. getToolChain().getArch() == llvm::Triple::mips64)
  7464. CmdArgs.push_back("-EB");
  7465. else
  7466. CmdArgs.push_back("-EL");
  7467. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7468. break;
  7469. }
  7470. case llvm::Triple::sparc:
  7471. case llvm::Triple::sparcel: {
  7472. CmdArgs.push_back("-32");
  7473. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7474. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7475. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7476. break;
  7477. }
  7478. case llvm::Triple::sparcv9: {
  7479. CmdArgs.push_back("-64");
  7480. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7481. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7482. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7483. break;
  7484. }
  7485. default:
  7486. break;
  7487. }
  7488. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7489. CmdArgs.push_back("-o");
  7490. CmdArgs.push_back(Output.getFilename());
  7491. for (const auto &II : Inputs)
  7492. CmdArgs.push_back(II.getFilename());
  7493. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  7494. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7495. }
  7496. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7497. const InputInfo &Output,
  7498. const InputInfoList &Inputs,
  7499. const ArgList &Args,
  7500. const char *LinkingOutput) const {
  7501. const Driver &D = getToolChain().getDriver();
  7502. ArgStringList CmdArgs;
  7503. if (!D.SysRoot.empty())
  7504. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7505. CmdArgs.push_back("--eh-frame-hdr");
  7506. if (Args.hasArg(options::OPT_static)) {
  7507. CmdArgs.push_back("-Bstatic");
  7508. } else {
  7509. if (Args.hasArg(options::OPT_rdynamic))
  7510. CmdArgs.push_back("-export-dynamic");
  7511. if (Args.hasArg(options::OPT_shared)) {
  7512. CmdArgs.push_back("-Bshareable");
  7513. } else {
  7514. Args.AddAllArgs(CmdArgs, options::OPT_pie);
  7515. CmdArgs.push_back("-dynamic-linker");
  7516. CmdArgs.push_back("/libexec/ld.elf_so");
  7517. }
  7518. }
  7519. // Many NetBSD architectures support more than one ABI.
  7520. // Determine the correct emulation for ld.
  7521. switch (getToolChain().getArch()) {
  7522. case llvm::Triple::x86:
  7523. CmdArgs.push_back("-m");
  7524. CmdArgs.push_back("elf_i386");
  7525. break;
  7526. case llvm::Triple::arm:
  7527. case llvm::Triple::thumb:
  7528. CmdArgs.push_back("-m");
  7529. switch (getToolChain().getTriple().getEnvironment()) {
  7530. case llvm::Triple::EABI:
  7531. case llvm::Triple::GNUEABI:
  7532. CmdArgs.push_back("armelf_nbsd_eabi");
  7533. break;
  7534. case llvm::Triple::EABIHF:
  7535. case llvm::Triple::GNUEABIHF:
  7536. CmdArgs.push_back("armelf_nbsd_eabihf");
  7537. break;
  7538. default:
  7539. CmdArgs.push_back("armelf_nbsd");
  7540. break;
  7541. }
  7542. break;
  7543. case llvm::Triple::armeb:
  7544. case llvm::Triple::thumbeb:
  7545. arm::appendEBLinkFlags(
  7546. Args, CmdArgs,
  7547. llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
  7548. CmdArgs.push_back("-m");
  7549. switch (getToolChain().getTriple().getEnvironment()) {
  7550. case llvm::Triple::EABI:
  7551. case llvm::Triple::GNUEABI:
  7552. CmdArgs.push_back("armelfb_nbsd_eabi");
  7553. break;
  7554. case llvm::Triple::EABIHF:
  7555. case llvm::Triple::GNUEABIHF:
  7556. CmdArgs.push_back("armelfb_nbsd_eabihf");
  7557. break;
  7558. default:
  7559. CmdArgs.push_back("armelfb_nbsd");
  7560. break;
  7561. }
  7562. break;
  7563. case llvm::Triple::mips64:
  7564. case llvm::Triple::mips64el:
  7565. if (mips::hasMipsAbiArg(Args, "32")) {
  7566. CmdArgs.push_back("-m");
  7567. if (getToolChain().getArch() == llvm::Triple::mips64)
  7568. CmdArgs.push_back("elf32btsmip");
  7569. else
  7570. CmdArgs.push_back("elf32ltsmip");
  7571. } else if (mips::hasMipsAbiArg(Args, "64")) {
  7572. CmdArgs.push_back("-m");
  7573. if (getToolChain().getArch() == llvm::Triple::mips64)
  7574. CmdArgs.push_back("elf64btsmip");
  7575. else
  7576. CmdArgs.push_back("elf64ltsmip");
  7577. }
  7578. break;
  7579. case llvm::Triple::ppc:
  7580. CmdArgs.push_back("-m");
  7581. CmdArgs.push_back("elf32ppc_nbsd");
  7582. break;
  7583. case llvm::Triple::ppc64:
  7584. case llvm::Triple::ppc64le:
  7585. CmdArgs.push_back("-m");
  7586. CmdArgs.push_back("elf64ppc");
  7587. break;
  7588. case llvm::Triple::sparc:
  7589. CmdArgs.push_back("-m");
  7590. CmdArgs.push_back("elf32_sparc");
  7591. break;
  7592. case llvm::Triple::sparcv9:
  7593. CmdArgs.push_back("-m");
  7594. CmdArgs.push_back("elf64_sparc");
  7595. break;
  7596. default:
  7597. break;
  7598. }
  7599. if (Output.isFilename()) {
  7600. CmdArgs.push_back("-o");
  7601. CmdArgs.push_back(Output.getFilename());
  7602. } else {
  7603. assert(Output.isNothing() && "Invalid output.");
  7604. }
  7605. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7606. if (!Args.hasArg(options::OPT_shared)) {
  7607. CmdArgs.push_back(
  7608. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7609. }
  7610. CmdArgs.push_back(
  7611. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7612. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) {
  7613. CmdArgs.push_back(
  7614. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7615. } else {
  7616. CmdArgs.push_back(
  7617. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7618. }
  7619. }
  7620. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7621. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7622. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7623. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7624. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7625. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7626. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7627. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7628. unsigned Major, Minor, Micro;
  7629. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  7630. bool useLibgcc = true;
  7631. if (Major >= 7 || Major == 0) {
  7632. switch (getToolChain().getArch()) {
  7633. case llvm::Triple::aarch64:
  7634. case llvm::Triple::arm:
  7635. case llvm::Triple::armeb:
  7636. case llvm::Triple::thumb:
  7637. case llvm::Triple::thumbeb:
  7638. case llvm::Triple::ppc:
  7639. case llvm::Triple::ppc64:
  7640. case llvm::Triple::ppc64le:
  7641. case llvm::Triple::sparc:
  7642. case llvm::Triple::sparcv9:
  7643. case llvm::Triple::x86:
  7644. case llvm::Triple::x86_64:
  7645. useLibgcc = false;
  7646. break;
  7647. default:
  7648. break;
  7649. }
  7650. }
  7651. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7652. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  7653. if (D.CCCIsCXX()) {
  7654. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7655. CmdArgs.push_back("-lm");
  7656. }
  7657. if (Args.hasArg(options::OPT_pthread))
  7658. CmdArgs.push_back("-lpthread");
  7659. CmdArgs.push_back("-lc");
  7660. if (useLibgcc) {
  7661. if (Args.hasArg(options::OPT_static)) {
  7662. // libgcc_eh depends on libc, so resolve as much as possible,
  7663. // pull in any new requirements from libc and then get the rest
  7664. // of libgcc.
  7665. CmdArgs.push_back("-lgcc_eh");
  7666. CmdArgs.push_back("-lc");
  7667. CmdArgs.push_back("-lgcc");
  7668. } else {
  7669. CmdArgs.push_back("-lgcc");
  7670. CmdArgs.push_back("--as-needed");
  7671. CmdArgs.push_back("-lgcc_s");
  7672. CmdArgs.push_back("--no-as-needed");
  7673. }
  7674. }
  7675. }
  7676. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7677. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  7678. CmdArgs.push_back(
  7679. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7680. else
  7681. CmdArgs.push_back(
  7682. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7683. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7684. }
  7685. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7686. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7687. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7688. }
  7689. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7690. const InputInfo &Output,
  7691. const InputInfoList &Inputs,
  7692. const ArgList &Args,
  7693. const char *LinkingOutput) const {
  7694. claimNoWarnArgs(Args);
  7695. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7696. llvm::Triple Triple = llvm::Triple(TripleStr);
  7697. ArgStringList CmdArgs;
  7698. llvm::Reloc::Model RelocationModel;
  7699. unsigned PICLevel;
  7700. bool IsPIE;
  7701. std::tie(RelocationModel, PICLevel, IsPIE) =
  7702. ParsePICArgs(getToolChain(), Triple, Args);
  7703. switch (getToolChain().getArch()) {
  7704. default:
  7705. break;
  7706. // Add --32/--64 to make sure we get the format we want.
  7707. // This is incomplete
  7708. case llvm::Triple::x86:
  7709. CmdArgs.push_back("--32");
  7710. break;
  7711. case llvm::Triple::x86_64:
  7712. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7713. CmdArgs.push_back("--x32");
  7714. else
  7715. CmdArgs.push_back("--64");
  7716. break;
  7717. case llvm::Triple::ppc:
  7718. CmdArgs.push_back("-a32");
  7719. CmdArgs.push_back("-mppc");
  7720. CmdArgs.push_back("-many");
  7721. break;
  7722. case llvm::Triple::ppc64:
  7723. CmdArgs.push_back("-a64");
  7724. CmdArgs.push_back("-mppc64");
  7725. CmdArgs.push_back("-many");
  7726. break;
  7727. case llvm::Triple::ppc64le:
  7728. CmdArgs.push_back("-a64");
  7729. CmdArgs.push_back("-mppc64");
  7730. CmdArgs.push_back("-many");
  7731. CmdArgs.push_back("-mlittle-endian");
  7732. break;
  7733. case llvm::Triple::sparc:
  7734. case llvm::Triple::sparcel: {
  7735. CmdArgs.push_back("-32");
  7736. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7737. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7738. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7739. break;
  7740. }
  7741. case llvm::Triple::sparcv9: {
  7742. CmdArgs.push_back("-64");
  7743. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7744. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7745. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7746. break;
  7747. }
  7748. case llvm::Triple::arm:
  7749. case llvm::Triple::armeb:
  7750. case llvm::Triple::thumb:
  7751. case llvm::Triple::thumbeb: {
  7752. const llvm::Triple &Triple2 = getToolChain().getTriple();
  7753. switch (Triple2.getSubArch()) {
  7754. case llvm::Triple::ARMSubArch_v7:
  7755. CmdArgs.push_back("-mfpu=neon");
  7756. break;
  7757. case llvm::Triple::ARMSubArch_v8:
  7758. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  7759. break;
  7760. default:
  7761. break;
  7762. }
  7763. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  7764. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  7765. case arm::FloatABI::Soft:
  7766. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  7767. break;
  7768. case arm::FloatABI::SoftFP:
  7769. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  7770. break;
  7771. case arm::FloatABI::Hard:
  7772. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  7773. break;
  7774. }
  7775. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  7776. // FIXME: remove krait check when GNU tools support krait cpu
  7777. // for now replace it with -mcpu=cortex-a15 to avoid a lower
  7778. // march from being picked in the absence of a cpu flag.
  7779. Arg *A;
  7780. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  7781. StringRef(A->getValue()).lower() == "krait")
  7782. CmdArgs.push_back("-mcpu=cortex-a15");
  7783. else
  7784. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  7785. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  7786. break;
  7787. }
  7788. case llvm::Triple::mips:
  7789. case llvm::Triple::mipsel:
  7790. case llvm::Triple::mips64:
  7791. case llvm::Triple::mips64el: {
  7792. StringRef CPUName;
  7793. StringRef ABIName;
  7794. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7795. ABIName = getGnuCompatibleMipsABIName(ABIName);
  7796. CmdArgs.push_back("-march");
  7797. CmdArgs.push_back(CPUName.data());
  7798. CmdArgs.push_back("-mabi");
  7799. CmdArgs.push_back(ABIName.data());
  7800. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  7801. // or -mshared (not implemented) is in effect.
  7802. if (RelocationModel == llvm::Reloc::Static)
  7803. CmdArgs.push_back("-mno-shared");
  7804. // LLVM doesn't support -mplt yet and acts as if it is always given.
  7805. // However, -mplt has no effect with the N64 ABI.
  7806. CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
  7807. if (getToolChain().getArch() == llvm::Triple::mips ||
  7808. getToolChain().getArch() == llvm::Triple::mips64)
  7809. CmdArgs.push_back("-EB");
  7810. else
  7811. CmdArgs.push_back("-EL");
  7812. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  7813. if (StringRef(A->getValue()) == "2008")
  7814. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  7815. }
  7816. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  7817. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  7818. options::OPT_mfp64)) {
  7819. A->claim();
  7820. A->render(Args, CmdArgs);
  7821. } else if (mips::shouldUseFPXX(
  7822. Args, getToolChain().getTriple(), CPUName, ABIName,
  7823. getMipsFloatABI(getToolChain().getDriver(), Args)))
  7824. CmdArgs.push_back("-mfpxx");
  7825. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  7826. // -mno-mips16 is actually -no-mips16.
  7827. if (Arg *A =
  7828. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  7829. if (A->getOption().matches(options::OPT_mips16)) {
  7830. A->claim();
  7831. A->render(Args, CmdArgs);
  7832. } else {
  7833. A->claim();
  7834. CmdArgs.push_back("-no-mips16");
  7835. }
  7836. }
  7837. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  7838. options::OPT_mno_micromips);
  7839. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  7840. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  7841. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  7842. // Do not use AddLastArg because not all versions of MIPS assembler
  7843. // support -mmsa / -mno-msa options.
  7844. if (A->getOption().matches(options::OPT_mmsa))
  7845. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  7846. }
  7847. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  7848. options::OPT_msoft_float);
  7849. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  7850. options::OPT_msingle_float);
  7851. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  7852. options::OPT_mno_odd_spreg);
  7853. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7854. break;
  7855. }
  7856. case llvm::Triple::systemz: {
  7857. // Always pass an -march option, since our default of z10 is later
  7858. // than the GNU assembler's default.
  7859. StringRef CPUName = getSystemZTargetCPU(Args);
  7860. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  7861. break;
  7862. }
  7863. }
  7864. Args.AddAllArgs(CmdArgs, options::OPT_I);
  7865. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7866. CmdArgs.push_back("-o");
  7867. CmdArgs.push_back(Output.getFilename());
  7868. for (const auto &II : Inputs)
  7869. CmdArgs.push_back(II.getFilename());
  7870. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7871. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7872. // Handle the debug info splitting at object creation time if we're
  7873. // creating an object.
  7874. // TODO: Currently only works on linux with newer objcopy.
  7875. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  7876. getToolChain().getTriple().isOSLinux())
  7877. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  7878. SplitDebugName(Args, Inputs[0]));
  7879. }
  7880. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  7881. ArgStringList &CmdArgs, const ArgList &Args) {
  7882. bool isAndroid = Triple.isAndroid();
  7883. bool isCygMing = Triple.isOSCygMing();
  7884. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  7885. Args.hasArg(options::OPT_static);
  7886. if (!D.CCCIsCXX())
  7887. CmdArgs.push_back("-lgcc");
  7888. if (StaticLibgcc || isAndroid) {
  7889. if (D.CCCIsCXX())
  7890. CmdArgs.push_back("-lgcc");
  7891. } else {
  7892. if (!D.CCCIsCXX() && !isCygMing)
  7893. CmdArgs.push_back("--as-needed");
  7894. CmdArgs.push_back("-lgcc_s");
  7895. if (!D.CCCIsCXX() && !isCygMing)
  7896. CmdArgs.push_back("--no-as-needed");
  7897. }
  7898. if (StaticLibgcc && !isAndroid)
  7899. CmdArgs.push_back("-lgcc_eh");
  7900. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  7901. CmdArgs.push_back("-lgcc");
  7902. // According to Android ABI, we have to link with libdl if we are
  7903. // linking with non-static libgcc.
  7904. //
  7905. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  7906. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  7907. if (isAndroid && !StaticLibgcc)
  7908. CmdArgs.push_back("-ldl");
  7909. }
  7910. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  7911. ArgStringList &CmdArgs, const ArgList &Args) {
  7912. // Make use of compiler-rt if --rtlib option is used
  7913. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  7914. switch (RLT) {
  7915. case ToolChain::RLT_CompilerRT:
  7916. switch (TC.getTriple().getOS()) {
  7917. default:
  7918. llvm_unreachable("unsupported OS");
  7919. case llvm::Triple::Win32:
  7920. case llvm::Triple::Linux:
  7921. addClangRT(TC, Args, CmdArgs);
  7922. break;
  7923. }
  7924. break;
  7925. case ToolChain::RLT_Libgcc:
  7926. // Make sure libgcc is not used under MSVC environment by default
  7927. if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
  7928. // Issue error diagnostic if libgcc is explicitly specified
  7929. // through command line as --rtlib option argument.
  7930. if (Args.hasArg(options::OPT_rtlib_EQ)) {
  7931. TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
  7932. << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
  7933. }
  7934. } else
  7935. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  7936. break;
  7937. }
  7938. }
  7939. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  7940. switch (T.getArch()) {
  7941. case llvm::Triple::x86:
  7942. return "elf_i386";
  7943. case llvm::Triple::aarch64:
  7944. return "aarch64linux";
  7945. case llvm::Triple::aarch64_be:
  7946. return "aarch64_be_linux";
  7947. case llvm::Triple::arm:
  7948. case llvm::Triple::thumb:
  7949. return "armelf_linux_eabi";
  7950. case llvm::Triple::armeb:
  7951. case llvm::Triple::thumbeb:
  7952. return "armelfb_linux_eabi";
  7953. case llvm::Triple::ppc:
  7954. return "elf32ppclinux";
  7955. case llvm::Triple::ppc64:
  7956. return "elf64ppc";
  7957. case llvm::Triple::ppc64le:
  7958. return "elf64lppc";
  7959. case llvm::Triple::sparc:
  7960. case llvm::Triple::sparcel:
  7961. return "elf32_sparc";
  7962. case llvm::Triple::sparcv9:
  7963. return "elf64_sparc";
  7964. case llvm::Triple::mips:
  7965. return "elf32btsmip";
  7966. case llvm::Triple::mipsel:
  7967. return "elf32ltsmip";
  7968. case llvm::Triple::mips64:
  7969. if (mips::hasMipsAbiArg(Args, "n32"))
  7970. return "elf32btsmipn32";
  7971. return "elf64btsmip";
  7972. case llvm::Triple::mips64el:
  7973. if (mips::hasMipsAbiArg(Args, "n32"))
  7974. return "elf32ltsmipn32";
  7975. return "elf64ltsmip";
  7976. case llvm::Triple::systemz:
  7977. return "elf64_s390";
  7978. case llvm::Triple::x86_64:
  7979. if (T.getEnvironment() == llvm::Triple::GNUX32)
  7980. return "elf32_x86_64";
  7981. return "elf_x86_64";
  7982. default:
  7983. llvm_unreachable("Unexpected arch");
  7984. }
  7985. }
  7986. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7987. const InputInfo &Output,
  7988. const InputInfoList &Inputs,
  7989. const ArgList &Args,
  7990. const char *LinkingOutput) const {
  7991. const toolchains::Linux &ToolChain =
  7992. static_cast<const toolchains::Linux &>(getToolChain());
  7993. const Driver &D = ToolChain.getDriver();
  7994. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7995. llvm::Triple Triple = llvm::Triple(TripleStr);
  7996. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7997. const bool isAndroid = ToolChain.getTriple().isAndroid();
  7998. const bool IsPIE =
  7999. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  8000. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  8001. const bool HasCRTBeginEndFiles =
  8002. ToolChain.getTriple().hasEnvironment() ||
  8003. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  8004. ArgStringList CmdArgs;
  8005. // Silence warning for "clang -g foo.o -o foo"
  8006. Args.ClaimAllArgs(options::OPT_g_Group);
  8007. // and "clang -emit-llvm foo.o -o foo"
  8008. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8009. // and for "clang -w foo.o -o foo". Other warning options are already
  8010. // handled somewhere else.
  8011. Args.ClaimAllArgs(options::OPT_w);
  8012. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8013. if (llvm::sys::path::filename(Exec) == "lld") {
  8014. CmdArgs.push_back("-flavor");
  8015. CmdArgs.push_back("old-gnu");
  8016. CmdArgs.push_back("-target");
  8017. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  8018. }
  8019. if (!D.SysRoot.empty())
  8020. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8021. if (IsPIE)
  8022. CmdArgs.push_back("-pie");
  8023. if (Args.hasArg(options::OPT_rdynamic))
  8024. CmdArgs.push_back("-export-dynamic");
  8025. if (Args.hasArg(options::OPT_s))
  8026. CmdArgs.push_back("-s");
  8027. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  8028. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  8029. for (const auto &Opt : ToolChain.ExtraOpts)
  8030. CmdArgs.push_back(Opt.c_str());
  8031. if (!Args.hasArg(options::OPT_static)) {
  8032. CmdArgs.push_back("--eh-frame-hdr");
  8033. }
  8034. CmdArgs.push_back("-m");
  8035. CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
  8036. if (Args.hasArg(options::OPT_static)) {
  8037. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  8038. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  8039. CmdArgs.push_back("-Bstatic");
  8040. else
  8041. CmdArgs.push_back("-static");
  8042. } else if (Args.hasArg(options::OPT_shared)) {
  8043. CmdArgs.push_back("-shared");
  8044. }
  8045. if (!Args.hasArg(options::OPT_static)) {
  8046. if (Args.hasArg(options::OPT_rdynamic))
  8047. CmdArgs.push_back("-export-dynamic");
  8048. if (!Args.hasArg(options::OPT_shared)) {
  8049. const std::string Loader =
  8050. D.DyldPrefix + ToolChain.getDynamicLinker(Args);
  8051. CmdArgs.push_back("-dynamic-linker");
  8052. CmdArgs.push_back(Args.MakeArgString(Loader));
  8053. }
  8054. }
  8055. CmdArgs.push_back("-o");
  8056. CmdArgs.push_back(Output.getFilename());
  8057. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8058. if (!isAndroid) {
  8059. const char *crt1 = nullptr;
  8060. if (!Args.hasArg(options::OPT_shared)) {
  8061. if (Args.hasArg(options::OPT_pg))
  8062. crt1 = "gcrt1.o";
  8063. else if (IsPIE)
  8064. crt1 = "Scrt1.o";
  8065. else
  8066. crt1 = "crt1.o";
  8067. }
  8068. if (crt1)
  8069. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  8070. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8071. }
  8072. const char *crtbegin;
  8073. if (Args.hasArg(options::OPT_static))
  8074. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  8075. else if (Args.hasArg(options::OPT_shared))
  8076. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  8077. else if (IsPIE)
  8078. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  8079. else
  8080. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  8081. if (HasCRTBeginEndFiles)
  8082. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8083. // Add crtfastmath.o if available and fast math is enabled.
  8084. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8085. }
  8086. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8087. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8088. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8089. if (D.isUsingLTO())
  8090. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  8091. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8092. CmdArgs.push_back("--no-demangle");
  8093. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  8094. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8095. // The profile runtime also needs access to system libraries.
  8096. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8097. if (D.CCCIsCXX() &&
  8098. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8099. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8100. !Args.hasArg(options::OPT_static);
  8101. if (OnlyLibstdcxxStatic)
  8102. CmdArgs.push_back("-Bstatic");
  8103. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8104. if (OnlyLibstdcxxStatic)
  8105. CmdArgs.push_back("-Bdynamic");
  8106. CmdArgs.push_back("-lm");
  8107. }
  8108. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  8109. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  8110. if (!Args.hasArg(options::OPT_nostdlib)) {
  8111. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8112. if (Args.hasArg(options::OPT_static))
  8113. CmdArgs.push_back("--start-group");
  8114. if (NeedsSanitizerDeps)
  8115. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  8116. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  8117. Args.hasArg(options::OPT_pthreads);
  8118. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8119. options::OPT_fno_openmp, false)) {
  8120. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  8121. // FIXME: Does this really make sense for all GNU toolchains?
  8122. WantPthread = true;
  8123. // Also link the particular OpenMP runtimes.
  8124. switch (getOpenMPRuntime(ToolChain, Args)) {
  8125. case OMPRT_OMP:
  8126. CmdArgs.push_back("-lomp");
  8127. break;
  8128. case OMPRT_GOMP:
  8129. CmdArgs.push_back("-lgomp");
  8130. // FIXME: Exclude this for platforms with libgomp that don't require
  8131. // librt. Most modern Linux platforms require it, but some may not.
  8132. CmdArgs.push_back("-lrt");
  8133. break;
  8134. case OMPRT_IOMP5:
  8135. CmdArgs.push_back("-liomp5");
  8136. break;
  8137. case OMPRT_Unknown:
  8138. // Already diagnosed.
  8139. break;
  8140. }
  8141. }
  8142. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8143. if (WantPthread && !isAndroid)
  8144. CmdArgs.push_back("-lpthread");
  8145. if (Args.hasArg(options::OPT_fsplit_stack))
  8146. CmdArgs.push_back("--wrap=pthread_create");
  8147. CmdArgs.push_back("-lc");
  8148. if (Args.hasArg(options::OPT_static))
  8149. CmdArgs.push_back("--end-group");
  8150. else
  8151. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  8152. }
  8153. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8154. const char *crtend;
  8155. if (Args.hasArg(options::OPT_shared))
  8156. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  8157. else if (IsPIE)
  8158. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  8159. else
  8160. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  8161. if (HasCRTBeginEndFiles)
  8162. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8163. if (!isAndroid)
  8164. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8165. }
  8166. }
  8167. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8168. }
  8169. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  8170. // for the various SFI requirements like register masking. The assembly tool
  8171. // inserts the file containing the macros as an input into all the assembly
  8172. // jobs.
  8173. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  8174. const InputInfo &Output,
  8175. const InputInfoList &Inputs,
  8176. const ArgList &Args,
  8177. const char *LinkingOutput) const {
  8178. const toolchains::NaClToolChain &ToolChain =
  8179. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  8180. InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
  8181. "nacl-arm-macros.s");
  8182. InputInfoList NewInputs;
  8183. NewInputs.push_back(NaClMacros);
  8184. NewInputs.append(Inputs.begin(), Inputs.end());
  8185. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  8186. LinkingOutput);
  8187. }
  8188. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  8189. // we use static by default, do not yet support sanitizers or LTO, and a few
  8190. // others. Eventually we can support more of that and hopefully migrate back
  8191. // to gnutools::Linker.
  8192. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8193. const InputInfo &Output,
  8194. const InputInfoList &Inputs,
  8195. const ArgList &Args,
  8196. const char *LinkingOutput) const {
  8197. const toolchains::NaClToolChain &ToolChain =
  8198. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  8199. const Driver &D = ToolChain.getDriver();
  8200. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  8201. const bool IsStatic =
  8202. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  8203. ArgStringList CmdArgs;
  8204. // Silence warning for "clang -g foo.o -o foo"
  8205. Args.ClaimAllArgs(options::OPT_g_Group);
  8206. // and "clang -emit-llvm foo.o -o foo"
  8207. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8208. // and for "clang -w foo.o -o foo". Other warning options are already
  8209. // handled somewhere else.
  8210. Args.ClaimAllArgs(options::OPT_w);
  8211. if (!D.SysRoot.empty())
  8212. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8213. if (Args.hasArg(options::OPT_rdynamic))
  8214. CmdArgs.push_back("-export-dynamic");
  8215. if (Args.hasArg(options::OPT_s))
  8216. CmdArgs.push_back("-s");
  8217. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  8218. // from there is --build-id, which we do want.
  8219. CmdArgs.push_back("--build-id");
  8220. if (!IsStatic)
  8221. CmdArgs.push_back("--eh-frame-hdr");
  8222. CmdArgs.push_back("-m");
  8223. if (Arch == llvm::Triple::x86)
  8224. CmdArgs.push_back("elf_i386_nacl");
  8225. else if (Arch == llvm::Triple::arm)
  8226. CmdArgs.push_back("armelf_nacl");
  8227. else if (Arch == llvm::Triple::x86_64)
  8228. CmdArgs.push_back("elf_x86_64_nacl");
  8229. else if (Arch == llvm::Triple::mipsel)
  8230. CmdArgs.push_back("mipselelf_nacl");
  8231. else
  8232. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  8233. << "Native Client";
  8234. if (IsStatic)
  8235. CmdArgs.push_back("-static");
  8236. else if (Args.hasArg(options::OPT_shared))
  8237. CmdArgs.push_back("-shared");
  8238. CmdArgs.push_back("-o");
  8239. CmdArgs.push_back(Output.getFilename());
  8240. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8241. if (!Args.hasArg(options::OPT_shared))
  8242. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  8243. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  8244. const char *crtbegin;
  8245. if (IsStatic)
  8246. crtbegin = "crtbeginT.o";
  8247. else if (Args.hasArg(options::OPT_shared))
  8248. crtbegin = "crtbeginS.o";
  8249. else
  8250. crtbegin = "crtbegin.o";
  8251. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  8252. }
  8253. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8254. Args.AddAllArgs(CmdArgs, options::OPT_u);
  8255. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  8256. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  8257. CmdArgs.push_back("--no-demangle");
  8258. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  8259. if (D.CCCIsCXX() &&
  8260. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8261. bool OnlyLibstdcxxStatic =
  8262. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  8263. if (OnlyLibstdcxxStatic)
  8264. CmdArgs.push_back("-Bstatic");
  8265. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  8266. if (OnlyLibstdcxxStatic)
  8267. CmdArgs.push_back("-Bdynamic");
  8268. CmdArgs.push_back("-lm");
  8269. }
  8270. if (!Args.hasArg(options::OPT_nostdlib)) {
  8271. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8272. // Always use groups, since it has no effect on dynamic libraries.
  8273. CmdArgs.push_back("--start-group");
  8274. CmdArgs.push_back("-lc");
  8275. // NaCl's libc++ currently requires libpthread, so just always include it
  8276. // in the group for C++.
  8277. if (Args.hasArg(options::OPT_pthread) ||
  8278. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  8279. // Gold, used by Mips, handles nested groups differently than ld, and
  8280. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  8281. // which is not a desired behaviour here.
  8282. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  8283. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8284. CmdArgs.push_back("-lnacl");
  8285. CmdArgs.push_back("-lpthread");
  8286. }
  8287. CmdArgs.push_back("-lgcc");
  8288. CmdArgs.push_back("--as-needed");
  8289. if (IsStatic)
  8290. CmdArgs.push_back("-lgcc_eh");
  8291. else
  8292. CmdArgs.push_back("-lgcc_s");
  8293. CmdArgs.push_back("--no-as-needed");
  8294. // Mips needs to create and use pnacl_legacy library that contains
  8295. // definitions from bitcode/pnaclmm.c and definitions for
  8296. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  8297. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8298. CmdArgs.push_back("-lpnacl_legacy");
  8299. CmdArgs.push_back("--end-group");
  8300. }
  8301. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8302. const char *crtend;
  8303. if (Args.hasArg(options::OPT_shared))
  8304. crtend = "crtendS.o";
  8305. else
  8306. crtend = "crtend.o";
  8307. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8308. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8309. }
  8310. }
  8311. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8312. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8313. }
  8314. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8315. const InputInfo &Output,
  8316. const InputInfoList &Inputs,
  8317. const ArgList &Args,
  8318. const char *LinkingOutput) const {
  8319. claimNoWarnArgs(Args);
  8320. ArgStringList CmdArgs;
  8321. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8322. CmdArgs.push_back("-o");
  8323. CmdArgs.push_back(Output.getFilename());
  8324. for (const auto &II : Inputs)
  8325. CmdArgs.push_back(II.getFilename());
  8326. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8327. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8328. }
  8329. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8330. const InputInfo &Output,
  8331. const InputInfoList &Inputs,
  8332. const ArgList &Args,
  8333. const char *LinkingOutput) const {
  8334. const Driver &D = getToolChain().getDriver();
  8335. ArgStringList CmdArgs;
  8336. if (Output.isFilename()) {
  8337. CmdArgs.push_back("-o");
  8338. CmdArgs.push_back(Output.getFilename());
  8339. } else {
  8340. assert(Output.isNothing() && "Invalid output.");
  8341. }
  8342. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8343. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8344. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8345. CmdArgs.push_back(
  8346. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8347. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8348. }
  8349. Args.AddAllArgs(CmdArgs,
  8350. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8351. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8352. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8353. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8354. if (D.CCCIsCXX()) {
  8355. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8356. CmdArgs.push_back("-lm");
  8357. }
  8358. }
  8359. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8360. if (Args.hasArg(options::OPT_pthread))
  8361. CmdArgs.push_back("-lpthread");
  8362. CmdArgs.push_back("-lc");
  8363. CmdArgs.push_back("-lCompilerRT-Generic");
  8364. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  8365. CmdArgs.push_back(
  8366. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8367. }
  8368. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8369. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8370. }
  8371. /// DragonFly Tools
  8372. // For now, DragonFly Assemble does just about the same as for
  8373. // FreeBSD, but this may change soon.
  8374. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8375. const InputInfo &Output,
  8376. const InputInfoList &Inputs,
  8377. const ArgList &Args,
  8378. const char *LinkingOutput) const {
  8379. claimNoWarnArgs(Args);
  8380. ArgStringList CmdArgs;
  8381. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8382. // instruct as in the base system to assemble 32-bit code.
  8383. if (getToolChain().getArch() == llvm::Triple::x86)
  8384. CmdArgs.push_back("--32");
  8385. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8386. CmdArgs.push_back("-o");
  8387. CmdArgs.push_back(Output.getFilename());
  8388. for (const auto &II : Inputs)
  8389. CmdArgs.push_back(II.getFilename());
  8390. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8391. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8392. }
  8393. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8394. const InputInfo &Output,
  8395. const InputInfoList &Inputs,
  8396. const ArgList &Args,
  8397. const char *LinkingOutput) const {
  8398. const Driver &D = getToolChain().getDriver();
  8399. ArgStringList CmdArgs;
  8400. if (!D.SysRoot.empty())
  8401. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8402. CmdArgs.push_back("--eh-frame-hdr");
  8403. if (Args.hasArg(options::OPT_static)) {
  8404. CmdArgs.push_back("-Bstatic");
  8405. } else {
  8406. if (Args.hasArg(options::OPT_rdynamic))
  8407. CmdArgs.push_back("-export-dynamic");
  8408. if (Args.hasArg(options::OPT_shared))
  8409. CmdArgs.push_back("-Bshareable");
  8410. else {
  8411. CmdArgs.push_back("-dynamic-linker");
  8412. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  8413. }
  8414. CmdArgs.push_back("--hash-style=gnu");
  8415. CmdArgs.push_back("--enable-new-dtags");
  8416. }
  8417. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8418. // instruct ld in the base system to link 32-bit code.
  8419. if (getToolChain().getArch() == llvm::Triple::x86) {
  8420. CmdArgs.push_back("-m");
  8421. CmdArgs.push_back("elf_i386");
  8422. }
  8423. if (Output.isFilename()) {
  8424. CmdArgs.push_back("-o");
  8425. CmdArgs.push_back(Output.getFilename());
  8426. } else {
  8427. assert(Output.isNothing() && "Invalid output.");
  8428. }
  8429. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8430. if (!Args.hasArg(options::OPT_shared)) {
  8431. if (Args.hasArg(options::OPT_pg))
  8432. CmdArgs.push_back(
  8433. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  8434. else {
  8435. if (Args.hasArg(options::OPT_pie))
  8436. CmdArgs.push_back(
  8437. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  8438. else
  8439. CmdArgs.push_back(
  8440. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8441. }
  8442. }
  8443. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8444. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8445. CmdArgs.push_back(
  8446. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  8447. else
  8448. CmdArgs.push_back(
  8449. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8450. }
  8451. Args.AddAllArgs(CmdArgs,
  8452. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8453. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8454. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8455. CmdArgs.push_back("-L/usr/lib/gcc50");
  8456. if (!Args.hasArg(options::OPT_static)) {
  8457. CmdArgs.push_back("-rpath");
  8458. CmdArgs.push_back("/usr/lib/gcc50");
  8459. }
  8460. if (D.CCCIsCXX()) {
  8461. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8462. CmdArgs.push_back("-lm");
  8463. }
  8464. if (Args.hasArg(options::OPT_pthread))
  8465. CmdArgs.push_back("-lpthread");
  8466. if (!Args.hasArg(options::OPT_nolibc)) {
  8467. CmdArgs.push_back("-lc");
  8468. }
  8469. if (Args.hasArg(options::OPT_static) ||
  8470. Args.hasArg(options::OPT_static_libgcc)) {
  8471. CmdArgs.push_back("-lgcc");
  8472. CmdArgs.push_back("-lgcc_eh");
  8473. } else {
  8474. if (Args.hasArg(options::OPT_shared_libgcc)) {
  8475. CmdArgs.push_back("-lgcc_pic");
  8476. if (!Args.hasArg(options::OPT_shared))
  8477. CmdArgs.push_back("-lgcc");
  8478. } else {
  8479. CmdArgs.push_back("-lgcc");
  8480. CmdArgs.push_back("--as-needed");
  8481. CmdArgs.push_back("-lgcc_pic");
  8482. CmdArgs.push_back("--no-as-needed");
  8483. }
  8484. }
  8485. }
  8486. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8487. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8488. CmdArgs.push_back(
  8489. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  8490. else
  8491. CmdArgs.push_back(
  8492. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8493. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8494. }
  8495. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8496. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8497. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8498. }
  8499. // Try to find Exe from a Visual Studio distribution. This first tries to find
  8500. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  8501. // making sure that whatever executable that's found is not a same-named exe
  8502. // from clang itself to prevent clang from falling back to itself.
  8503. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  8504. const char *Exe,
  8505. const char *ClangProgramPath) {
  8506. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8507. std::string visualStudioBinDir;
  8508. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  8509. visualStudioBinDir)) {
  8510. SmallString<128> FilePath(visualStudioBinDir);
  8511. llvm::sys::path::append(FilePath, Exe);
  8512. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  8513. return FilePath.str();
  8514. }
  8515. return Exe;
  8516. }
  8517. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8518. const InputInfo &Output,
  8519. const InputInfoList &Inputs,
  8520. const ArgList &Args,
  8521. const char *LinkingOutput) const {
  8522. ArgStringList CmdArgs;
  8523. const ToolChain &TC = getToolChain();
  8524. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  8525. if (Output.isFilename())
  8526. CmdArgs.push_back(
  8527. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  8528. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
  8529. !C.getDriver().IsCLMode())
  8530. CmdArgs.push_back("-defaultlib:libcmt");
  8531. if (!llvm::sys::Process::GetEnv("LIB")) {
  8532. // If the VC environment hasn't been configured (perhaps because the user
  8533. // did not run vcvarsall), try to build a consistent link environment. If
  8534. // the environment variable is set however, assume the user knows what
  8535. // they're doing.
  8536. std::string VisualStudioDir;
  8537. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8538. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  8539. SmallString<128> LibDir(VisualStudioDir);
  8540. llvm::sys::path::append(LibDir, "VC", "lib");
  8541. switch (MSVC.getArch()) {
  8542. case llvm::Triple::x86:
  8543. // x86 just puts the libraries directly in lib
  8544. break;
  8545. case llvm::Triple::x86_64:
  8546. llvm::sys::path::append(LibDir, "amd64");
  8547. break;
  8548. case llvm::Triple::arm:
  8549. llvm::sys::path::append(LibDir, "arm");
  8550. break;
  8551. default:
  8552. break;
  8553. }
  8554. CmdArgs.push_back(
  8555. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  8556. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  8557. std::string UniversalCRTLibPath;
  8558. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  8559. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8560. UniversalCRTLibPath.c_str()));
  8561. }
  8562. }
  8563. std::string WindowsSdkLibPath;
  8564. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  8565. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8566. WindowsSdkLibPath.c_str()));
  8567. }
  8568. CmdArgs.push_back("-nologo");
  8569. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
  8570. CmdArgs.push_back("-debug");
  8571. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  8572. options::OPT_shared);
  8573. if (DLL) {
  8574. CmdArgs.push_back(Args.MakeArgString("-dll"));
  8575. SmallString<128> ImplibName(Output.getFilename());
  8576. llvm::sys::path::replace_extension(ImplibName, "lib");
  8577. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  8578. }
  8579. if (TC.getSanitizerArgs().needsAsanRt()) {
  8580. CmdArgs.push_back(Args.MakeArgString("-debug"));
  8581. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  8582. if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  8583. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  8584. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8585. // Make sure the dynamic runtime thunk is not optimized out at link time
  8586. // to ensure proper SEH handling.
  8587. CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
  8588. } else if (DLL) {
  8589. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  8590. } else {
  8591. for (const auto &Lib : {"asan", "asan_cxx"})
  8592. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8593. }
  8594. }
  8595. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  8596. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8597. options::OPT_fno_openmp, false)) {
  8598. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  8599. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  8600. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8601. TC.getDriver().Dir + "/../lib"));
  8602. switch (getOpenMPRuntime(getToolChain(), Args)) {
  8603. case OMPRT_OMP:
  8604. CmdArgs.push_back("-defaultlib:libomp.lib");
  8605. break;
  8606. case OMPRT_IOMP5:
  8607. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  8608. break;
  8609. case OMPRT_GOMP:
  8610. break;
  8611. case OMPRT_Unknown:
  8612. // Already diagnosed.
  8613. break;
  8614. }
  8615. }
  8616. // Add compiler-rt lib in case if it was explicitly
  8617. // specified as an argument for --rtlib option.
  8618. if (!Args.hasArg(options::OPT_nostdlib)) {
  8619. AddRunTimeLibs(TC, TC.getDriver(), CmdArgs, Args);
  8620. }
  8621. // Add filenames, libraries, and other linker inputs.
  8622. for (const auto &Input : Inputs) {
  8623. if (Input.isFilename()) {
  8624. CmdArgs.push_back(Input.getFilename());
  8625. continue;
  8626. }
  8627. const Arg &A = Input.getInputArg();
  8628. // Render -l options differently for the MSVC linker.
  8629. if (A.getOption().matches(options::OPT_l)) {
  8630. StringRef Lib = A.getValue();
  8631. const char *LinkLibArg;
  8632. if (Lib.endswith(".lib"))
  8633. LinkLibArg = Args.MakeArgString(Lib);
  8634. else
  8635. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  8636. CmdArgs.push_back(LinkLibArg);
  8637. continue;
  8638. }
  8639. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  8640. // or -L. Render it, even if MSVC doesn't understand it.
  8641. A.renderAsInput(Args, CmdArgs);
  8642. }
  8643. TC.addProfileRTLibs(Args, CmdArgs);
  8644. // We need to special case some linker paths. In the case of lld, we need to
  8645. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  8646. // linker, we need to use a special search algorithm.
  8647. llvm::SmallString<128> linkPath;
  8648. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  8649. if (Linker.equals_lower("lld"))
  8650. Linker = "lld-link";
  8651. if (Linker.equals_lower("link")) {
  8652. // If we're using the MSVC linker, it's not sufficient to just use link
  8653. // from the program PATH, because other environments like GnuWin32 install
  8654. // their own link.exe which may come first.
  8655. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  8656. C.getDriver().getClangProgramPath());
  8657. } else {
  8658. linkPath = Linker;
  8659. llvm::sys::path::replace_extension(linkPath, "exe");
  8660. linkPath = TC.GetProgramPath(linkPath.c_str());
  8661. }
  8662. const char *Exec = Args.MakeArgString(linkPath);
  8663. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8664. }
  8665. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8666. const InputInfo &Output,
  8667. const InputInfoList &Inputs,
  8668. const ArgList &Args,
  8669. const char *LinkingOutput) const {
  8670. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  8671. }
  8672. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  8673. Compilation &C, const JobAction &JA, const InputInfo &Output,
  8674. const InputInfoList &Inputs, const ArgList &Args,
  8675. const char *LinkingOutput) const {
  8676. ArgStringList CmdArgs;
  8677. CmdArgs.push_back("/nologo");
  8678. CmdArgs.push_back("/c"); // Compile only.
  8679. CmdArgs.push_back("/W0"); // No warnings.
  8680. // The goal is to be able to invoke this tool correctly based on
  8681. // any flag accepted by clang-cl.
  8682. // These are spelled the same way in clang and cl.exe,.
  8683. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  8684. // Optimization level.
  8685. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  8686. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  8687. : "/Oi-");
  8688. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  8689. if (A->getOption().getID() == options::OPT_O0) {
  8690. CmdArgs.push_back("/Od");
  8691. } else {
  8692. CmdArgs.push_back("/Og");
  8693. StringRef OptLevel = A->getValue();
  8694. if (OptLevel == "s" || OptLevel == "z")
  8695. CmdArgs.push_back("/Os");
  8696. else
  8697. CmdArgs.push_back("/Ot");
  8698. CmdArgs.push_back("/Ob2");
  8699. }
  8700. }
  8701. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  8702. options::OPT_fno_omit_frame_pointer))
  8703. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  8704. ? "/Oy"
  8705. : "/Oy-");
  8706. if (!Args.hasArg(options::OPT_fwritable_strings))
  8707. CmdArgs.push_back("/GF");
  8708. // Flags for which clang-cl has an alias.
  8709. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  8710. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  8711. /*default=*/false))
  8712. CmdArgs.push_back("/GR-");
  8713. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  8714. options::OPT_fno_function_sections))
  8715. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  8716. ? "/Gy"
  8717. : "/Gy-");
  8718. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  8719. options::OPT_fno_data_sections))
  8720. CmdArgs.push_back(
  8721. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  8722. if (Args.hasArg(options::OPT_fsyntax_only))
  8723. CmdArgs.push_back("/Zs");
  8724. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  8725. options::OPT__SLASH_Z7))
  8726. CmdArgs.push_back("/Z7");
  8727. std::vector<std::string> Includes =
  8728. Args.getAllArgValues(options::OPT_include);
  8729. for (const auto &Include : Includes)
  8730. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  8731. // Flags that can simply be passed through.
  8732. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  8733. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  8734. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX);
  8735. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_GX_);
  8736. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  8737. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  8738. // The order of these flags is relevant, so pick the last one.
  8739. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  8740. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  8741. A->render(Args, CmdArgs);
  8742. // Pass through all unknown arguments so that the fallback command can see
  8743. // them too.
  8744. Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
  8745. // Input filename.
  8746. assert(Inputs.size() == 1);
  8747. const InputInfo &II = Inputs[0];
  8748. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  8749. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  8750. if (II.isFilename())
  8751. CmdArgs.push_back(II.getFilename());
  8752. else
  8753. II.getInputArg().renderAsInput(Args, CmdArgs);
  8754. // Output filename.
  8755. assert(Output.getType() == types::TY_Object);
  8756. const char *Fo =
  8757. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  8758. CmdArgs.push_back(Fo);
  8759. const Driver &D = getToolChain().getDriver();
  8760. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  8761. D.getClangProgramPath());
  8762. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8763. CmdArgs, Inputs);
  8764. }
  8765. /// MinGW Tools
  8766. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8767. const InputInfo &Output,
  8768. const InputInfoList &Inputs,
  8769. const ArgList &Args,
  8770. const char *LinkingOutput) const {
  8771. claimNoWarnArgs(Args);
  8772. ArgStringList CmdArgs;
  8773. if (getToolChain().getArch() == llvm::Triple::x86) {
  8774. CmdArgs.push_back("--32");
  8775. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  8776. CmdArgs.push_back("--64");
  8777. }
  8778. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8779. CmdArgs.push_back("-o");
  8780. CmdArgs.push_back(Output.getFilename());
  8781. for (const auto &II : Inputs)
  8782. CmdArgs.push_back(II.getFilename());
  8783. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8784. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8785. if (Args.hasArg(options::OPT_gsplit_dwarf))
  8786. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8787. SplitDebugName(Args, Inputs[0]));
  8788. }
  8789. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  8790. ArgStringList &CmdArgs) const {
  8791. if (Args.hasArg(options::OPT_mthreads))
  8792. CmdArgs.push_back("-lmingwthrd");
  8793. CmdArgs.push_back("-lmingw32");
  8794. // Make use of compiler-rt if --rtlib option is used
  8795. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  8796. if (RLT == ToolChain::RLT_Libgcc) {
  8797. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  8798. Args.hasArg(options::OPT_static);
  8799. bool Shared = Args.hasArg(options::OPT_shared);
  8800. bool CXX = getToolChain().getDriver().CCCIsCXX();
  8801. if (Static || (!CXX && !Shared)) {
  8802. CmdArgs.push_back("-lgcc");
  8803. CmdArgs.push_back("-lgcc_eh");
  8804. } else {
  8805. CmdArgs.push_back("-lgcc_s");
  8806. CmdArgs.push_back("-lgcc");
  8807. }
  8808. } else {
  8809. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  8810. }
  8811. CmdArgs.push_back("-lmoldname");
  8812. CmdArgs.push_back("-lmingwex");
  8813. CmdArgs.push_back("-lmsvcrt");
  8814. }
  8815. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8816. const InputInfo &Output,
  8817. const InputInfoList &Inputs,
  8818. const ArgList &Args,
  8819. const char *LinkingOutput) const {
  8820. const ToolChain &TC = getToolChain();
  8821. const Driver &D = TC.getDriver();
  8822. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  8823. ArgStringList CmdArgs;
  8824. // Silence warning for "clang -g foo.o -o foo"
  8825. Args.ClaimAllArgs(options::OPT_g_Group);
  8826. // and "clang -emit-llvm foo.o -o foo"
  8827. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8828. // and for "clang -w foo.o -o foo". Other warning options are already
  8829. // handled somewhere else.
  8830. Args.ClaimAllArgs(options::OPT_w);
  8831. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  8832. if (LinkerName.equals_lower("lld")) {
  8833. CmdArgs.push_back("-flavor");
  8834. CmdArgs.push_back("gnu");
  8835. } else if (!LinkerName.equals_lower("ld")) {
  8836. D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
  8837. }
  8838. if (!D.SysRoot.empty())
  8839. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8840. if (Args.hasArg(options::OPT_s))
  8841. CmdArgs.push_back("-s");
  8842. CmdArgs.push_back("-m");
  8843. if (TC.getArch() == llvm::Triple::x86)
  8844. CmdArgs.push_back("i386pe");
  8845. if (TC.getArch() == llvm::Triple::x86_64)
  8846. CmdArgs.push_back("i386pep");
  8847. if (TC.getArch() == llvm::Triple::arm)
  8848. CmdArgs.push_back("thumb2pe");
  8849. if (Args.hasArg(options::OPT_mwindows)) {
  8850. CmdArgs.push_back("--subsystem");
  8851. CmdArgs.push_back("windows");
  8852. } else if (Args.hasArg(options::OPT_mconsole)) {
  8853. CmdArgs.push_back("--subsystem");
  8854. CmdArgs.push_back("console");
  8855. }
  8856. if (Args.hasArg(options::OPT_static))
  8857. CmdArgs.push_back("-Bstatic");
  8858. else {
  8859. if (Args.hasArg(options::OPT_mdll))
  8860. CmdArgs.push_back("--dll");
  8861. else if (Args.hasArg(options::OPT_shared))
  8862. CmdArgs.push_back("--shared");
  8863. CmdArgs.push_back("-Bdynamic");
  8864. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  8865. CmdArgs.push_back("-e");
  8866. if (TC.getArch() == llvm::Triple::x86)
  8867. CmdArgs.push_back("_DllMainCRTStartup@12");
  8868. else
  8869. CmdArgs.push_back("DllMainCRTStartup");
  8870. CmdArgs.push_back("--enable-auto-image-base");
  8871. }
  8872. }
  8873. CmdArgs.push_back("-o");
  8874. CmdArgs.push_back(Output.getFilename());
  8875. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8876. // FIXME: add -N, -n flags
  8877. Args.AddLastArg(CmdArgs, options::OPT_r);
  8878. Args.AddLastArg(CmdArgs, options::OPT_s);
  8879. Args.AddLastArg(CmdArgs, options::OPT_t);
  8880. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  8881. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  8882. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8883. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  8884. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  8885. } else {
  8886. if (Args.hasArg(options::OPT_municode))
  8887. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  8888. else
  8889. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  8890. }
  8891. if (Args.hasArg(options::OPT_pg))
  8892. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  8893. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8894. }
  8895. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8896. TC.AddFilePathLibArgs(Args, CmdArgs);
  8897. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8898. // TODO: Add ASan stuff here
  8899. // TODO: Add profile stuff here
  8900. if (D.CCCIsCXX() &&
  8901. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8902. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8903. !Args.hasArg(options::OPT_static);
  8904. if (OnlyLibstdcxxStatic)
  8905. CmdArgs.push_back("-Bstatic");
  8906. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8907. if (OnlyLibstdcxxStatic)
  8908. CmdArgs.push_back("-Bdynamic");
  8909. }
  8910. if (!Args.hasArg(options::OPT_nostdlib)) {
  8911. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8912. if (Args.hasArg(options::OPT_static))
  8913. CmdArgs.push_back("--start-group");
  8914. if (Args.hasArg(options::OPT_fstack_protector) ||
  8915. Args.hasArg(options::OPT_fstack_protector_strong) ||
  8916. Args.hasArg(options::OPT_fstack_protector_all)) {
  8917. CmdArgs.push_back("-lssp_nonshared");
  8918. CmdArgs.push_back("-lssp");
  8919. }
  8920. if (Args.hasArg(options::OPT_fopenmp))
  8921. CmdArgs.push_back("-lgomp");
  8922. AddLibGCC(Args, CmdArgs);
  8923. if (Args.hasArg(options::OPT_pg))
  8924. CmdArgs.push_back("-lgmon");
  8925. if (Args.hasArg(options::OPT_pthread))
  8926. CmdArgs.push_back("-lpthread");
  8927. // add system libraries
  8928. if (Args.hasArg(options::OPT_mwindows)) {
  8929. CmdArgs.push_back("-lgdi32");
  8930. CmdArgs.push_back("-lcomdlg32");
  8931. }
  8932. CmdArgs.push_back("-ladvapi32");
  8933. CmdArgs.push_back("-lshell32");
  8934. CmdArgs.push_back("-luser32");
  8935. CmdArgs.push_back("-lkernel32");
  8936. if (Args.hasArg(options::OPT_static))
  8937. CmdArgs.push_back("--end-group");
  8938. else if (!LinkerName.equals_lower("lld"))
  8939. AddLibGCC(Args, CmdArgs);
  8940. }
  8941. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8942. // Add crtfastmath.o if available and fast math is enabled.
  8943. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8944. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8945. }
  8946. }
  8947. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  8948. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8949. }
  8950. /// XCore Tools
  8951. // We pass assemble and link construction to the xcc tool.
  8952. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8953. const InputInfo &Output,
  8954. const InputInfoList &Inputs,
  8955. const ArgList &Args,
  8956. const char *LinkingOutput) const {
  8957. claimNoWarnArgs(Args);
  8958. ArgStringList CmdArgs;
  8959. CmdArgs.push_back("-o");
  8960. CmdArgs.push_back(Output.getFilename());
  8961. CmdArgs.push_back("-c");
  8962. if (Args.hasArg(options::OPT_v))
  8963. CmdArgs.push_back("-v");
  8964. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  8965. if (!A->getOption().matches(options::OPT_g0))
  8966. CmdArgs.push_back("-g");
  8967. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  8968. false))
  8969. CmdArgs.push_back("-fverbose-asm");
  8970. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8971. for (const auto &II : Inputs)
  8972. CmdArgs.push_back(II.getFilename());
  8973. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8974. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8975. }
  8976. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8977. const InputInfo &Output,
  8978. const InputInfoList &Inputs,
  8979. const ArgList &Args,
  8980. const char *LinkingOutput) const {
  8981. ArgStringList CmdArgs;
  8982. if (Output.isFilename()) {
  8983. CmdArgs.push_back("-o");
  8984. CmdArgs.push_back(Output.getFilename());
  8985. } else {
  8986. assert(Output.isNothing() && "Invalid output.");
  8987. }
  8988. if (Args.hasArg(options::OPT_v))
  8989. CmdArgs.push_back("-v");
  8990. // Pass -fexceptions through to the linker if it was present.
  8991. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  8992. false))
  8993. CmdArgs.push_back("-fexceptions");
  8994. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8995. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8996. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8997. }
  8998. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8999. const InputInfo &Output,
  9000. const InputInfoList &Inputs,
  9001. const ArgList &Args,
  9002. const char *LinkingOutput) const {
  9003. claimNoWarnArgs(Args);
  9004. const auto &TC =
  9005. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  9006. ArgStringList CmdArgs;
  9007. const char *Exec;
  9008. switch (TC.getArch()) {
  9009. default:
  9010. llvm_unreachable("unsupported architecture");
  9011. case llvm::Triple::arm:
  9012. case llvm::Triple::thumb:
  9013. break;
  9014. case llvm::Triple::x86:
  9015. CmdArgs.push_back("--32");
  9016. break;
  9017. case llvm::Triple::x86_64:
  9018. CmdArgs.push_back("--64");
  9019. break;
  9020. }
  9021. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9022. CmdArgs.push_back("-o");
  9023. CmdArgs.push_back(Output.getFilename());
  9024. for (const auto &Input : Inputs)
  9025. CmdArgs.push_back(Input.getFilename());
  9026. const std::string Assembler = TC.GetProgramPath("as");
  9027. Exec = Args.MakeArgString(Assembler);
  9028. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9029. }
  9030. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9031. const InputInfo &Output,
  9032. const InputInfoList &Inputs,
  9033. const ArgList &Args,
  9034. const char *LinkingOutput) const {
  9035. const auto &TC =
  9036. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  9037. const llvm::Triple &T = TC.getTriple();
  9038. const Driver &D = TC.getDriver();
  9039. SmallString<128> EntryPoint;
  9040. ArgStringList CmdArgs;
  9041. const char *Exec;
  9042. // Silence warning for "clang -g foo.o -o foo"
  9043. Args.ClaimAllArgs(options::OPT_g_Group);
  9044. // and "clang -emit-llvm foo.o -o foo"
  9045. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9046. // and for "clang -w foo.o -o foo"
  9047. Args.ClaimAllArgs(options::OPT_w);
  9048. // Other warning options are already handled somewhere else.
  9049. if (!D.SysRoot.empty())
  9050. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9051. if (Args.hasArg(options::OPT_pie))
  9052. CmdArgs.push_back("-pie");
  9053. if (Args.hasArg(options::OPT_rdynamic))
  9054. CmdArgs.push_back("-export-dynamic");
  9055. if (Args.hasArg(options::OPT_s))
  9056. CmdArgs.push_back("--strip-all");
  9057. CmdArgs.push_back("-m");
  9058. switch (TC.getArch()) {
  9059. default:
  9060. llvm_unreachable("unsupported architecture");
  9061. case llvm::Triple::arm:
  9062. case llvm::Triple::thumb:
  9063. // FIXME: this is incorrect for WinCE
  9064. CmdArgs.push_back("thumb2pe");
  9065. break;
  9066. case llvm::Triple::x86:
  9067. CmdArgs.push_back("i386pe");
  9068. EntryPoint.append("_");
  9069. break;
  9070. case llvm::Triple::x86_64:
  9071. CmdArgs.push_back("i386pep");
  9072. break;
  9073. }
  9074. if (Args.hasArg(options::OPT_shared)) {
  9075. switch (T.getArch()) {
  9076. default:
  9077. llvm_unreachable("unsupported architecture");
  9078. case llvm::Triple::arm:
  9079. case llvm::Triple::thumb:
  9080. case llvm::Triple::x86_64:
  9081. EntryPoint.append("_DllMainCRTStartup");
  9082. break;
  9083. case llvm::Triple::x86:
  9084. EntryPoint.append("_DllMainCRTStartup@12");
  9085. break;
  9086. }
  9087. CmdArgs.push_back("-shared");
  9088. CmdArgs.push_back("-Bdynamic");
  9089. CmdArgs.push_back("--enable-auto-image-base");
  9090. CmdArgs.push_back("--entry");
  9091. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  9092. } else {
  9093. EntryPoint.append("mainCRTStartup");
  9094. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  9095. : "-Bdynamic");
  9096. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9097. CmdArgs.push_back("--entry");
  9098. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  9099. }
  9100. // FIXME: handle subsystem
  9101. }
  9102. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  9103. CmdArgs.push_back("--allow-multiple-definition");
  9104. CmdArgs.push_back("-o");
  9105. CmdArgs.push_back(Output.getFilename());
  9106. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  9107. SmallString<261> ImpLib(Output.getFilename());
  9108. llvm::sys::path::replace_extension(ImpLib, ".lib");
  9109. CmdArgs.push_back("--out-implib");
  9110. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  9111. }
  9112. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9113. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  9114. const char *CRTBegin;
  9115. CRTBegin =
  9116. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  9117. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  9118. }
  9119. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9120. TC.AddFilePathLibArgs(Args, CmdArgs);
  9121. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  9122. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  9123. !Args.hasArg(options::OPT_nodefaultlibs)) {
  9124. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  9125. !Args.hasArg(options::OPT_static);
  9126. if (StaticCXX)
  9127. CmdArgs.push_back("-Bstatic");
  9128. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  9129. if (StaticCXX)
  9130. CmdArgs.push_back("-Bdynamic");
  9131. }
  9132. if (!Args.hasArg(options::OPT_nostdlib)) {
  9133. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  9134. // TODO handle /MT[d] /MD[d]
  9135. CmdArgs.push_back("-lmsvcrt");
  9136. AddRunTimeLibs(TC, D, CmdArgs, Args);
  9137. }
  9138. }
  9139. if (TC.getSanitizerArgs().needsAsanRt()) {
  9140. // TODO handle /MT[d] /MD[d]
  9141. if (Args.hasArg(options::OPT_shared)) {
  9142. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  9143. } else {
  9144. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  9145. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  9146. // Make sure the dynamic runtime thunk is not optimized out at link time
  9147. // to ensure proper SEH handling.
  9148. CmdArgs.push_back(Args.MakeArgString("--undefined"));
  9149. CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
  9150. ? "___asan_seh_interceptor"
  9151. : "__asan_seh_interceptor"));
  9152. }
  9153. }
  9154. Exec = Args.MakeArgString(TC.GetLinkerPath());
  9155. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9156. }
  9157. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  9158. const InputInfo &Output,
  9159. const InputInfoList &Inputs,
  9160. const ArgList &Args,
  9161. const char *LinkingOutput) const {
  9162. ArgStringList CmdArgs;
  9163. assert(Inputs.size() == 1);
  9164. const InputInfo &II = Inputs[0];
  9165. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
  9166. II.getType() == types::TY_PP_CXX);
  9167. if (JA.getKind() == Action::PreprocessJobClass) {
  9168. Args.ClaimAllArgs();
  9169. CmdArgs.push_back("-E");
  9170. } else {
  9171. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  9172. CmdArgs.push_back("-S");
  9173. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  9174. }
  9175. CmdArgs.push_back("-DMYRIAD2");
  9176. // Append all -I, -iquote, -isystem paths, defines/undefines,
  9177. // 'f' flags, optimize flags, and warning options.
  9178. // These are spelled the same way in clang and moviCompile.
  9179. Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
  9180. options::OPT_std_EQ, options::OPT_D, options::OPT_U,
  9181. options::OPT_f_Group, options::OPT_f_clang_Group,
  9182. options::OPT_g_Group, options::OPT_M_Group,
  9183. options::OPT_O_Group, options::OPT_W_Group,
  9184. options::OPT_mcpu_EQ});
  9185. // If we're producing a dependency file, and assembly is the final action,
  9186. // then the name of the target in the dependency file should be the '.o'
  9187. // file, not the '.s' file produced by this step. For example, instead of
  9188. // /tmp/mumble.s: mumble.c .../someheader.h
  9189. // the filename on the lefthand side should be "mumble.o"
  9190. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  9191. C.getActions().size() == 1 &&
  9192. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  9193. Arg *A = Args.getLastArg(options::OPT_o);
  9194. if (A) {
  9195. CmdArgs.push_back("-MT");
  9196. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  9197. }
  9198. }
  9199. CmdArgs.push_back(II.getFilename());
  9200. CmdArgs.push_back("-o");
  9201. CmdArgs.push_back(Output.getFilename());
  9202. std::string Exec =
  9203. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  9204. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9205. CmdArgs, Inputs));
  9206. }
  9207. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9208. const InputInfo &Output,
  9209. const InputInfoList &Inputs,
  9210. const ArgList &Args,
  9211. const char *LinkingOutput) const {
  9212. ArgStringList CmdArgs;
  9213. assert(Inputs.size() == 1);
  9214. const InputInfo &II = Inputs[0];
  9215. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  9216. assert(Output.getType() == types::TY_Object);
  9217. CmdArgs.push_back("-no6thSlotCompression");
  9218. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  9219. if (CPUArg)
  9220. CmdArgs.push_back(
  9221. Args.MakeArgString("-cv:" + StringRef(CPUArg->getValue())));
  9222. CmdArgs.push_back("-noSPrefixing");
  9223. CmdArgs.push_back("-a"); // Mystery option.
  9224. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9225. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  9226. A->claim();
  9227. CmdArgs.push_back(
  9228. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  9229. }
  9230. CmdArgs.push_back("-elf"); // Output format.
  9231. CmdArgs.push_back(II.getFilename());
  9232. CmdArgs.push_back(
  9233. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  9234. std::string Exec =
  9235. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  9236. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9237. CmdArgs, Inputs));
  9238. }
  9239. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9240. const InputInfo &Output,
  9241. const InputInfoList &Inputs,
  9242. const ArgList &Args,
  9243. const char *LinkingOutput) const {
  9244. const auto &TC =
  9245. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  9246. const llvm::Triple &T = TC.getTriple();
  9247. ArgStringList CmdArgs;
  9248. bool UseStartfiles =
  9249. !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
  9250. bool UseDefaultLibs =
  9251. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  9252. if (T.getArch() == llvm::Triple::sparc)
  9253. CmdArgs.push_back("-EB");
  9254. else // SHAVE assumes little-endian, and sparcel is expressly so.
  9255. CmdArgs.push_back("-EL");
  9256. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  9257. // but we never pass through a --sysroot option and various other bits.
  9258. // For example, there are no sanitizers (yet) nor gold linker.
  9259. // Eat some arguments that may be present but have no effect.
  9260. Args.ClaimAllArgs(options::OPT_g_Group);
  9261. Args.ClaimAllArgs(options::OPT_w);
  9262. Args.ClaimAllArgs(options::OPT_static_libgcc);
  9263. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  9264. CmdArgs.push_back("-s");
  9265. CmdArgs.push_back("-o");
  9266. CmdArgs.push_back(Output.getFilename());
  9267. if (UseStartfiles) {
  9268. // If you want startfiles, it means you want the builtin crti and crtbegin,
  9269. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  9270. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
  9271. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  9272. }
  9273. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  9274. options::OPT_e, options::OPT_s, options::OPT_t,
  9275. options::OPT_Z_Flag, options::OPT_r});
  9276. TC.AddFilePathLibArgs(Args, CmdArgs);
  9277. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  9278. if (UseDefaultLibs) {
  9279. if (C.getDriver().CCCIsCXX())
  9280. CmdArgs.push_back("-lstdc++");
  9281. if (T.getOS() == llvm::Triple::RTEMS) {
  9282. CmdArgs.push_back("--start-group");
  9283. CmdArgs.push_back("-lc");
  9284. // You must provide your own "-L" option to enable finding these.
  9285. CmdArgs.push_back("-lrtemscpu");
  9286. CmdArgs.push_back("-lrtemsbsp");
  9287. CmdArgs.push_back("--end-group");
  9288. } else {
  9289. CmdArgs.push_back("-lc");
  9290. }
  9291. CmdArgs.push_back("-lgcc");
  9292. }
  9293. if (UseStartfiles) {
  9294. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  9295. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
  9296. }
  9297. std::string Exec =
  9298. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  9299. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  9300. CmdArgs, Inputs));
  9301. }
  9302. void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
  9303. const InputInfo &Output,
  9304. const InputInfoList &Inputs,
  9305. const ArgList &Args,
  9306. const char *LinkingOutput) const {
  9307. claimNoWarnArgs(Args);
  9308. ArgStringList CmdArgs;
  9309. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9310. CmdArgs.push_back("-o");
  9311. CmdArgs.push_back(Output.getFilename());
  9312. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  9313. const InputInfo &Input = Inputs[0];
  9314. assert(Input.isFilename() && "Invalid input.");
  9315. CmdArgs.push_back(Input.getFilename());
  9316. const char *Exec =
  9317. Args.MakeArgString(getToolChain().GetProgramPath("orbis-as"));
  9318. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9319. }
  9320. static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
  9321. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  9322. if (SanArgs.needsUbsanRt()) {
  9323. CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
  9324. }
  9325. if (SanArgs.needsAsanRt()) {
  9326. CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
  9327. }
  9328. }
  9329. static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
  9330. const JobAction &JA, const InputInfo &Output,
  9331. const InputInfoList &Inputs,
  9332. const ArgList &Args,
  9333. const char *LinkingOutput) {
  9334. const toolchains::FreeBSD &ToolChain =
  9335. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9336. const Driver &D = ToolChain.getDriver();
  9337. ArgStringList CmdArgs;
  9338. // Silence warning for "clang -g foo.o -o foo"
  9339. Args.ClaimAllArgs(options::OPT_g_Group);
  9340. // and "clang -emit-llvm foo.o -o foo"
  9341. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9342. // and for "clang -w foo.o -o foo". Other warning options are already
  9343. // handled somewhere else.
  9344. Args.ClaimAllArgs(options::OPT_w);
  9345. if (!D.SysRoot.empty())
  9346. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9347. if (Args.hasArg(options::OPT_pie))
  9348. CmdArgs.push_back("-pie");
  9349. if (Args.hasArg(options::OPT_rdynamic))
  9350. CmdArgs.push_back("-export-dynamic");
  9351. if (Args.hasArg(options::OPT_shared))
  9352. CmdArgs.push_back("--oformat=so");
  9353. if (Output.isFilename()) {
  9354. CmdArgs.push_back("-o");
  9355. CmdArgs.push_back(Output.getFilename());
  9356. } else {
  9357. assert(Output.isNothing() && "Invalid output.");
  9358. }
  9359. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9360. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9361. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9362. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9363. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9364. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9365. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9366. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9367. CmdArgs.push_back("--no-demangle");
  9368. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9369. if (Args.hasArg(options::OPT_pthread)) {
  9370. CmdArgs.push_back("-lpthread");
  9371. }
  9372. const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
  9373. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9374. }
  9375. static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
  9376. const JobAction &JA, const InputInfo &Output,
  9377. const InputInfoList &Inputs,
  9378. const ArgList &Args,
  9379. const char *LinkingOutput) {
  9380. const toolchains::FreeBSD &ToolChain =
  9381. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9382. const Driver &D = ToolChain.getDriver();
  9383. ArgStringList CmdArgs;
  9384. // Silence warning for "clang -g foo.o -o foo"
  9385. Args.ClaimAllArgs(options::OPT_g_Group);
  9386. // and "clang -emit-llvm foo.o -o foo"
  9387. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9388. // and for "clang -w foo.o -o foo". Other warning options are already
  9389. // handled somewhere else.
  9390. Args.ClaimAllArgs(options::OPT_w);
  9391. if (!D.SysRoot.empty())
  9392. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9393. if (Args.hasArg(options::OPT_pie))
  9394. CmdArgs.push_back("-pie");
  9395. if (Args.hasArg(options::OPT_static)) {
  9396. CmdArgs.push_back("-Bstatic");
  9397. } else {
  9398. if (Args.hasArg(options::OPT_rdynamic))
  9399. CmdArgs.push_back("-export-dynamic");
  9400. CmdArgs.push_back("--eh-frame-hdr");
  9401. if (Args.hasArg(options::OPT_shared)) {
  9402. CmdArgs.push_back("-Bshareable");
  9403. } else {
  9404. CmdArgs.push_back("-dynamic-linker");
  9405. CmdArgs.push_back("/libexec/ld-elf.so.1");
  9406. }
  9407. CmdArgs.push_back("--enable-new-dtags");
  9408. }
  9409. if (Output.isFilename()) {
  9410. CmdArgs.push_back("-o");
  9411. CmdArgs.push_back(Output.getFilename());
  9412. } else {
  9413. assert(Output.isNothing() && "Invalid output.");
  9414. }
  9415. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9416. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9417. const char *crt1 = nullptr;
  9418. if (!Args.hasArg(options::OPT_shared)) {
  9419. if (Args.hasArg(options::OPT_pg))
  9420. crt1 = "gcrt1.o";
  9421. else if (Args.hasArg(options::OPT_pie))
  9422. crt1 = "Scrt1.o";
  9423. else
  9424. crt1 = "crt1.o";
  9425. }
  9426. if (crt1)
  9427. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  9428. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  9429. const char *crtbegin = nullptr;
  9430. if (Args.hasArg(options::OPT_static))
  9431. crtbegin = "crtbeginT.o";
  9432. else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9433. crtbegin = "crtbeginS.o";
  9434. else
  9435. crtbegin = "crtbegin.o";
  9436. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  9437. }
  9438. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9439. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  9440. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9441. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9442. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9443. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9444. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9445. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9446. CmdArgs.push_back("--no-demangle");
  9447. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9448. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9449. // For PS4, we always want to pass libm, libstdc++ and libkernel
  9450. // libraries for both C and C++ compilations.
  9451. CmdArgs.push_back("-lkernel");
  9452. if (D.CCCIsCXX()) {
  9453. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  9454. if (Args.hasArg(options::OPT_pg))
  9455. CmdArgs.push_back("-lm_p");
  9456. else
  9457. CmdArgs.push_back("-lm");
  9458. }
  9459. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  9460. // the default system libraries. Just mimic this for now.
  9461. if (Args.hasArg(options::OPT_pg))
  9462. CmdArgs.push_back("-lgcc_p");
  9463. else
  9464. CmdArgs.push_back("-lcompiler_rt");
  9465. if (Args.hasArg(options::OPT_static)) {
  9466. CmdArgs.push_back("-lstdc++");
  9467. } else if (Args.hasArg(options::OPT_pg)) {
  9468. CmdArgs.push_back("-lgcc_eh_p");
  9469. } else {
  9470. CmdArgs.push_back("--as-needed");
  9471. CmdArgs.push_back("-lstdc++");
  9472. CmdArgs.push_back("--no-as-needed");
  9473. }
  9474. if (Args.hasArg(options::OPT_pthread)) {
  9475. if (Args.hasArg(options::OPT_pg))
  9476. CmdArgs.push_back("-lpthread_p");
  9477. else
  9478. CmdArgs.push_back("-lpthread");
  9479. }
  9480. if (Args.hasArg(options::OPT_pg)) {
  9481. if (Args.hasArg(options::OPT_shared))
  9482. CmdArgs.push_back("-lc");
  9483. else {
  9484. if (Args.hasArg(options::OPT_static)) {
  9485. CmdArgs.push_back("--start-group");
  9486. CmdArgs.push_back("-lc_p");
  9487. CmdArgs.push_back("-lpthread_p");
  9488. CmdArgs.push_back("--end-group");
  9489. } else {
  9490. CmdArgs.push_back("-lc_p");
  9491. }
  9492. }
  9493. CmdArgs.push_back("-lgcc_p");
  9494. } else {
  9495. if (Args.hasArg(options::OPT_static)) {
  9496. CmdArgs.push_back("--start-group");
  9497. CmdArgs.push_back("-lc");
  9498. CmdArgs.push_back("-lpthread");
  9499. CmdArgs.push_back("--end-group");
  9500. } else {
  9501. CmdArgs.push_back("-lc");
  9502. }
  9503. CmdArgs.push_back("-lcompiler_rt");
  9504. }
  9505. if (Args.hasArg(options::OPT_static)) {
  9506. CmdArgs.push_back("-lstdc++");
  9507. } else if (Args.hasArg(options::OPT_pg)) {
  9508. CmdArgs.push_back("-lgcc_eh_p");
  9509. } else {
  9510. CmdArgs.push_back("--as-needed");
  9511. CmdArgs.push_back("-lstdc++");
  9512. CmdArgs.push_back("--no-as-needed");
  9513. }
  9514. }
  9515. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9516. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9517. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  9518. else
  9519. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  9520. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  9521. }
  9522. const char *Exec =
  9523. #ifdef LLVM_ON_WIN32
  9524. Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld.gold"));
  9525. #else
  9526. Args.MakeArgString(ToolChain.GetProgramPath("orbis-ld"));
  9527. #endif
  9528. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9529. }
  9530. void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
  9531. const InputInfo &Output,
  9532. const InputInfoList &Inputs,
  9533. const ArgList &Args,
  9534. const char *LinkingOutput) const {
  9535. const toolchains::FreeBSD &ToolChain =
  9536. static_cast<const toolchains::FreeBSD &>(getToolChain());
  9537. const Driver &D = ToolChain.getDriver();
  9538. bool PS4Linker;
  9539. StringRef LinkerOptName;
  9540. if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  9541. LinkerOptName = A->getValue();
  9542. if (LinkerOptName != "ps4" && LinkerOptName != "gold")
  9543. D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
  9544. }
  9545. if (LinkerOptName == "gold")
  9546. PS4Linker = false;
  9547. else if (LinkerOptName == "ps4")
  9548. PS4Linker = true;
  9549. else
  9550. PS4Linker = !Args.hasArg(options::OPT_shared);
  9551. if (PS4Linker)
  9552. ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9553. else
  9554. ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9555. }
  9556. void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9557. const InputInfo &Output,
  9558. const InputInfoList &Inputs,
  9559. const ArgList &Args,
  9560. const char *LinkingOutput) const {
  9561. const auto &TC =
  9562. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  9563. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  9564. std::vector<std::string> gpu_archs =
  9565. Args.getAllArgValues(options::OPT_march_EQ);
  9566. assert(gpu_archs.size() == 1 && "Exactly one GPU Arch required for ptxas.");
  9567. const std::string& gpu_arch = gpu_archs[0];
  9568. ArgStringList CmdArgs;
  9569. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
  9570. if (Args.hasFlag(options::OPT_cuda_noopt_device_debug,
  9571. options::OPT_no_cuda_noopt_device_debug, false)) {
  9572. // ptxas does not accept -g option if optimization is enabled, so
  9573. // we ignore the compiler's -O* options if we want debug info.
  9574. CmdArgs.push_back("-g");
  9575. CmdArgs.push_back("--dont-merge-basicblocks");
  9576. CmdArgs.push_back("--return-at-end");
  9577. } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  9578. // Map the -O we received to -O{0,1,2,3}.
  9579. //
  9580. // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
  9581. // default, so it may correspond more closely to the spirit of clang -O2.
  9582. // -O3 seems like the least-bad option when -Osomething is specified to
  9583. // clang but it isn't handled below.
  9584. StringRef OOpt = "3";
  9585. if (A->getOption().matches(options::OPT_O4) ||
  9586. A->getOption().matches(options::OPT_Ofast))
  9587. OOpt = "3";
  9588. else if (A->getOption().matches(options::OPT_O0))
  9589. OOpt = "0";
  9590. else if (A->getOption().matches(options::OPT_O)) {
  9591. // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
  9592. OOpt = llvm::StringSwitch<const char *>(A->getValue())
  9593. .Case("1", "1")
  9594. .Case("2", "2")
  9595. .Case("3", "3")
  9596. .Case("s", "2")
  9597. .Case("z", "2")
  9598. .Default("2");
  9599. }
  9600. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
  9601. } else {
  9602. // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
  9603. // to no optimizations, but ptxas's default is -O3.
  9604. CmdArgs.push_back("-O0");
  9605. }
  9606. CmdArgs.push_back("--gpu-name");
  9607. CmdArgs.push_back(Args.MakeArgString(gpu_arch));
  9608. CmdArgs.push_back("--output-file");
  9609. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  9610. for (const auto& II : Inputs)
  9611. CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
  9612. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
  9613. CmdArgs.push_back(Args.MakeArgString(A));
  9614. const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
  9615. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9616. }
  9617. // All inputs to this linker must be from CudaDeviceActions, as we need to look
  9618. // at the Inputs' Actions in order to figure out which GPU architecture they
  9619. // correspond to.
  9620. void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9621. const InputInfo &Output,
  9622. const InputInfoList &Inputs,
  9623. const ArgList &Args,
  9624. const char *LinkingOutput) const {
  9625. const auto &TC =
  9626. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  9627. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  9628. ArgStringList CmdArgs;
  9629. CmdArgs.push_back("--cuda");
  9630. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
  9631. CmdArgs.push_back(Args.MakeArgString("--create"));
  9632. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  9633. for (const auto& II : Inputs) {
  9634. auto* A = cast<const CudaDeviceAction>(II.getAction());
  9635. // We need to pass an Arch of the form "sm_XX" for cubin files and
  9636. // "compute_XX" for ptx.
  9637. const char *Arch = (II.getType() == types::TY_PP_Asm)
  9638. ? A->getComputeArchName()
  9639. : A->getGpuArchName();
  9640. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
  9641. Arch + ",file=" + II.getFilename()));
  9642. }
  9643. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
  9644. CmdArgs.push_back(Args.MakeArgString(A));
  9645. const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
  9646. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9647. }