Tools.cpp 392 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778
  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. bool RenderedImplicitInclude = false;
  347. for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
  348. if (A->getOption().matches(options::OPT_include)) {
  349. bool IsFirstImplicitInclude = !RenderedImplicitInclude;
  350. RenderedImplicitInclude = true;
  351. // Use PCH if the user requested it.
  352. bool UsePCH = D.CCCUsePCH;
  353. bool FoundPTH = false;
  354. bool FoundPCH = false;
  355. SmallString<128> P(A->getValue());
  356. // We want the files to have a name like foo.h.pch. Add a dummy extension
  357. // so that replace_extension does the right thing.
  358. P += ".dummy";
  359. if (UsePCH) {
  360. llvm::sys::path::replace_extension(P, "pch");
  361. if (llvm::sys::fs::exists(P))
  362. FoundPCH = true;
  363. }
  364. if (!FoundPCH) {
  365. llvm::sys::path::replace_extension(P, "pth");
  366. if (llvm::sys::fs::exists(P))
  367. FoundPTH = true;
  368. }
  369. if (!FoundPCH && !FoundPTH) {
  370. llvm::sys::path::replace_extension(P, "gch");
  371. if (llvm::sys::fs::exists(P)) {
  372. FoundPCH = UsePCH;
  373. FoundPTH = !UsePCH;
  374. }
  375. }
  376. if (FoundPCH || FoundPTH) {
  377. if (IsFirstImplicitInclude) {
  378. A->claim();
  379. if (UsePCH)
  380. CmdArgs.push_back("-include-pch");
  381. else
  382. CmdArgs.push_back("-include-pth");
  383. CmdArgs.push_back(Args.MakeArgString(P));
  384. continue;
  385. } else {
  386. // Ignore the PCH if not first on command line and emit warning.
  387. D.Diag(diag::warn_drv_pch_not_first_include) << P
  388. << A->getAsString(Args);
  389. }
  390. }
  391. }
  392. // Not translated, render as usual.
  393. A->claim();
  394. A->render(Args, CmdArgs);
  395. }
  396. Args.AddAllArgs(CmdArgs,
  397. {options::OPT_D, options::OPT_U, options::OPT_I_Group,
  398. options::OPT_F, options::OPT_index_header_map});
  399. // Add -Wp, and -Xpreprocessor if using the preprocessor.
  400. // FIXME: There is a very unfortunate problem here, some troubled
  401. // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
  402. // really support that we would have to parse and then translate
  403. // those options. :(
  404. Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
  405. options::OPT_Xpreprocessor);
  406. // -I- is a deprecated GCC feature, reject it.
  407. if (Arg *A = Args.getLastArg(options::OPT_I_))
  408. D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
  409. // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
  410. // -isysroot to the CC1 invocation.
  411. StringRef sysroot = C.getSysRoot();
  412. if (sysroot != "") {
  413. if (!Args.hasArg(options::OPT_isysroot)) {
  414. CmdArgs.push_back("-isysroot");
  415. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  416. }
  417. }
  418. // Parse additional include paths from environment variables.
  419. // FIXME: We should probably sink the logic for handling these from the
  420. // frontend into the driver. It will allow deleting 4 otherwise unused flags.
  421. // CPATH - included following the user specified includes (but prior to
  422. // builtin and standard includes).
  423. addDirectoryList(Args, CmdArgs, "-I", "CPATH");
  424. // C_INCLUDE_PATH - system includes enabled when compiling C.
  425. addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
  426. // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
  427. addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
  428. // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
  429. addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
  430. // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
  431. addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
  432. // Optional AuxToolChain indicates that we need to include headers
  433. // for more than one target. If that's the case, add include paths
  434. // from AuxToolChain right after include paths of the same kind for
  435. // the current target.
  436. // Add C++ include arguments, if needed.
  437. if (types::isCXX(Inputs[0].getType())) {
  438. getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  439. if (AuxToolChain)
  440. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  441. }
  442. // Add system include arguments.
  443. getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
  444. if (AuxToolChain)
  445. AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
  446. // Add CUDA include arguments, if needed.
  447. if (types::isCuda(Inputs[0].getType()))
  448. getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
  449. }
  450. // FIXME: Move to target hook.
  451. static bool isSignedCharDefault(const llvm::Triple &Triple) {
  452. switch (Triple.getArch()) {
  453. default:
  454. return true;
  455. case llvm::Triple::aarch64:
  456. case llvm::Triple::aarch64_be:
  457. case llvm::Triple::arm:
  458. case llvm::Triple::armeb:
  459. case llvm::Triple::thumb:
  460. case llvm::Triple::thumbeb:
  461. if (Triple.isOSDarwin() || Triple.isOSWindows())
  462. return true;
  463. return false;
  464. case llvm::Triple::ppc:
  465. case llvm::Triple::ppc64:
  466. if (Triple.isOSDarwin())
  467. return true;
  468. return false;
  469. case llvm::Triple::hexagon:
  470. case llvm::Triple::ppc64le:
  471. case llvm::Triple::systemz:
  472. case llvm::Triple::xcore:
  473. return false;
  474. }
  475. }
  476. static bool isNoCommonDefault(const llvm::Triple &Triple) {
  477. switch (Triple.getArch()) {
  478. default:
  479. return false;
  480. case llvm::Triple::xcore:
  481. case llvm::Triple::wasm32:
  482. case llvm::Triple::wasm64:
  483. return true;
  484. }
  485. }
  486. // ARM tools start.
  487. // Get SubArch (vN).
  488. static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
  489. llvm::StringRef Arch = Triple.getArchName();
  490. return llvm::ARM::parseArchVersion(Arch);
  491. }
  492. // True if M-profile.
  493. static bool isARMMProfile(const llvm::Triple &Triple) {
  494. llvm::StringRef Arch = Triple.getArchName();
  495. unsigned Profile = llvm::ARM::parseArchProfile(Arch);
  496. return Profile == llvm::ARM::PK_M;
  497. }
  498. // Get Arch/CPU from args.
  499. static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
  500. llvm::StringRef &CPU, bool FromAs = false) {
  501. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  502. CPU = A->getValue();
  503. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  504. Arch = A->getValue();
  505. if (!FromAs)
  506. return;
  507. for (const Arg *A :
  508. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  509. StringRef Value = A->getValue();
  510. if (Value.startswith("-mcpu="))
  511. CPU = Value.substr(6);
  512. if (Value.startswith("-march="))
  513. Arch = Value.substr(7);
  514. }
  515. }
  516. // Handle -mhwdiv=.
  517. // FIXME: Use ARMTargetParser.
  518. static void getARMHWDivFeatures(const Driver &D, const Arg *A,
  519. const ArgList &Args, StringRef HWDiv,
  520. std::vector<const char *> &Features) {
  521. unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
  522. if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
  523. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  524. }
  525. // Handle -mfpu=.
  526. static void getARMFPUFeatures(const Driver &D, const Arg *A,
  527. const ArgList &Args, StringRef FPU,
  528. std::vector<const char *> &Features) {
  529. unsigned FPUID = llvm::ARM::parseFPU(FPU);
  530. if (!llvm::ARM::getFPUFeatures(FPUID, Features))
  531. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  532. }
  533. // Decode ARM features from string like +[no]featureA+[no]featureB+...
  534. static bool DecodeARMFeatures(const Driver &D, StringRef text,
  535. std::vector<const char *> &Features) {
  536. SmallVector<StringRef, 8> Split;
  537. text.split(Split, StringRef("+"), -1, false);
  538. for (StringRef Feature : Split) {
  539. const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
  540. if (FeatureName)
  541. Features.push_back(FeatureName);
  542. else
  543. return false;
  544. }
  545. return true;
  546. }
  547. // Check if -march is valid by checking if it can be canonicalised and parsed.
  548. // getARMArch is used here instead of just checking the -march value in order
  549. // to handle -march=native correctly.
  550. static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
  551. llvm::StringRef ArchName,
  552. std::vector<const char *> &Features,
  553. const llvm::Triple &Triple) {
  554. std::pair<StringRef, StringRef> Split = ArchName.split("+");
  555. std::string MArch = arm::getARMArch(ArchName, Triple);
  556. if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
  557. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  558. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  559. }
  560. // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
  561. static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
  562. llvm::StringRef CPUName, llvm::StringRef ArchName,
  563. std::vector<const char *> &Features,
  564. const llvm::Triple &Triple) {
  565. std::pair<StringRef, StringRef> Split = CPUName.split("+");
  566. std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
  567. if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
  568. (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
  569. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  570. }
  571. static bool useAAPCSForMachO(const llvm::Triple &T) {
  572. // The backend is hardwired to assume AAPCS for M-class processors, ensure
  573. // the frontend matches that.
  574. return T.getEnvironment() == llvm::Triple::EABI ||
  575. T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
  576. }
  577. // Select the float ABI as determined by -msoft-float, -mhard-float, and
  578. // -mfloat-abi=.
  579. arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
  580. const Driver &D = TC.getDriver();
  581. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
  582. auto SubArch = getARMSubArchVersionNumber(Triple);
  583. arm::FloatABI ABI = FloatABI::Invalid;
  584. if (Arg *A =
  585. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  586. options::OPT_mfloat_abi_EQ)) {
  587. if (A->getOption().matches(options::OPT_msoft_float)) {
  588. ABI = FloatABI::Soft;
  589. } else if (A->getOption().matches(options::OPT_mhard_float)) {
  590. ABI = FloatABI::Hard;
  591. } else {
  592. ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
  593. .Case("soft", FloatABI::Soft)
  594. .Case("softfp", FloatABI::SoftFP)
  595. .Case("hard", FloatABI::Hard)
  596. .Default(FloatABI::Invalid);
  597. if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  598. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  599. ABI = FloatABI::Soft;
  600. }
  601. }
  602. // It is incorrect to select hard float ABI on MachO platforms if the ABI is
  603. // "apcs-gnu".
  604. if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
  605. ABI == FloatABI::Hard) {
  606. D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
  607. << Triple.getArchName();
  608. }
  609. }
  610. // If unspecified, choose the default based on the platform.
  611. if (ABI == FloatABI::Invalid) {
  612. switch (Triple.getOS()) {
  613. case llvm::Triple::Darwin:
  614. case llvm::Triple::MacOSX:
  615. case llvm::Triple::IOS:
  616. case llvm::Triple::TvOS: {
  617. // Darwin defaults to "softfp" for v6 and v7.
  618. ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  619. ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
  620. break;
  621. }
  622. case llvm::Triple::WatchOS:
  623. ABI = FloatABI::Hard;
  624. break;
  625. // FIXME: this is invalid for WindowsCE
  626. case llvm::Triple::Win32:
  627. ABI = FloatABI::Hard;
  628. break;
  629. case llvm::Triple::FreeBSD:
  630. switch (Triple.getEnvironment()) {
  631. case llvm::Triple::GNUEABIHF:
  632. ABI = FloatABI::Hard;
  633. break;
  634. default:
  635. // FreeBSD defaults to soft float
  636. ABI = FloatABI::Soft;
  637. break;
  638. }
  639. break;
  640. default:
  641. switch (Triple.getEnvironment()) {
  642. case llvm::Triple::GNUEABIHF:
  643. case llvm::Triple::EABIHF:
  644. ABI = FloatABI::Hard;
  645. break;
  646. case llvm::Triple::GNUEABI:
  647. case llvm::Triple::EABI:
  648. // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
  649. ABI = FloatABI::SoftFP;
  650. break;
  651. case llvm::Triple::Android:
  652. ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
  653. break;
  654. default:
  655. // Assume "soft", but warn the user we are guessing.
  656. ABI = FloatABI::Soft;
  657. if (Triple.getOS() != llvm::Triple::UnknownOS ||
  658. !Triple.isOSBinFormatMachO())
  659. D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
  660. break;
  661. }
  662. }
  663. }
  664. assert(ABI != FloatABI::Invalid && "must select an ABI");
  665. return ABI;
  666. }
  667. static void getARMTargetFeatures(const ToolChain &TC,
  668. const llvm::Triple &Triple,
  669. const ArgList &Args,
  670. std::vector<const char *> &Features,
  671. bool ForAS) {
  672. const Driver &D = TC.getDriver();
  673. bool KernelOrKext =
  674. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  675. arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
  676. const Arg *WaCPU = nullptr, *WaFPU = nullptr;
  677. const Arg *WaHDiv = nullptr, *WaArch = nullptr;
  678. if (!ForAS) {
  679. // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
  680. // yet (it uses the -mfloat-abi and -msoft-float options), and it is
  681. // stripped out by the ARM target. We should probably pass this a new
  682. // -target-option, which is handled by the -cc1/-cc1as invocation.
  683. //
  684. // FIXME2: For consistency, it would be ideal if we set up the target
  685. // machine state the same when using the frontend or the assembler. We don't
  686. // currently do that for the assembler, we pass the options directly to the
  687. // backend and never even instantiate the frontend TargetInfo. If we did,
  688. // and used its handleTargetFeatures hook, then we could ensure the
  689. // assembler and the frontend behave the same.
  690. // Use software floating point operations?
  691. if (ABI == arm::FloatABI::Soft)
  692. Features.push_back("+soft-float");
  693. // Use software floating point argument passing?
  694. if (ABI != arm::FloatABI::Hard)
  695. Features.push_back("+soft-float-abi");
  696. } else {
  697. // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
  698. // to the assembler correctly.
  699. for (const Arg *A :
  700. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  701. StringRef Value = A->getValue();
  702. if (Value.startswith("-mfpu=")) {
  703. WaFPU = A;
  704. } else if (Value.startswith("-mcpu=")) {
  705. WaCPU = A;
  706. } else if (Value.startswith("-mhwdiv=")) {
  707. WaHDiv = A;
  708. } else if (Value.startswith("-march=")) {
  709. WaArch = A;
  710. }
  711. }
  712. }
  713. // Check -march. ClangAs gives preference to -Wa,-march=.
  714. const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
  715. StringRef ArchName;
  716. if (WaArch) {
  717. if (ArchArg)
  718. D.Diag(clang::diag::warn_drv_unused_argument)
  719. << ArchArg->getAsString(Args);
  720. ArchName = StringRef(WaArch->getValue()).substr(7);
  721. checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
  722. // FIXME: Set Arch.
  723. D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
  724. } else if (ArchArg) {
  725. ArchName = ArchArg->getValue();
  726. checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
  727. }
  728. // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
  729. const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
  730. StringRef CPUName;
  731. if (WaCPU) {
  732. if (CPUArg)
  733. D.Diag(clang::diag::warn_drv_unused_argument)
  734. << CPUArg->getAsString(Args);
  735. CPUName = StringRef(WaCPU->getValue()).substr(6);
  736. checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
  737. } else if (CPUArg) {
  738. CPUName = CPUArg->getValue();
  739. checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
  740. }
  741. // Add CPU features for generic CPUs
  742. if (CPUName == "native") {
  743. llvm::StringMap<bool> HostFeatures;
  744. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  745. for (auto &F : HostFeatures)
  746. Features.push_back(
  747. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  748. }
  749. // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
  750. const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
  751. if (WaFPU) {
  752. if (FPUArg)
  753. D.Diag(clang::diag::warn_drv_unused_argument)
  754. << FPUArg->getAsString(Args);
  755. getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
  756. Features);
  757. } else if (FPUArg) {
  758. getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
  759. }
  760. // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
  761. const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
  762. if (WaHDiv) {
  763. if (HDivArg)
  764. D.Diag(clang::diag::warn_drv_unused_argument)
  765. << HDivArg->getAsString(Args);
  766. getARMHWDivFeatures(D, WaHDiv, Args,
  767. StringRef(WaHDiv->getValue()).substr(8), Features);
  768. } else if (HDivArg)
  769. getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
  770. // Setting -msoft-float effectively disables NEON because of the GCC
  771. // implementation, although the same isn't true of VFP or VFP3.
  772. if (ABI == arm::FloatABI::Soft) {
  773. Features.push_back("-neon");
  774. // Also need to explicitly disable features which imply NEON.
  775. Features.push_back("-crypto");
  776. }
  777. // En/disable crc code generation.
  778. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  779. if (A->getOption().matches(options::OPT_mcrc))
  780. Features.push_back("+crc");
  781. else
  782. Features.push_back("-crc");
  783. }
  784. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
  785. Features.insert(Features.begin(), "+v8.1a");
  786. }
  787. // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
  788. // neither options are specified, see if we are compiling for kernel/kext and
  789. // decide whether to pass "+long-calls" based on the OS and its version.
  790. if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
  791. options::OPT_mno_long_calls)) {
  792. if (A->getOption().matches(options::OPT_mlong_calls))
  793. Features.push_back("+long-calls");
  794. } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  795. !Triple.isWatchOS()) {
  796. Features.push_back("+long-calls");
  797. }
  798. // Kernel code has more strict alignment requirements.
  799. if (KernelOrKext)
  800. Features.push_back("+strict-align");
  801. else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  802. options::OPT_munaligned_access)) {
  803. if (A->getOption().matches(options::OPT_munaligned_access)) {
  804. // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
  805. if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  806. D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
  807. } else
  808. Features.push_back("+strict-align");
  809. } else {
  810. // Assume pre-ARMv6 doesn't support unaligned accesses.
  811. //
  812. // ARMv6 may or may not support unaligned accesses depending on the
  813. // SCTLR.U bit, which is architecture-specific. We assume ARMv6
  814. // Darwin and NetBSD targets support unaligned accesses, and others don't.
  815. //
  816. // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
  817. // which raises an alignment fault on unaligned accesses. Linux
  818. // defaults this bit to 0 and handles it as a system-wide (not
  819. // per-process) setting. It is therefore safe to assume that ARMv7+
  820. // Linux targets support unaligned accesses. The same goes for NaCl.
  821. //
  822. // The above behavior is consistent with GCC.
  823. int VersionNum = getARMSubArchVersionNumber(Triple);
  824. if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  825. if (VersionNum < 6 ||
  826. Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
  827. Features.push_back("+strict-align");
  828. } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
  829. if (VersionNum < 7)
  830. Features.push_back("+strict-align");
  831. } else
  832. Features.push_back("+strict-align");
  833. }
  834. // llvm does not support reserving registers in general. There is support
  835. // for reserving r9 on ARM though (defined as a platform-specific register
  836. // in ARM EABI).
  837. if (Args.hasArg(options::OPT_ffixed_r9))
  838. Features.push_back("+reserve-r9");
  839. // The kext linker doesn't know how to deal with movw/movt.
  840. if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
  841. Features.push_back("+no-movt");
  842. }
  843. void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
  844. ArgStringList &CmdArgs, bool KernelOrKext) const {
  845. // Select the ABI to use.
  846. // FIXME: Support -meabi.
  847. // FIXME: Parts of this are duplicated in the backend, unify this somehow.
  848. const char *ABIName = nullptr;
  849. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  850. ABIName = A->getValue();
  851. } else if (Triple.isOSBinFormatMachO()) {
  852. if (useAAPCSForMachO(Triple)) {
  853. ABIName = "aapcs";
  854. } else if (Triple.isWatchABI()) {
  855. ABIName = "aapcs16";
  856. } else {
  857. ABIName = "apcs-gnu";
  858. }
  859. } else if (Triple.isOSWindows()) {
  860. // FIXME: this is invalid for WindowsCE
  861. ABIName = "aapcs";
  862. } else {
  863. // Select the default based on the platform.
  864. switch (Triple.getEnvironment()) {
  865. case llvm::Triple::Android:
  866. case llvm::Triple::GNUEABI:
  867. case llvm::Triple::GNUEABIHF:
  868. ABIName = "aapcs-linux";
  869. break;
  870. case llvm::Triple::EABIHF:
  871. case llvm::Triple::EABI:
  872. ABIName = "aapcs";
  873. break;
  874. default:
  875. if (Triple.getOS() == llvm::Triple::NetBSD)
  876. ABIName = "apcs-gnu";
  877. else
  878. ABIName = "aapcs";
  879. break;
  880. }
  881. }
  882. CmdArgs.push_back("-target-abi");
  883. CmdArgs.push_back(ABIName);
  884. // Determine floating point ABI from the options & target defaults.
  885. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  886. if (ABI == arm::FloatABI::Soft) {
  887. // Floating point operations and argument passing are soft.
  888. // FIXME: This changes CPP defines, we need -target-soft-float.
  889. CmdArgs.push_back("-msoft-float");
  890. CmdArgs.push_back("-mfloat-abi");
  891. CmdArgs.push_back("soft");
  892. } else if (ABI == arm::FloatABI::SoftFP) {
  893. // Floating point operations are hard, but argument passing is soft.
  894. CmdArgs.push_back("-mfloat-abi");
  895. CmdArgs.push_back("soft");
  896. } else {
  897. // Floating point operations and argument passing are hard.
  898. assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
  899. CmdArgs.push_back("-mfloat-abi");
  900. CmdArgs.push_back("hard");
  901. }
  902. // Forward the -mglobal-merge option for explicit control over the pass.
  903. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  904. options::OPT_mno_global_merge)) {
  905. CmdArgs.push_back("-backend-option");
  906. if (A->getOption().matches(options::OPT_mno_global_merge))
  907. CmdArgs.push_back("-arm-global-merge=false");
  908. else
  909. CmdArgs.push_back("-arm-global-merge=true");
  910. }
  911. if (!Args.hasFlag(options::OPT_mimplicit_float,
  912. options::OPT_mno_implicit_float, true))
  913. CmdArgs.push_back("-no-implicit-float");
  914. }
  915. // ARM tools end.
  916. /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
  917. /// targeting.
  918. static std::string getAArch64TargetCPU(const ArgList &Args) {
  919. Arg *A;
  920. std::string CPU;
  921. // If we have -mtune or -mcpu, use that.
  922. if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
  923. CPU = StringRef(A->getValue()).lower();
  924. } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
  925. StringRef Mcpu = A->getValue();
  926. CPU = Mcpu.split("+").first.lower();
  927. }
  928. // Handle CPU name is 'native'.
  929. if (CPU == "native")
  930. return llvm::sys::getHostCPUName();
  931. else if (CPU.size())
  932. return CPU;
  933. // Make sure we pick "cyclone" if -arch is used.
  934. // FIXME: Should this be picked by checking the target triple instead?
  935. if (Args.getLastArg(options::OPT_arch))
  936. return "cyclone";
  937. return "generic";
  938. }
  939. void Clang::AddAArch64TargetArgs(const ArgList &Args,
  940. ArgStringList &CmdArgs) const {
  941. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  942. llvm::Triple Triple(TripleStr);
  943. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  944. Args.hasArg(options::OPT_mkernel) ||
  945. Args.hasArg(options::OPT_fapple_kext))
  946. CmdArgs.push_back("-disable-red-zone");
  947. if (!Args.hasFlag(options::OPT_mimplicit_float,
  948. options::OPT_mno_implicit_float, true))
  949. CmdArgs.push_back("-no-implicit-float");
  950. const char *ABIName = nullptr;
  951. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  952. ABIName = A->getValue();
  953. else if (Triple.isOSDarwin())
  954. ABIName = "darwinpcs";
  955. else
  956. ABIName = "aapcs";
  957. CmdArgs.push_back("-target-abi");
  958. CmdArgs.push_back(ABIName);
  959. if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
  960. options::OPT_mno_fix_cortex_a53_835769)) {
  961. CmdArgs.push_back("-backend-option");
  962. if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
  963. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  964. else
  965. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
  966. } else if (Triple.isAndroid()) {
  967. // Enabled A53 errata (835769) workaround by default on android
  968. CmdArgs.push_back("-backend-option");
  969. CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
  970. }
  971. // Forward the -mglobal-merge option for explicit control over the pass.
  972. if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
  973. options::OPT_mno_global_merge)) {
  974. CmdArgs.push_back("-backend-option");
  975. if (A->getOption().matches(options::OPT_mno_global_merge))
  976. CmdArgs.push_back("-aarch64-global-merge=false");
  977. else
  978. CmdArgs.push_back("-aarch64-global-merge=true");
  979. }
  980. }
  981. // Get CPU and ABI names. They are not independent
  982. // so we have to calculate them together.
  983. void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
  984. StringRef &CPUName, StringRef &ABIName) {
  985. const char *DefMips32CPU = "mips32r2";
  986. const char *DefMips64CPU = "mips64r2";
  987. // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
  988. // default for mips64(el)?-img-linux-gnu.
  989. if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
  990. Triple.getEnvironment() == llvm::Triple::GNU) {
  991. DefMips32CPU = "mips32r6";
  992. DefMips64CPU = "mips64r6";
  993. }
  994. // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
  995. if (Triple.isAndroid())
  996. DefMips64CPU = "mips64r6";
  997. // MIPS3 is the default for mips64*-unknown-openbsd.
  998. if (Triple.getOS() == llvm::Triple::OpenBSD)
  999. DefMips64CPU = "mips3";
  1000. if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
  1001. CPUName = A->getValue();
  1002. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
  1003. ABIName = A->getValue();
  1004. // Convert a GNU style Mips ABI name to the name
  1005. // accepted by LLVM Mips backend.
  1006. ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
  1007. .Case("32", "o32")
  1008. .Case("64", "n64")
  1009. .Default(ABIName);
  1010. }
  1011. // Setup default CPU and ABI names.
  1012. if (CPUName.empty() && ABIName.empty()) {
  1013. switch (Triple.getArch()) {
  1014. default:
  1015. llvm_unreachable("Unexpected triple arch name");
  1016. case llvm::Triple::mips:
  1017. case llvm::Triple::mipsel:
  1018. CPUName = DefMips32CPU;
  1019. break;
  1020. case llvm::Triple::mips64:
  1021. case llvm::Triple::mips64el:
  1022. CPUName = DefMips64CPU;
  1023. break;
  1024. }
  1025. }
  1026. if (ABIName.empty()) {
  1027. // Deduce ABI name from the target triple.
  1028. if (Triple.getArch() == llvm::Triple::mips ||
  1029. Triple.getArch() == llvm::Triple::mipsel)
  1030. ABIName = "o32";
  1031. else
  1032. ABIName = "n64";
  1033. }
  1034. if (CPUName.empty()) {
  1035. // Deduce CPU name from ABI name.
  1036. CPUName = llvm::StringSwitch<const char *>(ABIName)
  1037. .Cases("o32", "eabi", DefMips32CPU)
  1038. .Cases("n32", "n64", DefMips64CPU)
  1039. .Default("");
  1040. }
  1041. // FIXME: Warn on inconsistent use of -march and -mabi.
  1042. }
  1043. std::string mips::getMipsABILibSuffix(const ArgList &Args,
  1044. const llvm::Triple &Triple) {
  1045. StringRef CPUName, ABIName;
  1046. tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1047. return llvm::StringSwitch<std::string>(ABIName)
  1048. .Case("o32", "")
  1049. .Case("n32", "32")
  1050. .Case("n64", "64");
  1051. }
  1052. // Convert ABI name to the GNU tools acceptable variant.
  1053. static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
  1054. return llvm::StringSwitch<llvm::StringRef>(ABI)
  1055. .Case("o32", "32")
  1056. .Case("n64", "64")
  1057. .Default(ABI);
  1058. }
  1059. // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
  1060. // and -mfloat-abi=.
  1061. static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
  1062. mips::FloatABI ABI = mips::FloatABI::Invalid;
  1063. if (Arg *A =
  1064. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1065. options::OPT_mfloat_abi_EQ)) {
  1066. if (A->getOption().matches(options::OPT_msoft_float))
  1067. ABI = mips::FloatABI::Soft;
  1068. else if (A->getOption().matches(options::OPT_mhard_float))
  1069. ABI = mips::FloatABI::Hard;
  1070. else {
  1071. ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
  1072. .Case("soft", mips::FloatABI::Soft)
  1073. .Case("hard", mips::FloatABI::Hard)
  1074. .Default(mips::FloatABI::Invalid);
  1075. if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1076. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1077. ABI = mips::FloatABI::Hard;
  1078. }
  1079. }
  1080. }
  1081. // If unspecified, choose the default based on the platform.
  1082. if (ABI == mips::FloatABI::Invalid) {
  1083. // Assume "hard", because it's a default value used by gcc.
  1084. // When we start to recognize specific target MIPS processors,
  1085. // we will be able to select the default more correctly.
  1086. ABI = mips::FloatABI::Hard;
  1087. }
  1088. assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
  1089. return ABI;
  1090. }
  1091. static void AddTargetFeature(const ArgList &Args,
  1092. std::vector<const char *> &Features,
  1093. OptSpecifier OnOpt, OptSpecifier OffOpt,
  1094. StringRef FeatureName) {
  1095. if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
  1096. if (A->getOption().matches(OnOpt))
  1097. Features.push_back(Args.MakeArgString("+" + FeatureName));
  1098. else
  1099. Features.push_back(Args.MakeArgString("-" + FeatureName));
  1100. }
  1101. }
  1102. static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1103. const ArgList &Args,
  1104. std::vector<const char *> &Features) {
  1105. StringRef CPUName;
  1106. StringRef ABIName;
  1107. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1108. ABIName = getGnuCompatibleMipsABIName(ABIName);
  1109. AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
  1110. options::OPT_mabicalls, "noabicalls");
  1111. mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
  1112. if (FloatABI == mips::FloatABI::Soft) {
  1113. // FIXME: Note, this is a hack. We need to pass the selected float
  1114. // mode to the MipsTargetInfoBase to define appropriate macros there.
  1115. // Now it is the only method.
  1116. Features.push_back("+soft-float");
  1117. }
  1118. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  1119. StringRef Val = StringRef(A->getValue());
  1120. if (Val == "2008") {
  1121. if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
  1122. Features.push_back("+nan2008");
  1123. else {
  1124. Features.push_back("-nan2008");
  1125. D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
  1126. }
  1127. } else if (Val == "legacy") {
  1128. if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
  1129. Features.push_back("-nan2008");
  1130. else {
  1131. Features.push_back("+nan2008");
  1132. D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
  1133. }
  1134. } else
  1135. D.Diag(diag::err_drv_unsupported_option_argument)
  1136. << A->getOption().getName() << Val;
  1137. }
  1138. AddTargetFeature(Args, Features, options::OPT_msingle_float,
  1139. options::OPT_mdouble_float, "single-float");
  1140. AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
  1141. "mips16");
  1142. AddTargetFeature(Args, Features, options::OPT_mmicromips,
  1143. options::OPT_mno_micromips, "micromips");
  1144. AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
  1145. "dsp");
  1146. AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
  1147. "dspr2");
  1148. AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
  1149. "msa");
  1150. // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
  1151. // pass -mfpxx
  1152. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  1153. options::OPT_mfp64)) {
  1154. if (A->getOption().matches(options::OPT_mfp32))
  1155. Features.push_back(Args.MakeArgString("-fp64"));
  1156. else if (A->getOption().matches(options::OPT_mfpxx)) {
  1157. Features.push_back(Args.MakeArgString("+fpxx"));
  1158. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1159. } else
  1160. Features.push_back(Args.MakeArgString("+fp64"));
  1161. } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
  1162. Features.push_back(Args.MakeArgString("+fpxx"));
  1163. Features.push_back(Args.MakeArgString("+nooddspreg"));
  1164. }
  1165. AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
  1166. options::OPT_modd_spreg, "nooddspreg");
  1167. }
  1168. void Clang::AddMIPSTargetArgs(const ArgList &Args,
  1169. ArgStringList &CmdArgs) const {
  1170. const Driver &D = getToolChain().getDriver();
  1171. StringRef CPUName;
  1172. StringRef ABIName;
  1173. const llvm::Triple &Triple = getToolChain().getTriple();
  1174. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  1175. CmdArgs.push_back("-target-abi");
  1176. CmdArgs.push_back(ABIName.data());
  1177. mips::FloatABI ABI = getMipsFloatABI(D, Args);
  1178. if (ABI == mips::FloatABI::Soft) {
  1179. // Floating point operations and argument passing are soft.
  1180. CmdArgs.push_back("-msoft-float");
  1181. CmdArgs.push_back("-mfloat-abi");
  1182. CmdArgs.push_back("soft");
  1183. } else {
  1184. // Floating point operations and argument passing are hard.
  1185. assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
  1186. CmdArgs.push_back("-mfloat-abi");
  1187. CmdArgs.push_back("hard");
  1188. }
  1189. if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
  1190. if (A->getOption().matches(options::OPT_mxgot)) {
  1191. CmdArgs.push_back("-mllvm");
  1192. CmdArgs.push_back("-mxgot");
  1193. }
  1194. }
  1195. if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
  1196. options::OPT_mno_ldc1_sdc1)) {
  1197. if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
  1198. CmdArgs.push_back("-mllvm");
  1199. CmdArgs.push_back("-mno-ldc1-sdc1");
  1200. }
  1201. }
  1202. if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
  1203. options::OPT_mno_check_zero_division)) {
  1204. if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
  1205. CmdArgs.push_back("-mllvm");
  1206. CmdArgs.push_back("-mno-check-zero-division");
  1207. }
  1208. }
  1209. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  1210. StringRef v = A->getValue();
  1211. CmdArgs.push_back("-mllvm");
  1212. CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
  1213. A->claim();
  1214. }
  1215. }
  1216. /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
  1217. static std::string getPPCTargetCPU(const ArgList &Args) {
  1218. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1219. StringRef CPUName = A->getValue();
  1220. if (CPUName == "native") {
  1221. std::string CPU = llvm::sys::getHostCPUName();
  1222. if (!CPU.empty() && CPU != "generic")
  1223. return CPU;
  1224. else
  1225. return "";
  1226. }
  1227. return llvm::StringSwitch<const char *>(CPUName)
  1228. .Case("common", "generic")
  1229. .Case("440", "440")
  1230. .Case("440fp", "440")
  1231. .Case("450", "450")
  1232. .Case("601", "601")
  1233. .Case("602", "602")
  1234. .Case("603", "603")
  1235. .Case("603e", "603e")
  1236. .Case("603ev", "603ev")
  1237. .Case("604", "604")
  1238. .Case("604e", "604e")
  1239. .Case("620", "620")
  1240. .Case("630", "pwr3")
  1241. .Case("G3", "g3")
  1242. .Case("7400", "7400")
  1243. .Case("G4", "g4")
  1244. .Case("7450", "7450")
  1245. .Case("G4+", "g4+")
  1246. .Case("750", "750")
  1247. .Case("970", "970")
  1248. .Case("G5", "g5")
  1249. .Case("a2", "a2")
  1250. .Case("a2q", "a2q")
  1251. .Case("e500mc", "e500mc")
  1252. .Case("e5500", "e5500")
  1253. .Case("power3", "pwr3")
  1254. .Case("power4", "pwr4")
  1255. .Case("power5", "pwr5")
  1256. .Case("power5x", "pwr5x")
  1257. .Case("power6", "pwr6")
  1258. .Case("power6x", "pwr6x")
  1259. .Case("power7", "pwr7")
  1260. .Case("power8", "pwr8")
  1261. .Case("pwr3", "pwr3")
  1262. .Case("pwr4", "pwr4")
  1263. .Case("pwr5", "pwr5")
  1264. .Case("pwr5x", "pwr5x")
  1265. .Case("pwr6", "pwr6")
  1266. .Case("pwr6x", "pwr6x")
  1267. .Case("pwr7", "pwr7")
  1268. .Case("pwr8", "pwr8")
  1269. .Case("powerpc", "ppc")
  1270. .Case("powerpc64", "ppc64")
  1271. .Case("powerpc64le", "ppc64le")
  1272. .Default("");
  1273. }
  1274. return "";
  1275. }
  1276. static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1277. const ArgList &Args,
  1278. std::vector<const char *> &Features) {
  1279. handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
  1280. ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
  1281. if (FloatABI == ppc::FloatABI::Soft &&
  1282. !(Triple.getArch() == llvm::Triple::ppc64 ||
  1283. Triple.getArch() == llvm::Triple::ppc64le))
  1284. Features.push_back("+soft-float");
  1285. else if (FloatABI == ppc::FloatABI::Soft &&
  1286. (Triple.getArch() == llvm::Triple::ppc64 ||
  1287. Triple.getArch() == llvm::Triple::ppc64le))
  1288. D.Diag(diag::err_drv_invalid_mfloat_abi)
  1289. << "soft float is not supported for ppc64";
  1290. // Altivec is a bit weird, allow overriding of the Altivec feature here.
  1291. AddTargetFeature(Args, Features, options::OPT_faltivec,
  1292. options::OPT_fno_altivec, "altivec");
  1293. }
  1294. ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
  1295. ppc::FloatABI ABI = ppc::FloatABI::Invalid;
  1296. if (Arg *A =
  1297. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
  1298. options::OPT_mfloat_abi_EQ)) {
  1299. if (A->getOption().matches(options::OPT_msoft_float))
  1300. ABI = ppc::FloatABI::Soft;
  1301. else if (A->getOption().matches(options::OPT_mhard_float))
  1302. ABI = ppc::FloatABI::Hard;
  1303. else {
  1304. ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
  1305. .Case("soft", ppc::FloatABI::Soft)
  1306. .Case("hard", ppc::FloatABI::Hard)
  1307. .Default(ppc::FloatABI::Invalid);
  1308. if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
  1309. D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
  1310. ABI = ppc::FloatABI::Hard;
  1311. }
  1312. }
  1313. }
  1314. // If unspecified, choose the default based on the platform.
  1315. if (ABI == ppc::FloatABI::Invalid) {
  1316. ABI = ppc::FloatABI::Hard;
  1317. }
  1318. return ABI;
  1319. }
  1320. void Clang::AddPPCTargetArgs(const ArgList &Args,
  1321. ArgStringList &CmdArgs) const {
  1322. // Select the ABI to use.
  1323. const char *ABIName = nullptr;
  1324. if (getToolChain().getTriple().isOSLinux())
  1325. switch (getToolChain().getArch()) {
  1326. case llvm::Triple::ppc64: {
  1327. // When targeting a processor that supports QPX, or if QPX is
  1328. // specifically enabled, default to using the ABI that supports QPX (so
  1329. // long as it is not specifically disabled).
  1330. bool HasQPX = false;
  1331. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1332. HasQPX = A->getValue() == StringRef("a2q");
  1333. HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
  1334. if (HasQPX) {
  1335. ABIName = "elfv1-qpx";
  1336. break;
  1337. }
  1338. ABIName = "elfv1";
  1339. break;
  1340. }
  1341. case llvm::Triple::ppc64le:
  1342. ABIName = "elfv2";
  1343. break;
  1344. default:
  1345. break;
  1346. }
  1347. if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
  1348. // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
  1349. // the option if given as we don't have backend support for any targets
  1350. // that don't use the altivec abi.
  1351. if (StringRef(A->getValue()) != "altivec")
  1352. ABIName = A->getValue();
  1353. ppc::FloatABI FloatABI =
  1354. ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
  1355. if (FloatABI == ppc::FloatABI::Soft) {
  1356. // Floating point operations and argument passing are soft.
  1357. CmdArgs.push_back("-msoft-float");
  1358. CmdArgs.push_back("-mfloat-abi");
  1359. CmdArgs.push_back("soft");
  1360. } else {
  1361. // Floating point operations and argument passing are hard.
  1362. assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
  1363. CmdArgs.push_back("-mfloat-abi");
  1364. CmdArgs.push_back("hard");
  1365. }
  1366. if (ABIName) {
  1367. CmdArgs.push_back("-target-abi");
  1368. CmdArgs.push_back(ABIName);
  1369. }
  1370. }
  1371. bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  1372. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  1373. return A && (A->getValue() == StringRef(Value));
  1374. }
  1375. /// Get the (LLVM) name of the R600 gpu we are targeting.
  1376. static std::string getR600TargetGPU(const ArgList &Args) {
  1377. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1378. const char *GPUName = A->getValue();
  1379. return llvm::StringSwitch<const char *>(GPUName)
  1380. .Cases("rv630", "rv635", "r600")
  1381. .Cases("rv610", "rv620", "rs780", "rs880")
  1382. .Case("rv740", "rv770")
  1383. .Case("palm", "cedar")
  1384. .Cases("sumo", "sumo2", "sumo")
  1385. .Case("hemlock", "cypress")
  1386. .Case("aruba", "cayman")
  1387. .Default(GPUName);
  1388. }
  1389. return "";
  1390. }
  1391. void Clang::AddSparcTargetArgs(const ArgList &Args,
  1392. ArgStringList &CmdArgs) const {
  1393. const Driver &D = getToolChain().getDriver();
  1394. std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
  1395. bool SoftFloatABI = false;
  1396. if (Arg *A =
  1397. Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
  1398. if (A->getOption().matches(options::OPT_msoft_float))
  1399. SoftFloatABI = true;
  1400. }
  1401. // Only the hard-float ABI on Sparc is standardized, and it is the
  1402. // default. GCC also supports a nonstandard soft-float ABI mode, and
  1403. // perhaps LLVM should implement that, too. However, since llvm
  1404. // currently does not support Sparc soft-float, at all, display an
  1405. // error if it's requested.
  1406. if (SoftFloatABI) {
  1407. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
  1408. << Triple;
  1409. }
  1410. }
  1411. static const char *getSystemZTargetCPU(const ArgList &Args) {
  1412. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1413. return A->getValue();
  1414. return "z10";
  1415. }
  1416. static void getSystemZTargetFeatures(const ArgList &Args,
  1417. std::vector<const char *> &Features) {
  1418. // -m(no-)htm overrides use of the transactional-execution facility.
  1419. if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
  1420. if (A->getOption().matches(options::OPT_mhtm))
  1421. Features.push_back("+transactional-execution");
  1422. else
  1423. Features.push_back("-transactional-execution");
  1424. }
  1425. // -m(no-)vx overrides use of the vector facility.
  1426. if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
  1427. if (A->getOption().matches(options::OPT_mvx))
  1428. Features.push_back("+vector");
  1429. else
  1430. Features.push_back("-vector");
  1431. }
  1432. }
  1433. static const char *getX86TargetCPU(const ArgList &Args,
  1434. const llvm::Triple &Triple) {
  1435. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1436. if (StringRef(A->getValue()) != "native") {
  1437. if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
  1438. return "core-avx2";
  1439. return A->getValue();
  1440. }
  1441. // FIXME: Reject attempts to use -march=native unless the target matches
  1442. // the host.
  1443. //
  1444. // FIXME: We should also incorporate the detected target features for use
  1445. // with -native.
  1446. std::string CPU = llvm::sys::getHostCPUName();
  1447. if (!CPU.empty() && CPU != "generic")
  1448. return Args.MakeArgString(CPU);
  1449. }
  1450. if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1451. // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
  1452. StringRef Arch = A->getValue();
  1453. const char *CPU;
  1454. if (Triple.getArch() == llvm::Triple::x86) {
  1455. CPU = llvm::StringSwitch<const char *>(Arch)
  1456. .Case("IA32", "i386")
  1457. .Case("SSE", "pentium3")
  1458. .Case("SSE2", "pentium4")
  1459. .Case("AVX", "sandybridge")
  1460. .Case("AVX2", "haswell")
  1461. .Default(nullptr);
  1462. } else {
  1463. CPU = llvm::StringSwitch<const char *>(Arch)
  1464. .Case("AVX", "sandybridge")
  1465. .Case("AVX2", "haswell")
  1466. .Default(nullptr);
  1467. }
  1468. if (CPU)
  1469. return CPU;
  1470. }
  1471. // Select the default CPU if none was given (or detection failed).
  1472. if (Triple.getArch() != llvm::Triple::x86_64 &&
  1473. Triple.getArch() != llvm::Triple::x86)
  1474. return nullptr; // This routine is only handling x86 targets.
  1475. bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
  1476. // FIXME: Need target hooks.
  1477. if (Triple.isOSDarwin()) {
  1478. if (Triple.getArchName() == "x86_64h")
  1479. return "core-avx2";
  1480. return Is64Bit ? "core2" : "yonah";
  1481. }
  1482. // Set up default CPU name for PS4 compilers.
  1483. if (Triple.isPS4CPU())
  1484. return "btver2";
  1485. // On Android use targets compatible with gcc
  1486. if (Triple.isAndroid())
  1487. return Is64Bit ? "x86-64" : "i686";
  1488. // Everything else goes to x86-64 in 64-bit mode.
  1489. if (Is64Bit)
  1490. return "x86-64";
  1491. switch (Triple.getOS()) {
  1492. case llvm::Triple::FreeBSD:
  1493. case llvm::Triple::NetBSD:
  1494. case llvm::Triple::OpenBSD:
  1495. return "i486";
  1496. case llvm::Triple::Haiku:
  1497. return "i586";
  1498. case llvm::Triple::Bitrig:
  1499. return "i686";
  1500. default:
  1501. // Fallback to p4.
  1502. return "pentium4";
  1503. }
  1504. }
  1505. /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
  1506. static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
  1507. // If we have -mcpu=, use that.
  1508. if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
  1509. StringRef CPU = A->getValue();
  1510. #ifdef __wasm__
  1511. // Handle "native" by examining the host. "native" isn't meaningful when
  1512. // cross compiling, so only support this when the host is also WebAssembly.
  1513. if (CPU == "native")
  1514. return llvm::sys::getHostCPUName();
  1515. #endif
  1516. return CPU;
  1517. }
  1518. return "generic";
  1519. }
  1520. static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
  1521. bool FromAs = false) {
  1522. switch (T.getArch()) {
  1523. default:
  1524. return "";
  1525. case llvm::Triple::aarch64:
  1526. case llvm::Triple::aarch64_be:
  1527. return getAArch64TargetCPU(Args);
  1528. case llvm::Triple::arm:
  1529. case llvm::Triple::armeb:
  1530. case llvm::Triple::thumb:
  1531. case llvm::Triple::thumbeb: {
  1532. StringRef MArch, MCPU;
  1533. getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
  1534. return arm::getARMTargetCPU(MCPU, MArch, T);
  1535. }
  1536. case llvm::Triple::mips:
  1537. case llvm::Triple::mipsel:
  1538. case llvm::Triple::mips64:
  1539. case llvm::Triple::mips64el: {
  1540. StringRef CPUName;
  1541. StringRef ABIName;
  1542. mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
  1543. return CPUName;
  1544. }
  1545. case llvm::Triple::nvptx:
  1546. case llvm::Triple::nvptx64:
  1547. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
  1548. return A->getValue();
  1549. return "";
  1550. case llvm::Triple::ppc:
  1551. case llvm::Triple::ppc64:
  1552. case llvm::Triple::ppc64le: {
  1553. std::string TargetCPUName = getPPCTargetCPU(Args);
  1554. // LLVM may default to generating code for the native CPU,
  1555. // but, like gcc, we default to a more generic option for
  1556. // each architecture. (except on Darwin)
  1557. if (TargetCPUName.empty() && !T.isOSDarwin()) {
  1558. if (T.getArch() == llvm::Triple::ppc64)
  1559. TargetCPUName = "ppc64";
  1560. else if (T.getArch() == llvm::Triple::ppc64le)
  1561. TargetCPUName = "ppc64le";
  1562. else
  1563. TargetCPUName = "ppc";
  1564. }
  1565. return TargetCPUName;
  1566. }
  1567. case llvm::Triple::sparc:
  1568. case llvm::Triple::sparcel:
  1569. case llvm::Triple::sparcv9:
  1570. if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
  1571. return A->getValue();
  1572. return "";
  1573. case llvm::Triple::x86:
  1574. case llvm::Triple::x86_64:
  1575. return getX86TargetCPU(Args, T);
  1576. case llvm::Triple::hexagon:
  1577. return "hexagon" +
  1578. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  1579. case llvm::Triple::systemz:
  1580. return getSystemZTargetCPU(Args);
  1581. case llvm::Triple::r600:
  1582. case llvm::Triple::amdgcn:
  1583. return getR600TargetGPU(Args);
  1584. case llvm::Triple::wasm32:
  1585. case llvm::Triple::wasm64:
  1586. return getWebAssemblyTargetCPU(Args);
  1587. }
  1588. }
  1589. static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
  1590. ArgStringList &CmdArgs, bool IsThinLTO) {
  1591. // Tell the linker to load the plugin. This has to come before AddLinkerInputs
  1592. // as gold requires -plugin to come before any -plugin-opt that -Wl might
  1593. // forward.
  1594. CmdArgs.push_back("-plugin");
  1595. std::string Plugin =
  1596. ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
  1597. CmdArgs.push_back(Args.MakeArgString(Plugin));
  1598. // Try to pass driver level flags relevant to LTO code generation down to
  1599. // the plugin.
  1600. // Handle flags for selecting CPU variants.
  1601. std::string CPU = getCPUName(Args, ToolChain.getTriple());
  1602. if (!CPU.empty())
  1603. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
  1604. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  1605. StringRef OOpt;
  1606. if (A->getOption().matches(options::OPT_O4) ||
  1607. A->getOption().matches(options::OPT_Ofast))
  1608. OOpt = "3";
  1609. else if (A->getOption().matches(options::OPT_O))
  1610. OOpt = A->getValue();
  1611. else if (A->getOption().matches(options::OPT_O0))
  1612. OOpt = "0";
  1613. if (!OOpt.empty())
  1614. CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
  1615. }
  1616. if (IsThinLTO)
  1617. CmdArgs.push_back("-plugin-opt=thinlto");
  1618. // If an explicit debugger tuning argument appeared, pass it along.
  1619. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  1620. options::OPT_ggdbN_Group)) {
  1621. if (A->getOption().matches(options::OPT_glldb))
  1622. CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
  1623. else if (A->getOption().matches(options::OPT_gsce))
  1624. CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
  1625. else
  1626. CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
  1627. }
  1628. }
  1629. /// This is a helper function for validating the optional refinement step
  1630. /// parameter in reciprocal argument strings. Return false if there is an error
  1631. /// parsing the refinement step. Otherwise, return true and set the Position
  1632. /// of the refinement step in the input string.
  1633. static bool getRefinementStep(StringRef In, const Driver &D,
  1634. const Arg &A, size_t &Position) {
  1635. const char RefinementStepToken = ':';
  1636. Position = In.find(RefinementStepToken);
  1637. if (Position != StringRef::npos) {
  1638. StringRef Option = A.getOption().getName();
  1639. StringRef RefStep = In.substr(Position + 1);
  1640. // Allow exactly one numeric character for the additional refinement
  1641. // step parameter. This is reasonable for all currently-supported
  1642. // operations and architectures because we would expect that a larger value
  1643. // of refinement steps would cause the estimate "optimization" to
  1644. // under-perform the native operation. Also, if the estimate does not
  1645. // converge quickly, it probably will not ever converge, so further
  1646. // refinement steps will not produce a better answer.
  1647. if (RefStep.size() != 1) {
  1648. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1649. return false;
  1650. }
  1651. char RefStepChar = RefStep[0];
  1652. if (RefStepChar < '0' || RefStepChar > '9') {
  1653. D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
  1654. return false;
  1655. }
  1656. }
  1657. return true;
  1658. }
  1659. /// The -mrecip flag requires processing of many optional parameters.
  1660. static void ParseMRecip(const Driver &D, const ArgList &Args,
  1661. ArgStringList &OutStrings) {
  1662. StringRef DisabledPrefixIn = "!";
  1663. StringRef DisabledPrefixOut = "!";
  1664. StringRef EnabledPrefixOut = "";
  1665. StringRef Out = "-mrecip=";
  1666. Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
  1667. if (!A)
  1668. return;
  1669. unsigned NumOptions = A->getNumValues();
  1670. if (NumOptions == 0) {
  1671. // No option is the same as "all".
  1672. OutStrings.push_back(Args.MakeArgString(Out + "all"));
  1673. return;
  1674. }
  1675. // Pass through "all", "none", or "default" with an optional refinement step.
  1676. if (NumOptions == 1) {
  1677. StringRef Val = A->getValue(0);
  1678. size_t RefStepLoc;
  1679. if (!getRefinementStep(Val, D, *A, RefStepLoc))
  1680. return;
  1681. StringRef ValBase = Val.slice(0, RefStepLoc);
  1682. if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
  1683. OutStrings.push_back(Args.MakeArgString(Out + Val));
  1684. return;
  1685. }
  1686. }
  1687. // Each reciprocal type may be enabled or disabled individually.
  1688. // Check each input value for validity, concatenate them all back together,
  1689. // and pass through.
  1690. llvm::StringMap<bool> OptionStrings;
  1691. OptionStrings.insert(std::make_pair("divd", false));
  1692. OptionStrings.insert(std::make_pair("divf", false));
  1693. OptionStrings.insert(std::make_pair("vec-divd", false));
  1694. OptionStrings.insert(std::make_pair("vec-divf", false));
  1695. OptionStrings.insert(std::make_pair("sqrtd", false));
  1696. OptionStrings.insert(std::make_pair("sqrtf", false));
  1697. OptionStrings.insert(std::make_pair("vec-sqrtd", false));
  1698. OptionStrings.insert(std::make_pair("vec-sqrtf", false));
  1699. for (unsigned i = 0; i != NumOptions; ++i) {
  1700. StringRef Val = A->getValue(i);
  1701. bool IsDisabled = Val.startswith(DisabledPrefixIn);
  1702. // Ignore the disablement token for string matching.
  1703. if (IsDisabled)
  1704. Val = Val.substr(1);
  1705. size_t RefStep;
  1706. if (!getRefinementStep(Val, D, *A, RefStep))
  1707. return;
  1708. StringRef ValBase = Val.slice(0, RefStep);
  1709. llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
  1710. if (OptionIter == OptionStrings.end()) {
  1711. // Try again specifying float suffix.
  1712. OptionIter = OptionStrings.find(ValBase.str() + 'f');
  1713. if (OptionIter == OptionStrings.end()) {
  1714. // The input name did not match any known option string.
  1715. D.Diag(diag::err_drv_unknown_argument) << Val;
  1716. return;
  1717. }
  1718. // The option was specified without a float or double suffix.
  1719. // Make sure that the double entry was not already specified.
  1720. // The float entry will be checked below.
  1721. if (OptionStrings[ValBase.str() + 'd']) {
  1722. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1723. return;
  1724. }
  1725. }
  1726. if (OptionIter->second == true) {
  1727. // Duplicate option specified.
  1728. D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
  1729. return;
  1730. }
  1731. // Mark the matched option as found. Do not allow duplicate specifiers.
  1732. OptionIter->second = true;
  1733. // If the precision was not specified, also mark the double entry as found.
  1734. if (ValBase.back() != 'f' && ValBase.back() != 'd')
  1735. OptionStrings[ValBase.str() + 'd'] = true;
  1736. // Build the output string.
  1737. StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
  1738. Out = Args.MakeArgString(Out + Prefix + Val);
  1739. if (i != NumOptions - 1)
  1740. Out = Args.MakeArgString(Out + ",");
  1741. }
  1742. OutStrings.push_back(Args.MakeArgString(Out));
  1743. }
  1744. static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
  1745. const ArgList &Args,
  1746. std::vector<const char *> &Features) {
  1747. // If -march=native, autodetect the feature list.
  1748. if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
  1749. if (StringRef(A->getValue()) == "native") {
  1750. llvm::StringMap<bool> HostFeatures;
  1751. if (llvm::sys::getHostCPUFeatures(HostFeatures))
  1752. for (auto &F : HostFeatures)
  1753. Features.push_back(
  1754. Args.MakeArgString((F.second ? "+" : "-") + F.first()));
  1755. }
  1756. }
  1757. if (Triple.getArchName() == "x86_64h") {
  1758. // x86_64h implies quite a few of the more modern subtarget features
  1759. // for Haswell class CPUs, but not all of them. Opt-out of a few.
  1760. Features.push_back("-rdrnd");
  1761. Features.push_back("-aes");
  1762. Features.push_back("-pclmul");
  1763. Features.push_back("-rtm");
  1764. Features.push_back("-hle");
  1765. Features.push_back("-fsgsbase");
  1766. }
  1767. const llvm::Triple::ArchType ArchType = Triple.getArch();
  1768. // Add features to be compatible with gcc for Android.
  1769. if (Triple.isAndroid()) {
  1770. if (ArchType == llvm::Triple::x86_64) {
  1771. Features.push_back("+sse4.2");
  1772. Features.push_back("+popcnt");
  1773. } else
  1774. Features.push_back("+ssse3");
  1775. }
  1776. // Set features according to the -arch flag on MSVC.
  1777. if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
  1778. StringRef Arch = A->getValue();
  1779. bool ArchUsed = false;
  1780. // First, look for flags that are shared in x86 and x86-64.
  1781. if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
  1782. if (Arch == "AVX" || Arch == "AVX2") {
  1783. ArchUsed = true;
  1784. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1785. }
  1786. }
  1787. // Then, look for x86-specific flags.
  1788. if (ArchType == llvm::Triple::x86) {
  1789. if (Arch == "IA32") {
  1790. ArchUsed = true;
  1791. } else if (Arch == "SSE" || Arch == "SSE2") {
  1792. ArchUsed = true;
  1793. Features.push_back(Args.MakeArgString("+" + Arch.lower()));
  1794. }
  1795. }
  1796. if (!ArchUsed)
  1797. D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
  1798. }
  1799. // Now add any that the user explicitly requested on the command line,
  1800. // which may override the defaults.
  1801. handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
  1802. }
  1803. void Clang::AddX86TargetArgs(const ArgList &Args,
  1804. ArgStringList &CmdArgs) const {
  1805. if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
  1806. Args.hasArg(options::OPT_mkernel) ||
  1807. Args.hasArg(options::OPT_fapple_kext))
  1808. CmdArgs.push_back("-disable-red-zone");
  1809. // Default to avoid implicit floating-point for kernel/kext code, but allow
  1810. // that to be overridden with -mno-soft-float.
  1811. bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
  1812. Args.hasArg(options::OPT_fapple_kext));
  1813. if (Arg *A = Args.getLastArg(
  1814. options::OPT_msoft_float, options::OPT_mno_soft_float,
  1815. options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
  1816. const Option &O = A->getOption();
  1817. NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
  1818. O.matches(options::OPT_msoft_float));
  1819. }
  1820. if (NoImplicitFloat)
  1821. CmdArgs.push_back("-no-implicit-float");
  1822. if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
  1823. StringRef Value = A->getValue();
  1824. if (Value == "intel" || Value == "att") {
  1825. CmdArgs.push_back("-mllvm");
  1826. CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
  1827. } else {
  1828. getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
  1829. << A->getOption().getName() << Value;
  1830. }
  1831. }
  1832. }
  1833. void Clang::AddHexagonTargetArgs(const ArgList &Args,
  1834. ArgStringList &CmdArgs) const {
  1835. CmdArgs.push_back("-mqdsp6-compat");
  1836. CmdArgs.push_back("-Wreturn-type");
  1837. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  1838. std::string N = llvm::utostr(G.getValue());
  1839. std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
  1840. CmdArgs.push_back("-mllvm");
  1841. CmdArgs.push_back(Args.MakeArgString(Opt));
  1842. }
  1843. if (!Args.hasArg(options::OPT_fno_short_enums))
  1844. CmdArgs.push_back("-fshort-enums");
  1845. if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
  1846. CmdArgs.push_back("-mllvm");
  1847. CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
  1848. }
  1849. CmdArgs.push_back("-mllvm");
  1850. CmdArgs.push_back("-machine-sink-split=0");
  1851. }
  1852. void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
  1853. ArgStringList &CmdArgs) const {
  1854. // Default to "hidden" visibility.
  1855. if (!Args.hasArg(options::OPT_fvisibility_EQ,
  1856. options::OPT_fvisibility_ms_compat)) {
  1857. CmdArgs.push_back("-fvisibility");
  1858. CmdArgs.push_back("hidden");
  1859. }
  1860. }
  1861. // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
  1862. static bool DecodeAArch64Features(const Driver &D, StringRef text,
  1863. std::vector<const char *> &Features) {
  1864. SmallVector<StringRef, 8> Split;
  1865. text.split(Split, StringRef("+"), -1, false);
  1866. for (StringRef Feature : Split) {
  1867. const char *result = llvm::StringSwitch<const char *>(Feature)
  1868. .Case("fp", "+fp-armv8")
  1869. .Case("simd", "+neon")
  1870. .Case("crc", "+crc")
  1871. .Case("crypto", "+crypto")
  1872. .Case("fp16", "+fullfp16")
  1873. .Case("profile", "+spe")
  1874. .Case("nofp", "-fp-armv8")
  1875. .Case("nosimd", "-neon")
  1876. .Case("nocrc", "-crc")
  1877. .Case("nocrypto", "-crypto")
  1878. .Case("nofp16", "-fullfp16")
  1879. .Case("noprofile", "-spe")
  1880. .Default(nullptr);
  1881. if (result)
  1882. Features.push_back(result);
  1883. else if (Feature == "neon" || Feature == "noneon")
  1884. D.Diag(diag::err_drv_no_neon_modifier);
  1885. else
  1886. return false;
  1887. }
  1888. return true;
  1889. }
  1890. // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
  1891. // decode CPU and feature.
  1892. static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
  1893. std::vector<const char *> &Features) {
  1894. std::pair<StringRef, StringRef> Split = Mcpu.split("+");
  1895. CPU = Split.first;
  1896. if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
  1897. CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1") {
  1898. Features.push_back("+neon");
  1899. Features.push_back("+crc");
  1900. Features.push_back("+crypto");
  1901. } else if (CPU == "generic") {
  1902. Features.push_back("+neon");
  1903. } else {
  1904. return false;
  1905. }
  1906. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  1907. return false;
  1908. return true;
  1909. }
  1910. static bool
  1911. getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
  1912. const ArgList &Args,
  1913. std::vector<const char *> &Features) {
  1914. std::string MarchLowerCase = March.lower();
  1915. std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
  1916. if (Split.first == "armv8-a" || Split.first == "armv8a") {
  1917. // ok, no additional features.
  1918. } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
  1919. Features.push_back("+v8.1a");
  1920. } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
  1921. Features.push_back("+v8.2a");
  1922. } else {
  1923. return false;
  1924. }
  1925. if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
  1926. return false;
  1927. return true;
  1928. }
  1929. static bool
  1930. getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  1931. const ArgList &Args,
  1932. std::vector<const char *> &Features) {
  1933. StringRef CPU;
  1934. std::string McpuLowerCase = Mcpu.lower();
  1935. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
  1936. return false;
  1937. return true;
  1938. }
  1939. static bool
  1940. getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
  1941. const ArgList &Args,
  1942. std::vector<const char *> &Features) {
  1943. std::string MtuneLowerCase = Mtune.lower();
  1944. // Handle CPU name is 'native'.
  1945. if (MtuneLowerCase == "native")
  1946. MtuneLowerCase = llvm::sys::getHostCPUName();
  1947. if (MtuneLowerCase == "cyclone") {
  1948. Features.push_back("+zcm");
  1949. Features.push_back("+zcz");
  1950. }
  1951. return true;
  1952. }
  1953. static bool
  1954. getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
  1955. const ArgList &Args,
  1956. std::vector<const char *> &Features) {
  1957. StringRef CPU;
  1958. std::vector<const char *> DecodedFeature;
  1959. std::string McpuLowerCase = Mcpu.lower();
  1960. if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
  1961. return false;
  1962. return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
  1963. }
  1964. static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
  1965. std::vector<const char *> &Features) {
  1966. Arg *A;
  1967. bool success = true;
  1968. // Enable NEON by default.
  1969. Features.push_back("+neon");
  1970. if ((A = Args.getLastArg(options::OPT_march_EQ)))
  1971. success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
  1972. else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
  1973. success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  1974. else if (Args.hasArg(options::OPT_arch))
  1975. success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
  1976. Features);
  1977. if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
  1978. success =
  1979. getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
  1980. else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
  1981. success =
  1982. getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
  1983. else if (Args.hasArg(options::OPT_arch))
  1984. success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
  1985. Args, Features);
  1986. if (!success)
  1987. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  1988. if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
  1989. Features.push_back("-fp-armv8");
  1990. Features.push_back("-crypto");
  1991. Features.push_back("-neon");
  1992. }
  1993. // En/disable crc
  1994. if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
  1995. if (A->getOption().matches(options::OPT_mcrc))
  1996. Features.push_back("+crc");
  1997. else
  1998. Features.push_back("-crc");
  1999. }
  2000. if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
  2001. options::OPT_munaligned_access))
  2002. if (A->getOption().matches(options::OPT_mno_unaligned_access))
  2003. Features.push_back("+strict-align");
  2004. if (Args.hasArg(options::OPT_ffixed_x18))
  2005. Features.push_back("+reserve-x18");
  2006. }
  2007. static void getHexagonTargetFeatures(const ArgList &Args,
  2008. std::vector<const char *> &Features) {
  2009. bool HasHVX = false, HasHVXD = false;
  2010. // FIXME: This should be able to use handleTargetFeaturesGroup except it is
  2011. // doing dependent option handling here rather than in initFeatureMap or a
  2012. // similar handler.
  2013. for (auto &A : Args) {
  2014. auto &Opt = A->getOption();
  2015. if (Opt.matches(options::OPT_mhexagon_hvx))
  2016. HasHVX = true;
  2017. else if (Opt.matches(options::OPT_mno_hexagon_hvx))
  2018. HasHVXD = HasHVX = false;
  2019. else if (Opt.matches(options::OPT_mhexagon_hvx_double))
  2020. HasHVXD = HasHVX = true;
  2021. else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
  2022. HasHVXD = false;
  2023. else
  2024. continue;
  2025. A->claim();
  2026. }
  2027. Features.push_back(HasHVX ? "+hvx" : "-hvx");
  2028. Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
  2029. }
  2030. static void getWebAssemblyTargetFeatures(const ArgList &Args,
  2031. std::vector<const char *> &Features) {
  2032. handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
  2033. }
  2034. static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
  2035. const ArgList &Args, ArgStringList &CmdArgs,
  2036. bool ForAS) {
  2037. const Driver &D = TC.getDriver();
  2038. std::vector<const char *> Features;
  2039. switch (Triple.getArch()) {
  2040. default:
  2041. break;
  2042. case llvm::Triple::mips:
  2043. case llvm::Triple::mipsel:
  2044. case llvm::Triple::mips64:
  2045. case llvm::Triple::mips64el:
  2046. getMIPSTargetFeatures(D, Triple, Args, Features);
  2047. break;
  2048. case llvm::Triple::arm:
  2049. case llvm::Triple::armeb:
  2050. case llvm::Triple::thumb:
  2051. case llvm::Triple::thumbeb:
  2052. getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
  2053. break;
  2054. case llvm::Triple::ppc:
  2055. case llvm::Triple::ppc64:
  2056. case llvm::Triple::ppc64le:
  2057. getPPCTargetFeatures(D, Triple, Args, Features);
  2058. break;
  2059. case llvm::Triple::systemz:
  2060. getSystemZTargetFeatures(Args, Features);
  2061. break;
  2062. case llvm::Triple::aarch64:
  2063. case llvm::Triple::aarch64_be:
  2064. getAArch64TargetFeatures(D, Args, Features);
  2065. break;
  2066. case llvm::Triple::x86:
  2067. case llvm::Triple::x86_64:
  2068. getX86TargetFeatures(D, Triple, Args, Features);
  2069. break;
  2070. case llvm::Triple::hexagon:
  2071. getHexagonTargetFeatures(Args, Features);
  2072. break;
  2073. case llvm::Triple::wasm32:
  2074. case llvm::Triple::wasm64:
  2075. getWebAssemblyTargetFeatures(Args, Features);
  2076. break;
  2077. }
  2078. // Find the last of each feature.
  2079. llvm::StringMap<unsigned> LastOpt;
  2080. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2081. const char *Name = Features[I];
  2082. assert(Name[0] == '-' || Name[0] == '+');
  2083. LastOpt[Name + 1] = I;
  2084. }
  2085. for (unsigned I = 0, N = Features.size(); I < N; ++I) {
  2086. // If this feature was overridden, ignore it.
  2087. const char *Name = Features[I];
  2088. llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
  2089. assert(LastI != LastOpt.end());
  2090. unsigned Last = LastI->second;
  2091. if (Last != I)
  2092. continue;
  2093. CmdArgs.push_back("-target-feature");
  2094. CmdArgs.push_back(Name);
  2095. }
  2096. }
  2097. static bool
  2098. shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
  2099. const llvm::Triple &Triple) {
  2100. // We use the zero-cost exception tables for Objective-C if the non-fragile
  2101. // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
  2102. // later.
  2103. if (runtime.isNonFragile())
  2104. return true;
  2105. if (!Triple.isMacOSX())
  2106. return false;
  2107. return (!Triple.isMacOSXVersionLT(10, 5) &&
  2108. (Triple.getArch() == llvm::Triple::x86_64 ||
  2109. Triple.getArch() == llvm::Triple::arm));
  2110. }
  2111. /// Adds exception related arguments to the driver command arguments. There's a
  2112. /// master flag, -fexceptions and also language specific flags to enable/disable
  2113. /// C++ and Objective-C exceptions. This makes it possible to for example
  2114. /// disable C++ exceptions but enable Objective-C exceptions.
  2115. static void addExceptionArgs(const ArgList &Args, types::ID InputType,
  2116. const ToolChain &TC, bool KernelOrKext,
  2117. const ObjCRuntime &objcRuntime,
  2118. ArgStringList &CmdArgs) {
  2119. const Driver &D = TC.getDriver();
  2120. const llvm::Triple &Triple = TC.getTriple();
  2121. if (KernelOrKext) {
  2122. // -mkernel and -fapple-kext imply no exceptions, so claim exception related
  2123. // arguments now to avoid warnings about unused arguments.
  2124. Args.ClaimAllArgs(options::OPT_fexceptions);
  2125. Args.ClaimAllArgs(options::OPT_fno_exceptions);
  2126. Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
  2127. Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
  2128. Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
  2129. Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
  2130. return;
  2131. }
  2132. // See if the user explicitly enabled exceptions.
  2133. bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  2134. false);
  2135. // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
  2136. // is not necessarily sensible, but follows GCC.
  2137. if (types::isObjC(InputType) &&
  2138. Args.hasFlag(options::OPT_fobjc_exceptions,
  2139. options::OPT_fno_objc_exceptions, true)) {
  2140. CmdArgs.push_back("-fobjc-exceptions");
  2141. EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
  2142. }
  2143. if (types::isCXX(InputType)) {
  2144. // Disable C++ EH by default on XCore, PS4, and MSVC.
  2145. // FIXME: Remove MSVC from this list once things work.
  2146. bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
  2147. !Triple.isPS4CPU() &&
  2148. !Triple.isWindowsMSVCEnvironment();
  2149. Arg *ExceptionArg = Args.getLastArg(
  2150. options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
  2151. options::OPT_fexceptions, options::OPT_fno_exceptions);
  2152. if (ExceptionArg)
  2153. CXXExceptionsEnabled =
  2154. ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
  2155. ExceptionArg->getOption().matches(options::OPT_fexceptions);
  2156. if (CXXExceptionsEnabled) {
  2157. if (Triple.isPS4CPU()) {
  2158. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  2159. assert(ExceptionArg &&
  2160. "On the PS4 exceptions should only be enabled if passing "
  2161. "an argument");
  2162. if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
  2163. const Arg *RTTIArg = TC.getRTTIArg();
  2164. assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
  2165. D.Diag(diag::err_drv_argument_not_allowed_with)
  2166. << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
  2167. } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
  2168. D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
  2169. } else
  2170. assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
  2171. CmdArgs.push_back("-fcxx-exceptions");
  2172. EH = true;
  2173. }
  2174. }
  2175. if (EH)
  2176. CmdArgs.push_back("-fexceptions");
  2177. }
  2178. static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
  2179. bool Default = true;
  2180. if (TC.getTriple().isOSDarwin()) {
  2181. // The native darwin assembler doesn't support the linker_option directives,
  2182. // so we disable them if we think the .s file will be passed to it.
  2183. Default = TC.useIntegratedAs();
  2184. }
  2185. return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
  2186. Default);
  2187. }
  2188. static bool ShouldDisableDwarfDirectory(const ArgList &Args,
  2189. const ToolChain &TC) {
  2190. bool UseDwarfDirectory =
  2191. Args.hasFlag(options::OPT_fdwarf_directory_asm,
  2192. options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
  2193. return !UseDwarfDirectory;
  2194. }
  2195. /// \brief Check whether the given input tree contains any compilation actions.
  2196. static bool ContainsCompileAction(const Action *A) {
  2197. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
  2198. return true;
  2199. for (const auto &Act : *A)
  2200. if (ContainsCompileAction(Act))
  2201. return true;
  2202. return false;
  2203. }
  2204. /// \brief Check if -relax-all should be passed to the internal assembler.
  2205. /// This is done by default when compiling non-assembler source with -O0.
  2206. static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
  2207. bool RelaxDefault = true;
  2208. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2209. RelaxDefault = A->getOption().matches(options::OPT_O0);
  2210. if (RelaxDefault) {
  2211. RelaxDefault = false;
  2212. for (const auto &Act : C.getActions()) {
  2213. if (ContainsCompileAction(Act)) {
  2214. RelaxDefault = true;
  2215. break;
  2216. }
  2217. }
  2218. }
  2219. return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
  2220. RelaxDefault);
  2221. }
  2222. // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
  2223. // to the corresponding DebugInfoKind.
  2224. static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
  2225. assert(A.getOption().matches(options::OPT_gN_Group) &&
  2226. "Not a -g option that specifies a debug-info level");
  2227. if (A.getOption().matches(options::OPT_g0) ||
  2228. A.getOption().matches(options::OPT_ggdb0))
  2229. return codegenoptions::NoDebugInfo;
  2230. if (A.getOption().matches(options::OPT_gline_tables_only) ||
  2231. A.getOption().matches(options::OPT_ggdb1))
  2232. return codegenoptions::DebugLineTablesOnly;
  2233. return codegenoptions::LimitedDebugInfo;
  2234. }
  2235. // Extract the integer N from a string spelled "-dwarf-N", returning 0
  2236. // on mismatch. The StringRef input (rather than an Arg) allows
  2237. // for use by the "-Xassembler" option parser.
  2238. static unsigned DwarfVersionNum(StringRef ArgValue) {
  2239. return llvm::StringSwitch<unsigned>(ArgValue)
  2240. .Case("-gdwarf-2", 2)
  2241. .Case("-gdwarf-3", 3)
  2242. .Case("-gdwarf-4", 4)
  2243. .Case("-gdwarf-5", 5)
  2244. .Default(0);
  2245. }
  2246. static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
  2247. codegenoptions::DebugInfoKind DebugInfoKind,
  2248. unsigned DwarfVersion,
  2249. llvm::DebuggerKind DebuggerTuning) {
  2250. switch (DebugInfoKind) {
  2251. case codegenoptions::DebugLineTablesOnly:
  2252. CmdArgs.push_back("-debug-info-kind=line-tables-only");
  2253. break;
  2254. case codegenoptions::LimitedDebugInfo:
  2255. CmdArgs.push_back("-debug-info-kind=limited");
  2256. break;
  2257. case codegenoptions::FullDebugInfo:
  2258. CmdArgs.push_back("-debug-info-kind=standalone");
  2259. break;
  2260. default:
  2261. break;
  2262. }
  2263. if (DwarfVersion > 0)
  2264. CmdArgs.push_back(
  2265. Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
  2266. switch (DebuggerTuning) {
  2267. case llvm::DebuggerKind::GDB:
  2268. CmdArgs.push_back("-debugger-tuning=gdb");
  2269. break;
  2270. case llvm::DebuggerKind::LLDB:
  2271. CmdArgs.push_back("-debugger-tuning=lldb");
  2272. break;
  2273. case llvm::DebuggerKind::SCE:
  2274. CmdArgs.push_back("-debugger-tuning=sce");
  2275. break;
  2276. default:
  2277. break;
  2278. }
  2279. }
  2280. static void CollectArgsForIntegratedAssembler(Compilation &C,
  2281. const ArgList &Args,
  2282. ArgStringList &CmdArgs,
  2283. const Driver &D) {
  2284. if (UseRelaxAll(C, Args))
  2285. CmdArgs.push_back("-mrelax-all");
  2286. // Only default to -mincremental-linker-compatible if we think we are
  2287. // targeting the MSVC linker.
  2288. bool DefaultIncrementalLinkerCompatible =
  2289. C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
  2290. if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
  2291. options::OPT_mno_incremental_linker_compatible,
  2292. DefaultIncrementalLinkerCompatible))
  2293. CmdArgs.push_back("-mincremental-linker-compatible");
  2294. // When passing -I arguments to the assembler we sometimes need to
  2295. // unconditionally take the next argument. For example, when parsing
  2296. // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
  2297. // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
  2298. // arg after parsing the '-I' arg.
  2299. bool TakeNextArg = false;
  2300. // When using an integrated assembler, translate -Wa, and -Xassembler
  2301. // options.
  2302. bool CompressDebugSections = false;
  2303. const char *MipsTargetFeature = nullptr;
  2304. for (const Arg *A :
  2305. Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
  2306. A->claim();
  2307. for (StringRef Value : A->getValues()) {
  2308. if (TakeNextArg) {
  2309. CmdArgs.push_back(Value.data());
  2310. TakeNextArg = false;
  2311. continue;
  2312. }
  2313. switch (C.getDefaultToolChain().getArch()) {
  2314. default:
  2315. break;
  2316. case llvm::Triple::mips:
  2317. case llvm::Triple::mipsel:
  2318. case llvm::Triple::mips64:
  2319. case llvm::Triple::mips64el:
  2320. if (Value == "--trap") {
  2321. CmdArgs.push_back("-target-feature");
  2322. CmdArgs.push_back("+use-tcc-in-div");
  2323. continue;
  2324. }
  2325. if (Value == "--break") {
  2326. CmdArgs.push_back("-target-feature");
  2327. CmdArgs.push_back("-use-tcc-in-div");
  2328. continue;
  2329. }
  2330. if (Value.startswith("-msoft-float")) {
  2331. CmdArgs.push_back("-target-feature");
  2332. CmdArgs.push_back("+soft-float");
  2333. continue;
  2334. }
  2335. if (Value.startswith("-mhard-float")) {
  2336. CmdArgs.push_back("-target-feature");
  2337. CmdArgs.push_back("-soft-float");
  2338. continue;
  2339. }
  2340. MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
  2341. .Case("-mips1", "+mips1")
  2342. .Case("-mips2", "+mips2")
  2343. .Case("-mips3", "+mips3")
  2344. .Case("-mips4", "+mips4")
  2345. .Case("-mips5", "+mips5")
  2346. .Case("-mips32", "+mips32")
  2347. .Case("-mips32r2", "+mips32r2")
  2348. .Case("-mips32r3", "+mips32r3")
  2349. .Case("-mips32r5", "+mips32r5")
  2350. .Case("-mips32r6", "+mips32r6")
  2351. .Case("-mips64", "+mips64")
  2352. .Case("-mips64r2", "+mips64r2")
  2353. .Case("-mips64r3", "+mips64r3")
  2354. .Case("-mips64r5", "+mips64r5")
  2355. .Case("-mips64r6", "+mips64r6")
  2356. .Default(nullptr);
  2357. if (MipsTargetFeature)
  2358. continue;
  2359. }
  2360. if (Value == "-force_cpusubtype_ALL") {
  2361. // Do nothing, this is the default and we don't support anything else.
  2362. } else if (Value == "-L") {
  2363. CmdArgs.push_back("-msave-temp-labels");
  2364. } else if (Value == "--fatal-warnings") {
  2365. CmdArgs.push_back("-massembler-fatal-warnings");
  2366. } else if (Value == "--noexecstack") {
  2367. CmdArgs.push_back("-mnoexecstack");
  2368. } else if (Value == "-compress-debug-sections" ||
  2369. Value == "--compress-debug-sections") {
  2370. CompressDebugSections = true;
  2371. } else if (Value == "-nocompress-debug-sections" ||
  2372. Value == "--nocompress-debug-sections") {
  2373. CompressDebugSections = false;
  2374. } else if (Value.startswith("-I")) {
  2375. CmdArgs.push_back(Value.data());
  2376. // We need to consume the next argument if the current arg is a plain
  2377. // -I. The next arg will be the include directory.
  2378. if (Value == "-I")
  2379. TakeNextArg = true;
  2380. } else if (Value.startswith("-gdwarf-")) {
  2381. // "-gdwarf-N" options are not cc1as options.
  2382. unsigned DwarfVersion = DwarfVersionNum(Value);
  2383. if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
  2384. CmdArgs.push_back(Value.data());
  2385. } else {
  2386. RenderDebugEnablingArgs(Args, CmdArgs,
  2387. codegenoptions::LimitedDebugInfo,
  2388. DwarfVersion, llvm::DebuggerKind::Default);
  2389. }
  2390. } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
  2391. Value.startswith("-mhwdiv") || Value.startswith("-march")) {
  2392. // Do nothing, we'll validate it later.
  2393. } else {
  2394. D.Diag(diag::err_drv_unsupported_option_argument)
  2395. << A->getOption().getName() << Value;
  2396. }
  2397. }
  2398. }
  2399. if (CompressDebugSections) {
  2400. if (llvm::zlib::isAvailable())
  2401. CmdArgs.push_back("-compress-debug-sections");
  2402. else
  2403. D.Diag(diag::warn_debug_compression_unavailable);
  2404. }
  2405. if (MipsTargetFeature != nullptr) {
  2406. CmdArgs.push_back("-target-feature");
  2407. CmdArgs.push_back(MipsTargetFeature);
  2408. }
  2409. }
  2410. // This adds the static libclang_rt.builtins-arch.a directly to the command line
  2411. // FIXME: Make sure we can also emit shared objects if they're requested
  2412. // and available, check for possible errors, etc.
  2413. static void addClangRT(const ToolChain &TC, const ArgList &Args,
  2414. ArgStringList &CmdArgs) {
  2415. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
  2416. }
  2417. namespace {
  2418. enum OpenMPRuntimeKind {
  2419. /// An unknown OpenMP runtime. We can't generate effective OpenMP code
  2420. /// without knowing what runtime to target.
  2421. OMPRT_Unknown,
  2422. /// The LLVM OpenMP runtime. When completed and integrated, this will become
  2423. /// the default for Clang.
  2424. OMPRT_OMP,
  2425. /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
  2426. /// this runtime but can swallow the pragmas, and find and link against the
  2427. /// runtime library itself.
  2428. OMPRT_GOMP,
  2429. /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
  2430. /// OpenMP runtime. We support this mode for users with existing dependencies
  2431. /// on this runtime library name.
  2432. OMPRT_IOMP5
  2433. };
  2434. }
  2435. /// Compute the desired OpenMP runtime from the flag provided.
  2436. static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
  2437. const ArgList &Args) {
  2438. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  2439. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  2440. if (A)
  2441. RuntimeName = A->getValue();
  2442. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  2443. .Case("libomp", OMPRT_OMP)
  2444. .Case("libgomp", OMPRT_GOMP)
  2445. .Case("libiomp5", OMPRT_IOMP5)
  2446. .Default(OMPRT_Unknown);
  2447. if (RT == OMPRT_Unknown) {
  2448. if (A)
  2449. TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
  2450. << A->getOption().getName() << A->getValue();
  2451. else
  2452. // FIXME: We could use a nicer diagnostic here.
  2453. TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  2454. }
  2455. return RT;
  2456. }
  2457. static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
  2458. const ArgList &Args) {
  2459. if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  2460. options::OPT_fno_openmp, false))
  2461. return;
  2462. switch (getOpenMPRuntime(TC, Args)) {
  2463. case OMPRT_OMP:
  2464. CmdArgs.push_back("-lomp");
  2465. break;
  2466. case OMPRT_GOMP:
  2467. CmdArgs.push_back("-lgomp");
  2468. break;
  2469. case OMPRT_IOMP5:
  2470. CmdArgs.push_back("-liomp5");
  2471. break;
  2472. case OMPRT_Unknown:
  2473. // Already diagnosed.
  2474. break;
  2475. }
  2476. }
  2477. static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
  2478. ArgStringList &CmdArgs, StringRef Sanitizer,
  2479. bool IsShared, bool IsWhole) {
  2480. // Wrap any static runtimes that must be forced into executable in
  2481. // whole-archive.
  2482. if (IsWhole) CmdArgs.push_back("-whole-archive");
  2483. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
  2484. if (IsWhole) CmdArgs.push_back("-no-whole-archive");
  2485. }
  2486. // Tries to use a file with the list of dynamic symbols that need to be exported
  2487. // from the runtime library. Returns true if the file was found.
  2488. static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
  2489. ArgStringList &CmdArgs,
  2490. StringRef Sanitizer) {
  2491. SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
  2492. if (llvm::sys::fs::exists(SanRT + ".syms")) {
  2493. CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
  2494. return true;
  2495. }
  2496. return false;
  2497. }
  2498. static void linkSanitizerRuntimeDeps(const ToolChain &TC,
  2499. ArgStringList &CmdArgs) {
  2500. // Force linking against the system libraries sanitizers depends on
  2501. // (see PR15823 why this is necessary).
  2502. CmdArgs.push_back("--no-as-needed");
  2503. CmdArgs.push_back("-lpthread");
  2504. CmdArgs.push_back("-lrt");
  2505. CmdArgs.push_back("-lm");
  2506. // There's no libdl on FreeBSD.
  2507. if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
  2508. CmdArgs.push_back("-ldl");
  2509. }
  2510. static void
  2511. collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2512. SmallVectorImpl<StringRef> &SharedRuntimes,
  2513. SmallVectorImpl<StringRef> &StaticRuntimes,
  2514. SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
  2515. SmallVectorImpl<StringRef> &HelperStaticRuntimes,
  2516. SmallVectorImpl<StringRef> &RequiredSymbols) {
  2517. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  2518. // Collect shared runtimes.
  2519. if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
  2520. SharedRuntimes.push_back("asan");
  2521. }
  2522. // The stats_client library is also statically linked into DSOs.
  2523. if (SanArgs.needsStatsRt())
  2524. StaticRuntimes.push_back("stats_client");
  2525. // Collect static runtimes.
  2526. if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
  2527. // Don't link static runtimes into DSOs or if compiling for Android.
  2528. return;
  2529. }
  2530. if (SanArgs.needsAsanRt()) {
  2531. if (SanArgs.needsSharedAsanRt()) {
  2532. HelperStaticRuntimes.push_back("asan-preinit");
  2533. } else {
  2534. StaticRuntimes.push_back("asan");
  2535. if (SanArgs.linkCXXRuntimes())
  2536. StaticRuntimes.push_back("asan_cxx");
  2537. }
  2538. }
  2539. if (SanArgs.needsDfsanRt())
  2540. StaticRuntimes.push_back("dfsan");
  2541. if (SanArgs.needsLsanRt())
  2542. StaticRuntimes.push_back("lsan");
  2543. if (SanArgs.needsMsanRt()) {
  2544. StaticRuntimes.push_back("msan");
  2545. if (SanArgs.linkCXXRuntimes())
  2546. StaticRuntimes.push_back("msan_cxx");
  2547. }
  2548. if (SanArgs.needsTsanRt()) {
  2549. StaticRuntimes.push_back("tsan");
  2550. if (SanArgs.linkCXXRuntimes())
  2551. StaticRuntimes.push_back("tsan_cxx");
  2552. }
  2553. if (SanArgs.needsUbsanRt()) {
  2554. StaticRuntimes.push_back("ubsan_standalone");
  2555. if (SanArgs.linkCXXRuntimes())
  2556. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2557. }
  2558. if (SanArgs.needsSafeStackRt())
  2559. StaticRuntimes.push_back("safestack");
  2560. if (SanArgs.needsCfiRt())
  2561. StaticRuntimes.push_back("cfi");
  2562. if (SanArgs.needsCfiDiagRt()) {
  2563. StaticRuntimes.push_back("cfi_diag");
  2564. if (SanArgs.linkCXXRuntimes())
  2565. StaticRuntimes.push_back("ubsan_standalone_cxx");
  2566. }
  2567. if (SanArgs.needsStatsRt()) {
  2568. NonWholeStaticRuntimes.push_back("stats");
  2569. RequiredSymbols.push_back("__sanitizer_stats_register");
  2570. }
  2571. }
  2572. // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
  2573. // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
  2574. static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
  2575. ArgStringList &CmdArgs) {
  2576. SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
  2577. NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
  2578. collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
  2579. NonWholeStaticRuntimes, HelperStaticRuntimes,
  2580. RequiredSymbols);
  2581. for (auto RT : SharedRuntimes)
  2582. addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
  2583. for (auto RT : HelperStaticRuntimes)
  2584. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2585. bool AddExportDynamic = false;
  2586. for (auto RT : StaticRuntimes) {
  2587. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
  2588. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2589. }
  2590. for (auto RT : NonWholeStaticRuntimes) {
  2591. addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
  2592. AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
  2593. }
  2594. for (auto S : RequiredSymbols) {
  2595. CmdArgs.push_back("-u");
  2596. CmdArgs.push_back(Args.MakeArgString(S));
  2597. }
  2598. // If there is a static runtime with no dynamic list, force all the symbols
  2599. // to be dynamic to be sure we export sanitizer interface functions.
  2600. if (AddExportDynamic)
  2601. CmdArgs.push_back("-export-dynamic");
  2602. return !StaticRuntimes.empty();
  2603. }
  2604. static bool areOptimizationsEnabled(const ArgList &Args) {
  2605. // Find the last -O arg and see if it is non-zero.
  2606. if (Arg *A = Args.getLastArg(options::OPT_O_Group))
  2607. return !A->getOption().matches(options::OPT_O0);
  2608. // Defaults to -O0.
  2609. return false;
  2610. }
  2611. static bool shouldUseFramePointerForTarget(const ArgList &Args,
  2612. const llvm::Triple &Triple) {
  2613. switch (Triple.getArch()) {
  2614. case llvm::Triple::xcore:
  2615. case llvm::Triple::wasm32:
  2616. case llvm::Triple::wasm64:
  2617. // XCore never wants frame pointers, regardless of OS.
  2618. // WebAssembly never wants frame pointers.
  2619. return false;
  2620. default:
  2621. break;
  2622. }
  2623. if (Triple.isOSLinux()) {
  2624. switch (Triple.getArch()) {
  2625. // Don't use a frame pointer on linux if optimizing for certain targets.
  2626. case llvm::Triple::mips64:
  2627. case llvm::Triple::mips64el:
  2628. case llvm::Triple::mips:
  2629. case llvm::Triple::mipsel:
  2630. case llvm::Triple::systemz:
  2631. case llvm::Triple::x86:
  2632. case llvm::Triple::x86_64:
  2633. return !areOptimizationsEnabled(Args);
  2634. default:
  2635. return true;
  2636. }
  2637. }
  2638. if (Triple.isOSWindows()) {
  2639. switch (Triple.getArch()) {
  2640. case llvm::Triple::x86:
  2641. return !areOptimizationsEnabled(Args);
  2642. case llvm::Triple::arm:
  2643. case llvm::Triple::thumb:
  2644. // Windows on ARM builds with FPO disabled to aid fast stack walking
  2645. return true;
  2646. default:
  2647. // All other supported Windows ISAs use xdata unwind information, so frame
  2648. // pointers are not generally useful.
  2649. return false;
  2650. }
  2651. }
  2652. return true;
  2653. }
  2654. static bool shouldUseFramePointer(const ArgList &Args,
  2655. const llvm::Triple &Triple) {
  2656. if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
  2657. options::OPT_fomit_frame_pointer))
  2658. return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
  2659. if (Args.hasArg(options::OPT_pg))
  2660. return true;
  2661. return shouldUseFramePointerForTarget(Args, Triple);
  2662. }
  2663. static bool shouldUseLeafFramePointer(const ArgList &Args,
  2664. const llvm::Triple &Triple) {
  2665. if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
  2666. options::OPT_momit_leaf_frame_pointer))
  2667. return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
  2668. if (Args.hasArg(options::OPT_pg))
  2669. return true;
  2670. if (Triple.isPS4CPU())
  2671. return false;
  2672. return shouldUseFramePointerForTarget(Args, Triple);
  2673. }
  2674. /// Add a CC1 option to specify the debug compilation directory.
  2675. static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
  2676. SmallString<128> cwd;
  2677. if (!llvm::sys::fs::current_path(cwd)) {
  2678. CmdArgs.push_back("-fdebug-compilation-dir");
  2679. CmdArgs.push_back(Args.MakeArgString(cwd));
  2680. }
  2681. }
  2682. static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
  2683. Arg *FinalOutput = Args.getLastArg(options::OPT_o);
  2684. if (FinalOutput && Args.hasArg(options::OPT_c)) {
  2685. SmallString<128> T(FinalOutput->getValue());
  2686. llvm::sys::path::replace_extension(T, "dwo");
  2687. return Args.MakeArgString(T);
  2688. } else {
  2689. // Use the compilation dir.
  2690. SmallString<128> T(
  2691. Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
  2692. SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
  2693. llvm::sys::path::replace_extension(F, "dwo");
  2694. T += F;
  2695. return Args.MakeArgString(F);
  2696. }
  2697. }
  2698. static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
  2699. const JobAction &JA, const ArgList &Args,
  2700. const InputInfo &Output, const char *OutFile) {
  2701. ArgStringList ExtractArgs;
  2702. ExtractArgs.push_back("--extract-dwo");
  2703. ArgStringList StripArgs;
  2704. StripArgs.push_back("--strip-dwo");
  2705. // Grabbing the output of the earlier compile step.
  2706. StripArgs.push_back(Output.getFilename());
  2707. ExtractArgs.push_back(Output.getFilename());
  2708. ExtractArgs.push_back(OutFile);
  2709. const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
  2710. InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
  2711. // First extract the dwo sections.
  2712. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
  2713. // Then remove them from the original .o file.
  2714. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
  2715. }
  2716. /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
  2717. /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
  2718. static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
  2719. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  2720. if (A->getOption().matches(options::OPT_O4) ||
  2721. A->getOption().matches(options::OPT_Ofast))
  2722. return true;
  2723. if (A->getOption().matches(options::OPT_O0))
  2724. return false;
  2725. assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
  2726. // Vectorize -Os.
  2727. StringRef S(A->getValue());
  2728. if (S == "s")
  2729. return true;
  2730. // Don't vectorize -Oz, unless it's the slp vectorizer.
  2731. if (S == "z")
  2732. return isSlpVec;
  2733. unsigned OptLevel = 0;
  2734. if (S.getAsInteger(10, OptLevel))
  2735. return false;
  2736. return OptLevel > 1;
  2737. }
  2738. return false;
  2739. }
  2740. /// Add -x lang to \p CmdArgs for \p Input.
  2741. static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  2742. ArgStringList &CmdArgs) {
  2743. // When using -verify-pch, we don't want to provide the type
  2744. // 'precompiled-header' if it was inferred from the file extension
  2745. if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
  2746. return;
  2747. CmdArgs.push_back("-x");
  2748. if (Args.hasArg(options::OPT_rewrite_objc))
  2749. CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
  2750. else
  2751. CmdArgs.push_back(types::getTypeName(Input.getType()));
  2752. }
  2753. static VersionTuple getMSCompatibilityVersion(unsigned Version) {
  2754. if (Version < 100)
  2755. return VersionTuple(Version);
  2756. if (Version < 10000)
  2757. return VersionTuple(Version / 100, Version % 100);
  2758. unsigned Build = 0, Factor = 1;
  2759. for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
  2760. Build = Build + (Version % 10) * Factor;
  2761. return VersionTuple(Version / 100, Version % 100, Build);
  2762. }
  2763. // Claim options we don't want to warn if they are unused. We do this for
  2764. // options that build systems might add but are unused when assembling or only
  2765. // running the preprocessor for example.
  2766. static void claimNoWarnArgs(const ArgList &Args) {
  2767. // Don't warn about unused -f(no-)?lto. This can happen when we're
  2768. // preprocessing, precompiling or assembling.
  2769. Args.ClaimAllArgs(options::OPT_flto_EQ);
  2770. Args.ClaimAllArgs(options::OPT_flto);
  2771. Args.ClaimAllArgs(options::OPT_fno_lto);
  2772. }
  2773. static void appendUserToPath(SmallVectorImpl<char> &Result) {
  2774. #ifdef LLVM_ON_UNIX
  2775. const char *Username = getenv("LOGNAME");
  2776. #else
  2777. const char *Username = getenv("USERNAME");
  2778. #endif
  2779. if (Username) {
  2780. // Validate that LoginName can be used in a path, and get its length.
  2781. size_t Len = 0;
  2782. for (const char *P = Username; *P; ++P, ++Len) {
  2783. if (!isAlphanumeric(*P) && *P != '_') {
  2784. Username = nullptr;
  2785. break;
  2786. }
  2787. }
  2788. if (Username && Len > 0) {
  2789. Result.append(Username, Username + Len);
  2790. return;
  2791. }
  2792. }
  2793. // Fallback to user id.
  2794. #ifdef LLVM_ON_UNIX
  2795. std::string UID = llvm::utostr(getuid());
  2796. #else
  2797. // FIXME: Windows seems to have an 'SID' that might work.
  2798. std::string UID = "9999";
  2799. #endif
  2800. Result.append(UID.begin(), UID.end());
  2801. }
  2802. VersionTuple visualstudio::getMSVCVersion(const Driver *D,
  2803. const llvm::Triple &Triple,
  2804. const llvm::opt::ArgList &Args,
  2805. bool IsWindowsMSVC) {
  2806. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  2807. IsWindowsMSVC) ||
  2808. Args.hasArg(options::OPT_fmsc_version) ||
  2809. Args.hasArg(options::OPT_fms_compatibility_version)) {
  2810. const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
  2811. const Arg *MSCompatibilityVersion =
  2812. Args.getLastArg(options::OPT_fms_compatibility_version);
  2813. if (MSCVersion && MSCompatibilityVersion) {
  2814. if (D)
  2815. D->Diag(diag::err_drv_argument_not_allowed_with)
  2816. << MSCVersion->getAsString(Args)
  2817. << MSCompatibilityVersion->getAsString(Args);
  2818. return VersionTuple();
  2819. }
  2820. if (MSCompatibilityVersion) {
  2821. VersionTuple MSVT;
  2822. if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
  2823. D->Diag(diag::err_drv_invalid_value)
  2824. << MSCompatibilityVersion->getAsString(Args)
  2825. << MSCompatibilityVersion->getValue();
  2826. return MSVT;
  2827. }
  2828. if (MSCVersion) {
  2829. unsigned Version = 0;
  2830. if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
  2831. D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
  2832. << MSCVersion->getValue();
  2833. return getMSCompatibilityVersion(Version);
  2834. }
  2835. unsigned Major, Minor, Micro;
  2836. Triple.getEnvironmentVersion(Major, Minor, Micro);
  2837. if (Major || Minor || Micro)
  2838. return VersionTuple(Major, Minor, Micro);
  2839. return VersionTuple(18);
  2840. }
  2841. return VersionTuple();
  2842. }
  2843. static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
  2844. const InputInfo &Output, const ArgList &Args,
  2845. ArgStringList &CmdArgs) {
  2846. auto *ProfileGenerateArg = Args.getLastArg(
  2847. options::OPT_fprofile_instr_generate,
  2848. options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
  2849. options::OPT_fprofile_generate_EQ,
  2850. options::OPT_fno_profile_instr_generate);
  2851. if (ProfileGenerateArg &&
  2852. ProfileGenerateArg->getOption().matches(
  2853. options::OPT_fno_profile_instr_generate))
  2854. ProfileGenerateArg = nullptr;
  2855. auto *ProfileUseArg = Args.getLastArg(
  2856. options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
  2857. options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
  2858. options::OPT_fno_profile_instr_use);
  2859. if (ProfileUseArg &&
  2860. ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
  2861. ProfileUseArg = nullptr;
  2862. if (ProfileGenerateArg && ProfileUseArg)
  2863. D.Diag(diag::err_drv_argument_not_allowed_with)
  2864. << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
  2865. if (ProfileGenerateArg) {
  2866. if (ProfileGenerateArg->getOption().matches(
  2867. options::OPT_fprofile_instr_generate_EQ))
  2868. ProfileGenerateArg->render(Args, CmdArgs);
  2869. else if (ProfileGenerateArg->getOption().matches(
  2870. options::OPT_fprofile_generate_EQ)) {
  2871. SmallString<128> Path(ProfileGenerateArg->getValue());
  2872. llvm::sys::path::append(Path, "default.profraw");
  2873. CmdArgs.push_back(
  2874. Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
  2875. } else
  2876. Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
  2877. }
  2878. if (ProfileUseArg) {
  2879. if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
  2880. ProfileUseArg->render(Args, CmdArgs);
  2881. else if ((ProfileUseArg->getOption().matches(
  2882. options::OPT_fprofile_use_EQ) ||
  2883. ProfileUseArg->getOption().matches(
  2884. options::OPT_fprofile_instr_use))) {
  2885. SmallString<128> Path(
  2886. ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
  2887. if (Path.empty() || llvm::sys::fs::is_directory(Path))
  2888. llvm::sys::path::append(Path, "default.profdata");
  2889. CmdArgs.push_back(
  2890. Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
  2891. }
  2892. }
  2893. if (Args.hasArg(options::OPT_ftest_coverage) ||
  2894. Args.hasArg(options::OPT_coverage))
  2895. CmdArgs.push_back("-femit-coverage-notes");
  2896. if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  2897. false) ||
  2898. Args.hasArg(options::OPT_coverage))
  2899. CmdArgs.push_back("-femit-coverage-data");
  2900. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  2901. options::OPT_fno_coverage_mapping, false) &&
  2902. !ProfileGenerateArg)
  2903. D.Diag(diag::err_drv_argument_only_allowed_with)
  2904. << "-fcoverage-mapping"
  2905. << "-fprofile-instr-generate";
  2906. if (Args.hasFlag(options::OPT_fcoverage_mapping,
  2907. options::OPT_fno_coverage_mapping, false))
  2908. CmdArgs.push_back("-fcoverage-mapping");
  2909. if (C.getArgs().hasArg(options::OPT_c) ||
  2910. C.getArgs().hasArg(options::OPT_S)) {
  2911. if (Output.isFilename()) {
  2912. CmdArgs.push_back("-coverage-file");
  2913. SmallString<128> CoverageFilename;
  2914. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
  2915. CoverageFilename = FinalOutput->getValue();
  2916. } else {
  2917. CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
  2918. }
  2919. if (llvm::sys::path::is_relative(CoverageFilename)) {
  2920. SmallString<128> Pwd;
  2921. if (!llvm::sys::fs::current_path(Pwd)) {
  2922. llvm::sys::path::append(Pwd, CoverageFilename);
  2923. CoverageFilename.swap(Pwd);
  2924. }
  2925. }
  2926. CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
  2927. }
  2928. }
  2929. }
  2930. static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
  2931. ArgStringList &CmdArgs) {
  2932. if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
  2933. false) ||
  2934. Args.hasFlag(options::OPT_fprofile_generate,
  2935. options::OPT_fno_profile_instr_generate, false) ||
  2936. Args.hasFlag(options::OPT_fprofile_generate_EQ,
  2937. options::OPT_fno_profile_instr_generate, false) ||
  2938. Args.hasFlag(options::OPT_fprofile_instr_generate,
  2939. options::OPT_fno_profile_instr_generate, false) ||
  2940. Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
  2941. options::OPT_fno_profile_instr_generate, false) ||
  2942. Args.hasArg(options::OPT_fcreate_profile) ||
  2943. Args.hasArg(options::OPT_coverage)))
  2944. CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
  2945. }
  2946. /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
  2947. /// smooshes them together with platform defaults, to decide whether
  2948. /// this compile should be using PIC mode or not. Returns a tuple of
  2949. /// (RelocationModel, PICLevel, IsPIE).
  2950. static std::tuple<llvm::Reloc::Model, unsigned, bool>
  2951. ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
  2952. const ArgList &Args) {
  2953. // FIXME: why does this code...and so much everywhere else, use both
  2954. // ToolChain.getTriple() and Triple?
  2955. bool PIE = ToolChain.isPIEDefault();
  2956. bool PIC = PIE || ToolChain.isPICDefault();
  2957. // The Darwin/MachO default to use PIC does not apply when using -static.
  2958. if (ToolChain.getTriple().isOSBinFormatMachO() &&
  2959. Args.hasArg(options::OPT_static))
  2960. PIE = PIC = false;
  2961. bool IsPICLevelTwo = PIC;
  2962. bool KernelOrKext =
  2963. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  2964. // Android-specific defaults for PIC/PIE
  2965. if (ToolChain.getTriple().isAndroid()) {
  2966. switch (ToolChain.getArch()) {
  2967. case llvm::Triple::arm:
  2968. case llvm::Triple::armeb:
  2969. case llvm::Triple::thumb:
  2970. case llvm::Triple::thumbeb:
  2971. case llvm::Triple::aarch64:
  2972. case llvm::Triple::mips:
  2973. case llvm::Triple::mipsel:
  2974. case llvm::Triple::mips64:
  2975. case llvm::Triple::mips64el:
  2976. PIC = true; // "-fpic"
  2977. break;
  2978. case llvm::Triple::x86:
  2979. case llvm::Triple::x86_64:
  2980. PIC = true; // "-fPIC"
  2981. IsPICLevelTwo = true;
  2982. break;
  2983. default:
  2984. break;
  2985. }
  2986. }
  2987. // OpenBSD-specific defaults for PIE
  2988. if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
  2989. switch (ToolChain.getArch()) {
  2990. case llvm::Triple::mips64:
  2991. case llvm::Triple::mips64el:
  2992. case llvm::Triple::sparcel:
  2993. case llvm::Triple::x86:
  2994. case llvm::Triple::x86_64:
  2995. IsPICLevelTwo = false; // "-fpie"
  2996. break;
  2997. case llvm::Triple::ppc:
  2998. case llvm::Triple::sparc:
  2999. case llvm::Triple::sparcv9:
  3000. IsPICLevelTwo = true; // "-fPIE"
  3001. break;
  3002. default:
  3003. break;
  3004. }
  3005. }
  3006. // The last argument relating to either PIC or PIE wins, and no
  3007. // other argument is used. If the last argument is any flavor of the
  3008. // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
  3009. // option implicitly enables PIC at the same level.
  3010. Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
  3011. options::OPT_fpic, options::OPT_fno_pic,
  3012. options::OPT_fPIE, options::OPT_fno_PIE,
  3013. options::OPT_fpie, options::OPT_fno_pie);
  3014. // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
  3015. // is forced, then neither PIC nor PIE flags will have no effect.
  3016. if (!ToolChain.isPICDefaultForced()) {
  3017. if (LastPICArg) {
  3018. Option O = LastPICArg->getOption();
  3019. if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
  3020. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
  3021. PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
  3022. PIC =
  3023. PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
  3024. IsPICLevelTwo =
  3025. O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
  3026. } else {
  3027. PIE = PIC = false;
  3028. if (Triple.isPS4CPU()) {
  3029. Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
  3030. StringRef Model = ModelArg ? ModelArg->getValue() : "";
  3031. if (Model != "kernel") {
  3032. PIC = true;
  3033. ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
  3034. << LastPICArg->getSpelling();
  3035. }
  3036. }
  3037. }
  3038. }
  3039. }
  3040. // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
  3041. // PIC level would've been set to level 1, force it back to level 2 PIC
  3042. // instead.
  3043. if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
  3044. IsPICLevelTwo |= ToolChain.isPICDefault();
  3045. // This kernel flags are a trump-card: they will disable PIC/PIE
  3046. // generation, independent of the argument order.
  3047. if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
  3048. !Triple.isWatchOS()))
  3049. PIC = PIE = false;
  3050. if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
  3051. // This is a very special mode. It trumps the other modes, almost no one
  3052. // uses it, and it isn't even valid on any OS but Darwin.
  3053. if (!ToolChain.getTriple().isOSDarwin())
  3054. ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
  3055. << A->getSpelling() << ToolChain.getTriple().str();
  3056. // FIXME: Warn when this flag trumps some other PIC or PIE flag.
  3057. // Only a forced PIC mode can cause the actual compile to have PIC defines
  3058. // etc., no flags are sufficient. This behavior was selected to closely
  3059. // match that of llvm-gcc and Apple GCC before that.
  3060. PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
  3061. return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
  3062. }
  3063. if (PIC)
  3064. return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
  3065. return std::make_tuple(llvm::Reloc::Static, 0, false);
  3066. }
  3067. static const char *RelocationModelName(llvm::Reloc::Model Model) {
  3068. switch (Model) {
  3069. case llvm::Reloc::Default:
  3070. return nullptr;
  3071. case llvm::Reloc::Static:
  3072. return "static";
  3073. case llvm::Reloc::PIC_:
  3074. return "pic";
  3075. case llvm::Reloc::DynamicNoPIC:
  3076. return "dynamic-no-pic";
  3077. }
  3078. llvm_unreachable("Unknown Reloc::Model kind");
  3079. }
  3080. static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
  3081. ArgStringList &CmdArgs) {
  3082. llvm::Reloc::Model RelocationModel;
  3083. unsigned PICLevel;
  3084. bool IsPIE;
  3085. std::tie(RelocationModel, PICLevel, IsPIE) =
  3086. ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
  3087. if (RelocationModel != llvm::Reloc::Static)
  3088. CmdArgs.push_back("-KPIC");
  3089. }
  3090. void Clang::ConstructJob(Compilation &C, const JobAction &JA,
  3091. const InputInfo &Output, const InputInfoList &Inputs,
  3092. const ArgList &Args, const char *LinkingOutput) const {
  3093. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  3094. const llvm::Triple Triple(TripleStr);
  3095. bool KernelOrKext =
  3096. Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
  3097. const Driver &D = getToolChain().getDriver();
  3098. ArgStringList CmdArgs;
  3099. bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
  3100. bool IsWindowsCygnus =
  3101. getToolChain().getTriple().isWindowsCygwinEnvironment();
  3102. bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
  3103. bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
  3104. // Check number of inputs for sanity. We need at least one input.
  3105. assert(Inputs.size() >= 1 && "Must have at least one input.");
  3106. const InputInfo &Input = Inputs[0];
  3107. // CUDA compilation may have multiple inputs (source file + results of
  3108. // device-side compilations). All other jobs are expected to have exactly one
  3109. // input.
  3110. bool IsCuda = types::isCuda(Input.getType());
  3111. assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
  3112. // Invoke ourselves in -cc1 mode.
  3113. //
  3114. // FIXME: Implement custom jobs for internal actions.
  3115. CmdArgs.push_back("-cc1");
  3116. // Add the "effective" target triple.
  3117. CmdArgs.push_back("-triple");
  3118. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  3119. const ToolChain *AuxToolChain = nullptr;
  3120. if (IsCuda) {
  3121. // FIXME: We need a (better) way to pass information about
  3122. // particular compilation pass we're constructing here. For now we
  3123. // can check which toolchain we're using and pick the other one to
  3124. // extract the triple.
  3125. if (&getToolChain() == C.getCudaDeviceToolChain())
  3126. AuxToolChain = C.getCudaHostToolChain();
  3127. else if (&getToolChain() == C.getCudaHostToolChain())
  3128. AuxToolChain = C.getCudaDeviceToolChain();
  3129. else
  3130. llvm_unreachable("Can't figure out CUDA compilation mode.");
  3131. assert(AuxToolChain != nullptr && "No aux toolchain.");
  3132. CmdArgs.push_back("-aux-triple");
  3133. CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
  3134. CmdArgs.push_back("-fcuda-target-overloads");
  3135. CmdArgs.push_back("-fcuda-disable-target-call-checks");
  3136. }
  3137. if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
  3138. Triple.getArch() == llvm::Triple::thumb)) {
  3139. unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
  3140. unsigned Version;
  3141. Triple.getArchName().substr(Offset).getAsInteger(10, Version);
  3142. if (Version < 7)
  3143. D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
  3144. << TripleStr;
  3145. }
  3146. // Push all default warning arguments that are specific to
  3147. // the given target. These come before user provided warning options
  3148. // are provided.
  3149. getToolChain().addClangWarningOptions(CmdArgs);
  3150. // Select the appropriate action.
  3151. RewriteKind rewriteKind = RK_None;
  3152. if (isa<AnalyzeJobAction>(JA)) {
  3153. assert(JA.getType() == types::TY_Plist && "Invalid output type.");
  3154. CmdArgs.push_back("-analyze");
  3155. } else if (isa<MigrateJobAction>(JA)) {
  3156. CmdArgs.push_back("-migrate");
  3157. } else if (isa<PreprocessJobAction>(JA)) {
  3158. if (Output.getType() == types::TY_Dependencies)
  3159. CmdArgs.push_back("-Eonly");
  3160. else {
  3161. CmdArgs.push_back("-E");
  3162. if (Args.hasArg(options::OPT_rewrite_objc) &&
  3163. !Args.hasArg(options::OPT_g_Group))
  3164. CmdArgs.push_back("-P");
  3165. }
  3166. } else if (isa<AssembleJobAction>(JA)) {
  3167. CmdArgs.push_back("-emit-obj");
  3168. CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
  3169. // Also ignore explicit -force_cpusubtype_ALL option.
  3170. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  3171. } else if (isa<PrecompileJobAction>(JA)) {
  3172. // Use PCH if the user requested it.
  3173. bool UsePCH = D.CCCUsePCH;
  3174. if (JA.getType() == types::TY_Nothing)
  3175. CmdArgs.push_back("-fsyntax-only");
  3176. else if (UsePCH)
  3177. CmdArgs.push_back("-emit-pch");
  3178. else
  3179. CmdArgs.push_back("-emit-pth");
  3180. } else if (isa<VerifyPCHJobAction>(JA)) {
  3181. CmdArgs.push_back("-verify-pch");
  3182. } else {
  3183. assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
  3184. "Invalid action for clang tool.");
  3185. if (JA.getType() == types::TY_Nothing) {
  3186. CmdArgs.push_back("-fsyntax-only");
  3187. } else if (JA.getType() == types::TY_LLVM_IR ||
  3188. JA.getType() == types::TY_LTO_IR) {
  3189. CmdArgs.push_back("-emit-llvm");
  3190. } else if (JA.getType() == types::TY_LLVM_BC ||
  3191. JA.getType() == types::TY_LTO_BC) {
  3192. CmdArgs.push_back("-emit-llvm-bc");
  3193. } else if (JA.getType() == types::TY_PP_Asm) {
  3194. CmdArgs.push_back("-S");
  3195. } else if (JA.getType() == types::TY_AST) {
  3196. CmdArgs.push_back("-emit-pch");
  3197. } else if (JA.getType() == types::TY_ModuleFile) {
  3198. CmdArgs.push_back("-module-file-info");
  3199. } else if (JA.getType() == types::TY_RewrittenObjC) {
  3200. CmdArgs.push_back("-rewrite-objc");
  3201. rewriteKind = RK_NonFragile;
  3202. } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
  3203. CmdArgs.push_back("-rewrite-objc");
  3204. rewriteKind = RK_Fragile;
  3205. } else {
  3206. assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
  3207. }
  3208. // Preserve use-list order by default when emitting bitcode, so that
  3209. // loading the bitcode up in 'opt' or 'llc' and running passes gives the
  3210. // same result as running passes here. For LTO, we don't need to preserve
  3211. // the use-list order, since serialization to bitcode is part of the flow.
  3212. if (JA.getType() == types::TY_LLVM_BC)
  3213. CmdArgs.push_back("-emit-llvm-uselists");
  3214. if (D.isUsingLTO())
  3215. Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
  3216. }
  3217. if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
  3218. if (!types::isLLVMIR(Input.getType()))
  3219. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  3220. << "-x ir";
  3221. Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
  3222. }
  3223. // We normally speed up the clang process a bit by skipping destructors at
  3224. // exit, but when we're generating diagnostics we can rely on some of the
  3225. // cleanup.
  3226. if (!C.isForDiagnostics())
  3227. CmdArgs.push_back("-disable-free");
  3228. // Disable the verification pass in -asserts builds.
  3229. #ifdef NDEBUG
  3230. CmdArgs.push_back("-disable-llvm-verifier");
  3231. #endif
  3232. // Set the main file name, so that debug info works even with
  3233. // -save-temps.
  3234. CmdArgs.push_back("-main-file-name");
  3235. CmdArgs.push_back(getBaseInputName(Args, Input));
  3236. // Some flags which affect the language (via preprocessor
  3237. // defines).
  3238. if (Args.hasArg(options::OPT_static))
  3239. CmdArgs.push_back("-static-define");
  3240. if (isa<AnalyzeJobAction>(JA)) {
  3241. // Enable region store model by default.
  3242. CmdArgs.push_back("-analyzer-store=region");
  3243. // Treat blocks as analysis entry points.
  3244. CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
  3245. CmdArgs.push_back("-analyzer-eagerly-assume");
  3246. // Add default argument set.
  3247. if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
  3248. CmdArgs.push_back("-analyzer-checker=core");
  3249. if (!IsWindowsMSVC) {
  3250. CmdArgs.push_back("-analyzer-checker=unix");
  3251. } else {
  3252. // Enable "unix" checkers that also work on Windows.
  3253. CmdArgs.push_back("-analyzer-checker=unix.API");
  3254. CmdArgs.push_back("-analyzer-checker=unix.Malloc");
  3255. CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
  3256. CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
  3257. CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
  3258. CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
  3259. }
  3260. // Disable some unix checkers for PS4.
  3261. if (IsPS4CPU) {
  3262. CmdArgs.push_back("-analyzer-disable-checker=unix.API");
  3263. CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
  3264. }
  3265. if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
  3266. CmdArgs.push_back("-analyzer-checker=osx");
  3267. CmdArgs.push_back("-analyzer-checker=deadcode");
  3268. if (types::isCXX(Input.getType()))
  3269. CmdArgs.push_back("-analyzer-checker=cplusplus");
  3270. if (!IsPS4CPU) {
  3271. CmdArgs.push_back(
  3272. "-analyzer-checker=security.insecureAPI.UncheckedReturn");
  3273. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
  3274. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
  3275. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
  3276. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
  3277. CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
  3278. }
  3279. // Default nullability checks.
  3280. CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
  3281. CmdArgs.push_back(
  3282. "-analyzer-checker=nullability.NullReturnedFromNonnull");
  3283. }
  3284. // Set the output format. The default is plist, for (lame) historical
  3285. // reasons.
  3286. CmdArgs.push_back("-analyzer-output");
  3287. if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
  3288. CmdArgs.push_back(A->getValue());
  3289. else
  3290. CmdArgs.push_back("plist");
  3291. // Disable the presentation of standard compiler warnings when
  3292. // using --analyze. We only want to show static analyzer diagnostics
  3293. // or frontend errors.
  3294. CmdArgs.push_back("-w");
  3295. // Add -Xanalyzer arguments when running as analyzer.
  3296. Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
  3297. }
  3298. CheckCodeGenerationOptions(D, Args);
  3299. llvm::Reloc::Model RelocationModel;
  3300. unsigned PICLevel;
  3301. bool IsPIE;
  3302. std::tie(RelocationModel, PICLevel, IsPIE) =
  3303. ParsePICArgs(getToolChain(), Triple, Args);
  3304. const char *RMName = RelocationModelName(RelocationModel);
  3305. if (RMName) {
  3306. CmdArgs.push_back("-mrelocation-model");
  3307. CmdArgs.push_back(RMName);
  3308. }
  3309. if (PICLevel > 0) {
  3310. CmdArgs.push_back("-pic-level");
  3311. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3312. if (IsPIE) {
  3313. CmdArgs.push_back("-pie-level");
  3314. CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
  3315. }
  3316. }
  3317. if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
  3318. CmdArgs.push_back("-meabi");
  3319. CmdArgs.push_back(A->getValue());
  3320. }
  3321. CmdArgs.push_back("-mthread-model");
  3322. if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
  3323. CmdArgs.push_back(A->getValue());
  3324. else
  3325. CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
  3326. Args.AddLastArg(CmdArgs, options::OPT_fveclib);
  3327. if (!Args.hasFlag(options::OPT_fmerge_all_constants,
  3328. options::OPT_fno_merge_all_constants))
  3329. CmdArgs.push_back("-fno-merge-all-constants");
  3330. // LLVM Code Generator Options.
  3331. if (Args.hasArg(options::OPT_frewrite_map_file) ||
  3332. Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
  3333. for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
  3334. options::OPT_frewrite_map_file_EQ)) {
  3335. CmdArgs.push_back("-frewrite-map-file");
  3336. CmdArgs.push_back(A->getValue());
  3337. A->claim();
  3338. }
  3339. }
  3340. if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
  3341. StringRef v = A->getValue();
  3342. CmdArgs.push_back("-mllvm");
  3343. CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
  3344. A->claim();
  3345. }
  3346. if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
  3347. CmdArgs.push_back("-mregparm");
  3348. CmdArgs.push_back(A->getValue());
  3349. }
  3350. if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
  3351. options::OPT_freg_struct_return)) {
  3352. if (getToolChain().getArch() != llvm::Triple::x86) {
  3353. D.Diag(diag::err_drv_unsupported_opt_for_target)
  3354. << A->getSpelling() << getToolChain().getTriple().str();
  3355. } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
  3356. CmdArgs.push_back("-fpcc-struct-return");
  3357. } else {
  3358. assert(A->getOption().matches(options::OPT_freg_struct_return));
  3359. CmdArgs.push_back("-freg-struct-return");
  3360. }
  3361. }
  3362. if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
  3363. CmdArgs.push_back("-mrtd");
  3364. if (shouldUseFramePointer(Args, getToolChain().getTriple()))
  3365. CmdArgs.push_back("-mdisable-fp-elim");
  3366. if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
  3367. options::OPT_fno_zero_initialized_in_bss))
  3368. CmdArgs.push_back("-mno-zero-initialized-in-bss");
  3369. bool OFastEnabled = isOptimizationLevelFast(Args);
  3370. // If -Ofast is the optimization level, then -fstrict-aliasing should be
  3371. // enabled. This alias option is being used to simplify the hasFlag logic.
  3372. OptSpecifier StrictAliasingAliasOption =
  3373. OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
  3374. // We turn strict aliasing off by default if we're in CL mode, since MSVC
  3375. // doesn't do any TBAA.
  3376. bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
  3377. if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
  3378. options::OPT_fno_strict_aliasing, TBAAOnByDefault))
  3379. CmdArgs.push_back("-relaxed-aliasing");
  3380. if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
  3381. options::OPT_fno_struct_path_tbaa))
  3382. CmdArgs.push_back("-no-struct-path-tbaa");
  3383. if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
  3384. false))
  3385. CmdArgs.push_back("-fstrict-enums");
  3386. if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
  3387. options::OPT_fno_strict_vtable_pointers,
  3388. false))
  3389. CmdArgs.push_back("-fstrict-vtable-pointers");
  3390. if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
  3391. options::OPT_fno_optimize_sibling_calls))
  3392. CmdArgs.push_back("-mdisable-tail-calls");
  3393. // Handle segmented stacks.
  3394. if (Args.hasArg(options::OPT_fsplit_stack))
  3395. CmdArgs.push_back("-split-stacks");
  3396. // If -Ofast is the optimization level, then -ffast-math should be enabled.
  3397. // This alias option is being used to simplify the getLastArg logic.
  3398. OptSpecifier FastMathAliasOption =
  3399. OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
  3400. // Handle various floating point optimization flags, mapping them to the
  3401. // appropriate LLVM code generation flags. The pattern for all of these is to
  3402. // default off the codegen optimizations, and if any flag enables them and no
  3403. // flag disables them after the flag enabling them, enable the codegen
  3404. // optimization. This is complicated by several "umbrella" flags.
  3405. if (Arg *A = Args.getLastArg(
  3406. options::OPT_ffast_math, FastMathAliasOption,
  3407. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3408. options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
  3409. options::OPT_fno_honor_infinities))
  3410. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3411. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3412. A->getOption().getID() != options::OPT_fhonor_infinities)
  3413. CmdArgs.push_back("-menable-no-infs");
  3414. if (Arg *A = Args.getLastArg(
  3415. options::OPT_ffast_math, FastMathAliasOption,
  3416. options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
  3417. options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
  3418. options::OPT_fno_honor_nans))
  3419. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3420. A->getOption().getID() != options::OPT_fno_finite_math_only &&
  3421. A->getOption().getID() != options::OPT_fhonor_nans)
  3422. CmdArgs.push_back("-menable-no-nans");
  3423. // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
  3424. bool MathErrno = getToolChain().IsMathErrnoDefault();
  3425. if (Arg *A =
  3426. Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3427. options::OPT_fno_fast_math, options::OPT_fmath_errno,
  3428. options::OPT_fno_math_errno)) {
  3429. // Turning on -ffast_math (with either flag) removes the need for MathErrno.
  3430. // However, turning *off* -ffast_math merely restores the toolchain default
  3431. // (which may be false).
  3432. if (A->getOption().getID() == options::OPT_fno_math_errno ||
  3433. A->getOption().getID() == options::OPT_ffast_math ||
  3434. A->getOption().getID() == options::OPT_Ofast)
  3435. MathErrno = false;
  3436. else if (A->getOption().getID() == options::OPT_fmath_errno)
  3437. MathErrno = true;
  3438. }
  3439. if (MathErrno)
  3440. CmdArgs.push_back("-fmath-errno");
  3441. // There are several flags which require disabling very specific
  3442. // optimizations. Any of these being disabled forces us to turn off the
  3443. // entire set of LLVM optimizations, so collect them through all the flag
  3444. // madness.
  3445. bool AssociativeMath = false;
  3446. if (Arg *A = Args.getLastArg(
  3447. options::OPT_ffast_math, FastMathAliasOption,
  3448. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3449. options::OPT_fno_unsafe_math_optimizations,
  3450. options::OPT_fassociative_math, options::OPT_fno_associative_math))
  3451. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3452. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3453. A->getOption().getID() != options::OPT_fno_associative_math)
  3454. AssociativeMath = true;
  3455. bool ReciprocalMath = false;
  3456. if (Arg *A = Args.getLastArg(
  3457. options::OPT_ffast_math, FastMathAliasOption,
  3458. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3459. options::OPT_fno_unsafe_math_optimizations,
  3460. options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
  3461. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3462. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3463. A->getOption().getID() != options::OPT_fno_reciprocal_math)
  3464. ReciprocalMath = true;
  3465. bool SignedZeros = true;
  3466. if (Arg *A = Args.getLastArg(
  3467. options::OPT_ffast_math, FastMathAliasOption,
  3468. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3469. options::OPT_fno_unsafe_math_optimizations,
  3470. options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
  3471. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3472. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3473. A->getOption().getID() != options::OPT_fsigned_zeros)
  3474. SignedZeros = false;
  3475. bool TrappingMath = true;
  3476. if (Arg *A = Args.getLastArg(
  3477. options::OPT_ffast_math, FastMathAliasOption,
  3478. options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
  3479. options::OPT_fno_unsafe_math_optimizations,
  3480. options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
  3481. if (A->getOption().getID() != options::OPT_fno_fast_math &&
  3482. A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
  3483. A->getOption().getID() != options::OPT_ftrapping_math)
  3484. TrappingMath = false;
  3485. if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
  3486. !TrappingMath)
  3487. CmdArgs.push_back("-menable-unsafe-fp-math");
  3488. if (!SignedZeros)
  3489. CmdArgs.push_back("-fno-signed-zeros");
  3490. if (ReciprocalMath)
  3491. CmdArgs.push_back("-freciprocal-math");
  3492. // Validate and pass through -fp-contract option.
  3493. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3494. options::OPT_fno_fast_math,
  3495. options::OPT_ffp_contract)) {
  3496. if (A->getOption().getID() == options::OPT_ffp_contract) {
  3497. StringRef Val = A->getValue();
  3498. if (Val == "fast" || Val == "on" || Val == "off") {
  3499. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
  3500. } else {
  3501. D.Diag(diag::err_drv_unsupported_option_argument)
  3502. << A->getOption().getName() << Val;
  3503. }
  3504. } else if (A->getOption().matches(options::OPT_ffast_math) ||
  3505. (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
  3506. // If fast-math is set then set the fp-contract mode to fast.
  3507. CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
  3508. }
  3509. }
  3510. ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
  3511. // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
  3512. // and if we find them, tell the frontend to provide the appropriate
  3513. // preprocessor macros. This is distinct from enabling any optimizations as
  3514. // these options induce language changes which must survive serialization
  3515. // and deserialization, etc.
  3516. if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
  3517. options::OPT_fno_fast_math))
  3518. if (!A->getOption().matches(options::OPT_fno_fast_math))
  3519. CmdArgs.push_back("-ffast-math");
  3520. if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
  3521. options::OPT_fno_fast_math))
  3522. if (A->getOption().matches(options::OPT_ffinite_math_only))
  3523. CmdArgs.push_back("-ffinite-math-only");
  3524. // Decide whether to use verbose asm. Verbose assembly is the default on
  3525. // toolchains which have the integrated assembler on by default.
  3526. bool IsIntegratedAssemblerDefault =
  3527. getToolChain().IsIntegratedAssemblerDefault();
  3528. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  3529. IsIntegratedAssemblerDefault) ||
  3530. Args.hasArg(options::OPT_dA))
  3531. CmdArgs.push_back("-masm-verbose");
  3532. if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
  3533. IsIntegratedAssemblerDefault))
  3534. CmdArgs.push_back("-no-integrated-as");
  3535. if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
  3536. CmdArgs.push_back("-mdebug-pass");
  3537. CmdArgs.push_back("Structure");
  3538. }
  3539. if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
  3540. CmdArgs.push_back("-mdebug-pass");
  3541. CmdArgs.push_back("Arguments");
  3542. }
  3543. // Enable -mconstructor-aliases except on darwin, where we have to work around
  3544. // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
  3545. // aliases aren't supported.
  3546. if (!getToolChain().getTriple().isOSDarwin() &&
  3547. !getToolChain().getTriple().isNVPTX())
  3548. CmdArgs.push_back("-mconstructor-aliases");
  3549. // Darwin's kernel doesn't support guard variables; just die if we
  3550. // try to use them.
  3551. if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
  3552. CmdArgs.push_back("-fforbid-guard-variables");
  3553. if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
  3554. false)) {
  3555. CmdArgs.push_back("-mms-bitfields");
  3556. }
  3557. // This is a coarse approximation of what llvm-gcc actually does, both
  3558. // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
  3559. // complicated ways.
  3560. bool AsynchronousUnwindTables =
  3561. Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
  3562. options::OPT_fno_asynchronous_unwind_tables,
  3563. (getToolChain().IsUnwindTablesDefault() ||
  3564. getToolChain().getSanitizerArgs().needsUnwindTables()) &&
  3565. !KernelOrKext);
  3566. if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
  3567. AsynchronousUnwindTables))
  3568. CmdArgs.push_back("-munwind-tables");
  3569. getToolChain().addClangTargetOptions(Args, CmdArgs);
  3570. if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
  3571. CmdArgs.push_back("-mlimit-float-precision");
  3572. CmdArgs.push_back(A->getValue());
  3573. }
  3574. // FIXME: Handle -mtune=.
  3575. (void)Args.hasArg(options::OPT_mtune_EQ);
  3576. if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
  3577. CmdArgs.push_back("-mcode-model");
  3578. CmdArgs.push_back(A->getValue());
  3579. }
  3580. // Add the target cpu
  3581. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
  3582. if (!CPU.empty()) {
  3583. CmdArgs.push_back("-target-cpu");
  3584. CmdArgs.push_back(Args.MakeArgString(CPU));
  3585. }
  3586. if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
  3587. CmdArgs.push_back("-mfpmath");
  3588. CmdArgs.push_back(A->getValue());
  3589. }
  3590. // Add the target features
  3591. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
  3592. // Add target specific flags.
  3593. switch (getToolChain().getArch()) {
  3594. default:
  3595. break;
  3596. case llvm::Triple::arm:
  3597. case llvm::Triple::armeb:
  3598. case llvm::Triple::thumb:
  3599. case llvm::Triple::thumbeb:
  3600. // Use the effective triple, which takes into account the deployment target.
  3601. AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
  3602. break;
  3603. case llvm::Triple::aarch64:
  3604. case llvm::Triple::aarch64_be:
  3605. AddAArch64TargetArgs(Args, CmdArgs);
  3606. break;
  3607. case llvm::Triple::mips:
  3608. case llvm::Triple::mipsel:
  3609. case llvm::Triple::mips64:
  3610. case llvm::Triple::mips64el:
  3611. AddMIPSTargetArgs(Args, CmdArgs);
  3612. break;
  3613. case llvm::Triple::ppc:
  3614. case llvm::Triple::ppc64:
  3615. case llvm::Triple::ppc64le:
  3616. AddPPCTargetArgs(Args, CmdArgs);
  3617. break;
  3618. case llvm::Triple::sparc:
  3619. case llvm::Triple::sparcel:
  3620. case llvm::Triple::sparcv9:
  3621. AddSparcTargetArgs(Args, CmdArgs);
  3622. break;
  3623. case llvm::Triple::x86:
  3624. case llvm::Triple::x86_64:
  3625. AddX86TargetArgs(Args, CmdArgs);
  3626. break;
  3627. case llvm::Triple::hexagon:
  3628. AddHexagonTargetArgs(Args, CmdArgs);
  3629. break;
  3630. case llvm::Triple::wasm32:
  3631. case llvm::Triple::wasm64:
  3632. AddWebAssemblyTargetArgs(Args, CmdArgs);
  3633. break;
  3634. }
  3635. // The 'g' groups options involve a somewhat intricate sequence of decisions
  3636. // about what to pass from the driver to the frontend, but by the time they
  3637. // reach cc1 they've been factored into three well-defined orthogonal choices:
  3638. // * what level of debug info to generate
  3639. // * what dwarf version to write
  3640. // * what debugger tuning to use
  3641. // This avoids having to monkey around further in cc1 other than to disable
  3642. // codeview if not running in a Windows environment. Perhaps even that
  3643. // decision should be made in the driver as well though.
  3644. unsigned DwarfVersion = 0;
  3645. llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
  3646. // These two are potentially updated by AddClangCLArgs.
  3647. codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
  3648. bool EmitCodeView = false;
  3649. // Add clang-cl arguments.
  3650. if (getToolChain().getDriver().IsCLMode())
  3651. AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
  3652. // Pass the linker version in use.
  3653. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  3654. CmdArgs.push_back("-target-linker-version");
  3655. CmdArgs.push_back(A->getValue());
  3656. }
  3657. if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
  3658. CmdArgs.push_back("-momit-leaf-frame-pointer");
  3659. // Explicitly error on some things we know we don't support and can't just
  3660. // ignore.
  3661. types::ID InputType = Input.getType();
  3662. if (!Args.hasArg(options::OPT_fallow_unsupported)) {
  3663. Arg *Unsupported;
  3664. if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
  3665. getToolChain().getArch() == llvm::Triple::x86) {
  3666. if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
  3667. (Unsupported = Args.getLastArg(options::OPT_mkernel)))
  3668. D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
  3669. << Unsupported->getOption().getName();
  3670. }
  3671. }
  3672. Args.AddAllArgs(CmdArgs, options::OPT_v);
  3673. Args.AddLastArg(CmdArgs, options::OPT_H);
  3674. if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
  3675. CmdArgs.push_back("-header-include-file");
  3676. CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
  3677. : "-");
  3678. }
  3679. Args.AddLastArg(CmdArgs, options::OPT_P);
  3680. Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
  3681. if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
  3682. CmdArgs.push_back("-diagnostic-log-file");
  3683. CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
  3684. : "-");
  3685. }
  3686. Args.ClaimAllArgs(options::OPT_g_Group);
  3687. Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
  3688. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  3689. // If the last option explicitly specified a debug-info level, use it.
  3690. if (A->getOption().matches(options::OPT_gN_Group)) {
  3691. DebugInfoKind = DebugLevelToInfoKind(*A);
  3692. // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
  3693. // But -gsplit-dwarf is not a g_group option, hence we have to check the
  3694. // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
  3695. if (SplitDwarfArg && DebugInfoKind < codegenoptions::LimitedDebugInfo &&
  3696. A->getIndex() > SplitDwarfArg->getIndex())
  3697. SplitDwarfArg = nullptr;
  3698. } else
  3699. // For any other 'g' option, use Limited.
  3700. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3701. }
  3702. // If a debugger tuning argument appeared, remember it.
  3703. if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
  3704. options::OPT_ggdbN_Group)) {
  3705. if (A->getOption().matches(options::OPT_glldb))
  3706. DebuggerTuning = llvm::DebuggerKind::LLDB;
  3707. else if (A->getOption().matches(options::OPT_gsce))
  3708. DebuggerTuning = llvm::DebuggerKind::SCE;
  3709. else
  3710. DebuggerTuning = llvm::DebuggerKind::GDB;
  3711. }
  3712. // If a -gdwarf argument appeared, remember it.
  3713. if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
  3714. options::OPT_gdwarf_4, options::OPT_gdwarf_5))
  3715. DwarfVersion = DwarfVersionNum(A->getSpelling());
  3716. // Forward -gcodeview.
  3717. // 'EmitCodeView might have been set by CL-compatibility argument parsing.
  3718. if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
  3719. // DwarfVersion remains at 0 if no explicit choice was made.
  3720. CmdArgs.push_back("-gcodeview");
  3721. } else if (DwarfVersion == 0 &&
  3722. DebugInfoKind != codegenoptions::NoDebugInfo) {
  3723. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  3724. }
  3725. // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
  3726. Args.ClaimAllArgs(options::OPT_g_flags_Group);
  3727. // PS4 defaults to no column info
  3728. if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
  3729. /*Default=*/ !IsPS4CPU))
  3730. CmdArgs.push_back("-dwarf-column-info");
  3731. // FIXME: Move backend command line options to the module.
  3732. if (Args.hasArg(options::OPT_gmodules)) {
  3733. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3734. CmdArgs.push_back("-dwarf-ext-refs");
  3735. CmdArgs.push_back("-fmodule-format=obj");
  3736. }
  3737. // -gsplit-dwarf should turn on -g and enable the backend dwarf
  3738. // splitting and extraction.
  3739. // FIXME: Currently only works on Linux.
  3740. if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
  3741. DebugInfoKind = codegenoptions::LimitedDebugInfo;
  3742. CmdArgs.push_back("-backend-option");
  3743. CmdArgs.push_back("-split-dwarf=Enable");
  3744. }
  3745. // After we've dealt with all combinations of things that could
  3746. // make DebugInfoKind be other than None or DebugLineTablesOnly,
  3747. // figure out if we need to "upgrade" it to standalone debug info.
  3748. // We parse these two '-f' options whether or not they will be used,
  3749. // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
  3750. bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
  3751. options::OPT_fno_standalone_debug,
  3752. getToolChain().GetDefaultStandaloneDebug());
  3753. if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
  3754. DebugInfoKind = codegenoptions::FullDebugInfo;
  3755. RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
  3756. DebuggerTuning);
  3757. // -ggnu-pubnames turns on gnu style pubnames in the backend.
  3758. if (Args.hasArg(options::OPT_ggnu_pubnames)) {
  3759. CmdArgs.push_back("-backend-option");
  3760. CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
  3761. }
  3762. // -gdwarf-aranges turns on the emission of the aranges section in the
  3763. // backend.
  3764. // Always enabled on the PS4.
  3765. if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
  3766. CmdArgs.push_back("-backend-option");
  3767. CmdArgs.push_back("-generate-arange-section");
  3768. }
  3769. if (Args.hasFlag(options::OPT_fdebug_types_section,
  3770. options::OPT_fno_debug_types_section, false)) {
  3771. CmdArgs.push_back("-backend-option");
  3772. CmdArgs.push_back("-generate-type-units");
  3773. }
  3774. // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
  3775. // default.
  3776. bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
  3777. Triple.getArch() == llvm::Triple::wasm32 ||
  3778. Triple.getArch() == llvm::Triple::wasm64;
  3779. if (Args.hasFlag(options::OPT_ffunction_sections,
  3780. options::OPT_fno_function_sections, UseSeparateSections)) {
  3781. CmdArgs.push_back("-ffunction-sections");
  3782. }
  3783. if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
  3784. UseSeparateSections)) {
  3785. CmdArgs.push_back("-fdata-sections");
  3786. }
  3787. if (!Args.hasFlag(options::OPT_funique_section_names,
  3788. options::OPT_fno_unique_section_names, true))
  3789. CmdArgs.push_back("-fno-unique-section-names");
  3790. Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
  3791. addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
  3792. // Add runtime flag for PS4 when PGO or Coverage are enabled.
  3793. if (getToolChain().getTriple().isPS4CPU())
  3794. addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
  3795. // Pass options for controlling the default header search paths.
  3796. if (Args.hasArg(options::OPT_nostdinc)) {
  3797. CmdArgs.push_back("-nostdsysteminc");
  3798. CmdArgs.push_back("-nobuiltininc");
  3799. } else {
  3800. if (Args.hasArg(options::OPT_nostdlibinc))
  3801. CmdArgs.push_back("-nostdsysteminc");
  3802. Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
  3803. Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
  3804. }
  3805. // Pass the path to compiler resource files.
  3806. CmdArgs.push_back("-resource-dir");
  3807. CmdArgs.push_back(D.ResourceDir.c_str());
  3808. Args.AddLastArg(CmdArgs, options::OPT_working_directory);
  3809. bool ARCMTEnabled = false;
  3810. if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
  3811. if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
  3812. options::OPT_ccc_arcmt_modify,
  3813. options::OPT_ccc_arcmt_migrate)) {
  3814. ARCMTEnabled = true;
  3815. switch (A->getOption().getID()) {
  3816. default:
  3817. llvm_unreachable("missed a case");
  3818. case options::OPT_ccc_arcmt_check:
  3819. CmdArgs.push_back("-arcmt-check");
  3820. break;
  3821. case options::OPT_ccc_arcmt_modify:
  3822. CmdArgs.push_back("-arcmt-modify");
  3823. break;
  3824. case options::OPT_ccc_arcmt_migrate:
  3825. CmdArgs.push_back("-arcmt-migrate");
  3826. CmdArgs.push_back("-mt-migrate-directory");
  3827. CmdArgs.push_back(A->getValue());
  3828. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
  3829. Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
  3830. break;
  3831. }
  3832. }
  3833. } else {
  3834. Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
  3835. Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
  3836. Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
  3837. }
  3838. if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
  3839. if (ARCMTEnabled) {
  3840. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  3841. << "-ccc-arcmt-migrate";
  3842. }
  3843. CmdArgs.push_back("-mt-migrate-directory");
  3844. CmdArgs.push_back(A->getValue());
  3845. if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
  3846. options::OPT_objcmt_migrate_subscripting,
  3847. options::OPT_objcmt_migrate_property)) {
  3848. // None specified, means enable them all.
  3849. CmdArgs.push_back("-objcmt-migrate-literals");
  3850. CmdArgs.push_back("-objcmt-migrate-subscripting");
  3851. CmdArgs.push_back("-objcmt-migrate-property");
  3852. } else {
  3853. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3854. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3855. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3856. }
  3857. } else {
  3858. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
  3859. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
  3860. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
  3861. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
  3862. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
  3863. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
  3864. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
  3865. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
  3866. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
  3867. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
  3868. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
  3869. Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
  3870. Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
  3871. Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
  3872. Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
  3873. Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
  3874. }
  3875. // Add preprocessing options like -I, -D, etc. if we are using the
  3876. // preprocessor.
  3877. //
  3878. // FIXME: Support -fpreprocessed
  3879. if (types::getPreprocessedType(InputType) != types::TY_INVALID)
  3880. AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
  3881. AuxToolChain);
  3882. // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
  3883. // that "The compiler can only warn and ignore the option if not recognized".
  3884. // When building with ccache, it will pass -D options to clang even on
  3885. // preprocessed inputs and configure concludes that -fPIC is not supported.
  3886. Args.ClaimAllArgs(options::OPT_D);
  3887. // Manually translate -O4 to -O3; let clang reject others.
  3888. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  3889. if (A->getOption().matches(options::OPT_O4)) {
  3890. CmdArgs.push_back("-O3");
  3891. D.Diag(diag::warn_O4_is_O3);
  3892. } else {
  3893. A->render(Args, CmdArgs);
  3894. }
  3895. }
  3896. // Warn about ignored options to clang.
  3897. for (const Arg *A :
  3898. Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
  3899. D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
  3900. A->claim();
  3901. }
  3902. claimNoWarnArgs(Args);
  3903. Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
  3904. Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
  3905. if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
  3906. CmdArgs.push_back("-pedantic");
  3907. Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
  3908. Args.AddLastArg(CmdArgs, options::OPT_w);
  3909. // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
  3910. // (-ansi is equivalent to -std=c89 or -std=c++98).
  3911. //
  3912. // If a std is supplied, only add -trigraphs if it follows the
  3913. // option.
  3914. bool ImplyVCPPCXXVer = false;
  3915. if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
  3916. if (Std->getOption().matches(options::OPT_ansi))
  3917. if (types::isCXX(InputType))
  3918. CmdArgs.push_back("-std=c++98");
  3919. else
  3920. CmdArgs.push_back("-std=c89");
  3921. else
  3922. Std->render(Args, CmdArgs);
  3923. // If -f(no-)trigraphs appears after the language standard flag, honor it.
  3924. if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
  3925. options::OPT_ftrigraphs,
  3926. options::OPT_fno_trigraphs))
  3927. if (A != Std)
  3928. A->render(Args, CmdArgs);
  3929. } else {
  3930. // Honor -std-default.
  3931. //
  3932. // FIXME: Clang doesn't correctly handle -std= when the input language
  3933. // doesn't match. For the time being just ignore this for C++ inputs;
  3934. // eventually we want to do all the standard defaulting here instead of
  3935. // splitting it between the driver and clang -cc1.
  3936. if (!types::isCXX(InputType))
  3937. Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
  3938. /*Joined=*/true);
  3939. else if (IsWindowsMSVC)
  3940. ImplyVCPPCXXVer = true;
  3941. Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
  3942. options::OPT_fno_trigraphs);
  3943. }
  3944. // GCC's behavior for -Wwrite-strings is a bit strange:
  3945. // * In C, this "warning flag" changes the types of string literals from
  3946. // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
  3947. // for the discarded qualifier.
  3948. // * In C++, this is just a normal warning flag.
  3949. //
  3950. // Implementing this warning correctly in C is hard, so we follow GCC's
  3951. // behavior for now. FIXME: Directly diagnose uses of a string literal as
  3952. // a non-const char* in C, rather than using this crude hack.
  3953. if (!types::isCXX(InputType)) {
  3954. // FIXME: This should behave just like a warning flag, and thus should also
  3955. // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
  3956. Arg *WriteStrings =
  3957. Args.getLastArg(options::OPT_Wwrite_strings,
  3958. options::OPT_Wno_write_strings, options::OPT_w);
  3959. if (WriteStrings &&
  3960. WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
  3961. CmdArgs.push_back("-fconst-strings");
  3962. }
  3963. // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
  3964. // during C++ compilation, which it is by default. GCC keeps this define even
  3965. // in the presence of '-w', match this behavior bug-for-bug.
  3966. if (types::isCXX(InputType) &&
  3967. Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
  3968. true)) {
  3969. CmdArgs.push_back("-fdeprecated-macro");
  3970. }
  3971. // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
  3972. if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
  3973. if (Asm->getOption().matches(options::OPT_fasm))
  3974. CmdArgs.push_back("-fgnu-keywords");
  3975. else
  3976. CmdArgs.push_back("-fno-gnu-keywords");
  3977. }
  3978. if (ShouldDisableDwarfDirectory(Args, getToolChain()))
  3979. CmdArgs.push_back("-fno-dwarf-directory-asm");
  3980. if (ShouldDisableAutolink(Args, getToolChain()))
  3981. CmdArgs.push_back("-fno-autolink");
  3982. // Add in -fdebug-compilation-dir if necessary.
  3983. addDebugCompDirArg(Args, CmdArgs);
  3984. for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
  3985. StringRef Map = A->getValue();
  3986. if (Map.find('=') == StringRef::npos)
  3987. D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
  3988. else
  3989. CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
  3990. A->claim();
  3991. }
  3992. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
  3993. options::OPT_ftemplate_depth_EQ)) {
  3994. CmdArgs.push_back("-ftemplate-depth");
  3995. CmdArgs.push_back(A->getValue());
  3996. }
  3997. if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
  3998. CmdArgs.push_back("-foperator-arrow-depth");
  3999. CmdArgs.push_back(A->getValue());
  4000. }
  4001. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
  4002. CmdArgs.push_back("-fconstexpr-depth");
  4003. CmdArgs.push_back(A->getValue());
  4004. }
  4005. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
  4006. CmdArgs.push_back("-fconstexpr-steps");
  4007. CmdArgs.push_back(A->getValue());
  4008. }
  4009. if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
  4010. CmdArgs.push_back("-fbracket-depth");
  4011. CmdArgs.push_back(A->getValue());
  4012. }
  4013. if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
  4014. options::OPT_Wlarge_by_value_copy_def)) {
  4015. if (A->getNumValues()) {
  4016. StringRef bytes = A->getValue();
  4017. CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
  4018. } else
  4019. CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
  4020. }
  4021. if (Args.hasArg(options::OPT_relocatable_pch))
  4022. CmdArgs.push_back("-relocatable-pch");
  4023. if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
  4024. CmdArgs.push_back("-fconstant-string-class");
  4025. CmdArgs.push_back(A->getValue());
  4026. }
  4027. if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
  4028. CmdArgs.push_back("-ftabstop");
  4029. CmdArgs.push_back(A->getValue());
  4030. }
  4031. CmdArgs.push_back("-ferror-limit");
  4032. if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
  4033. CmdArgs.push_back(A->getValue());
  4034. else
  4035. CmdArgs.push_back("19");
  4036. if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
  4037. CmdArgs.push_back("-fmacro-backtrace-limit");
  4038. CmdArgs.push_back(A->getValue());
  4039. }
  4040. if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
  4041. CmdArgs.push_back("-ftemplate-backtrace-limit");
  4042. CmdArgs.push_back(A->getValue());
  4043. }
  4044. if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
  4045. CmdArgs.push_back("-fconstexpr-backtrace-limit");
  4046. CmdArgs.push_back(A->getValue());
  4047. }
  4048. if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
  4049. CmdArgs.push_back("-fspell-checking-limit");
  4050. CmdArgs.push_back(A->getValue());
  4051. }
  4052. // Pass -fmessage-length=.
  4053. CmdArgs.push_back("-fmessage-length");
  4054. if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
  4055. CmdArgs.push_back(A->getValue());
  4056. } else {
  4057. // If -fmessage-length=N was not specified, determine whether this is a
  4058. // terminal and, if so, implicitly define -fmessage-length appropriately.
  4059. unsigned N = llvm::sys::Process::StandardErrColumns();
  4060. CmdArgs.push_back(Args.MakeArgString(Twine(N)));
  4061. }
  4062. // -fvisibility= and -fvisibility-ms-compat are of a piece.
  4063. if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
  4064. options::OPT_fvisibility_ms_compat)) {
  4065. if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
  4066. CmdArgs.push_back("-fvisibility");
  4067. CmdArgs.push_back(A->getValue());
  4068. } else {
  4069. assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
  4070. CmdArgs.push_back("-fvisibility");
  4071. CmdArgs.push_back("hidden");
  4072. CmdArgs.push_back("-ftype-visibility");
  4073. CmdArgs.push_back("default");
  4074. }
  4075. }
  4076. Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
  4077. Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
  4078. // -fhosted is default.
  4079. if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
  4080. KernelOrKext)
  4081. CmdArgs.push_back("-ffreestanding");
  4082. // Forward -f (flag) options which we can pass directly.
  4083. Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
  4084. Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
  4085. Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
  4086. // Emulated TLS is enabled by default on Android, and can be enabled manually
  4087. // with -femulated-tls.
  4088. bool EmulatedTLSDefault = Triple.isAndroid() || Triple.isWindowsCygwinEnvironment();
  4089. if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
  4090. EmulatedTLSDefault))
  4091. CmdArgs.push_back("-femulated-tls");
  4092. // AltiVec-like language extensions aren't relevant for assembling.
  4093. if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
  4094. Args.AddLastArg(CmdArgs, options::OPT_faltivec);
  4095. Args.AddLastArg(CmdArgs, options::OPT_fzvector);
  4096. }
  4097. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
  4098. Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
  4099. // Forward flags for OpenMP
  4100. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  4101. options::OPT_fno_openmp, false))
  4102. switch (getOpenMPRuntime(getToolChain(), Args)) {
  4103. case OMPRT_OMP:
  4104. case OMPRT_IOMP5:
  4105. // Clang can generate useful OpenMP code for these two runtime libraries.
  4106. CmdArgs.push_back("-fopenmp");
  4107. // If no option regarding the use of TLS in OpenMP codegeneration is
  4108. // given, decide a default based on the target. Otherwise rely on the
  4109. // options and pass the right information to the frontend.
  4110. if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
  4111. options::OPT_fnoopenmp_use_tls, /*Default=*/true))
  4112. CmdArgs.push_back("-fnoopenmp-use-tls");
  4113. break;
  4114. default:
  4115. // By default, if Clang doesn't know how to generate useful OpenMP code
  4116. // for a specific runtime library, we just don't pass the '-fopenmp' flag
  4117. // down to the actual compilation.
  4118. // FIXME: It would be better to have a mode which *only* omits IR
  4119. // generation based on the OpenMP support so that we get consistent
  4120. // semantic analysis, etc.
  4121. break;
  4122. }
  4123. const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
  4124. Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
  4125. // Report an error for -faltivec on anything other than PowerPC.
  4126. if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
  4127. const llvm::Triple::ArchType Arch = getToolChain().getArch();
  4128. if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  4129. Arch == llvm::Triple::ppc64le))
  4130. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  4131. << "ppc/ppc64/ppc64le";
  4132. }
  4133. // -fzvector is incompatible with -faltivec.
  4134. if (Arg *A = Args.getLastArg(options::OPT_fzvector))
  4135. if (Args.hasArg(options::OPT_faltivec))
  4136. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  4137. << "-faltivec";
  4138. if (getToolChain().SupportsProfiling())
  4139. Args.AddLastArg(CmdArgs, options::OPT_pg);
  4140. // -flax-vector-conversions is default.
  4141. if (!Args.hasFlag(options::OPT_flax_vector_conversions,
  4142. options::OPT_fno_lax_vector_conversions))
  4143. CmdArgs.push_back("-fno-lax-vector-conversions");
  4144. if (Args.getLastArg(options::OPT_fapple_kext) ||
  4145. (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
  4146. CmdArgs.push_back("-fapple-kext");
  4147. Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
  4148. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
  4149. Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
  4150. Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
  4151. Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
  4152. if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
  4153. CmdArgs.push_back("-ftrapv-handler");
  4154. CmdArgs.push_back(A->getValue());
  4155. }
  4156. Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
  4157. // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
  4158. // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
  4159. if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
  4160. if (A->getOption().matches(options::OPT_fwrapv))
  4161. CmdArgs.push_back("-fwrapv");
  4162. } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
  4163. options::OPT_fno_strict_overflow)) {
  4164. if (A->getOption().matches(options::OPT_fno_strict_overflow))
  4165. CmdArgs.push_back("-fwrapv");
  4166. }
  4167. if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
  4168. options::OPT_fno_reroll_loops))
  4169. if (A->getOption().matches(options::OPT_freroll_loops))
  4170. CmdArgs.push_back("-freroll-loops");
  4171. Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
  4172. Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
  4173. options::OPT_fno_unroll_loops);
  4174. Args.AddLastArg(CmdArgs, options::OPT_pthread);
  4175. // -stack-protector=0 is default.
  4176. unsigned StackProtectorLevel = 0;
  4177. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  4178. Args.ClaimAllArgs(options::OPT_fno_stack_protector);
  4179. Args.ClaimAllArgs(options::OPT_fstack_protector_all);
  4180. Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
  4181. Args.ClaimAllArgs(options::OPT_fstack_protector);
  4182. } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
  4183. options::OPT_fstack_protector_all,
  4184. options::OPT_fstack_protector_strong,
  4185. options::OPT_fstack_protector)) {
  4186. if (A->getOption().matches(options::OPT_fstack_protector)) {
  4187. StackProtectorLevel = std::max<unsigned>(
  4188. LangOptions::SSPOn,
  4189. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
  4190. } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
  4191. StackProtectorLevel = LangOptions::SSPStrong;
  4192. else if (A->getOption().matches(options::OPT_fstack_protector_all))
  4193. StackProtectorLevel = LangOptions::SSPReq;
  4194. } else {
  4195. StackProtectorLevel =
  4196. getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
  4197. }
  4198. if (StackProtectorLevel) {
  4199. CmdArgs.push_back("-stack-protector");
  4200. CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
  4201. }
  4202. // --param ssp-buffer-size=
  4203. for (const Arg *A : Args.filtered(options::OPT__param)) {
  4204. StringRef Str(A->getValue());
  4205. if (Str.startswith("ssp-buffer-size=")) {
  4206. if (StackProtectorLevel) {
  4207. CmdArgs.push_back("-stack-protector-buffer-size");
  4208. // FIXME: Verify the argument is a valid integer.
  4209. CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
  4210. }
  4211. A->claim();
  4212. }
  4213. }
  4214. // Translate -mstackrealign
  4215. if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
  4216. false))
  4217. CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
  4218. if (Args.hasArg(options::OPT_mstack_alignment)) {
  4219. StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
  4220. CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
  4221. }
  4222. if (Args.hasArg(options::OPT_mstack_probe_size)) {
  4223. StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
  4224. if (!Size.empty())
  4225. CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
  4226. else
  4227. CmdArgs.push_back("-mstack-probe-size=0");
  4228. }
  4229. switch (getToolChain().getArch()) {
  4230. case llvm::Triple::aarch64:
  4231. case llvm::Triple::aarch64_be:
  4232. case llvm::Triple::arm:
  4233. case llvm::Triple::armeb:
  4234. case llvm::Triple::thumb:
  4235. case llvm::Triple::thumbeb:
  4236. CmdArgs.push_back("-fallow-half-arguments-and-returns");
  4237. break;
  4238. default:
  4239. break;
  4240. }
  4241. if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
  4242. options::OPT_mno_restrict_it)) {
  4243. if (A->getOption().matches(options::OPT_mrestrict_it)) {
  4244. CmdArgs.push_back("-backend-option");
  4245. CmdArgs.push_back("-arm-restrict-it");
  4246. } else {
  4247. CmdArgs.push_back("-backend-option");
  4248. CmdArgs.push_back("-arm-no-restrict-it");
  4249. }
  4250. } else if (Triple.isOSWindows() &&
  4251. (Triple.getArch() == llvm::Triple::arm ||
  4252. Triple.getArch() == llvm::Triple::thumb)) {
  4253. // Windows on ARM expects restricted IT blocks
  4254. CmdArgs.push_back("-backend-option");
  4255. CmdArgs.push_back("-arm-restrict-it");
  4256. }
  4257. // Forward -f options with positive and negative forms; we translate
  4258. // these by hand.
  4259. if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
  4260. StringRef fname = A->getValue();
  4261. if (!llvm::sys::fs::exists(fname))
  4262. D.Diag(diag::err_drv_no_such_file) << fname;
  4263. else
  4264. A->render(Args, CmdArgs);
  4265. }
  4266. // -fbuiltin is default unless -mkernel is used.
  4267. bool UseBuiltins =
  4268. Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
  4269. !Args.hasArg(options::OPT_mkernel));
  4270. if (!UseBuiltins)
  4271. CmdArgs.push_back("-fno-builtin");
  4272. // -ffreestanding implies -fno-builtin.
  4273. if (Args.hasArg(options::OPT_ffreestanding))
  4274. UseBuiltins = false;
  4275. // Process the -fno-builtin-* options.
  4276. for (const auto &Arg : Args) {
  4277. const Option &O = Arg->getOption();
  4278. if (!O.matches(options::OPT_fno_builtin_))
  4279. continue;
  4280. Arg->claim();
  4281. // If -fno-builtin is specified, then there's no need to pass the option to
  4282. // the frontend.
  4283. if (!UseBuiltins)
  4284. continue;
  4285. StringRef FuncName = Arg->getValue();
  4286. CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
  4287. }
  4288. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4289. options::OPT_fno_assume_sane_operator_new))
  4290. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4291. // -fblocks=0 is default.
  4292. if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
  4293. getToolChain().IsBlocksDefault()) ||
  4294. (Args.hasArg(options::OPT_fgnu_runtime) &&
  4295. Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
  4296. !Args.hasArg(options::OPT_fno_blocks))) {
  4297. CmdArgs.push_back("-fblocks");
  4298. if (!Args.hasArg(options::OPT_fgnu_runtime) &&
  4299. !getToolChain().hasBlocksRuntime())
  4300. CmdArgs.push_back("-fblocks-runtime-optional");
  4301. }
  4302. // -fmodules enables the use of precompiled modules (off by default).
  4303. // Users can pass -fno-cxx-modules to turn off modules support for
  4304. // C++/Objective-C++ programs.
  4305. bool HaveModules = false;
  4306. if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
  4307. bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
  4308. options::OPT_fno_cxx_modules, true);
  4309. if (AllowedInCXX || !types::isCXX(InputType)) {
  4310. CmdArgs.push_back("-fmodules");
  4311. HaveModules = true;
  4312. }
  4313. }
  4314. // -fmodule-maps enables implicit reading of module map files. By default,
  4315. // this is enabled if we are using precompiled modules.
  4316. if (Args.hasFlag(options::OPT_fimplicit_module_maps,
  4317. options::OPT_fno_implicit_module_maps, HaveModules)) {
  4318. CmdArgs.push_back("-fimplicit-module-maps");
  4319. }
  4320. // -fmodules-decluse checks that modules used are declared so (off by
  4321. // default).
  4322. if (Args.hasFlag(options::OPT_fmodules_decluse,
  4323. options::OPT_fno_modules_decluse, false)) {
  4324. CmdArgs.push_back("-fmodules-decluse");
  4325. }
  4326. // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
  4327. // all #included headers are part of modules.
  4328. if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
  4329. options::OPT_fno_modules_strict_decluse, false)) {
  4330. CmdArgs.push_back("-fmodules-strict-decluse");
  4331. }
  4332. // -fno-implicit-modules turns off implicitly compiling modules on demand.
  4333. if (!Args.hasFlag(options::OPT_fimplicit_modules,
  4334. options::OPT_fno_implicit_modules)) {
  4335. CmdArgs.push_back("-fno-implicit-modules");
  4336. }
  4337. // -fmodule-name specifies the module that is currently being built (or
  4338. // used for header checking by -fmodule-maps).
  4339. Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
  4340. // -fmodule-map-file can be used to specify files containing module
  4341. // definitions.
  4342. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
  4343. // -fmodule-file can be used to specify files containing precompiled modules.
  4344. if (HaveModules)
  4345. Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
  4346. else
  4347. Args.ClaimAllArgs(options::OPT_fmodule_file);
  4348. // -fmodule-cache-path specifies where our implicitly-built module files
  4349. // should be written.
  4350. SmallString<128> Path;
  4351. if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
  4352. Path = A->getValue();
  4353. if (HaveModules) {
  4354. if (C.isForDiagnostics()) {
  4355. // When generating crash reports, we want to emit the modules along with
  4356. // the reproduction sources, so we ignore any provided module path.
  4357. Path = Output.getFilename();
  4358. llvm::sys::path::replace_extension(Path, ".cache");
  4359. llvm::sys::path::append(Path, "modules");
  4360. } else if (Path.empty()) {
  4361. // No module path was provided: use the default.
  4362. llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
  4363. llvm::sys::path::append(Path, "org.llvm.clang.");
  4364. appendUserToPath(Path);
  4365. llvm::sys::path::append(Path, "ModuleCache");
  4366. }
  4367. const char Arg[] = "-fmodules-cache-path=";
  4368. Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
  4369. CmdArgs.push_back(Args.MakeArgString(Path));
  4370. }
  4371. // When building modules and generating crashdumps, we need to dump a module
  4372. // dependency VFS alongside the output.
  4373. if (HaveModules && C.isForDiagnostics()) {
  4374. SmallString<128> VFSDir(Output.getFilename());
  4375. llvm::sys::path::replace_extension(VFSDir, ".cache");
  4376. // Add the cache directory as a temp so the crash diagnostics pick it up.
  4377. C.addTempFile(Args.MakeArgString(VFSDir));
  4378. llvm::sys::path::append(VFSDir, "vfs");
  4379. CmdArgs.push_back("-module-dependency-dir");
  4380. CmdArgs.push_back(Args.MakeArgString(VFSDir));
  4381. }
  4382. if (HaveModules)
  4383. Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
  4384. // Pass through all -fmodules-ignore-macro arguments.
  4385. Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
  4386. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
  4387. Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
  4388. Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
  4389. if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
  4390. if (Args.hasArg(options::OPT_fbuild_session_timestamp))
  4391. D.Diag(diag::err_drv_argument_not_allowed_with)
  4392. << A->getAsString(Args) << "-fbuild-session-timestamp";
  4393. llvm::sys::fs::file_status Status;
  4394. if (llvm::sys::fs::status(A->getValue(), Status))
  4395. D.Diag(diag::err_drv_no_such_file) << A->getValue();
  4396. CmdArgs.push_back(Args.MakeArgString(
  4397. "-fbuild-session-timestamp=" +
  4398. Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
  4399. }
  4400. if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
  4401. if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
  4402. options::OPT_fbuild_session_file))
  4403. D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
  4404. Args.AddLastArg(CmdArgs,
  4405. options::OPT_fmodules_validate_once_per_build_session);
  4406. }
  4407. Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
  4408. // -faccess-control is default.
  4409. if (Args.hasFlag(options::OPT_fno_access_control,
  4410. options::OPT_faccess_control, false))
  4411. CmdArgs.push_back("-fno-access-control");
  4412. // -felide-constructors is the default.
  4413. if (Args.hasFlag(options::OPT_fno_elide_constructors,
  4414. options::OPT_felide_constructors, false))
  4415. CmdArgs.push_back("-fno-elide-constructors");
  4416. ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
  4417. if (KernelOrKext || (types::isCXX(InputType) &&
  4418. (RTTIMode == ToolChain::RM_DisabledExplicitly ||
  4419. RTTIMode == ToolChain::RM_DisabledImplicitly)))
  4420. CmdArgs.push_back("-fno-rtti");
  4421. // -fshort-enums=0 is default for all architectures except Hexagon.
  4422. if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
  4423. getToolChain().getArch() == llvm::Triple::hexagon))
  4424. CmdArgs.push_back("-fshort-enums");
  4425. // -fsigned-char is default.
  4426. if (Arg *A = Args.getLastArg(
  4427. options::OPT_fsigned_char, options::OPT_fno_signed_char,
  4428. options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
  4429. if (A->getOption().matches(options::OPT_funsigned_char) ||
  4430. A->getOption().matches(options::OPT_fno_signed_char)) {
  4431. CmdArgs.push_back("-fno-signed-char");
  4432. }
  4433. } else if (!isSignedCharDefault(getToolChain().getTriple())) {
  4434. CmdArgs.push_back("-fno-signed-char");
  4435. }
  4436. // -fuse-cxa-atexit is default.
  4437. if (!Args.hasFlag(
  4438. options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
  4439. !IsWindowsCygnus && !IsWindowsGNU &&
  4440. getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
  4441. getToolChain().getArch() != llvm::Triple::hexagon &&
  4442. getToolChain().getArch() != llvm::Triple::xcore &&
  4443. ((getToolChain().getTriple().getVendor() !=
  4444. llvm::Triple::MipsTechnologies) ||
  4445. getToolChain().getTriple().hasEnvironment())) ||
  4446. KernelOrKext)
  4447. CmdArgs.push_back("-fno-use-cxa-atexit");
  4448. // -fms-extensions=0 is default.
  4449. if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
  4450. IsWindowsMSVC))
  4451. CmdArgs.push_back("-fms-extensions");
  4452. // -fno-use-line-directives is default.
  4453. if (Args.hasFlag(options::OPT_fuse_line_directives,
  4454. options::OPT_fno_use_line_directives, false))
  4455. CmdArgs.push_back("-fuse-line-directives");
  4456. // -fms-compatibility=0 is default.
  4457. if (Args.hasFlag(options::OPT_fms_compatibility,
  4458. options::OPT_fno_ms_compatibility,
  4459. (IsWindowsMSVC &&
  4460. Args.hasFlag(options::OPT_fms_extensions,
  4461. options::OPT_fno_ms_extensions, true))))
  4462. CmdArgs.push_back("-fms-compatibility");
  4463. // -fms-compatibility-version=18.00 is default.
  4464. VersionTuple MSVT = visualstudio::getMSVCVersion(
  4465. &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
  4466. if (!MSVT.empty())
  4467. CmdArgs.push_back(
  4468. Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
  4469. bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
  4470. if (ImplyVCPPCXXVer) {
  4471. if (IsMSVC2015Compatible)
  4472. CmdArgs.push_back("-std=c++14");
  4473. else
  4474. CmdArgs.push_back("-std=c++11");
  4475. }
  4476. // -fno-borland-extensions is default.
  4477. if (Args.hasFlag(options::OPT_fborland_extensions,
  4478. options::OPT_fno_borland_extensions, false))
  4479. CmdArgs.push_back("-fborland-extensions");
  4480. // -fno-declspec is default, except for PS4.
  4481. if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
  4482. getToolChain().getTriple().isPS4()))
  4483. CmdArgs.push_back("-fdeclspec");
  4484. else if (Args.hasArg(options::OPT_fno_declspec))
  4485. CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
  4486. // -fthreadsafe-static is default, except for MSVC compatibility versions less
  4487. // than 19.
  4488. if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
  4489. options::OPT_fno_threadsafe_statics,
  4490. !IsWindowsMSVC || IsMSVC2015Compatible))
  4491. CmdArgs.push_back("-fno-threadsafe-statics");
  4492. // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
  4493. // needs it.
  4494. if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
  4495. options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
  4496. CmdArgs.push_back("-fdelayed-template-parsing");
  4497. // -fgnu-keywords default varies depending on language; only pass if
  4498. // specified.
  4499. if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
  4500. options::OPT_fno_gnu_keywords))
  4501. A->render(Args, CmdArgs);
  4502. if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
  4503. false))
  4504. CmdArgs.push_back("-fgnu89-inline");
  4505. if (Args.hasArg(options::OPT_fno_inline))
  4506. CmdArgs.push_back("-fno-inline");
  4507. if (Args.hasArg(options::OPT_fno_inline_functions))
  4508. CmdArgs.push_back("-fno-inline-functions");
  4509. ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
  4510. // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
  4511. // legacy is the default. Except for deployment taget of 10.5,
  4512. // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
  4513. // gets ignored silently.
  4514. if (objcRuntime.isNonFragile()) {
  4515. if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
  4516. options::OPT_fno_objc_legacy_dispatch,
  4517. objcRuntime.isLegacyDispatchDefaultForArch(
  4518. getToolChain().getArch()))) {
  4519. if (getToolChain().UseObjCMixedDispatch())
  4520. CmdArgs.push_back("-fobjc-dispatch-method=mixed");
  4521. else
  4522. CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
  4523. }
  4524. }
  4525. // When ObjectiveC legacy runtime is in effect on MacOSX,
  4526. // turn on the option to do Array/Dictionary subscripting
  4527. // by default.
  4528. if (getToolChain().getArch() == llvm::Triple::x86 &&
  4529. getToolChain().getTriple().isMacOSX() &&
  4530. !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
  4531. objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
  4532. objcRuntime.isNeXTFamily())
  4533. CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
  4534. // -fencode-extended-block-signature=1 is default.
  4535. if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
  4536. CmdArgs.push_back("-fencode-extended-block-signature");
  4537. }
  4538. // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
  4539. // NOTE: This logic is duplicated in ToolChains.cpp.
  4540. bool ARC = isObjCAutoRefCount(Args);
  4541. if (ARC) {
  4542. getToolChain().CheckObjCARC();
  4543. CmdArgs.push_back("-fobjc-arc");
  4544. // FIXME: It seems like this entire block, and several around it should be
  4545. // wrapped in isObjC, but for now we just use it here as this is where it
  4546. // was being used previously.
  4547. if (types::isCXX(InputType) && types::isObjC(InputType)) {
  4548. if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
  4549. CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
  4550. else
  4551. CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
  4552. }
  4553. // Allow the user to enable full exceptions code emission.
  4554. // We define off for Objective-CC, on for Objective-C++.
  4555. if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
  4556. options::OPT_fno_objc_arc_exceptions,
  4557. /*default*/ types::isCXX(InputType)))
  4558. CmdArgs.push_back("-fobjc-arc-exceptions");
  4559. }
  4560. // -fobjc-infer-related-result-type is the default, except in the Objective-C
  4561. // rewriter.
  4562. if (rewriteKind != RK_None)
  4563. CmdArgs.push_back("-fno-objc-infer-related-result-type");
  4564. // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
  4565. // takes precedence.
  4566. const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
  4567. if (!GCArg)
  4568. GCArg = Args.getLastArg(options::OPT_fobjc_gc);
  4569. if (GCArg) {
  4570. if (ARC) {
  4571. D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
  4572. } else if (getToolChain().SupportsObjCGC()) {
  4573. GCArg->render(Args, CmdArgs);
  4574. } else {
  4575. // FIXME: We should move this to a hard error.
  4576. D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
  4577. }
  4578. }
  4579. // Pass down -fobjc-weak or -fno-objc-weak if present.
  4580. if (types::isObjC(InputType)) {
  4581. auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
  4582. options::OPT_fno_objc_weak);
  4583. if (!WeakArg) {
  4584. // nothing to do
  4585. } else if (GCArg) {
  4586. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4587. D.Diag(diag::err_objc_weak_with_gc);
  4588. } else if (!objcRuntime.allowsWeak()) {
  4589. if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
  4590. D.Diag(diag::err_objc_weak_unsupported);
  4591. } else {
  4592. WeakArg->render(Args, CmdArgs);
  4593. }
  4594. }
  4595. if (Args.hasFlag(options::OPT_fapplication_extension,
  4596. options::OPT_fno_application_extension, false))
  4597. CmdArgs.push_back("-fapplication-extension");
  4598. // Handle GCC-style exception args.
  4599. if (!C.getDriver().IsCLMode())
  4600. addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
  4601. CmdArgs);
  4602. if (getToolChain().UseSjLjExceptions(Args))
  4603. CmdArgs.push_back("-fsjlj-exceptions");
  4604. // C++ "sane" operator new.
  4605. if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
  4606. options::OPT_fno_assume_sane_operator_new))
  4607. CmdArgs.push_back("-fno-assume-sane-operator-new");
  4608. // -fsized-deallocation is off by default, as it is an ABI-breaking change for
  4609. // most platforms.
  4610. if (Args.hasFlag(options::OPT_fsized_deallocation,
  4611. options::OPT_fno_sized_deallocation, false))
  4612. CmdArgs.push_back("-fsized-deallocation");
  4613. // -fconstant-cfstrings is default, and may be subject to argument translation
  4614. // on Darwin.
  4615. if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
  4616. options::OPT_fno_constant_cfstrings) ||
  4617. !Args.hasFlag(options::OPT_mconstant_cfstrings,
  4618. options::OPT_mno_constant_cfstrings))
  4619. CmdArgs.push_back("-fno-constant-cfstrings");
  4620. // -fshort-wchar default varies depending on platform; only
  4621. // pass if specified.
  4622. if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
  4623. options::OPT_fno_short_wchar))
  4624. A->render(Args, CmdArgs);
  4625. // -fno-pascal-strings is default, only pass non-default.
  4626. if (Args.hasFlag(options::OPT_fpascal_strings,
  4627. options::OPT_fno_pascal_strings, false))
  4628. CmdArgs.push_back("-fpascal-strings");
  4629. // Honor -fpack-struct= and -fpack-struct, if given. Note that
  4630. // -fno-pack-struct doesn't apply to -fpack-struct=.
  4631. if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
  4632. std::string PackStructStr = "-fpack-struct=";
  4633. PackStructStr += A->getValue();
  4634. CmdArgs.push_back(Args.MakeArgString(PackStructStr));
  4635. } else if (Args.hasFlag(options::OPT_fpack_struct,
  4636. options::OPT_fno_pack_struct, false)) {
  4637. CmdArgs.push_back("-fpack-struct=1");
  4638. }
  4639. // Handle -fmax-type-align=N and -fno-type-align
  4640. bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
  4641. if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
  4642. if (!SkipMaxTypeAlign) {
  4643. std::string MaxTypeAlignStr = "-fmax-type-align=";
  4644. MaxTypeAlignStr += A->getValue();
  4645. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4646. }
  4647. } else if (getToolChain().getTriple().isOSDarwin()) {
  4648. if (!SkipMaxTypeAlign) {
  4649. std::string MaxTypeAlignStr = "-fmax-type-align=16";
  4650. CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
  4651. }
  4652. }
  4653. // -fcommon is the default unless compiling kernel code or the target says so
  4654. bool NoCommonDefault =
  4655. KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
  4656. if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
  4657. !NoCommonDefault))
  4658. CmdArgs.push_back("-fno-common");
  4659. // -fsigned-bitfields is default, and clang doesn't yet support
  4660. // -funsigned-bitfields.
  4661. if (!Args.hasFlag(options::OPT_fsigned_bitfields,
  4662. options::OPT_funsigned_bitfields))
  4663. D.Diag(diag::warn_drv_clang_unsupported)
  4664. << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
  4665. // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
  4666. if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
  4667. D.Diag(diag::err_drv_clang_unsupported)
  4668. << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
  4669. // -finput_charset=UTF-8 is default. Reject others
  4670. if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
  4671. StringRef value = inputCharset->getValue();
  4672. if (value != "UTF-8")
  4673. D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
  4674. << value;
  4675. }
  4676. // -fexec_charset=UTF-8 is default. Reject others
  4677. if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
  4678. StringRef value = execCharset->getValue();
  4679. if (value != "UTF-8")
  4680. D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
  4681. << value;
  4682. }
  4683. // -fcaret-diagnostics is default.
  4684. if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
  4685. options::OPT_fno_caret_diagnostics, true))
  4686. CmdArgs.push_back("-fno-caret-diagnostics");
  4687. // -fdiagnostics-fixit-info is default, only pass non-default.
  4688. if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
  4689. options::OPT_fno_diagnostics_fixit_info))
  4690. CmdArgs.push_back("-fno-diagnostics-fixit-info");
  4691. // Enable -fdiagnostics-show-option by default.
  4692. if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
  4693. options::OPT_fno_diagnostics_show_option))
  4694. CmdArgs.push_back("-fdiagnostics-show-option");
  4695. if (const Arg *A =
  4696. Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
  4697. CmdArgs.push_back("-fdiagnostics-show-category");
  4698. CmdArgs.push_back(A->getValue());
  4699. }
  4700. if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
  4701. CmdArgs.push_back("-fdiagnostics-format");
  4702. CmdArgs.push_back(A->getValue());
  4703. }
  4704. if (Arg *A = Args.getLastArg(
  4705. options::OPT_fdiagnostics_show_note_include_stack,
  4706. options::OPT_fno_diagnostics_show_note_include_stack)) {
  4707. if (A->getOption().matches(
  4708. options::OPT_fdiagnostics_show_note_include_stack))
  4709. CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
  4710. else
  4711. CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
  4712. }
  4713. // Color diagnostics are the default, unless the terminal doesn't support
  4714. // them.
  4715. // Support both clang's -f[no-]color-diagnostics and gcc's
  4716. // -f[no-]diagnostics-colors[=never|always|auto].
  4717. enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
  4718. for (const auto &Arg : Args) {
  4719. const Option &O = Arg->getOption();
  4720. if (!O.matches(options::OPT_fcolor_diagnostics) &&
  4721. !O.matches(options::OPT_fdiagnostics_color) &&
  4722. !O.matches(options::OPT_fno_color_diagnostics) &&
  4723. !O.matches(options::OPT_fno_diagnostics_color) &&
  4724. !O.matches(options::OPT_fdiagnostics_color_EQ))
  4725. continue;
  4726. Arg->claim();
  4727. if (O.matches(options::OPT_fcolor_diagnostics) ||
  4728. O.matches(options::OPT_fdiagnostics_color)) {
  4729. ShowColors = Colors_On;
  4730. } else if (O.matches(options::OPT_fno_color_diagnostics) ||
  4731. O.matches(options::OPT_fno_diagnostics_color)) {
  4732. ShowColors = Colors_Off;
  4733. } else {
  4734. assert(O.matches(options::OPT_fdiagnostics_color_EQ));
  4735. StringRef value(Arg->getValue());
  4736. if (value == "always")
  4737. ShowColors = Colors_On;
  4738. else if (value == "never")
  4739. ShowColors = Colors_Off;
  4740. else if (value == "auto")
  4741. ShowColors = Colors_Auto;
  4742. else
  4743. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  4744. << ("-fdiagnostics-color=" + value).str();
  4745. }
  4746. }
  4747. if (ShowColors == Colors_On ||
  4748. (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
  4749. CmdArgs.push_back("-fcolor-diagnostics");
  4750. if (Args.hasArg(options::OPT_fansi_escape_codes))
  4751. CmdArgs.push_back("-fansi-escape-codes");
  4752. if (!Args.hasFlag(options::OPT_fshow_source_location,
  4753. options::OPT_fno_show_source_location))
  4754. CmdArgs.push_back("-fno-show-source-location");
  4755. if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
  4756. true))
  4757. CmdArgs.push_back("-fno-show-column");
  4758. if (!Args.hasFlag(options::OPT_fspell_checking,
  4759. options::OPT_fno_spell_checking))
  4760. CmdArgs.push_back("-fno-spell-checking");
  4761. // -fno-asm-blocks is default.
  4762. if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
  4763. false))
  4764. CmdArgs.push_back("-fasm-blocks");
  4765. // -fgnu-inline-asm is default.
  4766. if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
  4767. options::OPT_fno_gnu_inline_asm, true))
  4768. CmdArgs.push_back("-fno-gnu-inline-asm");
  4769. // Enable vectorization per default according to the optimization level
  4770. // selected. For optimization levels that want vectorization we use the alias
  4771. // option to simplify the hasFlag logic.
  4772. bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
  4773. OptSpecifier VectorizeAliasOption =
  4774. EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
  4775. if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
  4776. options::OPT_fno_vectorize, EnableVec))
  4777. CmdArgs.push_back("-vectorize-loops");
  4778. // -fslp-vectorize is enabled based on the optimization level selected.
  4779. bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
  4780. OptSpecifier SLPVectAliasOption =
  4781. EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
  4782. if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
  4783. options::OPT_fno_slp_vectorize, EnableSLPVec))
  4784. CmdArgs.push_back("-vectorize-slp");
  4785. // -fno-slp-vectorize-aggressive is default.
  4786. if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
  4787. options::OPT_fno_slp_vectorize_aggressive, false))
  4788. CmdArgs.push_back("-vectorize-slp-aggressive");
  4789. if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
  4790. A->render(Args, CmdArgs);
  4791. // -fdollars-in-identifiers default varies depending on platform and
  4792. // language; only pass if specified.
  4793. if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
  4794. options::OPT_fno_dollars_in_identifiers)) {
  4795. if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
  4796. CmdArgs.push_back("-fdollars-in-identifiers");
  4797. else
  4798. CmdArgs.push_back("-fno-dollars-in-identifiers");
  4799. }
  4800. // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
  4801. // practical purposes.
  4802. if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
  4803. options::OPT_fno_unit_at_a_time)) {
  4804. if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
  4805. D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
  4806. }
  4807. if (Args.hasFlag(options::OPT_fapple_pragma_pack,
  4808. options::OPT_fno_apple_pragma_pack, false))
  4809. CmdArgs.push_back("-fapple-pragma-pack");
  4810. // le32-specific flags:
  4811. // -fno-math-builtin: clang should not convert math builtins to intrinsics
  4812. // by default.
  4813. if (getToolChain().getArch() == llvm::Triple::le32) {
  4814. CmdArgs.push_back("-fno-math-builtin");
  4815. }
  4816. // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
  4817. //
  4818. // FIXME: Now that PR4941 has been fixed this can be enabled.
  4819. #if 0
  4820. if (getToolChain().getTriple().isOSDarwin() &&
  4821. (getToolChain().getArch() == llvm::Triple::arm ||
  4822. getToolChain().getArch() == llvm::Triple::thumb)) {
  4823. if (!Args.hasArg(options::OPT_fbuiltin_strcat))
  4824. CmdArgs.push_back("-fno-builtin-strcat");
  4825. if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
  4826. CmdArgs.push_back("-fno-builtin-strcpy");
  4827. }
  4828. #endif
  4829. // Enable rewrite includes if the user's asked for it or if we're generating
  4830. // diagnostics.
  4831. // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
  4832. // nice to enable this when doing a crashdump for modules as well.
  4833. if (Args.hasFlag(options::OPT_frewrite_includes,
  4834. options::OPT_fno_rewrite_includes, false) ||
  4835. (C.isForDiagnostics() && !HaveModules))
  4836. CmdArgs.push_back("-frewrite-includes");
  4837. // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
  4838. if (Arg *A = Args.getLastArg(options::OPT_traditional,
  4839. options::OPT_traditional_cpp)) {
  4840. if (isa<PreprocessJobAction>(JA))
  4841. CmdArgs.push_back("-traditional-cpp");
  4842. else
  4843. D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
  4844. }
  4845. Args.AddLastArg(CmdArgs, options::OPT_dM);
  4846. Args.AddLastArg(CmdArgs, options::OPT_dD);
  4847. // Handle serialized diagnostics.
  4848. if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
  4849. CmdArgs.push_back("-serialize-diagnostic-file");
  4850. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  4851. }
  4852. if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
  4853. CmdArgs.push_back("-fretain-comments-from-system-headers");
  4854. // Forward -fcomment-block-commands to -cc1.
  4855. Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
  4856. // Forward -fparse-all-comments to -cc1.
  4857. Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
  4858. // Turn -fplugin=name.so into -load name.so
  4859. for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
  4860. CmdArgs.push_back("-load");
  4861. CmdArgs.push_back(A->getValue());
  4862. A->claim();
  4863. }
  4864. // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
  4865. // parser.
  4866. Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
  4867. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  4868. A->claim();
  4869. // We translate this by hand to the -cc1 argument, since nightly test uses
  4870. // it and developers have been trained to spell it with -mllvm.
  4871. if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
  4872. CmdArgs.push_back("-disable-llvm-optzns");
  4873. } else
  4874. A->render(Args, CmdArgs);
  4875. }
  4876. // With -save-temps, we want to save the unoptimized bitcode output from the
  4877. // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
  4878. // by the frontend.
  4879. if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
  4880. CmdArgs.push_back("-disable-llvm-passes");
  4881. if (Output.getType() == types::TY_Dependencies) {
  4882. // Handled with other dependency code.
  4883. } else if (Output.isFilename()) {
  4884. CmdArgs.push_back("-o");
  4885. CmdArgs.push_back(Output.getFilename());
  4886. } else {
  4887. assert(Output.isNothing() && "Invalid output.");
  4888. }
  4889. addDashXForInput(Args, Input, CmdArgs);
  4890. if (Input.isFilename())
  4891. CmdArgs.push_back(Input.getFilename());
  4892. else
  4893. Input.getInputArg().renderAsInput(Args, CmdArgs);
  4894. Args.AddAllArgs(CmdArgs, options::OPT_undef);
  4895. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  4896. // Optionally embed the -cc1 level arguments into the debug info, for build
  4897. // analysis.
  4898. if (getToolChain().UseDwarfDebugFlags()) {
  4899. ArgStringList OriginalArgs;
  4900. for (const auto &Arg : Args)
  4901. Arg->render(Args, OriginalArgs);
  4902. SmallString<256> Flags;
  4903. Flags += Exec;
  4904. for (const char *OriginalArg : OriginalArgs) {
  4905. SmallString<128> EscapedArg;
  4906. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  4907. Flags += " ";
  4908. Flags += EscapedArg;
  4909. }
  4910. CmdArgs.push_back("-dwarf-debug-flags");
  4911. CmdArgs.push_back(Args.MakeArgString(Flags));
  4912. }
  4913. // Add the split debug info name to the command lines here so we
  4914. // can propagate it to the backend.
  4915. bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
  4916. (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
  4917. isa<BackendJobAction>(JA));
  4918. const char *SplitDwarfOut;
  4919. if (SplitDwarf) {
  4920. CmdArgs.push_back("-split-dwarf-file");
  4921. SplitDwarfOut = SplitDebugName(Args, Input);
  4922. CmdArgs.push_back(SplitDwarfOut);
  4923. }
  4924. // Host-side cuda compilation receives device-side outputs as Inputs[1...].
  4925. // Include them with -fcuda-include-gpubinary.
  4926. if (IsCuda && Inputs.size() > 1)
  4927. for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
  4928. CmdArgs.push_back("-fcuda-include-gpubinary");
  4929. CmdArgs.push_back(I->getFilename());
  4930. }
  4931. // Finally add the compile command to the compilation.
  4932. if (Args.hasArg(options::OPT__SLASH_fallback) &&
  4933. Output.getType() == types::TY_Object &&
  4934. (InputType == types::TY_C || InputType == types::TY_CXX)) {
  4935. auto CLCommand =
  4936. getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
  4937. C.addCommand(llvm::make_unique<FallbackCommand>(
  4938. JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
  4939. } else {
  4940. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  4941. }
  4942. // Handle the debug info splitting at object creation time if we're
  4943. // creating an object.
  4944. // TODO: Currently only works on linux with newer objcopy.
  4945. if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  4946. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
  4947. if (Arg *A = Args.getLastArg(options::OPT_pg))
  4948. if (Args.hasArg(options::OPT_fomit_frame_pointer))
  4949. D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
  4950. << A->getAsString(Args);
  4951. // Claim some arguments which clang supports automatically.
  4952. // -fpch-preprocess is used with gcc to add a special marker in the output to
  4953. // include the PCH file. Clang's PTH solution is completely transparent, so we
  4954. // do not need to deal with it at all.
  4955. Args.ClaimAllArgs(options::OPT_fpch_preprocess);
  4956. // Claim some arguments which clang doesn't support, but we don't
  4957. // care to warn the user about.
  4958. Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
  4959. Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
  4960. // Disable warnings for clang -E -emit-llvm foo.c
  4961. Args.ClaimAllArgs(options::OPT_emit_llvm);
  4962. }
  4963. /// Add options related to the Objective-C runtime/ABI.
  4964. ///
  4965. /// Returns true if the runtime is non-fragile.
  4966. ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
  4967. ArgStringList &cmdArgs,
  4968. RewriteKind rewriteKind) const {
  4969. // Look for the controlling runtime option.
  4970. Arg *runtimeArg =
  4971. args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
  4972. options::OPT_fobjc_runtime_EQ);
  4973. // Just forward -fobjc-runtime= to the frontend. This supercedes
  4974. // options about fragility.
  4975. if (runtimeArg &&
  4976. runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
  4977. ObjCRuntime runtime;
  4978. StringRef value = runtimeArg->getValue();
  4979. if (runtime.tryParse(value)) {
  4980. getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
  4981. << value;
  4982. }
  4983. runtimeArg->render(args, cmdArgs);
  4984. return runtime;
  4985. }
  4986. // Otherwise, we'll need the ABI "version". Version numbers are
  4987. // slightly confusing for historical reasons:
  4988. // 1 - Traditional "fragile" ABI
  4989. // 2 - Non-fragile ABI, version 1
  4990. // 3 - Non-fragile ABI, version 2
  4991. unsigned objcABIVersion = 1;
  4992. // If -fobjc-abi-version= is present, use that to set the version.
  4993. if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
  4994. StringRef value = abiArg->getValue();
  4995. if (value == "1")
  4996. objcABIVersion = 1;
  4997. else if (value == "2")
  4998. objcABIVersion = 2;
  4999. else if (value == "3")
  5000. objcABIVersion = 3;
  5001. else
  5002. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
  5003. } else {
  5004. // Otherwise, determine if we are using the non-fragile ABI.
  5005. bool nonFragileABIIsDefault =
  5006. (rewriteKind == RK_NonFragile ||
  5007. (rewriteKind == RK_None &&
  5008. getToolChain().IsObjCNonFragileABIDefault()));
  5009. if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
  5010. options::OPT_fno_objc_nonfragile_abi,
  5011. nonFragileABIIsDefault)) {
  5012. // Determine the non-fragile ABI version to use.
  5013. #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
  5014. unsigned nonFragileABIVersion = 1;
  5015. #else
  5016. unsigned nonFragileABIVersion = 2;
  5017. #endif
  5018. if (Arg *abiArg =
  5019. args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
  5020. StringRef value = abiArg->getValue();
  5021. if (value == "1")
  5022. nonFragileABIVersion = 1;
  5023. else if (value == "2")
  5024. nonFragileABIVersion = 2;
  5025. else
  5026. getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
  5027. << value;
  5028. }
  5029. objcABIVersion = 1 + nonFragileABIVersion;
  5030. } else {
  5031. objcABIVersion = 1;
  5032. }
  5033. }
  5034. // We don't actually care about the ABI version other than whether
  5035. // it's non-fragile.
  5036. bool isNonFragile = objcABIVersion != 1;
  5037. // If we have no runtime argument, ask the toolchain for its default runtime.
  5038. // However, the rewriter only really supports the Mac runtime, so assume that.
  5039. ObjCRuntime runtime;
  5040. if (!runtimeArg) {
  5041. switch (rewriteKind) {
  5042. case RK_None:
  5043. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5044. break;
  5045. case RK_Fragile:
  5046. runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
  5047. break;
  5048. case RK_NonFragile:
  5049. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5050. break;
  5051. }
  5052. // -fnext-runtime
  5053. } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
  5054. // On Darwin, make this use the default behavior for the toolchain.
  5055. if (getToolChain().getTriple().isOSDarwin()) {
  5056. runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
  5057. // Otherwise, build for a generic macosx port.
  5058. } else {
  5059. runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
  5060. }
  5061. // -fgnu-runtime
  5062. } else {
  5063. assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
  5064. // Legacy behaviour is to target the gnustep runtime if we are in
  5065. // non-fragile mode or the GCC runtime in fragile mode.
  5066. if (isNonFragile)
  5067. runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
  5068. else
  5069. runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
  5070. }
  5071. cmdArgs.push_back(
  5072. args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
  5073. return runtime;
  5074. }
  5075. static bool maybeConsumeDash(const std::string &EH, size_t &I) {
  5076. bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
  5077. I += HaveDash;
  5078. return !HaveDash;
  5079. }
  5080. namespace {
  5081. struct EHFlags {
  5082. EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
  5083. bool Synch;
  5084. bool Asynch;
  5085. bool NoExceptC;
  5086. };
  5087. } // end anonymous namespace
  5088. /// /EH controls whether to run destructor cleanups when exceptions are
  5089. /// thrown. There are three modifiers:
  5090. /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
  5091. /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
  5092. /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
  5093. /// - c: Assume that extern "C" functions are implicitly noexcept. This
  5094. /// modifier is an optimization, so we ignore it for now.
  5095. /// The default is /EHs-c-, meaning cleanups are disabled.
  5096. static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
  5097. EHFlags EH;
  5098. std::vector<std::string> EHArgs =
  5099. Args.getAllArgValues(options::OPT__SLASH_EH);
  5100. for (auto EHVal : EHArgs) {
  5101. for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
  5102. switch (EHVal[I]) {
  5103. case 'a':
  5104. EH.Asynch = maybeConsumeDash(EHVal, I);
  5105. continue;
  5106. case 'c':
  5107. EH.NoExceptC = maybeConsumeDash(EHVal, I);
  5108. continue;
  5109. case 's':
  5110. EH.Synch = maybeConsumeDash(EHVal, I);
  5111. continue;
  5112. default:
  5113. break;
  5114. }
  5115. D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
  5116. break;
  5117. }
  5118. }
  5119. return EH;
  5120. }
  5121. void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
  5122. codegenoptions::DebugInfoKind *DebugInfoKind,
  5123. bool *EmitCodeView) const {
  5124. unsigned RTOptionID = options::OPT__SLASH_MT;
  5125. if (Args.hasArg(options::OPT__SLASH_LDd))
  5126. // The /LDd option implies /MTd. The dependent lib part can be overridden,
  5127. // but defining _DEBUG is sticky.
  5128. RTOptionID = options::OPT__SLASH_MTd;
  5129. if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
  5130. RTOptionID = A->getOption().getID();
  5131. StringRef FlagForCRT;
  5132. switch (RTOptionID) {
  5133. case options::OPT__SLASH_MD:
  5134. if (Args.hasArg(options::OPT__SLASH_LDd))
  5135. CmdArgs.push_back("-D_DEBUG");
  5136. CmdArgs.push_back("-D_MT");
  5137. CmdArgs.push_back("-D_DLL");
  5138. FlagForCRT = "--dependent-lib=msvcrt";
  5139. break;
  5140. case options::OPT__SLASH_MDd:
  5141. CmdArgs.push_back("-D_DEBUG");
  5142. CmdArgs.push_back("-D_MT");
  5143. CmdArgs.push_back("-D_DLL");
  5144. FlagForCRT = "--dependent-lib=msvcrtd";
  5145. break;
  5146. case options::OPT__SLASH_MT:
  5147. if (Args.hasArg(options::OPT__SLASH_LDd))
  5148. CmdArgs.push_back("-D_DEBUG");
  5149. CmdArgs.push_back("-D_MT");
  5150. FlagForCRT = "--dependent-lib=libcmt";
  5151. break;
  5152. case options::OPT__SLASH_MTd:
  5153. CmdArgs.push_back("-D_DEBUG");
  5154. CmdArgs.push_back("-D_MT");
  5155. FlagForCRT = "--dependent-lib=libcmtd";
  5156. break;
  5157. default:
  5158. llvm_unreachable("Unexpected option ID.");
  5159. }
  5160. if (Args.hasArg(options::OPT__SLASH_Zl)) {
  5161. CmdArgs.push_back("-D_VC_NODEFAULTLIB");
  5162. } else {
  5163. CmdArgs.push_back(FlagForCRT.data());
  5164. // This provides POSIX compatibility (maps 'open' to '_open'), which most
  5165. // users want. The /Za flag to cl.exe turns this off, but it's not
  5166. // implemented in clang.
  5167. CmdArgs.push_back("--dependent-lib=oldnames");
  5168. }
  5169. // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
  5170. // would produce interleaved output, so ignore /showIncludes in such cases.
  5171. if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
  5172. if (Arg *A = Args.getLastArg(options::OPT_show_includes))
  5173. A->render(Args, CmdArgs);
  5174. // This controls whether or not we emit RTTI data for polymorphic types.
  5175. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  5176. /*default=*/false))
  5177. CmdArgs.push_back("-fno-rtti-data");
  5178. // Emit CodeView if -Z7 is present.
  5179. *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
  5180. bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
  5181. // If we are emitting CV but not DWARF, don't build information that LLVM
  5182. // can't yet process.
  5183. if (*EmitCodeView && !EmitDwarf)
  5184. *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
  5185. if (*EmitCodeView)
  5186. CmdArgs.push_back("-gcodeview");
  5187. const Driver &D = getToolChain().getDriver();
  5188. EHFlags EH = parseClangCLEHFlags(D, Args);
  5189. // FIXME: Do something with NoExceptC.
  5190. if (EH.Synch || EH.Asynch) {
  5191. CmdArgs.push_back("-fcxx-exceptions");
  5192. CmdArgs.push_back("-fexceptions");
  5193. }
  5194. // /EP should expand to -E -P.
  5195. if (Args.hasArg(options::OPT__SLASH_EP)) {
  5196. CmdArgs.push_back("-E");
  5197. CmdArgs.push_back("-P");
  5198. }
  5199. unsigned VolatileOptionID;
  5200. if (getToolChain().getArch() == llvm::Triple::x86_64 ||
  5201. getToolChain().getArch() == llvm::Triple::x86)
  5202. VolatileOptionID = options::OPT__SLASH_volatile_ms;
  5203. else
  5204. VolatileOptionID = options::OPT__SLASH_volatile_iso;
  5205. if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
  5206. VolatileOptionID = A->getOption().getID();
  5207. if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
  5208. CmdArgs.push_back("-fms-volatile");
  5209. Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
  5210. Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
  5211. if (MostGeneralArg && BestCaseArg)
  5212. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5213. << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
  5214. if (MostGeneralArg) {
  5215. Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
  5216. Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
  5217. Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
  5218. Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
  5219. Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
  5220. if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
  5221. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  5222. << FirstConflict->getAsString(Args)
  5223. << SecondConflict->getAsString(Args);
  5224. if (SingleArg)
  5225. CmdArgs.push_back("-fms-memptr-rep=single");
  5226. else if (MultipleArg)
  5227. CmdArgs.push_back("-fms-memptr-rep=multiple");
  5228. else
  5229. CmdArgs.push_back("-fms-memptr-rep=virtual");
  5230. }
  5231. if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
  5232. A->render(Args, CmdArgs);
  5233. if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
  5234. CmdArgs.push_back("-fdiagnostics-format");
  5235. if (Args.hasArg(options::OPT__SLASH_fallback))
  5236. CmdArgs.push_back("msvc-fallback");
  5237. else
  5238. CmdArgs.push_back("msvc");
  5239. }
  5240. }
  5241. visualstudio::Compiler *Clang::getCLFallback() const {
  5242. if (!CLFallback)
  5243. CLFallback.reset(new visualstudio::Compiler(getToolChain()));
  5244. return CLFallback.get();
  5245. }
  5246. void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
  5247. ArgStringList &CmdArgs) const {
  5248. StringRef CPUName;
  5249. StringRef ABIName;
  5250. const llvm::Triple &Triple = getToolChain().getTriple();
  5251. mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
  5252. CmdArgs.push_back("-target-abi");
  5253. CmdArgs.push_back(ABIName.data());
  5254. }
  5255. void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
  5256. const InputInfo &Output, const InputInfoList &Inputs,
  5257. const ArgList &Args,
  5258. const char *LinkingOutput) const {
  5259. ArgStringList CmdArgs;
  5260. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  5261. const InputInfo &Input = Inputs[0];
  5262. std::string TripleStr =
  5263. getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
  5264. const llvm::Triple Triple(TripleStr);
  5265. // Don't warn about "clang -w -c foo.s"
  5266. Args.ClaimAllArgs(options::OPT_w);
  5267. // and "clang -emit-llvm -c foo.s"
  5268. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5269. claimNoWarnArgs(Args);
  5270. // Invoke ourselves in -cc1as mode.
  5271. //
  5272. // FIXME: Implement custom jobs for internal actions.
  5273. CmdArgs.push_back("-cc1as");
  5274. // Add the "effective" target triple.
  5275. CmdArgs.push_back("-triple");
  5276. CmdArgs.push_back(Args.MakeArgString(TripleStr));
  5277. // Set the output mode, we currently only expect to be used as a real
  5278. // assembler.
  5279. CmdArgs.push_back("-filetype");
  5280. CmdArgs.push_back("obj");
  5281. // Set the main file name, so that debug info works even with
  5282. // -save-temps or preprocessed assembly.
  5283. CmdArgs.push_back("-main-file-name");
  5284. CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
  5285. // Add the target cpu
  5286. std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
  5287. if (!CPU.empty()) {
  5288. CmdArgs.push_back("-target-cpu");
  5289. CmdArgs.push_back(Args.MakeArgString(CPU));
  5290. }
  5291. // Add the target features
  5292. getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
  5293. // Ignore explicit -force_cpusubtype_ALL option.
  5294. (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
  5295. // Pass along any -I options so we get proper .include search paths.
  5296. Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
  5297. // Determine the original source input.
  5298. const Action *SourceAction = &JA;
  5299. while (SourceAction->getKind() != Action::InputClass) {
  5300. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  5301. SourceAction = SourceAction->getInputs()[0];
  5302. }
  5303. // Forward -g and handle debug info related flags, assuming we are dealing
  5304. // with an actual assembly file.
  5305. if (SourceAction->getType() == types::TY_Asm ||
  5306. SourceAction->getType() == types::TY_PP_Asm) {
  5307. bool WantDebug = false;
  5308. unsigned DwarfVersion = 0;
  5309. Args.ClaimAllArgs(options::OPT_g_Group);
  5310. if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
  5311. WantDebug = !A->getOption().matches(options::OPT_g0) &&
  5312. !A->getOption().matches(options::OPT_ggdb0);
  5313. if (WantDebug)
  5314. DwarfVersion = DwarfVersionNum(A->getSpelling());
  5315. }
  5316. if (DwarfVersion == 0)
  5317. DwarfVersion = getToolChain().GetDefaultDwarfVersion();
  5318. RenderDebugEnablingArgs(Args, CmdArgs,
  5319. (WantDebug ? codegenoptions::LimitedDebugInfo
  5320. : codegenoptions::NoDebugInfo),
  5321. DwarfVersion, llvm::DebuggerKind::Default);
  5322. // Add the -fdebug-compilation-dir flag if needed.
  5323. addDebugCompDirArg(Args, CmdArgs);
  5324. // Set the AT_producer to the clang version when using the integrated
  5325. // assembler on assembly source files.
  5326. CmdArgs.push_back("-dwarf-debug-producer");
  5327. CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
  5328. // And pass along -I options
  5329. Args.AddAllArgs(CmdArgs, options::OPT_I);
  5330. }
  5331. // Handle -fPIC et al -- the relocation-model affects the assembler
  5332. // for some targets.
  5333. llvm::Reloc::Model RelocationModel;
  5334. unsigned PICLevel;
  5335. bool IsPIE;
  5336. std::tie(RelocationModel, PICLevel, IsPIE) =
  5337. ParsePICArgs(getToolChain(), Triple, Args);
  5338. const char *RMName = RelocationModelName(RelocationModel);
  5339. if (RMName) {
  5340. CmdArgs.push_back("-mrelocation-model");
  5341. CmdArgs.push_back(RMName);
  5342. }
  5343. // Optionally embed the -cc1as level arguments into the debug info, for build
  5344. // analysis.
  5345. if (getToolChain().UseDwarfDebugFlags()) {
  5346. ArgStringList OriginalArgs;
  5347. for (const auto &Arg : Args)
  5348. Arg->render(Args, OriginalArgs);
  5349. SmallString<256> Flags;
  5350. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5351. Flags += Exec;
  5352. for (const char *OriginalArg : OriginalArgs) {
  5353. SmallString<128> EscapedArg;
  5354. EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
  5355. Flags += " ";
  5356. Flags += EscapedArg;
  5357. }
  5358. CmdArgs.push_back("-dwarf-debug-flags");
  5359. CmdArgs.push_back(Args.MakeArgString(Flags));
  5360. }
  5361. // FIXME: Add -static support, once we have it.
  5362. // Add target specific flags.
  5363. switch (getToolChain().getArch()) {
  5364. default:
  5365. break;
  5366. case llvm::Triple::mips:
  5367. case llvm::Triple::mipsel:
  5368. case llvm::Triple::mips64:
  5369. case llvm::Triple::mips64el:
  5370. AddMIPSTargetArgs(Args, CmdArgs);
  5371. break;
  5372. }
  5373. // Consume all the warning flags. Usually this would be handled more
  5374. // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
  5375. // doesn't handle that so rather than warning about unused flags that are
  5376. // actually used, we'll lie by omission instead.
  5377. // FIXME: Stop lying and consume only the appropriate driver flags
  5378. Args.ClaimAllArgs(options::OPT_W_Group);
  5379. CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
  5380. getToolChain().getDriver());
  5381. Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
  5382. assert(Output.isFilename() && "Unexpected lipo output.");
  5383. CmdArgs.push_back("-o");
  5384. CmdArgs.push_back(Output.getFilename());
  5385. assert(Input.isFilename() && "Invalid input.");
  5386. CmdArgs.push_back(Input.getFilename());
  5387. const char *Exec = getToolChain().getDriver().getClangProgramPath();
  5388. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5389. // Handle the debug info splitting at object creation time if we're
  5390. // creating an object.
  5391. // TODO: Currently only works on linux with newer objcopy.
  5392. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  5393. getToolChain().getTriple().isOSLinux())
  5394. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  5395. SplitDebugName(Args, Input));
  5396. }
  5397. void GnuTool::anchor() {}
  5398. void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
  5399. const InputInfo &Output,
  5400. const InputInfoList &Inputs, const ArgList &Args,
  5401. const char *LinkingOutput) const {
  5402. const Driver &D = getToolChain().getDriver();
  5403. ArgStringList CmdArgs;
  5404. for (const auto &A : Args) {
  5405. if (forwardToGCC(A->getOption())) {
  5406. // It is unfortunate that we have to claim here, as this means
  5407. // we will basically never report anything interesting for
  5408. // platforms using a generic gcc, even if we are just using gcc
  5409. // to get to the assembler.
  5410. A->claim();
  5411. // Don't forward any -g arguments to assembly steps.
  5412. if (isa<AssembleJobAction>(JA) &&
  5413. A->getOption().matches(options::OPT_g_Group))
  5414. continue;
  5415. // Don't forward any -W arguments to assembly and link steps.
  5416. if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
  5417. A->getOption().matches(options::OPT_W_Group))
  5418. continue;
  5419. A->render(Args, CmdArgs);
  5420. }
  5421. }
  5422. RenderExtraToolArgs(JA, CmdArgs);
  5423. // If using a driver driver, force the arch.
  5424. if (getToolChain().getTriple().isOSDarwin()) {
  5425. CmdArgs.push_back("-arch");
  5426. CmdArgs.push_back(
  5427. Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
  5428. }
  5429. // Try to force gcc to match the tool chain we want, if we recognize
  5430. // the arch.
  5431. //
  5432. // FIXME: The triple class should directly provide the information we want
  5433. // here.
  5434. switch (getToolChain().getArch()) {
  5435. default:
  5436. break;
  5437. case llvm::Triple::x86:
  5438. case llvm::Triple::ppc:
  5439. CmdArgs.push_back("-m32");
  5440. break;
  5441. case llvm::Triple::x86_64:
  5442. case llvm::Triple::ppc64:
  5443. case llvm::Triple::ppc64le:
  5444. CmdArgs.push_back("-m64");
  5445. break;
  5446. case llvm::Triple::sparcel:
  5447. CmdArgs.push_back("-EL");
  5448. break;
  5449. }
  5450. if (Output.isFilename()) {
  5451. CmdArgs.push_back("-o");
  5452. CmdArgs.push_back(Output.getFilename());
  5453. } else {
  5454. assert(Output.isNothing() && "Unexpected output");
  5455. CmdArgs.push_back("-fsyntax-only");
  5456. }
  5457. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5458. // Only pass -x if gcc will understand it; otherwise hope gcc
  5459. // understands the suffix correctly. The main use case this would go
  5460. // wrong in is for linker inputs if they happened to have an odd
  5461. // suffix; really the only way to get this to happen is a command
  5462. // like '-x foobar a.c' which will treat a.c like a linker input.
  5463. //
  5464. // FIXME: For the linker case specifically, can we safely convert
  5465. // inputs into '-Wl,' options?
  5466. for (const auto &II : Inputs) {
  5467. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5468. if (types::isLLVMIR(II.getType()))
  5469. D.Diag(diag::err_drv_no_linker_llvm_support)
  5470. << getToolChain().getTripleString();
  5471. else if (II.getType() == types::TY_AST)
  5472. D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
  5473. else if (II.getType() == types::TY_ModuleFile)
  5474. D.Diag(diag::err_drv_no_module_support)
  5475. << getToolChain().getTripleString();
  5476. if (types::canTypeBeUserSpecified(II.getType())) {
  5477. CmdArgs.push_back("-x");
  5478. CmdArgs.push_back(types::getTypeName(II.getType()));
  5479. }
  5480. if (II.isFilename())
  5481. CmdArgs.push_back(II.getFilename());
  5482. else {
  5483. const Arg &A = II.getInputArg();
  5484. // Reverse translate some rewritten options.
  5485. if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
  5486. CmdArgs.push_back("-lstdc++");
  5487. continue;
  5488. }
  5489. // Don't render as input, we need gcc to do the translations.
  5490. A.render(Args, CmdArgs);
  5491. }
  5492. }
  5493. const std::string customGCCName = D.getCCCGenericGCCName();
  5494. const char *GCCName;
  5495. if (!customGCCName.empty())
  5496. GCCName = customGCCName.c_str();
  5497. else if (D.CCCIsCXX()) {
  5498. GCCName = "g++";
  5499. } else
  5500. GCCName = "gcc";
  5501. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
  5502. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5503. }
  5504. void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
  5505. ArgStringList &CmdArgs) const {
  5506. CmdArgs.push_back("-E");
  5507. }
  5508. void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
  5509. ArgStringList &CmdArgs) const {
  5510. const Driver &D = getToolChain().getDriver();
  5511. switch (JA.getType()) {
  5512. // If -flto, etc. are present then make sure not to force assembly output.
  5513. case types::TY_LLVM_IR:
  5514. case types::TY_LTO_IR:
  5515. case types::TY_LLVM_BC:
  5516. case types::TY_LTO_BC:
  5517. CmdArgs.push_back("-c");
  5518. break;
  5519. // We assume we've got an "integrated" assembler in that gcc will produce an
  5520. // object file itself.
  5521. case types::TY_Object:
  5522. CmdArgs.push_back("-c");
  5523. break;
  5524. case types::TY_PP_Asm:
  5525. CmdArgs.push_back("-S");
  5526. break;
  5527. case types::TY_Nothing:
  5528. CmdArgs.push_back("-fsyntax-only");
  5529. break;
  5530. default:
  5531. D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
  5532. }
  5533. }
  5534. void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
  5535. ArgStringList &CmdArgs) const {
  5536. // The types are (hopefully) good enough.
  5537. }
  5538. // Hexagon tools start.
  5539. void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
  5540. ArgStringList &CmdArgs) const {
  5541. }
  5542. void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  5543. const InputInfo &Output,
  5544. const InputInfoList &Inputs,
  5545. const ArgList &Args,
  5546. const char *LinkingOutput) const {
  5547. claimNoWarnArgs(Args);
  5548. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5549. const Driver &D = HTC.getDriver();
  5550. ArgStringList CmdArgs;
  5551. std::string MArchString = "-march=hexagon";
  5552. CmdArgs.push_back(Args.MakeArgString(MArchString));
  5553. RenderExtraToolArgs(JA, CmdArgs);
  5554. std::string AsName = "hexagon-llvm-mc";
  5555. std::string MCpuString = "-mcpu=hexagon" +
  5556. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5557. CmdArgs.push_back("-filetype=obj");
  5558. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5559. if (Output.isFilename()) {
  5560. CmdArgs.push_back("-o");
  5561. CmdArgs.push_back(Output.getFilename());
  5562. } else {
  5563. assert(Output.isNothing() && "Unexpected output");
  5564. CmdArgs.push_back("-fsyntax-only");
  5565. }
  5566. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5567. std::string N = llvm::utostr(G.getValue());
  5568. CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
  5569. }
  5570. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  5571. // Only pass -x if gcc will understand it; otherwise hope gcc
  5572. // understands the suffix correctly. The main use case this would go
  5573. // wrong in is for linker inputs if they happened to have an odd
  5574. // suffix; really the only way to get this to happen is a command
  5575. // like '-x foobar a.c' which will treat a.c like a linker input.
  5576. //
  5577. // FIXME: For the linker case specifically, can we safely convert
  5578. // inputs into '-Wl,' options?
  5579. for (const auto &II : Inputs) {
  5580. // Don't try to pass LLVM or AST inputs to a generic gcc.
  5581. if (types::isLLVMIR(II.getType()))
  5582. D.Diag(clang::diag::err_drv_no_linker_llvm_support)
  5583. << HTC.getTripleString();
  5584. else if (II.getType() == types::TY_AST)
  5585. D.Diag(clang::diag::err_drv_no_ast_support)
  5586. << HTC.getTripleString();
  5587. else if (II.getType() == types::TY_ModuleFile)
  5588. D.Diag(diag::err_drv_no_module_support)
  5589. << HTC.getTripleString();
  5590. if (II.isFilename())
  5591. CmdArgs.push_back(II.getFilename());
  5592. else
  5593. // Don't render as input, we need gcc to do the translations.
  5594. // FIXME: What is this?
  5595. II.getInputArg().render(Args, CmdArgs);
  5596. }
  5597. auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
  5598. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  5599. }
  5600. void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
  5601. ArgStringList &CmdArgs) const {
  5602. }
  5603. static void
  5604. constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
  5605. const toolchains::HexagonToolChain &HTC,
  5606. const InputInfo &Output, const InputInfoList &Inputs,
  5607. const ArgList &Args, ArgStringList &CmdArgs,
  5608. const char *LinkingOutput) {
  5609. const Driver &D = HTC.getDriver();
  5610. //----------------------------------------------------------------------------
  5611. //
  5612. //----------------------------------------------------------------------------
  5613. bool IsStatic = Args.hasArg(options::OPT_static);
  5614. bool IsShared = Args.hasArg(options::OPT_shared);
  5615. bool IsPIE = Args.hasArg(options::OPT_pie);
  5616. bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
  5617. bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
  5618. bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
  5619. bool UseG0 = false;
  5620. bool UseShared = IsShared && !IsStatic;
  5621. //----------------------------------------------------------------------------
  5622. // Silence warnings for various options
  5623. //----------------------------------------------------------------------------
  5624. Args.ClaimAllArgs(options::OPT_g_Group);
  5625. Args.ClaimAllArgs(options::OPT_emit_llvm);
  5626. Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
  5627. // handled somewhere else.
  5628. Args.ClaimAllArgs(options::OPT_static_libgcc);
  5629. //----------------------------------------------------------------------------
  5630. //
  5631. //----------------------------------------------------------------------------
  5632. if (Args.hasArg(options::OPT_s))
  5633. CmdArgs.push_back("-s");
  5634. if (Args.hasArg(options::OPT_r))
  5635. CmdArgs.push_back("-r");
  5636. for (const auto &Opt : HTC.ExtraOpts)
  5637. CmdArgs.push_back(Opt.c_str());
  5638. CmdArgs.push_back("-march=hexagon");
  5639. std::string CpuVer =
  5640. toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
  5641. std::string MCpuString = "-mcpu=hexagon" + CpuVer;
  5642. CmdArgs.push_back(Args.MakeArgString(MCpuString));
  5643. if (IsShared) {
  5644. CmdArgs.push_back("-shared");
  5645. // The following should be the default, but doing as hexagon-gcc does.
  5646. CmdArgs.push_back("-call_shared");
  5647. }
  5648. if (IsStatic)
  5649. CmdArgs.push_back("-static");
  5650. if (IsPIE && !IsShared)
  5651. CmdArgs.push_back("-pie");
  5652. if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
  5653. std::string N = llvm::utostr(G.getValue());
  5654. CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
  5655. UseG0 = G.getValue() == 0;
  5656. }
  5657. //----------------------------------------------------------------------------
  5658. //
  5659. //----------------------------------------------------------------------------
  5660. CmdArgs.push_back("-o");
  5661. CmdArgs.push_back(Output.getFilename());
  5662. //----------------------------------------------------------------------------
  5663. // moslib
  5664. //----------------------------------------------------------------------------
  5665. std::vector<std::string> OsLibs;
  5666. bool HasStandalone = false;
  5667. for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
  5668. A->claim();
  5669. OsLibs.emplace_back(A->getValue());
  5670. HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
  5671. }
  5672. if (OsLibs.empty()) {
  5673. OsLibs.push_back("standalone");
  5674. HasStandalone = true;
  5675. }
  5676. //----------------------------------------------------------------------------
  5677. // Start Files
  5678. //----------------------------------------------------------------------------
  5679. const std::string MCpuSuffix = "/" + CpuVer;
  5680. const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
  5681. const std::string RootDir =
  5682. HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
  5683. const std::string StartSubDir =
  5684. "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
  5685. auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
  5686. const char *Name) -> std::string {
  5687. std::string RelName = SubDir + Name;
  5688. std::string P = HTC.GetFilePath(RelName.c_str());
  5689. if (llvm::sys::fs::exists(P))
  5690. return P;
  5691. return RootDir + RelName;
  5692. };
  5693. if (IncStdLib && IncStartFiles) {
  5694. if (!IsShared) {
  5695. if (HasStandalone) {
  5696. std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
  5697. CmdArgs.push_back(Args.MakeArgString(Crt0SA));
  5698. }
  5699. std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
  5700. CmdArgs.push_back(Args.MakeArgString(Crt0));
  5701. }
  5702. std::string Init = UseShared
  5703. ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
  5704. : Find(RootDir, StartSubDir, "/init.o");
  5705. CmdArgs.push_back(Args.MakeArgString(Init));
  5706. }
  5707. //----------------------------------------------------------------------------
  5708. // Library Search Paths
  5709. //----------------------------------------------------------------------------
  5710. const ToolChain::path_list &LibPaths = HTC.getFilePaths();
  5711. for (const auto &LibPath : LibPaths)
  5712. CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
  5713. //----------------------------------------------------------------------------
  5714. //
  5715. //----------------------------------------------------------------------------
  5716. Args.AddAllArgs(CmdArgs,
  5717. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  5718. options::OPT_t, options::OPT_u_Group});
  5719. AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
  5720. //----------------------------------------------------------------------------
  5721. // Libraries
  5722. //----------------------------------------------------------------------------
  5723. if (IncStdLib && IncDefLibs) {
  5724. if (D.CCCIsCXX()) {
  5725. HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
  5726. CmdArgs.push_back("-lm");
  5727. }
  5728. CmdArgs.push_back("--start-group");
  5729. if (!IsShared) {
  5730. for (const std::string &Lib : OsLibs)
  5731. CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
  5732. CmdArgs.push_back("-lc");
  5733. }
  5734. CmdArgs.push_back("-lgcc");
  5735. CmdArgs.push_back("--end-group");
  5736. }
  5737. //----------------------------------------------------------------------------
  5738. // End files
  5739. //----------------------------------------------------------------------------
  5740. if (IncStdLib && IncStartFiles) {
  5741. std::string Fini = UseShared
  5742. ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
  5743. : Find(RootDir, StartSubDir, "/fini.o");
  5744. CmdArgs.push_back(Args.MakeArgString(Fini));
  5745. }
  5746. }
  5747. void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5748. const InputInfo &Output,
  5749. const InputInfoList &Inputs,
  5750. const ArgList &Args,
  5751. const char *LinkingOutput) const {
  5752. auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
  5753. ArgStringList CmdArgs;
  5754. constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
  5755. LinkingOutput);
  5756. std::string Linker = HTC.GetProgramPath("hexagon-link");
  5757. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5758. CmdArgs, Inputs));
  5759. }
  5760. // Hexagon tools end.
  5761. void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5762. const InputInfo &Output,
  5763. const InputInfoList &Inputs,
  5764. const ArgList &Args,
  5765. const char *LinkingOutput) const {
  5766. std::string Linker = getToolChain().GetProgramPath(getShortName());
  5767. ArgStringList CmdArgs;
  5768. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  5769. CmdArgs.push_back("-o");
  5770. CmdArgs.push_back(Output.getFilename());
  5771. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
  5772. CmdArgs, Inputs));
  5773. }
  5774. // AMDGPU tools end.
  5775. wasm::Linker::Linker(const ToolChain &TC)
  5776. : GnuTool("wasm::Linker", "lld", TC) {}
  5777. bool wasm::Linker::isLinkJob() const {
  5778. return true;
  5779. }
  5780. bool wasm::Linker::hasIntegratedCPP() const {
  5781. return false;
  5782. }
  5783. void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  5784. const InputInfo &Output,
  5785. const InputInfoList &Inputs,
  5786. const ArgList &Args,
  5787. const char *LinkingOutput) const {
  5788. const char *Linker = Args.MakeArgString(getToolChain().GetLinkerPath());
  5789. ArgStringList CmdArgs;
  5790. CmdArgs.push_back("-flavor");
  5791. CmdArgs.push_back("ld");
  5792. // Enable garbage collection of unused input sections by default, since code
  5793. // size is of particular importance. This is significantly facilitated by
  5794. // the enabling of -ffunction-sections and -fdata-sections in
  5795. // Clang::ConstructJob.
  5796. if (areOptimizationsEnabled(Args))
  5797. CmdArgs.push_back("--gc-sections");
  5798. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  5799. CmdArgs.push_back("-o");
  5800. CmdArgs.push_back(Output.getFilename());
  5801. C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
  5802. }
  5803. const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  5804. std::string MArch;
  5805. if (!Arch.empty())
  5806. MArch = Arch;
  5807. else
  5808. MArch = Triple.getArchName();
  5809. MArch = StringRef(MArch).split("+").first.lower();
  5810. // Handle -march=native.
  5811. if (MArch == "native") {
  5812. std::string CPU = llvm::sys::getHostCPUName();
  5813. if (CPU != "generic") {
  5814. // Translate the native cpu into the architecture suffix for that CPU.
  5815. StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
  5816. // If there is no valid architecture suffix for this CPU we don't know how
  5817. // to handle it, so return no architecture.
  5818. if (Suffix.empty())
  5819. MArch = "";
  5820. else
  5821. MArch = std::string("arm") + Suffix.str();
  5822. }
  5823. }
  5824. return MArch;
  5825. }
  5826. /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
  5827. StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
  5828. std::string MArch = getARMArch(Arch, Triple);
  5829. // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
  5830. // here means an -march=native that we can't handle, so instead return no CPU.
  5831. if (MArch.empty())
  5832. return StringRef();
  5833. // We need to return an empty string here on invalid MArch values as the
  5834. // various places that call this function can't cope with a null result.
  5835. return Triple.getARMCPUForArch(MArch);
  5836. }
  5837. /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
  5838. std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
  5839. const llvm::Triple &Triple) {
  5840. // FIXME: Warn on inconsistent use of -mcpu and -march.
  5841. // If we have -mcpu=, use that.
  5842. if (!CPU.empty()) {
  5843. std::string MCPU = StringRef(CPU).split("+").first.lower();
  5844. // Handle -mcpu=native.
  5845. if (MCPU == "native")
  5846. return llvm::sys::getHostCPUName();
  5847. else
  5848. return MCPU;
  5849. }
  5850. return getARMCPUForMArch(Arch, Triple);
  5851. }
  5852. /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
  5853. /// CPU (or Arch, if CPU is generic).
  5854. // FIXME: This is redundant with -mcpu, why does LLVM use this.
  5855. StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
  5856. const llvm::Triple &Triple) {
  5857. unsigned ArchKind;
  5858. if (CPU == "generic") {
  5859. std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
  5860. ArchKind = llvm::ARM::parseArch(ARMArch);
  5861. if (ArchKind == llvm::ARM::AK_INVALID)
  5862. // In case of generic Arch, i.e. "arm",
  5863. // extract arch from default cpu of the Triple
  5864. ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
  5865. } else {
  5866. // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
  5867. // armv7k triple if it's actually been specified via "-arch armv7k".
  5868. ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
  5869. ? (unsigned)llvm::ARM::AK_ARMV7K
  5870. : llvm::ARM::parseCPUArch(CPU);
  5871. }
  5872. if (ArchKind == llvm::ARM::AK_INVALID)
  5873. return "";
  5874. return llvm::ARM::getSubArch(ArchKind);
  5875. }
  5876. void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
  5877. const llvm::Triple &Triple) {
  5878. if (Args.hasArg(options::OPT_r))
  5879. return;
  5880. // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
  5881. // to generate BE-8 executables.
  5882. if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
  5883. CmdArgs.push_back("--be8");
  5884. }
  5885. mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
  5886. // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
  5887. // was first introduced in Release 3. However, other compilers have
  5888. // traditionally allowed it for Release 2 so we should do the same.
  5889. return (NanEncoding)llvm::StringSwitch<int>(CPU)
  5890. .Case("mips1", NanLegacy)
  5891. .Case("mips2", NanLegacy)
  5892. .Case("mips3", NanLegacy)
  5893. .Case("mips4", NanLegacy)
  5894. .Case("mips5", NanLegacy)
  5895. .Case("mips32", NanLegacy)
  5896. .Case("mips32r2", NanLegacy | Nan2008)
  5897. .Case("mips32r3", NanLegacy | Nan2008)
  5898. .Case("mips32r5", NanLegacy | Nan2008)
  5899. .Case("mips32r6", Nan2008)
  5900. .Case("mips64", NanLegacy)
  5901. .Case("mips64r2", NanLegacy | Nan2008)
  5902. .Case("mips64r3", NanLegacy | Nan2008)
  5903. .Case("mips64r5", NanLegacy | Nan2008)
  5904. .Case("mips64r6", Nan2008)
  5905. .Default(NanLegacy);
  5906. }
  5907. bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
  5908. Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  5909. return A && (A->getValue() == StringRef(Value));
  5910. }
  5911. bool mips::isUCLibc(const ArgList &Args) {
  5912. Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
  5913. return A && A->getOption().matches(options::OPT_muclibc);
  5914. }
  5915. bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
  5916. if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
  5917. return llvm::StringSwitch<bool>(NaNArg->getValue())
  5918. .Case("2008", true)
  5919. .Case("legacy", false)
  5920. .Default(false);
  5921. // NaN2008 is the default for MIPS32r6/MIPS64r6.
  5922. return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
  5923. .Cases("mips32r6", "mips64r6", true)
  5924. .Default(false);
  5925. return false;
  5926. }
  5927. bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
  5928. StringRef ABIName, mips::FloatABI FloatABI) {
  5929. if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
  5930. Triple.getVendor() != llvm::Triple::MipsTechnologies)
  5931. return false;
  5932. if (ABIName != "32")
  5933. return false;
  5934. // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
  5935. // present.
  5936. if (FloatABI == mips::FloatABI::Soft)
  5937. return false;
  5938. return llvm::StringSwitch<bool>(CPUName)
  5939. .Cases("mips2", "mips3", "mips4", "mips5", true)
  5940. .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
  5941. .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
  5942. .Default(false);
  5943. }
  5944. bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
  5945. StringRef CPUName, StringRef ABIName,
  5946. mips::FloatABI FloatABI) {
  5947. bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
  5948. // FPXX shouldn't be used if -msingle-float is present.
  5949. if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
  5950. options::OPT_mdouble_float))
  5951. if (A->getOption().matches(options::OPT_msingle_float))
  5952. UseFPXX = false;
  5953. return UseFPXX;
  5954. }
  5955. llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
  5956. // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
  5957. // archs which Darwin doesn't use.
  5958. // The matching this routine does is fairly pointless, since it is neither the
  5959. // complete architecture list, nor a reasonable subset. The problem is that
  5960. // historically the driver driver accepts this and also ties its -march=
  5961. // handling to the architecture name, so we need to be careful before removing
  5962. // support for it.
  5963. // This code must be kept in sync with Clang's Darwin specific argument
  5964. // translation.
  5965. return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
  5966. .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
  5967. .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
  5968. .Case("ppc64", llvm::Triple::ppc64)
  5969. .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
  5970. .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
  5971. llvm::Triple::x86)
  5972. .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
  5973. // This is derived from the driver driver.
  5974. .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
  5975. .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
  5976. .Cases("armv7s", "xscale", llvm::Triple::arm)
  5977. .Case("arm64", llvm::Triple::aarch64)
  5978. .Case("r600", llvm::Triple::r600)
  5979. .Case("amdgcn", llvm::Triple::amdgcn)
  5980. .Case("nvptx", llvm::Triple::nvptx)
  5981. .Case("nvptx64", llvm::Triple::nvptx64)
  5982. .Case("amdil", llvm::Triple::amdil)
  5983. .Case("spir", llvm::Triple::spir)
  5984. .Default(llvm::Triple::UnknownArch);
  5985. }
  5986. void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
  5987. const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
  5988. T.setArch(Arch);
  5989. if (Str == "x86_64h")
  5990. T.setArchName(Str);
  5991. else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
  5992. T.setOS(llvm::Triple::UnknownOS);
  5993. T.setObjectFormat(llvm::Triple::MachO);
  5994. }
  5995. }
  5996. const char *Clang::getBaseInputName(const ArgList &Args,
  5997. const InputInfo &Input) {
  5998. return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
  5999. }
  6000. const char *Clang::getBaseInputStem(const ArgList &Args,
  6001. const InputInfoList &Inputs) {
  6002. const char *Str = getBaseInputName(Args, Inputs[0]);
  6003. if (const char *End = strrchr(Str, '.'))
  6004. return Args.MakeArgString(std::string(Str, End));
  6005. return Str;
  6006. }
  6007. const char *Clang::getDependencyFileName(const ArgList &Args,
  6008. const InputInfoList &Inputs) {
  6009. // FIXME: Think about this more.
  6010. std::string Res;
  6011. if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
  6012. std::string Str(OutputOpt->getValue());
  6013. Res = Str.substr(0, Str.rfind('.'));
  6014. } else {
  6015. Res = getBaseInputStem(Args, Inputs);
  6016. }
  6017. return Args.MakeArgString(Res + ".d");
  6018. }
  6019. void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6020. const InputInfo &Output,
  6021. const InputInfoList &Inputs,
  6022. const ArgList &Args,
  6023. const char *LinkingOutput) const {
  6024. const ToolChain &ToolChain = getToolChain();
  6025. const Driver &D = ToolChain.getDriver();
  6026. ArgStringList CmdArgs;
  6027. // Silence warning for "clang -g foo.o -o foo"
  6028. Args.ClaimAllArgs(options::OPT_g_Group);
  6029. // and "clang -emit-llvm foo.o -o foo"
  6030. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6031. // and for "clang -w foo.o -o foo". Other warning options are already
  6032. // handled somewhere else.
  6033. Args.ClaimAllArgs(options::OPT_w);
  6034. if (!D.SysRoot.empty())
  6035. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6036. // CloudABI only supports static linkage.
  6037. CmdArgs.push_back("-Bstatic");
  6038. CmdArgs.push_back("--eh-frame-hdr");
  6039. CmdArgs.push_back("--gc-sections");
  6040. if (Output.isFilename()) {
  6041. CmdArgs.push_back("-o");
  6042. CmdArgs.push_back(Output.getFilename());
  6043. } else {
  6044. assert(Output.isNothing() && "Invalid output.");
  6045. }
  6046. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6047. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
  6048. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
  6049. }
  6050. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6051. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  6052. Args.AddAllArgs(CmdArgs,
  6053. {options::OPT_T_Group, options::OPT_e, options::OPT_s,
  6054. options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
  6055. if (D.isUsingLTO())
  6056. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  6057. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  6058. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6059. if (D.CCCIsCXX())
  6060. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  6061. CmdArgs.push_back("-lc");
  6062. CmdArgs.push_back("-lcompiler_rt");
  6063. }
  6064. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6065. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  6066. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  6067. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6068. }
  6069. void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6070. const InputInfo &Output,
  6071. const InputInfoList &Inputs,
  6072. const ArgList &Args,
  6073. const char *LinkingOutput) const {
  6074. ArgStringList CmdArgs;
  6075. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  6076. const InputInfo &Input = Inputs[0];
  6077. // Determine the original source input.
  6078. const Action *SourceAction = &JA;
  6079. while (SourceAction->getKind() != Action::InputClass) {
  6080. assert(!SourceAction->getInputs().empty() && "unexpected root action!");
  6081. SourceAction = SourceAction->getInputs()[0];
  6082. }
  6083. // If -fno-integrated-as is used add -Q to the darwin assember driver to make
  6084. // sure it runs its system assembler not clang's integrated assembler.
  6085. // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
  6086. // FIXME: at run-time detect assembler capabilities or rely on version
  6087. // information forwarded by -target-assembler-version.
  6088. if (Args.hasArg(options::OPT_fno_integrated_as)) {
  6089. const llvm::Triple &T(getToolChain().getTriple());
  6090. if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
  6091. CmdArgs.push_back("-Q");
  6092. }
  6093. // Forward -g, assuming we are dealing with an actual assembly file.
  6094. if (SourceAction->getType() == types::TY_Asm ||
  6095. SourceAction->getType() == types::TY_PP_Asm) {
  6096. if (Args.hasArg(options::OPT_gstabs))
  6097. CmdArgs.push_back("--gstabs");
  6098. else if (Args.hasArg(options::OPT_g_Group))
  6099. CmdArgs.push_back("-g");
  6100. }
  6101. // Derived from asm spec.
  6102. AddMachOArch(Args, CmdArgs);
  6103. // Use -force_cpusubtype_ALL on x86 by default.
  6104. if (getToolChain().getArch() == llvm::Triple::x86 ||
  6105. getToolChain().getArch() == llvm::Triple::x86_64 ||
  6106. Args.hasArg(options::OPT_force__cpusubtype__ALL))
  6107. CmdArgs.push_back("-force_cpusubtype_ALL");
  6108. if (getToolChain().getArch() != llvm::Triple::x86_64 &&
  6109. (((Args.hasArg(options::OPT_mkernel) ||
  6110. Args.hasArg(options::OPT_fapple_kext)) &&
  6111. getMachOToolChain().isKernelStatic()) ||
  6112. Args.hasArg(options::OPT_static)))
  6113. CmdArgs.push_back("-static");
  6114. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6115. assert(Output.isFilename() && "Unexpected lipo output.");
  6116. CmdArgs.push_back("-o");
  6117. CmdArgs.push_back(Output.getFilename());
  6118. assert(Input.isFilename() && "Invalid input.");
  6119. CmdArgs.push_back(Input.getFilename());
  6120. // asm_final spec is empty.
  6121. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6122. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6123. }
  6124. void darwin::MachOTool::anchor() {}
  6125. void darwin::MachOTool::AddMachOArch(const ArgList &Args,
  6126. ArgStringList &CmdArgs) const {
  6127. StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
  6128. // Derived from darwin_arch spec.
  6129. CmdArgs.push_back("-arch");
  6130. CmdArgs.push_back(Args.MakeArgString(ArchName));
  6131. // FIXME: Is this needed anymore?
  6132. if (ArchName == "arm")
  6133. CmdArgs.push_back("-force_cpusubtype_ALL");
  6134. }
  6135. bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
  6136. // We only need to generate a temp path for LTO if we aren't compiling object
  6137. // files. When compiling source files, we run 'dsymutil' after linking. We
  6138. // don't run 'dsymutil' when compiling object files.
  6139. for (const auto &Input : Inputs)
  6140. if (Input.getType() != types::TY_Object)
  6141. return true;
  6142. return false;
  6143. }
  6144. void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
  6145. ArgStringList &CmdArgs,
  6146. const InputInfoList &Inputs) const {
  6147. const Driver &D = getToolChain().getDriver();
  6148. const toolchains::MachO &MachOTC = getMachOToolChain();
  6149. unsigned Version[3] = {0, 0, 0};
  6150. if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
  6151. bool HadExtra;
  6152. if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
  6153. Version[2], HadExtra) ||
  6154. HadExtra)
  6155. D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
  6156. }
  6157. // Newer linkers support -demangle. Pass it if supported and not disabled by
  6158. // the user.
  6159. if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  6160. CmdArgs.push_back("-demangle");
  6161. if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
  6162. CmdArgs.push_back("-export_dynamic");
  6163. // If we are using App Extension restrictions, pass a flag to the linker
  6164. // telling it that the compiled code has been audited.
  6165. if (Args.hasFlag(options::OPT_fapplication_extension,
  6166. options::OPT_fno_application_extension, false))
  6167. CmdArgs.push_back("-application_extension");
  6168. if (D.isUsingLTO()) {
  6169. // If we are using LTO, then automatically create a temporary file path for
  6170. // the linker to use, so that it's lifetime will extend past a possible
  6171. // dsymutil step.
  6172. if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
  6173. const char *TmpPath = C.getArgs().MakeArgString(
  6174. D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
  6175. C.addTempFile(TmpPath);
  6176. CmdArgs.push_back("-object_path_lto");
  6177. CmdArgs.push_back(TmpPath);
  6178. }
  6179. // Use -lto_library option to specify the libLTO.dylib path. Try to find
  6180. // it in clang installed libraries. If not found, the option is not used
  6181. // and 'ld' will use its default mechanism to search for libLTO.dylib.
  6182. if (Version[0] >= 133) {
  6183. // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
  6184. StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
  6185. SmallString<128> LibLTOPath(P);
  6186. llvm::sys::path::append(LibLTOPath, "lib");
  6187. llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
  6188. if (llvm::sys::fs::exists(LibLTOPath)) {
  6189. CmdArgs.push_back("-lto_library");
  6190. CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
  6191. } else {
  6192. D.Diag(diag::warn_drv_lto_libpath);
  6193. }
  6194. }
  6195. }
  6196. // Derived from the "link" spec.
  6197. Args.AddAllArgs(CmdArgs, options::OPT_static);
  6198. if (!Args.hasArg(options::OPT_static))
  6199. CmdArgs.push_back("-dynamic");
  6200. if (Args.hasArg(options::OPT_fgnu_runtime)) {
  6201. // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
  6202. // here. How do we wish to handle such things?
  6203. }
  6204. if (!Args.hasArg(options::OPT_dynamiclib)) {
  6205. AddMachOArch(Args, CmdArgs);
  6206. // FIXME: Why do this only on this path?
  6207. Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
  6208. Args.AddLastArg(CmdArgs, options::OPT_bundle);
  6209. Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
  6210. Args.AddAllArgs(CmdArgs, options::OPT_client__name);
  6211. Arg *A;
  6212. if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
  6213. (A = Args.getLastArg(options::OPT_current__version)) ||
  6214. (A = Args.getLastArg(options::OPT_install__name)))
  6215. D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
  6216. << "-dynamiclib";
  6217. Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
  6218. Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
  6219. Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
  6220. } else {
  6221. CmdArgs.push_back("-dylib");
  6222. Arg *A;
  6223. if ((A = Args.getLastArg(options::OPT_bundle)) ||
  6224. (A = Args.getLastArg(options::OPT_bundle__loader)) ||
  6225. (A = Args.getLastArg(options::OPT_client__name)) ||
  6226. (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
  6227. (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
  6228. (A = Args.getLastArg(options::OPT_private__bundle)))
  6229. D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
  6230. << "-dynamiclib";
  6231. Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
  6232. "-dylib_compatibility_version");
  6233. Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
  6234. "-dylib_current_version");
  6235. AddMachOArch(Args, CmdArgs);
  6236. Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
  6237. "-dylib_install_name");
  6238. }
  6239. Args.AddLastArg(CmdArgs, options::OPT_all__load);
  6240. Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
  6241. Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
  6242. if (MachOTC.isTargetIOSBased())
  6243. Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
  6244. Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
  6245. Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
  6246. Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
  6247. Args.AddLastArg(CmdArgs, options::OPT_dynamic);
  6248. Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
  6249. Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
  6250. Args.AddAllArgs(CmdArgs, options::OPT_force__load);
  6251. Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
  6252. Args.AddAllArgs(CmdArgs, options::OPT_image__base);
  6253. Args.AddAllArgs(CmdArgs, options::OPT_init);
  6254. // Add the deployment target.
  6255. MachOTC.addMinVersionArgs(Args, CmdArgs);
  6256. Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
  6257. Args.AddLastArg(CmdArgs, options::OPT_multi__module);
  6258. Args.AddLastArg(CmdArgs, options::OPT_single__module);
  6259. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
  6260. Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
  6261. if (const Arg *A =
  6262. Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
  6263. options::OPT_fno_pie, options::OPT_fno_PIE)) {
  6264. if (A->getOption().matches(options::OPT_fpie) ||
  6265. A->getOption().matches(options::OPT_fPIE))
  6266. CmdArgs.push_back("-pie");
  6267. else
  6268. CmdArgs.push_back("-no_pie");
  6269. }
  6270. Args.AddLastArg(CmdArgs, options::OPT_prebind);
  6271. Args.AddLastArg(CmdArgs, options::OPT_noprebind);
  6272. Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
  6273. Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
  6274. Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
  6275. Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
  6276. Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
  6277. Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
  6278. Args.AddAllArgs(CmdArgs, options::OPT_segprot);
  6279. Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
  6280. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
  6281. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
  6282. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
  6283. Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
  6284. Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
  6285. Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
  6286. // Give --sysroot= preference, over the Apple specific behavior to also use
  6287. // --isysroot as the syslibroot.
  6288. StringRef sysroot = C.getSysRoot();
  6289. if (sysroot != "") {
  6290. CmdArgs.push_back("-syslibroot");
  6291. CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
  6292. } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
  6293. CmdArgs.push_back("-syslibroot");
  6294. CmdArgs.push_back(A->getValue());
  6295. }
  6296. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
  6297. Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
  6298. Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
  6299. Args.AddAllArgs(CmdArgs, options::OPT_undefined);
  6300. Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
  6301. Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
  6302. Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
  6303. Args.AddAllArgs(CmdArgs, options::OPT_y);
  6304. Args.AddLastArg(CmdArgs, options::OPT_w);
  6305. Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
  6306. Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
  6307. Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
  6308. Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
  6309. Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
  6310. Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
  6311. Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
  6312. Args.AddLastArg(CmdArgs, options::OPT_whyload);
  6313. Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
  6314. Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
  6315. Args.AddLastArg(CmdArgs, options::OPT_dylinker);
  6316. Args.AddLastArg(CmdArgs, options::OPT_Mach);
  6317. }
  6318. void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6319. const InputInfo &Output,
  6320. const InputInfoList &Inputs,
  6321. const ArgList &Args,
  6322. const char *LinkingOutput) const {
  6323. assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
  6324. // If the number of arguments surpasses the system limits, we will encode the
  6325. // input files in a separate file, shortening the command line. To this end,
  6326. // build a list of input file names that can be passed via a file with the
  6327. // -filelist linker option.
  6328. llvm::opt::ArgStringList InputFileList;
  6329. // The logic here is derived from gcc's behavior; most of which
  6330. // comes from specs (starting with link_command). Consult gcc for
  6331. // more information.
  6332. ArgStringList CmdArgs;
  6333. /// Hack(tm) to ignore linking errors when we are doing ARC migration.
  6334. if (Args.hasArg(options::OPT_ccc_arcmt_check,
  6335. options::OPT_ccc_arcmt_migrate)) {
  6336. for (const auto &Arg : Args)
  6337. Arg->claim();
  6338. const char *Exec =
  6339. Args.MakeArgString(getToolChain().GetProgramPath("touch"));
  6340. CmdArgs.push_back(Output.getFilename());
  6341. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
  6342. return;
  6343. }
  6344. // I'm not sure why this particular decomposition exists in gcc, but
  6345. // we follow suite for ease of comparison.
  6346. AddLinkArgs(C, Args, CmdArgs, Inputs);
  6347. // It seems that the 'e' option is completely ignored for dynamic executables
  6348. // (the default), and with static executables, the last one wins, as expected.
  6349. Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
  6350. options::OPT_Z_Flag, options::OPT_u_Group,
  6351. options::OPT_e, options::OPT_r});
  6352. // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
  6353. // members of static archive libraries which implement Objective-C classes or
  6354. // categories.
  6355. if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
  6356. CmdArgs.push_back("-ObjC");
  6357. CmdArgs.push_back("-o");
  6358. CmdArgs.push_back(Output.getFilename());
  6359. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
  6360. getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
  6361. // SafeStack requires its own runtime libraries
  6362. // These libraries should be linked first, to make sure the
  6363. // __safestack_init constructor executes before everything else
  6364. if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
  6365. getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
  6366. "libclang_rt.safestack_osx.a",
  6367. /*AlwaysLink=*/true);
  6368. }
  6369. Args.AddAllArgs(CmdArgs, options::OPT_L);
  6370. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6371. // Build the input file for -filelist (list of linker input files) in case we
  6372. // need it later
  6373. for (const auto &II : Inputs) {
  6374. if (!II.isFilename()) {
  6375. // This is a linker input argument.
  6376. // We cannot mix input arguments and file names in a -filelist input, thus
  6377. // we prematurely stop our list (remaining files shall be passed as
  6378. // arguments).
  6379. if (InputFileList.size() > 0)
  6380. break;
  6381. continue;
  6382. }
  6383. InputFileList.push_back(II.getFilename());
  6384. }
  6385. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
  6386. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  6387. if (isObjCRuntimeLinked(Args) &&
  6388. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6389. // We use arclite library for both ARC and subscripting support.
  6390. getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
  6391. CmdArgs.push_back("-framework");
  6392. CmdArgs.push_back("Foundation");
  6393. // Link libobj.
  6394. CmdArgs.push_back("-lobjc");
  6395. }
  6396. if (LinkingOutput) {
  6397. CmdArgs.push_back("-arch_multiple");
  6398. CmdArgs.push_back("-final_output");
  6399. CmdArgs.push_back(LinkingOutput);
  6400. }
  6401. if (Args.hasArg(options::OPT_fnested_functions))
  6402. CmdArgs.push_back("-allow_stack_execute");
  6403. getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
  6404. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6405. if (getToolChain().getDriver().CCCIsCXX())
  6406. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6407. // link_ssp spec is empty.
  6408. // Let the tool chain choose which runtime library to link.
  6409. getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
  6410. }
  6411. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6412. // endfile_spec is empty.
  6413. }
  6414. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  6415. Args.AddAllArgs(CmdArgs, options::OPT_F);
  6416. // -iframework should be forwarded as -F.
  6417. for (const Arg *A : Args.filtered(options::OPT_iframework))
  6418. CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
  6419. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6420. if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
  6421. if (A->getValue() == StringRef("Accelerate")) {
  6422. CmdArgs.push_back("-framework");
  6423. CmdArgs.push_back("Accelerate");
  6424. }
  6425. }
  6426. }
  6427. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6428. std::unique_ptr<Command> Cmd =
  6429. llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
  6430. Cmd->setInputFileList(std::move(InputFileList));
  6431. C.addCommand(std::move(Cmd));
  6432. }
  6433. void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
  6434. const InputInfo &Output,
  6435. const InputInfoList &Inputs,
  6436. const ArgList &Args,
  6437. const char *LinkingOutput) const {
  6438. ArgStringList CmdArgs;
  6439. CmdArgs.push_back("-create");
  6440. assert(Output.isFilename() && "Unexpected lipo output.");
  6441. CmdArgs.push_back("-output");
  6442. CmdArgs.push_back(Output.getFilename());
  6443. for (const auto &II : Inputs) {
  6444. assert(II.isFilename() && "Unexpected lipo input.");
  6445. CmdArgs.push_back(II.getFilename());
  6446. }
  6447. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
  6448. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6449. }
  6450. void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
  6451. const InputInfo &Output,
  6452. const InputInfoList &Inputs,
  6453. const ArgList &Args,
  6454. const char *LinkingOutput) const {
  6455. ArgStringList CmdArgs;
  6456. CmdArgs.push_back("-o");
  6457. CmdArgs.push_back(Output.getFilename());
  6458. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6459. const InputInfo &Input = Inputs[0];
  6460. assert(Input.isFilename() && "Unexpected dsymutil input.");
  6461. CmdArgs.push_back(Input.getFilename());
  6462. const char *Exec =
  6463. Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
  6464. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6465. }
  6466. void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
  6467. const InputInfo &Output,
  6468. const InputInfoList &Inputs,
  6469. const ArgList &Args,
  6470. const char *LinkingOutput) const {
  6471. ArgStringList CmdArgs;
  6472. CmdArgs.push_back("--verify");
  6473. CmdArgs.push_back("--debug-info");
  6474. CmdArgs.push_back("--eh-frame");
  6475. CmdArgs.push_back("--quiet");
  6476. assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
  6477. const InputInfo &Input = Inputs[0];
  6478. assert(Input.isFilename() && "Unexpected verify input");
  6479. // Grabbing the output of the earlier dsymutil run.
  6480. CmdArgs.push_back(Input.getFilename());
  6481. const char *Exec =
  6482. Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
  6483. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6484. }
  6485. void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6486. const InputInfo &Output,
  6487. const InputInfoList &Inputs,
  6488. const ArgList &Args,
  6489. const char *LinkingOutput) const {
  6490. claimNoWarnArgs(Args);
  6491. ArgStringList CmdArgs;
  6492. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6493. CmdArgs.push_back("-o");
  6494. CmdArgs.push_back(Output.getFilename());
  6495. for (const auto &II : Inputs)
  6496. CmdArgs.push_back(II.getFilename());
  6497. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6498. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6499. }
  6500. void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6501. const InputInfo &Output,
  6502. const InputInfoList &Inputs,
  6503. const ArgList &Args,
  6504. const char *LinkingOutput) const {
  6505. ArgStringList CmdArgs;
  6506. // Demangle C++ names in errors
  6507. CmdArgs.push_back("-C");
  6508. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6509. CmdArgs.push_back("-e");
  6510. CmdArgs.push_back("_start");
  6511. }
  6512. if (Args.hasArg(options::OPT_static)) {
  6513. CmdArgs.push_back("-Bstatic");
  6514. CmdArgs.push_back("-dn");
  6515. } else {
  6516. CmdArgs.push_back("-Bdynamic");
  6517. if (Args.hasArg(options::OPT_shared)) {
  6518. CmdArgs.push_back("-shared");
  6519. } else {
  6520. CmdArgs.push_back("--dynamic-linker");
  6521. CmdArgs.push_back(
  6522. Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
  6523. }
  6524. }
  6525. if (Output.isFilename()) {
  6526. CmdArgs.push_back("-o");
  6527. CmdArgs.push_back(Output.getFilename());
  6528. } else {
  6529. assert(Output.isNothing() && "Invalid output.");
  6530. }
  6531. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6532. if (!Args.hasArg(options::OPT_shared))
  6533. CmdArgs.push_back(
  6534. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  6535. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  6536. CmdArgs.push_back(
  6537. Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
  6538. CmdArgs.push_back(
  6539. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6540. }
  6541. getToolChain().AddFilePathLibArgs(Args, CmdArgs);
  6542. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6543. options::OPT_e, options::OPT_r});
  6544. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6545. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6546. if (getToolChain().getDriver().CCCIsCXX())
  6547. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6548. CmdArgs.push_back("-lgcc_s");
  6549. CmdArgs.push_back("-lc");
  6550. if (!Args.hasArg(options::OPT_shared)) {
  6551. CmdArgs.push_back("-lgcc");
  6552. CmdArgs.push_back("-lm");
  6553. }
  6554. }
  6555. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6556. CmdArgs.push_back(
  6557. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6558. }
  6559. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  6560. getToolChain().addProfileRTLibs(Args, CmdArgs);
  6561. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6562. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6563. }
  6564. void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6565. const InputInfo &Output,
  6566. const InputInfoList &Inputs,
  6567. const ArgList &Args,
  6568. const char *LinkingOutput) const {
  6569. claimNoWarnArgs(Args);
  6570. ArgStringList CmdArgs;
  6571. switch (getToolChain().getArch()) {
  6572. case llvm::Triple::x86:
  6573. // When building 32-bit code on OpenBSD/amd64, we have to explicitly
  6574. // instruct as in the base system to assemble 32-bit code.
  6575. CmdArgs.push_back("--32");
  6576. break;
  6577. case llvm::Triple::ppc:
  6578. CmdArgs.push_back("-mppc");
  6579. CmdArgs.push_back("-many");
  6580. break;
  6581. case llvm::Triple::sparc:
  6582. case llvm::Triple::sparcel: {
  6583. CmdArgs.push_back("-32");
  6584. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6585. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6586. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6587. break;
  6588. }
  6589. case llvm::Triple::sparcv9: {
  6590. CmdArgs.push_back("-64");
  6591. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6592. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6593. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6594. break;
  6595. }
  6596. case llvm::Triple::mips64:
  6597. case llvm::Triple::mips64el: {
  6598. StringRef CPUName;
  6599. StringRef ABIName;
  6600. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6601. CmdArgs.push_back("-mabi");
  6602. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6603. if (getToolChain().getArch() == llvm::Triple::mips64)
  6604. CmdArgs.push_back("-EB");
  6605. else
  6606. CmdArgs.push_back("-EL");
  6607. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6608. break;
  6609. }
  6610. default:
  6611. break;
  6612. }
  6613. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6614. CmdArgs.push_back("-o");
  6615. CmdArgs.push_back(Output.getFilename());
  6616. for (const auto &II : Inputs)
  6617. CmdArgs.push_back(II.getFilename());
  6618. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6619. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6620. }
  6621. void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6622. const InputInfo &Output,
  6623. const InputInfoList &Inputs,
  6624. const ArgList &Args,
  6625. const char *LinkingOutput) const {
  6626. const Driver &D = getToolChain().getDriver();
  6627. ArgStringList CmdArgs;
  6628. // Silence warning for "clang -g foo.o -o foo"
  6629. Args.ClaimAllArgs(options::OPT_g_Group);
  6630. // and "clang -emit-llvm foo.o -o foo"
  6631. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6632. // and for "clang -w foo.o -o foo". Other warning options are already
  6633. // handled somewhere else.
  6634. Args.ClaimAllArgs(options::OPT_w);
  6635. if (getToolChain().getArch() == llvm::Triple::mips64)
  6636. CmdArgs.push_back("-EB");
  6637. else if (getToolChain().getArch() == llvm::Triple::mips64el)
  6638. CmdArgs.push_back("-EL");
  6639. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6640. CmdArgs.push_back("-e");
  6641. CmdArgs.push_back("__start");
  6642. }
  6643. if (Args.hasArg(options::OPT_static)) {
  6644. CmdArgs.push_back("-Bstatic");
  6645. } else {
  6646. if (Args.hasArg(options::OPT_rdynamic))
  6647. CmdArgs.push_back("-export-dynamic");
  6648. CmdArgs.push_back("--eh-frame-hdr");
  6649. CmdArgs.push_back("-Bdynamic");
  6650. if (Args.hasArg(options::OPT_shared)) {
  6651. CmdArgs.push_back("-shared");
  6652. } else {
  6653. CmdArgs.push_back("-dynamic-linker");
  6654. CmdArgs.push_back("/usr/libexec/ld.so");
  6655. }
  6656. }
  6657. if (Args.hasArg(options::OPT_nopie))
  6658. CmdArgs.push_back("-nopie");
  6659. if (Output.isFilename()) {
  6660. CmdArgs.push_back("-o");
  6661. CmdArgs.push_back(Output.getFilename());
  6662. } else {
  6663. assert(Output.isNothing() && "Invalid output.");
  6664. }
  6665. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6666. if (!Args.hasArg(options::OPT_shared)) {
  6667. if (Args.hasArg(options::OPT_pg))
  6668. CmdArgs.push_back(
  6669. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6670. else
  6671. CmdArgs.push_back(
  6672. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6673. CmdArgs.push_back(
  6674. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6675. } else {
  6676. CmdArgs.push_back(
  6677. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6678. }
  6679. }
  6680. std::string Triple = getToolChain().getTripleString();
  6681. if (Triple.substr(0, 6) == "x86_64")
  6682. Triple.replace(0, 6, "amd64");
  6683. CmdArgs.push_back(
  6684. Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
  6685. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  6686. options::OPT_e, options::OPT_s, options::OPT_t,
  6687. options::OPT_Z_Flag, options::OPT_r});
  6688. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6689. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6690. if (D.CCCIsCXX()) {
  6691. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6692. if (Args.hasArg(options::OPT_pg))
  6693. CmdArgs.push_back("-lm_p");
  6694. else
  6695. CmdArgs.push_back("-lm");
  6696. }
  6697. // FIXME: For some reason GCC passes -lgcc before adding
  6698. // the default system libraries. Just mimic this for now.
  6699. CmdArgs.push_back("-lgcc");
  6700. if (Args.hasArg(options::OPT_pthread)) {
  6701. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6702. CmdArgs.push_back("-lpthread_p");
  6703. else
  6704. CmdArgs.push_back("-lpthread");
  6705. }
  6706. if (!Args.hasArg(options::OPT_shared)) {
  6707. if (Args.hasArg(options::OPT_pg))
  6708. CmdArgs.push_back("-lc_p");
  6709. else
  6710. CmdArgs.push_back("-lc");
  6711. }
  6712. CmdArgs.push_back("-lgcc");
  6713. }
  6714. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6715. if (!Args.hasArg(options::OPT_shared))
  6716. CmdArgs.push_back(
  6717. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6718. else
  6719. CmdArgs.push_back(
  6720. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6721. }
  6722. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6723. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6724. }
  6725. void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6726. const InputInfo &Output,
  6727. const InputInfoList &Inputs,
  6728. const ArgList &Args,
  6729. const char *LinkingOutput) const {
  6730. claimNoWarnArgs(Args);
  6731. ArgStringList CmdArgs;
  6732. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6733. CmdArgs.push_back("-o");
  6734. CmdArgs.push_back(Output.getFilename());
  6735. for (const auto &II : Inputs)
  6736. CmdArgs.push_back(II.getFilename());
  6737. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6738. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6739. }
  6740. void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6741. const InputInfo &Output,
  6742. const InputInfoList &Inputs,
  6743. const ArgList &Args,
  6744. const char *LinkingOutput) const {
  6745. const Driver &D = getToolChain().getDriver();
  6746. ArgStringList CmdArgs;
  6747. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
  6748. CmdArgs.push_back("-e");
  6749. CmdArgs.push_back("__start");
  6750. }
  6751. if (Args.hasArg(options::OPT_static)) {
  6752. CmdArgs.push_back("-Bstatic");
  6753. } else {
  6754. if (Args.hasArg(options::OPT_rdynamic))
  6755. CmdArgs.push_back("-export-dynamic");
  6756. CmdArgs.push_back("--eh-frame-hdr");
  6757. CmdArgs.push_back("-Bdynamic");
  6758. if (Args.hasArg(options::OPT_shared)) {
  6759. CmdArgs.push_back("-shared");
  6760. } else {
  6761. CmdArgs.push_back("-dynamic-linker");
  6762. CmdArgs.push_back("/usr/libexec/ld.so");
  6763. }
  6764. }
  6765. if (Output.isFilename()) {
  6766. CmdArgs.push_back("-o");
  6767. CmdArgs.push_back(Output.getFilename());
  6768. } else {
  6769. assert(Output.isNothing() && "Invalid output.");
  6770. }
  6771. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6772. if (!Args.hasArg(options::OPT_shared)) {
  6773. if (Args.hasArg(options::OPT_pg))
  6774. CmdArgs.push_back(
  6775. Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
  6776. else
  6777. CmdArgs.push_back(
  6778. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  6779. CmdArgs.push_back(
  6780. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  6781. } else {
  6782. CmdArgs.push_back(
  6783. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  6784. }
  6785. }
  6786. Args.AddAllArgs(CmdArgs,
  6787. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  6788. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  6789. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  6790. if (D.CCCIsCXX()) {
  6791. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  6792. if (Args.hasArg(options::OPT_pg))
  6793. CmdArgs.push_back("-lm_p");
  6794. else
  6795. CmdArgs.push_back("-lm");
  6796. }
  6797. if (Args.hasArg(options::OPT_pthread)) {
  6798. if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
  6799. CmdArgs.push_back("-lpthread_p");
  6800. else
  6801. CmdArgs.push_back("-lpthread");
  6802. }
  6803. if (!Args.hasArg(options::OPT_shared)) {
  6804. if (Args.hasArg(options::OPT_pg))
  6805. CmdArgs.push_back("-lc_p");
  6806. else
  6807. CmdArgs.push_back("-lc");
  6808. }
  6809. StringRef MyArch;
  6810. switch (getToolChain().getArch()) {
  6811. case llvm::Triple::arm:
  6812. MyArch = "arm";
  6813. break;
  6814. case llvm::Triple::x86:
  6815. MyArch = "i386";
  6816. break;
  6817. case llvm::Triple::x86_64:
  6818. MyArch = "amd64";
  6819. break;
  6820. default:
  6821. llvm_unreachable("Unsupported architecture");
  6822. }
  6823. CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
  6824. }
  6825. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6826. if (!Args.hasArg(options::OPT_shared))
  6827. CmdArgs.push_back(
  6828. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  6829. else
  6830. CmdArgs.push_back(
  6831. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  6832. }
  6833. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  6834. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6835. }
  6836. void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  6837. const InputInfo &Output,
  6838. const InputInfoList &Inputs,
  6839. const ArgList &Args,
  6840. const char *LinkingOutput) const {
  6841. claimNoWarnArgs(Args);
  6842. ArgStringList CmdArgs;
  6843. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  6844. // instruct as in the base system to assemble 32-bit code.
  6845. switch (getToolChain().getArch()) {
  6846. default:
  6847. break;
  6848. case llvm::Triple::x86:
  6849. CmdArgs.push_back("--32");
  6850. break;
  6851. case llvm::Triple::ppc:
  6852. CmdArgs.push_back("-a32");
  6853. break;
  6854. case llvm::Triple::mips:
  6855. case llvm::Triple::mipsel:
  6856. case llvm::Triple::mips64:
  6857. case llvm::Triple::mips64el: {
  6858. StringRef CPUName;
  6859. StringRef ABIName;
  6860. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  6861. CmdArgs.push_back("-march");
  6862. CmdArgs.push_back(CPUName.data());
  6863. CmdArgs.push_back("-mabi");
  6864. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  6865. if (getToolChain().getArch() == llvm::Triple::mips ||
  6866. getToolChain().getArch() == llvm::Triple::mips64)
  6867. CmdArgs.push_back("-EB");
  6868. else
  6869. CmdArgs.push_back("-EL");
  6870. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  6871. StringRef v = A->getValue();
  6872. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  6873. A->claim();
  6874. }
  6875. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6876. break;
  6877. }
  6878. case llvm::Triple::arm:
  6879. case llvm::Triple::armeb:
  6880. case llvm::Triple::thumb:
  6881. case llvm::Triple::thumbeb: {
  6882. arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
  6883. if (ABI == arm::FloatABI::Hard)
  6884. CmdArgs.push_back("-mfpu=vfp");
  6885. else
  6886. CmdArgs.push_back("-mfpu=softvfp");
  6887. switch (getToolChain().getTriple().getEnvironment()) {
  6888. case llvm::Triple::GNUEABIHF:
  6889. case llvm::Triple::GNUEABI:
  6890. case llvm::Triple::EABI:
  6891. CmdArgs.push_back("-meabi=5");
  6892. break;
  6893. default:
  6894. CmdArgs.push_back("-matpcs");
  6895. }
  6896. break;
  6897. }
  6898. case llvm::Triple::sparc:
  6899. case llvm::Triple::sparcel:
  6900. case llvm::Triple::sparcv9: {
  6901. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  6902. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  6903. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  6904. break;
  6905. }
  6906. }
  6907. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  6908. CmdArgs.push_back("-o");
  6909. CmdArgs.push_back(Output.getFilename());
  6910. for (const auto &II : Inputs)
  6911. CmdArgs.push_back(II.getFilename());
  6912. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  6913. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  6914. }
  6915. void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  6916. const InputInfo &Output,
  6917. const InputInfoList &Inputs,
  6918. const ArgList &Args,
  6919. const char *LinkingOutput) const {
  6920. const toolchains::FreeBSD &ToolChain =
  6921. static_cast<const toolchains::FreeBSD &>(getToolChain());
  6922. const Driver &D = ToolChain.getDriver();
  6923. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  6924. const bool IsPIE =
  6925. !Args.hasArg(options::OPT_shared) &&
  6926. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  6927. ArgStringList CmdArgs;
  6928. // Silence warning for "clang -g foo.o -o foo"
  6929. Args.ClaimAllArgs(options::OPT_g_Group);
  6930. // and "clang -emit-llvm foo.o -o foo"
  6931. Args.ClaimAllArgs(options::OPT_emit_llvm);
  6932. // and for "clang -w foo.o -o foo". Other warning options are already
  6933. // handled somewhere else.
  6934. Args.ClaimAllArgs(options::OPT_w);
  6935. if (!D.SysRoot.empty())
  6936. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  6937. if (IsPIE)
  6938. CmdArgs.push_back("-pie");
  6939. if (Args.hasArg(options::OPT_static)) {
  6940. CmdArgs.push_back("-Bstatic");
  6941. } else {
  6942. if (Args.hasArg(options::OPT_rdynamic))
  6943. CmdArgs.push_back("-export-dynamic");
  6944. CmdArgs.push_back("--eh-frame-hdr");
  6945. if (Args.hasArg(options::OPT_shared)) {
  6946. CmdArgs.push_back("-Bshareable");
  6947. } else {
  6948. CmdArgs.push_back("-dynamic-linker");
  6949. CmdArgs.push_back("/libexec/ld-elf.so.1");
  6950. }
  6951. if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
  6952. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
  6953. Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
  6954. CmdArgs.push_back("--hash-style=both");
  6955. }
  6956. }
  6957. CmdArgs.push_back("--enable-new-dtags");
  6958. }
  6959. // When building 32-bit code on FreeBSD/amd64, we have to explicitly
  6960. // instruct ld in the base system to link 32-bit code.
  6961. if (Arch == llvm::Triple::x86) {
  6962. CmdArgs.push_back("-m");
  6963. CmdArgs.push_back("elf_i386_fbsd");
  6964. }
  6965. if (Arch == llvm::Triple::ppc) {
  6966. CmdArgs.push_back("-m");
  6967. CmdArgs.push_back("elf32ppc_fbsd");
  6968. }
  6969. if (Arg *A = Args.getLastArg(options::OPT_G)) {
  6970. if (ToolChain.getArch() == llvm::Triple::mips ||
  6971. ToolChain.getArch() == llvm::Triple::mipsel ||
  6972. ToolChain.getArch() == llvm::Triple::mips64 ||
  6973. ToolChain.getArch() == llvm::Triple::mips64el) {
  6974. StringRef v = A->getValue();
  6975. CmdArgs.push_back(Args.MakeArgString("-G" + v));
  6976. A->claim();
  6977. }
  6978. }
  6979. if (Output.isFilename()) {
  6980. CmdArgs.push_back("-o");
  6981. CmdArgs.push_back(Output.getFilename());
  6982. } else {
  6983. assert(Output.isNothing() && "Invalid output.");
  6984. }
  6985. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  6986. const char *crt1 = nullptr;
  6987. if (!Args.hasArg(options::OPT_shared)) {
  6988. if (Args.hasArg(options::OPT_pg))
  6989. crt1 = "gcrt1.o";
  6990. else if (IsPIE)
  6991. crt1 = "Scrt1.o";
  6992. else
  6993. crt1 = "crt1.o";
  6994. }
  6995. if (crt1)
  6996. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  6997. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  6998. const char *crtbegin = nullptr;
  6999. if (Args.hasArg(options::OPT_static))
  7000. crtbegin = "crtbeginT.o";
  7001. else if (Args.hasArg(options::OPT_shared) || IsPIE)
  7002. crtbegin = "crtbeginS.o";
  7003. else
  7004. crtbegin = "crtbegin.o";
  7005. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7006. }
  7007. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7008. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7009. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7010. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7011. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7012. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7013. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7014. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7015. if (D.isUsingLTO())
  7016. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  7017. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7018. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7019. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7020. addOpenMPRuntime(CmdArgs, ToolChain, Args);
  7021. if (D.CCCIsCXX()) {
  7022. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7023. if (Args.hasArg(options::OPT_pg))
  7024. CmdArgs.push_back("-lm_p");
  7025. else
  7026. CmdArgs.push_back("-lm");
  7027. }
  7028. if (NeedsSanitizerDeps)
  7029. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7030. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  7031. // the default system libraries. Just mimic this for now.
  7032. if (Args.hasArg(options::OPT_pg))
  7033. CmdArgs.push_back("-lgcc_p");
  7034. else
  7035. CmdArgs.push_back("-lgcc");
  7036. if (Args.hasArg(options::OPT_static)) {
  7037. CmdArgs.push_back("-lgcc_eh");
  7038. } else if (Args.hasArg(options::OPT_pg)) {
  7039. CmdArgs.push_back("-lgcc_eh_p");
  7040. } else {
  7041. CmdArgs.push_back("--as-needed");
  7042. CmdArgs.push_back("-lgcc_s");
  7043. CmdArgs.push_back("--no-as-needed");
  7044. }
  7045. if (Args.hasArg(options::OPT_pthread)) {
  7046. if (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_pg)) {
  7052. if (Args.hasArg(options::OPT_shared))
  7053. CmdArgs.push_back("-lc");
  7054. else
  7055. CmdArgs.push_back("-lc_p");
  7056. CmdArgs.push_back("-lgcc_p");
  7057. } else {
  7058. CmdArgs.push_back("-lc");
  7059. CmdArgs.push_back("-lgcc");
  7060. }
  7061. if (Args.hasArg(options::OPT_static)) {
  7062. CmdArgs.push_back("-lgcc_eh");
  7063. } else if (Args.hasArg(options::OPT_pg)) {
  7064. CmdArgs.push_back("-lgcc_eh_p");
  7065. } else {
  7066. CmdArgs.push_back("--as-needed");
  7067. CmdArgs.push_back("-lgcc_s");
  7068. CmdArgs.push_back("--no-as-needed");
  7069. }
  7070. }
  7071. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7072. if (Args.hasArg(options::OPT_shared) || IsPIE)
  7073. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  7074. else
  7075. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  7076. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7077. }
  7078. ToolChain.addProfileRTLibs(Args, CmdArgs);
  7079. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7080. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7081. }
  7082. void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7083. const InputInfo &Output,
  7084. const InputInfoList &Inputs,
  7085. const ArgList &Args,
  7086. const char *LinkingOutput) const {
  7087. claimNoWarnArgs(Args);
  7088. ArgStringList CmdArgs;
  7089. // GNU as needs different flags for creating the correct output format
  7090. // on architectures with different ABIs or optional feature sets.
  7091. switch (getToolChain().getArch()) {
  7092. case llvm::Triple::x86:
  7093. CmdArgs.push_back("--32");
  7094. break;
  7095. case llvm::Triple::arm:
  7096. case llvm::Triple::armeb:
  7097. case llvm::Triple::thumb:
  7098. case llvm::Triple::thumbeb: {
  7099. StringRef MArch, MCPU;
  7100. getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
  7101. std::string Arch =
  7102. arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
  7103. CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
  7104. break;
  7105. }
  7106. case llvm::Triple::mips:
  7107. case llvm::Triple::mipsel:
  7108. case llvm::Triple::mips64:
  7109. case llvm::Triple::mips64el: {
  7110. StringRef CPUName;
  7111. StringRef ABIName;
  7112. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7113. CmdArgs.push_back("-march");
  7114. CmdArgs.push_back(CPUName.data());
  7115. CmdArgs.push_back("-mabi");
  7116. CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
  7117. if (getToolChain().getArch() == llvm::Triple::mips ||
  7118. getToolChain().getArch() == llvm::Triple::mips64)
  7119. CmdArgs.push_back("-EB");
  7120. else
  7121. CmdArgs.push_back("-EL");
  7122. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7123. break;
  7124. }
  7125. case llvm::Triple::sparc:
  7126. case llvm::Triple::sparcel: {
  7127. CmdArgs.push_back("-32");
  7128. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7129. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7130. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7131. break;
  7132. }
  7133. case llvm::Triple::sparcv9: {
  7134. CmdArgs.push_back("-64");
  7135. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7136. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7137. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7138. break;
  7139. }
  7140. default:
  7141. break;
  7142. }
  7143. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7144. CmdArgs.push_back("-o");
  7145. CmdArgs.push_back(Output.getFilename());
  7146. for (const auto &II : Inputs)
  7147. CmdArgs.push_back(II.getFilename());
  7148. const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
  7149. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7150. }
  7151. void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7152. const InputInfo &Output,
  7153. const InputInfoList &Inputs,
  7154. const ArgList &Args,
  7155. const char *LinkingOutput) const {
  7156. const Driver &D = getToolChain().getDriver();
  7157. ArgStringList CmdArgs;
  7158. if (!D.SysRoot.empty())
  7159. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7160. CmdArgs.push_back("--eh-frame-hdr");
  7161. if (Args.hasArg(options::OPT_static)) {
  7162. CmdArgs.push_back("-Bstatic");
  7163. } else {
  7164. if (Args.hasArg(options::OPT_rdynamic))
  7165. CmdArgs.push_back("-export-dynamic");
  7166. if (Args.hasArg(options::OPT_shared)) {
  7167. CmdArgs.push_back("-Bshareable");
  7168. } else {
  7169. CmdArgs.push_back("-dynamic-linker");
  7170. CmdArgs.push_back("/libexec/ld.elf_so");
  7171. }
  7172. }
  7173. // Many NetBSD architectures support more than one ABI.
  7174. // Determine the correct emulation for ld.
  7175. switch (getToolChain().getArch()) {
  7176. case llvm::Triple::x86:
  7177. CmdArgs.push_back("-m");
  7178. CmdArgs.push_back("elf_i386");
  7179. break;
  7180. case llvm::Triple::arm:
  7181. case llvm::Triple::thumb:
  7182. CmdArgs.push_back("-m");
  7183. switch (getToolChain().getTriple().getEnvironment()) {
  7184. case llvm::Triple::EABI:
  7185. case llvm::Triple::GNUEABI:
  7186. CmdArgs.push_back("armelf_nbsd_eabi");
  7187. break;
  7188. case llvm::Triple::EABIHF:
  7189. case llvm::Triple::GNUEABIHF:
  7190. CmdArgs.push_back("armelf_nbsd_eabihf");
  7191. break;
  7192. default:
  7193. CmdArgs.push_back("armelf_nbsd");
  7194. break;
  7195. }
  7196. break;
  7197. case llvm::Triple::armeb:
  7198. case llvm::Triple::thumbeb:
  7199. arm::appendEBLinkFlags(
  7200. Args, CmdArgs,
  7201. llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
  7202. CmdArgs.push_back("-m");
  7203. switch (getToolChain().getTriple().getEnvironment()) {
  7204. case llvm::Triple::EABI:
  7205. case llvm::Triple::GNUEABI:
  7206. CmdArgs.push_back("armelfb_nbsd_eabi");
  7207. break;
  7208. case llvm::Triple::EABIHF:
  7209. case llvm::Triple::GNUEABIHF:
  7210. CmdArgs.push_back("armelfb_nbsd_eabihf");
  7211. break;
  7212. default:
  7213. CmdArgs.push_back("armelfb_nbsd");
  7214. break;
  7215. }
  7216. break;
  7217. case llvm::Triple::mips64:
  7218. case llvm::Triple::mips64el:
  7219. if (mips::hasMipsAbiArg(Args, "32")) {
  7220. CmdArgs.push_back("-m");
  7221. if (getToolChain().getArch() == llvm::Triple::mips64)
  7222. CmdArgs.push_back("elf32btsmip");
  7223. else
  7224. CmdArgs.push_back("elf32ltsmip");
  7225. } else if (mips::hasMipsAbiArg(Args, "64")) {
  7226. CmdArgs.push_back("-m");
  7227. if (getToolChain().getArch() == llvm::Triple::mips64)
  7228. CmdArgs.push_back("elf64btsmip");
  7229. else
  7230. CmdArgs.push_back("elf64ltsmip");
  7231. }
  7232. break;
  7233. case llvm::Triple::ppc:
  7234. CmdArgs.push_back("-m");
  7235. CmdArgs.push_back("elf32ppc_nbsd");
  7236. break;
  7237. case llvm::Triple::ppc64:
  7238. case llvm::Triple::ppc64le:
  7239. CmdArgs.push_back("-m");
  7240. CmdArgs.push_back("elf64ppc");
  7241. break;
  7242. case llvm::Triple::sparc:
  7243. CmdArgs.push_back("-m");
  7244. CmdArgs.push_back("elf32_sparc");
  7245. break;
  7246. case llvm::Triple::sparcv9:
  7247. CmdArgs.push_back("-m");
  7248. CmdArgs.push_back("elf64_sparc");
  7249. break;
  7250. default:
  7251. break;
  7252. }
  7253. if (Output.isFilename()) {
  7254. CmdArgs.push_back("-o");
  7255. CmdArgs.push_back(Output.getFilename());
  7256. } else {
  7257. assert(Output.isNothing() && "Invalid output.");
  7258. }
  7259. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7260. if (!Args.hasArg(options::OPT_shared)) {
  7261. CmdArgs.push_back(
  7262. Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
  7263. CmdArgs.push_back(
  7264. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7265. CmdArgs.push_back(
  7266. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  7267. } else {
  7268. CmdArgs.push_back(
  7269. Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  7270. CmdArgs.push_back(
  7271. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  7272. }
  7273. }
  7274. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7275. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  7276. Args.AddAllArgs(CmdArgs, options::OPT_e);
  7277. Args.AddAllArgs(CmdArgs, options::OPT_s);
  7278. Args.AddAllArgs(CmdArgs, options::OPT_t);
  7279. Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
  7280. Args.AddAllArgs(CmdArgs, options::OPT_r);
  7281. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  7282. unsigned Major, Minor, Micro;
  7283. getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
  7284. bool useLibgcc = true;
  7285. if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
  7286. switch (getToolChain().getArch()) {
  7287. case llvm::Triple::aarch64:
  7288. case llvm::Triple::arm:
  7289. case llvm::Triple::armeb:
  7290. case llvm::Triple::thumb:
  7291. case llvm::Triple::thumbeb:
  7292. case llvm::Triple::ppc:
  7293. case llvm::Triple::ppc64:
  7294. case llvm::Triple::ppc64le:
  7295. case llvm::Triple::x86:
  7296. case llvm::Triple::x86_64:
  7297. useLibgcc = false;
  7298. break;
  7299. default:
  7300. break;
  7301. }
  7302. }
  7303. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7304. addOpenMPRuntime(CmdArgs, getToolChain(), Args);
  7305. if (D.CCCIsCXX()) {
  7306. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  7307. CmdArgs.push_back("-lm");
  7308. }
  7309. if (Args.hasArg(options::OPT_pthread))
  7310. CmdArgs.push_back("-lpthread");
  7311. CmdArgs.push_back("-lc");
  7312. if (useLibgcc) {
  7313. if (Args.hasArg(options::OPT_static)) {
  7314. // libgcc_eh depends on libc, so resolve as much as possible,
  7315. // pull in any new requirements from libc and then get the rest
  7316. // of libgcc.
  7317. CmdArgs.push_back("-lgcc_eh");
  7318. CmdArgs.push_back("-lc");
  7319. CmdArgs.push_back("-lgcc");
  7320. } else {
  7321. CmdArgs.push_back("-lgcc");
  7322. CmdArgs.push_back("--as-needed");
  7323. CmdArgs.push_back("-lgcc_s");
  7324. CmdArgs.push_back("--no-as-needed");
  7325. }
  7326. }
  7327. }
  7328. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7329. if (!Args.hasArg(options::OPT_shared))
  7330. CmdArgs.push_back(
  7331. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  7332. else
  7333. CmdArgs.push_back(
  7334. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  7335. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  7336. }
  7337. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7338. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  7339. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7340. }
  7341. void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  7342. const InputInfo &Output,
  7343. const InputInfoList &Inputs,
  7344. const ArgList &Args,
  7345. const char *LinkingOutput) const {
  7346. claimNoWarnArgs(Args);
  7347. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7348. llvm::Triple Triple = llvm::Triple(TripleStr);
  7349. ArgStringList CmdArgs;
  7350. llvm::Reloc::Model RelocationModel;
  7351. unsigned PICLevel;
  7352. bool IsPIE;
  7353. std::tie(RelocationModel, PICLevel, IsPIE) =
  7354. ParsePICArgs(getToolChain(), Triple, Args);
  7355. switch (getToolChain().getArch()) {
  7356. default:
  7357. break;
  7358. // Add --32/--64 to make sure we get the format we want.
  7359. // This is incomplete
  7360. case llvm::Triple::x86:
  7361. CmdArgs.push_back("--32");
  7362. break;
  7363. case llvm::Triple::x86_64:
  7364. if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7365. CmdArgs.push_back("--x32");
  7366. else
  7367. CmdArgs.push_back("--64");
  7368. break;
  7369. case llvm::Triple::ppc:
  7370. CmdArgs.push_back("-a32");
  7371. CmdArgs.push_back("-mppc");
  7372. CmdArgs.push_back("-many");
  7373. break;
  7374. case llvm::Triple::ppc64:
  7375. CmdArgs.push_back("-a64");
  7376. CmdArgs.push_back("-mppc64");
  7377. CmdArgs.push_back("-many");
  7378. break;
  7379. case llvm::Triple::ppc64le:
  7380. CmdArgs.push_back("-a64");
  7381. CmdArgs.push_back("-mppc64");
  7382. CmdArgs.push_back("-many");
  7383. CmdArgs.push_back("-mlittle-endian");
  7384. break;
  7385. case llvm::Triple::sparc:
  7386. case llvm::Triple::sparcel: {
  7387. CmdArgs.push_back("-32");
  7388. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7389. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7390. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7391. break;
  7392. }
  7393. case llvm::Triple::sparcv9: {
  7394. CmdArgs.push_back("-64");
  7395. std::string CPU = getCPUName(Args, getToolChain().getTriple());
  7396. CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
  7397. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7398. break;
  7399. }
  7400. case llvm::Triple::arm:
  7401. case llvm::Triple::armeb:
  7402. case llvm::Triple::thumb:
  7403. case llvm::Triple::thumbeb: {
  7404. const llvm::Triple &Triple2 = getToolChain().getTriple();
  7405. switch (Triple2.getSubArch()) {
  7406. case llvm::Triple::ARMSubArch_v7:
  7407. CmdArgs.push_back("-mfpu=neon");
  7408. break;
  7409. case llvm::Triple::ARMSubArch_v8:
  7410. CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
  7411. break;
  7412. default:
  7413. break;
  7414. }
  7415. switch (arm::getARMFloatABI(getToolChain(), Args)) {
  7416. case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
  7417. case arm::FloatABI::Soft:
  7418. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
  7419. break;
  7420. case arm::FloatABI::SoftFP:
  7421. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
  7422. break;
  7423. case arm::FloatABI::Hard:
  7424. CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
  7425. break;
  7426. }
  7427. Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
  7428. // FIXME: remove krait check when GNU tools support krait cpu
  7429. // for now replace it with -march=armv7-a to avoid a lower
  7430. // march from being picked in the absence of a cpu flag.
  7431. Arg *A;
  7432. if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
  7433. StringRef(A->getValue()).lower() == "krait")
  7434. CmdArgs.push_back("-march=armv7-a");
  7435. else
  7436. Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
  7437. Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
  7438. break;
  7439. }
  7440. case llvm::Triple::mips:
  7441. case llvm::Triple::mipsel:
  7442. case llvm::Triple::mips64:
  7443. case llvm::Triple::mips64el: {
  7444. StringRef CPUName;
  7445. StringRef ABIName;
  7446. mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
  7447. ABIName = getGnuCompatibleMipsABIName(ABIName);
  7448. CmdArgs.push_back("-march");
  7449. CmdArgs.push_back(CPUName.data());
  7450. CmdArgs.push_back("-mabi");
  7451. CmdArgs.push_back(ABIName.data());
  7452. // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
  7453. // or -mshared (not implemented) is in effect.
  7454. if (RelocationModel == llvm::Reloc::Static)
  7455. CmdArgs.push_back("-mno-shared");
  7456. // LLVM doesn't support -mplt yet and acts as if it is always given.
  7457. // However, -mplt has no effect with the N64 ABI.
  7458. CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
  7459. if (getToolChain().getArch() == llvm::Triple::mips ||
  7460. getToolChain().getArch() == llvm::Triple::mips64)
  7461. CmdArgs.push_back("-EB");
  7462. else
  7463. CmdArgs.push_back("-EL");
  7464. if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
  7465. if (StringRef(A->getValue()) == "2008")
  7466. CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
  7467. }
  7468. // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
  7469. if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
  7470. options::OPT_mfp64)) {
  7471. A->claim();
  7472. A->render(Args, CmdArgs);
  7473. } else if (mips::shouldUseFPXX(
  7474. Args, getToolChain().getTriple(), CPUName, ABIName,
  7475. getMipsFloatABI(getToolChain().getDriver(), Args)))
  7476. CmdArgs.push_back("-mfpxx");
  7477. // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
  7478. // -mno-mips16 is actually -no-mips16.
  7479. if (Arg *A =
  7480. Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
  7481. if (A->getOption().matches(options::OPT_mips16)) {
  7482. A->claim();
  7483. A->render(Args, CmdArgs);
  7484. } else {
  7485. A->claim();
  7486. CmdArgs.push_back("-no-mips16");
  7487. }
  7488. }
  7489. Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
  7490. options::OPT_mno_micromips);
  7491. Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
  7492. Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
  7493. if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
  7494. // Do not use AddLastArg because not all versions of MIPS assembler
  7495. // support -mmsa / -mno-msa options.
  7496. if (A->getOption().matches(options::OPT_mmsa))
  7497. CmdArgs.push_back(Args.MakeArgString("-mmsa"));
  7498. }
  7499. Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
  7500. options::OPT_msoft_float);
  7501. Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
  7502. options::OPT_msingle_float);
  7503. Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
  7504. options::OPT_mno_odd_spreg);
  7505. AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
  7506. break;
  7507. }
  7508. case llvm::Triple::systemz: {
  7509. // Always pass an -march option, since our default of z10 is later
  7510. // than the GNU assembler's default.
  7511. StringRef CPUName = getSystemZTargetCPU(Args);
  7512. CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
  7513. break;
  7514. }
  7515. }
  7516. Args.AddAllArgs(CmdArgs, options::OPT_I);
  7517. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  7518. CmdArgs.push_back("-o");
  7519. CmdArgs.push_back(Output.getFilename());
  7520. for (const auto &II : Inputs)
  7521. CmdArgs.push_back(II.getFilename());
  7522. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  7523. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7524. // Handle the debug info splitting at object creation time if we're
  7525. // creating an object.
  7526. // TODO: Currently only works on linux with newer objcopy.
  7527. if (Args.hasArg(options::OPT_gsplit_dwarf) &&
  7528. getToolChain().getTriple().isOSLinux())
  7529. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  7530. SplitDebugName(Args, Inputs[0]));
  7531. }
  7532. static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
  7533. ArgStringList &CmdArgs, const ArgList &Args) {
  7534. bool isAndroid = Triple.isAndroid();
  7535. bool isCygMing = Triple.isOSCygMing();
  7536. bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
  7537. Args.hasArg(options::OPT_static);
  7538. if (!D.CCCIsCXX())
  7539. CmdArgs.push_back("-lgcc");
  7540. if (StaticLibgcc || isAndroid) {
  7541. if (D.CCCIsCXX())
  7542. CmdArgs.push_back("-lgcc");
  7543. } else {
  7544. if (!D.CCCIsCXX() && !isCygMing)
  7545. CmdArgs.push_back("--as-needed");
  7546. CmdArgs.push_back("-lgcc_s");
  7547. if (!D.CCCIsCXX() && !isCygMing)
  7548. CmdArgs.push_back("--no-as-needed");
  7549. }
  7550. if (StaticLibgcc && !isAndroid)
  7551. CmdArgs.push_back("-lgcc_eh");
  7552. else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
  7553. CmdArgs.push_back("-lgcc");
  7554. // According to Android ABI, we have to link with libdl if we are
  7555. // linking with non-static libgcc.
  7556. //
  7557. // NOTE: This fixes a link error on Android MIPS as well. The non-static
  7558. // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
  7559. if (isAndroid && !StaticLibgcc)
  7560. CmdArgs.push_back("-ldl");
  7561. }
  7562. static std::string getLinuxDynamicLinker(const ArgList &Args,
  7563. const toolchains::Linux &ToolChain) {
  7564. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7565. if (ToolChain.getTriple().isAndroid()) {
  7566. if (ToolChain.getTriple().isArch64Bit())
  7567. return "/system/bin/linker64";
  7568. else
  7569. return "/system/bin/linker";
  7570. } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
  7571. Arch == llvm::Triple::sparcel)
  7572. return "/lib/ld-linux.so.2";
  7573. else if (Arch == llvm::Triple::aarch64)
  7574. return "/lib/ld-linux-aarch64.so.1";
  7575. else if (Arch == llvm::Triple::aarch64_be)
  7576. return "/lib/ld-linux-aarch64_be.so.1";
  7577. else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
  7578. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7579. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7580. return "/lib/ld-linux-armhf.so.3";
  7581. else
  7582. return "/lib/ld-linux.so.3";
  7583. } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
  7584. // TODO: check which dynamic linker name.
  7585. if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
  7586. arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
  7587. return "/lib/ld-linux-armhf.so.3";
  7588. else
  7589. return "/lib/ld-linux.so.3";
  7590. } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
  7591. Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
  7592. std::string LibDir =
  7593. "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
  7594. StringRef LibName;
  7595. bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
  7596. if (mips::isUCLibc(Args))
  7597. LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
  7598. else if (!ToolChain.getTriple().hasEnvironment()) {
  7599. bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
  7600. (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
  7601. LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
  7602. } else
  7603. LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
  7604. return (LibDir + "/" + LibName).str();
  7605. } else if (Arch == llvm::Triple::ppc)
  7606. return "/lib/ld.so.1";
  7607. else if (Arch == llvm::Triple::ppc64) {
  7608. if (ppc::hasPPCAbiArg(Args, "elfv2"))
  7609. return "/lib64/ld64.so.2";
  7610. return "/lib64/ld64.so.1";
  7611. } else if (Arch == llvm::Triple::ppc64le) {
  7612. if (ppc::hasPPCAbiArg(Args, "elfv1"))
  7613. return "/lib64/ld64.so.1";
  7614. return "/lib64/ld64.so.2";
  7615. } else if (Arch == llvm::Triple::systemz)
  7616. return "/lib/ld64.so.1";
  7617. else if (Arch == llvm::Triple::sparcv9)
  7618. return "/lib64/ld-linux.so.2";
  7619. else if (Arch == llvm::Triple::x86_64 &&
  7620. ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
  7621. return "/libx32/ld-linux-x32.so.2";
  7622. else
  7623. return "/lib64/ld-linux-x86-64.so.2";
  7624. }
  7625. static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
  7626. ArgStringList &CmdArgs, const ArgList &Args) {
  7627. // Make use of compiler-rt if --rtlib option is used
  7628. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
  7629. switch (RLT) {
  7630. case ToolChain::RLT_CompilerRT:
  7631. switch (TC.getTriple().getOS()) {
  7632. default:
  7633. llvm_unreachable("unsupported OS");
  7634. case llvm::Triple::Win32:
  7635. case llvm::Triple::Linux:
  7636. addClangRT(TC, Args, CmdArgs);
  7637. break;
  7638. }
  7639. break;
  7640. case ToolChain::RLT_Libgcc:
  7641. AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
  7642. break;
  7643. }
  7644. }
  7645. static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
  7646. switch (T.getArch()) {
  7647. case llvm::Triple::x86:
  7648. return "elf_i386";
  7649. case llvm::Triple::aarch64:
  7650. return "aarch64linux";
  7651. case llvm::Triple::aarch64_be:
  7652. return "aarch64_be_linux";
  7653. case llvm::Triple::arm:
  7654. case llvm::Triple::thumb:
  7655. return "armelf_linux_eabi";
  7656. case llvm::Triple::armeb:
  7657. case llvm::Triple::thumbeb:
  7658. return "armebelf_linux_eabi"; /* TODO: check which NAME. */
  7659. case llvm::Triple::ppc:
  7660. return "elf32ppclinux";
  7661. case llvm::Triple::ppc64:
  7662. return "elf64ppc";
  7663. case llvm::Triple::ppc64le:
  7664. return "elf64lppc";
  7665. case llvm::Triple::sparc:
  7666. case llvm::Triple::sparcel:
  7667. return "elf32_sparc";
  7668. case llvm::Triple::sparcv9:
  7669. return "elf64_sparc";
  7670. case llvm::Triple::mips:
  7671. return "elf32btsmip";
  7672. case llvm::Triple::mipsel:
  7673. return "elf32ltsmip";
  7674. case llvm::Triple::mips64:
  7675. if (mips::hasMipsAbiArg(Args, "n32"))
  7676. return "elf32btsmipn32";
  7677. return "elf64btsmip";
  7678. case llvm::Triple::mips64el:
  7679. if (mips::hasMipsAbiArg(Args, "n32"))
  7680. return "elf32ltsmipn32";
  7681. return "elf64ltsmip";
  7682. case llvm::Triple::systemz:
  7683. return "elf64_s390";
  7684. case llvm::Triple::x86_64:
  7685. if (T.getEnvironment() == llvm::Triple::GNUX32)
  7686. return "elf32_x86_64";
  7687. return "elf_x86_64";
  7688. default:
  7689. llvm_unreachable("Unexpected arch");
  7690. }
  7691. }
  7692. void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7693. const InputInfo &Output,
  7694. const InputInfoList &Inputs,
  7695. const ArgList &Args,
  7696. const char *LinkingOutput) const {
  7697. const toolchains::Linux &ToolChain =
  7698. static_cast<const toolchains::Linux &>(getToolChain());
  7699. const Driver &D = ToolChain.getDriver();
  7700. std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
  7701. llvm::Triple Triple = llvm::Triple(TripleStr);
  7702. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7703. const bool isAndroid = ToolChain.getTriple().isAndroid();
  7704. const bool IsPIE =
  7705. !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
  7706. (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
  7707. const bool HasCRTBeginEndFiles =
  7708. ToolChain.getTriple().hasEnvironment() ||
  7709. (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
  7710. ArgStringList CmdArgs;
  7711. // Silence warning for "clang -g foo.o -o foo"
  7712. Args.ClaimAllArgs(options::OPT_g_Group);
  7713. // and "clang -emit-llvm foo.o -o foo"
  7714. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7715. // and for "clang -w foo.o -o foo". Other warning options are already
  7716. // handled somewhere else.
  7717. Args.ClaimAllArgs(options::OPT_w);
  7718. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  7719. if (llvm::sys::path::filename(Exec) == "lld") {
  7720. CmdArgs.push_back("-flavor");
  7721. CmdArgs.push_back("old-gnu");
  7722. CmdArgs.push_back("-target");
  7723. CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
  7724. }
  7725. if (!D.SysRoot.empty())
  7726. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7727. if (IsPIE)
  7728. CmdArgs.push_back("-pie");
  7729. if (Args.hasArg(options::OPT_rdynamic))
  7730. CmdArgs.push_back("-export-dynamic");
  7731. if (Args.hasArg(options::OPT_s))
  7732. CmdArgs.push_back("-s");
  7733. if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
  7734. arm::appendEBLinkFlags(Args, CmdArgs, Triple);
  7735. for (const auto &Opt : ToolChain.ExtraOpts)
  7736. CmdArgs.push_back(Opt.c_str());
  7737. if (!Args.hasArg(options::OPT_static)) {
  7738. CmdArgs.push_back("--eh-frame-hdr");
  7739. }
  7740. CmdArgs.push_back("-m");
  7741. CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
  7742. if (Args.hasArg(options::OPT_static)) {
  7743. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7744. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
  7745. CmdArgs.push_back("-Bstatic");
  7746. else
  7747. CmdArgs.push_back("-static");
  7748. } else if (Args.hasArg(options::OPT_shared)) {
  7749. CmdArgs.push_back("-shared");
  7750. }
  7751. if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
  7752. Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
  7753. (!Args.hasArg(options::OPT_static) &&
  7754. !Args.hasArg(options::OPT_shared))) {
  7755. CmdArgs.push_back("-dynamic-linker");
  7756. CmdArgs.push_back(Args.MakeArgString(
  7757. D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
  7758. }
  7759. CmdArgs.push_back("-o");
  7760. CmdArgs.push_back(Output.getFilename());
  7761. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7762. if (!isAndroid) {
  7763. const char *crt1 = nullptr;
  7764. if (!Args.hasArg(options::OPT_shared)) {
  7765. if (Args.hasArg(options::OPT_pg))
  7766. crt1 = "gcrt1.o";
  7767. else if (IsPIE)
  7768. crt1 = "Scrt1.o";
  7769. else
  7770. crt1 = "crt1.o";
  7771. }
  7772. if (crt1)
  7773. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  7774. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7775. }
  7776. const char *crtbegin;
  7777. if (Args.hasArg(options::OPT_static))
  7778. crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
  7779. else if (Args.hasArg(options::OPT_shared))
  7780. crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
  7781. else if (IsPIE)
  7782. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
  7783. else
  7784. crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
  7785. if (HasCRTBeginEndFiles)
  7786. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7787. // Add crtfastmath.o if available and fast math is enabled.
  7788. ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  7789. }
  7790. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7791. Args.AddAllArgs(CmdArgs, options::OPT_u);
  7792. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7793. if (D.isUsingLTO())
  7794. AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
  7795. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7796. CmdArgs.push_back("--no-demangle");
  7797. bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
  7798. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7799. // The profile runtime also needs access to system libraries.
  7800. getToolChain().addProfileRTLibs(Args, CmdArgs);
  7801. if (D.CCCIsCXX() &&
  7802. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7803. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  7804. !Args.hasArg(options::OPT_static);
  7805. if (OnlyLibstdcxxStatic)
  7806. CmdArgs.push_back("-Bstatic");
  7807. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7808. if (OnlyLibstdcxxStatic)
  7809. CmdArgs.push_back("-Bdynamic");
  7810. CmdArgs.push_back("-lm");
  7811. }
  7812. // Silence warnings when linking C code with a C++ '-stdlib' argument.
  7813. Args.ClaimAllArgs(options::OPT_stdlib_EQ);
  7814. if (!Args.hasArg(options::OPT_nostdlib)) {
  7815. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  7816. if (Args.hasArg(options::OPT_static))
  7817. CmdArgs.push_back("--start-group");
  7818. if (NeedsSanitizerDeps)
  7819. linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
  7820. bool WantPthread = Args.hasArg(options::OPT_pthread) ||
  7821. Args.hasArg(options::OPT_pthreads);
  7822. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  7823. options::OPT_fno_openmp, false)) {
  7824. // OpenMP runtimes implies pthreads when using the GNU toolchain.
  7825. // FIXME: Does this really make sense for all GNU toolchains?
  7826. WantPthread = true;
  7827. // Also link the particular OpenMP runtimes.
  7828. switch (getOpenMPRuntime(ToolChain, Args)) {
  7829. case OMPRT_OMP:
  7830. CmdArgs.push_back("-lomp");
  7831. break;
  7832. case OMPRT_GOMP:
  7833. CmdArgs.push_back("-lgomp");
  7834. // FIXME: Exclude this for platforms with libgomp that don't require
  7835. // librt. Most modern Linux platforms require it, but some may not.
  7836. CmdArgs.push_back("-lrt");
  7837. break;
  7838. case OMPRT_IOMP5:
  7839. CmdArgs.push_back("-liomp5");
  7840. break;
  7841. case OMPRT_Unknown:
  7842. // Already diagnosed.
  7843. break;
  7844. }
  7845. }
  7846. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7847. if (WantPthread && !isAndroid)
  7848. CmdArgs.push_back("-lpthread");
  7849. if (Args.hasArg(options::OPT_fsplit_stack))
  7850. CmdArgs.push_back("--wrap=pthread_create");
  7851. CmdArgs.push_back("-lc");
  7852. if (Args.hasArg(options::OPT_static))
  7853. CmdArgs.push_back("--end-group");
  7854. else
  7855. AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
  7856. }
  7857. if (!Args.hasArg(options::OPT_nostartfiles)) {
  7858. const char *crtend;
  7859. if (Args.hasArg(options::OPT_shared))
  7860. crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
  7861. else if (IsPIE)
  7862. crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
  7863. else
  7864. crtend = isAndroid ? "crtend_android.o" : "crtend.o";
  7865. if (HasCRTBeginEndFiles)
  7866. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  7867. if (!isAndroid)
  7868. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  7869. }
  7870. }
  7871. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  7872. }
  7873. // NaCl ARM assembly (inline or standalone) can be written with a set of macros
  7874. // for the various SFI requirements like register masking. The assembly tool
  7875. // inserts the file containing the macros as an input into all the assembly
  7876. // jobs.
  7877. void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
  7878. const InputInfo &Output,
  7879. const InputInfoList &Inputs,
  7880. const ArgList &Args,
  7881. const char *LinkingOutput) const {
  7882. const toolchains::NaClToolChain &ToolChain =
  7883. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  7884. InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
  7885. "nacl-arm-macros.s");
  7886. InputInfoList NewInputs;
  7887. NewInputs.push_back(NaClMacros);
  7888. NewInputs.append(Inputs.begin(), Inputs.end());
  7889. gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
  7890. LinkingOutput);
  7891. }
  7892. // This is quite similar to gnutools::Linker::ConstructJob with changes that
  7893. // we use static by default, do not yet support sanitizers or LTO, and a few
  7894. // others. Eventually we can support more of that and hopefully migrate back
  7895. // to gnutools::Linker.
  7896. void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  7897. const InputInfo &Output,
  7898. const InputInfoList &Inputs,
  7899. const ArgList &Args,
  7900. const char *LinkingOutput) const {
  7901. const toolchains::NaClToolChain &ToolChain =
  7902. static_cast<const toolchains::NaClToolChain &>(getToolChain());
  7903. const Driver &D = ToolChain.getDriver();
  7904. const llvm::Triple::ArchType Arch = ToolChain.getArch();
  7905. const bool IsStatic =
  7906. !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
  7907. ArgStringList CmdArgs;
  7908. // Silence warning for "clang -g foo.o -o foo"
  7909. Args.ClaimAllArgs(options::OPT_g_Group);
  7910. // and "clang -emit-llvm foo.o -o foo"
  7911. Args.ClaimAllArgs(options::OPT_emit_llvm);
  7912. // and for "clang -w foo.o -o foo". Other warning options are already
  7913. // handled somewhere else.
  7914. Args.ClaimAllArgs(options::OPT_w);
  7915. if (!D.SysRoot.empty())
  7916. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  7917. if (Args.hasArg(options::OPT_rdynamic))
  7918. CmdArgs.push_back("-export-dynamic");
  7919. if (Args.hasArg(options::OPT_s))
  7920. CmdArgs.push_back("-s");
  7921. // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
  7922. // from there is --build-id, which we do want.
  7923. CmdArgs.push_back("--build-id");
  7924. if (!IsStatic)
  7925. CmdArgs.push_back("--eh-frame-hdr");
  7926. CmdArgs.push_back("-m");
  7927. if (Arch == llvm::Triple::x86)
  7928. CmdArgs.push_back("elf_i386_nacl");
  7929. else if (Arch == llvm::Triple::arm)
  7930. CmdArgs.push_back("armelf_nacl");
  7931. else if (Arch == llvm::Triple::x86_64)
  7932. CmdArgs.push_back("elf_x86_64_nacl");
  7933. else if (Arch == llvm::Triple::mipsel)
  7934. CmdArgs.push_back("mipselelf_nacl");
  7935. else
  7936. D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
  7937. << "Native Client";
  7938. if (IsStatic)
  7939. CmdArgs.push_back("-static");
  7940. else if (Args.hasArg(options::OPT_shared))
  7941. CmdArgs.push_back("-shared");
  7942. CmdArgs.push_back("-o");
  7943. CmdArgs.push_back(Output.getFilename());
  7944. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  7945. if (!Args.hasArg(options::OPT_shared))
  7946. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
  7947. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  7948. const char *crtbegin;
  7949. if (IsStatic)
  7950. crtbegin = "crtbeginT.o";
  7951. else if (Args.hasArg(options::OPT_shared))
  7952. crtbegin = "crtbeginS.o";
  7953. else
  7954. crtbegin = "crtbegin.o";
  7955. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  7956. }
  7957. Args.AddAllArgs(CmdArgs, options::OPT_L);
  7958. Args.AddAllArgs(CmdArgs, options::OPT_u);
  7959. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  7960. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  7961. CmdArgs.push_back("--no-demangle");
  7962. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  7963. if (D.CCCIsCXX() &&
  7964. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  7965. bool OnlyLibstdcxxStatic =
  7966. Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
  7967. if (OnlyLibstdcxxStatic)
  7968. CmdArgs.push_back("-Bstatic");
  7969. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  7970. if (OnlyLibstdcxxStatic)
  7971. CmdArgs.push_back("-Bdynamic");
  7972. CmdArgs.push_back("-lm");
  7973. }
  7974. if (!Args.hasArg(options::OPT_nostdlib)) {
  7975. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  7976. // Always use groups, since it has no effect on dynamic libraries.
  7977. CmdArgs.push_back("--start-group");
  7978. CmdArgs.push_back("-lc");
  7979. // NaCl's libc++ currently requires libpthread, so just always include it
  7980. // in the group for C++.
  7981. if (Args.hasArg(options::OPT_pthread) ||
  7982. Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
  7983. // Gold, used by Mips, handles nested groups differently than ld, and
  7984. // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
  7985. // which is not a desired behaviour here.
  7986. // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
  7987. if (getToolChain().getArch() == llvm::Triple::mipsel)
  7988. CmdArgs.push_back("-lnacl");
  7989. CmdArgs.push_back("-lpthread");
  7990. }
  7991. CmdArgs.push_back("-lgcc");
  7992. CmdArgs.push_back("--as-needed");
  7993. if (IsStatic)
  7994. CmdArgs.push_back("-lgcc_eh");
  7995. else
  7996. CmdArgs.push_back("-lgcc_s");
  7997. CmdArgs.push_back("--no-as-needed");
  7998. // Mips needs to create and use pnacl_legacy library that contains
  7999. // definitions from bitcode/pnaclmm.c and definitions for
  8000. // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
  8001. if (getToolChain().getArch() == llvm::Triple::mipsel)
  8002. CmdArgs.push_back("-lpnacl_legacy");
  8003. CmdArgs.push_back("--end-group");
  8004. }
  8005. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8006. const char *crtend;
  8007. if (Args.hasArg(options::OPT_shared))
  8008. crtend = "crtendS.o";
  8009. else
  8010. crtend = "crtend.o";
  8011. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
  8012. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  8013. }
  8014. }
  8015. const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
  8016. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8017. }
  8018. void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8019. const InputInfo &Output,
  8020. const InputInfoList &Inputs,
  8021. const ArgList &Args,
  8022. const char *LinkingOutput) const {
  8023. claimNoWarnArgs(Args);
  8024. ArgStringList CmdArgs;
  8025. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8026. CmdArgs.push_back("-o");
  8027. CmdArgs.push_back(Output.getFilename());
  8028. for (const auto &II : Inputs)
  8029. CmdArgs.push_back(II.getFilename());
  8030. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8031. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8032. }
  8033. void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8034. const InputInfo &Output,
  8035. const InputInfoList &Inputs,
  8036. const ArgList &Args,
  8037. const char *LinkingOutput) const {
  8038. const Driver &D = getToolChain().getDriver();
  8039. ArgStringList CmdArgs;
  8040. if (Output.isFilename()) {
  8041. CmdArgs.push_back("-o");
  8042. CmdArgs.push_back(Output.getFilename());
  8043. } else {
  8044. assert(Output.isNothing() && "Invalid output.");
  8045. }
  8046. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8047. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8048. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8049. CmdArgs.push_back(
  8050. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8051. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8052. }
  8053. Args.AddAllArgs(CmdArgs,
  8054. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8055. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8056. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8057. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8058. if (D.CCCIsCXX()) {
  8059. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8060. CmdArgs.push_back("-lm");
  8061. }
  8062. }
  8063. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8064. if (Args.hasArg(options::OPT_pthread))
  8065. CmdArgs.push_back("-lpthread");
  8066. CmdArgs.push_back("-lc");
  8067. CmdArgs.push_back("-lCompilerRT-Generic");
  8068. CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
  8069. CmdArgs.push_back(
  8070. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8071. }
  8072. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8073. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8074. }
  8075. /// DragonFly Tools
  8076. // For now, DragonFly Assemble does just about the same as for
  8077. // FreeBSD, but this may change soon.
  8078. void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8079. const InputInfo &Output,
  8080. const InputInfoList &Inputs,
  8081. const ArgList &Args,
  8082. const char *LinkingOutput) const {
  8083. claimNoWarnArgs(Args);
  8084. ArgStringList CmdArgs;
  8085. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8086. // instruct as in the base system to assemble 32-bit code.
  8087. if (getToolChain().getArch() == llvm::Triple::x86)
  8088. CmdArgs.push_back("--32");
  8089. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8090. CmdArgs.push_back("-o");
  8091. CmdArgs.push_back(Output.getFilename());
  8092. for (const auto &II : Inputs)
  8093. CmdArgs.push_back(II.getFilename());
  8094. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8095. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8096. }
  8097. void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8098. const InputInfo &Output,
  8099. const InputInfoList &Inputs,
  8100. const ArgList &Args,
  8101. const char *LinkingOutput) const {
  8102. const Driver &D = getToolChain().getDriver();
  8103. ArgStringList CmdArgs;
  8104. if (!D.SysRoot.empty())
  8105. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8106. CmdArgs.push_back("--eh-frame-hdr");
  8107. if (Args.hasArg(options::OPT_static)) {
  8108. CmdArgs.push_back("-Bstatic");
  8109. } else {
  8110. if (Args.hasArg(options::OPT_rdynamic))
  8111. CmdArgs.push_back("-export-dynamic");
  8112. if (Args.hasArg(options::OPT_shared))
  8113. CmdArgs.push_back("-Bshareable");
  8114. else {
  8115. CmdArgs.push_back("-dynamic-linker");
  8116. CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
  8117. }
  8118. CmdArgs.push_back("--hash-style=gnu");
  8119. CmdArgs.push_back("--enable-new-dtags");
  8120. }
  8121. // When building 32-bit code on DragonFly/pc64, we have to explicitly
  8122. // instruct ld in the base system to link 32-bit code.
  8123. if (getToolChain().getArch() == llvm::Triple::x86) {
  8124. CmdArgs.push_back("-m");
  8125. CmdArgs.push_back("elf_i386");
  8126. }
  8127. if (Output.isFilename()) {
  8128. CmdArgs.push_back("-o");
  8129. CmdArgs.push_back(Output.getFilename());
  8130. } else {
  8131. assert(Output.isNothing() && "Invalid output.");
  8132. }
  8133. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8134. if (!Args.hasArg(options::OPT_shared)) {
  8135. if (Args.hasArg(options::OPT_pg))
  8136. CmdArgs.push_back(
  8137. Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
  8138. else {
  8139. if (Args.hasArg(options::OPT_pie))
  8140. CmdArgs.push_back(
  8141. Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
  8142. else
  8143. CmdArgs.push_back(
  8144. Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
  8145. }
  8146. }
  8147. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
  8148. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8149. CmdArgs.push_back(
  8150. Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
  8151. else
  8152. CmdArgs.push_back(
  8153. Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
  8154. }
  8155. Args.AddAllArgs(CmdArgs,
  8156. {options::OPT_L, options::OPT_T_Group, options::OPT_e});
  8157. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8158. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8159. CmdArgs.push_back("-L/usr/lib/gcc50");
  8160. if (!Args.hasArg(options::OPT_static)) {
  8161. CmdArgs.push_back("-rpath");
  8162. CmdArgs.push_back("/usr/lib/gcc50");
  8163. }
  8164. if (D.CCCIsCXX()) {
  8165. getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
  8166. CmdArgs.push_back("-lm");
  8167. }
  8168. if (Args.hasArg(options::OPT_pthread))
  8169. CmdArgs.push_back("-lpthread");
  8170. if (!Args.hasArg(options::OPT_nolibc)) {
  8171. CmdArgs.push_back("-lc");
  8172. }
  8173. if (Args.hasArg(options::OPT_static) ||
  8174. Args.hasArg(options::OPT_static_libgcc)) {
  8175. CmdArgs.push_back("-lgcc");
  8176. CmdArgs.push_back("-lgcc_eh");
  8177. } else {
  8178. if (Args.hasArg(options::OPT_shared_libgcc)) {
  8179. CmdArgs.push_back("-lgcc_pic");
  8180. if (!Args.hasArg(options::OPT_shared))
  8181. CmdArgs.push_back("-lgcc");
  8182. } else {
  8183. CmdArgs.push_back("-lgcc");
  8184. CmdArgs.push_back("--as-needed");
  8185. CmdArgs.push_back("-lgcc_pic");
  8186. CmdArgs.push_back("--no-as-needed");
  8187. }
  8188. }
  8189. }
  8190. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8191. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  8192. CmdArgs.push_back(
  8193. Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
  8194. else
  8195. CmdArgs.push_back(
  8196. Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
  8197. CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
  8198. }
  8199. getToolChain().addProfileRTLibs(Args, CmdArgs);
  8200. const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
  8201. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8202. }
  8203. // Try to find Exe from a Visual Studio distribution. This first tries to find
  8204. // an installed copy of Visual Studio and, failing that, looks in the PATH,
  8205. // making sure that whatever executable that's found is not a same-named exe
  8206. // from clang itself to prevent clang from falling back to itself.
  8207. static std::string FindVisualStudioExecutable(const ToolChain &TC,
  8208. const char *Exe,
  8209. const char *ClangProgramPath) {
  8210. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8211. std::string visualStudioBinDir;
  8212. if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
  8213. visualStudioBinDir)) {
  8214. SmallString<128> FilePath(visualStudioBinDir);
  8215. llvm::sys::path::append(FilePath, Exe);
  8216. if (llvm::sys::fs::can_execute(FilePath.c_str()))
  8217. return FilePath.str();
  8218. }
  8219. return Exe;
  8220. }
  8221. void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8222. const InputInfo &Output,
  8223. const InputInfoList &Inputs,
  8224. const ArgList &Args,
  8225. const char *LinkingOutput) const {
  8226. ArgStringList CmdArgs;
  8227. const ToolChain &TC = getToolChain();
  8228. assert((Output.isFilename() || Output.isNothing()) && "invalid output");
  8229. if (Output.isFilename())
  8230. CmdArgs.push_back(
  8231. Args.MakeArgString(std::string("-out:") + Output.getFilename()));
  8232. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
  8233. !C.getDriver().IsCLMode())
  8234. CmdArgs.push_back("-defaultlib:libcmt");
  8235. if (!llvm::sys::Process::GetEnv("LIB")) {
  8236. // If the VC environment hasn't been configured (perhaps because the user
  8237. // did not run vcvarsall), try to build a consistent link environment. If
  8238. // the environment variable is set however, assume the user knows what
  8239. // they're doing.
  8240. std::string VisualStudioDir;
  8241. const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
  8242. if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
  8243. SmallString<128> LibDir(VisualStudioDir);
  8244. llvm::sys::path::append(LibDir, "VC", "lib");
  8245. switch (MSVC.getArch()) {
  8246. case llvm::Triple::x86:
  8247. // x86 just puts the libraries directly in lib
  8248. break;
  8249. case llvm::Triple::x86_64:
  8250. llvm::sys::path::append(LibDir, "amd64");
  8251. break;
  8252. case llvm::Triple::arm:
  8253. llvm::sys::path::append(LibDir, "arm");
  8254. break;
  8255. default:
  8256. break;
  8257. }
  8258. CmdArgs.push_back(
  8259. Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
  8260. if (MSVC.useUniversalCRT(VisualStudioDir)) {
  8261. std::string UniversalCRTLibPath;
  8262. if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
  8263. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8264. UniversalCRTLibPath.c_str()));
  8265. }
  8266. }
  8267. std::string WindowsSdkLibPath;
  8268. if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
  8269. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8270. WindowsSdkLibPath.c_str()));
  8271. }
  8272. CmdArgs.push_back("-nologo");
  8273. if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
  8274. CmdArgs.push_back("-debug");
  8275. bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
  8276. options::OPT_shared);
  8277. if (DLL) {
  8278. CmdArgs.push_back(Args.MakeArgString("-dll"));
  8279. SmallString<128> ImplibName(Output.getFilename());
  8280. llvm::sys::path::replace_extension(ImplibName, "lib");
  8281. CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
  8282. }
  8283. if (TC.getSanitizerArgs().needsAsanRt()) {
  8284. CmdArgs.push_back(Args.MakeArgString("-debug"));
  8285. CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
  8286. if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
  8287. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  8288. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8289. // Make sure the dynamic runtime thunk is not optimized out at link time
  8290. // to ensure proper SEH handling.
  8291. CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
  8292. } else if (DLL) {
  8293. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  8294. } else {
  8295. for (const auto &Lib : {"asan", "asan_cxx"})
  8296. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8297. }
  8298. }
  8299. Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
  8300. if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  8301. options::OPT_fno_openmp, false)) {
  8302. CmdArgs.push_back("-nodefaultlib:vcomp.lib");
  8303. CmdArgs.push_back("-nodefaultlib:vcompd.lib");
  8304. CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
  8305. TC.getDriver().Dir + "/../lib"));
  8306. switch (getOpenMPRuntime(getToolChain(), Args)) {
  8307. case OMPRT_OMP:
  8308. CmdArgs.push_back("-defaultlib:libomp.lib");
  8309. break;
  8310. case OMPRT_IOMP5:
  8311. CmdArgs.push_back("-defaultlib:libiomp5md.lib");
  8312. break;
  8313. case OMPRT_GOMP:
  8314. break;
  8315. case OMPRT_Unknown:
  8316. // Already diagnosed.
  8317. break;
  8318. }
  8319. }
  8320. // Add filenames, libraries, and other linker inputs.
  8321. for (const auto &Input : Inputs) {
  8322. if (Input.isFilename()) {
  8323. CmdArgs.push_back(Input.getFilename());
  8324. continue;
  8325. }
  8326. const Arg &A = Input.getInputArg();
  8327. // Render -l options differently for the MSVC linker.
  8328. if (A.getOption().matches(options::OPT_l)) {
  8329. StringRef Lib = A.getValue();
  8330. const char *LinkLibArg;
  8331. if (Lib.endswith(".lib"))
  8332. LinkLibArg = Args.MakeArgString(Lib);
  8333. else
  8334. LinkLibArg = Args.MakeArgString(Lib + ".lib");
  8335. CmdArgs.push_back(LinkLibArg);
  8336. continue;
  8337. }
  8338. // Otherwise, this is some other kind of linker input option like -Wl, -z,
  8339. // or -L. Render it, even if MSVC doesn't understand it.
  8340. A.renderAsInput(Args, CmdArgs);
  8341. }
  8342. TC.addProfileRTLibs(Args, CmdArgs);
  8343. // We need to special case some linker paths. In the case of lld, we need to
  8344. // translate 'lld' into 'lld-link', and in the case of the regular msvc
  8345. // linker, we need to use a special search algorithm.
  8346. llvm::SmallString<128> linkPath;
  8347. StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
  8348. if (Linker.equals_lower("lld"))
  8349. Linker = "lld-link";
  8350. if (Linker.equals_lower("link")) {
  8351. // If we're using the MSVC linker, it's not sufficient to just use link
  8352. // from the program PATH, because other environments like GnuWin32 install
  8353. // their own link.exe which may come first.
  8354. linkPath = FindVisualStudioExecutable(TC, "link.exe",
  8355. C.getDriver().getClangProgramPath());
  8356. } else {
  8357. linkPath = Linker;
  8358. llvm::sys::path::replace_extension(linkPath, "exe");
  8359. linkPath = TC.GetProgramPath(linkPath.c_str());
  8360. }
  8361. const char *Exec = Args.MakeArgString(linkPath);
  8362. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8363. }
  8364. void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8365. const InputInfo &Output,
  8366. const InputInfoList &Inputs,
  8367. const ArgList &Args,
  8368. const char *LinkingOutput) const {
  8369. C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
  8370. }
  8371. std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
  8372. Compilation &C, const JobAction &JA, const InputInfo &Output,
  8373. const InputInfoList &Inputs, const ArgList &Args,
  8374. const char *LinkingOutput) const {
  8375. ArgStringList CmdArgs;
  8376. CmdArgs.push_back("/nologo");
  8377. CmdArgs.push_back("/c"); // Compile only.
  8378. CmdArgs.push_back("/W0"); // No warnings.
  8379. // The goal is to be able to invoke this tool correctly based on
  8380. // any flag accepted by clang-cl.
  8381. // These are spelled the same way in clang and cl.exe,.
  8382. Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
  8383. // Optimization level.
  8384. if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
  8385. CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
  8386. : "/Oi-");
  8387. if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
  8388. if (A->getOption().getID() == options::OPT_O0) {
  8389. CmdArgs.push_back("/Od");
  8390. } else {
  8391. CmdArgs.push_back("/Og");
  8392. StringRef OptLevel = A->getValue();
  8393. if (OptLevel == "s" || OptLevel == "z")
  8394. CmdArgs.push_back("/Os");
  8395. else
  8396. CmdArgs.push_back("/Ot");
  8397. CmdArgs.push_back("/Ob2");
  8398. }
  8399. }
  8400. if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
  8401. options::OPT_fno_omit_frame_pointer))
  8402. CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
  8403. ? "/Oy"
  8404. : "/Oy-");
  8405. if (!Args.hasArg(options::OPT_fwritable_strings))
  8406. CmdArgs.push_back("/GF");
  8407. // Flags for which clang-cl has an alias.
  8408. // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
  8409. if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
  8410. /*default=*/false))
  8411. CmdArgs.push_back("/GR-");
  8412. if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
  8413. options::OPT_fno_function_sections))
  8414. CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
  8415. ? "/Gy"
  8416. : "/Gy-");
  8417. if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
  8418. options::OPT_fno_data_sections))
  8419. CmdArgs.push_back(
  8420. A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
  8421. if (Args.hasArg(options::OPT_fsyntax_only))
  8422. CmdArgs.push_back("/Zs");
  8423. if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
  8424. options::OPT__SLASH_Z7))
  8425. CmdArgs.push_back("/Z7");
  8426. std::vector<std::string> Includes =
  8427. Args.getAllArgValues(options::OPT_include);
  8428. for (const auto &Include : Includes)
  8429. CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
  8430. // Flags that can simply be passed through.
  8431. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
  8432. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
  8433. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
  8434. Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
  8435. // The order of these flags is relevant, so pick the last one.
  8436. if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
  8437. options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
  8438. A->render(Args, CmdArgs);
  8439. // Pass through all unknown arguments so that the fallback command can see
  8440. // them too.
  8441. Args.AddAllArgs(CmdArgs, options::OPT_UNKNOWN);
  8442. // Input filename.
  8443. assert(Inputs.size() == 1);
  8444. const InputInfo &II = Inputs[0];
  8445. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
  8446. CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
  8447. if (II.isFilename())
  8448. CmdArgs.push_back(II.getFilename());
  8449. else
  8450. II.getInputArg().renderAsInput(Args, CmdArgs);
  8451. // Output filename.
  8452. assert(Output.getType() == types::TY_Object);
  8453. const char *Fo =
  8454. Args.MakeArgString(std::string("/Fo") + Output.getFilename());
  8455. CmdArgs.push_back(Fo);
  8456. const Driver &D = getToolChain().getDriver();
  8457. std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
  8458. D.getClangProgramPath());
  8459. return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8460. CmdArgs, Inputs);
  8461. }
  8462. /// MinGW Tools
  8463. void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8464. const InputInfo &Output,
  8465. const InputInfoList &Inputs,
  8466. const ArgList &Args,
  8467. const char *LinkingOutput) const {
  8468. claimNoWarnArgs(Args);
  8469. ArgStringList CmdArgs;
  8470. if (getToolChain().getArch() == llvm::Triple::x86) {
  8471. CmdArgs.push_back("--32");
  8472. } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
  8473. CmdArgs.push_back("--64");
  8474. }
  8475. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8476. CmdArgs.push_back("-o");
  8477. CmdArgs.push_back(Output.getFilename());
  8478. for (const auto &II : Inputs)
  8479. CmdArgs.push_back(II.getFilename());
  8480. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
  8481. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8482. if (Args.hasArg(options::OPT_gsplit_dwarf))
  8483. SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
  8484. SplitDebugName(Args, Inputs[0]));
  8485. }
  8486. void MinGW::Linker::AddLibGCC(const ArgList &Args,
  8487. ArgStringList &CmdArgs) const {
  8488. if (Args.hasArg(options::OPT_mthreads))
  8489. CmdArgs.push_back("-lmingwthrd");
  8490. CmdArgs.push_back("-lmingw32");
  8491. // Make use of compiler-rt if --rtlib option is used
  8492. ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
  8493. if (RLT == ToolChain::RLT_Libgcc) {
  8494. bool Static = Args.hasArg(options::OPT_static_libgcc) ||
  8495. Args.hasArg(options::OPT_static);
  8496. bool Shared = Args.hasArg(options::OPT_shared);
  8497. bool CXX = getToolChain().getDriver().CCCIsCXX();
  8498. if (Static || (!CXX && !Shared)) {
  8499. CmdArgs.push_back("-lgcc");
  8500. CmdArgs.push_back("-lgcc_eh");
  8501. } else {
  8502. CmdArgs.push_back("-lgcc_s");
  8503. CmdArgs.push_back("-lgcc");
  8504. }
  8505. } else {
  8506. AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
  8507. }
  8508. CmdArgs.push_back("-lmoldname");
  8509. CmdArgs.push_back("-lmingwex");
  8510. CmdArgs.push_back("-lmsvcrt");
  8511. }
  8512. void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8513. const InputInfo &Output,
  8514. const InputInfoList &Inputs,
  8515. const ArgList &Args,
  8516. const char *LinkingOutput) const {
  8517. const ToolChain &TC = getToolChain();
  8518. const Driver &D = TC.getDriver();
  8519. // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
  8520. ArgStringList CmdArgs;
  8521. // Silence warning for "clang -g foo.o -o foo"
  8522. Args.ClaimAllArgs(options::OPT_g_Group);
  8523. // and "clang -emit-llvm foo.o -o foo"
  8524. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8525. // and for "clang -w foo.o -o foo". Other warning options are already
  8526. // handled somewhere else.
  8527. Args.ClaimAllArgs(options::OPT_w);
  8528. StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
  8529. if (LinkerName.equals_lower("lld")) {
  8530. CmdArgs.push_back("-flavor");
  8531. CmdArgs.push_back("gnu");
  8532. } else if (!LinkerName.equals_lower("ld")) {
  8533. D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
  8534. }
  8535. if (!D.SysRoot.empty())
  8536. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8537. if (Args.hasArg(options::OPT_s))
  8538. CmdArgs.push_back("-s");
  8539. CmdArgs.push_back("-m");
  8540. if (TC.getArch() == llvm::Triple::x86)
  8541. CmdArgs.push_back("i386pe");
  8542. if (TC.getArch() == llvm::Triple::x86_64)
  8543. CmdArgs.push_back("i386pep");
  8544. if (TC.getArch() == llvm::Triple::arm)
  8545. CmdArgs.push_back("thumb2pe");
  8546. if (Args.hasArg(options::OPT_mwindows)) {
  8547. CmdArgs.push_back("--subsystem");
  8548. CmdArgs.push_back("windows");
  8549. } else if (Args.hasArg(options::OPT_mconsole)) {
  8550. CmdArgs.push_back("--subsystem");
  8551. CmdArgs.push_back("console");
  8552. }
  8553. if (Args.hasArg(options::OPT_static))
  8554. CmdArgs.push_back("-Bstatic");
  8555. else {
  8556. if (Args.hasArg(options::OPT_mdll))
  8557. CmdArgs.push_back("--dll");
  8558. else if (Args.hasArg(options::OPT_shared))
  8559. CmdArgs.push_back("--shared");
  8560. CmdArgs.push_back("-Bdynamic");
  8561. if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
  8562. CmdArgs.push_back("-e");
  8563. if (TC.getArch() == llvm::Triple::x86)
  8564. CmdArgs.push_back("_DllMainCRTStartup@12");
  8565. else
  8566. CmdArgs.push_back("DllMainCRTStartup");
  8567. CmdArgs.push_back("--enable-auto-image-base");
  8568. }
  8569. }
  8570. CmdArgs.push_back("-o");
  8571. CmdArgs.push_back(Output.getFilename());
  8572. Args.AddAllArgs(CmdArgs, options::OPT_e);
  8573. // FIXME: add -N, -n flags
  8574. Args.AddLastArg(CmdArgs, options::OPT_r);
  8575. Args.AddLastArg(CmdArgs, options::OPT_s);
  8576. Args.AddLastArg(CmdArgs, options::OPT_t);
  8577. Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
  8578. Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
  8579. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8580. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
  8581. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
  8582. } else {
  8583. if (Args.hasArg(options::OPT_municode))
  8584. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
  8585. else
  8586. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
  8587. }
  8588. if (Args.hasArg(options::OPT_pg))
  8589. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
  8590. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8591. }
  8592. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8593. TC.AddFilePathLibArgs(Args, CmdArgs);
  8594. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8595. // TODO: Add ASan stuff here
  8596. // TODO: Add profile stuff here
  8597. if (D.CCCIsCXX() &&
  8598. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  8599. bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
  8600. !Args.hasArg(options::OPT_static);
  8601. if (OnlyLibstdcxxStatic)
  8602. CmdArgs.push_back("-Bstatic");
  8603. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8604. if (OnlyLibstdcxxStatic)
  8605. CmdArgs.push_back("-Bdynamic");
  8606. }
  8607. if (!Args.hasArg(options::OPT_nostdlib)) {
  8608. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8609. if (Args.hasArg(options::OPT_static))
  8610. CmdArgs.push_back("--start-group");
  8611. if (Args.hasArg(options::OPT_fstack_protector) ||
  8612. Args.hasArg(options::OPT_fstack_protector_strong) ||
  8613. Args.hasArg(options::OPT_fstack_protector_all)) {
  8614. CmdArgs.push_back("-lssp_nonshared");
  8615. CmdArgs.push_back("-lssp");
  8616. }
  8617. if (Args.hasArg(options::OPT_fopenmp))
  8618. CmdArgs.push_back("-lgomp");
  8619. AddLibGCC(Args, CmdArgs);
  8620. if (Args.hasArg(options::OPT_pg))
  8621. CmdArgs.push_back("-lgmon");
  8622. if (Args.hasArg(options::OPT_pthread))
  8623. CmdArgs.push_back("-lpthread");
  8624. // add system libraries
  8625. if (Args.hasArg(options::OPT_mwindows)) {
  8626. CmdArgs.push_back("-lgdi32");
  8627. CmdArgs.push_back("-lcomdlg32");
  8628. }
  8629. CmdArgs.push_back("-ladvapi32");
  8630. CmdArgs.push_back("-lshell32");
  8631. CmdArgs.push_back("-luser32");
  8632. CmdArgs.push_back("-lkernel32");
  8633. if (Args.hasArg(options::OPT_static))
  8634. CmdArgs.push_back("--end-group");
  8635. else if (!LinkerName.equals_lower("lld"))
  8636. AddLibGCC(Args, CmdArgs);
  8637. }
  8638. if (!Args.hasArg(options::OPT_nostartfiles)) {
  8639. // Add crtfastmath.o if available and fast math is enabled.
  8640. TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
  8641. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8642. }
  8643. }
  8644. const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
  8645. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8646. }
  8647. /// XCore Tools
  8648. // We pass assemble and link construction to the xcc tool.
  8649. void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8650. const InputInfo &Output,
  8651. const InputInfoList &Inputs,
  8652. const ArgList &Args,
  8653. const char *LinkingOutput) const {
  8654. claimNoWarnArgs(Args);
  8655. ArgStringList CmdArgs;
  8656. CmdArgs.push_back("-o");
  8657. CmdArgs.push_back(Output.getFilename());
  8658. CmdArgs.push_back("-c");
  8659. if (Args.hasArg(options::OPT_v))
  8660. CmdArgs.push_back("-v");
  8661. if (Arg *A = Args.getLastArg(options::OPT_g_Group))
  8662. if (!A->getOption().matches(options::OPT_g0))
  8663. CmdArgs.push_back("-g");
  8664. if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
  8665. false))
  8666. CmdArgs.push_back("-fverbose-asm");
  8667. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8668. for (const auto &II : Inputs)
  8669. CmdArgs.push_back(II.getFilename());
  8670. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8671. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8672. }
  8673. void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8674. const InputInfo &Output,
  8675. const InputInfoList &Inputs,
  8676. const ArgList &Args,
  8677. const char *LinkingOutput) const {
  8678. ArgStringList CmdArgs;
  8679. if (Output.isFilename()) {
  8680. CmdArgs.push_back("-o");
  8681. CmdArgs.push_back(Output.getFilename());
  8682. } else {
  8683. assert(Output.isNothing() && "Invalid output.");
  8684. }
  8685. if (Args.hasArg(options::OPT_v))
  8686. CmdArgs.push_back("-v");
  8687. // Pass -fexceptions through to the linker if it was present.
  8688. if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
  8689. false))
  8690. CmdArgs.push_back("-fexceptions");
  8691. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8692. const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
  8693. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8694. }
  8695. void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8696. const InputInfo &Output,
  8697. const InputInfoList &Inputs,
  8698. const ArgList &Args,
  8699. const char *LinkingOutput) const {
  8700. claimNoWarnArgs(Args);
  8701. const auto &TC =
  8702. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8703. ArgStringList CmdArgs;
  8704. const char *Exec;
  8705. switch (TC.getArch()) {
  8706. default:
  8707. llvm_unreachable("unsupported architecture");
  8708. case llvm::Triple::arm:
  8709. case llvm::Triple::thumb:
  8710. break;
  8711. case llvm::Triple::x86:
  8712. CmdArgs.push_back("--32");
  8713. break;
  8714. case llvm::Triple::x86_64:
  8715. CmdArgs.push_back("--64");
  8716. break;
  8717. }
  8718. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8719. CmdArgs.push_back("-o");
  8720. CmdArgs.push_back(Output.getFilename());
  8721. for (const auto &Input : Inputs)
  8722. CmdArgs.push_back(Input.getFilename());
  8723. const std::string Assembler = TC.GetProgramPath("as");
  8724. Exec = Args.MakeArgString(Assembler);
  8725. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8726. }
  8727. void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8728. const InputInfo &Output,
  8729. const InputInfoList &Inputs,
  8730. const ArgList &Args,
  8731. const char *LinkingOutput) const {
  8732. const auto &TC =
  8733. static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
  8734. const llvm::Triple &T = TC.getTriple();
  8735. const Driver &D = TC.getDriver();
  8736. SmallString<128> EntryPoint;
  8737. ArgStringList CmdArgs;
  8738. const char *Exec;
  8739. // Silence warning for "clang -g foo.o -o foo"
  8740. Args.ClaimAllArgs(options::OPT_g_Group);
  8741. // and "clang -emit-llvm foo.o -o foo"
  8742. Args.ClaimAllArgs(options::OPT_emit_llvm);
  8743. // and for "clang -w foo.o -o foo"
  8744. Args.ClaimAllArgs(options::OPT_w);
  8745. // Other warning options are already handled somewhere else.
  8746. if (!D.SysRoot.empty())
  8747. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  8748. if (Args.hasArg(options::OPT_pie))
  8749. CmdArgs.push_back("-pie");
  8750. if (Args.hasArg(options::OPT_rdynamic))
  8751. CmdArgs.push_back("-export-dynamic");
  8752. if (Args.hasArg(options::OPT_s))
  8753. CmdArgs.push_back("--strip-all");
  8754. CmdArgs.push_back("-m");
  8755. switch (TC.getArch()) {
  8756. default:
  8757. llvm_unreachable("unsupported architecture");
  8758. case llvm::Triple::arm:
  8759. case llvm::Triple::thumb:
  8760. // FIXME: this is incorrect for WinCE
  8761. CmdArgs.push_back("thumb2pe");
  8762. break;
  8763. case llvm::Triple::x86:
  8764. CmdArgs.push_back("i386pe");
  8765. EntryPoint.append("_");
  8766. break;
  8767. case llvm::Triple::x86_64:
  8768. CmdArgs.push_back("i386pep");
  8769. break;
  8770. }
  8771. if (Args.hasArg(options::OPT_shared)) {
  8772. switch (T.getArch()) {
  8773. default:
  8774. llvm_unreachable("unsupported architecture");
  8775. case llvm::Triple::arm:
  8776. case llvm::Triple::thumb:
  8777. case llvm::Triple::x86_64:
  8778. EntryPoint.append("_DllMainCRTStartup");
  8779. break;
  8780. case llvm::Triple::x86:
  8781. EntryPoint.append("_DllMainCRTStartup@12");
  8782. break;
  8783. }
  8784. CmdArgs.push_back("-shared");
  8785. CmdArgs.push_back("-Bdynamic");
  8786. CmdArgs.push_back("--enable-auto-image-base");
  8787. CmdArgs.push_back("--entry");
  8788. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  8789. } else {
  8790. EntryPoint.append("mainCRTStartup");
  8791. CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
  8792. : "-Bdynamic");
  8793. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8794. CmdArgs.push_back("--entry");
  8795. CmdArgs.push_back(Args.MakeArgString(EntryPoint));
  8796. }
  8797. // FIXME: handle subsystem
  8798. }
  8799. // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
  8800. CmdArgs.push_back("--allow-multiple-definition");
  8801. CmdArgs.push_back("-o");
  8802. CmdArgs.push_back(Output.getFilename());
  8803. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
  8804. SmallString<261> ImpLib(Output.getFilename());
  8805. llvm::sys::path::replace_extension(ImpLib, ".lib");
  8806. CmdArgs.push_back("--out-implib");
  8807. CmdArgs.push_back(Args.MakeArgString(ImpLib));
  8808. }
  8809. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  8810. const std::string CRTPath(D.SysRoot + "/usr/lib/");
  8811. const char *CRTBegin;
  8812. CRTBegin =
  8813. Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
  8814. CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
  8815. }
  8816. Args.AddAllArgs(CmdArgs, options::OPT_L);
  8817. TC.AddFilePathLibArgs(Args, CmdArgs);
  8818. AddLinkerInputs(TC, Inputs, Args, CmdArgs);
  8819. if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
  8820. !Args.hasArg(options::OPT_nodefaultlibs)) {
  8821. bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
  8822. !Args.hasArg(options::OPT_static);
  8823. if (StaticCXX)
  8824. CmdArgs.push_back("-Bstatic");
  8825. TC.AddCXXStdlibLibArgs(Args, CmdArgs);
  8826. if (StaticCXX)
  8827. CmdArgs.push_back("-Bdynamic");
  8828. }
  8829. if (!Args.hasArg(options::OPT_nostdlib)) {
  8830. if (!Args.hasArg(options::OPT_nodefaultlibs)) {
  8831. // TODO handle /MT[d] /MD[d]
  8832. CmdArgs.push_back("-lmsvcrt");
  8833. AddRunTimeLibs(TC, D, CmdArgs, Args);
  8834. }
  8835. }
  8836. if (TC.getSanitizerArgs().needsAsanRt()) {
  8837. // TODO handle /MT[d] /MD[d]
  8838. if (Args.hasArg(options::OPT_shared)) {
  8839. CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
  8840. } else {
  8841. for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
  8842. CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
  8843. // Make sure the dynamic runtime thunk is not optimized out at link time
  8844. // to ensure proper SEH handling.
  8845. CmdArgs.push_back(Args.MakeArgString("--undefined"));
  8846. CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
  8847. ? "___asan_seh_interceptor"
  8848. : "__asan_seh_interceptor"));
  8849. }
  8850. }
  8851. Exec = Args.MakeArgString(TC.GetLinkerPath());
  8852. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  8853. }
  8854. void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
  8855. const InputInfo &Output,
  8856. const InputInfoList &Inputs,
  8857. const ArgList &Args,
  8858. const char *LinkingOutput) const {
  8859. ArgStringList CmdArgs;
  8860. assert(Inputs.size() == 1);
  8861. const InputInfo &II = Inputs[0];
  8862. assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
  8863. II.getType() == types::TY_PP_CXX);
  8864. if (JA.getKind() == Action::PreprocessJobClass) {
  8865. Args.ClaimAllArgs();
  8866. CmdArgs.push_back("-E");
  8867. } else {
  8868. assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
  8869. CmdArgs.push_back("-S");
  8870. CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
  8871. }
  8872. CmdArgs.push_back("-mcpu=myriad2");
  8873. CmdArgs.push_back("-DMYRIAD2");
  8874. // Append all -I, -iquote, -isystem paths, defines/undefines,
  8875. // 'f' flags, optimize flags, and warning options.
  8876. // These are spelled the same way in clang and moviCompile.
  8877. Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
  8878. options::OPT_std_EQ, options::OPT_D, options::OPT_U,
  8879. options::OPT_f_Group, options::OPT_f_clang_Group,
  8880. options::OPT_g_Group, options::OPT_M_Group,
  8881. options::OPT_O_Group, options::OPT_W_Group});
  8882. // If we're producing a dependency file, and assembly is the final action,
  8883. // then the name of the target in the dependency file should be the '.o'
  8884. // file, not the '.s' file produced by this step. For example, instead of
  8885. // /tmp/mumble.s: mumble.c .../someheader.h
  8886. // the filename on the lefthand side should be "mumble.o"
  8887. if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
  8888. C.getActions().size() == 1 &&
  8889. C.getActions()[0]->getKind() == Action::AssembleJobClass) {
  8890. Arg *A = Args.getLastArg(options::OPT_o);
  8891. if (A) {
  8892. CmdArgs.push_back("-MT");
  8893. CmdArgs.push_back(Args.MakeArgString(A->getValue()));
  8894. }
  8895. }
  8896. CmdArgs.push_back(II.getFilename());
  8897. CmdArgs.push_back("-o");
  8898. CmdArgs.push_back(Output.getFilename());
  8899. std::string Exec =
  8900. Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
  8901. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8902. CmdArgs, Inputs));
  8903. }
  8904. void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  8905. const InputInfo &Output,
  8906. const InputInfoList &Inputs,
  8907. const ArgList &Args,
  8908. const char *LinkingOutput) const {
  8909. ArgStringList CmdArgs;
  8910. assert(Inputs.size() == 1);
  8911. const InputInfo &II = Inputs[0];
  8912. assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
  8913. assert(Output.getType() == types::TY_Object);
  8914. CmdArgs.push_back("-no6thSlotCompression");
  8915. CmdArgs.push_back("-cv:myriad2"); // Chip Version
  8916. CmdArgs.push_back("-noSPrefixing");
  8917. CmdArgs.push_back("-a"); // Mystery option.
  8918. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  8919. for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
  8920. A->claim();
  8921. CmdArgs.push_back(
  8922. Args.MakeArgString(std::string("-i:") + A->getValue(0)));
  8923. }
  8924. CmdArgs.push_back("-elf"); // Output format.
  8925. CmdArgs.push_back(II.getFilename());
  8926. CmdArgs.push_back(
  8927. Args.MakeArgString(std::string("-o:") + Output.getFilename()));
  8928. std::string Exec =
  8929. Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
  8930. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8931. CmdArgs, Inputs));
  8932. }
  8933. void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  8934. const InputInfo &Output,
  8935. const InputInfoList &Inputs,
  8936. const ArgList &Args,
  8937. const char *LinkingOutput) const {
  8938. const auto &TC =
  8939. static_cast<const toolchains::MyriadToolChain &>(getToolChain());
  8940. const llvm::Triple &T = TC.getTriple();
  8941. ArgStringList CmdArgs;
  8942. bool UseStartfiles =
  8943. !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
  8944. bool UseDefaultLibs =
  8945. !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
  8946. if (T.getArch() == llvm::Triple::sparc)
  8947. CmdArgs.push_back("-EB");
  8948. else // SHAVE assumes little-endian, and sparcel is expressly so.
  8949. CmdArgs.push_back("-EL");
  8950. // The remaining logic is mostly like gnutools::Linker::ConstructJob,
  8951. // but we never pass through a --sysroot option and various other bits.
  8952. // For example, there are no sanitizers (yet) nor gold linker.
  8953. // Eat some arguments that may be present but have no effect.
  8954. Args.ClaimAllArgs(options::OPT_g_Group);
  8955. Args.ClaimAllArgs(options::OPT_w);
  8956. Args.ClaimAllArgs(options::OPT_static_libgcc);
  8957. if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
  8958. CmdArgs.push_back("-s");
  8959. CmdArgs.push_back("-o");
  8960. CmdArgs.push_back(Output.getFilename());
  8961. if (UseStartfiles) {
  8962. // If you want startfiles, it means you want the builtin crti and crtbegin,
  8963. // but not crt0. Myriad link commands provide their own crt0.o as needed.
  8964. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
  8965. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
  8966. }
  8967. Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
  8968. options::OPT_e, options::OPT_s, options::OPT_t,
  8969. options::OPT_Z_Flag, options::OPT_r});
  8970. TC.AddFilePathLibArgs(Args, CmdArgs);
  8971. AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
  8972. if (UseDefaultLibs) {
  8973. if (C.getDriver().CCCIsCXX())
  8974. CmdArgs.push_back("-lstdc++");
  8975. if (T.getOS() == llvm::Triple::RTEMS) {
  8976. CmdArgs.push_back("--start-group");
  8977. CmdArgs.push_back("-lc");
  8978. // You must provide your own "-L" option to enable finding these.
  8979. CmdArgs.push_back("-lrtemscpu");
  8980. CmdArgs.push_back("-lrtemsbsp");
  8981. CmdArgs.push_back("--end-group");
  8982. } else {
  8983. CmdArgs.push_back("-lc");
  8984. }
  8985. CmdArgs.push_back("-lgcc");
  8986. }
  8987. if (UseStartfiles) {
  8988. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
  8989. CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
  8990. }
  8991. std::string Exec =
  8992. Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
  8993. C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
  8994. CmdArgs, Inputs));
  8995. }
  8996. void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
  8997. const InputInfo &Output,
  8998. const InputInfoList &Inputs,
  8999. const ArgList &Args,
  9000. const char *LinkingOutput) const {
  9001. claimNoWarnArgs(Args);
  9002. ArgStringList CmdArgs;
  9003. Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
  9004. CmdArgs.push_back("-o");
  9005. CmdArgs.push_back(Output.getFilename());
  9006. assert(Inputs.size() == 1 && "Unexpected number of inputs.");
  9007. const InputInfo &Input = Inputs[0];
  9008. assert(Input.isFilename() && "Invalid input.");
  9009. CmdArgs.push_back(Input.getFilename());
  9010. const char *Exec =
  9011. Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
  9012. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9013. }
  9014. static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
  9015. const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
  9016. if (SanArgs.needsUbsanRt()) {
  9017. CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
  9018. }
  9019. if (SanArgs.needsAsanRt()) {
  9020. CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
  9021. }
  9022. }
  9023. static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
  9024. const JobAction &JA, const InputInfo &Output,
  9025. const InputInfoList &Inputs,
  9026. const ArgList &Args,
  9027. const char *LinkingOutput) {
  9028. const toolchains::FreeBSD &ToolChain =
  9029. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9030. const Driver &D = ToolChain.getDriver();
  9031. ArgStringList CmdArgs;
  9032. // Silence warning for "clang -g foo.o -o foo"
  9033. Args.ClaimAllArgs(options::OPT_g_Group);
  9034. // and "clang -emit-llvm foo.o -o foo"
  9035. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9036. // and for "clang -w foo.o -o foo". Other warning options are already
  9037. // handled somewhere else.
  9038. Args.ClaimAllArgs(options::OPT_w);
  9039. if (!D.SysRoot.empty())
  9040. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9041. if (Args.hasArg(options::OPT_pie))
  9042. CmdArgs.push_back("-pie");
  9043. if (Args.hasArg(options::OPT_rdynamic))
  9044. CmdArgs.push_back("-export-dynamic");
  9045. if (Args.hasArg(options::OPT_shared))
  9046. CmdArgs.push_back("--oformat=so");
  9047. if (Output.isFilename()) {
  9048. CmdArgs.push_back("-o");
  9049. CmdArgs.push_back(Output.getFilename());
  9050. } else {
  9051. assert(Output.isNothing() && "Invalid output.");
  9052. }
  9053. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9054. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9055. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9056. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9057. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9058. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9059. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9060. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9061. CmdArgs.push_back("--no-demangle");
  9062. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9063. if (Args.hasArg(options::OPT_pthread)) {
  9064. CmdArgs.push_back("-lpthread");
  9065. }
  9066. const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  9067. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9068. }
  9069. static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
  9070. const JobAction &JA, const InputInfo &Output,
  9071. const InputInfoList &Inputs,
  9072. const ArgList &Args,
  9073. const char *LinkingOutput) {
  9074. const toolchains::FreeBSD &ToolChain =
  9075. static_cast<const toolchains::FreeBSD &>(T.getToolChain());
  9076. const Driver &D = ToolChain.getDriver();
  9077. ArgStringList CmdArgs;
  9078. // Silence warning for "clang -g foo.o -o foo"
  9079. Args.ClaimAllArgs(options::OPT_g_Group);
  9080. // and "clang -emit-llvm foo.o -o foo"
  9081. Args.ClaimAllArgs(options::OPT_emit_llvm);
  9082. // and for "clang -w foo.o -o foo". Other warning options are already
  9083. // handled somewhere else.
  9084. Args.ClaimAllArgs(options::OPT_w);
  9085. if (!D.SysRoot.empty())
  9086. CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
  9087. if (Args.hasArg(options::OPT_pie))
  9088. CmdArgs.push_back("-pie");
  9089. if (Args.hasArg(options::OPT_static)) {
  9090. CmdArgs.push_back("-Bstatic");
  9091. } else {
  9092. if (Args.hasArg(options::OPT_rdynamic))
  9093. CmdArgs.push_back("-export-dynamic");
  9094. CmdArgs.push_back("--eh-frame-hdr");
  9095. if (Args.hasArg(options::OPT_shared)) {
  9096. CmdArgs.push_back("-Bshareable");
  9097. } else {
  9098. CmdArgs.push_back("-dynamic-linker");
  9099. CmdArgs.push_back("/libexec/ld-elf.so.1");
  9100. }
  9101. CmdArgs.push_back("--enable-new-dtags");
  9102. }
  9103. if (Output.isFilename()) {
  9104. CmdArgs.push_back("-o");
  9105. CmdArgs.push_back(Output.getFilename());
  9106. } else {
  9107. assert(Output.isNothing() && "Invalid output.");
  9108. }
  9109. AddPS4SanitizerArgs(ToolChain, CmdArgs);
  9110. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9111. const char *crt1 = nullptr;
  9112. if (!Args.hasArg(options::OPT_shared)) {
  9113. if (Args.hasArg(options::OPT_pg))
  9114. crt1 = "gcrt1.o";
  9115. else if (Args.hasArg(options::OPT_pie))
  9116. crt1 = "Scrt1.o";
  9117. else
  9118. crt1 = "crt1.o";
  9119. }
  9120. if (crt1)
  9121. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
  9122. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
  9123. const char *crtbegin = nullptr;
  9124. if (Args.hasArg(options::OPT_static))
  9125. crtbegin = "crtbeginT.o";
  9126. else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9127. crtbegin = "crtbeginS.o";
  9128. else
  9129. crtbegin = "crtbegin.o";
  9130. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
  9131. }
  9132. Args.AddAllArgs(CmdArgs, options::OPT_L);
  9133. ToolChain.AddFilePathLibArgs(Args, CmdArgs);
  9134. Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
  9135. Args.AddAllArgs(CmdArgs, options::OPT_e);
  9136. Args.AddAllArgs(CmdArgs, options::OPT_s);
  9137. Args.AddAllArgs(CmdArgs, options::OPT_t);
  9138. Args.AddAllArgs(CmdArgs, options::OPT_r);
  9139. if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
  9140. CmdArgs.push_back("--no-demangle");
  9141. AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
  9142. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
  9143. // For PS4, we always want to pass libm, libstdc++ and libkernel
  9144. // libraries for both C and C++ compilations.
  9145. CmdArgs.push_back("-lkernel");
  9146. if (D.CCCIsCXX()) {
  9147. ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
  9148. if (Args.hasArg(options::OPT_pg))
  9149. CmdArgs.push_back("-lm_p");
  9150. else
  9151. CmdArgs.push_back("-lm");
  9152. }
  9153. // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
  9154. // the default system libraries. Just mimic this for now.
  9155. if (Args.hasArg(options::OPT_pg))
  9156. CmdArgs.push_back("-lgcc_p");
  9157. else
  9158. CmdArgs.push_back("-lcompiler_rt");
  9159. if (Args.hasArg(options::OPT_static)) {
  9160. CmdArgs.push_back("-lstdc++");
  9161. } else if (Args.hasArg(options::OPT_pg)) {
  9162. CmdArgs.push_back("-lgcc_eh_p");
  9163. } else {
  9164. CmdArgs.push_back("--as-needed");
  9165. CmdArgs.push_back("-lstdc++");
  9166. CmdArgs.push_back("--no-as-needed");
  9167. }
  9168. if (Args.hasArg(options::OPT_pthread)) {
  9169. if (Args.hasArg(options::OPT_pg))
  9170. CmdArgs.push_back("-lpthread_p");
  9171. else
  9172. CmdArgs.push_back("-lpthread");
  9173. }
  9174. if (Args.hasArg(options::OPT_pg)) {
  9175. if (Args.hasArg(options::OPT_shared))
  9176. CmdArgs.push_back("-lc");
  9177. else {
  9178. if (Args.hasArg(options::OPT_static)) {
  9179. CmdArgs.push_back("--start-group");
  9180. CmdArgs.push_back("-lc_p");
  9181. CmdArgs.push_back("-lpthread_p");
  9182. CmdArgs.push_back("--end-group");
  9183. } else {
  9184. CmdArgs.push_back("-lc_p");
  9185. }
  9186. }
  9187. CmdArgs.push_back("-lgcc_p");
  9188. } else {
  9189. if (Args.hasArg(options::OPT_static)) {
  9190. CmdArgs.push_back("--start-group");
  9191. CmdArgs.push_back("-lc");
  9192. CmdArgs.push_back("-lpthread");
  9193. CmdArgs.push_back("--end-group");
  9194. } else {
  9195. CmdArgs.push_back("-lc");
  9196. }
  9197. CmdArgs.push_back("-lcompiler_rt");
  9198. }
  9199. if (Args.hasArg(options::OPT_static)) {
  9200. CmdArgs.push_back("-lstdc++");
  9201. } else if (Args.hasArg(options::OPT_pg)) {
  9202. CmdArgs.push_back("-lgcc_eh_p");
  9203. } else {
  9204. CmdArgs.push_back("--as-needed");
  9205. CmdArgs.push_back("-lstdc++");
  9206. CmdArgs.push_back("--no-as-needed");
  9207. }
  9208. }
  9209. if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
  9210. if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
  9211. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
  9212. else
  9213. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
  9214. CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
  9215. }
  9216. const char *Exec =
  9217. #ifdef LLVM_ON_WIN32
  9218. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
  9219. #else
  9220. Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
  9221. #endif
  9222. C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
  9223. }
  9224. void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
  9225. const InputInfo &Output,
  9226. const InputInfoList &Inputs,
  9227. const ArgList &Args,
  9228. const char *LinkingOutput) const {
  9229. const toolchains::FreeBSD &ToolChain =
  9230. static_cast<const toolchains::FreeBSD &>(getToolChain());
  9231. const Driver &D = ToolChain.getDriver();
  9232. bool PS4Linker;
  9233. StringRef LinkerOptName;
  9234. if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
  9235. LinkerOptName = A->getValue();
  9236. if (LinkerOptName != "ps4" && LinkerOptName != "gold")
  9237. D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
  9238. }
  9239. if (LinkerOptName == "gold")
  9240. PS4Linker = false;
  9241. else if (LinkerOptName == "ps4")
  9242. PS4Linker = true;
  9243. else
  9244. PS4Linker = !Args.hasArg(options::OPT_shared);
  9245. if (PS4Linker)
  9246. ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9247. else
  9248. ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
  9249. }
  9250. void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
  9251. const InputInfo &Output,
  9252. const InputInfoList &Inputs,
  9253. const ArgList &Args,
  9254. const char *LinkingOutput) const {
  9255. const auto &TC =
  9256. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  9257. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  9258. std::vector<std::string> gpu_archs =
  9259. Args.getAllArgValues(options::OPT_march_EQ);
  9260. assert(gpu_archs.size() == 1 && "Exactly one GPU Arch required for ptxas.");
  9261. const std::string& gpu_arch = gpu_archs[0];
  9262. ArgStringList CmdArgs;
  9263. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
  9264. // Map the -O we received to -O{0,1,2,3}.
  9265. //
  9266. // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's default,
  9267. // so it may correspond more closely to the spirit of clang -O2.
  9268. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  9269. // -O3 seems like the least-bad option when -Osomething is specified to
  9270. // clang but it isn't handled below.
  9271. StringRef OOpt = "3";
  9272. if (A->getOption().matches(options::OPT_O4) ||
  9273. A->getOption().matches(options::OPT_Ofast))
  9274. OOpt = "3";
  9275. else if (A->getOption().matches(options::OPT_O0))
  9276. OOpt = "0";
  9277. else if (A->getOption().matches(options::OPT_O)) {
  9278. // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
  9279. OOpt = llvm::StringSwitch<const char *>(A->getValue())
  9280. .Case("1", "1")
  9281. .Case("2", "2")
  9282. .Case("3", "3")
  9283. .Case("s", "2")
  9284. .Case("z", "2")
  9285. .Default("2");
  9286. }
  9287. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
  9288. } else {
  9289. // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
  9290. // to no optimizations, but ptxas's default is -O3.
  9291. CmdArgs.push_back("-O0");
  9292. }
  9293. // Don't bother passing -g to ptxas: It's enabled by default at -O0, and
  9294. // not supported at other optimization levels.
  9295. CmdArgs.push_back("--gpu-name");
  9296. CmdArgs.push_back(Args.MakeArgString(gpu_arch));
  9297. CmdArgs.push_back("--output-file");
  9298. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  9299. for (const auto& II : Inputs)
  9300. CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
  9301. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
  9302. CmdArgs.push_back(Args.MakeArgString(A));
  9303. const char *Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
  9304. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9305. }
  9306. // All inputs to this linker must be from CudaDeviceActions, as we need to look
  9307. // at the Inputs' Actions in order to figure out which GPU architecture they
  9308. // correspond to.
  9309. void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
  9310. const InputInfo &Output,
  9311. const InputInfoList &Inputs,
  9312. const ArgList &Args,
  9313. const char *LinkingOutput) const {
  9314. const auto &TC =
  9315. static_cast<const toolchains::CudaToolChain &>(getToolChain());
  9316. assert(TC.getTriple().isNVPTX() && "Wrong platform");
  9317. ArgStringList CmdArgs;
  9318. CmdArgs.push_back("--cuda");
  9319. CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
  9320. CmdArgs.push_back(Args.MakeArgString("--create"));
  9321. CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
  9322. for (const auto& II : Inputs) {
  9323. auto* A = cast<const CudaDeviceAction>(II.getAction());
  9324. // We need to pass an Arch of the form "sm_XX" for cubin files and
  9325. // "compute_XX" for ptx.
  9326. const char *Arch = (II.getType() == types::TY_PP_Asm)
  9327. ? A->getComputeArchName()
  9328. : A->getGpuArchName();
  9329. CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
  9330. Arch + ",file=" + II.getFilename()));
  9331. }
  9332. for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
  9333. CmdArgs.push_back(Args.MakeArgString(A));
  9334. const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
  9335. C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
  9336. }